A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
clean up scripts, ci names, and the file size threshold (#3178)
ktf70e8ae24819
diff --git a/.cursor/BUGBOT.md b/.cursor/BUGBOT.mdindex 900241bbbc..7ab99488d5 100644--- a/.cursor/BUGBOT.md+++ b/.cursor/BUGBOT.md@@ -24,7 +24,7 @@ either changes.## File size (advisory)-- Flag new or grown Rust files past ~500 lines (tests included) as advisory guidance: cite the growth and suggest splitting by responsibility. Size is ADVISORY per the operator's ruling - a soft cap that informs review and never blocks a merge; the repo's `codebase-health` PR check reports the same as warnings only.+- Flag new or grown Rust files past ~2,000 lines (tests included) as advisory guidance: cite the growth and suggest splitting by responsibility. Size is ADVISORY per the operator's ruling - a soft cap that informs review and never blocks a merge; the repo's `codebase-health` PR check reports the same as warnings only.- Generated files are exempt from the size rule (see Generated files).## Dependency directiondiff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdindex 411f965b86..413250177a 100644--- a/.github/pull_request_template.md+++ b/.github/pull_request_template.md@@ -7,7 +7,7 @@## Parity-diff evidence (merge gate for user-visible surfaces)<!-- Per the AGENTS.md merge gates: features are not done until diffed against the TS binary. -->-- [ ] Rendered output: frame-diff vs the TS binary for every touched surface (visual_parity.py / the specific harness)+- [ ] Rendered output: frame-diff vs the TS binary for every touched surface- [ ] Interactive behavior: same input, identical handling (keys/mouse/timing) vs TS- [ ] Wire parity: byte-compare TS daemon traffic for protocol changes- [ ] User-visible invariants: every user action produces the same visible reaction TS shows; nothing extra TS does not showdiff --git a/.github/workflows/codebase-health.yml b/.github/workflows/codebase-health.ymlindex 89697d782d..cbd3823db0 100644--- a/.github/workflows/codebase-health.yml+++ b/.github/workflows/codebase-health.yml@@ -1,4 +1,4 @@-# Non-blocking, PR-only guidance for files growing past 500 lines.+# Non-blocking, PR-only guidance for files growing past 2,000 lines.name: codebase-healthon:pull_request:@@ -11,7 +11,7 @@ jobs:- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2with:persist-credentials: false- - name: Report growing Rust files over 500 lines+ - name: Report growing Rust files over 2,000 linescontinue-on-error: trueenv:BASE_SHA: ${{ github.event.pull_request.base.sha }}@@ -55,7 +55,7 @@ jobs:# reads, immune to symlinks in the checkoutafter = len(subprocess.check_output(git + ['show', f'HEAD:{path}']).splitlines())- if after > 500 and after > before:+ if after > 2000 and after > before:findings.append((path, before, after))# Annotations are capped at 10 per job by GitHub; the log carries the# full list either way.@@ -66,5 +66,5 @@ jobs:print('remaining findings beyond the annotation cap:')for path, before, after in findings[10:]:print(f' {before} -> {after} lines: {path}')- print(f'{len(findings)} changed Rust file(s) grew beyond 500 lines (guidance only).')+ print(f'{len(findings)} changed Rust file(s) grew beyond 2,000 lines (guidance only).')PYdiff --git a/.github/workflows/release-prepare.yml b/.github/workflows/release-prepare.ymlindex da08e8a1c4..de2ea7f3d0 100644--- a/.github/workflows/release-prepare.yml+++ b/.github/workflows/release-prepare.yml@@ -67,7 +67,7 @@ concurrency:jobs:prepare:if: github.event_name == 'workflow_dispatch'- name: "bump + fold, then open the release PR (base main)"+ name: open the release PRruns-on: ubuntu-latesttimeout-minutes: 30permissions:diff --git a/AGENTS.md b/AGENTS.mdindex 54d92c5c22..d6d2b7fe82 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -19,7 +19,7 @@ Every contributor (human or agent) must read this before working on this repo.no god-modules. The dependency direction is pinned in the Crates table below; each crate'sREADME.md states its scope, non-goals, and public API surface.- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.-- Aim for files under 500 lines, tests included. The 500-600 range is a soft review+- Aim for files under 2,000 lines, tests included. The 2,000-2,100 range is a soft reviewsignal, not a merge limit: when adding to an already-large file, consider splitting byresponsibility rather than growing it further. Move related tests and docs with extracted code.- Name modules for what they own, not `utils` or `common`. Follow existing structure: in@@ -78,11 +78,11 @@ Every contributor (human or agent) must read this before working on this repo.`cargo test --workspace` must pass before every merge. Run `make check` — the local mirror ofthe same gates; CI runs on the org's billing (`.github/workflows/continuous.yml` on `main`pushes; `release.yml` on version tags). The PR-only codebase-health check reports growth- past 500 lines as review guidance; it never blocks a merge.+ past 2,000 lines as review guidance; it never blocks a merge.- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PRthat touches a user-visible surface must include a "parity-diff evidence" section in itsdescription showing the TS-binary comparison for what it changed: (1) rendered output —- frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness);+ frame-diff vs the TS binary;(2) interactive behavior — the same input handled identically (keys, mouse, timing);(3) wire parity — byte-compare the TS daemon's traffic for protocol changes; (4) user-visibleinvariants — every user action produces the same visible reaction as TS (`/compact` showsdiff --git a/crates/pa-cli/README.md b/crates/pa-cli/README.mdindex 165cdfd427..d050c35e3c 100644--- a/crates/pa-cli/README.md+++ b/crates/pa-cli/README.md@@ -57,11 +57,7 @@ the slim `assistantMessageEvent` (the daemon wire drops the nestedthe first-turn boundary, the compaction `compaction_start`/`compaction_end`pairs with their durable outcome rows, the `goal_update`/`session_action_update`frames of the goal loop, and the refinement rows with-`refine_complete`/`refine_failed`. Verifier: `scripts/print_json_parity.py`-(the TS binary differential, the goal-budget/goal-natural plus the-session-command scenarios — the harness supports split runs: `--only ts`-on the TS host, `--only rust` against the sandbox build, both against one-`--out`) plus the `print_runtime_e2e` rows.+`refine_complete`/`refine_failed`. Verifier: the `print_runtime_e2e` rows.## Daemon clientThe daemon-backed public commands (`list`, `stop`, `rename`, `send`, `schedule`) talk to thediff --git a/crates/pa-cli/tests/interactive_daemon_e2e.rs b/crates/pa-cli/tests/interactive_daemon_e2e.rsindex dbb0115af1..a98a46b0dc 100644--- a/crates/pa-cli/tests/interactive_daemon_e2e.rs+++ b/crates/pa-cli/tests/interactive_daemon_e2e.rs@@ -2069,8 +2069,7 @@ async fn tui_compact_on_a_short_session_warns_nothing_to_compact() {/// summary row renders (TS `CompactionSummaryMessageComponent`) at the head/// of the rebuilt transcript (TS `rebuildChatFromMessages`). The loader row/// is a soft evidence capture (its in-flight window is delayMs-paced and a-/// loaded box can batch the whole window past the paint loop; the strict-/// loader assertion is the f14 battery flow, `scripts/compact_parity.py`);+/// loaded box can batch the whole window past the paint loop);/// the settled outcome — the summary row, the rebuilt transcript, and the/// retained tail — carries the hard asserts.#[tokio::test]@@ -2089,7 +2088,7 @@ async fn tui_compact_shows_the_loader_then_the_summary_and_rebuilds() {.expect("write settings");let supervisor = spawn_supervisor(dir.path());- // The compact_parity.py session shape (TS-binary-verified): a large+ // The session shape (TS-binary-verified): a large// first turn gives the compactor history to summarize, the small// second turn crosses the 10-token keep-recent budget AT its user// message — a non-split cut that keeps the whole second turn — and@@ -2201,9 +2200,8 @@ async fn tui_compact_shows_the_loader_then_the_summary_and_rebuilds() {// compaction-finished events then apply in one batched iteration (the// loop drains the queued events before it paints), so no captured frame// ever shows the loader row. Any finite pacing window leaves that race,- // so the strict frame-level loader assertion lives in- // scripts/compact_parity.py (the f14 battery flow, run on an idle box- // or a sandbox). Here the observed loader row is evidence only; the hard+ // so frame-level loader assertions belong in a sandboxed run on an+ // idle box. Here the observed loader row is evidence only; the hard// asserts below pin the settled outcome — the parity-critical claims.let loader = "Compacting context (focus: focus on the goal)... (Ctrl+C to cancel)";let loader_frames = outcome@@ -2212,7 +2210,7 @@ async fn tui_compact_shows_the_loader_then_the_summary_and_rebuilds() {.filter(|frame| frame.contains(loader)).count();println!(- "compaction loader evidence: {loader_frames} frames captured the loader row (soft check; the strict assertion is scripts/compact_parity.py)"+ "compaction loader evidence: {loader_frames} frames captured the loader row (soft check)");// The summary row: the TS header plus the collapsed summary.assert!(diff --git a/crates/pa-daemon/README.md b/crates/pa-daemon/README.mdindex ed58ffe8ce..8f3386182b 100644--- a/crates/pa-daemon/README.md+++ b/crates/pa-daemon/README.md@@ -207,8 +207,7 @@ worker coalesces them for broadcast in a single-slot coalescer with aparked update first and go out directly, so wire order and event-sequenceorder match uncoalesced streaming. The supervisor stays payload-free:deltas ride the worker -> client session-event stream (direct-attach or-supervisor-routed). Verifier: `scripts/battery/streaming_render.py`-(pane-growth acceptance + TS settled-frame differential).+supervisor-routed).Autonomouscontinuation driving in the worker's engine: per-message usage accountingdiff --git a/crates/pa-tui/examples/mcp_view_parity_frames.rs b/crates/pa-tui/examples/mcp_view_parity_frames.rsindex e997b1e6ce..ab3c54e1a8 100644--- a/crates/pa-tui/examples/mcp_view_parity_frames.rs+++ b/crates/pa-tui/examples/mcp_view_parity_frames.rs@@ -4,8 +4,7 @@//! two can be diffed line-for-line. Takes the fixture JSON path, the//! viewport rows, the render width, and a key sequence (space-separated//! key ids, "-" for none); prints one trimmed frame line per stdout-//! line. Test/evidence tooling for `scripts/mcp_view_parity.py` — never-//! linked into the product.+//! line. Test/evidence tooling — never linked into the product.// Pedantic-gate exceptions (every other pedantic warning in this crate is// fixed in place; each exception carries its one-line justification):// - the casts: terminal-layout arithmetic narrows structurally boundeddiff --git a/scripts/abort_visual_parity.py b/scripts/abort_visual_parity.pydeleted file mode 100755index 2911106900..0000000000--- a/scripts/abort_visual_parity.py+++ /dev/null@@ -1,396 +0,0 @@-#!/usr/bin/env python3-"""Abort-visual parity (TS binary vs Rust build): the interrupted turn's-transcript render, in tmux, compared frame-for-frame.--The TS interrupt (`interruptOrClearInput` -> `abortAndSendQueued`, schema-29) renders no transient hint: the aborted run's own assistant component-carries the interrupt - the red "Operation aborted" row (TS-`AssistantMessageComponent.rebuild`'s aborted arm). This probe drives both-binaries through the states that define the abort UX:--- b_aborted_row: a thinking-only turn (hidden in the collapsed detail- mode) streams slowly; Escape aborts it. The transcript shows the user- row and the red "Operation aborted" row - no Rust-only "aborting the- current turn" hint, no TS transient note - so the whole frame compares- byte-exact after visual_parity's normalization.-- c_parked_strip / c_steering_delivered: a second slow turn parks one- steering prompt at the boundary (the queue strip shows it); Escape- aborts the run AND delivers the parked steering (TS- `abortAndSendQueued`; the Rust `abort_and_send_queued` command). The- strip vanishes and the steering turn's reply renders - with no- resume-key press, the delivery IS the interrupt's own work.--Exit code is non-zero when any state's frame differs. Reuses the-visual_parity faux-provider harness (tmux rules: default socket,-vplane-* session names, sessions killed individually).-"""--import argparse-import difflib-import glob-import json-import os-import re-import shutil-import sys-import tempfile-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-import visual_parity as vp--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)---def default_ts_binary():- """The ts side's launch command (the rules queue_edit_parity.py- established): the box PATH `prime-agent` may itself be the Rust- dogfood install, and the deployed 0.9.5 release predates schema 29- (abortAndSendQueued, TS PR #2426, never reached it), so the harness- compares against the TS-main bundle from the parity checkout.- PA_TS_BINARY overrides (an absolute path or a full command string)."""- override = os.environ.get("PA_TS_BINARY")- if override:- return override- ts_main_cli = os.path.join(- "/home/ubuntu/prime-agent", "packages", "coding-agent", "dist", "bundle", "cli.js"- )- if os.path.exists(ts_main_cli):- return f"node {ts_main_cli}"- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- candidates = sorted(- glob.glob(os.path.join(releases, "0.9.5-linux-x64-*", "prime-agent"))- )- if not candidates:- raise SystemExit(- "neither the TS-main checkout nor a deployed TS release found; set PA_TS_BINARY"- )- return candidates[-1]--# Turns 1/2 are thinking-only and stream slowly (4 tokens/s over a long-# block): the collapsed detail mode hides the thinking, so the pane shows-# only the working loader while the turn streams - an abort there renders-# the aborted row with no partial text on screen, making the post-abort-# frame deterministic cross-side. The steering turn answers quickly.-ABORT_FAUX_SCRIPT = {- "engine": "faux",- "modelId": vp.TS_SCRIPT_MODEL,- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 4,- "responses": [- {- "content": [- {- "type": "thinking",- "thinking": (- "The user asked for a long careful analysis of the streaming path and the abort surface. "- "I will think through each layer slowly so the turn stays busy long enough for the "- "interrupt to land mid-stream: the provider stream, the message components, the queue "- "lanes, and the aborted row that the assistant message renders when the run cancels. "- "This thinking block is long on purpose so the faux provider keeps streaming it for "- "a good while before any visible text would appear."- ),- },- {"type": "text", "text": "the final answer never streams"},- ]- },- {- "content": [- {- "type": "thinking",- "thinking": (- "A second long thinking pass for the parked-steering abort: the interrupt must land "- "mid-stream here too, so the abort both cancels this run and delivers the steering "- "message waiting at the turn boundary, exactly like the TS abortAndSendQueued batch. "- "The steering turn then answers with its own quick reply so the settled frame is "- "deterministic cross-side."- ),- },- {"type": "text", "text": "the second final answer never streams"},- ]- },- {"content": [{"type": "text", "text": "steering delivered after the abort"}]},- ],-}--ABORT_ROW = "Operation aborted"-HELD_PROMPT = "hold this turn while i interrupt"-HELD_PROMPT_2 = "hold a second turn while i interrupt again"-STEERING_PROMPT = "steering message parked for the abort"-STEERING_DELIVERED = "steering delivered after the abort"--ANSI_PATTERN = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")---def strip_ansi(text):- return ANSI_PATTERN.sub("", text)---def prepare_abort_sandbox(base):- """The visual_parity fixture with the abort-specific faux script."""- shared_cwd, script_path, sandboxes = vp.prepare_sandbox(base)- script_path = os.path.join(base, "abort-faux-script.json")- with open(script_path, "w") as f:- json.dump(ABORT_FAUX_SCRIPT, f, indent=2)- return shared_cwd, script_path, sandboxes---def wait_plain(session, needle, timeout=30, gone=False):- """Poll the pane's ANSI-stripped text until `needle` appears (or is gone)."""- deadline = time.time() + timeout- while time.time() < deadline:- plain = strip_ansi(vp.capture(session, escape=False))- if (needle not in plain) == gone:- return- time.sleep(0.3)- raise RuntimeError(- f"timed out waiting for {needle!r} to {'vanish' if gone else 'appear'}"- )---def capture_settled(session, timeout=20):- """Capture once the pane stops changing: the TS live transcript can- transiently double a submitted user row (the local submit echo beside- the daemon's message_start row) until the post-turn rebuild flushes it- to the store's single row - a pane captured inside that window carries- a frame the settled transcript never shows."""- previous = None- deadline = time.time() + timeout- while time.time() < deadline:- frame = vp.capture(session)- if previous is not None and frame == previous:- return frame- previous = frame- time.sleep(0.5)- return previous or vp.capture(session)---def run_abort_session(binary, sandbox, shared_cwd, script_path, size, out_dir, prefix):- """Drive one binary through the abort states, capturing each frame."""- width, height = (str(size[0]), str(size[1]))- session = f"vplane-{prefix}-abort-{binary}-{size[0]}x{size[1]}"- vp.tmux("kill-session", "-t", session, check=False)- vp.tmux("new-session", "-d", "-s", session, "-x", width, "-y", height, "-c", shared_cwd)- env = (- f"HOME={sandbox['home']} "- f"TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"PRIME_AGENT_FAUX_SCRIPT={script_path} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- if binary == "ts":- command = (- f"{default_ts_binary()} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {vp.TS_SCRIPT_MODEL}"- )- else:- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)), "..", "target", "debug", "prime-agent"- ),- )- package_dir = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- command = (- f"PI_PACKAGE_DIR={package_dir} "- f"{rust} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {vp.TS_SCRIPT_MODEL}"- )- vp.tmux("send-keys", "-t", session, f"{env} {command}", "Enter")-- frames = {}- # (a) fresh start: the detail hint row is the ready signal; the fresh- # kernel boot plus the daemon's first-attach reconnect can take a- # while on a cold HOME.- wait_plain(session, "mode (Ctrl+O", timeout=150)- # Normalize the conversation detail: TS boots with thinking visible- # ("Details mode"), the Rust port boots collapsed (a pre-existing- # fresh-boot default gap this harness reports, not fixes) - toggle the- # collapsed side into Details so both products render the same- # thinking rows in the abort states below.- if "Collapsed mode" in strip_ansi(vp.capture(session, escape=False)):- vp.tmux("send-keys", "-t", session, "C-o")- wait_plain(session, "Details mode", timeout=10)- # (b) the aborted row: submit the thinking-only turn, wait until the- # working loader is up mid-stream (the thinking phase), then abort.- vp.tmux("send-keys", "-t", session, HELD_PROMPT)- vp.tmux("send-keys", "-t", session, "Enter")- wait_plain(session, "Thinking", timeout=90)- time.sleep(1.0)- vp.tmux("send-keys", "-t", session, "Escape")- # The aborted run settles on the red row - and no transient hint.- wait_plain(session, ABORT_ROW, timeout=30)- time.sleep(1.0)- # Flip through the shared detail cycle into the thinking-hidden state- # (details -> expanded -> collapsed, the same presses on both sides):- # the aborted turn's thinking row carries however much of the block- # streamed before the interrupt landed - a timing race between the- # products' stream pacing that no settled frame can compare, while the- # state's claim (the abort row, the hint row) is mode-independent.- vp.tmux("send-keys", "-t", session, "C-o")- vp.tmux("send-keys", "-t", session, "C-o")- wait_plain(session, "Collapsed mode", timeout=10)- frames["b_aborted_row"] = capture_settled(session)- plain = strip_ansi(frames["b_aborted_row"])- assert "aborting the current turn" not in plain, "the Rust-only abort hint rendered"- # (c) the abort-and-send: a second thinking-only turn parks one steering- # prompt at the boundary, and the interrupt aborts the run AND delivers- # it. The queue strip shows the parked message before the abort.- vp.tmux("send-keys", "-t", session, HELD_PROMPT_2)- vp.tmux("send-keys", "-t", session, "Enter")- wait_plain(session, "Thinking", timeout=90)- vp.tmux("send-keys", "-t", session, STEERING_PROMPT)- vp.tmux("send-keys", "-t", session, "Enter")- wait_plain(session, "Steering:", timeout=30)- # Let the streaming loader settle past its first frames: the label- # flips from "Waiting" to "Thinking" on the first thinking delta and- # the token counter renders with it, so a capture inside that window- # races the label on either product.- wait_plain(session, "Thinking", timeout=30)- time.sleep(1.0)- frames["c_parked_strip"] = vp.capture(session)- vp.tmux("send-keys", "-t", session, "Escape")- # The abort delivered the parked steering: the strip row vanishes and- # the steering turn's reply renders. No resume-key press happens: the- # delivery IS the interrupt's own work (abortAndSendQueued).- wait_plain(session, "Steering:", gone=True, timeout=60)- wait_plain(session, STEERING_DELIVERED, timeout=90)- # Both products already sit in the thinking-hidden state (the b- # capture's detail flip persists), so the settled frame is directly- # comparable: the aborted turn's rows, the delivered steering turn,- # and the detail hint.- frames["c_steering_delivered"] = capture_settled(session)- vp.tmux("kill-session", "-t", session, check=False)- return frames---def compare_frame(state, ts_frame, rust_frame, root):- """Byte-diff one state's frames (visual_parity normalization)."""- ts = vp.normalize(ts_frame, root)- rust = vp.normalize(rust_frame, root)- if ts == rust:- print(f"PASS {state}: frames match")- return None- print(f"FAIL {state}")- sys.stdout.writelines(- difflib.unified_diff(- ts.splitlines(keepends=True), rust.splitlines(keepends=True),- fromfile=f"ts-{state}", tofile=f"rust-{state}",- )- )- return state---def parked_strip_band(frame):- """The parked-strip state's claim: the streaming loader label and the- queue strip rows (visual_parity normalization on the band). The full- frame is NOT compared for this state - it carries the pre-existing- queued-strip mount gap (the Rust strip docks above the editor; TS- renders it directly under the working loader), which this lane- reports but does not own."""- plain = strip_ansi(frame)- band = "\n".join(- line- for line in plain.splitlines()- if "Thinking" in line or "Steering:" in line or "Alt+" in line- )- return band---def compare_parked_strip_band(ts_frame, rust_frame, root):- """Compare the parked-strip band cross-side (normalized)."""- ts = vp.normalize(parked_strip_band(ts_frame), root)- rust = vp.normalize(parked_strip_band(rust_frame), root)- if ts == rust:- print("PASS c_parked_strip: strip + streaming-label band matches")- return None- print("FAIL c_parked_strip band")- print(f"ts: {ts!r}")- print(f"rust: {rust!r}")- return "c_parked_strip"---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--keep", action="store_true")- parser.add_argument("--out", default=None)- parser.add_argument("--only", default=None, choices=("ts", "rust"))- parser.add_argument("--session-prefix", default="vp")- args = parser.parse_args()-- # Fail fast before any launch: a non-TS `prime-agent` on PATH plays a- # Rust build as the "ts" side and reports false divergences.- if args.only in (None, "ts"):- # The TS-main bundle prints its version line to stderr: redirect- # it into the guard's stdout probe (the queue_edit_parity rule).- ts_identity.assert_ts_side_is_the_ts_product(f"{default_ts_binary()} 2>&1")-- base = tempfile.mkdtemp(prefix="abort-parity-sandbox-")- out_dir = args.out or tempfile.mkdtemp(prefix="abort-parity-captures-")- os.makedirs(out_dir, exist_ok=True)- shared_cwd, script_path, sandboxes = prepare_abort_sandbox(base)- try:- if args.only:- frames = run_abort_session(- args.only, sandboxes[args.only], shared_cwd, script_path,- (120, 36), out_dir, args.session_prefix,- )- for state, frame in frames.items():- with open(os.path.join(out_dir, f"{args.only}-{state}.ansi"), "w") as f:- f.write(frame)- print(f"captures for {args.only} in {out_dir}")- return 0- frames = {}- for binary in ("ts", "rust"):- frames[binary] = run_abort_session(- binary, sandboxes[binary], shared_cwd, script_path,- (120, 36), out_dir, args.session_prefix,- )- for state, frame in frames[binary].items():- with open(os.path.join(out_dir, f"{binary}-{state}.ansi"), "w") as f:- f.write(frame)- # Scenario guards: the compared frames must actually show the- # abort surface (an early capture would diff equal empty panes).- for binary in ("ts", "rust"):- assert ABORT_ROW in strip_ansi(frames[binary]["b_aborted_row"]), (- f"{binary} never rendered the aborted row"- )- assert STEERING_DELIVERED in strip_ansi(frames[binary]["c_steering_delivered"]), (- f"{binary} never rendered the delivered steering reply"- )- assert "Thinking" in strip_ansi(frames[binary]["c_parked_strip"]), (- f"{binary} never rendered the streaming label mid-thinking"- )- failures = []- for state in ("b_aborted_row", "c_steering_delivered"):- failures.append(- compare_frame(state, frames["ts"][state], frames["rust"][state], shared_cwd)- )- # The parked-strip state compares band-wise (its full-frame diff is- # the pre-existing strip-mount gap, documented above).- failures.append(- compare_parked_strip_band(- frames["ts"]["c_parked_strip"], frames["rust"]["c_parked_strip"], shared_cwd- )- )- failed = [f for f in failures if f]- if failed:- print(f"{len(failed)} state(s) differ; captures in {out_dir}")- return 1- print(f"all abort states match; captures in {out_dir}")- return 0- finally:- # Rmtree alone leaks the scenario daemons (a killed TUI pane does- # not take its detached daemon/supervisor pair down; #223): sweep- # every daemon this run spawned before deleting the sandbox.- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if not args.keep:- shutil.rmtree(base, ignore_errors=True)---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/acp_compaction_parity.py b/scripts/acp_compaction_parity.pydeleted file mode 100644index 96fd6ee9a8..0000000000--- a/scripts/acp_compaction_parity.py+++ /dev/null@@ -1,534 +0,0 @@-#!/usr/bin/env python3-"""ACP-mode auto-compaction parity verifier: frame-diff the Rust in-process-ACP transport against the installed TS prime-agent binary for the automatic-compaction arms on the ACP turn path.--TS ruling under test (agent-session.ts): the arms live in the AgentSession-turn loop itself (`_runPreTurnCompaction` / `_checkCompaction` /-`_runAutoCompaction`), so the TS ACP mode hosts them through its-AgentConnection and its event adapter maps every `compaction_end` to the-namespaced `compaction` meta (`acp-events.ts`). The Rust in-process ACP-transport gained the same arms (`crates/pa-daemon/src/acp/compaction_arms.rs`);-this harness proves the observable wire parity.--Scenario (one shared faux provider script, per-binary isolated-HOME/agent-dir sandboxes; the TS side reads the script through the shared-faux extension, the Rust side through PRIME_AGENT_FAUX_SCRIPT — which also-forces the Rust in-process transport, bypassing the daemon-attached one):-- - threshold: turn one (8k chars, ~2k tokens over the 500-token headroom- on the 128k window): the threshold arm fires at the settled boundary- and the single-turn compaction skips — the skip is observable as the- empty `compaction: {}` meta,- - threshold turn two: the pre-turn arm skips again (still nothing- before turn one to summarize), then the settled boundary compaction- runs, summarizing turn one and publishing `tokensBefore` + the- scripted summary.- - goal: `/goal --budget 5 ...` (compaction disabled) drives the direct- ACP goal continuation surface the TS session hosts inside the one- `session/prompt` run: the goal-start continuation segment streams,- the crossing turn's usage flips the goal to `budget_limited`, and the- budget-limit wrap-up steer runs as the prompt's second model segment- before the end_turn response. Byte-compared against the TS binary- (the #244 direct-ACP ruling).--Every frame after `session/new` (notifications and responses alike) is-captured per side, normalized for volatile content (session ids, request-ids echo is deterministic by construction, timestamps, the tokensBefore-count), and diffed; the exit code is non-zero when any frame differs.-"""--import difflib-import json-import os-import re-import shutil-import subprocess-import sys-import tempfile-import threading-import time--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--FAUX_SCRIPT = {- "engine": "faux",- "modelId": "faux-1",- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "responses": [- {"text": "turn one reply"},- {"text": "turn two reply"},- {"text": "the auto summary"},- ],-}--# The threshold-crossing shape on the 128k window: turn one crosses on-# both products — TS at window - reserve = 4596, Rust at the combined-# input+output ceiling 128000 - 4096 output budget - 123404 reserve = 500-# — and a tiny keep-recent budget keeps the seeded turns summarizable.-SETTINGS = {- "compaction": {- "enabled": True,- "reserveTokens": 123404,- "keepRecentTokens": 10,- }-}--TS_FAUX_EXTENSION = open(- os.path.join(os.path.dirname(os.path.abspath(__file__)), "ts_faux_extension.js"),- encoding="utf-8",-).read()--TURN_ONE = "turn one " + "x" * 8000-TURN_TWO = "turn two"--# The overflow scenario: a seed turn, then a provider context-overflow-# error on the probe turn (the compact-and-retry recovers it).-OVERFLOW_ERROR = {- "text": "",- "stopReason": "error",- "errorMessage": "prompt is too long: 213462 tokens > 200000 maximum",-}--# The ACP meta namespace (the goal frames' home).-NAMESPACE = "ai.primeintellect.prime-agent"--TIMEOUT = 180---def find_runtime_package_dir():- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- if not os.path.isdir(releases):- raise SystemExit("cannot find the prime-agent-runtime sidecar; set PI_PACKAGE_DIR")- candidates = [- entry- for entry in sorted(os.listdir(releases))- if os.path.isdir(os.path.join(releases, entry, "prime-agent-runtime"))- ]- if not candidates:- raise SystemExit("no release with prime-agent-runtime/ under " + releases)- return os.path.join(releases, candidates[-1])---class AcpProcess:- """One ACP-mode child over stdio: requests out, frames in.-- The TS side reads the script through the faux extension from its- path; the Rust print/ACP path expects the JSON content inline.- """-- def __init__(self, command, env, faux_script_value):- self.env = dict(os.environ)- self.env.update(env)- self.env["PRIME_AGENT_FAUX_SCRIPT"] = faux_script_value- self.process = subprocess.Popen(- command,- stdin=subprocess.PIPE,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- env=self.env,- text=True,- bufsize=1,- )- self.frames = []- self.lock = threading.Lock()- threading.Thread(target=self._read, daemon=True).start()-- def _read(self):- for line in self.process.stdout:- line = line.strip()- if not line:- continue- try:- frame = json.loads(line)- except json.JSONDecodeError:- continue- with self.lock:- self.frames.append(frame)- self.process.stdout.close()-- def send(self, frame):- self.process.stdin.write(json.dumps(frame) + "\n")- self.process.stdin.flush()-- def request(self, request_id, method, params):- self.send({"jsonrpc": "2.0", "id": request_id, "method": method, "params": params})-- def wait_response(self, request_id, since):- """Read frames until the request answers; returns (response, frames)."""- deadline = time.time() + TIMEOUT- while time.time() < deadline:- with self.lock:- frames = self.frames[since:]- for frame in frames:- if frame.get("id") == request_id and (- "result" in frame or "error" in frame- ):- return frame, frames- time.sleep(0.05)- raise TimeoutError(f"request {request_id} never answered; frames: {frames!r}")-- def close(self):- try:- self.process.stdin.close()- except OSError:- pass- try:- self.process.wait(timeout=10)- except subprocess.TimeoutExpired:- self.process.kill()- stderr = self.process.stderr.read() if self.process.stderr else ""- if stderr.strip():- print(f" child stderr: {stderr.strip()[:2000]}", file=sys.stderr)---def normalize(frames):- """Erase volatile content from the captured frames: session ids, the- tokensBefore count, and the faux stream's chunk granularity (the TS- faux provider paces a response into several deltas where the Rust one- emits fewer — the joined text per message is the observable contract,- so consecutive chunks of one message coalesce into one frame, and- eventSequence renumbers over the coalesced list)."""- entries = [] # ("chunk", update-dict) or ("frame", response)- for frame in frames:- update = frame.get("params", {}).get("update")- if isinstance(update, dict) and update.get("sessionUpdate") in (- "agent_message_chunk",- "agent_thought_chunk",- ):- kind = update.get("sessionUpdate")- message_id = update.get("messageId")- if (- entries- and entries[-1][0] == "chunk"- and entries[-1][1].get("sessionUpdate") == kind- and entries[-1][1].get("messageId") == message_id- ):- entry = entries[-1][1]- entry["content"]["text"] += update.get("content", {}).get("text", "")- continue- entry = {- "sessionUpdate": kind,- "messageId": message_id,- "content": {"text": update.get("content", {}).get("text", "")},- }- entries.append(("chunk", entry))- continue- entries.append(("frame", frame))-- normalized = []- sequence = 0- for kind, payload in entries:- sequence += 1- if kind == "chunk":- normalized.append(- {- "jsonrpc": "2.0",- "method": "session/update",- "params": {- "sessionId": "<sid>",- "update": {- **payload,- "_meta": {- "ai.primeintellect.prime-agent": {- "eventSequence": sequence,- "phase": "event",- }- },- },- },- }- )- continue- text = json.dumps(payload, sort_keys=True)- text = re.sub(r'"sessionId": "[0-9a-f-]{36}"', '"sessionId": "<sid>"', text)- text = re.sub(r'"tokensBefore": \d+', '"tokensBefore": "<n>"', text)- # Goal usage is a per-side token estimate (the #182 normalization- # class): the goal metas and the goal-context texts carry the- # same scrub as the f7 goal-continue battery.- text = re.sub(r'"tokensUsed": \d+', '"tokensUsed": "<n>"', text)- text = re.sub(r"- tokens used: -?\d+", "- tokens used: <n>", text)- text = re.sub(r"- remaining tokens: -?\d+", "- remaining tokens: <n>", text)- text = re.sub(r"- time used seconds: \d+", "- time used seconds: <n>", text)- frame = json.loads(text)- params = frame.get("params")- if isinstance(params, dict):- meta = (- params.get("update", {}).get("_meta", {}).get(- "ai.primeintellect.prime-agent", {}- )- )- if "eventSequence" in meta:- meta["eventSequence"] = sequence- normalized.append(frame)- return normalized---def scenario(name):- """One scenario's script, settings, and prompts."""- if name == "threshold":- return {- "script": FAUX_SCRIPT,- "settings": SETTINGS,- "prompts": [TURN_ONE, TURN_TWO],- }- if name == "goal":- # The budget-bounded goal loop: the start segment streams, the- # crossing flips the goal to budget_limited, the wrap-up steer- # runs as the second segment, and the prompt settles end_turn.- # Compaction stays out of the picture (the goal frames are the- # diff target).- return {- "script": {- "engine": "faux",- "modelId": "faux-1",- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "responses": [- {"text": "goal turn reply"},- {"text": "wrap-up reply"},- ],- },- "settings": {"compaction": {"enabled": False}},- "prompts": ["/goal --budget 5 finish the work"],- }- return {- "script": {- "engine": "faux",- "modelId": "faux-1",- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "responses": [- {"text": "seed reply"},- OVERFLOW_ERROR,- {"text": "the summary"},- {"text": "recovered reply"},- ],- },- "settings": {- "compaction": {"enabled": True, "reserveTokens": 1, "keepRecentTokens": 10}- },- "prompts": [- "seed turn " + "x" * 48000,- "overflow probe " + "x" * 2000,- ],- }---def drive(binary, base, script_path, settings, prompts, out_dir):- home = os.path.join(base, binary, "home")- agent = os.path.join(base, binary, "agent")- tmp = os.path.join(base, binary, "tmp")- for path in (home, tmp, agent):- os.makedirs(path, exist_ok=True)- with open(os.path.join(agent, "settings.json"), "w") as f:- json.dump(settings, f, indent=2)- if binary == "ts":- os.makedirs(os.path.join(agent, "extensions"), exist_ok=True)- with open(os.path.join(agent, "extensions", "acp-faux.js"), "w") as f:- f.write(TS_FAUX_EXTENSION)- command = ["prime-agent", "--mode", "acp", "--no-session", "--model", "faux-1"]- env = {"HOME": home, "TMPDIR": tmp, "PRIME_AGENT_CODING_AGENT_DIR": agent}- else:- rust = ts_identity.default_rust_binary()- package_dir = os.environ.get("PI_PACKAGE_DIR") or find_runtime_package_dir()- command = [- rust,- "--mode",- "acp",- "--no-session",- "--model",- "faux-1",- ]- env = {- "HOME": home,- "TMPDIR": tmp,- "PRIME_AGENT_CODING_AGENT_DIR": agent,- "PI_PACKAGE_DIR": package_dir,- }- if binary == "ts":- faux_value = script_path- else:- with open(script_path) as f:- faux_value = f.read()- acp = AcpProcess(command, env, faux_value)- try:- acp.request(1, "initialize", {"protocolVersion": 1, "clientCapabilities": {}})- response, _ = acp.wait_response(1, 0)- assert "result" in response, f"initialize failed: {response}"-- acp.request(2, "session/new", {"cwd": os.getcwd(), "mcpServers": []})- response, frames = acp.wait_response(2, len(acp.frames))- assert "result" in response, f"session/new failed: {response}"-- # The scenario capture starts after admission: every frame of both- # prompt turns, notifications and responses alike.- session_id = response["result"]["sessionId"]- captured = []- request_id = 2- for prompt in prompts:- request_id += 1- since = len(acp.frames)- acp.request(- request_id,- "session/prompt",- {"sessionId": session_id, "prompt": [{"type": "text", "text": prompt}]},- )- reply, frames = acp.wait_response(request_id, since)- captured.extend(frames)- finally:- acp.close()-- normalized = normalize(captured)- os.makedirs(out_dir, exist_ok=True)- with open(os.path.join(out_dir, "frames.json"), "w") as f:- json.dump(normalized, f, indent=2)- return normalized---def main():- ts_identity.assert_ts_side_is_the_ts_product()- failures = 0- for name in ("threshold", "overflow", "goal"):- if run_scenario(name):- print(f"ACP auto-compaction parity ({name}): PASS")- else:- failures += 1- return 1 if failures else 0---def run_scenario(name):- base = tempfile.mkdtemp(prefix=f"acp-compaction-parity-{name}-")- try:- return _run_scenario(name, base)- finally:- shutil.rmtree(base, ignore_errors=True)---def _run_scenario(name, base):- config = scenario(name)- script_path = os.path.join(base, "faux-script.json")- with open(script_path, "w") as f:- json.dump(config["script"], f, indent=2)- out_dir = os.path.join(base, "out")- ts_frames = drive(- "ts", base, script_path, config["settings"], config["prompts"],- os.path.join(out_dir, "ts"),- )- rust_frames = drive(- "rust", base, script_path, config["settings"], config["prompts"],- os.path.join(out_dir, "rust"),- )-- def render(frames):- return [json.dumps(frame, sort_keys=True, indent=1) for frame in frames]-- def compaction_metas(frames):- metas = []- for frame in frames:- update = frame.get("params", {}).get("update", {})- meta = update.get("_meta", {}).get("ai.primeintellect.prime-agent", {})- if "compaction" in meta:- metas.append(meta["compaction"])- return metas-- # The scenario must exercise the arms on both sides; the expected- # metas differ per scenario.- expectations = {- # The goal scenario asserts on goal frames below, not compaction- # metas (its compaction is disabled).- "goal": [],- "threshold": [- ("a skipped-compaction frame (the single-turn skip)", lambda m: m == {}),- (- "the ran-compaction frame (the scripted summary)",- lambda m: "the auto summary" in (m.get("summary") or ""),- ),- ],- "overflow": [- (- "the ran-compaction frame (the compact-and-retry summary)",- lambda m: "the summary" in (m.get("summary") or ""),- ),- (- "the recovered turn settled with end_turn",- None, # response-level check below- ),- ],- }- for side, frames in (("ts", ts_frames), ("rust", rust_frames)):- metas = compaction_metas(frames)- for description, predicate in expectations[name]:- if predicate is None:- continue- assert any(predicate(meta) for meta in metas), (- f"the {side} side never published {description} "- f"(metas: {metas!r})"- )-- def responses(frames):- return [- frame for frame in frames- if "result" in frame or "error" in frame- ]-- # The goal scenario must drive the continuation surface on both- # sides: the goal flips to budget_limited, the wrap-up steer streams- # its scripted answer, and the prompt settles end_turn.- if name == "goal":- for side, frames in (("ts", ts_frames), ("rust", rust_frames)):- goals = [- frame["params"]["update"]["_meta"][NAMESPACE]["goal"]- for frame in frames- if frame.get("params", {})- .get("update", {})- .get("_meta", {})- .get(NAMESPACE, {})- .get("goal")- ]- assert any(goal.get("status") == "budget_limited" for goal in goals), (- f"the {side} side never published the budget_limited goal: {goals!r}"- )- replies = responses(frames)- assert len(replies) == 1, f"{side}: expected one prompt reply, got {replies!r}"- assert replies[0]["result"]["stopReason"] == "end_turn", (- f"the {side} side's goal prompt did not settle end_turn: {replies[0]!r}"- )- streamed = "".join(- frame["params"]["update"].get("content", {}).get("text", "")- for frame in frames- if "content" in frame.get("params", {}).get("update", {})- )- assert "wrap-up reply" in streamed, (- f"the {side} side's wrap-up steer never streamed: {streamed!r}"- )-- # The overflow scenario's probe turn must recover on both sides.- if name == "overflow":- for side, frames in (("ts", ts_frames), ("rust", rust_frames)):- replies = responses(frames)- assert len(replies) == 2, f"{side}: expected two prompt replies, got {replies!r}"- assert replies[1]["result"]["stopReason"] == "end_turn", (- f"the {side} side's overflow recovery did not settle end_turn: {replies[1]!r}"- )-- ts_lines, rust_lines = render(ts_frames), render(rust_frames)- if ts_lines == rust_lines:- print(f"({len(ts_lines)} frames identical)")- return True- diff = list(- difflib.unified_diff(ts_lines, rust_lines, "ts", "rust", lineterm="", n=2)- )- print(f"ACP auto-compaction parity ({name}): FAIL — frame diff:")- for line in diff[:80]:- print(line)- return False---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/attach_first_frame_parity.py b/scripts/attach_first_frame_parity.pydeleted file mode 100755index 4a6784a727..0000000000--- a/scripts/attach_first_frame_parity.py+++ /dev/null@@ -1,242 +0,0 @@-#!/usr/bin/env python3-"""Attach-render parity verifier: the first frame after a daemon attach of an-IDLE session (the live-dogfood blank-pane bug class).--Drives both products (the deployed TS `prime-agent` binary and a Rust build of-this repo) through the same flow against a mock-provider daemon:--1. Create a session over the daemon wire, settle one scripted turn, close the- wire client — the session ends idle with a durable transcript.-2. Launch the interactive TUI in tmux attaching to that session id. No keys are- ever sent and the window is never resized: the first frames must come from- the attach's own render scheduling (TS `renderInitialMessages` ends in- `requestRender`; the Rust equivalent is `rebuild_view`'s dirty flag). The- verifier measures time-to-first-frame and time-to-transcript and gates both.-3. With the pane idle and attached, rename the session from a second wire- client: the pane must repaint the renamed label with no input (TS- `handleEvent`'s `session_info_changed` arm).-4. The settled attach frame is normalized and diffed TS vs Rust (visual parity- evidence).--Exit code is non-zero when any gate fails on either side or the frames differ.-"""--import argparse-import difflib-import json-import os-import re-import shutil-import sys-import tempfile-import time-from pathlib import Path--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib as B # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--FIRST_FRAME_MAX_S = 10.0-TRANSCRIPT_MAX_S = 20.0-RENAME_MAX_S = 10.0-SETTLE_TEXT = "settle the attach fixture"-SETTLE_REPLY = "idle session fixture reply"-RENAMED = "renamed-while-attached"-VOLATILE = [- # Version/model rows differ by build; the transcript is the parity claim.- re.compile(r"prime agent v\S+"),- re.compile(r"model \S+"),- re.compile(r"\d+ tokens?\b.*"),- # The two sides run in separate evidence dirs; the cwd line neutralizes.- re.compile(r"attach-frame-parity-\S+"),-]---def normalize(frame: str) -> str:- lines = []- for line in frame.splitlines():- for pattern in VOLATILE:- line = pattern.sub("", line)- lines.append(line.rstrip())- while lines and not lines[-1]:- lines.pop()- return "\n".join(lines)---def nonblank_rows(frame: str) -> int:- return sum(1 for line in frame.splitlines() if line.strip())---def run_side(name: str, binary: str, root: Path) -> dict:- print(f"[{name}] starting daemon + mock provider")- agent = root / "agent"- work = root / "work"- work.mkdir(parents=True)- agent.mkdir(parents=True)- mock = B.MockProvider(root, [])- mock.set_responses([{"text": SETTLE_REPLY}])- mock.start()- tmpdir = Path("/tmp") / f"attach-frame-{name}"- if tmpdir.exists():- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- side = B.Side(- name=name,- binary=binary,- root=root,- agent_dir=agent,- work_dir=work,- daemon_socket=root / "daemon.sock",- mock=mock,- )- side.env = B.scrubbed_env(agent, tmpdir)- side.env["PRIME_API_KEY"] = "sk-battery"- if name == "rust":- side.env["PI_PACKAGE_DIR"] = str(Path(__file__).resolve().parents[1])- side.write_models_json()- # Mark the onboarding/trace-notice state as already shown so the pane- # settles straight into the conversation (run_battery's- # `suppress_first_run_notices`): the gates below are about the attach- # render, not the first-run overlay.- settings_path = agent / "settings.json"- settings = json.loads(settings_path.read_text()) if settings_path.exists() else {}- settings["onboardingShown"] = True- settings["telemetry"] = {**(settings.get("telemetry") or {}), "noticeShown": True}- settings_path.write_text(json.dumps(settings))- side.start_daemon()-- gates = []- try:- # 1. Idle session with a settled turn, owned by nobody.- wire = B.Wire(side.daemon_socket)- create = wire.request(- "c1",- {"type": "create", "config": {- "model": "mock-1", "provider": "prime-inference", "name": "attach-frame"}},- timeout=60,- )- session_id = (create.get("data") or {}).get("activeSessionId")- assert create.get("success") and session_id, f"create failed: {json.dumps(create)[:300]}"- wire.request(- "p1",- {"type": "prompt_and_wait", "activeSessionId": session_id, "message": SETTLE_TEXT},- timeout=240,- )- wire.close()-- # 2. Attach the interactive TUI: no keys, no resize.- tmux = f"attach-frame-{name}"- argv = [- side.binary, "--daemon-socket", str(side.daemon_socket),- "--provider", "prime-inference", "--model", "mock-1",- "--resume", session_id,- ]- launch = time.time()- B.tmux_launch(tmux, argv, side.env, side.work_dir)- first_frame_s = None- transcript_s = None- deadline = launch + TRANSCRIPT_MAX_S- while time.time() < deadline:- frame = B.tmux_capture(tmux)- if first_frame_s is None and nonblank_rows(frame) >= 5:- first_frame_s = round(time.time() - launch, 2)- if SETTLE_TEXT in frame and SETTLE_REPLY in frame:- transcript_s = round(time.time() - launch, 2)- break- time.sleep(0.05)- settled = B.tmux_capture(tmux)- (root / "frames").mkdir(exist_ok=True)- (root / "frames" / "01-attach-settled.txt").write_text(settled)- if first_frame_s is None:- gates.append(f"{name}: the attach never painted a frame (no keys, no resize)")- elif first_frame_s > FIRST_FRAME_MAX_S:- gates.append(f"{name}: first frame took {first_frame_s}s (> {FIRST_FRAME_MAX_S}s)")- if transcript_s is None:- gates.append(f"{name}: the settled transcript never rendered within {TRANSCRIPT_MAX_S}s without /reload")- else:- print(f"[{name}] first frame {first_frame_s}s, transcript {transcript_s}s (no input)")- if gates:- return {"gates": gates, "frame": settled}-- # 3. Idle-session event repaint: rename from a second wire client.- renamer = B.Wire(side.daemon_socket)- rename = renamer.request(- "r1",- {"type": "rename", "activeSessionId": session_id, "name": RENAMED},- timeout=60,- )- renamer.close()- if rename.get("success") is not True:- gates.append(f"{name}: the wire rename failed: {json.dumps(rename)[:300]}")- return {"gates": gates, "frame": settled}- rename_at = time.time()- renamed_frame = ""- while time.time() < rename_at + RENAME_MAX_S:- renamed_frame = B.tmux_capture(tmux)- if RENAMED in renamed_frame:- break- time.sleep(0.05)- (root / "frames" / "02-renamed.txt").write_text(renamed_frame)- if RENAMED not in renamed_frame:- gates.append(- f"{name}: the session_info_changed rename never repainted the idle pane within {RENAME_MAX_S}s"- )- else:- print(f"[{name}] rename repainted in {round(time.time() - rename_at, 2)}s")- return {"gates": gates, "frame": settled}- finally:- B.tmux_kill(f"attach-frame-{name}")- side.stop_daemon()- mock.stop()---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--rust-bin", default=os.path.join(- Path(__file__).resolve().parents[1], "target", "release", "prime-agent"))- parser.add_argument("--ts-bin", default="prime-agent")- parser.add_argument("--keep", action="store_true", help="keep the evidence dir")- args = parser.parse_args()-- args.rust_bin = str(Path(args.rust_bin).resolve())- args.ts_bin = str(Path(args.ts_bin)) if "/" in args.ts_bin else args.ts_bin- ts_identity.assert_ts_side_is_the_ts_product(args.ts_bin, args.rust_bin)-- failures = 0- evidence = Path(tempfile.mkdtemp(prefix="attach-frame-parity-"))- print(f"evidence: {evidence}")- try:- results = {}- for name, binary in (("ts", args.ts_bin), ("rust", args.rust_bin)):- results[name] = run_side(name, binary, evidence / name)- for gate in results[name]["gates"]:- print(f"GATE FAIL: {gate}")- failures += 1- # 4. Settled-frame parity diff (normalized: version/model rows differ).- ts_frame = normalize(results["ts"]["frame"])- rust_frame = normalize(results["rust"]["frame"])- (evidence / "diff.txt").write_text(- "\n".join(difflib.unified_diff(- ts_frame.splitlines(), rust_frame.splitlines(),- fromfile="ts", tofile="rust", lineterm="")))- if ts_frame != rust_frame:- print("FRAME DIFF (normalized): see " + str(evidence / "diff.txt"))- for line in difflib.unified_diff(- ts_frame.splitlines(), rust_frame.splitlines(),- fromfile="ts", tofile="rust", lineterm=""):- print(line)- failures += 1- else:- print("settled attach frames identical after normalization")- if failures:- print(f"{failures} gate(s) failed")- return 1- print("attach-render parity: PASS")- return 0- finally:- if not args.keep:- shutil.rmtree(evidence, ignore_errors=True)---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/bang_parity.py b/scripts/bang_parity.pydeleted file mode 100644index e079ace3fc..0000000000--- a/scripts/bang_parity.py+++ /dev/null@@ -1,720 +0,0 @@-#!/usr/bin/env python3-"""Bash-mode parity: drive the `!`/`!!` chat shortcut against the installed-TS prime-agent binary and the Rust build in tmux, capture the rendered-states, and report both the behavioral needles (present on both sides or-the check fails) and the per-state frame diff as evidence.--States (same inputs on both binaries):--- `bang_run`: `!echo bang-parity-hi` — the bash row mounts, the streamed- output renders, and the run settles;-- `bangbang_run`: `!!echo excluded-row` — the excluded variant renders the- same row shape;-- `long_output`: `!seq 1 40 | sed 's/^/line-/'` — the BashExecutionComponent- box with its 20-line tail preview and `... N more lines`;-- `truncation`: `!seq 1 2100 | sed 's/^/line-/'` — past the 2000-line context- budget, the `Output truncated. Full output: <spill>` notice;-- `cancelled`: a `!sleep 30` run aborted mid-flight marks itself- `(cancelled)`;-- `exit_hint`: an idle first Ctrl+C paints the exit hint at once (TS- `showCtrlCExitHint` requestRender's on the key) — captured inside the- two-second window;-- `pane_bash`: a `!` run inside the open `/btw` side pane mounts in the- pane (transient, pane-owned);-- `guard`: a `!sleep 5` run is held open, then a second `!echo second`- submission must show the already-running guard instead of dispatching- (verified in the session file too: only the sleep row recorded);-- `bare`: a bare `!` submission is inert — nothing mounts, nothing is- sent as a prompt (verified in the session file: no new row);-- `session_rows`: the persisted rows — `!` recorded without- `excludeFromContext` (output joins the model context), `!!` recorded- with it, and the bare/`!echo second` submissions recorded nothing.--The Rust side renders the run through the ported BashExecutionComponent-(the bordered `$ cmd` card), so the per-state frames compare-byte-for-byte after the run-variant normalization (tokens, durations,-spill hex, sandbox roots) and the SGR-carryover materialization; the-behavioral needles (the `$ command` row, the streamed output, the guard-sentence, the exit hint, the persisted context flags) must also hold on-both sides, and the check prints the full frame diff per state as the-parity-diff evidence.--tmux rules: default socket only (`env -u TMUX`), bang-* session names,-no kill-server; sessions are killed individually at the end.-"""--import argparse-import json-import os-import re-import subprocess-import sys-import tempfile-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-import visual_parity as vp # noqa: E402 (sandbox prep, capture, normalize)--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--SIZE = ("120", "36")-RUN_COMMAND = "echo bang-parity-hi"-EXCLUDED_COMMAND = "echo excluded-row"-SLEEP_COMMAND = "sleep 5"-# The preview/truncation states key their needles on `line-N` rows, so the-# commands prefix every output line (`seq` alone prints bare numbers).-LONG_COMMAND = "seq 1 40 | sed 's/^/line-/'"-TRUNCATED_COMMAND = "seq 1 2100 | sed 's/^/line-/'"-CANCEL_COMMAND = "sleep 30"-PANE_COMMAND = "echo pane-run"--# The bang surface's own faux script: the /btw pane question and the-# flush turn get text-only answers (the shared FAUX_SCRIPT's tool calls-# would execute against the real daemon inside the pane).-BANG_FAUX_SCRIPT = {- "engine": "faux",- "modelId": "faux-1",- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 18,- "responses": [- {"content": [{"type": "text", "text": "4"}]},- {"content": [{"type": "text", "text": "quick check done"}]},- ],-}---def ts_release_binary():- """The deployed TS release binary as an ABSOLUTE path.-- tmux pane commands resolve `prime-agent` through the tmux SERVER's- PATH (not the harness env), and this box's PATH install is the Rust- dogfood build — a bare `prime-agent` in a pane would play a Rust- build as the ts side. Resolve the release directory that ships- `prime-agent-runtime` and is not the Rust product (its binary reports- a different version line), so the pane runs the real TS binary.- """- import ts_identity-- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- rust = ts_identity.default_rust_binary()- candidates = sorted(- (- entry- for entry in os.listdir(releases)- if os.path.isdir(os.path.join(releases, entry, "prime-agent-runtime"))- ),- reverse=True,- )- for entry in candidates:- binary = os.path.join(releases, entry, "prime-agent")- if not os.access(binary, os.X_OK):- continue- if ts_identity.probe_version(binary) and ts_identity.probe_version(- binary- ) != ts_identity.probe_version(rust):- return binary- raise SystemExit(- f"no deployed TS release under {releases} that is not the Rust build"- )---#: The ts side's absolute binary (the pane resolves PATH through the tmux-#: server, whose `prime-agent` is the Rust dogfood on this box).-TS_BINARY = ts_release_binary()---def start_binary(binary, sandbox, shared_cwd, script_path, session):- vp.tmux("kill-session", "-t", session, check=False)- vp.tmux(- "new-session", "-d", "-s", session, "-x", SIZE[0], "-y", SIZE[1], "-c", shared_cwd- )- env = (- f"HOME={sandbox['home']} "- f"TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"PRIME_AGENT_FAUX_SCRIPT={script_path} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- if binary == "ts":- command = (- f"{TS_BINARY} --daemon-socket {sandbox['agent']}/daemon.sock --model {vp.TS_SCRIPT_MODEL}"- )- else:- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)),- "..",- "target",- "debug",- "prime-agent",- ),- )- package_dir = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- # The resolved binary is part of the evidence: a polluted- # PA_RUST_BINARY (a shared-box env leak) silently plays a foreign- # build as the rust side otherwise.- print(f" [rust] binary: {rust}")- command = (- f"PI_PACKAGE_DIR={package_dir} "- f"{rust} --daemon-socket {sandbox['agent']}/daemon.sock --model {vp.TS_SCRIPT_MODEL}"- )- vp.tmux("send-keys", "-t", session, f"{env} {command}", "Enter")- vp.wait_for(session, "Collapsed mode", timeout=60)- # Settle past the attach render: a submit inside the attach window- # races renderSessionContext(clearChat) — the daemon can deliver the- # run's events after the clear (a duplicated card: the transcript row- # plus the late-mounted live card) or before it (a wiped card, the- # needle never seen). The rebuild is frame-invisible on a fresh- # session, so the settle is a grace wait plus one stable capture pair.- time.sleep(4.0)- previous = vp.capture(session, escape=False)- deadline = time.time() + 10- while time.time() < deadline:- time.sleep(0.5)- current = vp.capture(session, escape=False)- if current == previous:- break- previous = current---def assert_daemon_binary(binary, sandbox):- """The daemon serving this side's socket must be this side's binary.-- Proven hazard on the shared box: a stale daemon built days earlier- (another lane's binary) ended up serving a sandbox socket; the probe- accepted its protocol and the whole side ran against pre-feature- code. argv[0] of the daemon on our socket must match the binary the- side launched."""- socket = f"{sandbox['agent']}/daemon.sock"- expected = TS_BINARY if binary == "ts" else os.environ.get(- "PA_RUST_BINARY",- os.path.normpath(- os.path.join(- os.path.dirname(os.path.abspath(__file__)),- "..",- "target",- "debug",- "prime-agent",- )- ),- )- deadline = time.time() + 20- argv0 = None- while time.time() < deadline:- listing = subprocess.run(- ["pgrep", "-af", socket],- capture_output=True,- text=True,- ).stdout- for line in listing.splitlines():- _, _, cmd = line.partition(" ")- if "--mode daemon" in cmd:- argv0 = cmd.split()[0]- if os.path.realpath(argv0) == os.path.realpath(expected):- return- time.sleep(0.5)- raise SystemExit(- f"the {binary} daemon on {socket} is {argv0!r}, expected {expected!r} "- "(a foreign/stale daemon claimed the sandbox socket)"- )---SGR_TOKEN = re.compile(r"\x1b\[([0-9;]*)m")---def materialize_sgr(frame):- """The frame as per-cell screen state instead of escape bytes.-- SGR state persists across rows on the real screen, and `capture -e`- re-emits carried-over state inconsistently (an escape on one side's- row, carryover on the other's). Rebuilding each row from the running- state — foreground ignored on spaces, default-background trailing- spaces dropped — compares what the user sees, not where tmux placed- the escapes."""- fg = None- bg = None- attrs = set()- rows = []- for line in frame.split("\n"):- cells = []-- def push(text):- for ch in text:- cell_fg = None if ch == " " else fg- cell_attrs = () if ch == " " else tuple(sorted(attrs))- cells.append((ch, cell_fg, bg, cell_attrs))-- pos = 0- for match in SGR_TOKEN.finditer(line):- push(line[pos : match.start()])- pos = match.end()- codes = [int(code) for code in match.group(1).split(";") if code] or [0]- i = 0- while i < len(codes):- code = codes[i]- if code == 0:- fg = None- bg = None- attrs.clear()- elif code == 39:- fg = None- elif code == 49:- bg = None- elif code in (38, 48):- if i + 4 < len(codes) and codes[i + 1] == 2:- color = tuple(codes[i : i + 5])- i += 4- elif i + 2 < len(codes) and codes[i + 1] == 5:- color = tuple(codes[i : i + 3])- i += 2- else:- color = (code,)- if code == 38:- fg = color- else:- bg = color- elif 30 <= code <= 37 or 90 <= code <= 97:- fg = (code,)- elif 40 <= code <= 47 or 100 <= code <= 107:- bg = (code,)- elif code == 22:- attrs -= {1, 2}- elif 21 <= code <= 29:- attrs.discard(code - 20)- else:- attrs.add(code)- i += 1- push(line[pos:])- while cells and cells[-1][0] == " " and cells[-1][2] is None:- cells.pop()- parts = []- state = (None, None, ())- for ch, cell_fg, cell_bg, cell_attrs in cells:- cell_state = (cell_fg, cell_bg, cell_attrs)- if cell_state != state and (ch != " " or cell_bg != state[1]):- parts.append(f"<{cell_fg}|{cell_bg}|{cell_attrs}>")- state = cell_state- parts.append(ch)- rows.append("".join(parts))- return "\n".join(rows)---def visible_text(frame):- return re.sub("\x1b\[[0-9;]*m", "", frame)---def settled_pane(session):- """The pane with volatile rows (the exit-hint tray line) filtered, so- inert-action comparisons ignore the hint arming/expiring."""- pane = visible_text(vp.capture(session, escape=False))- return "\n".join(- line for line in pane.split("\n") if "again to exit" not in line- )---def session_rows(agent_dir):- rows = []- sessions = os.path.join(agent_dir, "sessions")- for name in sorted(os.listdir(sessions)) if os.path.isdir(sessions) else []:- path = os.path.join(sessions, name)- if not name.endswith(".jsonl") or not os.path.getsize(path):- continue- with open(path) as f:- for line in f:- try:- entry = json.loads(line)- except json.JSONDecodeError:- continue- message = entry.get("message", {})- if isinstance(message, dict) and message.get("role") in (- "user",- "bashExecution",- ):- rows.append(- {- "role": message.get("role"),- "command": message.get("command"),- "text": (message.get("content") or [{}])[0].get("text"),- "excluded": message.get("excludeFromContext", False) is True,- }- )- return rows---def run_states(binary, sandbox, shared_cwd, script_path):- session = f"bang-{binary}"- frames = {}- start_binary(binary, sandbox, shared_cwd, script_path, session)- assert_daemon_binary(binary, sandbox)- try:- # `!command`: the row mounts and the run settles. The needle is the- # mounted `$ command` row (the typed input echoes the same words in- # the editor before Enter, so the bare words would race the mount).- vp.tmux("send-keys", "-t", session, f"!{RUN_COMMAND}", "Enter")- vp.wait_for(session, f"$ {RUN_COMMAND}", timeout=30)- time.sleep(1.0)- frames["bang_run"] = vp.capture(session)- # The attach-render race guard: one run mounts one card. A second- # card means the settle above lost the race (the recorded row- # rendered next to the live card) -- fail loudly, never compare- # through it.- cards = visible_text(frames["bang_run"]).count(f"$ {RUN_COMMAND}")- if cards != 1:- print(f" [{binary}] the first bang run mounted {cards} cards (attach race)")-- # `!!command`: the excluded variant renders the same row shape.- vp.tmux("send-keys", "-t", session, f"!!{EXCLUDED_COMMAND}", "Enter")- vp.wait_for(session, f"$ {EXCLUDED_COMMAND}", timeout=30)- time.sleep(1.0)- frames["bangbang_run"] = vp.capture(session)-- # The already-running guard: hold a run open, submit a second one.- vp.tmux("send-keys", "-t", session, f"!{SLEEP_COMMAND}", "Enter")- vp.wait_for(session, f"$ {SLEEP_COMMAND}", timeout=30)- time.sleep(0.5)- vp.tmux("send-keys", "-t", session, "!echo second", "Enter")- deadline = time.time() + 20- guard = False- while time.time() < deadline:- pane = visible_text(vp.capture(session, escape=False))- if "already running" in pane:- guard = True- break- time.sleep(0.2)- frames["guard"] = vp.capture(session)- if not guard:- print(f" [{binary}] the guard sentence never rendered")- # Cancel the held run (TS's guard names the clear key) and settle.- # The exit hint ("Press Ctrl+C again to exit") arms on each press- # and expires after two seconds, so settle past it before the- # bare-! comparison frames.- vp.tmux("send-keys", "-t", session, "C-c")- time.sleep(2.5)- vp.tmux("send-keys", "-t", session, "C-c")- time.sleep(2.5)-- # A bare `!` is inert: nothing mounts, nothing is sent.- before = settled_pane(session)- vp.tmux("send-keys", "-t", session, "!", "Enter")- time.sleep(2.5)- after = settled_pane(session)- frames["bare"] = vp.capture(session)- frames["bare_inert"] = "1" if before == after else ""- if before != after:- print(f" [{binary}] a bare ! changed the frame (should be inert):")- import difflib-- for delta in difflib.unified_diff(- before.split("\n"), after.split("\n"), lineterm="", n=0- ):- if delta and delta[0] in "+-" and delta[:3] not in ("+++", "---"):- print(f" {delta!r}")- frames["bare"] += "\n\nBARE NOT INERT\n" + vp.capture(session)-- # The live-event cards the lane's verifier spec adds: the long- # output preview, the truncation notice, the cancelled run, and- # the bang inside the /btw side pane.- # Long output: the 20-line preview plus its hidden-count row.- vp.tmux("send-keys", "-t", session, f"!{LONG_COMMAND}", "Enter")- vp.wait_for(session, f"$ {LONG_COMMAND}", timeout=30)- time.sleep(2.0)- frames["long_output"] = vp.capture(session)-- # Truncation: past the 2000-line context budget the tail cut names- # its spill file (TS `truncateTail` + `fullOutputPath`).- vp.tmux("send-keys", "-t", session, f"!{TRUNCATED_COMMAND}", "Enter")- deadline = time.time() + 30- while time.time() < deadline:- pane = visible_text(vp.capture(session, escape=False))- if "more lines" in pane and "Output truncated" in pane:- break- time.sleep(0.3)- time.sleep(1.0)- frames["truncation"] = vp.capture(session)-- # Cancel mid-run: the clear key aborts the held run, the card- # marks itself (cancelled). The guard case above already left a- # cancelled sleep-5 card in the transcript, so the probe must find- # the marker BELOW this run's header, never the earlier card's.- vp.tmux("send-keys", "-t", session, "!sleep 30", "Enter")- vp.wait_for(session, "$ sleep 30", timeout=30)- time.sleep(0.5)- vp.tmux("send-keys", "-t", session, "C-c")- deadline = time.time() + 30- cancelled_below_header = False- while time.time() < deadline:- rows = visible_text(vp.capture(session, escape=False)).split("\n")- header = [i for i, line in enumerate(rows) if "$ sleep 30" in line]- marker = [i for i, line in enumerate(rows) if "(cancelled)" in line]- if header and marker and min(marker) > max(header):- cancelled_below_header = True- break- time.sleep(0.3)- if not cancelled_below_header:- print(f" [{binary}] the sleep-30 run never marked itself (cancelled)")- # The exit hint arms on the interrupt and expires after two- # seconds; settle past it before capturing.- time.sleep(2.5)- frames["cancelled"] = vp.capture(session)-- # The idle first press paints the exit hint AT ONCE (TS- # `showCtrlCExitHint` requestRender's on the key; the paint must- # carry the freshly armed tray row, not the pre-key tray). The- # capture sits inside the two-second window.- vp.tmux("send-keys", "-t", session, "C-c")- time.sleep(0.3)- frames["exit_hint"] = vp.capture(session)- # Let the hint expire before any later key lands.- time.sleep(2.5)-- # Bang inside the side pane: the /btw pane mounts, and the run- # renders inside it (transient, pane-owned).- vp.tmux("send-keys", "-t", session, "/btw what is 2+2", "Enter")- vp.wait_for(session, "/btw", timeout=30)- time.sleep(3.0)- vp.tmux("send-keys", "-t", session, "!echo pane-run", "Enter")- vp.wait_for(session, "$ echo pane-run", timeout=30)- time.sleep(1.5)- frames["pane_bash"] = vp.capture(session)- # Leave the pane before the flush turn (a prompt closes it).- vp.tmux("send-keys", "-t", session, "Escape")- time.sleep(2.5)-- # One settled model turn: the session store flushes its buffered- # rows (the TS store appends lazily; a killed daemon would lose- # them), so the persisted context flags become observable.- vp.tmux("send-keys", "-t", session, vp.PROMPT, "Enter")- try:- vp.wait_for(session, "quick check", timeout=60)- except TimeoutError:- print(f" [{binary}] the flush turn never streamed")- time.sleep(10)- frames["session_rows"] = json.dumps(session_rows(sandbox["agent"]), indent=1)- except TimeoutError:- # The pane and the side's processes at the failure instant — the- # finally kills the session, so this is the only evidence a- # needle timeout leaves behind.- print(f" [{binary}] TIMEOUT — pane at failure:")- for line in visible_text(vp.capture(session, escape=False)).split("\n"):- if line.strip():- print(f" |{line}")- listing = subprocess.run(- ["pgrep", "-af", sandbox["agent"]], capture_output=True, text=True- ).stdout- print(f" [{binary}] processes: {listing}")- raise- finally:- vp.tmux("kill-session", "-t", session, check=False)- return frames---def needles(binary, frames):- """The visible facts each state must show."""- facts = {- "bang_run": visible_text(frames["bang_run"]),- "bangbang_run": visible_text(frames["bangbang_run"]),- "guard": visible_text(frames["guard"]),- }- return facts---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--keep", action="store_true", help="keep the sandbox dir")- parser.add_argument("--out", default=None, help="captures directory")- args = parser.parse_args()-- ts_identity.assert_ts_side_is_the_ts_product(TS_BINARY)-- # A SHORT base: the truncation notice renders its spill path inside- # the box, and the Rust spill hex is 32 chars (TS's is 16), so a long- # base would wrap the notice on the Rust side only — a sandbox- # artifact, not a product divergence. Short keeps both sides inside- # the content width.- base = tempfile.mkdtemp(prefix="bp-sb-")- print(f"sandbox: {base}")- out_dir = args.out or tempfile.mkdtemp(prefix="bang-parity-captures-")- os.makedirs(out_dir, exist_ok=True)- shared_cwd, script_path, sandboxes = vp.prepare_sandbox(base)- with open(script_path, "w") as f:- json.dump(BANG_FAUX_SCRIPT, f, indent=2)- failures = []- try:- os.environ.pop("TMUX", None)- ts_frames = run_states("ts", sandboxes["ts"], shared_cwd, script_path)- rust_frames = run_states("rust", sandboxes["rust"], shared_cwd, script_path)-- # The behavioral needles: each visible fact must hold on both sides.- for command in (RUN_COMMAND, EXCLUDED_COMMAND):- for binary, frames in (("ts", ts_frames), ("rust", rust_frames)):- key = "bang_run" if command == RUN_COMMAND else "bangbang_run"- cards = visible_text(frames[key]).count(f"$ {command}")- if cards != 1:- # Zero = the attach render wiped the submit; two = the- # recorded row rendered next to the live card. Either- # way the settle in start_binary was outrun — a rerun- # decides, never a normalization.- failures.append(f"{binary}-{key}-card-count")- print(f"FAIL {binary} {key}: {cards} `$ {command}` cards")- if command.split()[-1] not in visible_text(frames[key]):- failures.append(f"{binary}-{key}-output")- print(f"FAIL {binary} {key}: the output never rendered")- for binary, frames in (("ts", ts_frames), ("rust", rust_frames)):- if "already running" not in visible_text(frames["guard"]):- failures.append(f"{binary}-guard")- print(f"FAIL {binary} guard: the guard sentence never rendered")- if frames.get("bare_inert") != "1":- failures.append(f"{binary}-bare-inert")- print(f"FAIL {binary} bare: a bare ! was not inert")-- # The live-event cards (the lane's verifier extension).- long_text = visible_text(frames["long_output"])- if f"$ {LONG_COMMAND}" not in long_text:- failures.append(f"{binary}-long-output-header")- print(f"FAIL {binary} long_output: no `$ {LONG_COMMAND}` header")- if "line-40" not in long_text or "more lines" not in long_text:- failures.append(f"{binary}-long-output-preview")- print(f"FAIL {binary} long_output: the preview tail never rendered")- if "line-1 " in long_text:- failures.append(f"{binary}-long-output-hidden")- print(f"FAIL {binary} long_output: the older half leaked past the preview")-- truncated_text = visible_text(frames["truncation"])- if f"$ {TRUNCATED_COMMAND}" not in truncated_text:- failures.append(f"{binary}-truncation-header")- print(f"FAIL {binary} truncation: no `$ {TRUNCATED_COMMAND}` header")- if "Output truncated. Full output:" not in truncated_text:- failures.append(f"{binary}-truncation-notice")- print(f"FAIL {binary} truncation: the spill notice never rendered")- if "line-2100" not in truncated_text:- failures.append(f"{binary}-truncation-tail")- print(f"FAIL {binary} truncation: the tail never rendered")-- cancelled_rows = visible_text(frames["cancelled"]).split("\n")- cancelled_header = [- i for i, line in enumerate(cancelled_rows) if f"$ {CANCEL_COMMAND}" in line- ]- cancelled_marker = [- i for i, line in enumerate(cancelled_rows) if "(cancelled)" in line- ]- if not cancelled_header:- failures.append(f"{binary}-cancelled-header")- print(f"FAIL {binary} cancelled: no `$ {CANCEL_COMMAND}` header")- # The earlier guard case's cancelled card stays in the- # transcript, so only a marker below THIS run's header counts.- if not (cancelled_header and cancelled_marker and min(cancelled_marker) > max(cancelled_header)):- failures.append(f"{binary}-cancelled-marker")- print(f"FAIL {binary} cancelled: the marker never rendered on the run's card")-- pane_text = visible_text(frames["pane_bash"])- if f"$ {PANE_COMMAND}" not in pane_text:- failures.append(f"{binary}-pane-bash-mount")- print(f"FAIL {binary} pane_bash: the pane never mounted the run")- elif pane_text.count(PANE_COMMAND.split()[-1]) < 2:- failures.append(f"{binary}-pane-bash-output")- print(f"FAIL {binary} pane_bash: the pane run's output never rendered")-- exit_hint_text = visible_text(frames["exit_hint"])- if "Press Ctrl+C again to exit" not in exit_hint_text:- failures.append(f"{binary}-exit-hint")- print(f"FAIL {binary} exit_hint: the first press never painted the hint")-- # The persisted context flags: `!` joins the context, `!!` does not,- # and the guarded/bare submissions recorded nothing.- for binary, frames in (("ts", ts_frames), ("rust", rust_frames)):- rows = json.loads(frames["session_rows"])- joined = [row for row in rows if row["role"] == "bashExecution" and not row["excluded"]]- excluded = [row for row in rows if row["excluded"]]- if not any(row["command"] == RUN_COMMAND for row in joined):- failures.append(f"{binary}-context-join")- print(f"FAIL {binary}: the ! run was not recorded into the session context")- if not any(row["command"] == EXCLUDED_COMMAND for row in excluded):- failures.append(f"{binary}-context-exclude")- print(f"FAIL {binary}: the !! run was not recorded excluded")- second = [row for row in rows if row["role"] == "user" and "second" in (row["text"] or "")]- if second:- failures.append(f"{binary}-guarded-not-sent")- print(f"FAIL {binary}: the guarded submission leaked into the session")-- # The frame diff per rendered state (the parity evidence).- def bang_normalize(frame, root):- # The truncation notice names each side's own spill file (the- # per-binary sandbox tmp dir plus a run hex), so those- # normalize to one placeholder before comparing.- norm = vp.normalize(frame, root)- # The pane's first row: tmux attaches the previous row's- # foreground reset differently for identical screens (before- # the popup-background escape, or absent when the row above- # already ended default); a reset ahead of another escape- # describes the same default either way.- norm = re.sub(r"\n\x1b\[39m(?=\x1b)", "\n", norm)- # TS spills as pi-bash-<hex>.log, the Rust port as- # pa-bash-<hex>.log (branding; the path itself is transient- # either way).- norm = re.sub(- r"<SANDBOX>/(?:ts|rust)/tmp/p[ia]-bash-[0-9a-f]+\.log",- "<SPILL>",- norm,- )- # tmux capture -e omits an SGR that carried over from a- # previous row (the color stays active on screen without a- # re-emitted escape) and both sides paint identical screens- # with different carryover layouts: materialize the active- # foreground at each row start so the compare sees the screen,- # not the escape placement.- return materialize_sgr(norm)-- for state in (- "bang_run",- "bangbang_run",- "guard",- "long_output",- "truncation",- "cancelled",- "exit_hint",- "pane_bash",- ):- ts_norm = bang_normalize(ts_frames[state], base)- rust_norm = bang_normalize(rust_frames[state], base)- name = f"{state}-{SIZE[0]}x{SIZE[1]}"- if ts_norm == rust_norm:- print(f"PASS {name}")- else:- report = os.path.join(out_dir, f"diff-{name}.txt")- with open(report, "w") as f:- f.write(vp.diff_lines(ts_norm, rust_norm))- failures.append(f"{state}-frame-diff")- print(f"DIFF {name} (renderer deviation, see {report})")- for state, frames in (- ("ts", ts_frames),- ("rust", rust_frames),- ):- with open(os.path.join(out_dir, f"frames-{state}.txt"), "w") as f:- f.write(f"{state} session rows:\n{frames['session_rows']}\n\n")- for key in (- "bang_run",- "bangbang_run",- "guard",- "bare",- "long_output",- "truncation",- "cancelled",- "exit_hint",- "pane_bash",- ):- f.write(f"\n===== {key} =====\n{frames[key]}\n")- print(f"captures in {out_dir}")- return 1 if failures else 0- finally:- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if not args.keep:- subprocess.run(["rm", "-rf", base], check=False)---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/battery/README.md b/scripts/battery/README.mdindex f1658f2dae..e322b1a865 100644--- a/scripts/battery/README.md+++ b/scripts/battery/README.md@@ -1,70 +1,62 @@-# Parity battery--NOTE: battery greenness ("0 gaps") covers only the scripted flows run-here over the deterministic mock provider - it is not a product-parity-statement. Flows f14-f21 are the real-surface flows (compact, a2a, refine,-/model, goal/autonomous, heartbeat, subagents, worker recovery): they drive-the daemon session plus the attached interactive TUI, frame-diff TS vs Rust-at the key moment, and record surface gaps as EXPECTED-FAIL with the owning-fix lane.--One-command re-run (from the repo root):-- python3 scripts/battery/run_battery.py--Each run writes `scripts/battery/runs/<UTC stamp>/` with per-side evidence-(`ts/`, `rust/`), a `report.md` comparison table, and machine-readable-`findings.json`. Requires the TS binary `prime-agent` on PATH (ground truth)-and a built Rust binary (default `target/release/prime-agent`).--Files: `run_battery.py` (driver), `batterylib.py` (shared harness; also-owns the daemon-reap sweep every standalone parity harness reuses:-`reap_daemons(needles=[...])` sweeps any `--mode daemon` process whose-argv references the given paths — the graceful `sd` shutdown first, then-the SIGTERM/SIGKILL rounds until a respawned main is gone. Every-standalone harness (visual, osc, queue, compact, tool-card,-custom-message, print-json, compaction-abort, provider-error) reaps in-its cleanup path — a sandbox tempdir must never outlive its daemons-(#223: one was observed spinning at 74% CPU on a deleted socket); the-harness sandboxes pin an isolated per-side TMPDIR so the TS supervisor's-socket lands under the sandbox root the sweep can name),-`ts_identity.py` (shared ts-identity guard: every PATH-driven parity-harness refuses to run when its "ts" binary is this repo's Rust product —-e.g. a stale Rust build symlinked onto PATH as `prime-agent`),-`provider_error_probe.py` (provider-error shape probe: scripted-non-2xx answers, raw-socket h2 and WebSocket mocks, dead-port connection-probes — one custom provider per scenario; captures the persisted-errorMessage plus the `provider_stream_failure` / `provider_transport_failure`-diagnostics per side, TS vs Rust),-`mock_provider.py` (deterministic mock provider; responses are-session-scoped queues — a queue is selected per request by markers in the-request's user-message text, so a parent session and a concurrently running-spawned child each get their own scripted responses deterministically),-`perf.py` (f10 perf rows),-`sustained_cpu.py` (sustained-CPU regression guard, lane cpu-spin: the-interactive TUI driven through the faux provider — a 30s idle window, a-paced plain-text stream, a paced markdown/code stream, and a long-tool-execution turn — with %CPU sampled per process from /proc and-ASSERTED: idle <5% and streaming <30% of one core, keystroke-to-render-mid-stream <50ms, the paused viewport stable mid-stream, and a double-Ctrl+C mid-scroll terminating the process (bug #6's no-escape invariant).-`perf_wave.py` exposes it as the `sustained_cpu` dimension and-`perf_gate.py` tracks its medians against the baseline),-`framediff_first_run.py` (first-run frame diff),-`streaming_render.py` (live token-stream rendering verifier: pane captures-must grow progressively mid-turn over a paced faux provider, TS vs Rust-differential on the settled frame),-`scale_corpus.py` (f12 heavy-scale corpus generator).--Heavy flow (opt-in, not part of the default battery run):-- PA_BATTERY_HEAVY=1 python3 scripts/battery/run_battery.py --flows f12_scale_resume--`f12_scale_resume` generates a deterministic PA_BATTERY_HEAVY_TURNS-turn-session (default 5,000 turns = 15,261 transcript rows of user / assistant /-ipython-tool turns plus harness-digest rows) and measures interactive-`--resume` -> ready for both binaries through tmux. Gates: the Rust side-must reach ready within SCALE_RESUME_MAX_READY_S (30s) and within-SCALE_RESUME_MAX_RATIO (2.0x) of the TS side in the same run - a-regression gate for the snapshot replay/render path (per-row re-layout or-uncached preview work must not come back).+# Perf-wave battery++The perf wave measures the interactive TUI against the deployed TS+binary (the "ts" side) and a release build of this repo (the "rust"+side), gates the rust medians against the recorded baseline, and is+driven by the Makefile `perf-wave` target:++ make perf-wave++`perf-wave` runs `ci_perf_wave.sh`, the CI-shaped entry: it creates an+ephemeral Prime sandbox (4 CPU / 16 GB, the spec class the baseline was+recorded on), installs the deployed TS binary plus a fresh release build+of the checkout, runs the wave there, downloads the results, and gates+them (`perf_gate.py` against `perf-baseline.json`). Every timing comes+from the same quiet machine for both sides, which is the whole point of+the sandbox. `PA_BENCH_NO_SANDBOX=1` runs the wave directly on the host+instead (`run_perf_wave.sh` + `perf_wave.py`).++Files:++- `ci_perf_wave.sh` — the Makefile entry (sandbox lifecycle, results+ download, the gate call)+- `run_perf_wave.sh` — the local runner (same shape as the CI entry,+ without the sandbox dance)+- `perf_wave.py` — the driver (dimensions below; accepts --ts-bin /+ --rust-bin)+- `sustained_cpu.py` — the sustained-CPU dimension: the interactive TUI+ driven through the faux provider — a 30s idle window, a paced plain-text+ stream, a paced markdown/code stream, and a long tool-execution turn —+ with %CPU sampled per process from /proc and ASSERTED: idle <5% and+ streaming <30% of one core, keystroke-to-render mid-stream <50ms, the+ paused viewport stable mid-stream, and a double Ctrl+C mid-scroll+ terminating the process (bug #6's no-escape invariant)+- `stream_throughput.py` — the stream-throughput dimension (token+ throughput of the live render loop, both binaries)+- `perf.py` — the perf measurement helpers the dimensions share:+ startup launch-to-ready, keystroke-to-render typing latency, and+ cold-resume-to-ready over the same tmux pane channel a real user+ types through (both product sides)+- `scale_corpus.py` — the deterministic heavy-scale corpus the resume+ dimension replays (the 350-turn / 1078-row corpus perf_wave.py+ generates via scale_corpus for its resume dim)+- `perf_gate.py` — the gate (medians vs `perf-baseline.json`, default+ threshold 1.10)+- `perf-baseline.json` — the recorded baseline the gate compares against+- `batterylib.py` — the shared harness (side sessions, the deterministic+ mock provider, the daemon-reap sweep every harness reuses:+ `reap_daemons(needles=[...])` sweeps any `--mode daemon` process whose+ argv references the given paths — the graceful `sd` shutdown first, then+ the SIGTERM/SIGKILL rounds until a respawned main is gone; the harness+ sandboxes pin an isolated per-side TMPDIR so a supervisor's socket lands+ under the sandbox root the sweep can name)+- `mock_provider.py` — the deterministic mock provider batterylib drives+ (responses are session-scoped queues — a queue is selected per request+ by markers in the request's user-message text, so a parent session and+ a concurrently running spawned child each get their own scripted+ responses deterministically)+- `ts_identity.py` — the shared ts-identity guard: every PATH-driven+ harness refuses to run when its "ts" binary is this repo's Rust product+- `../ts_faux_extension.js` — the faux-provider driver extension the TS+ side loads (scripted responses read from PRIME_AGENT_FAUX_SCRIPT);+ verification harness only, never installed for real usersdiff --git a/scripts/battery/aborted_row_probe.py b/scripts/battery/aborted_row_probe.pydeleted file mode 100644index 86f631f84b..0000000000--- a/scripts/battery/aborted_row_probe.py+++ /dev/null@@ -1,273 +0,0 @@-"""Ground-truth probe for the terminal turn_end frame + the aborted-turn-row (lanes turn-end-frame / aborted-row): what each side's daemon-broadcasts + persists when a turn settles normally, when it is aborted-mid-provider-wait (plain `abort`), when one parked steering message is-delivered by the interrupt (`abort_and_send_queued`, schema 29), and what-the compact abort shows. The `turn_end` frames are captured raw per side-and compared cross-side (timestamps normalized) — settled and aborted-turns alike."""-import glob-import json, os, sys, time, shutil-from pathlib import Path--sys.path.insert(0, str(Path(__file__).resolve().parent))-import batterylib as B-import ts_identity # noqa: E402 (the shared binary-identity guard)--RUN = Path("/tmp/aborted-row-probe")---def default_ts_binary() -> str:- """The ts side's launch command (the rules queue_edit_parity.py- established): the box PATH `prime-agent` may itself be the Rust- dogfood install, and the deployed 0.9.5 release predates schema 29- (abortAndSendQueued, TS PR #2426, never reached it), so the probe- compares against the TS-main bundle from the parity checkout.- PA_TS_BINARY overrides (an absolute path or a full command string)."""- override = os.environ.get("PA_TS_BINARY")- if override:- return override- ts_main_cli = os.path.join(- "/home/ubuntu/prime-agent", "packages", "coding-agent", "dist", "bundle", "cli.js"- )- if os.path.exists(ts_main_cli):- return f"node {ts_main_cli}"- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- candidates = sorted(glob.glob(os.path.join(releases, "0.9.5-linux-x64-*", "prime-agent")))- if not candidates:- raise SystemExit("neither the TS-main checkout nor a deployed TS release found; set PA_TS_BINARY")- return candidates[-1]---def ts_executable(command: str) -> str:- """batterylib spawns `[binary, ...]` directly, so a node-bundle- command needs a wrapper executable."""- if " " not in command:- return command- RUN.mkdir(parents=True, exist_ok=True)- wrapper = RUN / "ts-cli"- wrapper.write_text(f"#!/bin/sh\nexec {command} \"$@\"\n")- wrapper.chmod(0o755)- return str(wrapper)--def make_side(name: str, binary: str) -> B.Side:- root = RUN / name- if root.exists():- shutil.rmtree(root)- root.mkdir(parents=True)- agent = root / "agent"- work = root / "work"- work.mkdir(parents=True)- agent.mkdir(parents=True)- mock = B.MockProvider(root, [])- mock.set_responses([{"text": "statusline filler"}])- mock.start()- tmpdir = Path("/tmp") / f"abrt-probe-{name}"- if tmpdir.exists():- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- side = B.Side(name=name, binary=binary, root=root, agent_dir=agent,- work_dir=work, daemon_socket=root / "daemon.sock", mock=mock)- side.env = B.scrubbed_env(agent, tmpdir, {"PRIME_DISABLE_AUTO_COMPACTION": "1"})- side.write_models_json()- return side--def turn_end_frames(frames: list[dict]) -> list[dict]:- """The `turn_end` session events, raw event payloads in arrival order."""- out = []- for frame in frames:- event = frame.get("event") or {}- if event.get("type") == "turn_end":- out.append(event)- return out--def normalize_turn_end(event: dict) -> dict:- """The volatile-free form compared cross-side: wire envelope metadata- and the message timestamp differ per side, everything else must- byte-match (the terminal message shape, the toolResults list)."""- event = json.loads(json.dumps(event))- message = event.get("message")- if isinstance(message, dict):- message.pop("timestamp", None)- return event--def probe(side: B.Side, abort_command: dict | None, key: str) -> None:- # The settled case consumes the immediate reply; the abort cases hold- # the turn mid-provider-wait (the 15s delay) — each side is fresh, so- # the queue holds exactly the one reply the case needs first. The- # abort-and-send case parks one steering message before the interrupt- # (the held reply cancels with the turn, the second reply answers the- # delivered steering turn).- reply = (- {"text": "settled reply", "delayMs": 0}- if abort_command is None- else {"text": "held reply", "delayMs": 15000}- )- replies = [reply]- if key == "abort_and_send_queued":- replies.append({"text": "queued steering reply", "delayMs": 0})- side.mock.set_responses(- [{"text": "statusline filler"}],- queues=[{- "name": "aborted-row-probe",- "matchModels": ["mock-1"],- "responses": replies,- }],- )- side.start_daemon()- wire = B.Wire(side.daemon_socket)- create = wire.request("c1", {- "type": "create", "name": f"aborted-row-probe-{key}",- "config": {- "cwd": str(side.work_dir),- "sessionDir": str(side.agent_dir / "sessions"),- "provider": "prime-inference",- "model": "mock-1",- "executionMode": "print",- },- }, timeout=120)- session_id = create.get("data", {}).get("activeSessionId") or create.get("data", {}).get("id")- attacher = B.Wire(side.daemon_socket)- attacher.request("a1", {"type": "attach", "activeSessionId": session_id}, timeout=60)- attacher.events.clear()- prompt = wire.request("p1", {- "type": "prompt", "activeSessionId": session_id,- "message": "held turn for the abort probe" if abort_command else- "settled turn for the frame probe",- }, timeout=60)- if abort_command:- time.sleep(0.8) # mid-provider-wait (the 15s hold)- if key == "abort_and_send_queued":- # One steering message parked at the turn boundary, so the- # interrupt aborts the held run AND delivers it (schema 29):- # TS batches the armed steering into one new turn, the Rust- # port runs it as its own boundary turn — the `turn_end`- # payloads compared below must match either way.- steer = wire.request("sq1", {- "type": "steer", "activeSessionId": session_id,- "message": "queued steering text",- }, timeout=60)- print(f"[{side.name}/{key}] steer queued: {steer.get('success')}")- # The close command itself must answer on the CANCELLED turn: TS- # `closeSessionOnce` fires `session.abort()` (the run cancel) before- # any close work that can wait on the turn, so the reply lands far- # inside the 15s hold (a kill that streams the held reply out first- # is the #247 residue: the abort landed only after the turn settled- # naturally).- command_started = time.monotonic()- abort = wire.request("ab1", dict(abort_command, activeSessionId=session_id), timeout=120)- command_seconds = time.monotonic() - command_started- else:- abort, command_seconds = {"success": True}, 0.0- idle = wire.request("w1", {"type": "wait_for_idle", "activeSessionId": session_id}, timeout=120)- attacher.drain(2.0)- rows = []- for frame in attacher.events:- ev = frame.get("event") or {}- if ev.get("type") in ("message_start", "message_end", "message_update", "turn_end", "agent_end"):- m = ev.get("message") or {}- rows.append({- "wire": ev.get("type"),- "role": m.get("role"),- "stopReason": m.get("stopReason"),- "errorMessage": m.get("errorMessage"),- "text": (m.get("content") if isinstance(m.get("content"), str) else- "".join(p.get("text", "") for p in (m.get("content") or []) if isinstance(p, dict))),- })- (side.root / f"{key}-wire-events.json").write_text(json.dumps(rows, indent=1))- (side.root / f"{key}-raw-frames.json").write_text(json.dumps(attacher.events, indent=1))- turn_ends = [normalize_turn_end(event) for event in turn_end_frames(attacher.events)]- (side.root / f"{key}-turn-end-frames.json").write_text(json.dumps(turn_ends, indent=1))- (side.root / f"{key}-timing.json").write_text(json.dumps({- "command": (abort_command or {}).get("type"),- "command_seconds": round(command_seconds, 3),- "hold_seconds": 0 if not abort_command else 15,- }, indent=1))- # the durable store- store_rows = []- for path in side.session_files():- for line in path.read_text().splitlines():- try:- entry = json.loads(line)- except Exception:- continue- if entry.get("type") == "message":- m = entry.get("fields", {}).get("message") or entry.get("message") or {}- store_rows.append({- "role": m.get("role"),- "stopReason": m.get("stopReason"),- "errorMessage": m.get("errorMessage"),- })- (side.root / f"{key}-store-rows.json").write_text(json.dumps(store_rows, indent=1))- print(f"[{side.name}/{key}] abort={abort.get('success')} idle={idle.get('success')} "- f"command_seconds={command_seconds:.2f}")- print(f"[{side.name}/{key}] wire: {json.dumps(rows)[:600]}")- print(f"[{side.name}/{key}] turn_ends: {json.dumps(turn_ends)[:600]}")- print(f"[{side.name}/{key}] store: {json.dumps([r for r in store_rows if r.get('role') == 'assistant'])[:600]}")- attacher.close()- wire.close()- side.stop_daemon()--def compare(key: str, sides: list[str]) -> bool:- """Byte-compare the normalized `turn_end` frames cross-side for one- case: settled and aborted turns must carry the same terminal payload- (the terminal/aborted assistant message and the toolResults list)."""- captures = {}- for name in sides:- path = RUN / f"{name}-{key}" / f"{key}-turn-end-frames.json"- if path.exists():- captures[name] = json.loads(path.read_text())- if len(captures) < 2:- print(f"[compare/{key}] missing sides: {sorted(captures)}")- return False- ts, rust = captures["ts"], captures["rust"]- if ts == rust:- print(f"[compare/{key}] turn_end frames MATCH ({len(ts)} frame(s))")- print(f"[compare/{key}] ts: {json.dumps(ts)[:400]}")- return True- print(f"[compare/{key}] turn_end frames DIFFER")- print(f"[compare/{key}] ts: {json.dumps(ts)[:800]}")- print(f"[compare/{key}] rust: {json.dumps(rust)[:800]}")- return False--def main():- ts_command = default_ts_binary()- # Fail fast before any launch: the probe's parity tables are only a- # parity claim when the ts side is the TS product. The TS-main bundle- # prints its version line to stderr: redirect it into the guard's- # stdout probe (the queue_edit_parity rule).- ts_identity.assert_ts_side_is_the_ts_product(f"{ts_command} 2>&1")- ts_bin = ts_executable(ts_command)- rust_bin = os.environ.get("ABORTED_ROW_RUST_BIN") or ts_identity.default_rust_binary()- cases = [- ("settled", None),- ("abort", {"type": "abort"}),- ("abort_and_send_queued", {"type": "abort_and_send_queued"}),- ("compact", {"type": "compact"}),- ("kill", {"type": "kill"}),- ("abort_and_clear_queue", {"type": "abort_and_clear_queue"}),- ]- sides = [- name- for name in os.environ.get("ABORTED_ROW_SIDES", "ts,rust").split(",")- if name- ]- binaries = {"ts": ts_bin, "rust": rust_bin}- for name, binary in binaries.items():- if name not in sides:- continue- for key, command in cases:- side = make_side(f"{name}-{key}", binary)- try:- probe(side, command, key)- finally:- side.stop_daemon()- if "ts" in sides and "rust" in sides:- ok = True- for key, _ in cases:- ok = compare(key, sides) and ok- print("[compare] " + ("ALL turn_end frames MATCH" if ok else "DIFFERENCES FOUND"))- sys.exit(0 if ok else 1)--if __name__ == "__main__":- main()diff --git a/scripts/battery/agent_end_messages_probe.py b/scripts/battery/agent_end_messages_probe.pydeleted file mode 100644index d8a4c269da..0000000000--- a/scripts/battery/agent_end_messages_probe.py+++ /dev/null@@ -1,270 +0,0 @@-"""Ground-truth probe for the agent_end messages payload (lane-agent-end-messages): what each side's daemon broadcasts on the wire for-the run-boundary frames of one turn - the `agent_end` frames' `messages`-payloads (TS `agent_end` carries the run's whole message set, one frame-per agent run), plus the per-run `agent_start`/`turn_start` frames that-retried and continued runs restart with.--Cases (each side fresh, one turn each):- - settled: a plain turn that settles normally - one agent run whose- agent_end carries the harness-digest row, the accepted- user row, and the settled assistant row.- - retried: a retryable provider failure (HTTP 500) then a success -- two agent runs; the failed run's agent_end carries the- accepted rows plus the failed assistant row, the retry- re-opens with its own agent_start/turn_start, and its- agent_end carries only the retry's messages.- - continued: a context-overflow error (HTTP 400) then a success - the- compact-and-retry recovery: the overflow run ends with its- agent_end, the compaction runs, and the re-issued- continuation run re-opens with its own frames and its own- agent_end payload.--The `agent_end` frames are captured raw per side and compared cross-side-(timestamps normalized) - frame count, frame order, and every payload-byte must match.-"""-import json, os, sys, time, shutil-from pathlib import Path--sys.path.insert(0, str(Path(__file__).resolve().parent))-import batterylib as B--RUN = Path("/tmp/agent-end-messages-probe")--# The overflow error text the TS `isContextOverflow` and the Rust-# `is_context_overflow` classifiers both match (the mock-provider-# documented scripted overflow shape).-OVERFLOW_ERROR = "prompt is too long: 213462 tokens > 200000 maximum"---def make_side(name: str, binary: str, retry_settings: bool, compact_settings: bool) -> B.Side:- root = RUN / name- if root.exists():- shutil.rmtree(root)- root.mkdir(parents=True)- agent = root / "agent"- work = root / "work"- work.mkdir(parents=True)- agent.mkdir(parents=True)- mock = B.MockProvider(root, [])- mock.set_responses([{"text": "statusline filler"}])- mock.start()- tmpdir = Path("/tmp") / f"agent-end-probe-{name}"- if tmpdir.exists():- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- side = B.Side(name=name, binary=binary, root=root, agent_dir=agent,- work_dir=work, daemon_socket=root / "daemon.sock", mock=mock)- side.env = B.scrubbed_env(agent, tmpdir)- side.write_models_json()- settings = {}- if retry_settings:- # Small retry delays so the retried case settles fast on both- # sides (TS `retry.baseDelayMs` / the Rust `retry.baseDelayMs`).- settings["retry"] = {"enabled": True, "maxRetries": 2, "baseDelayMs": 100}- if compact_settings:- # The overflow recovery's compaction needs a cut point: the tiny- # keep-recent tail lets the short probe session compact instead of- # skipping ("Session is too short to compact").- settings["compaction"] = {"keepRecentTokens": 10}- if settings:- (agent / "settings.json").write_text(json.dumps(settings))- return side---def agent_end_frames(frames: list[dict]) -> list[dict]:- """The `agent_end` session events, raw event payloads in arrival order."""- out = []- for frame in frames:- event = frame.get("event") or {}- if event.get("type") == "agent_end":- out.append(event)- return out---def normalize(value):- """Strip the volatile fields cross-side: message timestamps (and the- diagnostics' timestamps) and the JS `stack` traces inside- provider_stream_failure diagnostics (a bun binary path trace the Rust- side structurally never has); everything else must byte-match."""- if isinstance(value, dict):- return {- key: normalize(item)- for key, item in value.items()- if key not in ("timestamp", "stack")- }- if isinstance(value, list):- return [normalize(item) for item in value]- return value---def frame_fingerprint(frames: list[dict]) -> list[str]:- """The run-boundary frame sequence (type + payload presence), so the- probe diff also catches a missing/extra per-run frame, not just the- payloads."""- out = []- for frame in frames:- event = frame.get("event") or {}- etype = event.get("type")- # `auto_retry_*` is deliberately excluded: the retry driver's- # `auto_retry_end` ordering (TS resets at the successful- # message_end hook, before the retry run's turn_end; the Rust- # retry driver closes it after the attempt boundary) is a known- # pre-existing divergence owned by the provider-retry surface, not- # the run-boundary frames this probe locks.- if etype in ("agent_start", "turn_start", "turn_end", "agent_end",- "compaction_start", "compaction_end"):- if etype == "turn_end":- message = event.get("message") or {}- out.append(f"turn_end:{message.get('stopReason')}")- elif etype == "agent_end":- roles = [- message.get("role")- for message in (event.get("messages") or [])- ]- out.append("agent_end:" + ",".join(roles))- else:- out.append(str(etype))- return out---def probe(side: B.Side, key: str, responses: list[dict], timeout: float) -> None:- side.mock.set_responses(- [{"text": "statusline filler"}],- queues=[{- "name": "agent-end-probe",- "matchModels": ["mock-1"],- "responses": responses,- }],- )- side.start_daemon()- wire = B.Wire(side.daemon_socket)- create = wire.request("c1", {- "type": "create", "name": f"agent-end-probe-{key}",- "config": {- "cwd": str(side.work_dir),- "sessionDir": str(side.agent_dir / "sessions"),- "provider": "prime-inference",- "model": "mock-1",- "executionMode": "print",- },- }, timeout=120)- session_id = create.get("data", {}).get("activeSessionId") or create.get("data", {}).get("id")- attacher = B.Wire(side.daemon_socket)- attacher.request("a1", {"type": "attach", "activeSessionId": session_id}, timeout=60)- attacher.events.clear()- if key == "continued":- # The compact-and-retry recovery needs compaction material: a long- # first turn fills the session so the overflow arm's compaction- # runs instead of skipping ("Session is too short to compact").- wire.request("filler", {- "type": "prompt", "activeSessionId": session_id,- "message": "context filler turn for the continued probe",- }, timeout=60)- wire.request("w0", {"type": "wait_for_idle", "activeSessionId": session_id}, timeout=timeout)- wire.request("p1", {- "type": "prompt", "activeSessionId": session_id,- "message": f"{key} turn for the agent end probe",- }, timeout=60)- idle = wire.request("w1", {"type": "wait_for_idle", "activeSessionId": session_id}, timeout=timeout)- print(f"[{side.name}/{key}] idle={idle.get('success')}")- attacher.drain(3.0)- (side.root / f"{key}-raw-frames.json").write_text(json.dumps(attacher.events, indent=1))- (side.root / f"{key}-agent-end-frames.json").write_text(- json.dumps([normalize(event) for event in agent_end_frames(attacher.events)], indent=1)- )- fingerprint = frame_fingerprint(attacher.events)- (side.root / f"{key}-boundary-fingerprint.json").write_text(json.dumps(fingerprint, indent=1))- print(f"[{side.name}/{key}] boundary: {json.dumps(fingerprint)}")- print(f"[{side.name}/{key}] agent_ends: "- f"{json.dumps([normalize(e) for e in agent_end_frames(attacher.events)])[:900]}")- attacher.close()- wire.close()- side.stop_daemon()---def compare(key: str) -> bool:- """Byte-compare the normalized `agent_end` frames and the boundary- frame sequence cross-side for one case."""- captures = {}- for name in ("ts", "rust"):- path = RUN / f"{name}-{key}" / f"{key}-agent-end-frames.json"- if path.exists():- captures[name] = json.loads(path.read_text())- if len(captures) < 2:- print(f"[compare/{key}] missing sides: {sorted(captures)}")- return False- ok = True- if captures["ts"] == captures["rust"]:- print(f"[compare/{key}] agent_end frames MATCH ({len(captures['ts'])} frame(s))")- for frame in captures["ts"]:- print(f"[compare/{key}] payload roles: "- f"{[m.get('role') for m in frame.get('messages', [])]}")- else:- ok = False- print(f"[compare/{key}] agent_end frames DIFFER")- print(f"[compare/{key}] ts: {json.dumps(captures['ts'])[:900]}")- print(f"[compare/{key}] rust: {json.dumps(captures['rust'])[:900]}")- fingerprints = {}- for name in ("ts", "rust"):- path = RUN / f"{name}-{key}" / f"{key}-boundary-fingerprint.json"- if path.exists():- fingerprints[name] = json.loads(path.read_text())- if fingerprints.get("ts") == fingerprints.get("rust"):- print(f"[compare/{key}] boundary sequence MATCH: {json.dumps(fingerprints.get('ts'))}")- else:- ok = False- print(f"[compare/{key}] boundary sequence DIFFER")- print(f"[compare/{key}] ts: {json.dumps(fingerprints.get('ts'))}")- print(f"[compare/{key}] rust: {json.dumps(fingerprints.get('rust'))}")- return ok---def main():- ts_bin = "prime-agent"- rust_bin = os.environ.get(- "AGENT_END_RUST_BIN",- "/home/ubuntu/lane-worktrees/agent-end-messages/target/release/prime-agent",- )- cases = [- # key, mock responses (served in order, last replays), retry settings, idle timeout- ("settled", [{"text": "settled reply"}], False, False, 120),- ("retried", [{"error": "mock provider overloaded", "status": 500},- {"text": "recovered reply"}], True, False, 180),- ("continued", [- {"text": "history filler " * 120},- {"error": OVERFLOW_ERROR, "status": 400},- {"text": "recovered after compaction reply"},- ], False, True, 300),- ]- sides = [- name- for name in os.environ.get("AGENT_END_SIDES", "ts,rust").split(",")- if name- ]- wanted = [- name- for name in os.environ.get("AGENT_END_CASES", "settled,retried,continued").split(",")- if name- ]- cases = [case for case in cases if case[0] in wanted]- binaries = {"ts": ts_bin, "rust": rust_bin}- for name in sides:- binary = binaries[name]- for key, responses, retry_settings, compact_settings, timeout in cases:- side = make_side(f"{name}-{key}", binary, retry_settings, compact_settings)- try:- probe(side, key, responses, timeout)- finally:- side.stop_daemon()- if "ts" in sides and "rust" in sides:- ok = True- for key, _, _, _, _ in cases:- ok = compare(key) and ok- print("[compare] " + ("ALL agent_end frames MATCH" if ok else "DIFFERENCES FOUND"))- sys.exit(0 if ok else 1)---if __name__ == "__main__":- main()diff --git a/scripts/battery/flicker_parity.py b/scripts/battery/flicker_parity.pydeleted file mode 100644index a3862fcd8f..0000000000--- a/scripts/battery/flicker_parity.py+++ /dev/null@@ -1,336 +0,0 @@-#!/usr/bin/env python3-"""View-switch flicker verifier (lane: pa-tui alt-screen handoff).--Drives the TS and Rust products through the chat -> agents -> chat view-cycle in a tmux pane whose PRIMARY screen carries a marker line, and-samples tmux's per-pane `alternate_on` state throughout the in-app window.-The alternate screen must stay active across every view switch (TS-`pendingAltScreenHandoff`: the screen is entered once and handed between-surfaces); any sample showing the primary screen (alternate_on=0) mid-flow-is a flicker frame and is captured as evidence.--Also verifies the teardown parity around the handoff:- - a real chat exit (C-c C-c) leaves the screen and flushes the inline- frame onto the primary screen (exit-flush fires only on real exits);- - exiting the agents view leaves the screen with no flush (TS- `flushFullscreen: false`), so the marker line is back in view.--Run (from the repo root):-- python3 scripts/battery/flicker_parity.py --rust-bin <ABS>/target/release/prime-agent--Writes evidence under scripts/battery/runs/<stamp>-flicker/{ts,rust}/ and-prints a verdict per side; exit code 1 on any flicker frame or teardown gap.-"""--from __future__ import annotations--import argparse-import datetime-import json-import os-import re-import shutil-import sys-import threading-import time-from pathlib import Path--sys.path.insert(0, str(Path(__file__).parent))-import batterylib as B # noqa: E402-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--MARKER = "PRIMARYSCREENMARKER-0123456789"-REPLY_TEXT = "flicker idle reply"-PROMPT_TEXT = "flicker idle prompt"-SESSION_NAME = "flicker-idle-session"---class FlickerSampler(threading.Thread):- """Poll the pane's alternate-screen state; capture flicker frames."""-- def __init__(self, session: str):- super().__init__(daemon=True)- self.session = session- self.stop_flag = threading.Event()- self.samples = 0- self.flickers: list[dict] = []-- def run(self) -> None:- while not self.stop_flag.is_set():- out = B.tmux(- "display-message",- "-p",- "-t",- f"{self.session}:0",- "#{alternate_on}",- check=False,- ).stdout.strip()- self.samples += 1- if out == "0":- frame = B.tmux_capture(self.session)- self.flickers.append({"alternate_on": out, "frame": frame})-- def stop(self) -> None:- self.stop_flag.set()- self.join(timeout=10)---def make_side(name: str, binary: str, run_dir: Path) -> B.Side:- root = run_dir / name- root.mkdir(parents=True, exist_ok=True)- agent = root / "agent"- work = root / "work"- work.mkdir(parents=True, exist_ok=True)- agent.mkdir(parents=True, exist_ok=True)- mock = B.MockProvider(root, [])- mock.set_responses([{"text": REPLY_TEXT}])- mock.start()- tmpdir = Path("/tmp") / f"{run_dir.name}-{name}"- if tmpdir.exists():- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- side = B.Side(- name=name,- binary=binary,- root=root,- agent_dir=agent,- work_dir=work,- daemon_socket=root / "daemon.sock",- mock=mock,- )- side.env = B.scrubbed_env(agent, tmpdir)- side.env["PRIME_API_KEY"] = "sk-battery"- side.write_models_json()- side.start_daemon()- # The agents view is gated on completed onboarding on both products.- settings_path = agent / "settings.json"- settings = json.loads(settings_path.read_text()) if settings_path.exists() else {}- settings["onboardingShown"] = True- settings_path.write_text(json.dumps(settings))- create_idle_session(side)- return side---def create_idle_session(side: B.Side) -> str:- """One completed live session, so the roster shows an openable row."""- wire = B.Wire(side.daemon_socket)- create = wire.request(- "cfl",- {- "type": "create",- "name": SESSION_NAME,- "config": {- "cwd": str(side.work_dir),- "sessionDir": str(side.agent_dir / "sessions"),- "provider": "prime-inference",- "model": "mock-1",- "executionMode": "print",- },- },- timeout=120,- )- if create.get("success") is not True:- wire.close()- raise RuntimeError(f"{side.name}: daemon create failed: {json.dumps(create)[:300]}")- idle_id = create.get("data", {}).get("activeSessionId") or create.get("data", {}).get("id") or ""- wire.request(- "pfl",- {"type": "prompt_and_wait", "activeSessionId": idle_id, "message": PROMPT_TEXT},- timeout=240,- )- wire.close()- return idle_id---def run_cycle(side: B.Side, cycles: int) -> dict:- """Launch the agents view in a marked pane, cycle view -> chat -> view,- sampling the alternate-screen state throughout, then verify the two- teardown paths (real chat exit vs. agents-view exit)."""- evidence_dir = side.root / "f14_view_switch"- evidence_dir.mkdir(parents=True, exist_ok=True)- session = f"{run_id}-{side.name}-f14"- # A plain shell pane first: the marker line makes the primary screen- # unmistakable if a view switch ever shows it.- B.tmux_launch(session, ["/bin/sh"], side.env, side.work_dir)- time.sleep(0.5)- B.tmux_send(session, f"printf '{MARKER}'")- time.sleep(0.5)- side.evidence(- "f14_view_switch",- "00-primary-screen-marker.txt",- B.tmux_capture(session),- )- B.tmux_send(- session,- f"exec {side.binary} agents --daemon-socket {side.daemon_socket}",- )- view = B.tmux_wait_text(session, r"Idle \(|Running \(|Inactive \(", timeout=40)- side.evidence("f14_view_switch", "01-agents-view.txt", view)-- sampler = FlickerSampler(session)- sampler.start()- transitions = []- for i in range(cycles):- # Open the idle row (search narrows to the session by name).- B.tmux_send(session, SESSION_NAME)- time.sleep(0.8)- chat = B.tmux_wait_text(session, re.escape(REPLY_TEXT), timeout=60)- transitions.append(("open", chat))- # Agents-back (Left with an empty editor hands the pane to the view).- B.tmux_send(session, "Left", enter=False)- view_back = B.tmux_wait_text(session, r"Idle \(", timeout=60)- transitions.append(("back", view_back))- # Clear the search so the next cycle starts from the full roster.- B.tmux_send(session, "C-u", enter=False)- time.sleep(0.5)- sampler.stop()- for j, (kind, frame) in enumerate(transitions):- side.evidence("f14_view_switch", f"02-{kind}-{j:02d}.txt", frame)- for k, flicker in enumerate(sampler.flickers):- side.evidence(- "f14_view_switch",- f"03-FLICKER-{k:02d}.txt",- flicker["frame"],- )-- # Real exit from the chat: the pane must die showing the flushed- # transcript (the exit flush fires on real exits only) and the- # primary screen must be back (alternate_on 0 is legitimate here).- B.tmux_send(session, SESSION_NAME)- time.sleep(0.8)- B.tmux_wait_text(session, re.escape(REPLY_TEXT), timeout=60)- B.tmux("set-option", "-t", session, "remain-on-exit", "on", check=False)- B.tmux_send(session, "C-c", enter=False)- time.sleep(0.3)- B.tmux_send(session, "C-c", enter=False)- deadline = time.time() + 10- pane_state = ""- while time.time() < deadline:- pane_state = B.tmux(- "display-message", "-p", "-t", session, "#{pane_dead} #{pane_dead_status}", check=False- ).stdout.strip()- if pane_state.startswith("1"):- break- time.sleep(0.1)- final = B.tmux_capture(session)- side.evidence("f14_view_switch", "04-chat-exit-frame.txt", final)- alt_after_exit = B.tmux(- "display-message", "-p", "-t", session, "#{alternate_on}", check=False- ).stdout.strip()- B.tmux_kill(session)-- # Agents-view exit: the screen is left with no flush, so the marker- # line is back in view on the primary screen.- session2 = f"{session}-exit"- B.tmux_launch(session2, ["/bin/sh"], side.env, side.work_dir)- time.sleep(0.5)- B.tmux_send(session2, f"printf '{MARKER}'")- time.sleep(0.5)- B.tmux_send(session2, f"exec {side.binary} agents --daemon-socket {side.daemon_socket}")- B.tmux_wait_text(session2, r"Idle \(", timeout=40)- B.tmux("set-option", "-t", session2, "remain-on-exit", "on", check=False)- B.tmux_send(session2, "Escape", enter=False)- deadline = time.time() + 10- alt_view_exit = None- while time.time() < deadline:- alt_view_exit = B.tmux(- "display-message", "-p", "-t", session2, "#{alternate_on}", check=False- ).stdout.strip()- pane_dead = B.tmux(- "display-message", "-p", "-t", session2, "#{pane_dead}", check=False- ).stdout.strip()- if pane_dead == "1":- break- time.sleep(0.1)- view_exit_frame = B.tmux_capture(session2)- side.evidence("f14_view_switch", "05-agents-view-exit-frame.txt", view_exit_frame)- B.tmux_kill(session2)-- return {- "samples": sampler.samples,- "flickers": len(sampler.flickers),- "chat_exit_frame_flushed": PROMPT_TEXT in final,- "chat_exit_alt_released": alt_after_exit == "0",- "chat_exit_pane_dead": pane_state.startswith("1"),- "view_exit_alt_released": alt_view_exit == "0",- "view_exit_marker_back": MARKER in view_exit_frame,- "view_exit_no_flush": PROMPT_TEXT not in view_exit_frame,- }---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--ts-bin", default="prime-agent")- parser.add_argument(- "--rust-bin",- default=str(Path.cwd() / "target" / "release" / "prime-agent"),- )- parser.add_argument("--runs-root", default=str(Path(__file__).parent / "runs"))- parser.add_argument("--cycles", type=int, default=2)- args = parser.parse_args()-- stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")- global run_id- run_id = "flick" + stamp- run_dir = Path(args.runs_root) / f"{stamp}-flicker"- run_dir.mkdir(parents=True)-- ts_bin = B.run_cmd(["which", args.ts_bin], os.environ.copy(), Path("/tmp"), timeout=10)- ts_path = ts_bin["stdout"].strip() if ts_bin["exit_code"] == 0 else args.ts_bin- rust_bin = str(Path(args.rust_bin).resolve())- if not Path(rust_bin).exists():- print(f"Rust binary not found: {rust_bin}", file=sys.stderr)- return 1- # Fail fast before any launch: a non-TS ts binary plays a Rust build as- # the "ts" side and reports false divergences.- ts_identity.assert_ts_side_is_the_ts_product(ts_path, rust_bin)-- results: dict[str, dict] = {}- sides = []- ok = True- try:- for name, binary in (("ts", ts_path), ("rust", rust_bin)):- side = make_side(name, binary, run_dir)- sides.append(side)- print(f"[{name}] cycling view switches (cycles={args.cycles}) ...")- results[name] = run_cycle(side, args.cycles)- rec = results[name]- print(f"[{name}] {json.dumps(rec)}")- verdict = (- rec["flickers"] == 0- and rec["chat_exit_frame_flushed"]- and rec["chat_exit_pane_dead"]- and rec["view_exit_alt_released"]- and rec["view_exit_marker_back"]- )- ok = ok and verdict- print(f"[{name}] verdict: {'PASS' if verdict else 'FAIL'}")- # Differential: the TS reference must show the same handoff contract.- ts_flickers = results["ts"]["flickers"]- rs_flickers = results["rust"]["flickers"]- print(- f"parity: primary-screen frames during view switches — ts={ts_flickers}, rust={rs_flickers}"- )- finally:- for side in sides:- try:- wire = B.Wire(side.daemon_socket)- wire.send_command("sfl", {"type": "shutdown"})- wire.close()- except (OSError, EOFError):- pass- side.stop_daemon()- side.mock.stop()- report = {- "run_dir": str(run_dir),- "cycles": args.cycles,- "results": results,- }- (run_dir / "report.json").write_text(json.dumps(report, indent=1))- print(f"evidence: {run_dir}/report.json")- return 0 if ok else 1---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/battery/framediff_first_run.py b/scripts/battery/framediff_first_run.pydeleted file mode 100644index 3c5866f11c..0000000000--- a/scripts/battery/framediff_first_run.py+++ /dev/null@@ -1,256 +0,0 @@-#!/usr/bin/env python3-"""B-2 first-run frame-diff: capture the fresh-install onboarding frame-(splash + trace-sharing notice) from the TS and Rust binaries at 120x36 and-diff it row-for-row, like scripts/visual_parity.py.--The splash animates a lab field behind the brand mark (cells drift every-120ms), so the two frame captures can never be byte-equal in that band. The-diff therefore splits the frame:- - text rows (welcome line, question panel, choice rows, note) compare with- their escape sequences (colour, bold/italic, the selection wash) after- the visual-parity normalizations;- - the mark band (the seven animated rows) compares only at the static- brand-mark cells (the logo quiet zone); the drifting field around them- cannot be synchronized across captures.--Both sides launch flagless (no --provider/--model): the onboarding gate-must resolve the startup model from settings + auth, exactly like the TS-`isOnboardingModelReady` chain, so the fresh agent dir (PRIME_API_KEY +-models.json provider key, no saved default) reaches the trace question-without explicit flags. Exit code is non-zero when the frames differ.-- python3 scripts/battery/framediff_first_run.py [--out DIR]-"""--import argparse-import difflib-import re-import json-import shutil-import sys-import time-from pathlib import Path--import ts_identity # the shared PATH-binary identity guard (same dir)--sys.path.insert(0, str(Path(__file__).parent))-import batterylib as B--FLOW = "framediff"-# The splash layout: frame row 0 blank, rows 1-7 the mark band. The brand-# mark (LOGO_INDENT=5) paints its glyphs at priority 8 over the animated-# field, so exactly the logo glyph cells are static and comparable; the-# drifting field (ambient dots, contours, traces) rides everywhere else,-# including the mark's blank cells, and cannot be synchronized.-MARK_ROW_BASE = 1-LOGO_INDENT = 5-LOGO_LINES = [- " ▗▄▄█▀",- " ███▄ ▗▄███▀",- " ▗█▛▐█▙ ▗▄█▀▗█▀",- " ▗█▛ ▟██▙▄██▛ ▟▛",- " ▗▟▌ ▐███▛▘▗▄█▖",- "▟███▄ ▄▄▟███▀",- "▜█▛▀▘ ▜█▛▀▘",-]---def band_text(frame: str) -> list[str]:- """The static mark cells: one string per band row, logo glyphs only."""- import re as _re-- rows = frame.split("\n")- out = []- for y, logo in enumerate(LOGO_LINES):- row = rows[MARK_ROW_BASE + y] if MARK_ROW_BASE + y < len(rows) else ""- row = _re.sub("\x1b\[[0-9;]*m", "", row)- out.append("".join(row[LOGO_INDENT + x] for x, char in enumerate(logo) if char != " "))- return out---def capture_escape(session: str) -> str:- return B.tmux("capture-pane", "-e", "-p", "-t", session).stdout---def capture_plain(session: str) -> str:- return B.tmux_capture(session)---def normalize(frame: str, root: str) -> str:- frame = frame.replace(root, "<SANDBOX>")- # tmux moves the trailing foreground-reset between identical screens;- # both spellings describe default-coloured cells.- frame = frame.replace("\x1b[39m\n", "\n")- lines = []- for line in frame.split("\n"):- # crossterm emits an explicit default-fg reset where TS writes- # nothing (the theme's empty text colour); visually identical.- line = re.sub(r"^\x1b\[39m", "", line)- # TS styles the row text and leaves its leading indent unstyled;- # the Rust span starts at the indent. The same cells either way:- # move the indent before the row's SGR.- line = re.sub(r"^((?:\x1b\[[0-9;]+m)+)( )", r"\2\1", line)- lines.append(line)- return "\n".join(lines)---def split_frame(frame: str) -> tuple[list[str], list[str]]:- """(styled text rows, static mark cells) as separate line lists."""- band_rows = {MARK_ROW_BASE + y for y in range(len(LOGO_LINES))}- rows = frame.split("\n")- text = [- row for index, row in enumerate(rows) if index not in band_rows- ]- return text, band_text(frame)---def diff_lines(left: list[str], right: list[str]) -> str:- return "\n".join(- difflib.unified_diff(left, right, fromfile="ts", tofile="rust", lineterm="", n=1)- )---def make_side(name: str, binary: str, root: Path) -> B.Side:- agent = root / "agent"- work = root / "work"- work.mkdir(parents=True, exist_ok=True)- agent.mkdir(parents=True)- mock = B.MockProvider(root, [])- mock.set_responses([{"text": "framediff reply"}])- mock.start()- tmpdir = Path("/tmp") / f"f1fd-{name}"- if tmpdir.exists():- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- side = B.Side(- name=name,- binary=binary,- root=root,- agent_dir=agent,- work_dir=work,- daemon_socket=root / "daemon.sock",- mock=mock,- )- side.env = B.scrubbed_env(agent, tmpdir)- side.env["PRIME_API_KEY"] = "sk-battery"- # A real user terminal: the ambient sandbox NO_COLOR would strip TS- # chalk modifiers (bold/italic) while the Rust side forces color output,- # so the pane command unsets it and opts both sides into truecolor.- side.env["COLORTERM"] = "truecolor"- side.write_models_json()- return side---def run_side(name: str, binary: str, base: Path, out: Path) -> dict[str, str]:- root = base / name- root.mkdir(parents=True)- side = make_side(name, binary, root)- session = f"f1fd-{name}"- # Flagless: the startup model comes from settings + auth resolution- # (TS findInitialModel over the auth-configured catalog), not from- # explicit provider/model flags.- argv = [- "/usr/bin/env",- # A real user terminal: the ambient sandbox pins NO_COLOR/FORCE_COLOR- # to suppress chalk styling in the TS binary; strip them so both- # sides render their full styled surface.- "-u",- "NO_COLOR",- "-u",- "FORCE_COLOR",- "-u",- "CLICOLOR",- binary,- "--daemon-socket",- str(side.daemon_socket),- "--offline",- ]- B.tmux_launch(session, argv, side.env, side.work_dir)- frames: dict[str, str] = {}- try:- deadline = time.time() + 30- while time.time() < deadline:- plain = capture_plain(session)- if "Share agent traces" in plain:- break- time.sleep(0.5)- else:- print(f"{name}: never reached the trace question")- sys.exit(2)- # Let a fresh animation frame settle, then capture with escapes.- time.sleep(0.3)- frames["notice-share-selected"] = capture_escape(session)- # Down moves the selection to `Not now`: the highlight row follows.- B.tmux_send(session, "Down", enter=False)- time.sleep(0.4)- frames["notice-notnow-selected"] = capture_escape(session)- # Answering settles the pane into the main session screen.- B.tmux_send(session, "Enter", enter=False)- deadline = time.time() + 20- while time.time() < deadline:- plain = capture_plain(session)- if "Share agent traces" not in plain:- break- time.sleep(0.5)- time.sleep(0.5)- frames["after-answer"] = capture_escape(session)- finally:- B.tmux_kill(session)- side.mock.stop()- if side.daemon_proc and side.daemon_proc.poll() is None:- side.daemon_proc.terminate()- (out / name).mkdir(parents=True, exist_ok=True)- for state, frame in frames.items():- (out / name / f"{name}-{state}.txt").write_text(frame)- settings = side.agent_dir / "settings.json"- if settings.exists():- (out / name / "settings-after.json").write_text(settings.read_text())- return frames---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument(- "--rust-bin",- default=str(Path(__file__).parent.parent.parent / "target/release/prime-agent"),- )- parser.add_argument("--ts-bin", default="prime-agent")- parser.add_argument("--out", default=None)- args = parser.parse_args()-- import tempfile-- # Fail fast before any launch: a non-TS ts binary plays a Rust build as- # the "ts" side and reports false divergences.- ts_identity.assert_ts_side_is_the_ts_product(args.ts_bin, args.rust_bin)-- base = Path(tempfile.mkdtemp(prefix="f1framediff-"))- out = Path(args.out) if args.out else base / "captures"- out.mkdir(parents=True, exist_ok=True)-- ts = run_side("ts", args.ts_bin, base, out)- rust = run_side("rust", args.rust_bin, base, out)-- failures = []- for state in ("notice-share-selected", "notice-notnow-selected"):- ts_text, ts_band = split_frame(normalize(ts[state], str(base)))- rust_text, rust_band = split_frame(normalize(rust[state], str(base)))- if ts_band != rust_band:- print(f"FAIL {state}: mark band differs")- (out / f"diff-band-{state}.txt").write_text(diff_lines(ts_band, rust_band))- failures.append(f"{state}/band")- if ts_text != rust_text:- print(f"FAIL {state}: text rows differ")- (out / f"diff-text-{state}.txt").write_text(diff_lines(ts_text, rust_text))- failures.append(f"{state}/text")- if not any(f"{state}/" in f for f in failures):- print(f"PASS {state}: splash frames match (styled text rows + static mark cells)")-- both = (ts["after-answer"], rust["after-answer"])- print(f"after-answer frames captured for both sides: {len(both) == 2}")- print(f"captures in {out}")- return 1 if failures else 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/battery/framediff_prime_login.py b/scripts/battery/framediff_prime_login.pydeleted file mode 100755index 9cf489e6dd..0000000000--- a/scripts/battery/framediff_prime_login.py+++ /dev/null@@ -1,371 +0,0 @@-#!/usr/bin/env python3-"""B-3 first-run prime-login frame-diff: capture the fresh-install-onboarding + Prime Inference login flow from the TS and Rust binaries at-120x36 and diff it row-for-row, like scripts/battery/framediff_first_run.py-(the shared frame-parity harness grammar: scripts/custom_message_parity.py).--The flow needs a backend without a real Prime account, so both sides point-at ONE local mock Prime API (a read-only http.server): the challenge-generate answers a fixed challenge (the URL block + the "Code:" line), the-status poll stays pending forever (the pasted-key prompt wins the race),-whoami grants the inference write permission, and the team list carries two-teams (the onboarding team question — the TS OnboardingChoiceComponent-frame, not the /login team picker).--States, each captured with escapes after its needle settles:- welcome the splash (brand line, description, login action)- url-block the mounted login dialog (URL, Verification code,- the arm prompt, the paste field, the auth-actions row)- team-question the account question (personal account + the teams)- picker the connect-more providers picker- trace-question the trace-sharing question--The splash animates its lab field behind the brand mark, so the diff splits-like framediff_first_run.py: the seven mark-band rows compare only at the-static logo cells; every other row compares with its escape sequences after-the visual-parity normalizations (the default-fg reset, the indent-before-SGR-move). The mock challenge URL is canonicalized (the query shape may differ-in encoding across the two clients); the exit code is non-zero when any-state differs.-- python3 scripts/battery/framediff_prime_login.py [--out DIR]-"""--import argparse-import difflib-import http.server-import json-import re-import sys-import threading-import time-from pathlib import Path--import ts_identity # the shared PATH-binary identity guard (same dir)--sys.path.insert(0, str(Path(__file__).parent))-import batterylib as B--MARK_ROW_BASE = 1-LOGO_INDENT = 5-LOGO_LINES = [- " ▗▄▄█▀",- " ███▄ ▗▄███▀",- " ▗█▛▐█▙ ▗▄█▀▗█▀",- " ▗█▛ ▟██▙▄██▛ ▟▛",- " ▗▟▌ ▐███▛▘▗▄█▖",- "▟███▄ ▄▄▟███▀",- "▜█▛▀▘ ▜█▛▀▘",-]--TEAMS_BODY = json.dumps(- {- "data": [- {"teamId": "team-acme", "name": "Acme Corp", "slug": "acme", "role": "Owner"},- {"teamId": "team-beta", "name": "Beta Team", "slug": None, "role": "Member"},- ],- "total_count": 2,- }-)-WHOAMI_BODY = json.dumps({"data": {"scope": {"inference": {"write": True}}}})---class MockPrimeApi(http.server.BaseHTTPRequestHandler):- """The read-only Prime API: a pending browser challenge, a permitted- key, and a two-team account."""-- def log_message(self, *_args):- pass-- def _answer(self, body, status=200):- raw = body.encode()- self.send_response(status)- self.send_header("Content-Type", "application/json")- self.send_header("Content-Length", str(len(raw)))- self.end_headers()- self.wfile.write(raw)-- def do_GET(self): # noqa: N802 (http.server naming)- if "/api/v1/user/whoami" in self.path:- self._answer(WHOAMI_BODY)- elif "/api/v1/user/teams" in self.path:- self._answer(TEAMS_BODY)- elif "/api/v1/auth_challenge/status" in self.path:- self._answer('{"pending":true}')- else:- self._answer("{}", status=404)-- def do_POST(self): # noqa: N802 (http.server naming)- length = int(self.headers.get("Content-Length") or 0)- self.rfile.read(length)- if "/api/v1/auth_challenge/generate" in self.path:- self._answer('{"challenge":"ch-mock","status_auth_token":"tok-mock"}')- else:- self._answer("{}", status=404)---def start_prime_api() -> tuple[int, threading.Thread, http.server.ThreadingHTTPServer]:- server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), MockPrimeApi)- thread = threading.Thread(target=server.serve_forever, daemon=True)- thread.start()- return server.server_address[1], thread, server---def capture_escape(session: str) -> str:- return B.tmux("capture-pane", "-e", "-p", "-t", session).stdout---def capture_plain(session: str) -> str:- return B.tmux_capture(session)---def normalize(frame: str) -> str:- lines = []- for line in frame.split("\n"):- line = re.sub(r"^\x1b\[39m", "", line)- line = re.sub(r"^((?:\x1b\[[0-9;]+m)+)( )", r"\2\1", line)- # The login URL row: the mock challenge URL, canonicalized across- # the two clients' query encodings.- line = re.sub(- r"https://mock\.example/dashboard/tokens/challenge\?[^ ]*",- "<LOGIN-URL>",- line,- )- lines.append(line)- return "\n".join(lines)---def band_text(frame: str) -> list[str]:- rows = frame.split("\n")- out = []- for y, logo in enumerate(LOGO_LINES):- row = rows[MARK_ROW_BASE + y] if MARK_ROW_BASE + y < len(rows) else ""- row = re.sub("\x1b\[[0-9;]*m", "", row)- out.append(- "".join(row[LOGO_INDENT + x] for x, char in enumerate(logo) if char != " ")- )- return out---def split_frame(frame: str) -> tuple[list[str], list[str]]:- band_rows = {MARK_ROW_BASE + y for y in range(len(LOGO_LINES))}- rows = frame.split("\n")- text = [row for index, row in enumerate(rows) if index not in band_rows]- return text, band_text(frame)---def diff_lines(left: list[str], right: list[str]) -> str:- return "\n".join(- difflib.unified_diff(left, right, fromfile="ts", tofile="rust", lineterm="", n=1)- )---def wait_for(session: str, needle: str, timeout: float = 30.0) -> None:- deadline = time.time() + timeout- while time.time() < deadline:- if needle in capture_plain(session):- return- time.sleep(0.5)- print(f"{session}: never showed {needle!r}")- sys.exit(2)---def make_side(name: str, binary: str, root: Path, prime_port: int) -> B.Side:- agent = root / "agent"- work = root / "work"- work.mkdir(parents=True, exist_ok=True)- agent.mkdir(parents=True)- mock = B.MockProvider(root, [])- mock.set_responses([{"text": "framediff reply"}])- mock.start()- tmpdir = root / "tmp"- tmpdir.mkdir(parents=True)- side = B.Side(- name=name,- binary=binary,- root=root,- agent_dir=agent,- work_dir=work,- daemon_socket=root / "daemon.sock",- mock=mock,- )- side.env = B.scrubbed_env(agent, tmpdir)- # `scrubbed_env` keeps the ambient environment apart from the worker- # markers: an operator-pinned PRIME_TEAM_ID would skip the team- # question (the flow answers the pin instead), so the harness drops- # it — and `tmux_launch` unsets it in the pane (a key that only- # inherits from the tmux server is neither an assignment nor on the- # scrub list) — the frame-diff drives the full question.- side.env.pop("PRIME_TEAM_ID", None)- # A real user terminal: both sides render their full styled surface.- side.env["COLORTERM"] = "truecolor"- # The mock Prime API: the browser challenge stays pending, whoami- # permits the key, the account carries two teams (the team question).- side.env["PRIME_AGENT_INFERENCE_API_BASE_URL"] = f"http://127.0.0.1:{prime_port}"- side.env["PRIME_AGENT_INFERENCE_FRONTEND_URL"] = "https://mock.example"- # No PRIME_API_KEY and no stored apiKey: the home is not model-ready- # (batterylib's write_models_json seeds a configured prime-inference- # key, which would SKIP the welcome/login flow this harness drives),- # so the catalog carries the model without the credential and the- # full first-run flow runs (welcome -> sign-in -> team question ->- # picker -> traces).- side.agent_dir.mkdir(parents=True, exist_ok=True)- (side.agent_dir / "models.json").write_text(- json.dumps(- {- "providers": {- "prime-inference": {- "api": "openai-completions",- # `Side.base_url` is a property (batterylib): no call.- "baseUrl": side.base_url,- "models": [- {- "id": "mock-1",- "name": "Mock 1",- "api": "openai-completions",- "baseUrl": side.base_url,- "contextWindow": 128000,- "maxTokens": 4096,- }- ],- }- }- },- indent=1,- )- )- return side---def run_side(- name: str,- binary: str,- base: Path,- out: Path,- prime_port: int,-) -> dict[str, str]:- root = base / name- root.mkdir(parents=True)- side = make_side(name, binary, root, prime_port)- session = f"plfd-{name}"- argv = [- "/usr/bin/env",- "-u",- "NO_COLOR",- "-u",- "FORCE_COLOR",- "-u",- "CLICOLOR",- binary,- "--daemon-socket",- str(side.daemon_socket),- "--offline",- ]- B.tmux_launch(session, argv, side.env, side.work_dir, unset_keys=("PRIME_TEAM_ID",))- frames: dict[str, str] = {}- try:- wait_for(session, "Log in with Prime Intellect")- time.sleep(0.4)- frames["welcome"] = capture_escape(session)- # The welcome action starts the flow: the login dialog mounts with- # the mock challenge URL, the Verification code block, and the- # armed paste prompt under it.- B.tmux_send(session, "Enter", enter=False)- wait_for(- session, "Complete the sign-in in your browser, or paste an API key below:"- )- time.sleep(0.4)- frames["url-block"] = capture_escape(session)- # The pasted key races the (pending) browser poll: whoami permits- # it, the two teams mount the account question.- B.tmux_send(session, "sk-mock-battery", enter=True)- wait_for(session, "Which account should Prime Agent use?")- time.sleep(0.4)- frames["team-question"] = capture_escape(session)- # The personal account answers the question; the default model- # applies behind the pane, then the picker mounts.- B.tmux_send(session, "Enter", enter=False)- wait_for(session, "Connect other providers, or continue.")- time.sleep(0.4)- frames["picker"] = capture_escape(session)- # Continue ends the step; the trace question ends the flow.- B.tmux_send(session, "Enter", enter=False)- wait_for(session, "Share agent traces")- time.sleep(0.4)- frames["trace-question"] = capture_escape(session)- finally:- B.tmux_kill(session)- side.mock.stop()- side.stop_daemon()- (out / name).mkdir(parents=True, exist_ok=True)- for state, frame in frames.items():- (out / name / f"{name}-{state}.txt").write_text(frame)- settings = side.agent_dir / "settings.json"- if settings.exists():- (out / name / "settings-after.json").write_text(settings.read_text())- return frames---STATES = ["welcome", "url-block", "team-question", "picker", "trace-question"]---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument(- "--rust-bin",- default=str(Path(__file__).parent.parent.parent / "target/release/prime-agent"),- )- parser.add_argument("--ts-bin", default="prime-agent")- parser.add_argument("--out", default=None)- args = parser.parse_args()-- import tempfile-- # Fail fast before any launch: a non-TS ts binary plays a Rust build as- # the "ts" side and reports false divergences.- ts_identity.assert_ts_side_is_the_ts_product(args.ts_bin, args.rust_bin)- # Fail fast on a stale rust build: a binary older than the checkout's- # newest product commit reports false frame divergences against the- # TS ground truth (batterylib's 20260920 lesson).- repo = Path(__file__).parent.parent.parent- stale = B.rust_binary_staleness(Path(args.rust_bin), repo)- if stale:- print(f"STALE RUST BINARY: {stale}", file=sys.stderr)- return 2-- prime_port, prime_thread, prime_server = start_prime_api()- base = Path(tempfile.mkdtemp(prefix="plframediff-"))- out = Path(args.out) if args.out else base / "captures"- out.mkdir(parents=True, exist_ok=True)-- try:- ts = run_side("ts", args.ts_bin, base, out, prime_port)- rust = run_side("rust", args.rust_bin, base, out, prime_port)- finally:- prime_server.shutdown()- prime_thread.join(timeout=5)-- failures = []- for state in STATES:- if state not in ts or state not in rust:- failures.append(f"{state}/missing")- continue- ts_text, ts_band = split_frame(normalize(ts[state]))- rust_text, rust_band = split_frame(normalize(rust[state]))- if ts_band != rust_band:- print(f"FAIL {state}: mark band differs")- (out / f"diff-band-{state}.txt").write_text(diff_lines(ts_band, rust_band))- failures.append(f"{state}/band")- if ts_text != rust_text:- print(f"FAIL {state}: text rows differ")- (out / f"diff-text-{state}.txt").write_text(diff_lines(ts_text, rust_text))- failures.append(f"{state}/text")- if not any(f"{state}/" in f for f in failures):- print(f"PASS {state}: frames match (styled text rows + static mark cells)")-- print(f"captures in {out}")- return 1 if failures else 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/battery/provider_error_probe.py b/scripts/battery/provider_error_probe.pydeleted file mode 100644index 35b743f3be..0000000000--- a/scripts/battery/provider_error_probe.py+++ /dev/null@@ -1,892 +0,0 @@-#!/usr/bin/env python3-"""Provider-error shape parity probe (#215 sibling divergences).--Drives one product binary (the installed TS `prime-agent`, or a Rust build)-against a local mock provider whose per-API endpoints return scripted-non-2xx responses, plus dead-port connection probes, and captures what the-binary surfaces for each provider-error class:-- - mistral `Mistral API error (N): <body>` (formatMistralError)- - anthropic classified `Provider rejected the request (...)` form- - codex `CodexApiError.message` verbatim (usage-limit friendly text)- - bedrock `{prefix}: <message>` (formatBedrockError)- - bedrock h2 the http2 transport surface the TS default (NodeHttp2Handler,- h2c prior knowledge) produces: working-path 400 parsing,- `Protocol error` against http1-only peers, mid-stream RST /- GOAWAY / TCP-reset texts, and the refused-connect stream-cancel- text (vs the AWS_BEDROCK_FORCE_HTTP1 http1 surface)- - codex ws the WebSocket transport surface (the provider's default- transport before the SSE fallback): handshake rejections,- close frames, abrupt socket death, invalid frames, and the- mid-stream (after message stream start) twins; the- provider_transport_failure diagnostic (error.name /- error.message / error.code / fallback details)- - connection the per-SDK connection texts ("Connection error.", "fetch- failed", "Unable to make request: ...")--Evidence per scenario: exit code, stdout/stderr, the persisted assistant-message's errorMessage, and the `provider_stream_failure` diagnostic-(error.name / kind / status / retryAfterMs). Run with:-- python3 provider_error_probe.py --side ts --binary prime-agent --out evidence/ts- python3 provider_error_probe.py --side rust --binary <rust-build>/prime-agent \- --out evidence/rust--Not part of the product; parity-harness only.-"""--from __future__ import annotations--import argparse-import base64-import hashlib-import itertools-import json-import os-import shutil-import socket-import struct-import subprocess-import sys-import tempfile-import threading-import time-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer-from pathlib import Path--import batterylib # the shared daemon-reap sweep (same dir)-import ts_identity # the shared PATH-binary identity guard (same dir)--SCRUB_ENV_PREFIXES = ("PRIME_AGENT", "PI_", "OPENAI_", "ANTHROPIC_", "MISTRAL_", "GOOGLE_", "AWS_")-SCRUB_ENV_KEYS = {"HOME", "XDG_CONFIG_HOME", "TMPDIR"}--MOCK_JWT_CLAIM = {"https://api.openai.com/auth": {"chatgpt_account_id": "mock-account"}}---def mock_codex_jwt() -> str:- """A JWT-shaped api key both sides accept: the TS reads the payload with- `atob` (standard base64) and the Rust with URL_SAFE_NO_PAD, so the payload- must encode to plain alphanumeric base64 with no padding."""- for spacer in range(1, 100):- payload = json.dumps(MOCK_JWT_CLAIM, separators=(", ", ": "), indent=spacer).encode()- if len(payload) % 3:- continue- encoded = base64.b64encode(payload).decode()- if encoded.isalnum():- return "x." + encoded + ".y"- raise RuntimeError("no alnum base64 payload found")---HTTP2_PREFACE = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"-H2_SETTINGS, H2_HEADERS, H2_RST_STREAM, H2_GOAWAY = 0x4, 0x1, 0x3, 0x7-H2_FLAG_ACK, H2_FLAG_END_STREAM, H2_FLAG_END_HEADERS = 0x1, 0x1, 0x4-H2_ERR_INTERNAL_ERROR, H2_ERR_PROTOCOL_ERROR = 0x2, 0x1---def h2_frame(ftype: int, flags: int, stream_id: int, payload: bytes = b"") -> bytes:- """One HTTP/2 wire frame (RFC 7540: 9-byte header, big-endian)."""- return len(payload).to_bytes(3, "big") + bytes((ftype, flags)) + stream_id.to_bytes(4, "big") + payload---def hpack_str(value: bytes) -> bytes:- """A length-prefixed HPACK string literal (no Huffman; probes only)."""- assert len(value) < 127, "probe headers are short"- return bytes((len(value),)) + value---def hpack_response_headers(status: int, content_type: str, request_id: str | None) -> bytes:- """A minimal HPACK block: indexed `:status` (static table), literal- `content-type` (indexed name 31), optional literal `x-amzn-requestid`."""- indexed_status = {200: 0x88, 204: 0x89, 206: 0x8A, 304: 0x8B, 400: 0x8D, 404: 0x8E, 500: 0x8F}- block = (- bytes([indexed_status[status]])- if status in indexed_status- else b"\x00" + hpack_str(b":status") + hpack_str(str(status).encode())- )- block += b"\x0f\x10" + hpack_str(content_type.encode()) # literal, indexed name 31- if request_id is not None:- block += b"\x00" + hpack_str(b"x-amzn-requestid") + hpack_str(request_id.encode())- return block---def h2_send_response(- sock: socket.socket,- stream_id: int,- status: int,- body: bytes,- end_stream: bool,- request_id: str | None = None,-) -> None:- """HEADERS + DATA for the scripted response (`application/json` answers)."""- headers = hpack_response_headers(status, "application/json", request_id)- sock.sendall(h2_frame(H2_HEADERS, H2_FLAG_END_HEADERS, stream_id, headers))- flags = H2_FLAG_END_STREAM if end_stream else 0- sock.sendall(h2_frame(0x0, flags, stream_id, body))---def h2_send_partial_eventstream(sock: socket.socket, stream_id: int) -> None:- """HEADERS(200, event-stream) + a truncated aws eventstream message prelude,- so both sides are inside the response body when the transport failure hits."""- headers = hpack_response_headers(200, "application/vnd.amazon.eventstream", "probe-request-id")- sock.sendall(h2_frame(H2_HEADERS, H2_FLAG_END_HEADERS, stream_id, headers))- # aws eventstream prelude prefix: total length, headers length; truncated- # before the prelude CRC so the body decode stays mid-message.- partial = b"\x00\x00\x00\x40\x00\x00\x00\x10\x00\x00\x00\x00\x00\x00\x00\x00"- sock.sendall(h2_frame(0x0, 0, stream_id, partial))---def recv_exact(sock: socket.socket, count: int) -> bytes:- out = bytearray()- while len(out) < count:- chunk = sock.recv(count - len(out))- if not chunk:- raise ConnectionError("client closed early")- out += chunk- return bytes(out)---def serve_h2_connection(conn: socket.socket, scenario_path: Path) -> None:- """One scripted HTTP/2 connection: the aws-sdk default bedrock transport- (NodeHttp2Handler, h2c prior knowledge) served by a raw-frame mock."""- conn.settimeout(30)- try:- if recv_exact(conn, len(HTTP2_PREFACE)) != HTTP2_PREFACE:- conn.close()- return- conn.sendall(h2_frame(H2_SETTINGS, 0, 0))- stream_id: int | None = None- while stream_id is None:- header = recv_exact(conn, 9)- length = int.from_bytes(header[:3], "big")- ftype, flags = header[3], header[4]- stream = int.from_bytes(header[5:9], "big") & 0x7FFFFFFF- if length:- recv_exact(conn, length)- if ftype == H2_SETTINGS and not flags & H2_FLAG_ACK:- conn.sendall(h2_frame(H2_SETTINGS, H2_FLAG_ACK, 0))- elif ftype == H2_HEADERS and flags & H2_FLAG_END_HEADERS and stream:- stream_id = stream-- scenario = json.loads(scenario_path.read_text())- action = scenario.get("h2_action", "respond_error")- if action == "respond_error":- body = scenario["body"].encode()- h2_send_response(- conn, stream_id, scenario["status"], body, end_stream=True, request_id="probe-request-id"- )- # Keep the connection open until the client finishes its request- # body and closes, so no RST races the response away.- conn.settimeout(10)- try:- while conn.recv(65536):- pass- except OSError:- pass- else:- h2_send_partial_eventstream(conn, stream_id)- time.sleep(0.2)- if action == "rststream":- conn.sendall(h2_frame(H2_RST_STREAM, 0, stream_id, H2_ERR_INTERNAL_ERROR.to_bytes(4, "big")))- time.sleep(0.2)- conn.close()- elif action == "goaway":- payload = stream_id.to_bytes(4, "big") + H2_ERR_PROTOCOL_ERROR.to_bytes(4, "big")- conn.sendall(h2_frame(H2_GOAWAY, 0, 0, payload))- time.sleep(0.2)- conn.close()- elif action == "tcp_rst":- conn.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))- conn.close()- elif action == "tcp_fin":- conn.close()- else:- raise ValueError(f"unknown h2 action {action}")- except (ConnectionError, OSError):- pass- finally:- try:- conn.close()- except OSError:- pass---class H2MockServer:- """Accept-loop front for `serve_h2_connection`; one scenario file per run."""-- def __init__(self, scenario_path: Path):- self.scenario_path = scenario_path- self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)- self.socket.bind(("127.0.0.1", 0))- self.socket.listen(8)- self.port = self.socket.getsockname()[1]- self.stop = threading.Event()- threading.Thread(target=self._loop, daemon=True).start()-- def _loop(self):- self.socket.settimeout(0.5)- while not self.stop.is_set():- try:- conn, _ = self.socket.accept()- except socket.timeout:- continue- except OSError:- return- threading.Thread(- target=serve_h2_connection, args=(conn, self.scenario_path), daemon=True- ).start()-- def shutdown(self):- self.stop.set()- try:- self.socket.close()- except OSError:- pass---# The WS-mode scenarios: a raw-socket WebSocket mock serves the codex-# provider's upgrade request with a scripted wire sequence (handshake-# rejection, close frames, abrupt socket death, invalid frames), and the-# same listener answers the SSE fallback POST with a successful completion-# stream, so the provider_transport_failure diagnostic rides the final-# assistant message (TS-binary verified shape). `ws_action` scripts the-# sequence; the `start_then_*` twins emit response.created first so the-# failure lands after the message stream started (no fallback).-WS_GUID = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"-WS_OP_TEXT, WS_OP_CLOSE = 0x1, 0x8--WS_SSE_OK_EVENTS = [- {"type": "response.created", "response": {"id": "resp_mock", "status": "in_progress"}},- {"type": "response.completed", "response": {"id": "resp_mock", "status": "completed", "output": [],- "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}}},-]---def ws_accept(key: str) -> str:- return base64.b64encode(hashlib.sha1(key.encode() + WS_GUID).digest()).decode()---def ws_frame(opcode: int, payload: bytes = b"") -> bytes:- """One unmasked server frame (probes use short payloads)."""- assert len(payload) < 126- return bytes([0x80 | opcode, len(payload)]) + payload---def serve_ws_connection(conn: socket.socket, scenario_path: Path) -> None:- """One scripted WebSocket connection (plus the SSE fallback answers)."""- conn.settimeout(30)- try:- first = conn.recv(65536)- if not first:- return- if first[0:1] == b"\x16":- # A TLS ClientHello at the plain mock: answer HTTP immediately so- # both binaries' TLS handshakes fail the same way (fast).- conn.sendall(b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n")- conn.close()- return- head = first- while b"\r\n\r\n" not in head:- chunk = conn.recv(65536)- if not chunk:- return- head += chunk- if not head.startswith(b"GET"):- # SSE fallback POST: a successful completion stream.- body = b"".join(- b"data: " + json.dumps(event).encode() + b"\n\n" for event in WS_SSE_OK_EVENTS- )- conn.sendall(- b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n"- b"Cache-Control: no-cache\r\nConnection: close\r\n"- b"Content-Length: " + str(len(body)).encode() + b"\r\n\r\n" + body- )- time.sleep(0.3)- return-- scenario = json.loads(scenario_path.read_text())- action = scenario.get("ws_action", "reject_401")- if action in ("reject_401", "reject_500"):- status = 401 if action == "reject_401" else 500- reason = "Unauthorized" if status == 401 else "Internal Server Error"- conn.sendall(- f"HTTP/1.1 {status} {reason}\r\nContent-Length: 0\r\n\r\n".encode()- )- conn.close()- return-- key = ""- for line in head.split(b"\r\n"):- if line.lower().startswith(b"sec-websocket-key:"):- key = line.split(b":", 1)[1].strip().decode()- accept = ws_accept(key)- if action == "bad_accept_key":- accept = "aW52YWxpZA=="- conn.sendall(- (- "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n"- f"Connection: Upgrade\r\nSec-WebSocket-Accept: {accept}\r\n\r\n"- ).encode()- )- time.sleep(0.05)-- def send_event(event: dict) -> None:- conn.sendall(ws_frame(WS_OP_TEXT, json.dumps(event).encode()))-- def close_frame(code: int | None, reason: bytes = b"") -> None:- if code is None:- conn.sendall(ws_frame(WS_OP_CLOSE))- else:- conn.sendall(ws_frame(WS_OP_CLOSE, code.to_bytes(2, "big") + reason))-- if action == "close_1011_reason":- close_frame(1011, b"mock server reason")- elif action == "close_1009_no_reason":- close_frame(1009)- elif action == "close_1000_done":- close_frame(1000, b"done")- elif action == "close_no_code":- close_frame(None)- elif action == "fin_no_close":- conn.close()- return- elif action == "tcp_rst":- conn.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))- conn.close()- return- elif action == "reserved_opcode":- conn.sendall(bytes([0x83, 0x00]))- elif action == "reserved_control_opcode":- conn.sendall(bytes([0x8B, 0x00]))- elif action == "rsv_bits":- conn.sendall(bytes([0xC1, 0x00]))- elif action == "invalid_json":- conn.sendall(ws_frame(WS_OP_TEXT, b"not json"))- elif action == "error_event_then_close":- send_event({"type": "error", "code": "server_error", "message": "mock in-stream error"})- close_frame(1011, b"closed after error")- elif action == "start_then_close_1011":- send_event(WS_SSE_OK_EVENTS[0])- time.sleep(0.05)- close_frame(1011, b"mock server reason")- elif action == "start_then_fin":- send_event(WS_SSE_OK_EVENTS[0])- time.sleep(0.05)- conn.close()- return- elif action == "start_then_invalid_json":- send_event(WS_SSE_OK_EVENTS[0])- time.sleep(0.05)- conn.sendall(ws_frame(WS_OP_TEXT, b"not json"))- else:- raise ValueError(f"unknown ws action {action}")- time.sleep(0.2)- conn.close()- except (ConnectionError, OSError):- pass- finally:- try:- conn.close()- except OSError:- pass---class WsMockServer:- """Accept-loop front for `serve_ws_connection`; one scenario file per run."""-- def __init__(self, scenario_path: Path):- self.scenario_path = scenario_path- self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)- self.socket.bind(("127.0.0.1", 0))- self.socket.listen(8)- self.port = self.socket.getsockname()[1]- self.stop = threading.Event()- threading.Thread(target=self._loop, daemon=True).start()-- def _loop(self):- self.socket.settimeout(0.5)- while not self.stop.is_set():- try:- conn, _ = self.socket.accept()- except socket.timeout:- continue- except OSError:- return- threading.Thread(- target=serve_ws_connection, args=(conn, self.scenario_path), daemon=True- ).start()-- def shutdown(self):- self.stop.set()- try:- self.socket.close()- except OSError:- pass---class ErrorMockHandler(BaseHTTPRequestHandler):- """Serves scripted non-2xx responses per API path; the scenario file- (rewritten by the probe between runs) selects status + body. The codex- provider's websocket handshake (GET) is answered the same way, so every ws- attempt fails and the provider falls back to SSE."""-- # Real servers answer the WS upgrade over HTTP/1.1 (the TS runtime checks- # the status code; transports that check the version first must see a 1.1- # response, matching the deployed ChatGPT backend).- protocol_version = "HTTP/1.1"-- def log_message(self, *args): # silence- pass-- def _respond(self):- try:- scenario = json.loads(Path(self.server.scenario_path).read_text()) # type: ignore[attr-defined]- except Exception:- scenario = {"status": 500, "body": "{}"}- # Request log for wire-level diffs, appended per request.- log = Path(self.server.scenario_path).with_suffix(".requests.log") # type: ignore[attr-defined]- with log.open("a") as handle:- handle.write(- json.dumps(- {"command": self.command, "path": self.path, "scenario": scenario["name"]}- )- + "\n"- )- body = scenario["body"].encode()- self.send_response(scenario["status"])- self.send_header("Content-Type", scenario.get("contentType", "application/json"))- self.send_header("Content-Length", str(len(body)))- self.end_headers()- self.wfile.write(body)-- def _drain_request(self):- """Read the full request body before answering: closing a socket- with unread request data sends a TCP RST that can race the response- body away from the client (the client then sees an empty body)."""- try:- length = int(self.headers.get("Content-Length") or 0)- except ValueError:- length = 0- remaining = length- while remaining > 0:- chunk = self.rfile.read(min(remaining, 65536))- if not chunk:- break- remaining -= len(chunk)-- def do_POST(self):- self._drain_request()- self._respond()-- def do_GET(self):- self._drain_request()- self._respond()---def start_error_mock(scenario_path: Path) -> tuple[ThreadingHTTPServer, int]:- server = ThreadingHTTPServer(("127.0.0.1", 0), ErrorMockHandler)- server.scenario_path = str(scenario_path) # type: ignore[attr-defined]- threading.Thread(target=server.serve_forever, daemon=True).start()- return server, server.server_address[1]---# One mock answer per scenario; the provider api decides which endpoint of-# the mock the request hits (mistral /v1/chat/completions, anthropic-# /v1/messages, codex /codex/responses, bedrock /model/<id>/converse-stream,-# openai-completions /v1/chat/completions).-HTTP_SCENARIOS = [- {- "name": "mistral_400_body",- "api": "mistral-conversations",- "status": 400,- "body": json.dumps({"message": "mock mistral bad request"}),- },- {- "name": "anthropic_400_body",- "api": "anthropic-messages",- "status": 400,- "body": json.dumps(- {- "type": "error",- "error": {"type": "invalid_request_error", "message": "mock anthropic bad request"},- }- ),- },- {- "name": "codex_429_usage_limit",- "api": "openai-codex-responses",- "status": 429,- "body": json.dumps(- {- "error": {- "code": "usage_limit_reached",- "message": "mock usage limit",- "plan_type": "free",- }- }- ),- },- {- "name": "codex_400_body",- "api": "openai-codex-responses",- "status": 400,- "body": json.dumps({"error": {"message": "mock codex bad request"}}),- },- {- "name": "bedrock_400_validation",- "api": "bedrock-converse-stream",- "status": 400,- "body": json.dumps(- {- "__type": "com.amazonaws.bedrock#ValidationException",- "message": "mock bedrock bad request",- }- ),- },- # The TS bedrock client speaks HTTP/2 by default; the Rust one HTTP/1.1.- # The `AWS_BEDROCK_FORCE_HTTP1` mode is the comparable surface (the TS- # request-handler override the product itself ships for proxies).- {- "name": "bedrock_400_validation_http1",- "api": "bedrock-converse-stream",- "force_http1": True,- "status": 400,- "body": json.dumps(- {- "__type": "com.amazonaws.bedrock#ValidationException",- "message": "mock bedrock bad request",- }- ),- },- {- "name": "google_400_body",- "api": "google-generative-ai",- "status": 400,- "body": json.dumps(- {- "error": {- "code": 400,- "message": "mock google bad request",- "status": "INVALID_ARGUMENT",- }- }- ),- },-]--# HTTP/2 transport scenarios: a raw-frame h2c mock serves the bedrock default-# mode (the TS NodeHttp2Handler path). `h2_action` scripts the response:-# `respond_error` completes a parsed non-2xx; the mid-stream actions fail the-# transport inside the response body (RST_STREAM, GOAWAY, TCP RST/FIN); the-# `_http1` twin drives the http1 (AWS_BEDROCK_FORCE_HTTP1) surface at the same-# h2-only peer.-H2_SCENARIOS = [- {- "name": "bedrock_h2_400_validation",- "api": "bedrock-converse-stream",- "transport": "h2",- "h2_action": "respond_error",- "status": 400,- "body": json.dumps(- {- "__type": "com.amazonaws.bedrock#ValidationException",- "message": "mock bedrock bad request",- }- ),- },- {- "name": "bedrock_h2_rststream_midstream",- "api": "bedrock-converse-stream",- "transport": "h2",- "h2_action": "rststream",- },- {- "name": "bedrock_h2_goaway_midstream",- "api": "bedrock-converse-stream",- "transport": "h2",- "h2_action": "goaway",- },- {- "name": "bedrock_h2_tcp_rst_midstream",- "api": "bedrock-converse-stream",- "transport": "h2",- "h2_action": "tcp_rst",- },- {- "name": "bedrock_h2_tcp_fin_midstream",- "api": "bedrock-converse-stream",- "transport": "h2",- "h2_action": "tcp_fin",- },- {- "name": "bedrock_h2_400_validation_http1",- "api": "bedrock-converse-stream",- "transport": "h2",- "h2_action": "respond_error",- "force_http1": True,- "status": 400,- "body": json.dumps(- {- "__type": "com.amazonaws.bedrock#ValidationException",- "message": "mock bedrock bad request",- }- ),- },-]--CONNECTION_SCENARIOS = [- {"name": "connection_anthropic-messages", "api": "anthropic-messages", "connection": True},- {"name": "connection_mistral-conversations", "api": "mistral-conversations", "connection": True},- {"name": "connection_openai-codex-responses", "api": "openai-codex-responses", "connection": True},- {"name": "connection_bedrock-converse-stream", "api": "bedrock-converse-stream", "connection": True},- {- "name": "connection_bedrock-converse-stream_http1",- "api": "bedrock-converse-stream",- "force_http1": True,- "connection": True,- },- {"name": "connection_google-generative-ai", "api": "google-generative-ai", "connection": True},- {"name": "connection_openai-completions", "api": "openai-completions", "connection": True},-]--# Codex WebSocket transport scenarios: the WS mock serves the scripted wire-# sequence at the upgrade request and a successful SSE fallback at the POST,-# so the transport failure's diagnostic rides the final assistant message.-# The `start_then_*` twins fail after response.created (after the message-# stream started): the error is thrown with no fallback, carrying both the-# transport and the stream-failure diagnostics.-WS_SCENARIOS = [- {"name": "ws_handshake_reject_401", "api": "openai-codex-responses", "ws_action": "reject_401"},- {"name": "ws_handshake_reject_500", "api": "openai-codex-responses", "ws_action": "reject_500"},- {"name": "ws_bad_accept_key", "api": "openai-codex-responses", "ws_action": "bad_accept_key"},- {"name": "ws_close_1011_reason", "api": "openai-codex-responses", "ws_action": "close_1011_reason"},- {"name": "ws_close_1009_no_reason", "api": "openai-codex-responses", "ws_action": "close_1009_no_reason"},- {"name": "ws_close_1000_done", "api": "openai-codex-responses", "ws_action": "close_1000_done"},- {"name": "ws_close_no_code", "api": "openai-codex-responses", "ws_action": "close_no_code"},- {"name": "ws_fin_no_close", "api": "openai-codex-responses", "ws_action": "fin_no_close"},- {"name": "ws_tcp_rst", "api": "openai-codex-responses", "ws_action": "tcp_rst"},- {"name": "ws_reserved_opcode", "api": "openai-codex-responses", "ws_action": "reserved_opcode"},- {"name": "ws_reserved_control_opcode", "api": "openai-codex-responses", "ws_action": "reserved_control_opcode"},- {"name": "ws_rsv_bits", "api": "openai-codex-responses", "ws_action": "rsv_bits"},- {"name": "ws_wss_to_plain", "api": "openai-codex-responses", "ws_action": "reject_401", "wss": True},- {"name": "ws_invalid_json", "api": "openai-codex-responses", "ws_action": "invalid_json"},- {"name": "ws_error_event_then_close", "api": "openai-codex-responses", "ws_action": "error_event_then_close"},- {"name": "ws_start_then_close_1011", "api": "openai-codex-responses", "ws_action": "start_then_close_1011"},- {"name": "ws_start_then_fin", "api": "openai-codex-responses", "ws_action": "start_then_fin"},- {"name": "ws_start_then_invalid_json", "api": "openai-codex-responses", "ws_action": "start_then_invalid_json"},-]--DEAD_PORT = 1 # nothing listens here: every connect() is refused instantly---def scrubbed_env(agent_dir: Path, tmpdir: Path, extra: dict | None = None) -> dict:- env = {- k: v- for k, v in os.environ.items()- if not k.startswith(SCRUB_ENV_PREFIXES) and k not in SCRUB_ENV_KEYS- }- env["PRIME_AGENT_CODING_AGENT_DIR"] = str(agent_dir)- env["TMPDIR"] = str(tmpdir)- if extra:- env.update(extra)- return env---def prepare_agent_dir(agent_dir: Path, api: str, base_url: str, api_key: str) -> str:- """models.json custom provider + retry-disabled settings; returns the- provider id. Retries stay off so each failure surfaces once,- deterministically."""- agent_dir.mkdir(parents=True, exist_ok=True)- provider_id = f"mock-{api}"- models = {- "providers": {- provider_id: {- "api": api,- "baseUrl": base_url,- "apiKey": api_key,- "models": [- {- "id": "mock-1",- "name": "Mock 1",- "api": api,- "baseUrl": base_url,- "contextWindow": 128000,- "maxTokens": 4096,- }- ],- }- }- }- (agent_dir / "models.json").write_text(json.dumps(models, indent=1))- (agent_dir / "settings.json").write_text(json.dumps({"retry": {"enabled": False}}, indent=1))- return provider_id---def run_scenario(- binary: str, agent_dir: Path, tmpdir: Path, provider_id: str, extra: dict | None = None-) -> dict:- tmpdir.mkdir(parents=True, exist_ok=True)- argv = [binary, "-p", "Reply with the word done.", "--provider", provider_id, "--model", "mock-1"]- start = time.time()- try:- proc = subprocess.run(- argv,- env=scrubbed_env(agent_dir, tmpdir, extra),- cwd=str(tmpdir),- input="",- capture_output=True,- text=True,- timeout=120,- )- return {- "exit_code": proc.returncode,- "stdout": proc.stdout,- "stderr": proc.stderr,- "duration_s": round(time.time() - start, 2),- "timeout": False,- }- except subprocess.TimeoutExpired as exc:- return {- "exit_code": None,- "stdout": exc.stdout or "",- "stderr": exc.stderr or "",- "duration_s": round(time.time() - start, 2),- "timeout": True,- }---def transport_diagnostic_shape(diagnostic: dict) -> dict:- """Comparable shape of one provider_transport_failure diagnostic: the- error surface (name/message/code) and the fallback details, minus- requestBytes (the assembled prompt differs per binary) and the- runtime-inherent timestamp/stack fields."""- details = dict(diagnostic.get("details") or {})- details.pop("requestBytes", None)- return {- "name": (diagnostic.get("error") or {}).get("name"),- "message": (diagnostic.get("error") or {}).get("message"),- "code": (diagnostic.get("error") or {}).get("code"),- "details": details,- }---def session_evidence(agent_dir: Path) -> dict:- """The persisted assistant messages (errorMessage, provider_stream_failure- diagnostic, and any provider_transport_failure diagnostics) from the- most recent session file."""- sessions = agent_dir / "sessions"- files = sorted(sessions.glob("*.jsonl"), key=lambda p: p.stat().st_mtime) if sessions.exists() else []- if not files:- return {"session_file": None}- result: dict = {"session_file": files[-1].name}- transport: list[dict] = []- for line in files[-1].read_text().splitlines():- try:- row = json.loads(line)- except json.JSONDecodeError:- continue- message = row.get("message") if isinstance(row, dict) else None- if not isinstance(message, dict) or message.get("role") != "assistant":- continue- diagnostics = message.get("diagnostics") or []- transport.extend(- transport_diagnostic_shape(d)- for d in diagnostics- if d.get("type") == "provider_transport_failure"- )- if message.get("errorMessage") is not None or message.get("stopReason") == "error":- failure = next((d for d in diagnostics if d.get("type") == "provider_stream_failure"), None)- result["errorMessage"] = message.get("errorMessage")- result["stopReason"] = message.get("stopReason")- if failure:- result["diagnostic"] = {- "name": (failure.get("error") or {}).get("name"),- "kind": (failure.get("details") or {}).get("kind"),- "status": (failure.get("details") or {}).get("status"),- "providerErrorType": (failure.get("details") or {}).get("providerErrorType"),- "retryAfterMs": (failure.get("details") or {}).get("retryAfterMs"),- }- if transport:- result["transportDiagnostics"] = transport- return result---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--side", required=True, choices=("ts", "rust"))- parser.add_argument("--binary", required=True)- parser.add_argument("--out", required=True)- args = parser.parse_args()-- out = Path(args.out)- if args.side == "ts":- # Fail fast: a non-TS ts binary (e.g. a Rust build symlinked onto- # PATH as `prime-agent`) would capture the wrong product's errors.- ts_identity.assert_ts_side_is_the_ts_product(args.binary)- if out.exists():- shutil.rmtree(out)- out.mkdir(parents=True, exist_ok=True)- root = Path(tempfile.mkdtemp(prefix=f"provider-errors-{args.side}-"))- scenario_path = root / "scenario.json"-- server, port = start_error_mock(scenario_path)- mock_url = f"http://127.0.0.1:{port}"- h2_server = H2MockServer(scenario_path)- h2_url = f"http://127.0.0.1:{h2_server.port}"- ws_server = WsMockServer(scenario_path)- ws_url = f"http://127.0.0.1:{ws_server.port}"- jwt = mock_codex_jwt()-- scenarios: list[dict] = (- list(HTTP_SCENARIOS) + H2_SCENARIOS + WS_SCENARIOS + CONNECTION_SCENARIOS- )-- evidence = []- for scenario in scenarios:- api = scenario["api"]- if scenario.get("connection"):- base_url = f"http://127.0.0.1:{DEAD_PORT}"- elif scenario.get("transport") == "h2":- base_url = h2_url- elif "ws_action" in scenario:- base_url = ws_url- else:- base_url = mock_url- if scenario.get("wss"):- base_url = "https://" + base_url.split("://", 1)[1]- if "status" in scenario or "h2_action" in scenario or "ws_action" in scenario:- scenario_path.write_text(json.dumps(scenario))- api_key = jwt if api == "openai-codex-responses" else "mock-key"- extra = {}- if api == "bedrock-converse-stream":- extra["AWS_BEDROCK_SKIP_AUTH"] = "1"- extra["AWS_REGION"] = "us-east-1"- if scenario.get("force_http1"):- extra["AWS_BEDROCK_FORCE_HTTP1"] = "1"-- agent_dir = root / scenario["name"] / "agent"- provider_id = prepare_agent_dir(agent_dir, api, base_url, api_key)- run = run_scenario(args.binary, agent_dir, root / scenario["name"] / "tmp", provider_id, extra)- # The TS print run spawns a daemon (plus its supervisor) that- # outlives the CLI; sweep this scenario's tree so a long probe- # never stacks daemons, and an exit never leaks one onto a- # deleted socket (#223).- batterylib.reap_daemons(- needles=[str(root / scenario["name"])], cwd_roots=[str(root / scenario["name"])]- )- entry = {"scenario": scenario["name"], "api": api, "run": run}- entry.update(session_evidence(agent_dir))- evidence.append(entry)- print(json.dumps(entry, indent=1))- (out / f"{scenario['name']}.json").write_text(json.dumps(entry, indent=1))-- (out / "evidence.json").write_text(json.dumps(evidence, indent=1))- server.shutdown()- h2_server.shutdown()- ws_server.shutdown()- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/battery/reap_check.py b/scripts/battery/reap_check.pydeleted file mode 100755index 5929983144..0000000000--- a/scripts/battery/reap_check.py+++ /dev/null@@ -1,104 +0,0 @@-#!/usr/bin/env python3-"""Post-run daemon-leak checker (the #221 verification pattern).--Wraps a harness run, waits `--wait` seconds after it exits, then asserts-that no NEW prime-agent/pa-daemon process (a daemon, its supervisor, or a-worker) survived the run. The process table is snapshotted before the-run: daemons that already lived on the box (other lanes, interactive-sessions, this harness's own agent) are ignored; only the delta fails.-- python3 scripts/battery/reap_check.py [--wait 30] [--label NAME] -- <command...>--Exit 0 = every daemon the run spawned is gone; exit 1 = leaked-processes (their pid + argv printed as evidence). The wait covers the-respawn window: a killed main daemon is relaunched by its supervisor-within ~1.5s, so a 30s quiet window means the whole tree is down.--Not part of the product; verifier only.-"""--from __future__ import annotations--import argparse-import os-import subprocess-import sys-import time-from pathlib import Path--#: Executable basenames that mark a process as one of the products'-#: processes. Matching argv[0] (never "any argv part"): a substring match-#: would flag unrelated processes that merely quote the product's name-#: (observed: another agent's bash gate wrapper embedding the-#: "prime-agent-complete:" marker string).-PRODUCT_BASENAMES = ("prime-agent", "pa-daemon")---def snapshot() -> dict[int, str]:- """Live product processes: {pid: argv string}."""- out: dict[int, str] = {}- for proc_dir in Path("/proc").iterdir():- if not proc_dir.name.isdigit():- continue- pid = int(proc_dir.name)- if pid == os.getpid():- continue- try:- argv = [- part.decode(errors="replace")- for part in (proc_dir / "cmdline").read_bytes().split(b"\0")- if part- ]- except OSError:- continue- if argv and os.path.basename(argv[0]) in PRODUCT_BASENAMES:- out[pid] = " ".join(argv)- return out---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--wait", type=float, default=30.0)- parser.add_argument("--label", default=None)- parser.add_argument(- "--needle",- default=None,- help="count only survivors whose argv references this path (for "- "harnesses with known tempdir prefixes, so concurrent daemons "- "other agents spawn on a shared box are not misattributed)",- )- parser.add_argument("command", nargs=argparse.REMAINDER)- args = parser.parse_args()- if args.command and args.command[0] == "--":- args.command = args.command[1:]- if not args.command:- parser.error("no command given (use `-- <command...>`)")-- label = args.label or " ".join(args.command)- before = snapshot()- # Popen (not run): the direct child's pid must be excludable from the- # survivor set when the checked command itself names a product binary- # in its own argv (e.g. provider_error_probe --binary .../prime-agent).- child = subprocess.Popen(args.command)- exit_code = child.wait()- deadline = time.time() + args.wait- while time.time() < deadline:- time.sleep(min(1.0, deadline - time.time()))- after = snapshot()- survivors = {pid: argv for pid, argv in after.items() if pid not in before and pid != child.pid}- if args.needle:- survivors = {pid: argv for pid, argv in survivors.items() if args.needle in argv}- if survivors:- print(f"REAP FAIL [{label}]: {len(survivors)} product process(es) survived the run")- for pid, argv in sorted(survivors.items()):- print(f" pid {pid}: {argv}")- return 1- if exit_code != 0:- print(f"REAP OK [{label}]: no leaked daemons (harness itself exited {exit_code})")- return exit_code- print(f"REAP OK [{label}]: zero product processes remain {args.wait:g}s post-exit")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/battery/run_battery.py b/scripts/battery/run_battery.pydeleted file mode 100644index c75cdf12b9..0000000000--- a/scripts/battery/run_battery.py+++ /dev/null@@ -1,6236 +0,0 @@-#!/usr/bin/env python3-"""Standing live A/B parity battery: run the TS binary (ground truth) and the-Rust binary side by side over the same user flows, against the same-deterministic mock provider, and capture evidence + a gap report.--One-command re-run (from the repo root):-- python3 scripts/battery/run_battery.py--Options:- --flows f1,f2 comma list to run (default: all)- --ts-bin PATH TS binary (default: prime-agent on PATH)- --rust-bin PATH Rust binary (default: target/release/prime-agent)- --runs-root PATH evidence root (default: scripts/battery/runs)--Each run writes scripts/battery/runs/<UTC stamp>/ with:- ts/, rust/ per-side evidence per flow (frames, wire logs, copies)- report.md automated comparison table + findings- findings.json machine-readable findings--Isolation: every side gets its own agent dir, TMPDIR, daemon socket, and mock-provider port. The ambient daemon (this session's own host) is never touched:-all spawned daemons live on battery-specific sockets, and cleanup kills only-processes whose environment references the run directory.-"""--from __future__ import annotations--import argparse-import datetime-import re-import json-import os-import re-import shutil-import signal-import subprocess-import sys-import time-from pathlib import Path--sys.path.insert(0, str(Path(__file__).parent))-import batterylib as B # noqa: E402-import perf as P # noqa: E402-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)-from mock_provider import user_message_text # noqa: E402--# The scripted summaries of the f7 second-compaction differential (the-# durable rows are scoped to them; other f7 sessions compact too).-ITERATIVE_SUMMARIES = ("the first compaction summary", "the second compaction summary")--NL = chr(10)--ALL_FLOWS = ["f1_launch", "f2_prompt", "f3_tool", "f4_commands", "f5_side_questions", "f6_attach", "f7_compaction", "f8_resume", "f9_agents_view", "f10_perf", "f11_provider_failure", "f12_scroll", "f13_ctrlc_exit", "f14_compact", "f15_a2a", "f16_refine", "f17_slash_model", "f18_goal_autonomous", "f19_heartbeat", "f20_subagents", "f21_worker_recovery", "f22_provider_failover", "f23_keybindings", "f24_prompt_stash"]--# Real-surface flows (f14-f21): each drives one product surface end to end-# (the daemon session + the attached interactive TUI), captures the frame-# at the key moment, and byte-diffs TS vs Rust after normalization. A flow-# whose diff fails on a surface known to be missing in the Rust build-# records its finding with the owning fix lane: the report lists it as-# EXPECTED-FAIL (the evidence the lane needs), not an unexplained gap.-FLOW_LANES = {- "f14_compact": "compact-fb-2",- "f15_a2a": "decorations-3",- "f16_refine": "decorations-3",- "f17_slash_model": "model-picker-2",- "f18_goal_autonomous": "goal-autonomous",- "f19_heartbeat": "heartbeat-tui",- "f21_worker_recovery": "worker-recovery",- "f23_keybindings": "keybindings",- "f24_prompt_stash": "prompt-stash",-}--# Per-step lane overrides: a flow whose steps cross several surfaces can-# own one gap per step (the flow-level tag would mis-own the rest).-# f20's keyboard-path steps (proven 2026-09-21, run 20260921T201206Z):-# the reattached transcript's rebuilt python cell renders TS's `waiting-# for code` phase (TS's rebuild never replays the streamed code partials,-# so the rebuilt cell is codeless; Rust keeps the code in the rebuilt card-# and renders the settled row) — the tool-card replay surface; the child-# transcript's opening row is TS's `◆ Agent message received · from-# parent <name>` (the child session file persists the [task from parent]-# message with the agent_message custom type; Rust's child admission-# writes it as a plain user message) — the child-admission persistence-# surface. The keyboard path itself (focus, open, drill-in, back) passes-# on both sides.-FLOW_STEP_LANES = {- ("f20_subagents", "reattached"): "ipython-replay",- ("f20_subagents", "panel-focused"): "ipython-replay",- ("f20_subagents", "child-transcript"): "child-task-message",-}--# Heavy flows: opt-in by name (`--flows f12_scale_resume`) plus-# PA_BATTERY_HEAVY=1; they measure transcript-scale resume, not parity, and-# would inflate a normal battery run's wall time.-HEAVY_FLOWS = ["f12_scale_resume"]--# PERF row thresholds, measured on this box by scripts/battery/perf.py:-# the invariant is that the Rust binary is never materially slower than-# the TS binary on cold startup or keystroke-to-render latency.-PERF_STARTUP_MAX_RATIO = 1.5-PERF_TYPING_MAX_RATIO = 1.5-PERF_RUNS = 3--# f12 thresholds: a transcript-scale interactive resume (snapshot ingest +-# first full layout) must be scale-ready — seconds, not minutes. The TS-# binary resumes the same corpus in ~3.4s; the Rust gate is an absolute cap-# (the box's background load makes tight differential ratios noisy) plus a-# regression ratio against the TS side measured in the same run.-SCALE_RESUME_MAX_READY_S = 30.0-SCALE_RESUME_MAX_RATIO = 2.0--HELLO_TEXT = "battery hello from mock"-# The scripted Anthropic-style overflow error (B-31): an error-pattern text-# both overflow classifiers detect, so the compact-and-retry arm fires.-OVERFLOW_ERROR_TEXT = "prompt is too long: 213462 tokens > 200000 maximum"-# The dashboard status-line model the TS daemon asks after each turn (B-7).-STATUSLINE_MODEL_ID = "qwen/qwen3-30b-a3b-instruct-2507"-AGENT_STATUS_SYSTEM_PROMPT_PREFIX = "You generate a status line for an AI coding agent dashboard."---def is_statusline_request(req) -> bool:- """A dashboard status-line request: the small model plus the fixed system prompt."""- body = req.get("body") or {}- messages = body.get("messages", [])- system = ""- if messages and isinstance(messages[0].get("content"), str):- system = messages[0]["content"]- return (- body.get("model") == STATUSLINE_MODEL_ID- and system.startswith(AGENT_STATUS_SYSTEM_PROMPT_PREFIX)- )---class Battery:- def __init__(self, runs_root: Path, ts_bin: str, rust_bin: str, flows: list[str]):- self.stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")- self.run_dir = runs_root / self.stamp- self.run_dir.mkdir(parents=True)- self.flows = flows- self.ts_bin = ts_bin- self.rust_bin = rust_bin- self.findings: list[dict] = []- self.sides: dict[str, B.Side] = {}- self.runid = "vbat" + self.stamp-- # -- setup / teardown ------------------------------------------------------ def make_side(self, name: str, binary: str) -> B.Side:- root = self.run_dir / name- root.mkdir(parents=True, exist_ok=True)- agent = root / "agent"- work = root / "work"- work.mkdir(parents=True, exist_ok=True)- if agent.exists():- shutil.rmtree(agent)- agent.mkdir(parents=True)- mock = B.MockProvider(root, [])- mock.set_responses([{"text": HELLO_TEXT}])- mock.start()- # Short TMPDIR: worker sockets live under TMPDIR and must stay under- # the 107-char AF_UNIX path limit (the run dir is too deep).- tmpdir = Path("/tmp") / f"{self.runid}-{name}"- if tmpdir.exists():- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- side = B.Side(- name=name,- binary=binary,- root=root,- agent_dir=agent,- work_dir=work,- daemon_socket=root / "daemon.sock",- mock=mock,- )- side.env = B.scrubbed_env(agent, tmpdir)- # The Rust binary resolves the kernel runtime sidecar through- # PI_PACKAGE_DIR: a packaged layout ships it next to the exe, but a- # cargo/sandbox build bakes the BUILD machine's source-checkout path- # in, which does not exist when the binary runs on this box (run- # 20260919T002527Z: every kernel ipython cell died with "kernel- # startup failed ... uv pip install prime-agent-runtime ... exit- # code 1"). Point it at this checkout, which ships- # prime-agent-runtime/ (the same layout the packaged product uses).- if name == "rust":- side.env["PI_PACKAGE_DIR"] = str(Path(__file__).resolve().parents[2])- # Point both products at the mock through a provider whose API-key- # resolution both support: both read the models.json apiKey (the- # env key stays as the fallback both products share).- side.env["PRIME_API_KEY"] = "sk-battery"- side.write_models_json()- self.sides[name] = side- return side-- def record(self, flow: str, category: str, summary: str, evidence="", gap: bool = True, lane: str | None = None) -> None:- evidence = self.json_evidence(evidence)- self.findings.append(- {- "flow": flow,- "category": category,- "gap": gap,- "summary": summary,- "evidence": evidence,- "expectedFail": lane,- }- )-- def json_evidence(self, value):- """Serialize Path values (and containers holding them) so- findings.json stays JSON-serializable: a bare Path evidence row- and a list-of-Paths row (the f7 overflow projections) both record- run-relative strings."""- if isinstance(value, Path):- try:- return str(value.relative_to(self.run_dir))- except ValueError:- return str(value)- if isinstance(value, list):- return [self.json_evidence(item) for item in value]- if isinstance(value, dict):- return {key: self.json_evidence(item) for key, item in value.items()}- return value-- def new_mock_requests(self, side: B.Side, mark: int) -> list[dict]:- return side.mock.requests()[mark:]-- def copy_sessions(self, side: B.Side, flow: str) -> None:- dst = side.root / flow / "sessions"- if dst.exists():- shutil.rmtree(dst)- src = side.sessions_dir()- if src.exists():- shutil.copytree(src, dst)-- def stop(self) -> None:- """Shut down every battery-owned daemon and process."""- for side in self.sides.values():- # Graceful wire shutdown, best effort.- try:- wire = B.Wire(side.daemon_socket)- wire.send_command("sd", {"type": "shutdown"})- wire.close()- time.sleep(2)- except Exception:- pass- # Kill anything still referencing the run dir (own processes only).- self.kill_run_processes()- for side in self.sides.values():- side.mock.stop()- if side.daemon_proc and side.daemon_proc.poll() is None:- side.daemon_proc.terminate()- subprocess.run(["tmux", "ls", "-F", "#{session_name}"], capture_output=True, text=True)-- def kill_run_processes(self) -> None:- run_path = str(self.run_dir)- for proc_dir in Path("/proc").iterdir():- if not proc_dir.name.isdigit():- continue- pid = int(proc_dir.name)- if pid == 1 or pid == os.getpid():- continue- try:- environ = (proc_dir / "environ").read_bytes().decode(errors="replace")- cmdline = (proc_dir / "cmdline").read_bytes().decode(errors="replace")- except (OSError, PermissionError):- continue- if run_path in environ or run_path in cmdline:- try:- os.kill(pid, 15)- except (ProcessLookupError, PermissionError):- pass- time.sleep(1)-- def kill_tmux_sessions(self) -> None:- out = subprocess.run(- ["tmux", "ls", "-F", "#{session_name}"], capture_output=True, text=True- ).stdout- for name in out.split():- if name.startswith(self.runid):- B.tmux_kill(name)-- # -- flows ----------------------------------------------------------------- def f1_launch(self) -> None:- """Fresh install state: splash, first-run notice, first prompt+reply."""- noticed: dict[str, bool] = {}- for side in (self.sides["ts"], self.sides["rust"]):- flow = "f1_launch"- session = f"{self.runid}-f1-{side.name}"- argv = P.launch_argv(side, side.daemon_socket)- B.tmux_launch(session, argv, side.env, side.work_dir)- # The TS splash animation swallows keystrokes, and a fresh install- # first shows a trace-sharing notice: wait for the notice (up to- # 30s), answer it if present, then wait for the settled main- # screen (two identical frames) before typing.- frame = ""- deadline = time.time() + 30- while time.time() < deadline:- frame = B.tmux_capture(session)- if "Share agent traces" in frame:- break- time.sleep(1.0)- side.evidence(flow, "01-launch.txt", frame)- noticed[side.name] = "Share agent traces" in frame- if noticed[side.name]:- # B-2: the notice is answerable (Down + Enter = Not now) and- # the pane settles into the main screen afterwards.- B.tmux_send(session, "Down")- time.sleep(0.5)- B.tmux_send(session, "Enter")- time.sleep(2.0)- side.evidence(flow, "02-notice-answered.txt", B.tmux_capture(session))- elif "prime agent" in frame.lower() or "manage" in frame:- side.evidence(flow, "02-no-notice.txt", frame)- else:- self.record(flow, "visual", f"{side.name} launch frame shows no splash/welcome text", gap=True)- # Wait for a settled main screen before sending the prompt.- stable = False- deadline = time.time() + 30- while time.time() < deadline and not stable:- first = B.tmux_capture(session)- time.sleep(2.0)- second = B.tmux_capture(session)- stable = first == second and ("manage" in first or ">" in first)- if not stable:- self.record(flow, "behavior", f"{side.name}: TUI never reached a stable main screen within 30s", gap=True)- # Send the first prompt.- mark = len(side.mock.requests())- B.tmux_send(session, "hi")- frame2 = B.tmux_wait_text(session, HELLO_TEXT, timeout=90)- side.evidence(flow, "02-after-first-prompt.txt", frame2)- if HELLO_TEXT not in frame2:- self.record(- flow,- "behavior",- f"{side.name}: first interactive prompt did not reach the mock provider (mock requests: {len(self.new_mock_requests(side, mark))})",- evidence=side.root / flow / "02-after-first-prompt.txt",- )- else:- self.record(flow, "behavior", f"{side.name}: first interactive prompt answered by the mock provider", gap=False)- # B-1: the explicit --provider/--model flags must be authoritative- # end-to-end; the first request the mock sees must be the flagged- # model, not a fallback.- requests = self.new_mock_requests(side, mark)- side.evidence_json(flow, "first-prompt-mock-requests.json", requests)- request_models = [- request["body"].get("model") for request in requests if request.get("body")- ]- if request_models and all(model == "mock-1" for model in request_models):- self.record(- flow,- "protocol",- f"{side.name}: interactive model flags are authoritative (request model: {request_models[0]})",- gap=False,- )- else:- self.record(- flow,- "protocol",- f"{side.name}: interactive model flags did not reach the provider request (models seen: {request_models})",- evidence=side.root / flow / "first-prompt-mock-requests.json",- )- B.tmux_kill(session)- # B-2 cross-side verdict: the first-run surface (splash + trace- # notice) is parity when both products show and answer it.- flow = "f1_launch"- if noticed.get("ts") and noticed.get("rust"):- self.record(- flow,- "visual",- "first-run splash + trace-sharing notice rendered and answerable on both sides (fresh install)",- gap=False,- )- elif noticed.get("ts") and not noticed.get("rust"):- self.record(- flow,- "visual",- "ts shows a first-run notice on fresh install: splash + 'Share agent traces with Prime Intellect?' dialog (Share / Not now, /traces hint)",- evidence=self.sides["ts"].root / flow / "01-launch.txt",- )- self.record(- flow,- "visual",- "Rust launches straight into the TUI: no splash ASCII art and no first-run trace-sharing notice",- evidence=self.sides["rust"].root / flow / "01-launch.txt",- )- elif noticed.get("rust") and not noticed.get("ts"):- self.record(- flow,- "visual",- "rust shows the first-run notice but ts does not (ts agent dir already onboarded?)",- evidence=self.sides["ts"].root / flow / "01-launch.txt",- )-- def f2_prompt(self) -> None:- """Headless print mode: one prompt, one model response, protocol capture."""- flow = "f2_prompt"- recs = {}- for side in (self.sides["ts"], self.sides["rust"]):- mark = len(side.mock.requests())- argv = [- side.binary,- "-p",- "--daemon-socket",- str(side.daemon_socket),- "--provider",- "prime-inference",- "--model",- "mock-1",- "--offline",- "Say hello",- ]- rec = B.run_cmd(argv, side.env, side.work_dir, timeout=240)- recs[side.name] = rec- side.evidence_json(flow, "cmd.json", rec)- reqs = self.new_mock_requests(side, mark)- side.evidence_json(flow, "mock-requests.json", reqs)- self.copy_sessions(side, flow)- if rec["timeout"] or rec["exit_code"] != 0:- self.record(- flow,- "behavior",- f"{side.name}: print-mode run failed (exit={rec['exit_code']}, timeout={rec['timeout']}); stderr: {rec['stderr'][:200]}",- )- # stdout comparison- ts_out = recs["ts"]["stdout"].strip()- rs_out = recs["rust"]["stdout"].strip()- if ts_out == rs_out and ts_out:- self.record(flow, "behavior", f"print-mode stdout identical: {ts_out!r}", gap=False)- else:- self.record(- flow,- "behavior",- f"print-mode stdout differs: ts={ts_out!r} vs rust={rs_out!r}",- )- self.wire_request_diff(flow, "mock-requests.json")-- def wire_request_diff(self, flow: str, reqfile: str) -> None:- """Diff the mock request bodies between the two sides."""- ts_reqs = json.loads((self.sides["ts"].root / flow / reqfile).read_text())- rs_reqs = json.loads((self.sides["rust"].root / flow / reqfile).read_text())- if not ts_reqs or not rs_reqs:- self.record(flow, "protocol", f"missing mock requests: ts={len(ts_reqs)} rust={len(rs_reqs)}")- return- def session_request(reqs):- for req in reqs:- if req["body"].get("model") == "mock-1":- return req["body"]- return reqs[0]["body"] if reqs else None-- ts_body = session_request(ts_reqs)- rs_body = session_request(rs_reqs)- if ts_body is None or rs_body is None:- self.record(flow, "protocol", f"no session request captured: ts={len(ts_reqs)} rust={len(rs_reqs)}")- return- # The post-turn status-line request (B-7) is checked separately in- # f5 with a settled wait; a timing-sensitive capture here must not- # flap, so exclude it from the extra-request diff.- def extra_models(reqs):- return [- r["body"].get("model")- for r in reqs- if r["body"].get("model") not in ("mock-1", STATUSLINE_MODEL_ID)- ]-- ts_extra = extra_models(ts_reqs)- rs_extra = extra_models(rs_reqs)- if ts_extra != rs_extra:- self.record(- flow,- "protocol",- f"extra provider requests beyond the session turn differ: ts={ts_extra} rust={rs_extra}",- )- ts_keys = set(ts_body)- rs_keys = set(rs_body)- if ts_keys != rs_keys:- self.record(- flow,- "protocol",- f"request body keys differ: ts-only={sorted(ts_keys - rs_keys)} rust-only={sorted(rs_keys - ts_keys)}",- evidence=self.run_dir / "protocol-request-diff.txt",- )- # tools- ts_tools = [t.get("function", {}).get("name") for t in ts_body.get("tools", [])]- rs_tools = [t.get("function", {}).get("name") for t in rs_body.get("tools", [])]- if ts_tools != rs_tools:- self.record(- flow,- "protocol",- f"model tool surface differs: ts={ts_tools} rust={rs_tools}",- )- # messages- ts_msgs = ts_body.get("messages", [])- rs_msgs = rs_body.get("messages", [])- ts_roles = [m.get("role") for m in ts_msgs]- rs_roles = [m.get("role") for m in rs_msgs]- if ts_roles != rs_roles:- self.record(flow, "protocol", f"message roles differ: ts={ts_roles} rust={rs_roles}")- # harness digest- def has_digest(msgs):- for m in msgs:- content = m.get("content")- if isinstance(content, str) and "[harness-digest]" in content:- return True- if isinstance(content, list):- for block in content:- if isinstance(block, dict) and "[harness-digest]" in str(block.get("text", "")):- return True- return False- if has_digest(ts_msgs) != has_digest(rs_msgs):- self.record(- flow,- "protocol",- f"harness-digest user message: ts={has_digest(ts_msgs)} rust={has_digest(rs_msgs)}",- )- # system prompt comparison. TS-prompt parity is SUPERSEDED for the- # system prompt (roadmap item 3: the Rust product adopts the layered- # prompt redesign - cached static layers + dynamic tail - as its- # native prompt). The battery now checks the Rust prompt against the- # layered shape instead of the TS text, and keeps the raw TS prompt- # in the diff file as reference evidence.- ts_sys = [m["content"] for m in ts_msgs if m.get("role") == "system"]- rs_sys = [m["content"] for m in rs_msgs if m.get("role") == "system"]- if rs_sys:- diff_path = self.run_dir / "protocol-request-diff.txt"- with open(diff_path, "a") as f:- f.write(f"=== {flow} system prompt ==={NL}")- if ts_sys:- f.write("--- TS ---" + NL)- f.write(ts_sys[0] + NL)- f.write("--- RUST ---" + NL)- f.write(rs_sys[0] + NL)- shape = self.layered_prompt_shape(rs_sys[0])- if shape:- self.record(- flow,- "protocol",- f"system prompt: rust layered redesign (cached static layers + dynamic tail; TS-prompt parity superseded; raw prompts in protocol-request-diff.txt)",- gap=False,- )- else:- self.record(- flow,- "protocol",- f"system prompt: rust prompt does not match the layered shape (expected '# prime-agent harness' static core, mandatory-rules layer, skills inventory, dynamic tail; raw prompts in protocol-request-diff.txt)",- evidence=diff_path,- )- elif ts_sys and not rs_sys:- self.record(flow, "protocol", "system prompt: rust request has no system message but ts does")-- def layered_prompt_shape(self, text: str) -> bool:- """Whether the Rust system prompt matches the layered redesign:- the static core layer first, the mandatory usage layer, the- opinionated layer, then the dynamic tail (packages, skills- inventory, environment). Marker-based, so layer text edits do not- flap the battery; content-level pinning lives in the pa-core golden- snapshot test."""- markers = [- "# prime-agent harness",- "The following are mandatory rules",- "The following guidelines to agents have been shown",- "Pre-installed Python packages:",- "<available_skills>",- "Working directory:",- "Recursive agent depth: 0 (root)",- ]- at = -1- for marker in markers:- found = text.find(marker, at + 1)- if found == -1:- return False- at = found- return True-- def f3_tool(self) -> None:- """Tool call turn: deterministic ipython tool call in both products."""- flow = "f3_tool"- tool_responses = [- {"toolCall": {"name": "ipython", "arguments": {"code": "print('battery-tool-ok')"}}},- {"text": "tool turn done"},- ]- recs = {}- for side in (self.sides["ts"], self.sides["rust"]):- side.mock.set_responses(list(tool_responses))- mark = len(side.mock.requests())- argv = [- side.binary,- "-p",- "--daemon-socket",- str(side.daemon_socket),- "--provider",- "prime-inference",- "--model",- "mock-1",- "--offline",- "Run the tool",- ]- rec = B.run_cmd(argv, side.env, side.work_dir, timeout=600)- recs[side.name] = rec- side.evidence_json(flow, "cmd.json", rec)- side.evidence_json(flow, "mock-requests.json", self.new_mock_requests(side, mark))- self.copy_sessions(side, flow)- sessions = side.root / flow / "sessions"- body = ""- for sf in sorted(sessions.glob("*.jsonl")) if sessions.exists() else []:- body += sf.read_text()- side.evidence(flow, "session-entries.txt", body)- tool_ok = "battery-tool-ok" in body or "battery-tool-ok" in rec["stdout"]- if tool_ok:- self.record(flow, "behavior", f"{side.name}: ipython tool call executed and output captured", gap=False)- else:- self.record(- flow,- "behavior",- f"{side.name}: tool-call turn did not produce the tool output (stdout tail: {rec['stdout'][-200:]!r})",- )- # session entry types- self.session_shape_diff(flow)-- def session_shape_diff(self, flow: str) -> None:- counts = {}- for name in ("ts", "rust"):- side = self.sides[name]- types = {}- d = side.root / flow / "sessions"- for sf in sorted(d.glob("*.jsonl")) if d.exists() else []:- for line in sf.read_text().splitlines():- try:- entry = json.loads(line)- except json.JSONDecodeError:- continue- t = entry.get("type", "?")- types[t] = types.get(t, 0) + 1- counts[name] = types- (self.run_dir / f"{flow}-session-shapes.json").write_text(json.dumps(counts, indent=1))- ts_only = set(counts["ts"]) - set(counts["rust"])- rs_only = set(counts["rust"]) - set(counts["ts"])- if ts_only or rs_only:- self.record(- flow,- "protocol",- f"session entry types differ: ts-only={sorted(ts_only)} rust-only={sorted(rs_only)}; full counts in {flow}-session-shapes.json",- evidence=self.run_dir / f"{flow}-session-shapes.json",- )- else:- self.record(flow, "protocol", f"session entry type sets match ({sorted(counts['ts'])})", gap=False)-- def f4_commands(self) -> None:- """Slash command surface: the '/' menu and one benign command run."""- flow = "f4_commands"- for side in (self.sides["ts"], self.sides["rust"]):- session = f"{self.runid}-f4-{side.name}"- argv = [side.binary, "--daemon-socket", str(side.daemon_socket), "--offline"]- B.tmux_launch(session, argv, side.env, side.work_dir)- # TS fresh-install notice is already answered in f1 for these dirs,- # but print/daemon state may re-show it; press through if present.- B.tmux_wait_text(session, ">|manage|PRIME Agent", timeout=25)- B.tmux_send(session, "/", enter=False)- time.sleep(1.5)- frame = B.tmux_capture(session)- side.evidence(flow, "01-slash-menu.txt", frame)- if "/" in frame and ("commands" in frame.lower() or "model" in frame.lower() or "quit" in frame.lower()):- self.record(flow, "visual", f"{side.name}: '/' shows a slash-command menu", gap=False)- else:- self.record(flow, "visual", f"{side.name}: '/' did not show a command menu", evidence=side.root / flow / "01-slash-menu.txt")- B.tmux_send(session, "C-c", enter=False)- time.sleep(0.5)- # Benign run: /session shows session info in the TS product.- B.tmux_send(session, "/session")- frame2 = B.tmux_wait_text(session, "session|Session|cwd|error|Error|unknown|Unknown", timeout=15)- side.evidence(flow, "02-session-command.txt", frame2)- B.tmux_kill(session)-- def f5_side_questions(self) -> None:- """Side questions over the daemon socket on both daemons."""- flow = "f5_side_questions"- for side in (self.sides["ts"], self.sides["rust"]):- side.mock.set_responses([{"text": "side answer from mock"}])- self.ensure_daemon(side)- wire = B.Wire(side.daemon_socket)- side.evidence_json(flow, "hello.json", wire.hello)- create = wire.request(- "c1",- {"type": "create", "name": "battery-side-questions", "config": self.session_config(side)},- timeout=120,- )- side.evidence_json(flow, "create-response.json", create)- if create.get("success") is not True:- self.record(flow, "protocol", f"{side.name}: daemon create failed: {json.dumps(create)[:300]}")- wire.close()- continue- session_id = (create.get("data", {}).get("activeSessionId") or create.get("data", {}).get("id") or "")- # Side-question events stream only to clients attached to the- # session (the real /btw flow is an attached TUI client), so- # attach this wire first.- attach = wire.request(- "a0", {"type": "attach", "activeSessionId": session_id}, timeout=60- )- side.evidence_json(flow, "attach-response.json", attach)- if attach.get("success") is not True:- self.record(flow, "protocol", f"{side.name}: attach before side question failed: {json.dumps(attach)[:200]}")- wire.close()- continue- # Prime the session with one turn first (mock reply #1 is fresh).- side.mock.set_responses([{"text": "main turn reply"}, {"text": "side answer from mock"}])- prompt = wire.request(- "p1",- {"type": "prompt_and_wait", "activeSessionId": session_id, "message": "start a turn"},- timeout=240,- )- side.evidence_json(flow, "prompt-response.json", prompt)- mark = len(side.mock.requests())- sq = wire.request(- "sq1",- {- "type": "start_side_question",- "activeSessionId": session_id,- "sideQuestionId": "q1",- "question": "what is the mock answer?",- },- timeout=240,- )- side.evidence_json(flow, "side-question-response.json", sq)- side.evidence_json(flow, "side-question-events.json", wire.events)- # The side question runs async after the ack; wait for its- # completion to stream back as side_question_event frames.- deadline = time.time() + 90- while time.time() < deadline:- fresh = wire.drain(timeout=5)- text = json.dumps(fresh)- if "complete" in text or "side answer from mock" in text or "cancelled" in text:- break- events = wire.events- complete = any("complete" in json.dumps(e) for e in events)- got_side_answer = any("side answer from mock" in json.dumps(e) for e in events)- if sq.get("success") is True and (complete or got_side_answer):- self.record(- flow,- "protocol",- f"{side.name}: start_side_question answered via mock with side_question_event stream",- gap=False,- )- else:- self.record(- flow,- "protocol",- f"{side.name}: side question outcome differs (success={sq.get('success')}, events={len(events)}, complete={complete})",- evidence=side.root / flow / "side-question-response.json",- )- # Abort for an unknown id (guard parity).- abort = wire.request(- "ab0",- {"type": "abort_side_question", "activeSessionId": session_id, "sideQuestionId": "nope"},- timeout=60,- )- side.evidence_json(flow, "abort-unknown.json", abort)- side.evidence_json(flow, "mock-requests.json", self.new_mock_requests(side, mark))- wire.close()- # B-7: after a completed turn, the daemon session issues a second- # provider request for the dashboard status line (a small model).- # It may fire while the side question runs or up to the settle- # debounce later; wait out the debounce and filter the whole- # wire log for it.- time.sleep(5)- statusline = [req for req in side.mock.requests() if is_statusline_request(req)]- side.evidence_json(flow, "statusline-requests.json", statusline)- self.copy_sessions(side, flow)-- # B-7 differential: both sides must have issued the status-line- # request to the same small model after the turn.- status_rows = {}- for side in (self.sides["ts"], self.sides["rust"]):- path = side.root / flow / "statusline-requests.json"- requests = json.loads(path.read_text()) if path.exists() else []- status_rows[side.name] = len(requests)- if status_rows["ts"] and status_rows["rust"]:- self.record(- flow,- "protocol",- f"post-turn status-line request issued by both sides "- f"(ts={status_rows['ts']}, rust={status_rows['rust']} requests, model {STATUSLINE_MODEL_ID})",- gap=False,- )- else:- self.record(- flow,- "protocol",- f"post-turn status-line request missing: ts={status_rows['ts']} rust={status_rows['rust']}",- evidence="statusline-requests.json",- )- # Client-driven path: the /btw pane in the interactive TUI. The pane- # is a client surface over the engine above (no new daemon surface):- # /btw opens it mid-task, the answer streams into the pane, a reply- # seeds a follow-up, and esc returns to the main thread.- self.f5_side_questions_client()-- def f5_side_questions_client(self) -> None:- """The /btw pane in each product's interactive TUI: open mid-task,- answer, follow up, and close with esc; frames diffed TS vs Rust."""- flow = "f5_side_questions"- frames: dict[str, str] = {}- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- # Model-scoped queues: the main trio serves mock-1 requests in- # order, and the dashboard status-line requests (which arrive- # on their own debounce, even strays from the wire part's- # session) get their own queue instead of stealing a reply.- side.mock.set_responses(- [{"text": "status"}],- queues=[- {- "name": "client-turns",- "matchModels": ["mock-1"],- "responses": [- {"text": "main turn reply"},- {"text": "btw answer from mock"},- {"text": "btw follow-up answer from mock"},- ],- },- {- "name": "statusline",- "matchModels": [STATUSLINE_MODEL_ID],- "responses": [{"text": "status"}],- },- ],- )- session = f"{self.runid}-f5t-{side.name}"- argv = P.launch_argv(side, side.daemon_socket)- B.tmux_launch(session, argv, side.env, side.work_dir)- self.settle_first_run(session)- mark = len(side.mock.requests())- # The main turn runs first (the /btw purpose — ask about the- # in-flight work without disturbing it). Wait for the mock's- # reply before opening the pane: the 0.2s fire-and-hope gap is- # a race (a session still starting up can send the side- # question's provider request before the main prompt's, and the- # mock serves first-come).- B.tmux_send(session, "run the main task")- B.tmux_wait_text(session, "main turn reply", timeout=90)- B.tmux_send(session, "/btw what is the side answer?")- pane_open = B.tmux_wait_text(session, "what is the side answer\?", timeout=45)- side.evidence(flow, "10-btw-pane-open.txt", pane_open)- answered = B.tmux_wait_text(session, "btw answer from mock", timeout=90)- side.evidence(flow, "11-btw-pane-answered.txt", answered)- if "/btw" not in answered or "btw answer from mock" not in answered:- self.record(- flow,- "visual",- f"{side.name}: /btw pane did not render the question header and answer",- evidence=side.root / flow / "11-btw-pane-answered.txt",- )- else:- self.record(- flow,- "visual",- f"{side.name}: /btw pane renders the question header and the streamed answer",- gap=False,- )- # The pane hint line: esc returns to the main thread.- if "esc to return to session" not in answered:- self.record(- flow,- "visual",- f"{side.name}: /btw pane hint line missing (answer arrived; hint should read 'reply to follow up ...')",- evidence=side.root / flow / "11-btw-pane-answered.txt",- )- # A reply becomes a follow-up side question whose provider- # request replays the answered exchange (previousTurns seeding).- B.tmux_send(session, "and the follow-up?")- follow_up = B.tmux_wait_text(session, "btw follow-up answer from mock", timeout=90)- side.evidence(flow, "12-btw-follow-up.txt", follow_up)- requests = self.new_mock_requests(side, mark)- side.evidence_json(flow, "10-client-mock-requests.json", requests)- seeded = any(- "btw answer from mock" in json.dumps(req.get("body") or {})- and "and the follow-up?" in json.dumps(req.get("body") or {})- for req in requests- )- if seeded:- self.record(- flow,- "protocol",- f"{side.name}: follow-up reply seeded the side transcript (previous turns replayed to the provider)",- gap=False,- )- else:- self.record(- flow,- "protocol",- f"{side.name}: follow-up reply did not replay the previous turns to the provider",- evidence=side.root / flow / "10-client-mock-requests.json",- )- # esc closes the pane (aborting nothing: every turn settled).- B.tmux_send(session, "Escape", enter=False)- time.sleep(1.5)- after_esc = B.tmux_capture(session)- side.evidence(flow, "13-btw-after-esc.txt", after_esc)- if (- "what is the side answer?" in after_esc- or "esc to return to session" in after_esc- ):- self.record(- flow,- "behavior",- f"{side.name}: esc did not close the /btw pane",- evidence=side.root / flow / "13-btw-after-esc.txt",- )- else:- self.record(- flow,- "behavior",- f"{side.name}: esc closes the /btw pane and returns to the main thread",- gap=False,- )- frames[side.name] = answered- B.tmux_kill(session)- # Capture-compare: the answered-pane frame, normalized like the- # other real-surface flows.- self.frame_diff(- flow,- "btw-pane-answered",- frames,- normalizer=self.normalize_transcript_frame,- )- # The mid-turn dogfood phase: /btw during a busy main turn.- self.f5_side_questions_client_midturn()-- def f5_side_questions_client_midturn(self) -> None:- """The /btw pane opened DURING a busy main turn (the live-dogfood- report: "stuck in thinking"). The side question is a parallel model- call: the pane must answer while the main turn is still waiting on- its provider, and the main turn must then complete unaffected."""- flow = "f5_side_questions"- frames: dict[str, str] = {}- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- # Text-scoped queues (the side run clones the main conversation,- # so its request body carries the main turn's text too — the- # side queue matches first because queue order decides). The- # main turn's reply is delayed (delayMs), holding the session- # mid-turn while the side question runs.- side.mock.set_responses(- [{"text": "status"}],- queues=[- {- "name": "side-turns",- "match": ["what is the busy side answer"],- "responses": [{"text": "btw busy answer from mock"}],- },- {- "name": "main-turns",- "match": ["run the slow main task"],- "responses": [{"text": "main turn reply while busy", "delayMs": 20000}],- },- {- "name": "statusline",- "matchModels": [STATUSLINE_MODEL_ID],- "responses": [{"text": "status"}],- },- ],- )- session = f"{self.runid}-f5m-{side.name}"- argv = P.launch_argv(side, side.daemon_socket)- B.tmux_launch(session, argv, side.env, side.work_dir)- self.settle_first_run(session)- mark = len(side.mock.requests())- # The main turn starts and parks on the delayed provider reply.- B.tmux_send(session, "run the slow main task")- busy = B.tmux_wait_text(session, "Waiting", timeout=30)- side.evidence(flow, "20-midturn-busy.txt", busy)- if "Waiting" not in busy:- # The main turn never parked on its delayed reply: a /btw now- # would run against an idle session and pass spuriously.- self.record(- flow,- "behavior",- f"{side.name}: the main turn never reached the waiting state, so the mid-turn /btw run could not be exercised",- evidence=side.root / flow / "20-midturn-busy.txt",- )- B.tmux_kill(session)- continue- # /btw mid-turn: the pane opens on the thinking state and must- # render the streamed answer while the main turn is still- # waiting.- B.tmux_send(session, "/btw what is the busy side answer?")- pane = B.tmux_wait_text(session, "btw busy answer from mock", timeout=60)- side.evidence(flow, "21-midturn-btw-answered.txt", pane)- requests = self.new_mock_requests(side, mark)- side.evidence_json(flow, "20-midturn-mock-requests.json", requests)- side_order = [- index- for index, request in enumerate(requests)- if "busy side answer" in json.dumps(request.get("body") or {})- ]- if "/btw" in pane and "btw busy answer from mock" in pane:- if "main turn reply while busy" not in pane and side_order:- self.record(- flow,- "behavior",- f"{side.name}: /btw answered while the main turn was still waiting on its provider (the side run is a parallel model call)",- gap=False,- )- elif "main turn reply while busy" in pane:- self.record(- flow,- "behavior",- f"{side.name}: the /btw pane answered only after the main turn finished (the side run queued behind the busy main turn)",- evidence=side.root / flow / "21-midturn-btw-answered.txt",- )- else:- self.record(- flow,- "protocol",- f"{side.name}: the side pane answered without a side provider request (the run never reached the provider)",- evidence=side.root / flow / "20-midturn-mock-requests.json",- )- else:- self.record(- flow,- "behavior",- f"{side.name}: /btw pane never rendered the side answer mid-turn (stuck in thinking)",- evidence=side.root / flow / "21-midturn-btw-answered.txt",- )- # The main turn completes, unaffected by the side question; the- # answered pane stays mounted.- settled = B.tmux_wait_text(session, "main turn reply while busy", timeout=60)- side.evidence(flow, "22-midturn-settled.txt", settled)- if "btw busy answer from mock" in settled:- self.record(- flow,- "behavior",- f"{side.name}: the main turn completed with the /btw pane still answered (the main session was never blocked)",- gap=False,- )- else:- self.record(- flow,- "behavior",- f"{side.name}: the settled frame lost the answered side pane",- evidence=side.root / flow / "22-midturn-settled.txt",- )- # esc closes the pane; the main thread continues.- B.tmux_send(session, "Escape", enter=False)- time.sleep(1.5)- after_esc = B.tmux_capture(session)- side.evidence(flow, "23-midturn-after-esc.txt", after_esc)- if (- "busy side answer" in after_esc- or "esc to return to session" in after_esc- ):- self.record(- flow,- "behavior",- f"{side.name}: esc did not close the mid-turn /btw pane",- evidence=side.root / flow / "23-midturn-after-esc.txt",- )- else:- self.record(- flow,- "behavior",- f"{side.name}: esc closes the mid-turn /btw pane with the main thread intact",- gap=False,- )- frames[side.name] = settled- B.tmux_kill(session)- # Capture-compare: the settled frame (main reply landed, pane- # answered), normalized like the other real-surface flows.- self.frame_diff(- flow,- "btw-pane-midturn-settled",- frames,- normalizer=self.normalize_transcript_frame,- )-- def overflow_wire_projection(self, events: list) -> list:- """The overflow-relevant wire surface of one session: the- compaction event pair and the compaction_outcome rows, in order- (token counts, ids, and timestamps differ per side; the error- message text of the scripted provider failure is normalized to its- overflow phrase)."""- rows = []- for frame in events:- if not isinstance(frame, dict) or frame.get("type") != "session_event":- continue- event = frame.get("event") or {}- if not isinstance(event, dict):- continue- if event.get("type") == "compaction_start":- rows.append(- {"type": "compaction_start", "reason": event.get("reason")}- )- elif event.get("type") == "compaction_end":- rows.append(- {- "type": "compaction_end",- "reason": event.get("reason"),- "willRetry": event.get("willRetry"),- "hasResult": bool(event.get("result")),- "errorMessage": event.get("errorMessage"),- "errorSeverity": event.get("errorSeverity"),- }- )- elif event.get("type") in ("message_start", "message_end"):- message = event.get("message") or {}- if not isinstance(message, dict):- continue- if message.get("customType") == "compaction_outcome":- rows.append(- {- "type": "compaction_outcome",- "content": message.get("content"),- "details": message.get("details"),- "display": message.get("display"),- }- )- elif message.get("role") == "assistant" and message.get("stopReason") == "error":- error_text = message.get("errorMessage") or ""- rows.append(- {- "type": "assistant_error",- "overflow": OVERFLOW_ERROR_TEXT in error_text,- }- )- return rows-- def goal_continue_projection(self, events: list) -> list:- """The post-compact goal-continue wire window (the #234 residue):- from the aborted row of the turn the compact aborted (it- broadcasts before `compaction_start`), the compaction pair, the- mint's `goal_update`, the continuation turn's goal-context row and- its assistant rows, and the completion's `goal_update` — in order.- Ids, timestamps, usage, and token counts differ per side, so the- projected fields are the ones the TS branch owns: the event- sequence, the goal state's status/objective/continuation count,- and the row contents."""- rows = []- seen_goal_updates: list = []- started = False- for frame in events:- if not isinstance(frame, dict) or frame.get("type") != "session_event":- continue- event = frame.get("event") or {}- if not isinstance(event, dict):- continue- event_type = event.get("type")- if event_type == "compaction_start":- started = True- # Canary for the aborted row of the turn the compact- # interrupts: TS `compact()` detaches from agent events before- # the abort (`_disconnectFromAgent`), so the row never surfaces- # on either side in this window — the projection opens early if- # one ever does (a one-sided row is a parity bug: the Rust gate- # must swallow the compact interrupt's row exactly like TS).- if event_type in ("message_start", "message_end") and not started:- message = event.get("message") or {}- if (- isinstance(message, dict)- and message.get("role") == "assistant"- and message.get("stopReason") == "aborted"- ):- started = True- if not started:- continue- if event_type == "compaction_start":- rows.append({"type": "compaction_start", "reason": event.get("reason")})- elif event_type == "compaction_end":- rows.append(- {- "type": "compaction_end",- "reason": event.get("reason"),- "hasResult": bool(event.get("result")),- "errorMessage": event.get("errorMessage"),- }- )- elif event_type == "goal_update":- goal = event.get("goal") or {}- # Usage-accounting goal_updates repeat the projected- # state of the mint's goal_update (tokensUsed is- # per-side); the Rust engine checks the goal state after- # each forwarded event, so the repeat's position inside- # the turn is drain-timing while TS emits it at the- # turn's stop hook — repeats carry no new projected- # information and dedupe.- projected = {- "type": "goal_update",- "status": goal.get("status"),- "objective": goal.get("objective"),- "continuationsUsed": goal.get("continuationsUsed"),- }- if projected not in seen_goal_updates:- seen_goal_updates.append(projected)- rows.append(projected)- elif event_type in ("message_start", "message_end"):- message = event.get("message") or {}- if not isinstance(message, dict):- continue- if message.get("customType") == "goal_context":- details = message.get("details") or {}- # The context's "tokens used" line carries the- # per-side goal accounting at mint time and compares- # verbatim now: the mid-turn compact abort cancels the- # in-flight fetch immediately on both sides (TS- # `requestAbort` -> `agent.abort()`; the Rust- # `abort_in_flight_turn` funnel), so the aborted- # turn's usage is not counted on either.- content = str(message.get("content"))- rows.append(- {- "type": event_type,- "customType": "goal_context",- "content": content,- "details": {- key: details.get(key)- for key in ("kind", "status", "objective", "continuationsUsed")- },- }- )- elif message.get("role") == "assistant":- if event_type == "message_start":- # A streamed assistant's start content is volatile- # (TS carries the settled message at start, the- # Rust loop streams it in) — only the settled end- # row is the parity claim.- rows.append({"type": "message_start"})- continue- content = message.get("content")- if isinstance(content, list):- text = chr(10).join(- part.get("text", "")- for part in content- if isinstance(part, dict) and part.get("text")- )- tools = sorted(- part.get("name", "")- for part in content- if isinstance(part, dict) and part.get("type") == "toolCall"- )- else:- text = content or ""- tools = []- rows.append(- {- "type": event_type,- "assistant_text": text,- "tool_calls": tools,- "stopReason": message.get("stopReason"),- }- )- return rows-- def last_user_text(self, request: dict) -> str:- """The text of a provider request's last user-role message (string- or content-part form): the continuation prompt of a goal turn, or- the summarizer instruction of a compaction request."""- for message in reversed(request.get("body", {}).get("messages") or []):- if message.get("role") != "user":- continue- content = message.get("content")- if isinstance(content, str):- return content- if isinstance(content, list):- return chr(10).join(- part.get("text", "")- for part in content- if isinstance(part, dict) and part.get("text")- )- return ""- return ""-- def ensure_daemon(self, side: B.Side) -> None:- """A daemon must be listening on the side socket; start one if not."""- try:- probe = B.Wire(side.daemon_socket)- probe.close()- return- except (OSError, EOFError):- pass- side.start_daemon()-- def f6_attach(self) -> None:- """Attach: wire-level snapshot + event stream, and the CLI attach command."""- flow = "f6_attach"- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- owner = B.Wire(side.daemon_socket)- create = owner.request(- "c1",- {- "type": "create",- "name": "battery-attach",- "config": self.session_config(side),- },- timeout=120,- )- side.evidence_json(flow, "create-response.json", create)- session_id = (create.get("data", {}).get("activeSessionId") or create.get("data", {}).get("id") or "")- if create.get("success") is not True:- self.record(flow, "protocol", f"{side.name}: daemon create failed: {json.dumps(create)[:300]}")- owner.close()- continue- attacher = B.Wire(side.daemon_socket)- attach = attacher.request(- "a1",- {"type": "attach", "activeSessionId": session_id},- timeout=60,- )- side.evidence_json(flow, "attach-response.json", attach)- side.evidence_json(flow, "attach-events.json", attacher.events)- attach_ok = attach.get("success") is True and "data" in attach- if attach_ok:- data_keys = sorted((attach.get("data") or {}).keys())- side.evidence_json(flow, "attach-data-keys.json", data_keys)- self.record(flow, "protocol", f"{side.name}: wire attach returned a snapshot (data keys: {data_keys})", gap=False)- else:- self.record(- flow,- "protocol",- f"{side.name}: wire attach failed: {json.dumps(attach)[:300]}",- evidence=side.root / flow / "attach-response.json",- )- # Event stream: prompt from the owner, capture events on the attacher.- side.mock.set_responses([{"text": "attach stream reply"}])- mark = len(side.mock.requests())- prompt = owner.request(- "p1",- {"type": "prompt_and_wait", "activeSessionId": session_id, "message": "say something"},- timeout=240,- )- side.evidence_json(flow, "prompt-response.json", prompt)- # Drain whatever streamed to the attacher during the turn.- attacher.drain(timeout=5)- side.evidence_json(flow, "attacher-events-after-prompt.json", attacher.events)- if attacher.events:- self.record(- flow,- "protocol",- f"{side.name}: attached client received {len(attacher.events)} events during the turn",- gap=False,- )- else:- self.record(flow, "protocol", f"{side.name}: attached client received no events during the turn")- owner.close()- attacher.close()- # CLI-level attach is an interactive surface: run it in tmux.- attach_session = f"{self.runid}-f6cli-{side.name}"- argv = [side.binary, "attach", session_id, "--daemon-socket", str(side.daemon_socket)]- B.tmux_launch(attach_session, argv, side.env, side.work_dir)- frame = B.tmux_wait_text(attach_session, "attach stream reply|hello|Error|error|>", timeout=25)- side.evidence(flow, "cli-attach.txt", frame)- pane_state = B.tmux(- "list-panes", "-t", attach_session, "-F", "#{pane_dead} #{pane_dead_status}", check=False- ).stdout.strip()- B.tmux_kill(attach_session)- if pane_state.startswith("1"):- self.record(- flow,- "behavior",- f"{side.name}: CLI 'attach' exited in tmux ({pane_state}); visible frame tail: {[l for l in frame.splitlines() if l.strip()][-3:]}",- evidence=side.root / flow / "cli-attach.txt",- )- else:- self.record(- flow,- "behavior",- f"{side.name}: CLI 'attach' opened the session in tmux (frame captured)",- gap=False,- )- self.copy_sessions(side, flow)-- # f6 cross-side verdict: the attach event stream must carry the same- # wire events (type + message role / customType), in order.- from collections import Counter-- def fingerprints(side_name):- path = self.sides[side_name].root / flow / "attacher-events-after-prompt.json"- if not path.exists():- return None- out = []- for entry in json.loads(path.read_text()):- event = entry.get("event", entry)- message = event.get("message") or {}- etype = event.get("type")- # Row scope: the event-set parity locked here excludes the- # two documented model-surface diffs- # (the f6 commit): the harness-digest custom message pair- # (TS delivers the per-turn digest as a custom message;- # Rust composes it into the request only) and the- # turn_end/agent_end payloads (TS carries the final message).- # Drop the filter when the model-surface lane lands- # custom-message wire parity.- if (- etype in ("message_start", "message_end")- and message.get("customType") == "harness_digest"- ):- continue- if etype in ("turn_end", "agent_end"):- out.append(str(etype))- continue- out.append(- "{}:{}".format(- etype,- message.get("role") or message.get("customType") or "",- )- )- return out-- ts_events = fingerprints("ts")- rust_events = fingerprints("rust")- if ts_events and rust_events:- if ts_events == rust_events:- self.record(- flow,- "protocol",- f"attach event sequences match ({len(ts_events)} projected events, in order; "- "harness-digest custom pairs and turn_end/agent_end payloads are out of scope here — "- "documented model-surface diffs)",- gap=False,- )- else:- ts_counts = Counter(ts_events)- rust_counts = Counter(rust_events)- ts_only = ts_counts - rust_counts- rust_only = rust_counts - ts_counts- self.record(- flow,- "protocol",- "attach event sequences differ: "- f"ts={len(ts_events)} rust={len(rust_events)}; "- f"ts-only={sorted(ts_only.elements())} rust-only={sorted(rust_only.elements())}",- evidence=self.run_dir / flow,- )-- def session_config(self, side: B.Side) -> dict:- # Identical on both sides: explicit provider/model flags ride the- # create config over the wire and are authoritative in the worker- # (B-1 differential check; no env-based model workaround).- return {- "cwd": str(side.work_dir),- "sessionDir": str(side.agent_dir / "sessions"),- "provider": "prime-inference",- "model": "mock-1",- "executionMode": "print",- }-- def f7_compaction(self) -> None:- """Compaction: what the TS daemon does on 'compact'; what Rust does."""- flow = "f7_compaction"- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- wire = B.Wire(side.daemon_socket)- create = wire.request(- "c1",- {- "type": "create",- "name": "battery-compact",- "config": self.session_config(side),- },- timeout=120,- )- side.evidence_json(flow, "create-response.json", create)- session_id = (create.get("data", {}).get("activeSessionId") or create.get("data", {}).get("id") or "")- if create.get("success") is not True:- self.record(flow, "protocol", f"{side.name}: daemon create failed: {json.dumps(create)[:300]}")- wire.close()- continue- # Grow the session before compacting: several turns of- # deterministic content, so the TS compactor keeps the recent- # turns and has older ones to summarize.- turn_text = "Turn {n} of the parity battery. " * 800- side.mock.set_responses([{"text": f"pre-compaction reply {i}"} for i in range(7)])- for turn_index in range(1, 7):- prompt = wire.request(- f"p{turn_index}",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": turn_text.format(n=turn_index),- },- timeout=240,- )- side.evidence_json(flow, f"prompt-{turn_index}-response.json", prompt)- compact = wire.request(- "k1",- {"type": "compact", "activeSessionId": session_id},- timeout=240,- )- side.evidence_json(flow, "compact-response.json", compact)- if compact.get("success") is True:- self.record(- flow,- "protocol",- f"{side.name}: daemon 'compact' succeeded: {json.dumps(compact.get('data', {}))[:200]}",- gap=False,- )- else:- self.record(- flow,- "protocol",- f"{side.name}: daemon 'compact' failed: {json.dumps(compact)[:300]}",- evidence=side.root / flow / "compact-response.json",- )-- # B-31 differential: the overflow compact-and-retry arm (TS- # `_checkCompaction` Case 1). A scripted Anthropic-style overflow- # error triggers one compaction (compaction_start + compaction_end,- # reason "overflow", willRetry true) and the turn re-issues on the- # compacted context; the second overflow ends the run with the- # reported failure surface — the durable compaction_outcome row and- # the compaction_end failure — on both sides. A shrunken- # keep-recent budget gives the recovery pre-cut history to summarize- # (the default 64k keeps a one-turn session whole, and the recovery- # would skip — covered by the durable rows either way).- overflow_replies = {}- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- settings_path = side.agent_dir / "settings.json"- prior_settings = (- settings_path.read_text() if settings_path.exists() else None- )- settings_path.write_text(- json.dumps({"compaction": {"keepRecentTokens": 10, "reserveTokens": 1000}})- )- try:- wire = B.Wire(side.daemon_socket)- create = wire.request(- "oc1",- {- "type": "create",- "name": "battery-overflow",- "config": self.session_config(side),- },- timeout=120,- )- side.evidence_json(flow, "overflow-create-response.json", create)- session_id = (- create.get("data", {}).get("activeSessionId") or create.get("data", {}).get("id") or ""- )- if create.get("success") is not True:- self.record(- flow,- "protocol",- f"{side.name}: overflow session create failed: {json.dumps(create)[:300]}",- )- wire.close()- continue- # An attached client receives the compaction event pair; the- # prompting connection only carries the command responses.- attacher = B.Wire(side.daemon_socket)- attach = attacher.request(- "oa1",- {"type": "attach", "activeSessionId": session_id},- timeout=60,- )- side.evidence_json(flow, "overflow-attach-response.json", attach)- # Model-routed queue: seed turn, probe error, summarizer,- # and the retry error all draw from the scripted sequence;- # the dashboard status-line model falls through to the- # default queue.- side.mock.set_responses(- [{"text": "statusline filler"}],- queues=[- {- "name": "overflow",- "matchModels": ["mock-1"],- "responses": [- {"text": "seed reply"},- {"error": OVERFLOW_ERROR_TEXT},- {"text": "the overflow summary"},- {"error": OVERFLOW_ERROR_TEXT},- ],- }- ],- )- seed = wire.request(- "os1",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": "seed turn before the overflow probe",- },- timeout=240,- )- side.evidence_json(flow, "overflow-seed-response.json", seed)- attacher.drain(3.0)- attacher.events.clear()- mark = len(side.mock.requests())- # A seed turn plus a probe past the keep-recent budget give- # the recovery pre-cut history to summarize (the cut lands- # at the probe turn, leaving the seed turn to summarize).- prompt = wire.request(- "op1",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": "overflow probe " + ("x" * 400),- },- timeout=240,- )- side.evidence_json(flow, "overflow-prompt-response.json", prompt)- attacher.drain(5.0)- overflow_replies[side.name] = self.overflow_wire_projection(attacher.events)- side.evidence_json(flow, "overflow-wire-projection.json", overflow_replies[side.name])- side.evidence_json(flow, "overflow-attach-events.json", attacher.events)- side.evidence_json(flow, "overflow-mock-requests.json", self.new_mock_requests(side, mark))- wire.close()- attacher.close()- self.copy_sessions(side, flow)- finally:- if prior_settings is None:- settings_path.unlink(missing_ok=True)- else:- settings_path.write_text(prior_settings)- if overflow_replies.get("ts") is not None and overflow_replies.get("rust") is not None:- if overflow_replies["ts"] == overflow_replies["rust"] and overflow_replies["ts"]:- self.record(- flow,- "behavior",- "overflow compact-and-retry wire surface identical: "- f"{json.dumps(overflow_replies['ts'])[:300]}",- gap=False,- )- else:- self.record(- flow,- "behavior",- f"overflow compact-and-retry wire surface differs: ts={json.dumps(overflow_replies.get('ts'))[:400]} "- f"rust={json.dumps(overflow_replies.get('rust'))[:400]}",- evidence=[- side.root / flow / "overflow-wire-projection.json"- for side in self.sides.values()- ],- )-- # Split-turn differential (the pa-core split-turn lane): a cut- # inside a turn is a split-turn compaction. Turn two's assistant- # reply ("reply two padded more", 6 tokens under the chars/4- # estimate) pushes the keep-recent walk (10 tokens) over the- # budget at an ASSISTANT message, so the cut lands mid-turn: the- # seed turn is the history to summarize, turn two's user message- # is the split turn start, and the compact makes TWO summarizer- # wire calls (history, then turn prefix) writing the merged- # "**Turn Context (split turn):**" summary with the summed usage- # onto the durable row.- split_rows: dict[str, dict | None] = {}- split_requests: dict[str, list] = {}- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- settings_path = side.agent_dir / "settings.json"- prior_settings = (- settings_path.read_text() if settings_path.exists() else None- )- # autoRefine off (the print_json_parity pin): the TS daemon- # schedules a harness-state review request after every- # compaction, which would consume a mock response past the- # two summarizer calls this differential counts.- settings_path.write_text(- json.dumps(- {- "compaction": {"keepRecentTokens": 10, "reserveTokens": 1000},- "autoRefine": {"enabled": False},- }- )- )- try:- wire = B.Wire(side.daemon_socket)- create = wire.request(- "sc1",- {- "type": "create",- "name": "battery-split",- "config": self.session_config(side),- },- timeout=120,- )- side.evidence_json(flow, "split-create-response.json", create)- session_id = (- create.get("data", {}).get("activeSessionId") or create.get("data", {}).get("id") or ""- )- if create.get("success") is not True:- self.record(- flow,- "protocol",- f"{side.name}: split session create failed: {json.dumps(create)[:300]}",- )- wire.close()- continue- # The two summarizer calls race the provider concurrently- # (TS Promise.all / Rust tokio::join), so their arrival- # order at the shared mock is not deterministic: route- # each by its prompt marker (content-matched queues) so- # each call deterministically gets its own scripted- # response regardless of arrival order.- side.mock.set_responses(- [- {"text": "seed reply"},- {"text": "reply two padded more"},- {"text": "k3"},- ],- queues=[- {- "name": "split-history",- "match": ["Create a structured context checkpoint summary"],- "responses": [{"text": "the history summary"}],- },- {- "name": "split-turn-prefix",- "match": ["PREFIX of a turn that was too large to keep"],- "responses": [{"text": "the turn prefix summary"}],- },- ],- )- for index, message in enumerate(("seed turn", "turn two", "turn three"), start=1):- prompt = wire.request(- f"sp{index}",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": message,- },- timeout=240,- )- side.evidence_json(flow, f"split-prompt-{index}-response.json", prompt)- # The mark rides after the turn requests: the compact's- # summarizer calls are the only requests past it.- mark = len(side.mock.requests())- compact = wire.request(- "sk1",- {"type": "compact", "activeSessionId": session_id},- timeout=240,- )- side.evidence_json(flow, "split-compact-response.json", compact)- wire.close()- # The summarizer wire requests of the compact: the two- # call bodies (history checkpoint prompt, turn-prefix- # prompt) land on the mock in that order.- requests = self.new_mock_requests(side, mark)- split_requests[side.name] = [- {- "user_text": [- block.get("text", "")- if isinstance(block, dict)- else ""- for message_entry in (request.get("body", {}).get("messages") or [])- if message_entry.get("role") == "user"- for block in (- message_entry.get("content")- if isinstance(message_entry.get("content"), list)- else [{"text": message_entry.get("content", "")}]- )- ],- }- for request in requests- ]- side.evidence_json(flow, "split-mock-requests.json", requests)- # The durable split compaction row.- split_rows[side.name] = None- sessions_dir = side.sessions_dir()- for path in sorted(sessions_dir.glob("*.jsonl")) if sessions_dir.exists() else []:- for line in path.read_text().splitlines():- try:- entry = json.loads(line)- except json.JSONDecodeError:- continue- if entry.get("type") == "compaction" and "Turn Context (split turn)" in str(- entry.get("summary", "")- ):- split_rows[side.name] = {- key: entry.get(key)- for key in (- "summary",- "tokensBefore",- "details",- "fromHook",- "usage",- "harnessDigest",- )- }- self.copy_sessions(side, flow)- finally:- if prior_settings is None:- settings_path.unlink(missing_ok=True)- else:- settings_path.write_text(prior_settings)- if split_rows.get("ts") is not None and split_rows.get("rust") is not None:- # Two summarizer wire calls on both sides with byte-identical- # prompt shapes (the checkpoint instruction on the history- # call, the turn-prefix instruction on the prefix call). The- # calls race the provider concurrently (TS Promise.all / Rust- # tokio::join), so arrival order is not a parity claim: compare- # the request set, not the order.- split_set = lambda side_name: sorted( # noqa: E731- json.dumps(request, sort_keys=True)- for request in split_requests.get(side_name, [])- )- if len(split_requests.get("ts", [])) == 2 and split_set("ts") == split_set("rust"):- self.record(- flow,- "behavior",- "split-turn compaction: two summarizer requests with identical prompt shapes: "- f"{json.dumps(split_requests['ts'])[:300]}",- gap=False,- )- else:- self.record(- flow,- "behavior",- f"split-turn compaction summarizer requests differ: ts={json.dumps(split_requests.get('ts'))[:400]} "- f"rust={json.dumps(split_requests.get('rust'))[:400]}",- evidence=[side.root / flow / "split-mock-requests.json" for side in self.sides.values()],- )- if split_rows["ts"] == split_rows["rust"]:- self.record(- flow,- "behavior",- "split-turn durable compaction row identical (merged summary, summed usage): "- f"{json.dumps(split_rows['ts'])[:300]}",- gap=False,- )- else:- self.record(- flow,- "behavior",- f"split-turn durable compaction row differs: ts={json.dumps(split_rows['ts'])[:400]} "- f"rust={json.dumps(split_rows['rust'])[:400]}",- evidence=[side.root / flow / "split-compact-response.json" for side in self.sides.values()],- )-- # Iterative/second-compaction differential (the- # iterative-compaction lane): TS compaction runs in UPDATE mode on- # subsequent compactions — the prior compaction's summary wires- # into the history summarizer request inside <previous-summary>- # tags under the update instruction, and the new history covers- # only the conversation since the prior compaction's boundary- # (its first kept entry), never the already-summarized prefix. A- # session compacted twice: the second compaction's summarizer- # wire requests must be byte-identical on both sides, and both- # durable compaction rows must match.- iterative_requests: dict[str, list] = {}- iterative_rows: dict[str, list] = {}- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- settings_path = side.agent_dir / "settings.json"- prior_settings = (- settings_path.read_text() if settings_path.exists() else None- )- # autoRefine off (the split differential's pin): the TS daemon- # would otherwise schedule a harness-state review after each- # compaction and consume mock responses past the summarizer- # calls this differential counts.- settings_path.write_text(- json.dumps(- {- "compaction": {"keepRecentTokens": 10, "reserveTokens": 1000},- "autoRefine": {"enabled": False},- }- )- )- try:- wire = B.Wire(side.daemon_socket)- create = wire.request(- "ic1",- {- "type": "create",- "name": "battery-iterative",- "config": self.session_config(side),- },- timeout=120,- )- side.evidence_json(flow, "iterative-create-response.json", create)- session_id = (- create.get("data", {}).get("activeSessionId") or create.get("data", {}).get("id") or ""- )- if create.get("success") is not True:- self.record(- flow,- "protocol",- f"{side.name}: iterative session create failed: {json.dumps(create)[:300]}",- )- wire.close()- continue- # Two turns, compact #1 (checkpoint prompt over the first- # turn, keeping the second), one more turn, then compact- # #2: the update-mode call over the conversation the first- # compaction retained plus the new turn. A turn between- # the compacts keeps both sides' compact #2 preparing- # identically (TS appends an ipython_state custom message- # after each compaction when its prewarmed kernel is running —- # ported to Rust, but the Rust daemon does not prewarm the- # kernel at session creation yet, so a battery session (no- # ipython tool use) has no running kernel and no notice row;- # the turn-in-between shape exercises the update mode on both- # sides regardless).- # Model-routed queue (the suspension section's pattern):- # the session's mock-1 turns and the compact's summarizer- # draw their scripted replies in order while the daemon- # status-line model falls through to the default filler —- # a status-line request racing the default queue otherwise- # consumes a scripted response and misaligns the cursor- # (observed as the flaky iterative gap).- side.mock.set_responses(- [{"text": "statusline filler"}],- queues=[- {- "name": "iterative",- "matchModels": ["mock-1"],- "responses": [- {"text": "seed reply"},- {"text": "second reply"},- {"text": "the first compaction summary"},- {"text": "third reply"},- {"text": "the second compaction summary"},- ],- }- ],- )- for index, message in enumerate(- (- "history turn one to be summarized by the first compact",- "history turn two kept by the first compact",- ),- start=1,- ):- prompt = wire.request(- f"ip{index}",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": message,- },- timeout=240,- )- side.evidence_json(flow, f"iterative-prompt-{index}-response.json", prompt)- compact_one = wire.request(- "ik1",- {"type": "compact", "activeSessionId": session_id},- timeout=240,- )- side.evidence_json(flow, "iterative-compact-one-response.json", compact_one)- # The TUI's default submission behavior: steer resumes the- # post-compaction input suspension (TS compact() aborts,- # which suspends queued-input admission; a plain daemon- # prompt_and_wait is rejected while suspended — the TUI- # always submits steer, which carries resumeIfIdle).- prompt_three = wire.request(- "ip3",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": "turn three after the first compaction",- "streamingBehavior": "steer",- },- timeout=240,- )- side.evidence_json(flow, "iterative-prompt-3-response.json", prompt_three)- # The mark rides after the turn: the second compact's- # summarizer call is the only request past it.- mark = len(side.mock.requests())- compact_two = wire.request(- "ik2",- {"type": "compact", "activeSessionId": session_id},- timeout=240,- )- side.evidence_json(flow, "iterative-compact-two-response.json", compact_two)- wire.close()- # Session-model requests only (the status-line model's- # requests fall through to the filler queue and are not- # part of the two-call comparison).- requests = [- request- for request in self.new_mock_requests(side, mark)- if request.get("body", {}).get("model") == "mock-1"- ]- iterative_requests[side.name] = [- {- "user_text": [- block.get("text", "")- if isinstance(block, dict)- else ""- for message_entry in (request.get("body", {}).get("messages") or [])- if message_entry.get("role") == "user"- for block in (- message_entry.get("content")- if isinstance(message_entry.get("content"), list)- else [{"text": message_entry.get("content", "")}]- )- ],- }- for request in requests- ]- side.evidence_json(flow, "iterative-mock-requests.json", requests)- # Both durable compaction rows (the checkpoint summary and- # the updated one), scoped to this scenario's scripted- # summaries (the other f7 sessions compact too).- rows: list[dict] = []- sessions_dir = side.sessions_dir()- for path in sorted(sessions_dir.glob("*.jsonl")) if sessions_dir.exists() else []:- for line in path.read_text().splitlines():- try:- entry = json.loads(line)- except json.JSONDecodeError:- continue- if (- entry.get("type") == "compaction"- and entry.get("summary", "") in ITERATIVE_SUMMARIES- ):- rows.append(- {- key: entry.get(key)- for key in (- "summary",- "tokensBefore",- "details",- "fromHook",- "usage",- "harnessDigest",- )- }- )- iterative_rows[side.name] = rows- self.copy_sessions(side, flow)- finally:- if prior_settings is None:- settings_path.unlink(missing_ok=True)- else:- settings_path.write_text(prior_settings)- if iterative_rows.get("ts") is not None and iterative_rows.get("rust") is not None:- # One update-mode history wire call: the prior summary in- # <previous-summary> tags under the update instruction, the- # conversation since the prior compaction's boundary only,- # byte-identical on both sides.- iterative_ok = (- len(iterative_requests.get("ts", [])) == 1- and iterative_requests.get("ts") == iterative_requests.get("rust")- and any(- "<previous-summary>" in text- for request in iterative_requests.get("ts", [])- for text in request.get("user_text", [])- )- )- if iterative_ok:- self.record(- flow,- "behavior",- "second-compaction update-mode summarizer request identical (previous-summary merge, new history only): "- + "; ".join(- text[:200]- for request in iterative_requests["ts"]- for text in request.get("user_text", [])- ),- gap=False,- )- else:- self.record(- flow,- "behavior",- f"second-compaction summarizer request differs: ts={json.dumps(iterative_requests.get('ts'))[:400]} "- f"rust={json.dumps(iterative_requests.get('rust'))[:400]}",- evidence=[- side.root / flow / "iterative-mock-requests.json"- for side in self.sides.values()- ],- )- if iterative_rows["ts"] == iterative_rows["rust"] and iterative_rows["ts"]:- self.record(- flow,- "behavior",- "iterative compaction durable rows identical (checkpoint + updated summary): "- f"{json.dumps(iterative_rows['ts'])[:300]}",- gap=False,- )- else:- self.record(- flow,- "behavior",- f"iterative compaction durable rows differ: ts={json.dumps(iterative_rows['ts'])[:400]} "- f"rust={json.dumps(iterative_rows['rust'])[:400]}",- evidence=[- self.sides[name].root / flow / "iterative-compact-two-response.json"- for name in ("ts", "rust")- ],- )-- # Post-compact queued-input suspension lifecycle (the #227/#233- # ruling): a manual daemon `compact` aborts first (TS `compact()` ->- # `abort()` -> `requestAbort()`), which suspends queued-input- # admission indefinitely (no timeout). While suspended, a plain- # `prompt_and_wait` (daemon `resumeIfIdle: streamingBehavior !==- # undefined` -> false) is rejected with the TS admission error;- # a `steer` (resumeIfIdle: true) resumes the suspension and its- # turn runs; afterwards a plain prompt is admitted again. `abort`- # re-arms the suspension, and `resume_queue` clears it even while- # answering "No queued work to resume" (TS `resumeQueuedWork()`- # resumes admission first). Every wire response is compared- # (success + error string, byte-equal).- suspension_replies: dict[str, dict | None] = {}- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- settings_path = side.agent_dir / "settings.json"- prior_settings = (- settings_path.read_text() if settings_path.exists() else None- )- settings_path.write_text(- json.dumps(- {- "compaction": {"keepRecentTokens": 10, "reserveTokens": 1000},- "autoRefine": {"enabled": False},- }- )- )- try:- wire = B.Wire(side.daemon_socket)- create = wire.request(- "zc1",- {- "type": "create",- "name": "battery-suspension",- "config": self.session_config(side),- },- timeout=120,- )- side.evidence_json(flow, "suspension-create-response.json", create)- session_id = (- create.get("data", {}).get("activeSessionId") or create.get("data", {}).get("id") or ""- )- if create.get("success") is not True:- self.record(- flow,- "protocol",- f"{side.name}: suspension session create failed: {json.dumps(create)[:300]}",- )- wire.close()- continue- # Model-routed queue (the overflow section's pattern): the- # session's `mock-1` turns draw their scripted replies in- # order; the dashboard status-line model falls through to- # the default filler queue.- side.mock.set_responses(- [{"text": "statusline filler"}],- queues=[- {- "name": "suspension",- "matchModels": ["mock-1"],- "responses": [- {"text": "seed reply"},- {"text": "the suspension compaction summary"},- {"text": "steered reply after resumption"},- {"text": "plain reply after resumption"},- {"text": "plain reply after resume_queue"},- ],- }- ],- )- projection: dict[str, dict] = {}-- def suspend_step(key: str, response: dict) -> None:- side.evidence_json(flow, f"suspension-{key}.json", response)- projection[key] = {- "success": response.get("success"),- "error": response.get("error"),- }-- seed = wire.request(- "zs1",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": "suspension seed turn with enough history for the compaction to summarize",- },- timeout=240,- )- side.evidence_json(flow, "suspension-seed-response.json", seed)- compact = wire.request(- "zk1",- {"type": "compact", "activeSessionId": session_id},- timeout=240,- )- suspend_step("compact", compact)- # The suspension gate: a plain prompt_and_wait on the- # post-compact session must be rejected with the exact TS- # admission error.- plain_after_compact = wire.request(- "zp1",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": "plain prompt while suspended",- },- timeout=120,- )- suspend_step("plain_after_compact", plain_after_compact)- # A steer is a resume site (TS daemon steer passes- # resumeIfIdle: true): admitted, and its turn runs.- steer = wire.request(- "zst",- {- "type": "steer",- "activeSessionId": session_id,- "message": "steer resumes the suspension",- },- timeout=120,- )- suspend_step("steer", steer)- settled = wire.request(- "zwi1",- {"type": "wait_for_idle", "activeSessionId": session_id},- timeout=240,- )- side.evidence_json(flow, "suspension-wait-one-response.json", settled)- plain_after_resume = wire.request(- "zp2",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": "plain prompt after the steer resumed the session",- },- timeout=240,- )- suspend_step("plain_after_resume", plain_after_resume)- # abort re-arms the suspension (TS requestAbort).- abort = wire.request(- "zab",- {"type": "abort", "activeSessionId": session_id},- timeout=120,- )- suspend_step("abort", abort)- plain_after_abort = wire.request(- "zp3",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": "plain prompt while suspended again",- },- timeout=120,- )- suspend_step("plain_after_abort", plain_after_abort)- # resume_queue clears the suspension before answering the- # empty queue with the TS failure.- resume_queue = wire.request(- "zrq",- {"type": "resume_queue", "activeSessionId": session_id},- timeout=120,- )- suspend_step("resume_queue", resume_queue)- plain_after_resume_queue = wire.request(- "zp4",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": "plain prompt after resume_queue cleared the suspension",- },- timeout=240,- )- suspend_step("plain_after_resume_queue", plain_after_resume_queue)- suspension_replies[side.name] = projection- wire.close()- self.copy_sessions(side, flow)- finally:- if prior_settings is None:- settings_path.unlink(missing_ok=True)- else:- settings_path.write_text(prior_settings)- if suspension_replies.get("ts") is not None and suspension_replies.get("rust") is not None:- if suspension_replies["ts"] == suspension_replies["rust"]:- self.record(- flow,- "behavior",- "post-compact suspension lifecycle identical (plain prompts rejected with the TS admission error, steer/resume_queue resume): "- f"{json.dumps(suspension_replies['ts'])[:400]}",- gap=False,- )- else:- self.record(- flow,- "behavior",- f"post-compact suspension lifecycle differs: ts={json.dumps(suspension_replies.get('ts'))[:500]} "- f"rust={json.dumps(suspension_replies.get('rust'))[:500]}",- evidence=[- side.root / flow / "suspension-plain-after-compact.json"- for side in self.sides.values()- ],- )-- # Post-compact goal continuation (the #234 residue): a manual- # daemon `compact` on a session with an ACTIVE goal schedules the- # continuation TS's `compact()` didCompact branch owns- # (`_goalContinuationAwaitsRlmWork ||= !hasQueuedMessages()` ->- # `resumeQueuedWork()` mints the owed goal continuation ->- # `_schedulePostCompactionContinue()` drives it). The goal driver- # never rests on an active goal (each settled turn mints the next- # continuation), so the compact lands mid-turn: the fixture fires- # the compact while the goal-start continuation turn streams (a- # delayed mock reply), the compact aborts it, and both sides must- # then mint and run the post-compact continuation turn — the- # mint's `goal_update` (one continuation used, still active), the- # durable goal-context row, and the continuation's model turn,- # ended by a scripted `goal.complete()` so the run freezes- # deterministically. The wire window from `compaction_start` and- # the mock's request texts are compared byte-equal; `tokensBefore`- # and usage are excluded (per-side token estimates).- goal_wire: dict[str, list | None] = {}- goal_compact: dict[str, dict] = {}- goal_requests: dict[str, list] = {}- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- settings_path = side.agent_dir / "settings.json"- prior_settings = (- settings_path.read_text() if settings_path.exists() else None- )- settings_path.write_text(- json.dumps(- {- "compaction": {"keepRecentTokens": 10, "reserveTokens": 1000},- "autoRefine": {"enabled": False},- }- )- )- try:- wire = B.Wire(side.daemon_socket)- create = wire.request(- "gc1",- {- "type": "create",- "name": "battery-goal-continue",- "config": self.session_config(side),- },- timeout=120,- )- side.evidence_json(flow, "goal-create-response.json", create)- session_id = (- create.get("data", {}).get("activeSessionId")- or create.get("data", {}).get("id")- or ""- )- if create.get("success") is not True:- self.record(- flow,- "protocol",- f"{side.name}: goal-continue session create failed: {json.dumps(create)[:300]}",- )- wire.close()- continue- # An attached client sees the compaction events and the- # continuation turn; the prompting connection carries the- # command responses.- attacher = B.Wire(side.daemon_socket)- attach = attacher.request(- "ga1",- {"type": "attach", "activeSessionId": session_id},- timeout=60,- )- side.evidence_json(flow, "goal-attach-response.json", attach)- # Model-routed queue (the suspension section's pattern):- # the session's mock-1 turns and the compact's summarizer- # draw their scripted replies in order; the dashboard- # status-line model falls through to the default filler.- # The injected goal turn holds ONE representation on both- # sides (the custom row — TS `agent.prompt([customMessage])`,- # the Rust loop admission), so the short-session compact- # cuts whole turns identically and no extra split-turn- # prefix summarizer call exists on either side: the- # single ordered queue serves every mock-1 request.- side.mock.set_responses(- [{"text": "statusline filler"}],- queues=[- {- "name": "goal-continue",- "matchModels": ["mock-1"],- "responses": [- {"text": "seed reply one"},- {"text": "seed reply two"},- {"text": "seed reply three"},- # The goal-start continuation turn: the- # reply is held mid-stream so the compact- # lands while the turn is in flight (TS- # compact() aborts first).- {"text": "goal turn reply", "delayMs": 1500},- # The compact's summarizer.- {"text": "the post-compact goal continuation summary"},- # The post-compact continuation turn:- # the scripted kernel call completes the- # goal, so the driver freezes after one- # continuation (no infinite loop).- {- "toolCall": {- "name": "ipython",- "arguments": {- "code": "import goal; await goal.complete()"- },- }- },- {"text": "final reply after the goal completed"},- ],- }- ],- )- # Several turns of history: the compaction's cut must- # land with messages to summarize on both sides (a- # one-turn session skips "Session is too short to- # compact", which is the suspension scenario's shape).- seed_text = (- "goal continue seed turn with enough history for the "- "compaction to summarize "- ) * 8- for index in range(1, 4):- seed = wire.request(- f"gs{index}",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": f"{seed_text}turn {index}",- },- timeout=240,- )- side.evidence_json(flow, f"goal-seed-{index}-response.json", seed)- attacher.drain(3.0)- attacher.events.clear()- # The mark rides before the goal turn: its request, the- # compact's summarizer, and the continuation's model turn- # are the requests past it.- mark = len(side.mock.requests())- # `/goal <objective>`: the session command starts the- # goal and its continuation turn runs immediately (fire- # without waiting; the reply is delayed mid-stream).- goal_start = wire.request(- "gp1",- {- "type": "prompt",- "activeSessionId": session_id,- "message": "/goal land the post-compact continuation parity row",- },- timeout=120,- )- side.evidence_json(flow, "goal-start-response.json", goal_start)- # Let the goal-start continuation turn reach the provider- # (the delayed reply holds it mid-turn), then compact: the- # abort cuts the in-flight turn and the compaction runs.- time.sleep(0.6)- compact = wire.request(- "gk1",- {"type": "compact", "activeSessionId": session_id},- timeout=240,- )- side.evidence_json(flow, "goal-compact-response.json", compact)- # The compact response compares honestly: both sides- # cut whole turns (the injected turn holds one- # representation), so both summarizers draw the same- # scripted summary. `tokensBefore` stays a presence check- # (each side's own pre-compaction estimate).- goal_compact[side.name] = {- "success": compact.get("success"),- "error": compact.get("error"),- "hasTokensBefore": "tokensBefore" in (compact.get("data") or {}),- "summary": (compact.get("data") or {}).get("summary"),- }- # The post-compaction continue drives the continuation- # turn; settle it (the goal-complete tool call and the- # post-tool reply run inside one turn).- settled = wire.request(- "gwi1",- {"type": "wait_for_idle", "activeSessionId": session_id},- timeout=240,- )- side.evidence_json(flow, "goal-wait-idle-response.json", settled)- attacher.drain(8.0)- side.evidence_json(flow, "goal-attach-events.json", attacher.events)- goal_wire[side.name] = self.goal_continue_projection(attacher.events)- side.evidence_json(flow, "goal-wire-projection.json", goal_wire[side.name])- # The session-model requests only: the daemon's- # status-line model (its own id) fires at turn- # boundaries outside this differential's surface.- goal_requests[side.name] = [- {- "model": request.get("body", {}).get("model"),- "last_user_text": self.last_user_text(request),- }- for request in self.new_mock_requests(side, mark)- if request.get("body", {}).get("model") == "mock-1"- ]- side.evidence_json(flow, "goal-mock-requests.json", goal_requests[side.name])- wire.close()- attacher.close()- self.copy_sessions(side, flow)- finally:- if prior_settings is None:- settings_path.unlink(missing_ok=True)- else:- settings_path.write_text(prior_settings)- if goal_wire.get("ts") is not None and goal_wire.get("rust") is not None:- if goal_wire["ts"] == goal_wire["rust"] and goal_wire["ts"]:- self.record(- flow,- "behavior",- "post-compact goal continuation identical (compaction pair, minted goal_update, goal-context row, continuation turn, completion): "- f"{json.dumps(goal_wire['ts'])[:400]}",- gap=False,- )- else:- self.record(- flow,- "behavior",- f"post-compact goal continuation differs: ts={json.dumps(goal_wire.get('ts'))[:600]} "- f"rust={json.dumps(goal_wire.get('rust'))[:600]}",- evidence=[- side.root / flow / "goal-wire-projection.json"- for side in self.sides.values()- ],- )- if goal_requests.get("ts") == goal_requests.get("rust") and goal_requests.get("ts"):- self.record(- flow,- "behavior",- "post-compact goal continuation model requests identical (goal-start turn, summarizer, continuation prompt): "- f"{json.dumps(goal_requests['ts'])[:400]}",- gap=False,- )- else:- self.record(- flow,- "behavior",- f"post-compact goal continuation model requests differ: ts={json.dumps(goal_requests.get('ts'))[:600]} "- f"rust={json.dumps(goal_requests.get('rust'))[:600]}",- evidence=[- side.root / flow / "goal-mock-requests.json"- for side in self.sides.values()- ],- )- if goal_compact.get("ts") == goal_compact.get("rust"):- self.record(- flow,- "behavior",- "post-compact goal compact response identical (success, tokensBefore present): "- f"{json.dumps(goal_compact['ts'])[:200]}",- gap=False,- )- else:- self.record(- flow,- "behavior",- f"post-compact goal compact responses differ: ts={json.dumps(goal_compact.get('ts'))[:300]} "- f"rust={json.dumps(goal_compact.get('rust'))[:300]}",- evidence=[- side.root / flow / "goal-compact-response.json"- for side in self.sides.values()- ],- )-- # Durable compaction-entry wire-diff: both sides write a- # `compaction` row to the session file (TS `appendCompaction`). The- # compared shape is the TS `CompactionEntry` record minus- # per-session values (ids, timestamps, `firstKeptEntryId` —- # separate id spaces). `tokensBefore` is the probe-measured- # pre-compaction estimate, `fromHook` the TS built-in origin- # (false), and `harnessDigest` the `_harnessDigest()` snapshot- # attached at every compaction commit (same harness dirs, same- # scripted turns, same empty harness state on both sides, so the- # rendered digest must match byte-for-byte) — all must match.- durable_rows: dict[str, list[dict]] = {}- for side_name in ("ts", "rust"):- side = self.sides[side_name]- rows: list[dict] = []- sessions_dir = side.root / flow / "sessions"- for path in sorted(sessions_dir.glob("*.jsonl")) if sessions_dir.exists() else []:- # The goal-continue session is excluded: its compaction- # runs mid-goal-turn on session-specific seed text (the- # wire window and compact-response comparisons above own- # that session's compacted surface).- if "battery-goal-continue" in path.read_text():- continue- for line in path.read_text().splitlines():- try:- entry = json.loads(line)- except json.JSONDecodeError:- continue- if entry.get("type") == "compaction":- rows.append(- {- key: entry.get(key)- for key in (- "summary",- "tokensBefore",- "details",- "fromHook",- "usage",- "harnessDigest",- )- }- )- durable_rows[side_name] = sorted(rows, key=lambda row: json.dumps(row, sort_keys=True))- if durable_rows["ts"] and durable_rows["rust"]:- if durable_rows["ts"] == durable_rows["rust"]:- self.record(- flow,- "behavior",- "durable compaction entries identical (tokensBefore, fromHook, details, usage, harnessDigest; normalized ids/timestamps): "- f"{json.dumps(durable_rows['ts'])[:300]}",- gap=False,- )- else:- self.record(- flow,- "behavior",- f"durable compaction entries differ: ts={json.dumps(durable_rows['ts'])[:400]} "- f"rust={json.dumps(durable_rows['rust'])[:400]}",- evidence=[- self.sides[name].root / flow / "sessions"- for name in ("ts", "rust")- ],- )-- # Kernel-notice differential (the #227 residue): a session whose- # kernel is running (one scripted ipython tool call) appends the- # hidden `ipython_state` notice row after EVERY compaction, so a- # back-to-back second `compact` wire command with nothing in- # between runs again (update mode) instead of skipping "Already- # compacted". Both sides must keep the kernel through compaction,- # land the notice row on the durable branch after each compaction- # entry, and succeed on the second back-to-back compact.- self._kernel_notice_scenario(- flow,- {- "name": "battery-ipython-notice",- "queue": "notice",- "marker": "notice_var",- "evidence": "notice",- # One tool-call turn boots the kernel explicitly (the- # #227 residue verifier: the notice follows a kernel the- # model itself started), then a history turn the first- # compaction summarizes.- "settle_seconds": 0.0,- "responses": [- {- "toolCall": {- "name": "ipython",- "arguments": {"code": "notice_var = 'kept through compaction'"},- }- },- {"text": "kernel started"},- {"text": "history turn the first compaction summarizes"},- # The first compaction is a SPLIT on both sides (the- # tool-call turn pushes the keep-recent walk mid-turn),- # so its two concurrent summarizer calls pop these- # next two entries in arrival order: tokio::join /- # Promise.all races the shared queue, and which- # response becomes the history summary (embedded in- # the second compact's <previous-summary>) is a coin- # flip per side. Identical texts make the draw- # unobservable — the scenario's purpose is the notice- # row, not the summary content (same de-flake- # treatment as the #227 split differential).- {"text": "the notice compaction summary"},- {"text": "the notice compaction summary"},- ],- "turns": [- ("np1", "start the kernel and define notice_var"),- ("np2", "history turn for the summary"),- ],- },- )- # The prewarm sibling (the #230 residue): a session with NO ipython- # tool use at all still has a running kernel — TS prewarms at daemon- # session creation, and the Rust daemon now does too — so the- # kernel-less case lands the notice rows identically on both sides.- # The settle window after create lets both products finish the- # background boot (purely internal; TS races it the same way).- self._kernel_notice_scenario(- flow,- {- "name": "battery-ipython-prewarm",- "queue": "prewarm-notice",- "marker": "prewarm history turn",- "evidence": "prewarm-notice",- "settle_seconds": 15.0,- "responses": [- {"text": "prewarm history turn one noted"},- {"text": "prewarm history turn two noted"},- {"text": "the prewarm first compaction summary"},- {"text": "the prewarm second compaction summary"},- ],- "turns": [- ("pw1", "prewarm history turn one for the summary"),- ("pw2", "prewarm history turn two for the summary"),- ],- },- )-- def _kernel_notice_scenario(self, flow: str, scenario: dict) -> None:- """One kernel-notice differential (`ipython_state` after every- compaction a running kernel survives), both sides.-- The scenario drives one daemon session per side: scripted responses- through a model-routed queue (the session-model calls draw their- responses in order while the daemon status-line model falls through- to the default queue — background calls must not shift the scripted- cursors), two `compact` wire commands back-to-back, and the durable- notice rows compared by envelope plus the persistence sentence (the- kernel-namespace detail is side-dependent). The second compact must- run again (update mode, `<previous-summary>` in its summarizer- request) instead of skipping "Already compacted" — the notice row- keeps the session branch from ending on the compaction entry.- """- notice: dict[str, dict] = {}- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- settings_path = side.agent_dir / "settings.json"- prior_settings = (- settings_path.read_text() if settings_path.exists() else None- )- settings_path.write_text(- json.dumps(- {- "compaction": {"keepRecentTokens": 10, "reserveTokens": 1000},- "autoRefine": {"enabled": False},- }- )- )- try:- wire = B.Wire(side.daemon_socket)- create = wire.request(- scenario["name"][:4] + "-c1",- {- "type": "create",- "name": scenario["name"],- "config": self.session_config(side),- },- timeout=120,- )- side.evidence_json(flow, f'{scenario["evidence"]}-create-response.json', create)- session_id = (- create.get("data", {}).get("activeSessionId")- or create.get("data", {}).get("id")- or ""- )- if create.get("success") is not True:- self.record(- flow,- "protocol",- f'{side.name}: {scenario["name"]} session create failed: {json.dumps(create)[:300]}',- )- wire.close()- continue- # The prewarm settle window: a scenario whose kernel starts- # in the background at creation waits it out on both sides- # (a no-tool-use turn never joins the boot like a tool call- # does).- if scenario["settle_seconds"]:- time.sleep(scenario["settle_seconds"])- side.mock.set_responses(- [{"text": "statusline filler"}],- queues=[- {- "name": scenario["queue"],- "matchModels": ["mock-1"],- "responses": scenario["responses"],- }- ],- )- for request_id, message in scenario["turns"]:- turn = wire.request(- request_id,- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": message,- },- timeout=240,- )- side.evidence_json(- flow,- f'{scenario["evidence"]}-turn-{request_id}-response.json',- turn,- )- first = wire.request(- f'{scenario["evidence"]}-k1',- {"type": "compact", "activeSessionId": session_id},- timeout=240,- )- side.evidence_json(flow, f'{scenario["evidence"]}-compact-one-response.json', first)- # Back-to-back: nothing between the two compacts.- mark = len(side.mock.requests())- second = wire.request(- f'{scenario["evidence"]}-k2',- {"type": "compact", "activeSessionId": session_id},- timeout=240,- )- side.evidence_json(flow, f'{scenario["evidence"]}-compact-two-response.json', second)- wire.close()- # Only the session-model requests (the scenario queue):- # background status-line calls fall through to the default- # queue and differ in count between the products.- second_requests = [- request- for request in self.new_mock_requests(side, mark)- if request.get("queue") == scenario["queue"]- ]- side.evidence_json(- flow,- f'{scenario["evidence"]}-second-requests.json',- second_requests,- )- # Private sessions copy: the shared `sessions` evidence- # belongs to the durable wire-diff above, and this- # session's tool rows must not pollute it.- dst = side.root / flow / f'{scenario["evidence"]}-sessions'- if dst.exists():- shutil.rmtree(dst)- src = side.sessions_dir()- if src.exists():- shutil.copytree(src, dst)- rows = []- ordered_tail = []- for path in sorted(dst.glob("*.jsonl")) if dst.exists() else []:- body = path.read_text()- # The daemon prewarms its kernel, so EVERY session in- # the copy may carry notice rows; scope to this- # scenario's session (the marker only its turns carry).- if scenario["marker"] not in body:- continue- for line in body.splitlines():- try:- entry = json.loads(line)- except json.JSONDecodeError:- continue- entry_type = entry.get("type")- ordered_tail.append(entry_type)- if (- entry_type == "custom_message"- and entry.get("customType") == "ipython_state"- ):- content = entry.get("content")- if isinstance(content, list):- content = "".join(- block.get("text", "")- for block in content- if isinstance(block, dict)- )- rows.append(- {- "customType": entry.get("customType"),- "display": entry.get("display"),- "content": content,- }- )- notice[side.name] = {- "first_success": first.get("success") is True,- "second": second,- "second_success": second.get("success") is True,- "notice_rows": rows,- "ordered_tail": ordered_tail[-6:],- "second_requests": second_requests,- }- finally:- if prior_settings is None:- settings_path.unlink(missing_ok=True)- else:- settings_path.write_text(prior_settings)- if notice.get("ts") and notice.get("rust"):-- def notice_shape(rows: list) -> list:- shaped = []- for row in rows:- content = row.get("content") or ""- shaped.append(- {- "customType": row.get("customType"),- "display": row.get("display"),- # The kernel-namespace detail (pruned names,- # live names) is side-dependent: compare the- # row envelope and the persistence sentence.- "content_shape": content.split("available.")[0] + "available.",- }- )- return shaped-- second_ok = notice["ts"]["second_success"] and notice["rust"]["second_success"]- shapes = {- name: notice_shape(notice[name]["notice_rows"]) for name in ("ts", "rust")- }- requests = {- name: [- block.get("text", "")- if isinstance(block, dict)- else ""- for request in notice[name]["second_requests"]- for message_entry in (request.get("body", {}).get("messages") or [])- if message_entry.get("role") == "user"- for block in (- message_entry.get("content")- if isinstance(message_entry.get("content"), list)- else [{"text": message_entry.get("content", "")}]- )- ]- for name in ("ts", "rust")- }- if (- second_ok- and len(shapes["ts"]) == 2- and shapes["ts"] == shapes["rust"]- and requests["ts"] == requests["rust"]- and any(- "<previous-summary>" in text- for text in requests["ts"]- )- ):- self.record(- flow,- "behavior",- f'{scenario["name"]} parity: ipython_state row after each compaction, back-to-back second compact runs (update mode): '- + json.dumps(shapes["ts"])[:300],- gap=False,- )- else:- self.record(- flow,- "behavior",- f'{scenario["name"]} differential differs: '- f"second_compact ts={notice['ts']['second_success']} rust={notice['rust']['second_success']} "- f"row_counts ts={len(shapes['ts'])} rust={len(shapes['rust'])} "- f"rows ts={json.dumps(shapes['ts'])[:400]} rust={json.dumps(shapes['rust'])[:400]} "- f"second-requests-equal={requests['ts'] == requests['rust']} "- f"ts={json.dumps(requests['ts'])[:150]} rust={json.dumps(requests['rust'])[:150]}",- evidence=[- self.sides[name].root / flow / f'{scenario["evidence"]}-compact-two-response.json'- for name in ("ts", "rust")- ],- )-- def f8_resume(self) -> None:- """Exit + resume: headless session persisted, then continued in both."""- flow = "f8_resume"- recs = {}- for side in (self.sides["ts"], self.sides["rust"]):- side.mock.set_responses([{"text": "resumed turn reply"}])- mark = len(side.mock.requests())- rec = B.run_cmd(- [- side.binary,- "-p",- "--daemon-socket",- str(side.daemon_socket),- "--provider",- "prime-inference",- "--model",- "mock-1",- "--offline",- "-c",- "Continue this session",- ],- side.env,- side.work_dir,- timeout=240,- )- recs[side.name] = rec- side.evidence_json(flow, "continue-cmd.json", rec)- side.evidence_json(flow, "mock-requests.json", self.new_mock_requests(side, mark))- self.copy_sessions(side, flow)-- # B-11 differential: both sides must refuse to continue a session- # that is already active in the daemon, with the same message shape- # (the TS print path fails the daemon create with- # SessionAlreadyActiveError; the Rust print path guards identically).- def refused(rec):- return (- rec["exit_code"] == 1- and "Session is already active in " in rec["stdout"] + rec["stderr"]- )-- def refusal_id(rec):- match = re.search(- r"Session is already active in ([0-9a-f]+):", rec["stdout"] + rec["stderr"]- )- return match.group(1) if match else None-- if refused(recs["ts"]) and refused(recs["rust"]):- self.record(- flow,- "behavior",- f"print '-c' refuses a session active in the daemon on both sides: "- f"{refusal_id(recs['ts'])} (ts) vs {refusal_id(recs['rust'])} (rust)",- gap=False,- )- else:- for name, rec in recs.items():- if refused(rec):- continue- detail = (rec["stdout"] + rec["stderr"]).strip()[:200]- self.record(- flow,- "behavior",- f"{name}: print '-c' did not refuse the active session (exit={rec['exit_code']}): {detail}",- evidence=f"{name}/{flow}/continue-cmd.json",- )-- # Interactive resume of the same session.- for side in (self.sides["ts"], self.sides["rust"]):- files = side.session_files()- if files:- session = f"{self.runid}-f8-{side.name}"- argv = [- side.binary,- "--daemon-socket",- str(side.daemon_socket),- "--resume",- str(files[-1]),- "--offline",- ]- B.tmux_launch(session, argv, side.env, side.work_dir)- frame = B.tmux_wait_text(session, "resumed turn reply|battery hello|>", timeout=30)- side.evidence(flow, "resume-frame.txt", frame)- B.tmux_kill(session)- self.session_shape_diff(flow)-- def f9_agents_view(self) -> None:- """Agents view: section grouping over a scripted roster (running live- session, idle live session, saved-catalog session), the open action- attaching to the selected running session, and frame captures at two- terminal sizes for the cross-side frame diff."""- flow = "f9_agents_view"- frames: dict[str, dict[str, str]] = {}- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- # The agents view lists the whole daemon universe, so f9 starts- # from a clean one: restart the side daemon and wipe its session- # files, leaving only the sessions f9 creates below.- self.reset_side_sessions(side)- frames[side.name] = {}- # Idle live session: one completed exchange.- side.mock.set_responses([{"text": "f9 idle reply"}])- wire = B.Wire(side.daemon_socket)- create = wire.request(- "c9i",- {"type": "create", "name": "battery-f9-idle", "config": self.session_config(side)},- timeout=120,- )- if create.get("success") is not True:- self.record(flow, "protocol", f"{side.name}: daemon create failed: {json.dumps(create)[:300]}")- wire.close()- continue- idle_id = (create.get("data", {}).get("activeSessionId") or create.get("data", {}).get("id") or "")- idle_prompt = wire.request(- "p9i",- {"type": "prompt_and_wait", "activeSessionId": idle_id, "message": "f9 idle prompt"},- timeout=240,- )- side.evidence_json(flow, "idle-prompt-response.json", idle_prompt)- wire.close()- # A saved-catalog session: a headless print run whose file- # remains after the run (the Inactive section source).- print_rec = B.run_cmd(- [- side.binary,- "-p",- "--daemon-socket",- str(side.daemon_socket),- "--provider",- "prime-inference",- "--model",- "mock-1",- "--offline",- "f9 inactive prompt",- ],- side.env,- side.work_dir,- timeout=240,- )- side.evidence_json(flow, "inactive-print.json", print_rec)- # Busy live session: an in-flight delayed turn keeps the row- # Running while the view frames are captured. The idle turn's- # post-turn requests must settle first so the delayed script- # can only ever apply to the busy session's requests.- self.settle_mock(side)- side.mock.set_responses([{"text": "f9 busy reply", "delayMs": 25000}])- wire = B.Wire(side.daemon_socket)- create = wire.request(- "c9b",- {"type": "create", "name": "battery-f9-busy", "config": self.session_config(side)},- timeout=120,- )- if create.get("success") is not True:- self.record(flow, "protocol", f"{side.name}: busy create failed: {json.dumps(create)[:300]}")- wire.close()- continue- busy_id = (create.get("data", {}).get("activeSessionId") or create.get("data", {}).get("id") or "")- wire.send_command("p9b", {"type": "prompt_and_wait", "activeSessionId": busy_id, "message": "f9 busy prompt"})- wire.close()- if not self.wait_roster_status(side, busy_id, "running", timeout=15):- self.record(- flow,- "behavior",- f"{side.name}: the busy session never reached Running on the roster",- )- continue- # TS suppresses the agents view while onboarding is pending- # (`shouldOpenAgentsViewForDaemonInteractive`); mark the side- # onboarded so both products open the view directly.- settings_path = side.agent_dir / "settings.json"- settings = json.loads(settings_path.read_text()) if settings_path.exists() else {}- settings["onboardingShown"] = True- settings_path.write_text(json.dumps(settings))- # The view over the scripted roster, captured at both sizes.- view_session = f"{self.runid}-f9-{side.name}"- # No --offline: it disables telemetry for the invocation, and TS- # refuses to attach an active agent across that telemetry mismatch.- argv = [side.binary, "agents", "--daemon-socket", str(side.daemon_socket)]- B.tmux_launch(view_session, argv, side.env, side.work_dir)- # Wait for the catalog-fed Inactive section, not just any- # heading: the saved catalog loads asynchronously, and the first- # capture must show the full roster (an early "Running (" match- # captured a pre-catalog frame; run 20260919T084345Z).- frame120 = B.tmux_wait_text(view_session, "Inactive \(|No sessions", timeout=45)- side.evidence(flow, "01-agents-view-120x36.txt", frame120)- frames[side.name]["120x36"] = frame120- B.tmux_resize(view_session, (220, 50))- time.sleep(1.0)- frame220 = B.tmux_capture(view_session)- side.evidence(flow, "02-agents-view-220x50.txt", frame220)- frames[side.name]["220x50"] = frame220- B.tmux_resize(view_session, (120, 36))- time.sleep(0.5)- # Section grouping: each scripted session sits under its section.- sections = self.parse_agents_view_sections(frame120)- section_ok = True- for section, marker in (- ("Running", "battery-f9-busy"),- ("Idle", "battery-f9-idle"),- ("Inactive", "f9 inactive prompt"),- ):- rows = sections.get(section, [])- if not any(marker in row for row in rows):- section_ok = False- self.record(- flow,- "behavior",- f"{side.name}: '{marker}' is not grouped under the {section} section (sections: {json.dumps(sections)[:400]})",- evidence=side.root / flow / "01-agents-view-120x36.txt",- )- if section_ok:- self.record(- flow,- "behavior",- f"{side.name}: agents view groups the roster into Running/Idle/Inactive sections with the scripted sessions in place",- gap=False,- )- # Search-filter surface: typing narrows the roster to the- # match, Escape clears the query and restores the roster, and a- # transcript-only phrase still finds its session.- B.tmux_send(view_session, "busy", enter=False)- time.sleep(1.0)- filtered = B.tmux_capture(view_session)- side.evidence(flow, "03-filtered-roster-120x36.txt", filtered)- frames[side.name]["filtered-120x36"] = filtered- if "battery-f9-busy" not in filtered:- self.record(- flow,- "behavior",- f"{side.name}: the 'busy' query lost its match from the filtered roster",- evidence=side.root / flow / "03-filtered-roster-120x36.txt",- )- for hidden_marker in ("battery-f9-idle", "f9 inactive prompt"):- if hidden_marker in filtered:- self.record(- flow,- "behavior",- f"{side.name}: the 'busy' query did not hide '{hidden_marker}'",- evidence=side.root / flow / "03-filtered-roster-120x36.txt",- )- B.tmux_send(view_session, "Escape", enter=False)- time.sleep(1.0)- cleared = B.tmux_capture(view_session)- side.evidence(flow, "04-cleared-roster-120x36.txt", cleared)- for restored_marker in ("battery-f9-busy", "battery-f9-idle", "f9 inactive prompt"):- if restored_marker not in cleared:- self.record(- flow,- "behavior",- f"{side.name}: clearing the query did not restore '{restored_marker}'",- evidence=side.root / flow / "04-cleared-roster-120x36.txt",- )- # A quoted phrase that only appears as a saved transcript- # message (not as a name or first prompt) matches through the- # allMessagesText corpus.- B.tmux_send(view_session, '"f9 idle reply"', enter=False)- time.sleep(1.0)- transcript = B.tmux_capture(view_session)- side.evidence(flow, "05-transcript-filtered-120x36.txt", transcript)- frames[side.name]["transcript-120x36"] = transcript- if "battery-f9-idle" not in transcript:- self.record(- flow,- "behavior",- f"{side.name}: a transcript-only phrase did not find its session",- evidence=side.root / flow / "05-transcript-filtered-120x36.txt",- )- if "battery-f9-busy" in transcript:- self.record(- flow,- "behavior",- f"{side.name}: the transcript phrase left an unrelated row in the roster",- evidence=side.root / flow / "05-transcript-filtered-120x36.txt",- )- B.tmux_send(view_session, "Escape", enter=False)- time.sleep(0.5)- # Attach target: search down to the running row, open it, and the- # in-flight reply must render in the attached session UI.- B.tmux_send(view_session, "busy")- time.sleep(1.0)- B.tmux_send(view_session, "Enter", enter=False)- attached = B.tmux_wait_text(view_session, "f9 busy reply", timeout=60)- side.evidence(flow, "03-attached-session.txt", attached)- pane_state = B.tmux(- "list-panes", "-t", view_session, "-F", "#{pane_dead} #{pane_dead_status}", check=False- ).stdout.strip()- if pane_state.startswith("1"):- self.record(- flow,- "behavior",- f"{side.name}: opening the Running row exited the view instead of attaching ({pane_state})",- evidence=side.root / flow / "03-attached-session.txt",- )- else:- self.record(- flow,- "behavior",- f"{side.name}: opening the Running row attached to the live session and its in-flight reply rendered",- gap=False,- )- # Selection persistence under live roster churn (Kevin dogfood- # 2026-09-21: "it keeps teleporting me up — especially when- # subagents are being spawned"): a fresh view, the selection- # arrowed onto a session row, then the roster churns through a- # real busy flip (a live prompt on the idle session). The- # highlight must stay on the SAME session row across the- # rebuild-and-resort; the selected row is the one line in the- # pane that carries a background escape (48;...).- churn_session = f"{self.runid}-f9sel-{side.name}"- B.tmux_launch(- churn_session,- [side.binary, "agents", "--daemon-socket", str(side.daemon_socket)],- side.env,- side.work_dir,- )- B.tmux_wait_text(churn_session, "Idle \(|No sessions", timeout=45)- time.sleep(1.0)- B.tmux_send(churn_session, "Down", enter=False)- time.sleep(1.0)- pre_churn = B.tmux("capture-pane", "-e", "-p", "-t", churn_session).stdout- side.evidence(flow, "06-selection-pre-churn-ansi.txt", pre_churn)- session_markers = ["battery-f9-busy", "battery-f9-idle", "f9 inactive prompt"]- selected_pre = self.selected_row_name(pre_churn, session_markers)- if not selected_pre:- self.record(- flow,- "behavior",- f"{side.name}: no selected row found in the churn view before the flip",- evidence=side.root / flow / "06-selection-pre-churn-ansi.txt",- )- # Live churn: the idle session flips busy through a delayed- # prompt, and the roster pushes re-sort its row into the- # Running section while the view is open.- side.mock.set_responses([{"text": "f9 churn reply", "delayMs": 60000}])- wire = B.Wire(side.daemon_socket)- wire.send_command(- "p9c",- {"type": "prompt_and_wait", "activeSessionId": idle_id, "message": "f9 churn prompt"},- )- wire.close()- if not self.wait_roster_status(side, idle_id, "running", timeout=15):- self.record(- flow,- "behavior",- f"{side.name}: the churn prompt never reached Running on the roster",- )- time.sleep(1.5)- post_churn = B.tmux("capture-pane", "-e", "-p", "-t", churn_session).stdout- side.evidence(flow, "07-selection-post-churn-ansi.txt", post_churn)- selected_post = self.selected_row_name(post_churn, session_markers)- if selected_pre and selected_post and selected_post != selected_pre:- self.record(- flow,- "behavior",- f"{side.name}: the selection teleported during roster churn (was {selected_pre!r}, now {selected_post!r})",- evidence=side.root / flow / "07-selection-post-churn-ansi.txt",- )- elif selected_pre and selected_post:- self.record(- flow,- "behavior",- f"{side.name}: the selection stayed on the same session row through live roster churn ({selected_post!r})",- gap=False,- )- B.tmux_kill(churn_session)- B.tmux_kill(view_session)- # Leave the mock script plain for the flows that follow (f11's- # healthy exchange expects the HELLO_TEXT response).- side.mock.set_responses([{"text": HELLO_TEXT}])- # Frame diff: same scripted roster, same size, TS vs Rust — the- # unfiltered view and the filtered search results.- for size_label in ("120x36", "220x50", "filtered-120x36", "transcript-120x36"):- ts_frame = frames.get("ts", {}).get(size_label)- rs_frame = frames.get("rust", {}).get(size_label)- if ts_frame is None or rs_frame is None:- self.record(flow, "visual", f"missing frames for the {size_label} diff (ts={'y' if ts_frame else 'n'} rust={'y' if rs_frame else 'n'})")- continue- ts_norm = self.normalize_agents_view_frame(ts_frame, self.sides["ts"])- rs_norm = self.normalize_agents_view_frame(rs_frame, self.sides["rust"])- if ts_norm == rs_norm:- self.record(- flow,- "visual",- f"agents view frames identical at {size_label} (normalized: paths, ids, ages)",- gap=False,- )- else:- diff_path = self.sides["ts"].root / flow / f"frame-diff-{size_label}.txt"- diff_path.parent.mkdir(parents=True, exist_ok=True)- diff_path.write_text(- f"--- ts ({size_label})\n{ts_frame}\n+++ rust ({size_label})\n{rs_frame}"- )- self.record(- flow,- "visual",- f"agents view frames differ at {size_label} (see frame-diff-{size_label}.txt)",- evidence=diff_path,- )-- def parse_agents_view_sections(self, frame: str) -> dict[str, list[str]]:- """Map each rendered section heading to its row lines."""- sections: dict[str, list[str]] = {}- current = None- for line in frame.splitlines():- match = re.match(r"\s*(Running|Idle|Inactive) \(\d+\)", line)- if match:- current = match.group(1)- sections.setdefault(current, [])- continue- if current is not None and line.strip():- sections[current].append(line)- return sections-- def normalize_agents_view_frame(self, frame: str, side: B.Side) -> str:- """Erase side-varying text (paths, ids, ages, versions) so equal- layout and content compare equal."""- text = frame.rstrip("\n")- # The splash ~-compresses paths; expand so the absolute side paths match.- text = text.replace("~/", str(Path.home()) + "/")- text = text.replace(str(side.root), "<run>")- text = text.replace(str(side.agent_dir), "<agent>")- text = text.replace(str(side.work_dir), "<work>")- text = re.sub(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", "<uuid>", text)- text = re.sub(r"(?<![a-zA-Z]) *\d+[smhd](?![a-zA-Z])", " <age>", text)- text = re.sub(r"\bv\d+\.\d+[^ ]*", "<version>", text)- text = re.sub(r"\$0\.\d\d", "<cost>", text)- # The animated running-row icon and the per-build version string.- text = re.sub("[\u25c7\u25c8\u25c6]", "<pulse>", text)- text = re.sub(r"v\d+\.\d+\.\d+", "<version>", text)- return text-- def reset_side_sessions(self, side: B.Side) -> None:- """Restart the side daemon with no sessions: stop it, delete the- session files, start a fresh one on the same socket."""- try:- wire = B.Wire(side.daemon_socket)- wire.send_command("sd9", {"type": "shutdown"})- wire.close()- except (OSError, EOFError):- pass- side.stop_daemon()- time.sleep(1.0)- sessions = side.sessions_dir()- if sessions.exists():- shutil.rmtree(sessions)- side.start_daemon()-- def settle_mock(self, side: B.Side, quiet_s: float = 2.0, timeout: float = 20.0) -> None:- """Wait until the side's mock has gone `quiet_s` seconds with no new- request, so post-turn status-line requests have landed before the- flow swaps the response script (a swapped script resets the mock's- response cursor, and a delayed response would hang a status-line- request and hold the session busy)."""- deadline = time.time() + timeout- last_count = len(side.mock.requests())- last_change = time.time()- while time.time() < deadline:- time.sleep(0.5)- count = len(side.mock.requests())- if count != last_count:- last_count = count- last_change = time.time()- elif time.time() - last_change >= quiet_s:- return-- def selected_row_name(self, frame: str, markers: list[str]) -> str:- """Which session row the pane highlights: the selected row is the- one line carrying a background escape (the selection background- paints exactly that row). Returns the marker the highlighted line- contains, or "" when nothing is highlighted."""- for line in frame.splitlines():- if "\x1b[48;" in line or "\x1B[48;" in line:- for marker in markers:- if marker in line:- return marker- return ""-- def wait_roster_status(self, side: B.Side, active_session_id: str, status: str, timeout: float = 15.0) -> bool:- """Poll the roster snapshot until the session reaches `status`."""- deadline = time.time() + timeout- while time.time() < deadline:- try:- wire = B.Wire(side.daemon_socket)- except (OSError, EOFError):- time.sleep(0.5)- continue- try:- response = wire.request("rp", {"type": "roster_subscribe"}, timeout=10)- finally:- wire.close()- if response.get("success") is True:- for entry in (response.get("data", {}).get("roster") or []):- if (entry.get("summary", {}).get("activeSessionId") == active_session_id- and entry.get("status") == status):- return True- time.sleep(0.5)- return False-- def f12_scale_resume(self) -> None:- """HEAVY (opt-in: --flows f12_scale_resume + PA_BATTERY_HEAVY=1):- transcript-scale interactive `--resume` -> ready, Rust vs TS. The- corpus is deterministic (scripts/battery/scale_corpus.py): a- PA_BATTERY_HEAVY_TURNS-turn session (default 5,000 = 15,261- transcript rows) of user/assistant/ipython-tool turns. Ready means- the interactive frame a user would type at: ingest of the resume- snapshot plus the first full layout, in seconds — the regression- gate for the replay path."""- import scale_corpus as SC-- flow = "f12_scale_resume"- if os.environ.get("PA_BATTERY_HEAVY") != "1":- self.record(- flow,- "perf",- "skipped: set PA_BATTERY_HEAVY=1 (and pass --flows f12_scale_resume) to run the heavy-scale resume gate",- gap=False,- )- return- turns = int(os.environ.get("PA_BATTERY_HEAVY_TURNS", "5000"))- timeout_s = float(os.environ.get("PA_BATTERY_HEAVY_TIMEOUT", "300"))- corpus = SC.corpus_path(turns, self.run_dir, str(self.run_dir))- rows = SC.corpus_rows(turns)- ready: dict[str, float | None] = {}- for side in (self.sides["ts"], self.sides["rust"]):- self.perf_onboard(side)- socket = side.root / flow / "scale.sock"- rec = P.measure_resume(- side,- f"{self.runid}-scale-{side.name}",- socket,- corpus,- timeout_s,- )- P.stop_perf_daemon(socket)- side.evidence_json(flow, "resume.json", rec)- ready[side.name] = rec["ready_s"]- if rec["ready_s"] is None:- self.record(- flow,- "perf",- f"{side.name}: {turns}-turn ({rows}-row) interactive resume never reached ready within {timeout_s:.0f}s",- evidence=side.root / flow / "resume.json",- )- else:- self.record(- flow,- "perf",- f"{side.name}: {turns}-turn ({rows}-row) interactive resume ready in {rec['ready_s']}s "- f"(first frame {rec['first_frame_s']}s)",- gap=False,- )- ts_ready = ready.get("ts")- rs_ready = ready.get("rust")- if ts_ready is not None and rs_ready is not None:- ratio = rs_ready / ts_ready- detail = (- f"scale resume: rust {rs_ready:.3f}s vs ts {ts_ready:.3f}s for {rows} rows "- f"(ratio {ratio:.2f}, thresholds: ratio <= {SCALE_RESUME_MAX_RATIO}, rust <= {SCALE_RESUME_MAX_READY_S}s)"- )- if rs_ready <= SCALE_RESUME_MAX_READY_S and ratio <= SCALE_RESUME_MAX_RATIO:- self.record(flow, "perf", detail, gap=False)- else:- self.record(flow, "perf", f"REGRESSION {detail}", evidence=self.run_dir / flow)- else:- self.record(- flow,- "perf",- "scale-resume thresholds not evaluable: a side never reached ready",- gap=True,- )-- def f11_provider_failure(self) -> None:- """Kill the mock provider mid-session: the interactive transcript- must surface the provider failure (retry banner + error row(s))- exactly like the TS product, and the earlier exchange stays- rendered exactly once."""- flow = "f11_provider_failure"- # Bounded, fast retries so the flow settles in seconds instead of- # minutes. The provider recovery wait (TS retry.provider.waitForUsage)- # is disabled on both sides so exhaustion surfaces instead of- # pinging a dead provider for up to 15 minutes.- retry_settings = {- "retry": {- "enabled": True,- "maxRetries": 2,- "baseDelayMs": 200,- "provider": {"waitForUsage": {"enabled": False}},- }- }- for side in (self.sides["ts"], self.sides["rust"]):- session = f"{self.runid}-f11-{side.name}"- settings_path = side.agent_dir / "settings.json"- prior_settings = (- settings_path.read_text() if settings_path.exists() else None- )- settings_path.write_text(json.dumps(retry_settings))- try:- argv = [- side.binary,- "--daemon-socket",- str(side.daemon_socket),- "--provider",- "prime-inference",- "--model",- "mock-1",- "--offline",- ]- B.tmux_launch(session, argv, side.env, side.work_dir)- frame = ""- deadline = time.time() + 30- while time.time() < deadline:- frame = B.tmux_capture(session)- if "Share agent traces" in frame:- break- time.sleep(1.0)- if "Share agent traces" in frame:- B.tmux_send(session, "Down")- time.sleep(0.5)- B.tmux_send(session, "Enter")- time.sleep(2.0)- # A settled main screen before the exchange.- stable = False- deadline = time.time() + 30- while time.time() < deadline and not stable:- first = B.tmux_capture(session)- time.sleep(2.0)- second = B.tmux_capture(session)- stable = first == second and ("manage" in first or ">" in first)- # A healthy exchange first: the reply must render. Own the- # mock script for this flow — the response queue is shared- # with every earlier flow in the same battery process, so a- # leftover response would break the HELLO_TEXT assertion.- side.mock.set_responses([{"text": HELLO_TEXT}])- B.tmux_send(session, "hello")- healthy = B.tmux_wait_text(session, HELLO_TEXT, timeout=90)- side.evidence(flow, "01-healthy-exchange.txt", healthy)- # Kill the provider mid-session, then prompt again.- side.mock.stop()- B.tmux_send(session, "again")- settled = ""- deadline = time.time() + 120- while time.time() < deadline:- settled = B.tmux_capture(session)- if "Retry failed after" in settled:- # Let the final frame settle (retry banner + rows).- time.sleep(1.0)- settled = B.tmux_capture(session)- break- time.sleep(1.0)- side.evidence(flow, "02-provider-failure.txt", settled)- retry_banner = "Retry failed after" in settled- error_rows = len(re.findall(r"Error: ", settled))- hello_rows = settled.count(HELLO_TEXT)- side.evidence_json(- flow,- "verdict.json",- {- "retryBanner": retry_banner,- "errorRows": error_rows,- "helloRenders": hello_rows,- },- )- if not retry_banner or error_rows == 0:- self.record(- flow,- "behavior",- f"{side.name}: provider failure is silent in the interactive transcript (retry banner: {retry_banner}, error rows: {error_rows})",- evidence=side.root / flow / "02-provider-failure.txt",- )- else:- self.record(- flow,- "behavior",- f"{side.name}: provider failure surfaces (retry banner + {error_rows} error row(s))",- gap=False,- )- if hello_rows != 1:- self.record(- flow,- "behavior",- f"{side.name}: the healthy exchange renders {hello_rows} times (expected exactly 1)",- evidence=side.root / flow / "02-provider-failure.txt",- )- finally:- B.tmux_kill(session)- # The failure scenario kills the provider; the mock is- # per-run shared state, so bring it back (new port) and- # republish models.json — the f22_provider_failover restore- # precedent. Without this, every later flow (f12_scroll runs- # right after this one) drives its turns against a dead- # provider and fails on error-row transcript geometry.- side.mock.start()- side.mock.set_responses([{"text": HELLO_TEXT}])- side.write_models_json()- if prior_settings is None:- settings_path.unlink(missing_ok=True)- else:- settings_path.write_text(prior_settings)- # Cross-side parity: same number of failed-attempt error rows, same- # single render of the healthy exchange.- verdicts = {- name: json.loads(- (self.sides[name].root / flow / "verdict.json").read_text()- )- for name in ("ts", "rust")- if (self.sides[name].root / flow / "verdict.json").exists()- }- if len(verdicts) == 2:- if verdicts["ts"]["errorRows"] != verdicts["rust"]["errorRows"]:- self.record(- flow,- "visual",- f"failed-attempt error rows differ: ts={verdicts['ts']['errorRows']} rust={verdicts['rust']['errorRows']}",- evidence=self.run_dir / flow,- )- else:- self.record(- flow,- "visual",- f"provider-failure rendering parity: {verdicts['rust']['errorRows']} error row(s) on both sides",- gap=False,- )-- def f22_provider_failover(self) -> None:- """Provider failover (Rust resilience feature; the TS product has no- counterpart): a second configured provider serves the same model.- When the primary dies mid-session the Rust product re-routes the- failed turn to the backup provider and recovers; TS (no failover)- exhausts its retries and surfaces the failure. The intentional- divergence is recorded, not gapped: the failover surface itself is- the assertion."""- flow = "f22_provider_failover"- BACKUP_TEXT = "recovered on the backup provider"- # Bounded, fast retries so the flow settles in seconds: one quick- # retry on the primary, then the failover switch; one quick retry- # on the backup before its own budget is spent.- retry_settings = {- "retry": {- "enabled": True,- "maxRetries": 1,- "baseDelayMs": 200,- "failover": {- "enabled": True,- "maxRetries": 1,- "baseDelayMs": 200,- },- }- }- for side in (self.sides["ts"], self.sides["rust"]):- session = f"{self.runid}-f22-{side.name}"- # A second provider serving the same model id, on its own mock- # process (and its own script file) so the primary can die alone.- backup = B.MockProvider(side.root, [])- backup.script_path = side.root / "backup-mock-script.json"- backup.requests_path = Path(str(backup.script_path) + ".requests.jsonl")- backup.set_responses([{"text": BACKUP_TEXT}])- backup.start()- # Two-provider catalog: prime-inference first (primary),- # prime-backup second (failover target).- models = {- "providers": {- "prime-inference": {- "api": "openai-completions",- "baseUrl": side.base_url,- "apiKey": "sk-battery",- "models": [- {- "id": "mock-1",- "name": "Mock 1",- "api": "openai-completions",- "baseUrl": side.base_url,- "contextWindow": 128000,- "maxTokens": 4096,- }- ],- },- "prime-backup": {- "api": "openai-completions",- "baseUrl": backup.url(),- "apiKey": "sk-backup",- "models": [- {- "id": "mock-1",- "name": "Mock 1 (backup)",- "api": "openai-completions",- "baseUrl": backup.url(),- "contextWindow": 128000,- "maxTokens": 4096,- }- ],- },- }- }- (side.agent_dir / "models.json").write_text(json.dumps(models, indent=1))- settings_path = side.agent_dir / "settings.json"- prior_settings = (- settings_path.read_text() if settings_path.exists() else None- )- settings_path.write_text(json.dumps(retry_settings))- try:- argv = [- side.binary,- "--daemon-socket",- str(side.daemon_socket),- "--provider",- "prime-inference",- "--model",- "mock-1",- "--offline",- ]- B.tmux_launch(session, argv, side.env, side.work_dir)- frame = ""- deadline = time.time() + 30- while time.time() < deadline:- frame = B.tmux_capture(session)- if "Share agent traces" in frame:- break- time.sleep(1.0)- if "Share agent traces" in frame:- B.tmux_send(session, "Down")- time.sleep(0.5)- B.tmux_send(session, "Enter")- time.sleep(2.0)- stable = False- deadline = time.time() + 30- while time.time() < deadline and not stable:- first = B.tmux_capture(session)- time.sleep(2.0)- second = B.tmux_capture(session)- stable = first == second and ("manage" in first or ">" in first)- # A healthy exchange first (own the primary's queue).- side.mock.set_responses([{"text": HELLO_TEXT}])- healthy = B.tmux_wait_text(session, HELLO_TEXT, timeout=90)- side.evidence(flow, "01-healthy-exchange.txt", healthy)- # Kill the primary mid-session, then prompt again: the- # failed turn must re-route to the backup provider. The- # switch loader is transient (the switch re-issues with no- # countdown), so poll fast to catch it; the settled- # assertions use the durable transcript rows.- side.mock.stop()- B.tmux_send(session, "again")- switch_loader = ""- settled = ""- deadline = time.time() + 120- while time.time() < deadline:- frame = B.tmux_capture(session)- if "backup model prime-backup/mock-1" in frame and not switch_loader:- switch_loader = frame- if side.name == "rust" and BACKUP_TEXT in frame:- settled = frame- break- if side.name == "ts" and "Retry failed after" in frame:- time.sleep(1.0)- settled = B.tmux_capture(session)- break- time.sleep(0.2)- # Let the settled frame finish (the restore status row).- time.sleep(2.0)- settled = B.tmux_capture(session)- side.evidence(flow, "02-provider-failure.txt", settled)- if switch_loader:- side.evidence(flow, "03-switch-loader.txt", switch_loader)- if side.name == "rust":- recovered = (- "Primary provider recovered — back on prime-inference/mock-1"- in settled- )- answered = BACKUP_TEXT in settled- switch_rows = len(- re.findall(r"backup model prime-backup/mock-1", settled)- ) + (1 if switch_loader else 0)- side.evidence_json(- flow,- "verdict.json",- {- "switchRendered": switch_rows > 0,- "primaryRestored": recovered,- "backupAnswered": answered,- },- )- if recovered and answered:- self.record(- flow,- "behavior",- f"{side.name}: provider failure re-routed to prime-backup/mock-1, the backup answered, and the primary was restored (switch surface rendered: {switch_rows > 0})",- gap=False,- )- else:- self.record(- flow,- "behavior",- f"{side.name}: provider failover is incomplete (primary restored: {recovered}, backup answered: {answered})",- evidence=side.root / flow / "02-provider-failure.txt",- )- if switch_rows == 0:- self.record(- flow,- "visual",- f"{side.name}: the provider-switch loader row was not captured (it is transient; the switch itself settled: primary restored: {recovered}, backup answered: {answered})",- evidence=side.root / flow / "02-provider-failure.txt",- gap=False,- )- else:- retry_banner = "Retry failed after" in settled- side.evidence_json(- flow,- "verdict.json",- {"retryBanner": retry_banner, "hasFailover": False},- )- self.record(- flow,- "behavior",- "ts: the TS product has no provider failover — the same flow exhausts its quick retries and surfaces the failure (the resilience feature is Rust-side only; intentional divergence)",- evidence=side.root / flow / "02-provider-failure.txt",- gap=False,- )- finally:- B.tmux_kill(session)- backup.stop()- side.mock.start()- side.mock.set_responses([{"text": HELLO_TEXT}])- side.write_models_json()- if prior_settings is None:- settings_path.unlink(missing_ok=True)- else:- settings_path.write_text(prior_settings)-- # -- scroll + exit-lane verifiers (f12/f13) ---------------------------------- def settle_first_run(self, session: str, timeout: float = 40.0) -> None:- """Wait past first-run dialogs (the trace notice) into the ready- prompt; answers the notice when one shows (perf_onboard pattern)."""- deadline = time.time() + timeout- while time.time() < deadline:- frame = B.tmux_capture(session)- if "Share agent traces" in frame:- B.tmux_send(session, "Down")- time.sleep(0.5)- B.tmux_send(session, "Enter")- time.sleep(1.0)- elif P.is_ready(session, frame) or (">" in frame and "manage" in frame):- return- else:- time.sleep(0.5)-- def f12_scroll(self) -> None:- """Scrollback: PageUp pages history into view with the follow hint;- paging back to the tail resumes following. Both sides must move the- transcript window (pane frames carry the content offsets)."""- flow = "f12_scroll"- turns = 16- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- side.mock.set_responses([{"text": "scroll filler reply"}])- session = f"{self.runid}-f12-{side.name}"- argv = P.launch_argv(side, side.daemon_socket)- B.tmux_launch(session, argv, side.env, side.work_dir)- self.settle_first_run(session)- for i in range(turns):- mark = len(side.mock.requests())- B.tmux_send(session, f"prompt {i}")- deadline = time.time() + 30- while time.time() < deadline and len(side.mock.requests()) <= mark:- time.sleep(0.2)- time.sleep(2.0)- follow_frame = B.tmux_capture(session)- side.evidence(flow, "01-following.txt", follow_frame)- for _ in range(6):- B.tmux_send(session, "PageUp", enter=False)- time.sleep(0.15)- time.sleep(1.0)- paged_frame = B.tmux_capture(session)- side.evidence(flow, "02-paged.txt", paged_frame)- for _ in range(6):- B.tmux_send(session, "PageDown", enter=False)- time.sleep(0.15)- time.sleep(1.0)- resume_frame = B.tmux_capture(session)- side.evidence(flow, "03-resumed.txt", resume_frame)- B.tmux_kill(session)- checks = {- "follow shows tail prompt": f"prompt {turns - 1}" in follow_frame,- "follow hides top prompt": "prompt 0" not in follow_frame,- "paged shows early prompt": "prompt 2" in paged_frame,- "paged hides tail prompt": f"prompt {turns - 1}" not in paged_frame,- "paged shows follow hint": "to follow" in paged_frame,- "resumed shows tail prompt": f"prompt {turns - 1}" in resume_frame,- "resumed hides follow hint": "to follow" not in resume_frame,- }- failed = [name for name, ok in checks.items() if not ok]- if failed:- self.record(- flow,- "behavior",- f"{side.name}: scrollback checks failed: {', '.join(failed)}",- evidence=side.root / flow,- )- else:- self.record(- flow,- "behavior",- f"{side.name}: PageUp pages history into view with the follow hint; paging back to the tail resumes following",- gap=False,- )-- def ctrl_c_exit_timing(self, side: B.Side, case: str, kill: str | None) -> dict:- """Launch one interactive session, hold it mid-turn against a- delayed mock response, send C-c C-c, and time the client exit.-- `kill` wedges the run before the exit gesture: "worker" kills the- session worker (SIGKILL, dead worker socket mid-turn), "daemon"- kills the supervisor process entirely (the worker is orphaned and- the client's supervisor socket dies mid-turn). None keeps the run- healthy."""- self.ensure_daemon(side)- side.mock.set_responses([{"text": "held reply", "delayMs": 20_000}])- session = f"{self.runid}-f13-{side.name}-{case}"- argv = P.launch_argv(side, side.daemon_socket)- B.tmux_launch(session, argv, side.env, side.work_dir)- B.tmux("set-option", "-t", session, "remain-on-exit", "on", check=False)- self.settle_first_run(session)- mark = len(side.mock.requests())- B.tmux_send(session, "hold the turn")- deadline = time.time() + 30- while time.time() < deadline and len(side.mock.requests()) <= mark:- time.sleep(0.2)- if len(side.mock.requests()) <= mark:- B.tmux_kill(session)- return {"case": case, "error": "the held prompt never reached the mock"}- if kill == "worker":- # Kill the session worker mid-turn (SIGKILL): the worker socket- # is dead and cannot answer the abort or the detach.- children = B.children_of(side.daemon_proc.pid)- if not children:- B.tmux_kill(session)- return {"case": case, "error": "no worker process found to wedge"}- os.kill(children[-1], 9)- time.sleep(0.5)- if kill == "daemon":- # Kill the supervisor process entirely (SIGKILL): the client's- # supervisor socket dies mid-turn while the orphaned worker- # keeps holding the turn against the mock.- if side.daemon_proc is None or side.daemon_proc.poll() is not None:- B.tmux_kill(session)- return {"case": case, "error": "no daemon process to kill"}- os.kill(side.daemon_proc.pid, 9)- time.sleep(0.5)- B.tmux_send(session, "C-c", enter=False)- time.sleep(0.3)- exit_at = time.time()- B.tmux_send(session, "C-c", enter=False)- deadline = exit_at + 10- status = None- while time.time() < deadline:- out = B.tmux(- "display-message",- "-p",- "-t",- session,- "#{pane_dead} #{pane_dead_status}",- check=False,- ).stdout.strip()- if out.startswith("1"):- status = out- break- time.sleep(0.05)- elapsed_s = round(time.time() - exit_at, 2)- frame = B.tmux_capture(session)- side.evidence("f13_ctrlc_exit", f"{side.name}-{case}-final.txt", frame)- B.tmux_kill(session)- rec = {"case": case, "elapsed_s": elapsed_s}- if status is None:- rec["error"] = "the pane never died"- return rec- rec["status"] = status- rec["exit_code"] = int(status.split()[1]) if len(status.split()) > 1 else None- # The TS pane process is reaped late, so tmux never populates- # pane_dead_status for it (the observed pane stays a defunct- # process); its exit code is unobservable through tmux. The- # shutdown-path resume hint (formatResumeHint) corroborates a- # graceful shutdown instead.- rec["resume_hint"] = "Resume this session with:" in frame- # TS exit parity: leaving fullscreen flushes the transcript frame- # onto the main screen (tui.ts exitFullscreen), so the dead pane- # shows the last submitted prompt — not a blank screen. Both sides- # must leave the exit frame behind.- rec["exit_frame"] = "hold the turn" in frame- return rec-- def f13_ctrlc_exit(self) -> None:- """Double Ctrl+C exit: a long-turn session must exit promptly after the- second press in all three daemon states — healthy, worker killed- -9 mid-turn (dead worker socket), and the daemon process killed- entirely (dead supervisor socket). The hard contract is exit- within 2s of the second press with code 0; the healthy/wedged- Rust cases keep the stricter 1s bound, the daemon-dead case gets- the full 2s force-quit window."""- flow = "f13_ctrlc_exit"- for case, sides, kill in (- ("healthy", (self.sides["ts"], self.sides["rust"]), None),- ("wedged", (self.sides["rust"],), "worker"),- ("daemon_dead", (self.sides["rust"],), "daemon"),- ):- for side in sides:- rec = self.ctrl_c_exit_timing(side, case, kill)- side.evidence_json(flow, f"{side.name}-{case}.json", rec)- # The exit-latency contract is the Rust client's (exit within- # 1s of the second press for the healthy and worker-killed cases,- # within the 2s force-quit window when the daemon process itself- # died, exit code 0). The TS reference's- # timing is recorded as evidence; its shutdown drains input- # for up to 1s by design, so only a clean exit is required.- bound_s = 10.0- if side.name == "rust":- bound_s = 2.0 if case == "daemon_dead" else 1.0- # The TS exit code is often unobservable through tmux (the- # reaped-late pane leaves no pane_dead_status); the TS source- # exits via process.exit(0), so a dead pane inside the bound- # with the shutdown-path resume hint counts as clean.- exit_ok = rec.get("exit_code") == 0 or (- side.name == "ts" and rec.get("exit_code") is None and rec.get("resume_hint")- )- ok = (- "error" not in rec- and rec.get("elapsed_s") is not None- and rec["elapsed_s"] <= bound_s- and exit_ok- and rec.get("exit_frame")- )- if ok:- exit_code = rec.get("exit_code")- code_note = f"exit code {exit_code}" if exit_code is not None else "resume hint after exit"- self.record(- flow,- "behavior",- f"{side.name}: C-c C-c exits in {rec['elapsed_s']}s (case {case}, {code_note})",- gap=False,- )- else:- summary = f"{side.name}: C-c C-c did not exit cleanly (case {case})"- if "error" in rec:- summary += f": {rec['error']}"- elif not rec.get("exit_frame"):- summary += ": the exit frame is missing from the dead pane"- elif rec.get("elapsed_s") is not None:- summary += (- f": exit took {rec['elapsed_s']}s, status {rec.get('status')}"- )- self.record(- flow,- "behavior",- summary,- evidence=side.root / flow / f"{side.name}-{case}.json",- )-- # -- real-surface helpers (f14-f21) ---------------------------------------- def suppress_first_run_notices(self, side: B.Side) -> dict:- """Mark the side's onboarding/trace-notice state as already shown so- the interactive panes settle straight into the conversation. The TS- product re-runs the Welcome/trace-notice onboarding overlay on any- fresh TUI instance (including mid-flow rebinds) until the state is- persisted; a subset battery run (`--flows f15_a2a` without f1) would- otherwise capture notice-overlaid frames (see the frozen partial run- 20260918T190022Z ts/f15_a2a/01-received.txt). Returns the settings- dict so a flow can extend it before writing again."""- settings_path = side.agent_dir / "settings.json"- settings = json.loads(settings_path.read_text()) if settings_path.exists() else {}- settings["onboardingShown"] = True- settings["telemetry"] = {**(settings.get("telemetry") or {}), "noticeShown": True}- settings_path.write_text(json.dumps(settings))- return settings-- def settle_frame(self, session: str, quiet_s: float = 2.0, timeout: float = 40.0) -> str:- """Poll the pane until it stops changing; returns the settled frame."""- deadline = time.time() + timeout- last = B.tmux_capture(session)- last_change = time.time()- while time.time() < deadline:- time.sleep(0.5)- frame = B.tmux_capture(session)- if frame != last:- last = frame- last_change = time.time()- elif time.time() - last_change >= quiet_s:- return frame- return last-- def create_session(self, side: B.Side, flow: str, name: str, wire_id: str, timeout: float = 120) -> tuple[B.Wire, str] | None:- """Create one daemon session; returns (wire, session_id) or None after recording the failure."""- self.ensure_daemon(side)- wire = B.Wire(side.daemon_socket)- create = wire.request(wire_id, {"type": "create", "name": name, "config": self.session_config(side)}, timeout=timeout)- if create.get("success") is not True:- self.record(- flow,- "protocol",- f"{side.name}: daemon create failed: {json.dumps(create)[:300]}",- )- wire.close()- return None- session_id = (create.get("data", {}).get("activeSessionId") or create.get("data", {}).get("id") or "")- return wire, session_id-- def tui_ready_loop(self, session: str, ready_marker: str, timeout: float = 90.0) -> str:- """One ready gate for interactive panes: answer the first-run trace- notice whenever it shows (it can appear after the first ready-looking- frame — the splash carries ">" + "manage" too, and the transcript can- render before the notice overlays it), and return only once- `ready_marker` has rendered stably with no notice on top."""- deadline = time.time() + timeout- frame = ""- stable_since: float | None = None- while time.time() < deadline:- frame = B.tmux_capture(session)- if "Share agent traces" in frame:- B.tmux_send(session, "Down")- time.sleep(0.5)- B.tmux_send(session, "Enter")- time.sleep(1.5)- stable_since = None- continue- if ready_marker and ready_marker in frame:- if stable_since is None:- stable_since = time.time()- elif time.time() - stable_since >= 3.0:- return frame- else:- stable_since = None- time.sleep(0.5)- return frame-- def tui_send(self, session: str, keys: str, enter: bool = True) -> None:- """Send keys to an interactive pane, answering the first-run notice- first if it happens to be on top (a notice arriving late would- otherwise swallow the keystrokes)."""- frame = B.tmux_capture(session)- if "Share agent traces" in frame:- B.tmux_send(session, "Down")- time.sleep(0.5)- B.tmux_send(session, "Enter")- time.sleep(1.5)- B.tmux_send(session, keys, enter=enter)-- def launch_tui(self, side: B.Side, flow: str, argv: list[str], ready_marker: str, timeout: float = 90.0) -> tuple[str, str]:- """Launch one interactive pane (`argv`) and gate it through the- notice-aware ready loop. Returns (tmux session, ready frame)."""- session = f"{self.runid}-{flow}-{side.name}"- B.tmux_launch(session, argv, side.env, side.work_dir)- frame = self.tui_ready_loop(session, ready_marker, timeout=timeout)- return session, frame-- def attach_tui(self, side: B.Side, flow: str, session_id: str, ready_marker: str = ">") -> tuple[str, str] | None:- """Launch the interactive TUI attached to a live daemon session- (`--resume <session id>` attaches on both products); waits past- first-run notices into the ready prompt. Returns (tmux session,- ready frame)."""- # No --offline here: it disables telemetry for the invocation, and TS- # refuses to attach to an active worker across that telemetry mismatch- # (f6's CLI attach takes the same stance).- argv = [- side.binary,- "--daemon-socket",- str(side.daemon_socket),- "--resume",- session_id,- ]- return self.launch_tui(side, flow, argv, ready_marker)-- def frame_diff(self, flow: str, step: str, frames: dict[str, str], normalizer=None) -> None:- """Cross-side diff of one captured frame pair, recorded as one- finding (identical = pass; differ = gap evidence)."""- ts_frame = frames.get("ts")- rs_frame = frames.get("rust")- if ts_frame is None or rs_frame is None:- self.record(- flow,- "visual",- f"{step}: missing frames (ts={'y' if ts_frame else 'n'} rust={'y' if rs_frame else 'n'})",- )- return- ts_norm = normalizer(ts_frame, self.sides["ts"]) if normalizer else ts_frame- rs_norm = normalizer(rs_frame, self.sides["rust"]) if normalizer else rs_frame- if ts_norm == rs_norm:- self.record(- flow,- "visual",- f"{step}: frames identical TS vs Rust (normalized)",- gap=False,- )- else:- diff_path = self.sides["ts"].root / flow / f"frame-diff-{step}.txt"- diff_path.parent.mkdir(parents=True, exist_ok=True)- diff_path.write_text(f"--- ts ({step})\n{ts_frame}\n+++ rust ({step})\n{rs_frame}")- self.record(- flow,- "visual",- f"{step}: frames differ TS vs Rust (see frame-diff-{step}.txt)",- evidence=diff_path,- lane=FLOW_STEP_LANES.get((flow, step), FLOW_LANES.get(flow)),- )-- @staticmethod- def normalize_transcript_frame(frame: str, side: B.Side) -> str:- """Transcript-frame normalization: scrub side-specific paths, session- ids, timestamps, token counts, and trailing status lines so the diff- measures the durable rows, not volatile metadata."""- text = frame- home = str(Path.home())- # Both products render the session cwd with a leading `~`, so a- # side-specific path can appear in either form.- for value in (str(side.root), str(side.agent_dir), str(side.work_dir)):- text = text.replace(value, "<dir>")- if value.startswith(home):- text = text.replace(value.replace(home, "~", 1), "<dir>")- text = re.sub(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", "<uuid>", text)- # The splash banner's product version is per-build metadata (the TS- # release reports its pinned manifest, a cargo build reports the- # workspace version): scrub it like the other volatile fields so the- # diff measures the durable rows.- text = re.sub(r"prime agent v[0-9][0-9A-Za-z.+-]*", "prime agent <version>", text)- text = re.sub(r"\b[0-9,]{4,}\b", "<num>", text)- # Tool-execution summary rows report their wall time (`· 43ms` under- # one second, `· 1.2s` above it; the same row shape on both- # products): scrub both units so per-execution timing noise cannot- # fail the frame diff.- text = re.sub(r"\b\d+(\.\d+)?m?s\b", "<dur>", text)- # The expanded compaction block's metadata reports the pre-compaction- # context size, which each side estimates with its own counter (the- # row shape and the focus text are the parity claim; the count is- # per-implementation and can be under the 4-digit scrub above).- text = re.sub(r"Compacted from [0-9,]+ tokens", "Compacted from <num> tokens", text)- # The heartbeat prompt row's glyph is a sanctioned divergence- # (operator directive 2026-09-23): the Rust side renders the ◷- # clock (the unified-activity-dock Heartbeats icon), the TS side- # the ♥ heart. Canonicalize the single chars (the battery frames- # are plain-text captures, so the row renders contiguously) so- # the f19 frame diff keeps covering the rest of the row; the- # fired-row check asserts each side's glyph separately.- text = text.replace("♥", "<HBICON>")- text = text.replace("◷", "<HBICON>")- # The agent-message rows' icon is a sanctioned divergence (Kevin- # directive 2026-09-24): the Rust side renders the ✉ mail- # envelope, the TS side the ◆ diamond. The diamond also fronts- # other rows that keep matching directly (the compaction and- # refinement summary rows), so the canonicalization is scoped to- # the agent-message label compositions (received/sent/queued all- # start `Agent message`); the f15 flow asserts each side's glyph- # separately.- text = text.replace("◆ Agent message", "<AMICON> Agent message")- text = text.replace("✉ Agent message", "<AMICON> Agent message")- # The label/participant divergence (the operator's 2026-09-25- # directive): the Rust rows render the shared `Agent message`- # label with the viewer-relative arrow plus the counterpart name- # (received ↓, sent/queued ↑); the TS rows keep the direction- # word plus the `from/to <role> <name>` participant. The summary- # row is its own line, so the whole composition canonicalizes to- # one marker per side; the f15 flow asserts each side's exact row.- text = re.sub(r"<AMICON> Agent message[^\n]*", "<AMICON><AMROW>", text)- return text--- def f14_compact(self) -> None:- """/compact visible feedback and the auto-compaction threshold- crossing. Two sessions: the manual /compact loader + durable- `◆ Context compacted` summary row (session A), and the- `Auto-compacting...` loader + compacted row when one large turn- crosses the reserve-token headroom (session B — a manual compact- first would leave `Already compacted` skips for the auto path).- Session A also diffs the collapsed/expanded block states: the- summary row is a collapsible block (TS- CompactionSummaryMessageComponent over ExpandableEventMessage), so- after the settled collapsed frame it presses Ctrl+O twice to the- `all` detail (the markdown body + `Compacted from N tokens`- metadata), then once more to re-collapse.- Settings shape both: reserveTokens 4096 puts the- mock-reported 126k usage over the crossing on both products (TS- at window - reserve = 123904; Rust at the combined input+output- ceiling 128000 - 4096 output budget - 4096 headroom = 119808),- and keepRecentTokens 10 makes the seeded turns compactable (the- TS compactor skips sessions whose recent history already fits- keepRecentTokens with "Session is too short to compact" — the- frozen 20260918T190022Z partial run showed exactly that skip- with the default 20000). Frame diff TS vs Rust at each key- moment."""- flow = "f14_compact"- reply = "f14 parity fixture reply"- frames: dict[str, dict[str, str]] = {"ts": {}, "rust": {}}- for side in (self.sides["ts"], self.sides["rust"]):- settings = self.suppress_first_run_notices(side)- settings["compaction"] = {"enabled": True, "reserveTokens": 4096, "keepRecentTokens": 10}- settings_path = side.agent_dir / "settings.json"- settings_path.write_text(json.dumps(settings))- # -- session A: manual /compact --------------------------------- made = self.create_session(side, flow, "battery-f14-manual", "c14m")- if made:- wire, session_id = made- # Seed turns: deterministic content for the compactor to keep.- side.mock.set_responses([{"text": reply}])- for n in (1, 2):- wire.request(- f"p14s{n}",- {"type": "prompt_and_wait", "activeSessionId": session_id,- "message": f"f14 seed turn {n} of the parity battery with deterministic content"},- timeout=240,- )- wire.close()- self.settle_mock(side)- attached = self.attach_tui(side, flow, session_id, ready_marker="f14 seed turn 2")- if not attached:- self.record(flow, "visual", f"{side.name}: attached TUI never rendered the seeded transcript")- else:- tui, ready = attached- side.evidence(flow, "00-attached.txt", ready)- # Manual /compact: the loader while running, the durable- # outcome row after (the summarization request pops the- # mock's repeating text response; its default usage keeps- # the session below the auto-compaction headroom).- self.tui_send(tui, "/compact")- # The mock summarization returns instantly, so the- # loader may be gone before the first poll; keep the wait- # short and let the settled row be the real gate.- during = B.tmux_wait_text(tui, "ompacting", timeout=8)- side.evidence(flow, "01-during-compact.txt", during)- settled = self.settle_frame(tui, quiet_s=3.0, timeout=90)- side.evidence(flow, "02-after-compact.txt", settled)- frames[side.name]["manual-compact"] = settled- if "Context compacted" in settled:- self.record(- flow, "visual",- f"{side.name}: /compact shows the durable '◆ Context compacted' summary row",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: /compact produced no visible '◆ Context compacted' summary row",- evidence=side.root / flow / "02-after-compact.txt",- lane=FLOW_LANES[flow],- )- # The collapsible block: Ctrl+O twice (overview ->- # details -> all, TS applyChatExpansion ->- # CompactionSummaryMessageComponent) swaps the collapsed- # EventSummary for the markdown body plus the dim- # `Compacted from N tokens` metadata row.- self.tui_send(tui, "C-o", enter=False)- time.sleep(0.5)- self.tui_send(tui, "C-o", enter=False)- B.tmux_wait_text(tui, "Compacted from", timeout=30)- expanded = self.settle_frame(tui, quiet_s=2.0, timeout=60)- side.evidence(flow, "02b-expanded-block.txt", expanded)- frames[side.name]["manual-expanded"] = expanded- if "Compacted from" in expanded and "Context compacted" in expanded:- self.record(- flow, "visual",- f"{side.name}: the Ctrl+O detail cycle expands the compaction summary block",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: Ctrl+O never expanded the compaction summary block",- evidence=side.root / flow / "02b-expanded-block.txt",- lane=FLOW_LANES[flow],- )- # The third press wraps back to overview: re-collapsed.- self.tui_send(tui, "C-o", enter=False)- recollapsed = self.settle_frame(tui, quiet_s=2.0, timeout=60)- side.evidence(flow, "02c-recollapsed-block.txt", recollapsed)- if "Compacted from" in recollapsed:- self.record(- flow, "visual",- f"{side.name}: the detail cycle back to overview did not re-collapse the block",- evidence=side.root / flow / "02c-recollapsed-block.txt",- lane=FLOW_LANES[flow],- )- else:- self.record(- flow, "visual",- f"{side.name}: the third Ctrl+O re-collapses the compaction summary block",- gap=False,- )- B.tmux_kill(tui)- self.copy_sessions(side, flow)- # -- session B: auto-compaction threshold crossing ---------------- made = self.create_session(side, flow, "battery-f14-auto", "c14a")- if made:- wire, session_id = made- side.mock.set_responses([{"text": reply}])- wire.request(- "p14a",- {"type": "prompt_and_wait", "activeSessionId": session_id, "message": "f14 auto seed turn"},- timeout=240,- )- wire.close()- self.settle_mock(side)- attached = self.attach_tui(side, flow, session_id, ready_marker="f14 auto seed turn")- if not attached:- self.record(flow, "visual", f"{side.name}: attached TUI never rendered the auto-compaction seeded transcript")- else:- tui, ready = attached- side.evidence(flow, "03-auto-attached.txt", ready)- # The mock reports usage past the 500-token headroom- # (128000 - reserveTokens 127500), so the threshold check- # fires after this turn; the follow-up response carries- # the default (small) usage so the compacted session does- # not re-cross the threshold and loop.- self.settle_mock(side)- side.mock.set_responses(- [- {"text": reply, "usage": {"prompt_tokens": 126000, "completion_tokens": 10, "total_tokens": 126010, "prompt_tokens_details": {"cached_tokens": 80}}},- {"text": reply},- ]- )- self.tui_send(tui, "f14 threshold crossing turn")- auto_during = B.tmux_wait_text(tui, "Auto-compacting|Context compacted", timeout=90)- side.evidence(flow, "04-auto-during.txt", auto_during)- settled2 = self.settle_frame(tui, quiet_s=3.0, timeout=120)- side.evidence(flow, "05-auto-after.txt", settled2)- frames[side.name]["auto-compact"] = settled2- if "Context compacted" in settled2:- self.record(- flow, "behavior",- f"{side.name}: crossing the compaction threshold auto-compacts and shows the summary row",- gap=False,- )- else:- self.record(- flow, "behavior",- f"{side.name}: threshold crossing produced no visible auto-compaction outcome",- evidence=side.root / flow / "05-auto-after.txt",- lane=FLOW_LANES[flow],- )- side.evidence_json(flow, "mock-requests.json", side.mock.requests())- B.tmux_kill(tui)- self.copy_sessions(side, flow)- # Restore default compaction settings for the flows that follow.- settings["compaction"] = {"enabled": True}- settings_path.write_text(json.dumps(settings))- for step in ("manual-compact", "manual-expanded", "auto-compact"):- self.frame_diff(- flow, step,- {name: frames[name].get(step, "") for name in ("ts", "rust")},- self.normalize_transcript_frame,- )--- def f15_a2a(self) -> None:- """agent_message send/receive: the icon-decorated rows in both- directions — the received row in the receiver's transcript, the sent- summary row inside the sender's ipython cell — with participant- labels and the expanded preview body (the shape diverges by- directive: ts renders the ◆ diamond with the direction word and- the `from/to <role> <name>` participant; rust renders the ✉ mail- envelope — the Kevin-directed 2026-09-24 divergence — with the- shared `Agent message` label, the viewer-relative ↓/↑ arrow, and- the counterpart name only, no collapsed preview — the operator's- 2026-09-25 directive). Two sibling daemon- sessions exchange one message each way through their kernels."""- flow = "f15_a2a"- reply = "f15 a2a turn reply"- frames: dict[str, dict[str, str]] = {"ts": {}, "rust": {}}- for side in (self.sides["ts"], self.sides["rust"]):- self.suppress_first_run_notices(side)- made = self.create_session(side, flow, "battery-f15-a", "c15a")- if not made:- continue- wire_a, id_a = made- made = self.create_session(side, flow, "battery-f15-b", "c15b")- if not made:- wire_a.close()- continue- wire_b, id_b = made- # Seed both sessions so each is idle and named on the roster.- side.mock.set_responses([{"text": reply}])- wire_a.request(- "p15a", {"type": "prompt_and_wait", "activeSessionId": id_a, "message": "f15 seed a"}, timeout=240- )- wire_b.request(- "p15b", {"type": "prompt_and_wait", "activeSessionId": id_b, "message": "f15 seed b"}, timeout=240- )- wire_a.close()- wire_b.close()- self.settle_mock(side)- # Attach to B; A's kernel sends one sibling message.- attached = self.attach_tui(side, flow, id_b, ready_marker="f15 seed b")- if not attached:- self.record(flow, "visual", f"{side.name}: attached TUI never rendered the seeded transcript")- continue- tui, ready = attached- side.evidence(flow, "00-attached.txt", ready)- payload_a = "f15 a2a payload from a to b"- code_a = (- "import agent_message; await agent_message.send("- f"{payload_a!r}, receiver_role='sibling', receiver_name='battery-f15-b')"- )- side.mock.set_responses(- [- {"toolCall": {"name": "ipython", "arguments": {"code": code_a}}},- {"text": reply},- ]- )- wire_a = B.Wire(side.daemon_socket)- wire_a.send_command(- "p15s",- {"type": "prompt_and_wait", "activeSessionId": id_a, "message": "f15 send the sibling message to b"},- )- wire_a.close()- wait_a = (- "Agent message received|f15 a2a payload"- if side.name == "ts"- else "Agent message \u00b7 \u2193|f15 a2a payload"- )- received = B.tmux_wait_text(tui, wait_a, timeout=120)- side.evidence(flow, "01-received.txt", received)- settled = self.settle_frame(tui, quiet_s=3.0, timeout=90)- side.evidence(flow, "02-received-settled.txt", settled)- frames[side.name]["received"] = settled- # The received row's shape diverges by directive: the TS side- # keeps the ◆ diamond with the `Agent message received ·- # from …` participant (the baseline); the Rust side renders- # the ✉ mail envelope (the a2a rows read as agent mail —- # Kevin directive 2026-09-24) with the shared `Agent- # message` label, the viewer-relative ↓ arrow, and the- # counterpart name only (operator directive 2026-09-25).- if side.name == "ts":- row_a = "◆ Agent message received"- else:- row_a = "✉ Agent message \u00b7 \u2193"- if row_a in settled:- self.record(- flow, "visual",- f"{side.name}: a sibling agent message renders the '{row_a.strip()}' row with the participant",- gap=False,- )- elif "Agent message" in settled:- self.record(- flow, "behavior",- f"{side.name}: the received agent-message row renders the wrong shape (expected '{row_a.strip()}')",- evidence=side.root / flow / "02-received-settled.txt",- lane=FLOW_LANES[flow],- )- else:- self.record(- flow, "visual",- f"{side.name}: the delivered sibling message shows no agent-message row",- evidence=side.root / flow / "02-received-settled.txt",- lane=FLOW_LANES[flow],- )- # Reverse direction: B's kernel sends back to A (prompted through- # the attached TUI so the sent row renders in B's own pane).- self.settle_mock(side)- payload_b = "f15 a2a payload from b to a"- code_b = (- "import agent_message; await agent_message.send("- f"{payload_b!r}, receiver_role='sibling', receiver_name='battery-f15-a')"- )- side.mock.set_responses(- [- {"toolCall": {"name": "ipython", "arguments": {"code": code_b}}},- {"text": reply},- ]- )- self.tui_send(tui, "f15 send the sibling message back to a")- wait_b = (- "Agent message sent|Agent message queued"- if side.name == "ts"- else "Agent message \u00b7 \u2191"- )- sent = B.tmux_wait_text(tui, wait_b, timeout=120)- side.evidence(flow, "03-sent.txt", sent)- settled2 = self.settle_frame(tui, quiet_s=3.0, timeout=90)- side.evidence(flow, "04-sent-settled.txt", settled2)- frames[side.name]["sent"] = settled2- # The sent/queued receipt rows share the same summary line- # (and its per-side shape): TS keeps the ◆ diamond with the- # direction word; Rust renders the ✉ envelope with the- # shared `Agent message` label and the viewer-relative ↑- # arrow — delivered and queued fold into one row shape (the- # operator's 2026-09-25 directive).- if side.name == "ts":- rows_b = ("◆ Agent message sent", "◆ Agent message queued")- else:- rows_b = ("✉ Agent message \u00b7 \u2191",)- if any(row in settled2 for row in rows_b):- self.record(- flow, "visual",- f"{side.name}: the sender's ipython cell renders the sent/queued agent-message summary row with the participant",- gap=False,- )- elif "Agent message" in settled2:- self.record(- flow, "behavior",- f"{side.name}: the sent agent-message row renders the wrong shape (expected one of {rows_b})",- evidence=side.root / flow / "04-sent-settled.txt",- lane=FLOW_LANES[flow],- )- else:- self.record(- flow, "visual",- f"{side.name}: the sender's ipython cell shows no sent/queued agent-message row",- evidence=side.root / flow / "04-sent-settled.txt",- lane=FLOW_LANES[flow],- )- B.tmux_kill(tui)- self.copy_sessions(side, flow)- for step in ("received", "sent"):- self.frame_diff(- flow, step,- {name: frames[name].get(step, "") for name in ("ts", "rust")},- self.normalize_transcript_frame,- )-- def f16_refine(self) -> None:- """refine.run() from the kernel: the ◆ decorated refinement-outcome- row, and the harness_digest user message rendered on the next- boundary. One daemon session, one kernel-scheduled refinement."""- flow = "f16_refine"- reply = "f16 refine fixture reply"- frames: dict[str, dict[str, str]] = {"ts": {}, "rust": {}}- for side in (self.sides["ts"], self.sides["rust"]):- self.suppress_first_run_notices(side)- made = self.create_session(side, flow, "battery-f16", "c16")- if not made:- continue- wire, session_id = made- side.mock.set_responses([{"text": reply}])- wire.request(- "p16s", {"type": "prompt_and_wait", "activeSessionId": session_id, "message": "f16 seed turn"}, timeout=240- )- wire.close()- self.settle_mock(side)- attached = self.attach_tui(side, flow, session_id, ready_marker="f16 seed turn")- if not attached:- self.record(flow, "visual", f"{side.name}: attached TUI never rendered the seeded transcript")- continue- tui, ready = attached- side.evidence(flow, "00-attached.txt", ready)- code = (- "import refine; await refine.run("- "instructions='create one local memory titled f16-battery-memory describing this parity check')"- )- # The refinement runs host-side when the turn ends: after the- # tool-call reply and the turn's final text, the refinement- # planning request consumes the next queued response, so the- # queue scripts the exact refinement proposal JSON (the- # "You are Prime Agent's /refine continual harness subsystem"- # prompt's schema). Without it the mock repeats the last plain- # text response and refinement never applies (TS run- # 20260918T231155Z: both sides failed the outcome row on this).- refinement = {- "summary": "Record the f16 battery parity fixture",- "rationale": "The parity check requires one local memory entry to prove refinement applies edits.",- "expectedOutcome": "A local memory titled f16-battery-memory exists.",- "edits": [- {- "action": "create",- "kind": "memory",- "title": "f16-battery-memory",- "content": "The f16 battery flow verified the kernel-scheduled refinement end to end.",- "metadata": {"scope": "local"},- "reason": "battery parity fixture",- }- ],- }- side.mock.set_responses(- [- {"toolCall": {"name": "ipython", "arguments": {"code": code}}},- {"text": reply},- {"text": json.dumps(refinement)},- # The harness resumes the model after applying the edits.- {"text": reply},- ]- )- self.tui_send(tui, "f16 schedule the refinement now")- outcome = B.tmux_wait_text(tui, "Harness refined|Harness unchanged|refine", timeout=150)- side.evidence(flow, "01-refine-outcome.txt", outcome)- settled = self.settle_frame(tui, quiet_s=4.0, timeout=120)- side.evidence(flow, "02-refine-settled.txt", settled)- frames[side.name]["refine"] = settled- if "Harness refined" in settled:- self.record(- flow, "visual",- f"{side.name}: the kernel-scheduled refinement renders the '◆ Harness refined' outcome row",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: no '◆ Harness refined' outcome row after the kernel-scheduled refinement",- evidence=side.root / flow / "02-refine-settled.txt",- lane=FLOW_LANES[flow],- )- # The harness digest lands on the next turn boundary; the next- # prompt forces it into the transcript.- self.settle_mock(side)- side.mock.set_responses([{"text": reply}])- self.tui_send(tui, "f16 follow up turn")- digest = B.tmux_wait_text(tui, "harness-digest", timeout=150)- side.evidence(flow, "03-digest.txt", digest)- settled2 = self.settle_frame(tui, quiet_s=4.0, timeout=120)- side.evidence(flow, "04-digest-settled.txt", settled2)- frames[side.name]["digest"] = settled2- if "harness-digest" in settled2:- self.record(- flow, "visual",- f"{side.name}: the harness digest renders as a [harness-digest] message row on the boundary",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: no [harness-digest] message row on the post-refinement boundary",- evidence=side.root / flow / "04-digest-settled.txt",- lane=FLOW_LANES[flow],- )- B.tmux_kill(tui)- self.copy_sessions(side, flow)- for step in ("refine", "digest"):- self.frame_diff(- flow, step,- {name: frames[name].get(step, "") for name in ("ts", "rust")},- self.normalize_transcript_frame,- )--- def f24_prompt_stash(self) -> None:- """Prompt stash across session switches (TS `prompt-stash-state.ts`):- a draft typed into the editor survives the- chat -> agents view -> chat round trip inside one TUI process and- returns to the editor on reopen, with the TS `Restored stashed- prompt` status row. The switch is driven through `app.session.resume`- (no default key on either product): a `keybindings.json` fixture- binds it to `f2`, so the key fires with a draft in the editor — the- exact surface the stash captures. The full loop runs in one process- (`prime-agent agents`): open the session from the view, type the- draft, f2 back to the view, reopen, and the restored frame is- diffed TS vs Rust."""- flow = "f24_prompt_stash"- draft = "f24 stashed draft payload 4242"- frames: dict[str, dict[str, str]] = {"ts": {}, "rust": {}}- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- self.suppress_first_run_notices(side)- # The keybindings fixture: `app.session.resume` bound to a- # plain function key (both products fire the app action while- # the editor carries text; f2 survives tmux encoding on both).- (side.agent_dir / "keybindings.json").write_text(- json.dumps({"app.session.resume": "f2"}, indent=1) + NL- )- # One live session to open, wire-created so its id is known.- made = self.create_session(side, flow, "battery-f24", "c24")- if not made:- continue- wire, session_id = made- side.mock.set_responses([{"text": "f24 roster reply"}])- wire.request(- "p24s",- {"type": "prompt_and_wait", "activeSessionId": session_id,- "message": "f24 seed turn of the parity battery"},- timeout=240,- )- wire.close()- self.settle_mock(side)- # The full view<->chat loop in one process.- tui = f"{self.runid}-f24-{side.name}"- argv = [side.binary, "agents", "--daemon-socket", str(side.daemon_socket)]- B.tmux_launch(tui, argv, side.env, side.work_dir)- B.tmux_wait_text(tui, "battery-f24", timeout=45)- view_frame = self.settle_frame(tui, quiet_s=2.0, timeout=30)- side.evidence(flow, "00-agents-view.txt", view_frame)- # Open the session's row: filter to it, then Enter. The typed- # filter must be IN the search box before Enter (both products- # open the selected row either way, but the query persists- # across the round trip — the back-frame diff covers it).- B.tmux_wait_text(tui, "Search sessions", timeout=30)- B.tmux_send(tui, "f24", enter=False)- filtered = B.tmux_wait_text(tui, " f24", timeout=15)- side.evidence(flow, "00b-filtered.txt", filtered)- B.tmux_send(tui, "Enter", enter=False)- chat_ready = B.tmux_wait_text(tui, "f24 roster reply", timeout=60)- side.evidence(flow, "01-opened-chat.txt", chat_ready)- # Type the draft (never submitted) and settle the frame.- B.tmux_send(tui, draft, enter=False)- settled_draft = self.settle_frame(tui, quiet_s=2.0, timeout=30)- side.evidence(flow, "02-typed-draft.txt", settled_draft)- frames[side.name]["typed-draft"] = settled_draft- # f2 hands the pane back to the agents view: the draft rides the- # per-session stash.- B.tmux_send(tui, "f2", enter=False)- back = B.tmux_wait_text(tui, "battery-f24", timeout=45)- back = self.settle_frame(tui, quiet_s=2.0, timeout=30)- side.evidence(flow, "03-agents-view-back.txt", back)- frames[side.name]["agents-view-back"] = back- if draft in back:- self.record(- flow, "behavior",- f"{side.name}: the agents view leaked the stashed draft into the roster",- evidence=side.root / flow / "03-agents-view-back.txt",- lane=FLOW_LANES[flow],- )- # Reopen the same session: the draft returns to the editor with- # the TS restore status row. The persisted query (both products- # carry it across the chat round trip) keeps the row filtered- # and selected, so Enter opens it.- B.tmux_wait_text(tui, " f24", timeout=30)- B.tmux_send(tui, "Enter", enter=False)- B.tmux_wait_text(tui, "Restored stashed prompt", timeout=60)- restored = self.settle_frame(tui, quiet_s=2.5, timeout=60)- side.evidence(flow, "04-restored-draft.txt", restored)- frames[side.name]["restored"] = restored- if draft not in restored:- self.record(- flow, "behavior",- f"{side.name}: the reopened chat did not restore the stashed draft into the editor",- evidence=side.root / flow / "04-restored-draft.txt",- lane=FLOW_LANES[flow],- )- else:- self.record(- flow, "behavior",- f"{side.name}: the reopened chat restored the stashed draft into the editor",- gap=False,- )- # The restored draft is live: submitting it runs a turn.- B.tmux_send(tui, "Enter")- submitted = B.tmux_wait_text(tui, "f24 roster reply", timeout=60)- side.evidence(flow, "05-submitted-restored.txt", submitted)- frames[side.name]["submitted"] = self.settle_frame(tui, quiet_s=2.0, timeout=40)- B.tmux_kill(tui)- side.mock.set_responses([{"text": HELLO_TEXT}])- # The back step is a cross-surface probe: the roster frame belongs- # to the agents view, so a divergence there is the agents-view- # surface's gap, not this flow's prompt-stash surface. The observed- # shape (run 20260921T194517Z): both sides typed the filter and the- # 00b evidence shows the query set in the box before the open, but- # after the chat round trip the TS binary (0.9.5) shows the search- # box cleared while the Rust build keeps the query — the agents-view- # query-persistence divergence, recorded for that surface's owner.- ts_back = self.normalize_agents_view_frame(- frames["ts"].get("agents-view-back", ""), self.sides["ts"]- )- rs_back = self.normalize_agents_view_frame(- frames["rust"].get("agents-view-back", ""), self.sides["rust"]- )- if ts_back == rs_back:- self.record(- flow, "visual",- "agents-view-back: frames identical TS vs Rust (normalized)",- gap=False,- )- else:- diff_path = self.sides["ts"].root / flow / "frame-diff-agents-view-back.txt"- diff_path.parent.mkdir(parents=True, exist_ok=True)- diff_path.write_text(- f"--- ts (agents-view-back)\n{frames['ts'].get('agents-view-back', '')}"- f"\n+++ rust (agents-view-back)\n{frames['rust'].get('agents-view-back', '')}"- )- self.record(- flow, "visual",- "agents-view-back: the roster frame differs — the TS binary clears the search query after the chat round trip, the Rust build keeps it (agents-view query persistence; both sides set the query before the open, see 00b-filtered.txt)",- evidence=diff_path,- lane="agents-view",- )- for step in ("typed-draft", "restored", "submitted"):- self.frame_diff(- flow, step,- {name: frames[name].get(step, "") for name in ("ts", "rust")},- self.normalize_transcript_frame,- )-- """User-editable keybindings (roadmap item "keybinding- customization"): a `keybindings.json` fixture rebinding- `app.tools.expand` from ctrl+o to the plain key x. Both sides must render- the OVERRIDE in the prompt-context hint, fire the action on the- override key, ignore the removed default key, and document the- effective binding in `/hotkeys` (TS: the guide as chat rows; Rust:- the read-only info panel — the operator's 2026-09-26 directive).- The `?` quick-shortcut guide diverges BY THE SAME DIRECTIVE (TS- mounts it; Rust removed it entirely). Keybindings are client-side- only: no wire surface is touched by this flow."""- flow = "f23_keybindings"- frames: dict[str, dict[str, str]] = {"ts": {}, "rust": {}}- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- self.suppress_first_run_notices(side)- # The settings fixture, written before launch like a real- # user's file (the TS product loads it at TUI start; the Rust- # product at the same seam via the composition root). A plain- # printable key: both products check app actions before the- # editor, and a plain key survives any tmux/terminal encoding- # (a modifier combo like ctrl+alt+x depends on kitty/legacy- # encodings and would make the frame diff flaky).- (side.agent_dir / "keybindings.json").write_text(- json.dumps({"app.tools.expand": "x"}, indent=1) + NL- )- tui, ready = self.launch_tui(side, flow, P.launch_argv(side, side.daemon_socket), ready_marker=">")- side.evidence(flow, "00-ready.txt", ready)- # 1) The prompt-context hint renders the user's key, not the- # default ("Collapsed mode (X to expand)").- hint = B.tmux_wait_text(tui, r"mode \(X to expand\)", timeout=30)- side.evidence(flow, "01-detail-hint.txt", hint)- frames[side.name]["detail-hint"] = hint- if re.search(r"Collapsed mode \(X to expand\)", hint):- self.record(- flow, "visual",- f"{side.name}: the prompt-context hint renders the user override (X), not the default",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: the prompt-context hint did not render the user override",- evidence=side.root / flow / "01-detail-hint.txt",- lane=FLOW_LANES[flow],- )- # 2) The override key fires: overview -> details.- self.tui_send(tui, "x", enter=False)- time.sleep(1.0)- details = B.tmux_wait_text(tui, "Details mode", timeout=20)- side.evidence(flow, "02-override-fired.txt", details)- frames[side.name]["override-fired"] = details- if "Details mode" in details:- self.record(- flow, "visual",- f"{side.name}: the override key cycled the conversation detail",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: the override key did not fire the action",- evidence=side.root / flow / "02-override-fired.txt",- lane=FLOW_LANES[flow],- )- # 3) The removed default key no longer fires (the cycle must- # not reach the all-output mode).- self.tui_send(tui, "C-o", enter=False)- time.sleep(1.0)- after_default = self.settle_frame(tui, quiet_s=1.5, timeout=10)- side.evidence(flow, "03-default-key.txt", after_default)- frames[side.name]["default-key"] = after_default- if "All mode" not in after_default:- self.record(- flow, "visual",- f"{side.name}: the removed default key no longer cycles the detail",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: the default key still fired after the override",- evidence=side.root / flow / "03-default-key.txt",- lane=FLOW_LANES[flow],- )- # 4) `/hotkeys` documents the effective binding. The TS side- # renders the guide as chat rows (the whole guide in one- # 80-row capture); the Rust side mounts the read-only info- # panel (the operator's 2026-09-26 directive: the guide- # no longer floods the transcript) — the pane grows to 80- # rows on both sides, then Rust scrolls the panel to the- # guide's bottom with End. The two shapes differ BY- # DIRECTIVE, so this step records per-side findings and- # carries no cross-side frame diff.- B.tmux("resize-window", "-t", tui, "-x", "120", "-y", "80")- time.sleep(1.0)- self.tui_send(tui, "/hotkeys")- if side.name == "ts":- time.sleep(2.5)- guide = B.tmux_capture(tui)- side.evidence(flow, "04-hotkeys-guide.txt", guide)- frames[side.name]["hotkeys-guide"] = guide- if "Cycle overview" in guide and "Ctrl+O" not in guide:- self.record(- flow, "visual",- f"{side.name}: /hotkeys documents the effective override (X row)",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: /hotkeys did not show the effective override",- evidence=side.root / flow / "04-hotkeys-guide.txt",- lane=FLOW_LANES[flow],- )- else:- guide = B.tmux_wait_text(tui, "Hotkeys", timeout=30)- # The override's row sits mid-document: page down until- # the Other section (the expand-tools row, X vs the- # removed default Ctrl+O) rides the window — bounded by- # the guide's finite length, so the X-vs-Ctrl+O check- # reads the actual row, not an off-screen region.- for _ in range(12):- self.tui_send(tui, "PageDown", enter=False)- # tmux_wait_text returns the last frame on timeout,- # so the break condition reads the pattern in the- # returned frame, never the frame's mere existence.- if "Cycle overview" in B.tmux_wait_text(tui, "Cycle overview", timeout=4):- break- guide = self.settle_frame(tui, quiet_s=1.0, timeout=20)- side.evidence(flow, "04-hotkeys-guide.txt", guide)- frames[side.name]["hotkeys-guide"] = guide- if "Cycle overview" in guide and "Ctrl+O" not in guide:- self.record(- flow, "visual",- f"{side.name}: the /hotkeys info panel scrolled to the override's row (X, not Ctrl+O)",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: the /hotkeys info panel did not show the effective override",- evidence=side.root / flow / "04-hotkeys-guide.txt",- lane=FLOW_LANES[flow],- )- # Esc closes the panel deterministically: send the key,- # then poll until the panel's key-hint row is gone from- # the pane (the next step's ? must reach the EDITOR, not- # an open panel).- self.tui_send(tui, "Escape", enter=False)- deadline = time.time() + 20- closed = B.tmux_capture(tui)- while "Esc close" in closed and time.time() < deadline:- time.sleep(0.5)- closed = B.tmux_capture(tui)- if "Esc close" in closed:- self.record(- flow, "visual",- f"{side.name}: the /hotkeys info panel did not close on Esc",- evidence=side.root / flow / "04-hotkeys-guide.txt",- lane=FLOW_LANES[flow],- )- # 5) The `?` key. TS (`app.shortcuts`, empty editor) mounts- # the quick-shortcut guide and the next submission clears- # it (`clearShortcutGuide`); Rust REMOVED the guide (the- # operator's 2026-09-26 directive): the key types a- # literal `?` into the editor and the guide's vocabulary- # never mounts. Divergent BY DIRECTIVE — per-side- # findings, no cross-side frame diff.- if side.name == "ts":- self.tui_send(tui, "?", enter=False)- guide2 = B.tmux_wait_text(tui, "shell mode", timeout=30)- guide2 = self.settle_frame(tui, quiet_s=1.5, timeout=20)- side.evidence(flow, "05-shortcut-guide.txt", guide2)- frames[side.name]["shortcut-guide"] = guide2- if "shell mode" in guide2 and "full reference" in guide2:- self.record(- flow, "visual",- f"{side.name}: the ? quick-shortcut guide mounted with the effective bindings",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: the ? quick-shortcut guide did not render",- evidence=side.root / flow / "05-shortcut-guide.txt",- lane=FLOW_LANES[flow],- )- else:- self.tui_send(tui, "?", enter=False)- time.sleep(1.0)- guide2 = self.settle_frame(tui, quiet_s=1.5, timeout=20)- side.evidence(flow, "05-shortcut-guide.txt", guide2)- frames[side.name]["shortcut-guide"] = guide2- if "shell mode" not in guide2 and "full reference" not in guide2:- self.record(- flow, "visual",- f"{side.name}: the removed ? guide never mounts (operator directive)",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: the removed ? guide still mounted",- evidence=side.root / flow / "05-shortcut-guide.txt",- lane=FLOW_LANES[flow],- )- # Esc clears the typed `?` back to the empty editor:- # send the key, then poll until the `?` is gone from the- # pane (the typed char is the only `?` on this surface),- # so the closing submission starts from a clean editor.- self.tui_send(tui, "Escape", enter=False)- deadline = time.time() + 20- cleared_editor = B.tmux_capture(tui)- while "?" in cleared_editor and time.time() < deadline:- time.sleep(0.5)- cleared_editor = B.tmux_capture(tui)- # 6) The closing submission. TS clears the quick guide at its- # top; Rust's editor is already clean (the panel closed on- # Esc in step 4). Both sides run the turn and return to the- # ready prompt; the guide vocabulary must be gone from- # both frames.- self.tui_send(tui, "f23 closing turn")- cleared = self.settle_frame(tui, quiet_s=2.5, timeout=60)- side.evidence(flow, "06-guide-cleared.txt", cleared)- frames[side.name]["guide-cleared"] = cleared- if "shell mode" not in cleared and "full reference" not in cleared:- self.record(- flow, "visual",- f"{side.name}: the closing turn left the surface guide-free",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: the guide survived the closing submission",- evidence=side.root / flow / "06-guide-cleared.txt",- lane=FLOW_LANES[flow],- )- B.tmux_kill(tui)- # The detail-hint, override-fired, and default-key steps render- # identically on both sides (the keybindings engine is shared- # vocabulary); the /hotkeys and ? surfaces diverge BY OPERATOR- # DIRECTIVE (Rust: the read-only info panel + the removed guide),- # so only the shared steps carry the cross-side frame diff.- for step in ("detail-hint", "override-fired", "default-key"):- self.frame_diff(- flow, step,- {name: frames[name].get(step, "") for name in ("ts", "rust")},- self.normalize_transcript_frame,- )-- def f17_slash_model(self) -> None:- """/model and /effort pickers: the selector overlay open, a- selection through the picker, and the picker's confirm rows —- TS-identical result rows both sides."""- flow = "f17_slash_model"- frames: dict[str, dict[str, str]] = {"ts": {}, "rust": {}}- for side in (self.sides["ts"], self.sides["rust"]):- self.ensure_daemon(side)- self.suppress_first_run_notices(side)- tui, ready = self.launch_tui(side, flow, P.launch_argv(side, side.daemon_socket), ready_marker=">")- side.evidence(flow, "00-ready.txt", ready)- # /model: the selector overlay.- self.tui_send(tui, "/model")- time.sleep(2.5)- selector = B.tmux_capture(tui)- side.evidence(flow, "01-model-selector.txt", selector)- frames[side.name]["model-selector"] = selector- if "mock-1" in selector or "Mock 1" in selector:- self.record(flow, "visual", f"{side.name}: /model opens the selector with the configured model listed", gap=False)- else:- self.record(- flow, "visual",- f"{side.name}: /model selector did not list the configured mock model",- evidence=side.root / flow / "01-model-selector.txt",- lane=FLOW_LANES[flow],- )- # Select the model: type the search, confirm the first row.- self.tui_send(tui, "mock")- time.sleep(1.0)- self.tui_send(tui, "Enter", enter=False)- selected = B.tmux_wait_text(tui, "Model: |Switching model", timeout=30)- side.evidence(flow, "02-model-selected.txt", selected)- settled = self.settle_frame(tui, quiet_s=2.0, timeout=30)- side.evidence(flow, "03-model-selected-settled.txt", settled)- frames[side.name]["model-selected"] = settled- if "Model: " in settled:- self.record(flow, "visual", f"{side.name}: picking a model in the selector shows the 'Model: <id>' confirm row", gap=False)- else:- self.record(- flow, "visual",- f"{side.name}: no 'Model: <id>' confirm row after picking in the selector",- evidence=side.root / flow / "03-model-selected-settled.txt",- lane=FLOW_LANES[flow],- )- # /effort: the thinking-level picker (or the unsupported-model row).- self.tui_send(tui, "/effort")- time.sleep(2.5)- effort = B.tmux_capture(tui)- side.evidence(flow, "04-effort-picker.txt", effort)- frames[side.name]["effort-picker"] = effort- if "Thinking level" in effort or "thinking" in effort.lower():- self.record(- flow, "visual",- f"{side.name}: /effort shows the thinking-level picker or its unsupported-model row",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: /effort showed no thinking-level surface",- evidence=side.root / flow / "04-effort-picker.txt",- lane=FLOW_LANES[flow],- )- self.tui_send(tui, "Escape", enter=False)- time.sleep(0.5)- B.tmux_kill(tui)- for step in ("model-selector", "model-selected", "effort-picker"):- self.frame_diff(- flow, step,- {name: frames[name].get(step, "") for name in ("ts", "rust")},- self.normalize_transcript_frame,- )--- def f18_goal_autonomous(self) -> None:- """/goal lifecycle rows and /autonomous on/off rendering: the goal- start context row, the status/pause/resume rows, the completion row- (kernel `goal.complete()`), and the autonomous_status rows."""- flow = "f18_goal_autonomous"- reply = "f18 goal fixture reply"- objective = "f18 parity objective: land the battery flows"- frames: dict[str, dict[str, str]] = {"ts": {}, "rust": {}}- for side in (self.sides["ts"], self.sides["rust"]):- self.suppress_first_run_notices(side)- made = self.create_session(side, flow, "battery-f18", "c18")- if not made:- continue- wire, session_id = made- side.mock.set_responses([{"text": reply}])- wire.request(- "p18s", {"type": "prompt_and_wait", "activeSessionId": session_id, "message": "f18 seed turn"}, timeout=240- )- wire.close()- self.settle_mock(side)- attached = self.attach_tui(side, flow, session_id, ready_marker="f18 seed turn")- if not attached:- self.record(flow, "visual", f"{side.name}: attached TUI never rendered the seeded transcript")- continue- tui, ready = attached- side.evidence(flow, "00-attached.txt", ready)- # /goal <objective>: the start row, goal-context turn, tray- # label. Wait only for the row: with the goal active the TS- # daemon immediately starts driving [goal: continuation]- # turns, and the frame never goes quiet, so a settle here would- # burn its full timeout while the loop churns (runs- # 20260918T231155Z / 20260919T002527Z: the TS goal driver- # issued ~2900 continuation turns and starved queued composer- # input for minutes per command).- self.tui_send(tui, f"/goal {objective}")- settled = B.tmux_wait_text(tui, "Goal active|Pursuing goal|Goal context", timeout=30)- side.evidence(flow, "01-goal-start.txt", settled)- frames[side.name]["goal-start"] = settled- if ("Goal context" in settled or "Pursuing goal" in settled or "Goal active" in settled):- self.record(- flow, "visual",- f"{side.name}: /goal start renders the goal context row / active goal label",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: /goal start produced no visible goal row",- evidence=side.root / flow / "01-goal-start.txt",- lane=FLOW_LANES[flow],- )- # Pause immediately while the driver's queue is still shallow:- # every queued command lands after the loop drains (minutes when- # typed late), but lands within a turn or two when typed right- # after the start. Everything else in the flow then runs against- # a paused (quiet) goal driver.- self.tui_send(tui, "/goal pause")- settled = B.tmux_wait_text(tui, "Goal paused", timeout=120)- side.evidence(flow, "03-goal-pause.txt", settled)- frames[side.name]["goal-pause"] = settled- if "Goal paused" in settled:- self.record(flow, "visual", f"{side.name}: /goal pause renders the paused row", gap=False)- else:- self.record(- flow, "visual",- f"{side.name}: /goal pause produced no visible paused row",- evidence=side.root / flow / "03-goal-pause.txt",- lane=FLOW_LANES[flow],- )- # /goal (status): the status row (the driver is paused, so the- # frame settles normally).- self.tui_send(tui, "/goal")- settled = self.settle_frame(tui, quiet_s=3.0, timeout=30)- side.evidence(flow, "02-goal-status.txt", settled)- frames[side.name]["goal-status"] = settled- # /goal resume, then pause again before scripting responses: the- # resumed goal driver keeps issuing [goal: continuation] turns- # that drain the mock's response queue (run 20260918T231155Z:- # the loop fired ~870 continuation requests through the rest of- # the run and starved the f18 completion turn and the f21- # recovery turn). Pausing right after the resume capture keeps- # the churn to a turn or two.- self.tui_send(tui, "/goal resume")- settled = B.tmux_wait_text(tui, "Goal", timeout=15)- side.evidence(flow, "04-goal-resume.txt", settled)- frames[side.name]["goal-resume"] = settled- self.tui_send(tui, "/goal pause")- paused2 = B.tmux_wait_text(tui, "Goal paused", timeout=120)- side.evidence(flow, "04b-goal-pause-2.txt", paused2)- # Completion: the kernel's goal.complete() (scripted tool call).- # The 6s quiet window matters: the previous turn's status-line- # request can land seconds after the turn ends and would- # otherwise pop the scripted tool call out of the queue.- self.settle_mock(side, quiet_s=6.0, timeout=30.0)- code = "import goal; await goal.complete()"- side.mock.set_responses(- [- {"toolCall": {"name": "ipython", "arguments": {"code": code}}},- {"text": reply},- ]- )- self.tui_send(tui, "f18 finish the goal now")- settled = self.settle_frame(tui, quiet_s=4.0, timeout=120)- side.evidence(flow, "05-goal-complete.txt", settled)- frames[side.name]["goal-complete"] = settled- if "Goal complete" in settled:- self.record(flow, "visual", f"{side.name}: goal.complete() renders the completion row", gap=False)- else:- self.record(- flow, "visual",- f"{side.name}: goal.complete() produced no visible completion row",- evidence=side.root / flow / "05-goal-complete.txt",- lane=FLOW_LANES[flow],- )- # /autonomous on and off: the autonomous_status rows.- self.settle_mock(side)- side.mock.set_responses([{"text": reply}])- self.tui_send(tui, "/autonomous on")- settled = self.settle_frame(tui, quiet_s=3.0, timeout=60)- side.evidence(flow, "06-autonomous-on.txt", settled)- frames[side.name]["autonomous-on"] = settled- if "Autonomous" in settled or "autonomous" in settled:- self.record(flow, "visual", f"{side.name}: /autonomous on renders the autonomous status row", gap=False)- else:- self.record(- flow, "visual",- f"{side.name}: /autonomous on produced no visible status row",- evidence=side.root / flow / "06-autonomous-on.txt",- lane=FLOW_LANES[flow],- )- self.tui_send(tui, "/autonomous off")- settled = self.settle_frame(tui, quiet_s=3.0, timeout=60)- side.evidence(flow, "07-autonomous-off.txt", settled)- frames[side.name]["autonomous-off"] = settled- B.tmux_kill(tui)- self.copy_sessions(side, flow)- for step in ("goal-start", "goal-status", "goal-pause", "goal-resume", "goal-complete", "autonomous-on", "autonomous-off"):- self.frame_diff(- flow, step,- {name: frames[name].get(step, "") for name in ("ts", "rust")},- self.normalize_transcript_frame,- )--- def f19_heartbeat(self) -> None:- """/heartbeat visible surface: the set status row, the fired- heartbeat prompt row (the glyph diverges by directive: ts renders- the ♥ heart, rust the ◷ clock — the unified-activity-dock- Heartbeats icon), and the /heartbeats manager view."""- flow = "f19_heartbeat"- reply = "f19 heartbeat fixture reply"- frames: dict[str, dict[str, str]] = {"ts": {}, "rust": {}}- for side in (self.sides["ts"], self.sides["rust"]):- self.suppress_first_run_notices(side)- made = self.create_session(side, flow, "battery-f19", "c19")- if not made:- continue- wire, session_id = made- side.mock.set_responses([{"text": reply}])- wire.request(- "p19s", {"type": "prompt_and_wait", "activeSessionId": session_id, "message": "f19 seed turn"}, timeout=240- )- wire.close()- self.settle_mock(side)- attached = self.attach_tui(side, flow, session_id, ready_marker="f19 seed turn")- if not attached:- self.record(flow, "visual", f"{side.name}: attached TUI never rendered the seeded transcript")- continue- tui, ready = attached- side.evidence(flow, "00-attached.txt", ready)- # /heartbeat every 10s: the set status row.- self.tui_send(tui, "/heartbeat every 10s f19 heartbeat ping instruction")- settled = self.settle_frame(tui, quiet_s=3.0, timeout=60)- side.evidence(flow, "01-heartbeat-set.txt", settled)- frames[side.name]["heartbeat-set"] = settled- if "Heartbeat set" in settled:- self.record(flow, "visual", f"{side.name}: /heartbeat renders the 'Heartbeat set' status row", gap=False)- else:- self.record(- flow, "visual",- f"{side.name}: /heartbeat produced no 'Heartbeat set' status row",- evidence=side.root / flow / "01-heartbeat-set.txt",- lane=FLOW_LANES[flow],- )- # The heartbeat fires (10s schedule): the injected prompt row with- # the glyph prefix and schedule label, plus its model turn. The- # glyph diverges by directive (2026-09-23): the TS side keeps- # the ♥ heart; the Rust side renders the ◷ clock — the unified- # activity dock's Heartbeats icon.- fired = B.tmux_wait_text(tui, "Heartbeat prompt", timeout=60)- side.evidence(flow, "02-heartbeat-fired.txt", fired)- settled = self.settle_frame(tui, quiet_s=4.0, timeout=90)- side.evidence(flow, "03-heartbeat-fired-settled.txt", settled)- frames[side.name]["heartbeat-fired"] = settled- glyph_row = (- "♥ Heartbeat prompt · every 10s"- if side.name == "ts"- else "◷ Heartbeat prompt · every 10s"- )- if "Heartbeat prompt" not in settled:- self.record(- flow, "behavior",- f"{side.name}: the fired heartbeat produced no visible 'Heartbeat prompt' row",- evidence=side.root / flow / "03-heartbeat-fired-settled.txt",- lane=FLOW_LANES[flow],- )- elif glyph_row not in settled:- self.record(- flow, "behavior",- f"{side.name}: the fired heartbeat row renders no '{glyph_row}' glyph row",- evidence=side.root / flow / "03-heartbeat-fired-settled.txt",- lane=FLOW_LANES[flow],- )- else:- self.record(- flow, "behavior",- f"{side.name}: a fired heartbeat renders the '{glyph_row}' row",- gap=False,- )- # /heartbeats: the manager view.- self.tui_send(tui, "/heartbeats")- time.sleep(2.5)- manager = B.tmux_capture(tui)- side.evidence(flow, "04-heartbeats-manager.txt", manager)- frames[side.name]["heartbeats-manager"] = manager- if "Heartbeats" in manager and ("heartbeat" in manager.lower()):- self.record(flow, "visual", f"{side.name}: /heartbeats opens the heartbeat manager view", gap=False)- else:- self.record(- flow, "visual",- f"{side.name}: /heartbeats did not open a heartbeat manager view",- evidence=side.root / flow / "04-heartbeats-manager.txt",- lane=FLOW_LANES[flow],- )- self.tui_send(tui, "Escape", enter=False)- time.sleep(0.5)- # Stop the heartbeat so the daemon does not keep firing it.- self.tui_send(tui, "/heartbeat stop")- time.sleep(1.0)- B.tmux_kill(tui)- self.copy_sessions(side, flow)- for step in ("heartbeat-set", "heartbeat-fired", "heartbeats-manager"):- self.frame_diff(- flow, step,- {name: frames[name].get(step, "") for name in ("ts", "rust")},- self.normalize_transcript_frame,- )--- def f20_subagents(self) -> None:- """rlm.spawn() from the kernel, attached through the agents view: the- subagent summary line above the editor (live running counts, then the- child's `RLM child status` no-reply terminal notice), and the scoped- agents view opened from the focused summary line listing the child by- name — then the full main-chat keyboard path (the live-dogfood- ruling): back into the session through the view, Down at the end of- the prompt focuses the panel, Enter reopens the scoped view, Enter- drills into the child transcript, agents-back returns to the view.- Frame diff TS vs Rust at each key moment."""- flow = "f20_subagents"- reply = "f20 parent fixture reply"- child_reply = "f20 child fixture reply"- child_name = "f20-worker"- frames: dict[str, dict[str, str]] = {"ts": {}, "rust": {}}- for side in (self.sides["ts"], self.sides["rust"]):- made = self.create_session(side, flow, "battery-f20", "c20")- if not made:- continue- wire, session_id = made- side.mock.set_responses([{"text": reply}])- wire.request(- "p20s", {"type": "prompt_and_wait", "activeSessionId": session_id, "message": "f20 seed turn"}, timeout=240- )- wire.close()- self.settle_mock(side)- # TS suppresses the agents view while onboarding is pending- # (f9 precedent); suppress_first_run_notices marks the side- # onboarded so both products open the view directly. No --offline- # on this launch either: TS refuses to attach an active agent- # across a telemetry mismatch.- self.suppress_first_run_notices(side)- view = f"{self.runid}-f20-{side.name}"- B.tmux_launch(view, [side.binary, "agents", "--daemon-socket", str(side.daemon_socket)], side.env, side.work_dir)- listed = B.tmux_wait_text(view, "Running \(|Idle \(|Inactive \(|No sessions", timeout=30)- side.evidence(flow, "00-agents-view.txt", listed)- # Open the parent session from the view: the conversation then- # carries returnToAgentsView, which is what makes the subagent- # summary line openable into the scoped view.- B.tmux_send(view, "battery-f20")- time.sleep(1.0)- B.tmux_send(view, "Enter", enter=False)- attached = B.tmux_wait_text(view, "f20 seed turn", timeout=60)- if "f20 seed turn" not in attached:- self.record(flow, "visual", f"{side.name}: opening battery-f20 from the agents view did not attach to the seeded session", evidence=side.root / flow / "00-agents-view.txt")- B.tmux_kill(view)- continue- # Kernel rlm.spawn through the attached editor: the ipython cell- # spawns one named child. The child's own model turn and the- # parent's post-tool continuation hit the mock concurrently and- # TS itself flips their arrival order between runs, so a single- # shared response queue makes the transcript race on which side- # pops which text. The script is SESSION-SCOPED: the child's- # [task from parent] user message routes its requests to a- # child queue (child_reply), while the parent stays on the- # default queue (tool call, then its own continuation replies),- # so both sides deterministically render the parent's fixture- # reply around the child-exited notice turn. The child finishes- # without an agent_message reply and the parent receives the- # no-reply terminal notice.- self.settle_mock(side)- mark = len(side.mock.requests())- code = (- "import rlm; await rlm.spawn("- "'f20 child task: reply with the fixture summary', "- f"name={child_name!r})"- )- side.mock.set_responses(- [- {"toolCall": {"name": "ipython", "arguments": {"code": code}}},- # The parent's post-tool continuation, then its- # [child-exited: no-reply] notice turn: same fixture- # reply both times (the status-line requests that can- # interleave pop the same text harmlessly).- {"text": reply},- {"text": reply},- ],- queues=[- {- "name": child_name,- "match": ["f20 child task"],- "responses": [{"text": child_reply}],- }- ],- )- self.tui_send(view, "f20 spawn the subagent now")- spawned = B.tmux_wait_text(view, "subagents", timeout=180)- side.evidence(flow, "01-spawn.txt", spawned)- settled = self.settle_frame(view, quiet_s=3.0, timeout=90)- side.evidence(flow, "02-spawn-settled.txt", settled)- frames[side.name]["spawn"] = settled- if "subagents" in settled:- self.record(- flow, "visual",- f"{side.name}: a kernel rlm.spawn renders the subagent summary line above the editor with the running/idle/inactive counts",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: a kernel rlm.spawn produced no visible subagent summary line",- evidence=side.root / flow / "02-spawn-settled.txt",- lane=FLOW_LANES.get(flow),- )- # Child completion without a reply: the `RLM child status`- # terminal-notice row in the parent transcript.- noticed = B.tmux_wait_text(view, "RLM child status", timeout=240)- side.evidence(flow, "03-child-status.txt", noticed)- settled2 = self.settle_frame(view, quiet_s=3.0, timeout=90)- side.evidence(flow, "04-child-status-settled.txt", settled2)- frames[side.name]["child-status"] = settled2- if "RLM child status" in settled2:- self.record(- flow, "visual",- f"{side.name}: a child finishing without a reply renders the 'RLM child status' terminal-notice row in the parent transcript",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: the completed child produced no 'RLM child status' terminal-notice row",- evidence=side.root / flow / "04-child-status-settled.txt",- lane=FLOW_LANES.get(flow),- )- # The scoped agents view: alt+a focuses the summary line,- # confirm opens the child list.- self.tui_send(view, "M-a", enter=False)- time.sleep(1.0)- focused = B.tmux_capture(view)- side.evidence(flow, "05-summary-focused.txt", focused)- B.tmux_send(view, "Enter", enter=False)- scoped = B.tmux_wait_text(view, child_name, timeout=60)- side.evidence(flow, "06-scoped-agents.txt", scoped)- settled3 = self.settle_frame(view, quiet_s=2.0, timeout=30)- side.evidence(flow, "07-scoped-agents-settled.txt", settled3)- frames[side.name]["scoped-agents"] = settled3- if child_name in settled3:- self.record(- flow, "visual",- f"{side.name}: the scoped agents view lists the spawned child by name",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: the scoped agents view did not list the spawned child",- evidence=side.root / flow / "07-scoped-agents-settled.txt",- lane=FLOW_LANES.get(flow),- )- # Deterministic-routing evidence: the session-scoped mock split- # the spawn turn by session — every request the child queue- # served carries the child's task user message, and no request- # carrying it was served from the default queue.- turn_requests = [- req- for req in self.new_mock_requests(side, mark)- if req["body"].get("model") == "mock-1" and not is_statusline_request(req)- ]- child_queued = [req for req in turn_requests if req.get("queue") == child_name]- default_queued = [req for req in turn_requests if req.get("queue") == "default"]- misrouted_child = [- req for req in child_queued if "f20 child task" not in user_message_text(req["body"])- ]- misrouted_parent = [- req for req in default_queued if "f20 child task" in user_message_text(req["body"])- ]- if len(child_queued) >= 1 and not misrouted_child and not misrouted_parent:- self.record(- flow, "behavior",- f"{side.name}: the session-scoped mock routed the spawn turn deterministically "- f"({len(child_queued)} child-session request(s) to the child queue, {len(default_queued)} parent-session request(s) to the default queue)",- gap=False,- )- else:- self.record(- flow, "behavior",- f"{side.name}: the session-scoped mock misrouted the spawn turn "- f"(child-queue requests: {len(child_queued)}, misrouted child: {len(misrouted_child)}, misrouted parent: {len(misrouted_parent)})",- evidence=side.root / flow / "01-spawn.txt",- )- # The keyboard path from the MAIN CHAT (the live-dogfood ruling):- # the panel takes focus with Down at the end of the prompt, Enter- # opens the scoped view, Enter drills into the child transcript,- # and the agents-back key returns to the view. The route back to- # the session runs through the view: the scoped view's parent- # key pops the scope, and the global view's parent row reopens- # the transcript.- B.tmux_send(view, "Left", enter=False)- time.sleep(1.0)- B.tmux_send(view, "battery-f20")- time.sleep(1.0)- B.tmux_send(view, "Enter", enter=False)- reattached = B.tmux_wait_text(view, "f20 seed turn", timeout=60)- if "f20 seed turn" not in reattached:- self.record(- flow, "visual",- f"{side.name}: the parent row did not reopen the session from the global view",- evidence=side.root / flow / "07-scoped-agents-settled.txt",- )- B.tmux_kill(view)- continue- side.evidence(flow, "08-reattached.txt", reattached)- settled4 = self.settle_frame(view, quiet_s=2.0, timeout=30)- side.evidence(flow, "09-reattached-settled.txt", settled4)- frames[side.name]["reattached"] = settled4- # Down at the end of the empty prompt hands the focus to the- # panel: the `↓ select` hint flips to the focused open pair (TS- # `onMoveBelowPrompt` -> `focusSubagentSummary`).- B.tmux_send(view, "Down", enter=False)- time.sleep(1.0)- focused = B.tmux_capture(view)- side.evidence(flow, "10-panel-focused.txt", focused)- frames[side.name]["panel-focused"] = focused- if "Enter/→ open" in focused and "subagents" in focused:- self.record(- flow, "visual",- f"{side.name}: Down at the end of the prompt focuses the subagent panel (the hint flips to the focused open pair)",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: Down at the end of the prompt did not focus the subagent panel",- evidence=side.root / flow / "10-panel-focused.txt",- )- B.tmux_send(view, "Enter", enter=False)- scoped2 = B.tmux_wait_text(view, child_name, timeout=60)- side.evidence(flow, "11-scoped-again.txt", scoped2)- # Enter on the child row drills into the child's transcript- # (`[task from parent]` is the child's own user row; it never- # renders in the parent, whose tool rows carry only the spawn- # code).- B.tmux_send(view, "Enter", enter=False)- drilled = B.tmux_wait_text(view, "task from parent", timeout=60)- side.evidence(flow, "12-child-transcript.txt", drilled)- settled5 = self.settle_frame(view, quiet_s=2.0, timeout=30)- side.evidence(flow, "13-child-transcript-settled.txt", settled5)- frames[side.name]["child-transcript"] = settled5- if child_reply in settled5:- self.record(- flow, "visual",- f"{side.name}: Enter on the child row drills into the child transcript",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: Enter on the child row did not open the child transcript",- evidence=side.root / flow / "13-child-transcript-settled.txt",- )- # The agents-back key (empty editor) returns to the view.- B.tmux_send(view, "Left", enter=False)- backed = B.tmux_wait_text(view, child_name, timeout=60)- side.evidence(flow, "14-back-to-view.txt", backed)- settled6 = self.settle_frame(view, quiet_s=2.0, timeout=30)- side.evidence(flow, "15-back-to-view-settled.txt", settled6)- frames[side.name]["back-to-view"] = settled6- if child_name in settled6:- self.record(- flow, "visual",- f"{side.name}: the agents-back key returns from the child transcript to the view",- gap=False,- )- else:- self.record(- flow, "visual",- f"{side.name}: the agents-back key did not return to the view",- evidence=side.root / flow / "15-back-to-view-settled.txt",- )- B.tmux_kill(view)- self.copy_sessions(side, flow)- for step in ("spawn", "child-status", "scoped-agents", "reattached", "panel-focused", "child-transcript", "back-to-view"):- self.frame_diff(- flow, step,- {name: frames[name].get(step, "") for name in ("ts", "rust")},- self.normalize_transcript_frame,- )-- def f21_worker_recovery(self) -> None:- """Worker crash recovery: SIGKILL the session's live worker process- (pid from the daemon's own session summary), then keep using the- session through the attached TUI. Frame diff TS vs Rust at the- post-kill and post-recovery key moments.-- TS ground truth (captured 2026-09-18/19, deterministic across runs):- in this scenario's topology — a session created over the daemon wire- by a client that then disconnects, with the TUI attached as a- NON-owner — the TS daemon parks the dead worker "failed" (its- `recoverWorker` can only relaunch a client-owned worker whose owner- can re-supply launch env) and the session does NOT survive within- the daemon's lifetime: get_state fails with "Session worker is- failed", the TUI keeps the transcript, shows "Daemon connection- lost; reconnecting…", the follow-up submit fails with- "⚠ Error: Session worker is failed" and finally- "⚠ Error: Daemon reconnection failed: Session worker is failed",- with the typed text preserved in the input. TS's OWNED path (a TUI- that created the session, attaching with launch env + recovery- config) respawns the worker and re-attaches transparently — that is- the behavior contract the ARCHITECTURE.md supervisor redesign- generalizes ("workers are supervised, restarted with backoff").-- PARITY RULING (this lane): Rust must recover (not replicate the- unowned park): the supervisor owns every worker's create command, so- the respawn is always safe, and the attached TUI re-attaches over- the supervisor with the TS reconnect surface — the "Daemon- connection lost; reconnecting…" warning, the resync, and- "Daemon reconnected" on success. The TS rows below stay- EXPECTED-FAIL with this ruling documented; the frame diffs differ- by design (TS fails the follow-up turn, Rust completes it)."""- flow = "f21_worker_recovery"- reply = "f21 recovery fixture reply"- followup = "f21 post-recovery fixture reply"- frames: dict[str, dict[str, str]] = {"ts": {}, "rust": {}}- for side in (self.sides["ts"], self.sides["rust"]):- self.suppress_first_run_notices(side)- made = self.create_session(side, flow, "battery-f21", "c21")- if not made:- continue- wire, session_id = made- # The daemon's own session summary names the worker pid.- state = wire.request(- "g21", {"type": "get_state", "activeSessionId": session_id}, timeout=60- )- side.evidence_json(flow, "00-state.json", state)- summary = state.get("data") or {}- worker_pid = summary.get("workerPid")- worker_state = summary.get("workerState")- if state.get("success") is True and isinstance(worker_pid, int):- self.record(- flow, "protocol",- f"{side.name}: the session summary exposes the live worker pid (workerState: {worker_state})",- gap=False,- )- else:- self.record(- flow, "protocol",- f"{side.name}: the session summary exposes no live worker pid",- evidence=side.root / flow / "00-state.json",- lane=FLOW_LANES[flow],- )- # Seed turn: durable content the recovered worker must restore.- side.mock.set_responses([{"text": reply}])- wire.request(- "p21s", {"type": "prompt_and_wait", "activeSessionId": session_id, "message": "f21 seed turn"}, timeout=240- )- wire.close()- self.settle_mock(side)- attached = self.attach_tui(side, flow, session_id, ready_marker="f21 seed turn")- if not attached:- self.record(flow, "visual", f"{side.name}: attached TUI never rendered the seeded transcript")- continue- tui, ready = attached- side.evidence(flow, "01-attached.txt", ready)- # Key moment 1: the worker dies underneath the attached TUI. The- # visible frame must keep the transcript; recovery is invisible- # until the next command needs the worker.- killed = False- if isinstance(worker_pid, int):- try:- os.kill(worker_pid, signal.SIGKILL)- killed = True- except OSError as error:- self.record(- flow, "behavior",- f"{side.name}: could not kill the reported worker pid {worker_pid}: {error}",- evidence=side.root / flow / "00-state.json",- )- if not killed:- self.record(- flow, "behavior",- f"{side.name}: no live worker pid to kill; recovery cannot be exercised",- evidence=side.root / flow / "00-state.json",- lane=FLOW_LANES[flow],- )- B.tmux_kill(tui)- continue- time.sleep(2.0)- post_kill = B.tmux_capture(tui)- side.evidence(flow, "02-post-kill.txt", post_kill)- settled = self.settle_frame(tui, quiet_s=2.0, timeout=30)- side.evidence(flow, "03-post-kill-settled.txt", settled)- frames[side.name]["post-kill"] = settled- if "f21 seed turn" in settled:- self.record(- flow, "behavior",- f"{side.name}: the attached TUI keeps the transcript after the worker process is killed",- gap=False,- )- else:- self.record(- flow, "behavior",- f"{side.name}: the attached TUI lost the transcript after the worker process was killed",- evidence=side.root / flow / "03-post-kill-settled.txt",- lane=FLOW_LANES[flow],- )- # The reconnection surface (TS `connection_status` rows): the- # frame must carry the reconnecting warning while the link is- # down, or the reconnected status once the re-attach landed.- if (- "Daemon connection lost; reconnecting…" in settled- or "Daemon reconnected" in settled- ):- self.record(- flow, "behavior",- f"{side.name}: the worker death surfaces the daemon reconnection status row",- gap=False,- )- else:- self.record(- flow, "behavior",- f"{side.name}: the worker death never surfaced a reconnection status row",- evidence=side.root / flow / "03-post-kill-settled.txt",- lane=FLOW_LANES[flow],- )- post_kill_wire = B.Wire(side.daemon_socket)- post_kill_state = post_kill_wire.request(- "g21k", {"type": "get_state", "activeSessionId": session_id}, timeout=120- )- post_kill_wire.close()- side.evidence_json(flow, "04-post-kill-state.json", post_kill_state)- # Key moment 2: the next prompt goes through. The daemon respawns- # the worker (journal + session file restore), the turn completes,- # and the frame shows the recovered transcript plus the new reply.- self.settle_mock(side)- side.mock.set_responses([{"text": followup}])- self.tui_send(tui, "f21 keep working after the crash")- recovered = B.tmux_wait_text(tui, followup, timeout=240)- side.evidence(flow, "05-recovered.txt", recovered)- settled2 = self.settle_frame(tui, quiet_s=3.0, timeout=90)- side.evidence(flow, "06-recovered-settled.txt", settled2)- frames[side.name]["recovered"] = settled2- if "f21 seed turn" in settled2 and followup in settled2:- self.record(- flow, "behavior",- f"{side.name}: after the worker is killed the session recovers — the next turn completes with the transcript intact",- gap=False,- )- elif side.name == "ts":- # Ground truth, not a Rust parity target: the ruling above.- self.record(- flow, "behavior",- "ts ground truth (EXPECTED-FAIL, ruling in the flow docstring): the wire-created (unowned) session "- "does not survive its worker's death — the daemon parks the worker failed and the follow-up submit "- "fails with \"Session worker is failed\"; the owned-path respawn is the behavior Rust ports",- evidence=side.root / flow / "06-recovered-settled.txt",- lane=FLOW_LANES[flow],- )- else:- self.record(- flow, "behavior",- "rust: the session did not survive its worker's death (no post-recovery turn) — the re-attach driver must complete the turn",- evidence=side.root / flow / "06-recovered-settled.txt",- lane=FLOW_LANES[flow],- )- # TS's failed-submit surface is ground truth (documented, not- # ported); Rust must never surface it once the re-attach works.- if side.name == "ts" and "Session worker is failed" in settled2:- self.record(- flow, "behavior",- "ts ground truth: the failed follow-up surfaces the \"⚠ Error: Session worker is failed\" and "- "\"⚠ Error: Daemon reconnection failed: Session worker is failed\" rows with the typed text preserved in the input",- gap=False,- )- if side.name == "rust" and "Session worker is failed" in settled2:- self.record(- flow, "behavior",- "rust: the recovered session surfaces the TS failure rows (\"Session worker is failed\") — the re-attach must recover instead",- evidence=side.root / flow / "06-recovered-settled.txt",- lane=FLOW_LANES[flow],- )- # Wire-level: the recovered session must be served by a new,- # ready worker process.- recovered_wire = B.Wire(side.daemon_socket)- recovered_state = recovered_wire.request(- "g21r", {"type": "get_state", "activeSessionId": session_id}, timeout=120- )- recovered_wire.close()- side.evidence_json(flow, "07-post-recovery-state.json", recovered_state)- rsummary = recovered_state.get("data") or {}- if (- recovered_state.get("success") is True- and rsummary.get("workerState") == "ready"- and rsummary.get("workerPid") not in (None, worker_pid)- ):- self.record(- flow, "protocol",- f"{side.name}: recovery respawned the worker (pid {worker_pid} -> {rsummary.get('workerPid')}, workerState ready)",- gap=False,- )- elif side.name == "ts":- # Ground truth, not a Rust parity target: the ruling above.- self.record(- flow, "protocol",- "ts ground truth (EXPECTED-FAIL, ruling in the flow docstring): get_state fails with "- f"\"{recovered_state.get('error') or 'Session worker is failed'}\" — the unowned worker stays parked failed, no new ready worker in this daemon's lifetime",- evidence=side.root / flow / "07-post-recovery-state.json",- lane=FLOW_LANES[flow],- )- else:- self.record(- flow, "protocol",- f"rust: recovery did not produce a new ready worker (workerState: {rsummary.get('workerState')}, workerPid: {rsummary.get('workerPid')})",- evidence=side.root / flow / "07-post-recovery-state.json",- lane=FLOW_LANES[flow],- )- B.tmux_kill(tui)- self.copy_sessions(side, flow)- for step in ("post-kill", "recovered"):- self.frame_diff(- flow, step,- {name: frames[name].get(step, "") for name in ("ts", "rust")},- self.normalize_transcript_frame,- )-- def perf_onboard(self, side: B.Side) -> None:- """Settle first-run dialogs (the TS trace notice) once before measuring,- so measured launches settle straight into the main screen. The settle- launch is the same flagged invocation `P.launch_argv` every measured- launch uses: the Rust onboarding gate fires only with explicit- provider/model flags (TS resolves the startup model from settings),- so a flagless settle run would answer nothing and the notice would- surface (and stall) the measured launches instead."""- socket = side.root / "perf" / "onboard.sock"- socket.parent.mkdir(parents=True, exist_ok=True)- if socket.exists():- socket.unlink()- session = f"{self.runid}-perf-onboard-{side.name}"- argv = P.launch_argv(side, socket)- B.tmux_launch(session, argv, side.env, side.work_dir)- deadline = time.time() + 30- while time.time() < deadline:- frame = B.tmux_capture(session)- if "Share agent traces" in frame:- B.tmux_send(session, "Down")- time.sleep(0.5)- B.tmux_send(session, "Enter")- time.sleep(1.0)- elif P.is_ready(side.name, frame):- break- else:- time.sleep(0.5)- deadline = time.time() + 30- while time.time() < deadline:- if P.is_ready(side.name, B.tmux_capture(session)):- break- time.sleep(0.5)- B.tmux_kill(session)- P.stop_perf_daemon(socket)-- def f10_perf(self) -> None:- """PERF row: cold startup + keystroke-to-render latency, Rust vs TS."""- flow = "f10_perf"- measurements: dict[str, dict] = {}- for side in (self.sides["ts"], self.sides["rust"]):- self.perf_onboard(side)- binary_path = shutil.which(side.binary) or side.binary- binary_bytes = None- if Path(binary_path).is_file():- binary_bytes = os.path.getsize(binary_path)- measurements[side.name] = {- "binary": side.binary,- "binary_bytes": binary_bytes,- "ready_s": [],- "first_frame_s": [],- "typing_ms": [],- }- # Interleave the measured launches (ts run i, rust run i, ts run i+1,- # ...) so background load on the box hits both sides evenly; a- # per-side block would let one side measure during a build and bias- # the differential.- for i in range(PERF_RUNS):- for side in (self.sides["ts"], self.sides["rust"]):- socket = side.root / "perf" / f"sock-{i}.sock"- rec = P.measure_launch(- side, f"{self.runid}-perf-{side.name}-{i}", socket- )- side.evidence_json(flow, f"launch-{i}.json", rec)- P.stop_perf_daemon(socket)- if rec["ready_s"] is None:- self.record(- flow,- "perf",- f"{side.name}: measured launch {i} never reached an interactive-ready frame within 60s",- evidence=side.root / flow / f"launch-{i}.json",- )- continue- bucket = measurements[side.name]- bucket["ready_s"].append(rec["ready_s"])- bucket["first_frame_s"].append(rec["first_frame_s"] or rec["ready_s"])- bucket["typing_ms"].extend(rec["typing_ms"])- for side in (self.sides["ts"], self.sides["rust"]):- bucket = measurements[side.name]- side.evidence_json(flow, "summary.json", bucket)- ready = P.median(bucket["ready_s"])- typing = P.summarize(bucket["typing_ms"])- if ready is not None:- self.record(- flow,- "perf",- f"{side.name}: cold startup to interactive-ready median {ready:.3f}s "- f"over {len(bucket['ready_s'])} launches (first frame median {P.median(bucket['first_frame_s']):.3f}s); "- f"typing latency median {typing['median']}ms, p95 {typing['p95']}ms "- f"over {typing['n']} keystrokes",- gap=False,- )- ts = measurements["ts"]- rs = measurements["rust"]- # Startup threshold: rust median cold startup vs the TS binary.- ts_ready = P.median(ts["ready_s"])- rs_ready = P.median(rs["ready_s"])- if ts_ready is not None and rs_ready is not None:- ratio = rs_ready / ts_ready- detail = (- f"startup: rust {rs_ready:.3f}s vs ts {ts_ready:.3f}s cold-ready median "- f"(ratio {ratio:.2f}, threshold {PERF_STARTUP_MAX_RATIO})"- )- if ratio <= PERF_STARTUP_MAX_RATIO:- self.record(flow, "perf", detail, gap=False)- else:- self.record(flow, "perf", f"REGRESSION {detail}", evidence=rs["binary"])- else:- self.record(flow, "perf", "startup threshold not evaluable: a side never reached ready", gap=True)- # Typing threshold: rust p95 keystroke latency vs the TS binary.- ts_p95 = P.summarize(ts["typing_ms"]).get("p95")- rs_p95 = P.summarize(rs["typing_ms"]).get("p95")- if ts_p95 is not None and rs_p95 is not None:- ratio = rs_p95 / ts_p95- detail = (- f"typing: rust p95 {rs_p95}ms vs ts p95 {ts_p95}ms keystroke-to-render "- f"(ratio {ratio:.2f}, threshold {PERF_TYPING_MAX_RATIO})"- )- if ratio <= PERF_TYPING_MAX_RATIO:- self.record(flow, "perf", detail, gap=False)- else:- self.record(flow, "perf", f"REGRESSION {detail}", evidence=rs["binary"])- else:- self.record(flow, "perf", "typing threshold not evaluable: a side produced no keystroke samples", gap=True)- # Release-build note: the perf row is only meaningful against a- # release build; a debug binary is a finding, not a baseline. The- # workspace release profile keeps line-tables-only debug info- # (~103MB); a debug build of the same tree measures ~290MB, so the- # size threshold sits between them.- size_mb = (rs["binary_bytes"] or 0) / 1_000_000- if "/debug/" in rs["binary"] or (rs["binary_bytes"] or 0) > 150_000_000:- self.record(- flow,- "perf",- f"rust binary measured is a debug build ({rs['binary']}, {size_mb:.0f}MB); "- "the perf posture is cargo build --release",- evidence=rs["binary"],- )- else:- self.record(- flow,- "perf",- f"rust binary measured: {rs['binary']} ({size_mb:.1f}MB, release posture)",- gap=False,- )-- # -- report ----------------------------------------------------------------- def write_report(self) -> Path:- path = self.run_dir / "report.md"- lines = [f"# Parity battery run {self.stamp}", ""]- # Battery greenness is scoped: it proves only the scripted flows- # below, never overall product parity.- lines.append(- "Note: 0 gaps below covers only these scripted flows; it is not a product-parity verdict."- )- lines.append(f"- ts binary: {self.ts_bin}")- lines.append(f"- rust binary: {self.rust_bin}")- lines.append(f"- flows: {', '.join(self.flows)}")- lines.append("")- lines.append("## Findings")- lines.append("")- gaps = [f for f in self.findings if f["gap"]]- oks = [f for f in self.findings if not f["gap"]]- expected = [f for f in gaps if f.get("expectedFail")]- unexpected = [f for f in gaps if not f.get("expectedFail")]- lines.append(- f"{len(unexpected)} gaps, {len(expected)} EXPECTED-FAIL (known gaps, owner lanes), {len(oks)} parity checks passed."- )- if expected:- lines.append("")- lines.append("## Known gaps (EXPECTED-FAIL — evidence for the owning fix lanes)")- lines.append("")- for finding in expected:- ev = f" — evidence: {finding['evidence']}" if finding.get("evidence") else ""- lines.append(- f"- [{finding['flow']}/{finding['category']}] EXPECTED-FAIL (lane: {finding['expectedFail']}): {finding['summary']}{ev}"- )- lines.append("")- current = None- for finding in unexpected:- if finding["flow"] != current:- current = finding["flow"]- lines.append(f"### {current}")- lines.append("")- ev = f" — evidence: {finding['evidence']}" if finding.get("evidence") else ""- lines.append(f"- [{finding['category']}] {finding['summary']}{ev}")- lines.append("")- lines.append("## Passed checks")- lines.append("")- for finding in oks:- lines.append(f"- [{finding['flow']}/{finding['category']}] {finding['summary']}")- lines.append("")- path.write_text(NL.join(lines))- (self.run_dir / "findings.json").write_text(json.dumps(self.findings, indent=1))- return path-- def run(self) -> int:- print(f"battery run dir: {self.run_dir}")- # Fail fast before any flow: the battery's parity tables are only a- # parity claim when the ts side is the deployed TS product, not this- # repo's Rust build masquerading as `prime-agent` on PATH.- ts_identity.assert_ts_side_is_the_ts_product(self.ts_bin, self.rust_bin)- self.make_side("ts", self.ts_bin)- self.make_side("rust", self.rust_bin)- order = {- f: getattr(self, f)- for f in ALL_FLOWS + HEAVY_FLOWS- if callable(getattr(self, f, None))- }- try:- for flow in self.flows:- if flow not in order:- print(f"== {flow} (skipped: flow not implemented in this build)", flush=True)- continue- print(f"== {flow}", flush=True)- order[flow]()- finally:- self.kill_tmux_sessions()- self.stop()- report = self.write_report()- gaps = sum(1 for f in self.findings if f["gap"])- print(NL + report.read_text()[:4000])- print(f"report: {report}")- return 0---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- here = Path(__file__).resolve().parent- repo = here.parent.parent- parser.add_argument("--flows", default=",".join(ALL_FLOWS))- parser.add_argument("--ts-bin", default="prime-agent")- parser.add_argument("--rust-bin", default=str(repo / "target" / "release" / "prime-agent"))- parser.add_argument("--runs-root", default=str(here / "runs"))- args = parser.parse_args()- flows = [f.strip() for f in args.flows.split(",") if f.strip()]- for flow in flows:- if flow not in ALL_FLOWS and flow not in HEAVY_FLOWS:- parser.error(f"unknown flow {flow}; valid: {ALL_FLOWS + HEAVY_FLOWS}")- # Fail fast on a stale rust build: a binary older than the checkout's- # newest product commit produces false gap rows (the 20260920 f7+f14- # run crashed at report-write with a stale binary in the checkout).- stale = B.rust_binary_staleness(Path(args.rust_bin), repo)- if stale:- print(f"STALE RUST BINARY: {stale}", file=sys.stderr)- return 2- battery = Battery(Path(args.runs_root), args.ts_bin, args.rust_bin, flows)- return battery.run()---if __name__ == "__main__":- raise SystemExit(main())diff --git a/scripts/battery/spinner_cadence.py b/scripts/battery/spinner_cadence.pydeleted file mode 100644index adf304cde9..0000000000--- a/scripts/battery/spinner_cadence.py+++ /dev/null@@ -1,118 +0,0 @@-#!/usr/bin/env python3-"""Spinner cadence probe (lane cpu-spin).--The spinner phase must advance on the wall clock (~80ms per frame, TS-`Loader.DEFAULT_INTERVAL_MS`), constant regardless of the render rate.-Drives a long tool-execution turn (a quiet animating window: no stream-deltas, only the loader advances), samples the pane as fast as tmux-allows, and asserts the observed glyph transitions: sequential phases-(+1 mod 10), each within the cadence budget.-"""-import argparse, json, os, re, shutil, subprocess, sys, tempfile, time-from pathlib import Path-sys.path.insert(0, str(Path(__file__).parent))-import sustained_cpu as sc--FRAMES = sc.SPINNERS # 10 braille loader frames-TOOL_SLEEP_S = 40-WINDOW_S = 10.0-CADENCE_MS = 80.0-# budget: capture+render latency adds noise, but the phase boundaries are-# periodic - every observed transition must sit inside this window.-MIN_INTERVAL_MS, MAX_INTERVAL_MS = 50.0, 130.0--def faux_script():- return {- "engine": "faux", "modelId": "faux-1", "modelName": "Faux Model",- "reasoning": False, "contextWindow": 128000, "tokensPerSecond": 200,- "responses": [- {"content": [{"type": "toolCall", "name": "ipython",- "arguments": {"code": f"import time; time.sleep({TOOL_SLEEP_S})"}}]},- {"text": "spinner-turn-settled"},- ],- }--def run(out_path):- base = tempfile.mkdtemp(prefix="spinner-probe-")- script_path = os.path.join(base, "faux.json")- with open(script_path, "w") as f:- json.dump(faux_script(), f, indent=1)- shared_cwd = os.path.join(base, "cwd"); os.makedirs(shared_cwd)- home = os.path.join(base, "home"); agent = os.path.join(base, "agent")- os.makedirs(os.path.join(agent, "sessions"))- with open(os.path.join(agent, "settings.json"), "w") as f:- json.dump({"onboardingCompleted": True}, f)- session = "cpu-spinner"- sc.tmux("kill-session", "-t", session, check=False)- sc.tmux("new-session", "-d", "-s", session, "-x", sc.SIZE[0], "-y", sc.SIZE[1], "-c", shared_cwd)- env = (f"HOME={home} PRIME_AGENT_CODING_AGENT_DIR={agent} "- f"PRIME_AGENT_FAUX_SCRIPT={script_path} PRIME_AGENT_DISABLE_ANALYTICS=1")- rust = os.environ.get("PA_RUST_BINARY")- assert rust, "PA_RUST_BINARY required"- package_dir = os.environ.get("PI_PACKAGE_DIR") or sc.find_runtime_package_dir()- command = (f"PI_PACKAGE_DIR={package_dir} {rust} "- f"--daemon-socket {agent}/daemon.sock --model faux-1")- sc.tmux("send-keys", "-t", session, f"{env} {command}", "Enter")- sc.wait_ready(session)- sc.tmux("send-keys", "-t", session, "Run it.")- sc.tmux("send-keys", "-t", session, "Enter")- # wait for the loader- deadline = time.time() + 30- while time.time() < deadline:- if re.search(sc.SPINNER_CLASS, sc.capture(session)):- break- time.sleep(0.1)- samples = []- t_end = time.time() + WINDOW_S- while time.time() < t_end:- pane = sc.capture(session)- m = re.search(sc.SPINNER_CLASS, pane)- if m:- samples.append((time.time(), FRAMES.index(m.group(0))))- # collapse to transitions- transitions = []- for t, idx in samples:- if not transitions or transitions[-1][1] != idx:- transitions.append((t, idx))- intervals = [round((b[0] - a[0]) * 1000, 1)- for a, b in zip(transitions, transitions[1:])]- # phase steps: +1 mod 10 between consecutive transitions (drops from- # capture misses are +n; jumps BACKWARD are render races)- steps = [(b[1] - a[1]) % 10 for a, b in zip(transitions, transitions[1:])]- forward = all(0 < s <= 5 for s in steps)- failures = []- if len(intervals) < 8:- failures.append(f"too few transitions ({len(transitions)})")- bad = [i for i in intervals if not (MIN_INTERVAL_MS <= i <= MAX_INTERVAL_MS)]- # Capture noise: pane captures are not atomic with the loader row (the- # tool card grows, the loader row moves), so a run can show a couple of- # impossible intervals (two real 80ms-clock advances never land 8ms- # apart). A small outlier fraction is capture noise; a render race- # (the before-binary's per-frame advance) fails the median band anyway.- bad_budget = max(2, int(0.05 * len(intervals)))- if len(bad) > bad_budget:- failures.append(f"intervals outside [{MIN_INTERVAL_MS},{MAX_INTERVAL_MS}]ms: {bad}")- if intervals:- med = sorted(intervals)[len(intervals) // 2]- if not (CADENCE_MS * 0.8 <= med <= CADENCE_MS * 1.3):- failures.append(f"median interval {med}ms not ~{CADENCE_MS}ms")- else:- med = None- if not forward:- failures.append(f"non-forward phases: {steps}")- record = {"n_samples": len(samples), "n_transitions": len(transitions),- "intervals_ms": intervals, "median_ms": med,- "steps": steps, "passed": not failures, "failures": failures}- Path(out_path).write_text(json.dumps(record, indent=1))- print("PASS" if record["passed"] else "FAIL",- f"transitions={len(transitions)} median={med}ms",- "; ".join(failures))- sc.tmux("kill-session", "-t", session, check=False)- shutil.rmtree(base, ignore_errors=True)- return 0 if record["passed"] else 1--if __name__ == "__main__":- p = argparse.ArgumentParser()- p.add_argument("--out", required=True)- a = p.parse_args()- sys.exit(run(a.out))diff --git a/scripts/battery/streaming_render.py b/scripts/battery/streaming_render.pydeleted file mode 100644index 5a448bc616..0000000000--- a/scripts/battery/streaming_render.py+++ /dev/null@@ -1,419 +0,0 @@-#!/usr/bin/env python3-"""Live token-stream rendering verifier (lane: streaming-render + streaming-gaps).--Drives the interactive TUI through a paced faux provider inside tmux and-captures the pane repeatedly while the turn runs. The acceptance contract:--1. Mid-turn, the pane must GROW MONOTONICALLY: several growth samples- (>= MIN_GROWTH_SAMPLES) at least MIN_SAMPLE_GAP apart, not one jump at- turn end - i.e. token streaming renders live.-2. Mid-turn, paragraph structure must be visible DURING streaming: once the- second paragraph's first words appear, an empty row separates it from the- first paragraph (TS renders the marked `space` token as a blank row), and- the two paragraphs never share a pane row.-3. Mid-turn, a fenced code block streams as a growing region: its indented- code rows (TS renders no borders in chat markdown) are visible while the- turn still runs and grow across samples - not one dump at turn end.-4. The settled final frame must match the TS binary's settled frame- (differential, normalized for volatile chrome) - i.e. progressive- rendering changed nothing about the settled output.--Both sides run the same paced faux script (the TS side through the-visual-parity faux extension; the Rust side through PRIME_AGENT_FAUX_SCRIPT),-so the TS binary is the ground truth for the live behaviors and the settled-frame. Assertions 2 and 3 run on BOTH binaries: the TS side passing them-proves the assertions describe real TS behavior before they gate the Rust-side.--tmux rules: default socket only (`env -u TMUX`), vplane-* session names, no-kill-server; sessions are killed individually at the end.-"""--import argparse-import difflib-import json-import os-import re-import shutil-import subprocess-import sys-import tempfile-import time--import ts_identity # the shared PATH-binary identity guard (same dir)--TS_SCRIPT_MODEL = "faux-1"-SIZE = ("120", "40")-SESSION_NAME = "vplane-stream"--# The paced answer, structured for the streaming-structure assertions:-# two word-paragraphs, a fenced rust block whose lines each carry words, and-# a closing paragraph. 240 wordN tokens at 25 tokens/second (~10s).-STREAM_WORDS = 240-PARA_TWO_START = 81 # word81 opens paragraph two-CODE_WORDS_START = 161 # word161 opens the fenced block-TOKENS_PER_SECOND = 25---def _paragraph(start, end):- return " ".join(f"word{i}" for i in range(start, end + 1))---def _stream_text():- code_lines = []- next_word = CODE_WORDS_START- while next_word <= 232:- words = range(next_word, min(next_word + 4, 233))- code_lines.append(f"let v{words.start} = f({' '.join('word' + str(w) for w in words)});")- next_word += 4- return "\n\n".join(- [- _paragraph(1, 80),- _paragraph(PARA_TWO_START, 160),- "```\n" + "\n".join(code_lines) + "\n```",- _paragraph(233, STREAM_WORDS),- ]- )---FAUX_SCRIPT = {- "engine": "faux",- "modelId": "faux-1",- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": TOKENS_PER_SECOND,- "responses": [- {"content": [{"type": "text", "text": _stream_text()}]},- ],-}--PROMPT = "Write the structured answer."--# Loader/spinner frames (chat.rs LOADER_FRAMES); a settled turn shows none.-SPINNER_CHARS = "\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f\u25f4\u25f7\u25f6\u25f5\u25cb\u25f8\u25fb\u25fc"-SPINNER_CLASS = "[" + SPINNER_CHARS + "]"--SAMPLE_INTERVAL = 0.3-MIN_GROWTH_SAMPLES = 5 # distinct pane samples that gained words mid-turn-TURN_TIMEOUT = 240.0---def tmux(*args, check=True):- result = subprocess.run(- ["env", "-u", "TMUX", "tmux", *args], capture_output=True, text=True- )- if check and result.returncode != 0:- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")- return result.stdout---def capture(session, escape=False):- flag = "-e" if escape else "-p"- return tmux("capture-pane", flag, "-p", "-t", session)---def normalize(frame, root):- """Same volatile-content scrub visual_parity.py applies."""- frame = frame.replace(root, "<SANDBOX>")- frame = re.sub(r"v\d+\.\d+\.\d+", "vX.X.X", frame)- frame = re.sub(r"\b[0-9a-f]{12}\b", "<SID>", frame)- frame = re.sub(r"\b\d+(\.\d+)?(ms|s)\b", "<T>", frame)- frame = re.sub(r"\d+(\.\d+)?[kM]? \(\d+%\)", "<TOK> (<PCT>)", frame)- frame = re.sub(r"[\u2193\u2191] [\d.kM]+ tokens", "<DIR> <TOK> tokens", frame)- frame = re.sub(r"\b\d+s\b", "<S>", frame)- spinners = "".join("\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f")- frame = re.sub("[" + spinners + "]", "<SPIN>", frame)- pulses = "".join("\u25f4\u25f7\u25f6\u25f5\u25cb\u25f8\u25fb\u25fc")- frame = re.sub("[" + pulses + "]", "<PULSE>", frame)- frame = re.sub("\x1b\[39m\n", "\n", frame)- frame = re.sub("\n\x1b\[39m(?= )", "\n", frame)- # tmux places the background-reset ([49m) at row boundaries just like the- # foreground reset: same screen, two capture spellings.- frame = re.sub("\x1b\[49m\n", "\n", frame)- frame = re.sub("\n\x1b\[49m(?=\x1b|\x1b\[38| |$)", "\n", frame)- # The right-aligned footer tray pads with runs of spaces sized by the- # live token count; collapse space runs so padding width cannot differ.- frame = re.sub(" {2,}", " ", frame)- # The tmux extended-keys notice is environment chrome (it depends on the- # ambient tmux server options, not the product under test).- frame = re.sub(- "\x1b\[38;2;245;158;11m\u26a0 tmux extended-keys is off[\s\S]*?restart tmux\.\n?", "", frame- )- return frame---def diff_lines(left, right):- return "\n".join(- difflib.unified_diff(- left.split("\n"), right.split("\n"), fromfile="ts", tofile="rust", lineterm="", n=1,- )- )---def find_runtime_package_dir():- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- candidates = [- entry- for entry in sorted(os.listdir(releases))- if os.path.isdir(os.path.join(releases, entry, "prime-agent-runtime"))- ]- if not candidates:- raise SystemExit(- "cannot find the prime-agent-runtime sidecar; set PI_PACKAGE_DIR"- )- return os.path.join(releases, candidates[-1])---TS_FAUX_EXTENSION = open(- os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "ts_faux_extension.js"),- encoding="utf-8",-).read()---def rendered_words(pane):- return max((int(m) for m in re.findall(r"word(\d+)", pane)), default=0)---def wait_for(session, needle, timeout):- deadline = time.time() + timeout- while time.time() < deadline:- if needle in capture(session):- return True- time.sleep(0.3)- return False---def pane_rows(pane):- return [line.rstrip() for line in pane.split("\n")]---def row_with_word(rows, needle):- for index, row in enumerate(rows):- if needle in row:- return index- return None---def code_block_rows(rows):- """The fenced block's content rows: 3 leading spaces (1 margin + 2- codeBlockIndent) followed by the code text (TS renders no borders)."""- return [r for r in rows if re.match(r"^ {3}let v\d+", r)]---def assert_stream_structure(binary, panes, out_dir):- """Mid-stream assertions 2 and 3 over the sampled panes."""- errors = []-- # 2. paragraph structure mid-stream: the first pane where paragraph two's- # opening words are visible must separate it from paragraph one with an- # empty row, and the paragraphs never share a row.- for pane in panes:- if f"word{PARA_TWO_START}" in pane:- rows = pane_rows(pane)- index = row_with_word(rows, f"word{PARA_TWO_START}")- if index is None or index == 0:- errors.append("paragraph two appeared at the pane top without a separator row")- elif rows[index - 1].strip() != "":- errors.append(- f"paragraph two has no blank space row above it (row above: {rows[index - 1]!r})"- )- break- else:- errors.append("no mid-turn pane ever showed paragraph two")-- shared = [- pane for pane in panes- if re.search(r"word80\b", pane) and re.search(f"word{PARA_TWO_START}\b", pane)- ]- for pane in shared:- rows = pane_rows(pane)- i1 = row_with_word(rows, "word80")- i2 = row_with_word(rows, f"word{PARA_TWO_START}")- if i1 is not None and i1 == i2:- errors.append("paragraphs one and two shared one pane row mid-stream")- break-- # 3. the fenced block streams: it is visible while the turn still runs,- # and its visible content rows grow across samples.- growing = 0- last_count = -1- block_seen_mid_turn = False- for pane in panes:- rows = pane_rows(pane)- content = code_block_rows(rows)- if not content:- continue- if re.search(SPINNER_CLASS, pane):- block_seen_mid_turn = True- count = len(content)- if count > last_count:- if last_count >= 0:- growing += 1- last_count = count- if not block_seen_mid_turn:- errors.append("the fenced block never rendered mid-turn (indented code rows while the loader ran)")- if growing < 2:- errors.append(f"the fenced block content grew only {growing} times mid-turn (needs >= 2); rendering is batched")-- if errors:- evidence_path = os.path.join(out_dir, f"{binary}-structure-errors.txt")- with open(evidence_path, "w") as f:- f.write("\n".join(errors))- raise AssertionError(- f"{binary}: streaming structure assertions failed: {errors[0]}; evidence: {evidence_path}"- )---def run_session(binary, sandbox, shared_cwd, script_path, out_dir):- """Drive one binary: assert live growth and structure; return the settled frame."""- width, height = SIZE- session = f"{SESSION_NAME}-{binary}"- tmux("kill-session", "-t", session, check=False)- tmux("new-session", "-d", "-s", session, "-x", width, "-y", height, "-c", shared_cwd)- env = (- f"HOME={sandbox['home']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"PRIME_AGENT_FAUX_SCRIPT={script_path} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- if binary == "ts":- command = (- f"prime-agent --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {TS_SCRIPT_MODEL}"- )- else:- rust = os.environ.get("PA_RUST_BINARY") or os.path.join(- os.path.dirname(os.path.abspath(__file__)),- "..",- "..",- "target",- "release",- "prime-agent",- )- package_dir = os.environ.get("PI_PACKAGE_DIR") or find_runtime_package_dir()- command = (- f"PI_PACKAGE_DIR={package_dir} "- f"{rust} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {TS_SCRIPT_MODEL}"- )- tmux("send-keys", "-t", session, f"{env} {command}", "Enter")- if not wait_for(session, "Collapsed mode", timeout=60):- raise AssertionError(f"{binary}: the editor never came up")-- tmux("send-keys", "-t", session, PROMPT)- tmux("send-keys", "-t", session, "Enter")-- # Sample the pane while the turn runs: growth must be progressive and- # the structure assertions run over the sampled panes.- growth = [] # (t, words) samples where the pane gained words- panes = [] # every pane sample, for the structure assertions- last_words = 0- settled = False- deadline = time.time() + TURN_TIMEOUT- while time.time() < deadline:- pane = capture(session)- words = rendered_words(pane)- now = time.time()- panes.append(pane)- if words > last_words:- growth.append((round(now, 2), words))- last_words = words- if words >= STREAM_WORDS and not re.search(SPINNER_CLASS, pane):- settled = True- break- time.sleep(SAMPLE_INTERVAL)- evidence_path = os.path.join(out_dir, f"{binary}-samples.json")- os.makedirs(out_dir, exist_ok=True)- with open(evidence_path, "w") as f:- json.dump({"growth": growth, "panes": panes}, f, indent=1)- if not settled:- raise AssertionError(- f"{binary}: the turn never settled (last words={last_words}); evidence: {evidence_path}"- )- if len(growth) < MIN_GROWTH_SAMPLES:- raise AssertionError(- f"{binary}: pane grew only {len(growth)} times mid-turn "- f"(needs >= {MIN_GROWTH_SAMPLES}); rendering is batched, not streamed; "- f"evidence: {evidence_path}"- )- assert_stream_structure(binary, panes, out_dir)-- # The settled final frame: one more beat after the loader row is gone,- # so the trailing status chrome (usage tray, footer) finishes repainting.- time.sleep(1.0)- frame = capture(session, escape=True)- tmux("kill-session", "-t", session, check=False)-- with open(os.path.join(out_dir, f"{binary}-settled.txt"), "w") as f:- f.write(frame)- return frame, growth---def prepare_sandbox(base):- shared_cwd = os.path.join(base, "shared-cwd")- os.makedirs(shared_cwd, exist_ok=True)- script_path = os.path.join(base, "faux-script.json")- with open(script_path, "w") as f:- json.dump(FAUX_SCRIPT, f, indent=2)- sandboxes = {}- for binary in ("ts", "rust"):- home = os.path.join(base, binary, "home")- agent = os.path.join(base, binary, "agent")- os.makedirs(os.path.join(agent, "extensions"), exist_ok=True)- os.makedirs(os.path.join(agent, "sessions"), exist_ok=True)- with open(os.path.join(agent, "settings.json"), "w") as f:- json.dump({"onboardingCompleted": True}, f)- sandboxes[binary] = {"home": home, "agent": agent}- with open(- os.path.join(sandboxes["ts"]["agent"], "extensions", "stream-faux.js"), "w"- ) as f:- f.write(TS_FAUX_EXTENSION)- return shared_cwd, script_path, sandboxes---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--keep", action="store_true", help="keep the sandbox dir")- parser.add_argument(- "--out", default=None, help="captures directory (default: a fresh temp dir)"- )- parser.add_argument(- "--only", default=None, help="run a single binary (ts|rust) for a shakedown"- )- args = parser.parse_args()-- # Fail fast before any launch: a non-TS `prime-agent` on PATH plays a- # Rust build as the "ts" side and reports false divergences.- if args.only in (None, "ts"):- ts_identity.assert_ts_side_is_the_ts_product()-- base = tempfile.mkdtemp(prefix="streaming-render-sandbox-")- out_dir = args.out or tempfile.mkdtemp(prefix="streaming-render-captures-")- shared_cwd, script_path, sandboxes = prepare_sandbox(base)- try:- if args.only:- frame, growth = run_session(args.only, sandboxes[args.only], shared_cwd, script_path, out_dir)- print(f"{args.only}: {len(growth)} progressive growth samples; structure assertions passed; captures in {out_dir}")- return 0- ts_frame, ts_growth = run_session("ts", sandboxes["ts"], shared_cwd, script_path, out_dir)- print(f"ts: {len(ts_growth)} progressive growth samples; structure assertions passed")- rust_frame, rust_growth = run_session("rust", sandboxes["rust"], shared_cwd, script_path, out_dir)- print(f"rust: {len(rust_growth)} progressive growth samples; structure assertions passed")- ts_norm = normalize(ts_frame, base)- rust_norm = normalize(rust_frame, base)- if ts_norm == rust_norm:- print("PASS settled frames match")- return 0- report = os.path.join(out_dir, "diff-settled.txt")- with open(report, "w") as f:- f.write(diff_lines(ts_norm, rust_norm))- print(f"FAIL settled frames differ; diff: {report}")- return 1- finally:- if not args.keep:- shutil.rmtree(base, ignore_errors=True)---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/battery/switch_perf.py b/scripts/battery/switch_perf.pydeleted file mode 100644index 536d35e1c5..0000000000--- a/scripts/battery/switch_perf.py+++ /dev/null@@ -1,256 +0,0 @@-#!/usr/bin/env python3-"""Chat -> agents view switch latency: TS vs Rust, tmux channel both sides.--Kevin's dogfood directive (2026-09-21): "Left arrow to go from chat view to-agents view is slower than in the TS version. We want this to feel instant-and snappy." This is the verifier for the switch-snappiness lane: the same-tmux pane channel a real user types through, both products, interleaved-seeds (same session counts), one number per side — keypress-to-first--agents-view-frame — plus the flicker check (no blank or primary-screen-frame may appear between the two views; the handoff preserves the alternate-screen).--Flow per side: fresh isolated env + daemon, N seeded saved sessions plus-the live chat session, then R rounds of Left (chat -> agents view) and-Enter (agents view -> back into the chat). Each round records the switch-latency and every frame captured inside the switch window.--Not part of the product.--Usage:- python3 scripts/battery/switch_perf.py [--trials 5] [--saved 25]- [--ts-bin prime-agent] [--rust-bin target/release/prime-agent]-"""--from __future__ import annotations--import argparse-import datetime-import json-import re-import shutil-import subprocess-import sys-import time-from pathlib import Path--sys.path.insert(0, str(Path(__file__).parent))-import batterylib as B # noqa: E402-import perf as P # noqa: E402-import ts_identity # noqa: E402--# Chat-ready marker: the input prompt line, the manage bar, and the resolved-# mock model (perf.py's is_ready).-# Agents-view-ready marker: the search box placeholder both products render-# (TS `SEARCH_PROMPT_PLACEHOLDER`).-AGENTS_READY = "Search sessions"--# A primary-screen frame would show a shell prompt; the handoff must never-# leave the alternate screen, so no captured frame may match.-SHELL_PROMPT = re.compile(r"^\$ $", re.MULTILINE)--# Wire-request helper over the battery's raw socket protocol.-def wire_create(wire: B.Wire, tag: str, name: str, cwd: str, session_dir: str, runtime: dict | None = None) -> str:- # `runtimeMetadata` only rides the create when it is non-empty: the TS- # daemon treats its mere presence as an adopt-existing-session request- # (an empty object sends the worker down the import path and the- # supervisor rejects the mismatched active session id).- create_cmd = {- "type": "create",- "name": name,- "config": {- "cwd": cwd,- "sessionDir": session_dir,- "provider": "prime-inference",- "model": "mock-1",- "thinking": "high",- "executionMode": "print",- },- }- if runtime:- create_cmd["runtimeMetadata"] = runtime- create = wire.request(tag, create_cmd, timeout=120)- assert create.get("success") is True, create- return create["data"].get("activeSessionId") or create["data"].get("id")---def make_side(name: str, binary: str, run_dir: Path) -> B.Side:- root = run_dir / name- agent = root / "agent"- work = root / "work"- if agent.exists():- shutil.rmtree(agent)- agent.mkdir(parents=True)- work.mkdir(parents=True, exist_ok=True)- mock = B.MockProvider(root, [])- mock.set_responses([{"text": "seed reply"}])- mock.start()- tmpdir = Path("/tmp") / f"swperf-{name}"- if tmpdir.exists():- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- side = B.Side(- name=name,- binary=binary,- root=root,- agent_dir=agent,- work_dir=work,- daemon_socket=root / "daemon.sock",- mock=mock,- )- side.env = B.scrubbed_env(agent, tmpdir)- if name == "rust":- side.env["PI_PACKAGE_DIR"] = str(Path(__file__).resolve().parents[2])- side.env["PRIME_API_KEY"] = "sk-battery"- (agent / "settings.json").write_text(json.dumps({"onboardingShown": True}))- side.write_models_json()- side.start_daemon()- return side---def seed_saved(side: B.Side, count: int) -> None:- """Seed `count` stopped sessions so the saved catalog (Inactive rows)- has realistic scan cost on both sides."""- session_dir = side.agent_dir / "sessions"- session_dir.mkdir(parents=True, exist_ok=True)- wire = B.Wire(side.daemon_socket)- for i in range(count):- sid = wire_create(- wire, f"swc{i}", f"saved seed {i}", str(side.work_dir), str(session_dir)- )- reply = wire.request(- f"swp{i}",- {"type": "prompt_and_wait", "activeSessionId": sid, "message": "seed"},- timeout=180,- )- assert reply.get("success") is True, reply- kill = wire.request(f"swk{i}", {"type": "kill", "activeSessionId": sid}, timeout=120)- assert kill.get("success") is True, kill- wire.close()---def measure_rounds(side: B.Side, trials: int, evidence_dir: Path) -> list[dict]:- """One pane per side: launch into the chat, then trials rounds of- Left (chat -> agents view) measured keypress-to-first-agents-frame,- then Enter (back into the chat) so the next round starts settled."""- session = f"swperf-{side.name}"- argv = [- side.binary,- "--daemon-socket",- str(side.daemon_socket),- "--provider",- "prime-inference",- "--model",- "mock-1",- "--offline",- ]- # A previous crashed run can leave its pane behind (the name is- # per-side and stable); kill any stale session before relaunching.- B.tmux_kill(session)- B.tmux_launch(session, argv, side.env, side.work_dir)- ready = B.tmux_wait_text(session, r"^\s*>\s*$", timeout=60, poll=0.05)- assert P.is_ready(side.name, ready), f"chat never settled:\n{ready[-2000:]}"- records = []- for i in range(trials):- # Left: chat -> agents view. Keypress to first agents-view frame.- t0 = time.time()- B.tmux("send-keys", "-t", session, "Left")- window_frames: list[tuple[float, str]] = []- switch_ms = None- deadline = t0 + 10.0- while time.time() < deadline:- frame = B.tmux_capture(session)- window_frames.append((round((time.time() - t0) * 1000, 1), frame))- if AGENTS_READY in frame and not P.is_ready(side.name, frame):- switch_ms = round((time.time() - t0) * 1000, 1)- break- time.sleep(0.001)- blank = [t for t, f in window_frames if not f.strip()]- shell = [t for t, f in window_frames if SHELL_PROMPT.search(f)]- records.append(- {- "trial": i,- "switch_ms": switch_ms,- "frames_in_window": len(window_frames),- "blank_frame_ms": blank,- "primary_screen_frame_ms": shell,- }- )- assert switch_ms is not None, f"agents view never rendered:\n{window_frames[-1][1][-2000:]}"- assert not blank, f"blank frame inside the switch window at {blank}ms"- assert not shell, f"primary screen leaked into the switch window at {shell}ms"- # Enter: back into the chat (the anchor row is the selection). The- # empty session archives on detach (TS parity), so every reopen is- # a saved-file resume: a kernel boot, not a measured latency — the- # settle window must tolerate a loaded box (the switch metric is- # the Left above, not this wait).- B.tmux_send(session, "Enter")- settled = B.tmux_wait_text(session, r"^\s*>\s*$", timeout=180, poll=0.05)- assert P.is_ready(side.name, settled), f"chat did not reopen:\n{settled[-2000:]}"- print(f"[switch-perf] {side.name}: round {i} switch {switch_ms}ms, chat reopened")- B.tmux_kill(session)- (evidence_dir / f"{side.name}-frames.txt").write_text(- "\n".join(json.dumps(r) for r in records)- )- return records---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--ts-bin", default="prime-agent")- parser.add_argument("--rust-bin", default="target/release/prime-agent")- parser.add_argument("--trials", type=int, default=5)- parser.add_argument("--saved", type=int, default=25)- parser.add_argument(- "--runs-root", type=Path, default=Path(__file__).parent / "runs"- )- parser.add_argument("--run-name", default=None)- args = parser.parse_args()-- ts_identity.assert_ts_side_is_the_ts_product(ts_bin=args.ts_bin, rust_bin=args.rust_bin)-- stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")- run_dir = args.runs_root / f"switch-{args.run_name or stamp}"- run_dir.mkdir(parents=True, exist_ok=True)- print(f"[switch-perf] run dir: {run_dir}")-- report: dict = {- "run": str(run_dir),- "trials": args.trials,- "saved_sessions": args.saved,- "sides": {},- }- for name, binary in (("rust", args.rust_bin), ("ts", args.ts_bin)):- side = make_side(name, binary, run_dir)- print(f"[switch-perf] {name}: seeding {args.saved} saved sessions")- t_seed = time.time()- seed_saved(side, args.saved)- print(- f"[switch-perf] {name}: seeded in {time.time() - t_seed:.1f}s, measuring {args.trials} rounds"- )- records = measure_rounds(side, args.trials, run_dir)- switch = [r["switch_ms"] for r in records]- side_report = {- "binary": str(binary),- "switch_ms": switch,- "switch_summary": P.summarize(switch),- "flicker": {- "blank_frames": sum(len(r["blank_frame_ms"]) for r in records),- "primary_screen_frames": sum(len(r["primary_screen_frame_ms"]) for r in records),- },- }- report["sides"][name] = side_report- print(f"[switch-perf] {name}: {json.dumps(side_report['switch_summary'])}")- side.stop_daemon()- side.mock.stop()-- (run_dir / "report.json").write_text(json.dumps(report, indent=1))- rust = report["sides"]["rust"]["switch_summary"]- ts = report["sides"]["ts"]["switch_summary"]- print("[switch-perf] summary (median switch ms):")- print(f" rust: {rust.get('median')} ts: {ts.get('median')}")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/battery/ts_identity.py b/scripts/battery/ts_identity.pyindex a10d057176..bfb57d4bab 100644--- a/scripts/battery/ts_identity.py+++ b/scripts/battery/ts_identity.py@@ -19,9 +19,9 @@ Rust build misidentified as TS:import ts_identity # noqa: E402ts_identity.assert_ts_side_is_the_ts_product()-Harnesses with non-default binaries pass them explicitly (run_battery.py-drives target/release/prime-agent rather than the debug build, and its-flows accept --ts-bin/--rust-bin):+Harnesses with non-default binaries pass them explicitly (perf_wave.py+drives target/release/prime-agent rather than the debug build, and accepts+--ts-bin/--rust-bin):ts_identity.assert_ts_side_is_the_ts_product(ts_bin, rust_bin)diff --git a/scripts/battery/update_prepare_wire.py b/scripts/battery/update_prepare_wire.pydeleted file mode 100644index 651576181b..0000000000--- a/scripts/battery/update_prepare_wire.py+++ /dev/null@@ -1,458 +0,0 @@-#!/usr/bin/env python3-"""Wire parity battery for the update-prepare transaction:-the TS binary and the Rust-binary side by side on the `prepare_update_restart`/`commit_update_restart`-daemon-command surface (slices 2-3).--What is compared (same command ids, same sockets, real daemons both sides):-- P1 baseline reads: `list_saved_sessions` on an empty agent dir — the- response envelope must be byte-identical (canonical form).- P2 the admission gate: a mutating `create` while a prepare is active —- both products must answer with the TS message- "Daemon is preparing an update restart" and the same failure shape.- P3 reads stay served during the prepare window: `list_saved_sessions`- again, identical to P1 on both sides.- P4 user-visible invariant "a wedged update never wedges the daemon": the- TS supervisor stays fenced after a stray `prepare_update_restart`- (mutations refused indefinitely — the bug the spec kills); the Rust- supervisor's deadline watchdog aborts it and serves mutations again.--Documented divergences (spec redesign, not regressions — each row is-asserted, reported, and explained):- D1 `prepare_update_restart` without an `updateId`: TS accepts and runs the- whole blocking restart flow; Rust requires the idempotency key.- D2 `prepare_update_restart` with an `updateId`: TS ignores it and runs the- blocking flow (success + manifest, sessions stop); Rust returns the- prepare transaction's state (`prepared` + the marker `expiresAt`) and- keeps serving.- D3 a second `prepare_update_restart` with a different id while active:- TS has no such window to stage (its gate refuses inside the blocking- RPC); Rust answers with the TS string "Daemon is already preparing an- update restart" plus the typed `update_prepare_refused` info.- D4 `shutdown` during the window: TS exempts shutdown at `prepared`; Rust- refuses it as a mutation (the coordinator owns the restart).--Phase 2 (slice 3, live session): the graceful-stop divergence with a real-resident session, same binaries, fresh daemons:-- E1 prepare vs the session's life: TS's blocking prepare returns the- manifest AND stops the session (its worker is killed inside the RPC);- Rust's prepare returns `prepared` with the session still serving- (`get_state` answers) - invariant I3, graceful stops only at commit.- E2 Rust `commit_update_restart`: success `{state: "stopping", stopped: N}`,- the worker exits within budget, and the supervisor process exits for- the update (the socket goes away).--Usage:- python3 scripts/battery/update_prepare_wire.py \- --rust-bin /abs/path/prime-agent [--ts-bin prime-agent] [--out DIR]--Exit code is non-zero when any parity row (P*/E*) mismatches.-"""--import argparse-import json-import shutil-import subprocess-import sys-import time-from pathlib import Path--sys.path.insert(0, str(Path(__file__).parent))-import batterylib as B-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--FLOW = "update_prepare"-GATE_MESSAGE = "Daemon is preparing an update restart"-ALREADY_MESSAGE = "Daemon is already preparing an update restart"---def make_side(name: str, binary: str, root: Path, env_extra: dict) -> B.Side:- agent = root / "agent"- work = root / "work"- work.mkdir(parents=True, exist_ok=True)- agent.mkdir(parents=True)- mock = B.MockProvider(root, [])- mock.set_responses([{"text": "prepare-battery"}])- mock.start()- tmpdir = Path("/tmp") / f"upw-{name}"- if tmpdir.exists():- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- side = B.Side(- name=name,- binary=binary,- root=root,- agent_dir=agent,- work_dir=work,- daemon_socket=root / "daemon.sock",- mock=mock,- )- side.env = B.scrubbed_env(agent, tmpdir, env_extra)- side.env["PRIME_API_KEY"] = "sk-battery"- side.write_models_json()- return side---def canon(line: dict) -> str:- """Order-insensitive wire form: sorted keys, compact (JSON-equality)."""- return json.dumps(line, sort_keys=True, separators=(",", ":"))---def run_empty_flow(side: B.Side) -> tuple[list[dict], dict[str, dict]]:- """Drive one side; returns (raw response lines in order, by-command map)."""- side.start_daemon()- wire = B.Wire(side.daemon_socket)- raw = []- by_id = {}-- def step(command_id: str, command: dict, timeout: float = 60.0) -> dict:- response = wire.request(command_id, command, timeout=timeout)- raw.append(response)- by_id[command_id] = response- return response-- # P1 baseline read.- step("s1", {"type": "list"})- if side.name == "ts":- # D1: TS accepts a bare prepare and runs the whole flow.- step("s2", {"type": "prepare_update_restart"})- # P2 gate: mutations refused while TS sits in its prepared phase.- step("s3", {"type": "create", "cwd": str(side.work_dir)})- # P3 reads stay served.- step("s4", {"type": "list"})- # P4 TS wedge: still refused long after any reasonable budget.- time.sleep(5.0)- step("s5", {"type": "create", "cwd": str(side.work_dir)})- # D4: TS exempts shutdown at `prepared` — the daemon exits.- step("s6", {"type": "shutdown"})- else:- # D1: Rust requires the idempotency key.- step("s2", {"type": "prepare_update_restart"})- # D2: prepare with an id reports the transaction state.- step("s2b", {"type": "prepare_update_restart", "updateId": "upd-1"})- # P2 gate: mutations refused while Fenced.- step("s3", {"type": "create", "cwd": str(side.work_dir)})- # P3 reads stay served.- step("s4", {"type": "list"})- # D3: a different id is a typed refusal.- step("s2c", {"type": "prepare_update_restart", "updateId": "upd-2"})- # D4: shutdown during the window is refused as a mutation (the- # coordinator owns the restart), unlike TS's prepared exemption.- step("s6b", {"type": "shutdown"})- # P4 recovery: the deadline watchdog (3 s env override) aborts the- # prepare and the supervisor serves mutations again.- time.sleep(5.0)- step("s5", {"type": "create", "cwd": str(side.work_dir)})- # After recovery, shutdown is a plain mutation and succeeds.- step("s6", {"type": "shutdown"})- return raw, by_id---def session_id_of(create_response: dict) -> str | None:- data = create_response.get("data") or {}- for candidate in (data, data.get("session") or {}):- if isinstance(candidate, dict) and candidate.get("activeSessionId"):- return candidate["activeSessionId"]- return None---def run_session_flow(side: B.Side) -> tuple[list[dict], dict[str, dict], str | None]:- """Slice 3: one live session, then prepare (both) and commit (Rust)."""- side.start_daemon()- wire = B.Wire(side.daemon_socket)- raw = []- by_id = {}-- def step(command_id: str, command: dict, timeout: float = 60.0) -> dict:- response = wire.request(command_id, command, timeout=timeout)- raw.append(response)- by_id[command_id] = response- return response-- create = step("c1", {"type": "create", "cwd": str(side.work_dir)})- session_id = session_id_of(create)- if not session_id:- raise RuntimeError(f"{side.name} create returned no activeSessionId: {create}")- # The worker registers asynchronously; poll the roster until resident.- deadline = time.time() + 30.0- while time.time() < deadline:- listing = step("ls1", {"type": "list"})- sessions = ((listing.get("data") or {}).get("sessions")) or []- if sessions:- break- time.sleep(0.5)- if side.name == "ts":- # TS prepare: the blocking flow returns the manifest AND stops the- # session inside the RPC (spec §2's failure mode this redesign- # kills - sessions die at prepare, not at commit).- step("pre", {"type": "prepare_update_restart"})- # E1: the session worker is gone.- step("st1", {"type": "get_state", "activeSessionId": session_id})- return raw, by_id, session_id- # Rust prepare: a transaction to Prepared; the session keeps serving.- step("pre", {"type": "prepare_update_restart", "updateId": "upd-live"})- # E1: the session is still alive behind the gate.- step("st1", {"type": "get_state", "activeSessionId": session_id})- # E2: commit stops the worker and exits the supervisor.- step("cm1", {"type": "commit_update_restart", "updateId": "upd-live"})- return raw, by_id, session_id---def daemon_socket_alive(socket_path: Path) -> bool:- import socket as socket_module-- try:- with socket_module.socket(socket_module.AF_UNIX, socket_module.SOCK_STREAM) as probe:- probe.settimeout(2.0)- probe.connect(str(socket_path))- return True- except OSError:- return False---def main() -> int:- default_rust = Path(__file__).resolve().parents[2] / "target/release/prime-agent"- parser = argparse.ArgumentParser()- parser.add_argument("--ts-bin", default="prime-agent")- parser.add_argument("--rust-bin", default=str(default_rust))- parser.add_argument("--out", default=None)- args = parser.parse_args()- rust_bin = Path(args.rust_bin).resolve()- if not rust_bin.exists():- print(f"rust binary missing: {rust_bin}", file=sys.stderr)- return 2- # Fail fast before any launch: a non-TS ts binary plays a Rust build as- # the "ts" side and reports false parity rows.- ts_identity.assert_ts_side_is_the_ts_product(args.ts_bin, str(rust_bin))-- stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())- out = Path(args.out) if args.out else Path(__file__).parent / "runs" / f"{stamp}-{FLOW}"- out.mkdir(parents=True, exist_ok=True)-- # The Rust windows must be observable: a 3 s prepare budget and a 3 s- # marker self-expiry keep the gate active long enough to stage- # P2/P3/D3/D4, then the recovery row needs the watchdog to fire before- # the 5 s wait ends.- rust_env = {- "PRIME_AGENT_UPDATE_PREPARE_MS": "3000",- "PRIME_AGENT_UPDATE_PREPARED_EXPIRY_MS": "3000",- }- sides = {- "ts": make_side("ts", args.ts_bin, out / "ts", {}),- "rust": make_side("rust", str(rust_bin), out / "rust", rust_env),- }- results = {}- for name, side in sides.items():- raw, by_id = run_empty_flow(side)- results[name] = by_id- side.evidence(- FLOW,- "wire.jsonl",- "\n".join(json.dumps(line) for line in raw) + "\n",- )- side.stop_daemon()- side.mock.stop()-- ts, rs = results["ts"], results["rust"]- verdicts = []-- def parity(row: str, description: str, ts_line: dict, rs_line: dict) -> None:- ok = canon(ts_line) == canon(rs_line)- verdicts.append({"row": row, "description": description, "parity": ok})- if not ok:- side_diff = f"ts={canon(ts_line)}\nrust={canon(rs_line)}"- print(f"[MISMATCH] {row}: {description}\n{side_diff}")-- def divergence(row: str, description: str, observed: str) -> None:- verdicts.append({"row": row, "description": description, "divergence": observed})-- # P1: baseline read byte parity (canonical).- parity("P1", "list_saved_sessions baseline is byte-identical", ts["s1"], rs["s1"])- # P2: the gate refusal.- ts_gate_error = ts["s3"].get("error")- rs_gate_error = rs["s3"].get("error")- gate_ok = (- ts["s3"].get("success") is False- and rs["s3"].get("success") is False- and ts_gate_error == GATE_MESSAGE- and rs_gate_error == GATE_MESSAGE- )- verdicts.append({"row": "P2", "description": "gate refusal message parity", "parity": gate_ok})- if not gate_ok:- print(f"[MISMATCH] P2: ts={ts_gate_error!r} rust={rs_gate_error!r}")- # P3: reads stay served during the window, identical to baseline.- parity("P3", "reads stay served during the prepare window", ts["s4"], rs["s4"])- def masked(line: dict) -> str:- body = {k: v for k, v in line.items() if k != "id"}- return canon(body)-- served = (- ts["s4"].get("success") is True- and rs["s4"].get("success") is True- and masked(ts["s4"]) == masked(ts["s1"])- and masked(rs["s4"]) == masked(rs["s1"])- )- verdicts.append({"row": "P3b", "description": "served rows equal the baseline rows", "parity": served})- # P4: TS wedges, Rust recovers.- ts_wedged = ts["s5"].get("error") == GATE_MESSAGE- rs_recovered = rs["s5"].get("error") != GATE_MESSAGE- verdicts.append(- {- "row": "P4",- "description": "stray prepare: TS stays wedged (bug), Rust self-recovers",- "parity": ts_wedged and rs_recovered,- "ts_wedged": ts_wedged,- "rust_recovered": rs_recovered,- }- )- if not (ts_wedged and rs_recovered):- print(f"[MISMATCH] P4: ts_wedged={ts_wedged} rust_recovered={rs_recovered}")-- # Divergence rows (asserted, explained).- divergence(- "D1",- "prepare without updateId: TS runs the flow, Rust requires the key",- f"ts success={ts['s2'].get('success')} data-keys={sorted((ts['s2'].get('data') or {}).keys())}; "- f"rust success={rs['s2'].get('success')} error={rs['s2'].get('error')!r}",- )- divergence(- "D2",- "prepare with updateId: TS blocking full restart, Rust transaction state",- f"ts data={json.dumps(ts['s2'].get('data'), sort_keys=True)}; "- f"rust data={json.dumps(rs['s2b'].get('data'), sort_keys=True)}",- )- already_ok = (- rs["s2c"].get("success") is False- and rs["s2c"].get("error") == ALREADY_MESSAGE- and (rs["s2c"].get("errorInfo") or {}).get("code") == "update_prepare_refused"- )- verdicts.append(- {- "row": "D3",- "description": "different-id prepare: TS string + typed refusal info",- "parity": already_ok,- }- )- if not already_ok:- print(f"[MISMATCH] D3: rust={canon(rs['s2c'])}")- # D4 live: shutdown during the window — TS exempts it at `prepared`- # (its s6 succeeded while the gate was up), Rust refuses it as a- # mutation and serves it normally once the transaction aborted.- d4_ok = (- ts["s6"].get("success") is True- and rs["s6b"].get("success") is False- and rs["s6b"].get("error") == GATE_MESSAGE- and rs["s6"].get("success") is True- )- verdicts.append(- {- "row": "D4",- "description": "shutdown during the window: TS exempts at prepared, Rust refuses until recovery",- "parity": d4_ok,- }- )- if not d4_ok:- print(- f"[MISMATCH] D4: ts s6={canon(ts['s6'])} rust s6b={canon(rs['s6b'])} rust s6={canon(rs['s6'])}"- )-- # Phase 2 (slice 3): the live-session prepare/commit divergence with- # fresh daemons on fresh agent dirs.- live = {}- for name, side in sides.items():- live_side = make_side(f"{name}-live", side.binary, out / f"{name}-live", rust_env if name == "rust" else {})- raw_live, by_id_live, session_id = run_session_flow(live_side)- supervisor_exited = False- if name == "rust":- # E2: commit stops the worker and the supervisor exits for the- # update - poll the socket, not a shell ps.- exit_deadline = time.time() + 10.0- while time.time() < exit_deadline:- if not daemon_socket_alive(live_side.daemon_socket):- supervisor_exited = True- break- time.sleep(0.25)- live_side.evidence(- FLOW,- "wire-live.jsonl",- "\n".join(json.dumps(line) for line in raw_live) + "\n",- )- live_side.stop_daemon()- live_side.mock.stop()- live[name] = by_id_live- live[name]["__session_id__"] = session_id- if name == "rust":- live[name]["__supervisor_exited__"] = supervisor_exited-- tls, rls = live["ts"], live["rust"]- # E1: prepare vs the session's life. TS stops the session inside the- # blocking prepare (get_state fails); Rust leaves it serving.- e1_ok = (- tls["pre"].get("success") is True- and rls["pre"].get("success") is True- and (rls["pre"].get("data") or {}).get("state") == "prepared"- and tls["st1"].get("success") is False- and rls["st1"].get("success") is True- )- verdicts.append(- {- "row": "E1",- "description": "prepare: TS kills the session in the RPC, Rust keeps it serving (I3)",- "parity": e1_ok,- "ts_get_state": tls["st1"].get("error"),- "rust_get_state": rls["st1"].get("success"),- }- )- if not e1_ok:- print(f"[MISMATCH] E1: ts st1={canon(tls['st1'])} rust st1={canon(rls['st1'])}")- # E2: Rust commit stops the worker in budget and exits the supervisor.- commit_data = rls["cm1"].get("data") or {}- e2_ok = (- rls["cm1"].get("success") is True- and commit_data.get("state") == "stopping"- and int(commit_data.get("stopped") or 0) >= 1- and live["rust"].get("__supervisor_exited__") is True- )- verdicts.append(- {- "row": "E2",- "description": "commit: worker stopped in budget, supervisor exits for the update",- "parity": e2_ok,- }- )- if not e2_ok:- print(f"[MISMATCH] E2: commit={canon(rls['cm1'])} exited={live['rust'].get('__supervisor_exited__')}")- divergence(- "E3",- "commit_update_restart exists only on Rust (spec §5): TS has no separate commit surface",- f"ts prepare data-keys={sorted((tls['pre'].get('data') or {}).keys())}; "- f"rust commit data={json.dumps(commit_data, sort_keys=True)}",- )-- report = {- "flow": FLOW,- "ts_bin": args.ts_bin,- "rust_bin": str(rust_bin),- "verdicts": verdicts,- "raw": {name: {cmd: line for cmd, line in results[name].items()} for name in results},- "raw_live": {- name: {cmd: line for cmd, line in live[name].items()} for name in live- },- }- (out / f"{FLOW}-report.json").write_text(json.dumps(report, indent=1))- print(f"evidence: {out / f'{FLOW}-report.json'}")- for verdict in verdicts:- status = "PARITY" if verdict.get("parity") else verdict.get("divergence", "MISMATCH")- print(f" [{status}] {verdict['row']}: {verdict['description']}")- failed = [v["row"] for v in verdicts if "parity" in v and not v["parity"]]- if failed:- print(f"FAILED rows: {', '.join(failed)}")- return 1- print("all parity rows match; divergences documented")- return 0---if __name__ == "__main__":- raise SystemExit(main())diff --git a/scripts/battery/update_reattach_wire.py b/scripts/battery/update_reattach_wire.pydeleted file mode 100644index 7a07baf1a0..0000000000--- a/scripts/battery/update_reattach_wire.py+++ /dev/null@@ -1,538 +0,0 @@-#!/usr/bin/env python3-"""update_reattach_wire.py — the update flow's slice-6 battery: client-reattach (spec §10) end to end and the coordinator-kill construction-proofs (I2/I3), against the Rust release binary on fixture install roots.--Rows:- T1 the flagship: a TUI attached in tmux rides a full staged update — the- update banner renders, the daemon swaps binaries, the client- auto-reattaches to the same durable session (reattach is the DEFAULT- end state; spec §10). Evidence: captured tmux frames.- G4 attach-by-durable-id after the update: a fresh client attaches by the- durable id (§10.4/§10.5): same session, transcript replayed.- K1 kill -9 the coordinator mid-Preparing: the daemon's prepare transaction- self-expires back to Serving (spec §5/I3), the session survives, and a- re-run update completes end to end (the dead-holder intent steal).- K2 kill -9 the coordinator at Prepared: same recovery from the prepared- state (the marker self-expiry watchdog), then the re-run completes.--The battery never touches the real TS install: every `update` runs from-battery-owned fixture install roots.-"""--import argparse-import json-import os-import re-import shutil-import signal-import subprocess-import sys-import tempfile-import time-from pathlib import Path--import batterylib as B-import update_staged_wire as U--FLOW = "update_reattach"--TERMINAL_COMPLETE = "complete"---def tmux(*args, check=True):- """Run a tmux command on the default socket (never inside TMUX)."""- result = subprocess.run(- ["env", "-u", "TMUX", "tmux", *args],- capture_output=True,- text=True,- )- if check and result.returncode != 0:- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")- return result.stdout---def capture_pane(session):- return tmux("capture-pane", "-p", "-t", session)---def pane_alive(session):- result = subprocess.run(- ["env", "-u", "TMUX", "tmux", "list-panes", "-t", session, "-F", "#{pane_dead}"],- capture_output=True,- text=True,- )- return result.stdout.strip() != "1"---def wait_for_pane(session, needle, timeout=60.0):- deadline = time.time() + timeout- while time.time() < deadline:- pane = capture_pane(session)- if needle in pane:- return pane- time.sleep(0.3)- raise TimeoutError(f"pane never showed {needle!r}")---def status_file_of(side):- socket_dir = side.agent_dir / "update-restarts"- files = sorted(socket_dir.glob("*/status.json")) if socket_dir.exists() else []- return files[-1] if files else None---def read_status(side):- path = status_file_of(side)- if not path or not path.exists():- return None- try:- return json.loads(path.read_text())- except (OSError, json.JSONDecodeError):- return None---def wait_for_state(side, state, timeout=90.0):- deadline = time.time() + timeout- while time.time() < deadline:- status = read_status(side)- if status and status.get("state") == state:- return status- time.sleep(0.05)- return None---def intent_pid(side):- socket_dir = side.agent_dir / "update-restarts"- for path in sorted(socket_dir.glob("*/intent.json")) if socket_dir.exists() else []:- try:- return json.loads(path.read_text()).get("pid")- except (OSError, json.JSONDecodeError):- continue- return None---def coordinator_alive(pid):- try:- os.kill(pid, 0)- return True- except OSError:- return False---def main() -> int:- default_rust = Path(__file__).resolve().parents[2] / "target/release/prime-agent"- parser = argparse.ArgumentParser()- parser.add_argument("--rust-bin", default=str(default_rust))- parser.add_argument("--out", default=None)- args = parser.parse_args()- rust_bin = Path(args.rust_bin).resolve()- if not rust_bin.exists():- print(f"rust binary missing: {rust_bin}", file=sys.stderr)- return 2- version = subprocess.run(- [str(rust_bin), "--version"], capture_output=True, text=True- ).stdout.strip()-- stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())- out = Path(args.out) if args.out else Path(__file__).parent / "runs" / f"{stamp}-{FLOW}"- out.mkdir(parents=True, exist_ok=True)- verdicts = []- evidence = {"flow": FLOW, "version": version, "rows": {}}-- try:- server = U.ReleaseServer(out / "server")- (out / "server").mkdir(parents=True, exist_ok=True)-- # ------------------------------------------------------------------- # T1 + G4: the flagship — a TUI in tmux rides the whole update and- # auto-reattaches; then a fresh client attaches by durable id.- # ------------------------------------------------------------------- t1_root = out / "rust-t1"- if t1_root.exists():- shutil.rmtree(t1_root)- fixture = U.build_fixture_root(t1_root, rust_bin, version)- install = fixture["install"]- fixture_bin = install / "bin" / "prime-agent"- # The staged release's install-source points at the battery server.- (fixture["release_a"] / ".install-source").write_text(server.base_url + "\n")- archive_sha, archive_name = U.build_candidate(out / "server", rust_bin, version)- (out / "server" / "latest.json").write_text(- json.dumps(- {- "version": version,- "binaries": [- {- "platform": U.PLATFORM,- "file": archive_name,- "sha256": archive_sha,- }- ],- }- )- )- side = U.make_rust_side(- f"rust-t1-{stamp}",- str(fixture_bin),- t1_root,- {- "PRIME_AGENT_DOWNLOAD_BASE_URL": server.base_url,- "PRIME_AGENT_UPDATE_RESTORE_OVERALL_MS": "15000",- # Short expiry: a killed coordinator recovers fast (K rows).- "PRIME_AGENT_UPDATE_PREPARED_EXPIRY_MS": "3000",- },- )- side.daemon_socket = U.default_socket(side)- # Skip the first-run onboarding pane (the settings flag TS respects:- # `onboardingShown`): the row tests the reconnect contract, not the- # trace question.- (side.agent_dir / "settings.json").write_text(- json.dumps({"onboardingShown": True})- )- side.start_daemon()-- # A session the TUI will attach to (attach a pre-made session so the- # TUI opens straight into it: --resume <selector>-style attach).- wire = B.Wire(side.daemon_socket)- created = wire.request("t1-create", {"type": "create", "cwd": str(side.work_dir)})- session_id = None- deadline = time.time() + 30.0- while time.time() < deadline:- listing = wire.request("t1-ls", {"type": "list"})- rows = ((listing.get("data") or {}).get("sessions")) or []- if rows:- session_id = rows[0].get("sessionId")- break- time.sleep(0.5)- wire.sock.close()-- # The TUI in tmux, attached by durable id.- tui_session = f"usw-tui-{stamp}"- tmux("kill-session", "-t", tui_session, check=False)- tmux("new-session", "-d", "-s", tui_session, "-x", "120", "-y", "36", "-c", str(side.work_dir))- # A curated env (quoted; env values with spaces must not split the- # command line - the tmux pane is a shell).- tui_env = {- key: value- for key, value in side.env.items()- if key- in {- "PATH",- "HOME",- "LANG",- "TMPDIR",- "NO_COLOR",- "PRIME_AGENT_CODING_AGENT_DIR",- "PRIME_AGENT_DOWNLOAD_BASE_URL",- "PRIME_AGENT_UPDATE_RESTORE_OVERALL_MS",- "PRIME_AGENT_UPDATE_PREPARED_EXPIRY_MS",- "PRIME_API_KEY",- "PRIME_AGENT_BASH_SHELL",- "TERM",- }- }- env_pairs = " ".join(f"{key}='{value}'" for key, value in tui_env.items())- command = f"env {env_pairs} {fixture_bin} --daemon-socket {side.daemon_socket} --model mock-1"- tmux("send-keys", "-t", tui_session, command, "Enter")- # The Rust TUI's ready needle (the visual-parity harness waits for the- # same row).- try:- pane = wait_for_pane(tui_session, "Collapsed mode", timeout=40)- except TimeoutError:- pane = capture_pane(tui_session)- evidence["rows"]["T1"] = {- "tui_pane": pane[-2000:],- "error": "the TUI never reached its ready state",- }- verdicts.append({"row": "T1", "description": "TUI rides the update and auto-reattaches", "parity": False})- side.stop_daemon()- side.mock.stop()- tmux("kill-session", "-t", tui_session, check=False)- raise- evidence["rows"]["T1"] = {"pre_update_frame": pane[-4000:]}-- # The update from a second shell (same fixture env).- update = subprocess.Popen(- [str(fixture_bin), "update", "--force"],- env=side.env,- cwd=str(side.work_dir),- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- )- # A frame from inside the update window: the §11 banner is visible- # while the daemon restarts (the pre-reattach banner is transient -- # the reattach rebuild replaces the transcript with the session's- # truth, so only the mid-window capture shows it).- mid_pane = None- mid_deadline = time.time() + 60.0- while time.time() < mid_deadline:- status = read_status(side)- if status and status.get("state") in ("preparing", "prepared", "stopping", "activating", "booting", "restoring"):- mid_pane = capture_pane(tui_session)- if "Prime Agent is updating" in mid_pane:- break- mid_pane = None- time.sleep(0.1)- update_stdout, update_stderr = update.communicate(timeout=240)- time.sleep(2.0)-- final_pane = capture_pane(tui_session)- evidence["rows"]["T1"]["update_stdout"] = update_stdout- evidence["rows"]["T1"]["update_stderr"] = update_stderr- evidence["rows"]["T1"]["mid_update_frame"] = (mid_pane or "")[-4000:]- evidence["rows"]["T1"]["post_update_frame"] = final_pane[-4000:]- evidence["rows"]["T1"]["pane_alive"] = pane_alive(tui_session)- evidence["rows"]["T1"]["status"] = read_status(side) or {}-- after_wire = B.Wire(side.daemon_socket)- after_listing = after_wire.request("t1-after", {"type": "list"})- after_rows = ((after_listing.get("data") or {}).get("sessions")) or []- after_sessions = sorted(- row.get("sessionId") for row in after_rows if row.get("sessionId")- )- after_wire.sock.close()- evidence["rows"]["T1"]["after_sessions"] = after_sessions- t1_ok = (- update.returncode == 0- and mid_pane is not None- and "Prime Agent is updating" in mid_pane- and "Reconnected" in final_pane- and evidence["rows"]["T1"]["pane_alive"]- # The pre-made session is in the restored set (the TUI re-created- # its own session on the successor; the "Reconnected" banner is- # the TUI-side end state).- and session_id in after_sessions- and (evidence["rows"]["T1"]["status"] or {}).get("state") == "complete"- )- verdicts.append({"row": "T1", "description": "TUI rides the update: banner, auto-reattach, same durable session", "parity": bool(t1_ok)})-- # G4: a fresh client attaches by durable id (the §10.4/§10.5 end- # state: same session, transcript replayed).- g4_wire = B.Wire(side.daemon_socket)- attach = g4_wire.request(- "g4-attach", {"type": "attach", "activeSessionId": session_id}- )- attach_data = attach.get("data") or {}- attached_session = (attach_data.get("snapshot") or {}).get("sessionId")- if not attached_session:- # Fallback: the active id from the attach data resolves to the- # durable row in the list.- active = attach_data.get("activeSessionId")- listing = g4_wire.request("g4-list", {"type": "list"})- rows = ((listing.get("data") or {}).get("sessions")) or []- attached_session = next(- (- row.get("sessionId")- for row in rows- if row.get("activeSessionId") == active- ),- None,- )- attach_ok = bool(attach.get("success")) and attached_session == session_id- evidence["rows"]["G4"] = {- "attach_success": bool(attach.get("success")),- "attached_session": attached_session,- "session": session_id,- }- verdicts.append({"row": "G4", "description": "attach-by-durable-id after the update: same session, replayed", "parity": bool(attach_ok)})- g4_wire.sock.close()- tmux("kill-session", "-t", tui_session, check=False)- side.stop_daemon()- side.mock.stop()- # The successor daemon outlives the side handle: stop it over the- # wire, then reap this fixture's detached workers (cwd-scoped).- try:- stop_wire = B.Wire(side.daemon_socket)- stop_wire.request("t1-stop", {"type": "shutdown"})- stop_wire.sock.close()- except OSError:- pass- U.kill_detached_workers_under(t1_root)-- # ------------------------------------------------------------------- # K rows: kill -9 the coordinator mid-transaction (spec §13.6's- # construction proofs). The coordinator is SIGSTOPPED first so the- # kill lands deterministically inside the target window: K1 freezes- # it while the prepare RPC is in flight (the daemon finishes the- # transaction alone); K2 freezes it the same way, then waits for- # the prepared marker (the daemon reached `Prepared` with a frozen- # coordinator) before the kill. Both rows recover through the- # marker self-expiry watchdog back to `Serving`, the session- # survives, and a re-run update completes (the dead-holder intent- # steal).- # ------------------------------------------------------------------- for row, wait_for_marker in [("K1", False), ("K2", True)]:- k_root = out / f"rust-{row.lower()}"- if k_root.exists():- shutil.rmtree(k_root)- kfixture = U.build_fixture_root(k_root, rust_bin, version)- kinstall = kfixture["install"]- kbin = kinstall / "bin" / "prime-agent"- (kfixture["release_a"] / ".install-source").write_text(server.base_url + "\n")- kside = U.make_rust_side(- f"rust-{row.lower()}-{stamp}",- str(kbin),- k_root,- {- "PRIME_AGENT_DOWNLOAD_BASE_URL": server.base_url,- "PRIME_AGENT_UPDATE_RESTORE_OVERALL_MS": "15000",- "PRIME_AGENT_UPDATE_PREPARED_EXPIRY_MS": "3000",- },- )- kside.daemon_socket = U.default_socket(kside)- kside.start_daemon()- kwire = B.Wire(kside.daemon_socket)- kwire.request("k-create", {"type": "create", "cwd": str(kside.work_dir)})- ksession = None- deadline = time.time() + 30.0- while time.time() < deadline and ksession is None:- listing = kwire.request("k-ls", {"type": "list"})- rows = ((listing.get("data") or {}).get("sessions")) or []- ksession = next((row_.get("sessionId") for row_ in rows), None)- time.sleep(0.5)- kwire.sock.close()-- update_proc = subprocess.Popen(- [str(kbin), "update", "--force"],- env=kside.env,- cwd=str(kside.work_dir),- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- )- # 2 ms poll: the coordinator's `Preparing` window is ~10 ms on- # this fixture, so the freeze must land inside the RPC.- pid = None- deadline = time.time() + 60.0- marker = None- while time.time() < deadline:- pid = pid or intent_pid(kside)- status = read_status(kside)- if pid and status and status.get("state") == "preparing":- try:- os.kill(pid, signal.SIGSTOP)- except OSError:- pass- if wait_for_marker:- # The daemon completes the transaction alone; wait- # for the prepared marker (Prepared with a frozen- # coordinator), then kill.- marker_deadline = time.time() + 30.0- while time.time() < marker_deadline:- sockets = kside.agent_dir / "update-restarts"- markers = list(sockets.glob("*/prepared/*/marker.json")) if sockets.exists() else []- if markers:- marker = str(markers[0])- break- time.sleep(0.05)- try:- os.kill(pid, signal.SIGKILL)- except OSError:- pass- break- time.sleep(0.002)- update_proc.wait(timeout=30)-- row_data = {- "coordinator_pid": pid,- "prepared_marker_at_kill": marker,- "status_at_kill": (read_status(kside) or {}).get("state"),- }- # The invoker CLI tails the dead coordinator for its full- # liveness budget otherwise; it holds nothing after the hand-over,- # so kill it (the re-run steals the dead holder's intent).- try:- update_proc.kill()- except OSError:- pass-- # The transaction self-expires back to Serving (the watchdog- # aborts on the expiry; bounded by the short marker TTL).- deadline = time.time() + 20.0- served = False- while time.time() < deadline:- try:- probe = B.Wire(kside.daemon_socket)- listing = probe.request("k-probe", {"type": "list"})- served = bool(listing.get("success"))- if served:- # The gate must be gone: a mutating command passes.- mutate = probe.request(- "k-mutate",- {"type": "create", "cwd": str(kside.work_dir)},- )- served = bool(mutate.get("success"))- probe.sock.close()- except (OSError, EOFError, TimeoutError):- pass- if served:- break- time.sleep(0.5)- row_data["daemon_serving_after_kill"] = served-- # The session survived the killed update.- ksession_after = None- try:- kwire2 = B.Wire(kside.daemon_socket)- listing = kwire2.request("k-ls2", {"type": "list"})- rows = ((listing.get("data") or {}).get("sessions")) or []- ksession_after = next(- (row_.get("sessionId") for row_ in rows if row_.get("sessionId") == ksession),- None,- )- kwire2.sock.close()- except (OSError, EOFError, TimeoutError):- pass- row_data["session_survived"] = ksession_after == ksession-- # The re-run: the dead-holder intent steal, then a full update.- rerun = U.run_cli(kbin, ["update", "--force"], kside.env, kside.work_dir)- rerun_status = read_status(kside) or {}- row_data["rerun_exit"] = rerun["exit_code"]- row_data["rerun_status"] = {k_: rerun_status.get(k_) for k_ in ("state", "counts", "message")}- kill_label = "at Prepared (marker present)" if wait_for_marker else "mid-Preparing (RPC in flight)"- k_ok = (- bool(pid)- and (not wait_for_marker or row_data["prepared_marker_at_kill"])- and row_data["daemon_serving_after_kill"]- and row_data["session_survived"]- and rerun["exit_code"] == 0- and rerun_status.get("state") == "complete"- )- verdicts.append({"row": row, "description": f"kill -9 the coordinator {kill_label}: self-expiry to Serving, session survives, re-run completes", "parity": bool(k_ok)})- evidence["rows"][row] = row_data-- # Stop the successor daemon from the re-run + this side's daemon.- try:- stop = B.Wire(kside.daemon_socket)- stop.request("k-stop", {"type": "shutdown"})- stop.sock.close()- except OSError:- pass- kside.stop_daemon()- kside.mock.stop()- U.kill_detached_workers_under(k_root)- time.sleep(1.0)-- server.stop()-- finally:- (out / "update_reattach-report.json").write_text(- json.dumps({"verdicts": verdicts, **evidence}, indent=1)- )-- print(f"evidence: {out / 'update_reattach-report.json'}")- ok = True- for verdict in verdicts:- marker = "PARITY" if verdict["parity"] else "MISMATCH"- ok = ok and verdict["parity"]- print(f" [{marker}] {verdict['row']}: {verdict['description']}")- failed = [v["row"] for v in verdicts if not v["parity"]]- if failed:- print(f"FAILED rows: {', '.join(failed)}")- return 1- print("all parity rows match")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/battery/update_staged_wire.py b/scripts/battery/update_staged_wire.pydeleted file mode 100644index 01087ab70a..0000000000--- a/scripts/battery/update_staged_wire.py+++ /dev/null@@ -1,759 +0,0 @@-#!/usr/bin/env python3-"""Wire parity battery for the staged-activation update flow:-the coordinator FSM, the-bin-symlink staged activation, the rollback, and the TS status-file schema.--Rust phases run against a managed fixture install root (the battery's own-release binary copied into `.managed` + `releases/<ver>-<platform>-<sha>/`-+ `bin/prime-agent`) with the candidate served by a local HTTP server:-- F1 the full staged update (`update --force`, live session): status.json- walks Acquire..Complete (terminal `complete`), counts report the- adopted session (total=1, restored=1), the launcher swap lands- (`bin/prime-agent` -> candidate, `bin/previous` -> old), the prepared- dir is swept, the activation state and the intent lock are gone, and- the successor daemon serves the session's durable id.- F2 the rollback (`update --rollback`, live session): the same FSM with- the previous release as candidate - the launcher returns to the old- target, the status is terminal `complete` with the rolled-back- message, and the session survives.- F3 the unmanaged-install refusal: the repo binary (no `.managed` root)- refuses with the TS message byte-for-byte.--TS comparison (both sides, real binaries):-- P1 refusal parity: TS `update --force` on an unmanaged install prints the- same "This compiled application is not owned by the Prime Agent- installer." refusal.- P2 rollback-without-previous parity: both refuse with "No valid previous- compiled release is available."- P3 TS coordinator status schema: TS's `--internal-update-restart-*`- coordinator mode on a live TS daemon writes its status file; the- shared schema fields (version, socketPath, coordinator identity,- counts, failures) parse with the Rust UpdateStatus type, and the- terminal message "Restarted the daemon after the update" is- byte-identical to the Rust F1 terminal message.- D1 (documented divergence) TS phase names (`starting`, `preparing`,- `stopping`, `starting_daemon`, `restoring`, `complete`) vs the Rust- state vocabulary (`staged`..`complete`): the spec redesign replaces- the TS phase machine; the status file schema and terminal report- strings stay TS-compatible.--Usage:- python3 scripts/battery/update_staged_wire.py \- --rust-bin /abs/path/prime-agent [--ts-bin prime-agent] [--out DIR]--Exit code is non-zero when any parity row (P*/F*) mismatches.-"""--import argparse-import http.server-import json-import os-import shutil-import socket-import subprocess-import sys-import tarfile-import tempfile-import threading-import time-from pathlib import Path--sys.path.insert(0, str(Path(__file__).parent))-import batterylib as B-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--FLOW = "update_staged"-PLATFORM = "linux-x64" if sys.platform == "linux" else "darwin-x64"-PAYLOAD_ASSETS = ["prime-agent-runtime", "skills", "docs", "LICENSE", "README.md"]-UNMANAGED_REFUSAL = "This compiled application is not owned by the Prime Agent installer."-NO_PREVIOUS_REFUSAL = "No valid previous compiled release is available."-TERMINAL_MESSAGE = "Restarted the daemon after the update"---class ReleaseServer:- """A local HTTP server serving the manifest + candidate archive."""-- def __init__(self, directory: Path):- self.directory = directory- handler = lambda *args, **kwargs: http.server.SimpleHTTPRequestHandler(- *args, directory=str(directory), **kwargs- )- self.httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)- self.port = self.httpd.server_address[1]- self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True)- self.thread.start()-- @property- def base_url(self) -> str:- return f"http://127.0.0.1:{self.port}"-- def stop(self) -> None:- self.httpd.shutdown()---def sha256_of(path: Path) -> str:- import hashlib-- digest = hashlib.sha256()- with open(path, "rb") as handle:- for chunk in iter(lambda: handle.read(1 << 16), b""):- digest.update(chunk)- return digest.hexdigest()---def build_release_dir(- releases_root: Path,- version: str,- archive_sha: str,- binary: Path,-) -> Path:- """One fixture release: the binary, the payload, and the installer- metadata (assemble_artifacts.py payload + `.archive-sha256`/`.install-source`)."""- name = f"{version}-{PLATFORM}-{archive_sha}"- release = releases_root / name- release.mkdir(parents=True)- shutil.copy2(binary, release / "prime-agent")- os.chmod(release / "prime-agent", 0o755)- runtime = release / "prime-agent-runtime"- runtime.mkdir()- (runtime / "pyproject.toml").write_text("# battery fixture\n")- for asset in ["skills", "docs"]:- (release / asset).mkdir()- (release / "LICENSE").write_text("battery\n")- (release / "README.md").write_text("battery\n")- (release / ".archive-sha256").write_text(archive_sha)- return release---def build_fixture_root(root: Path, binary: Path, version: str) -> dict:- """A managed install root whose active release is `version` (sha A)."""- install = root / "install"- (install / "releases").mkdir(parents=True)- (install / ".managed").write_text("prime-agent-native-v1")- sha_a = "a" * 64- release_a = build_release_dir(install / "releases", version, sha_a, binary)- (release_a / ".install-source").write_text("http://127.0.0.1:1") # replaced per phase- (install / "bin").mkdir()- os.symlink(f"../releases/{release_a.name}/prime-agent", install / "bin" / "prime-agent")- return {"install": install, "sha_a": sha_a, "release_a": release_a}---def build_candidate(server_dir: Path, binary: Path, version: str) -> tuple[str, str]:- """Stage + tar the candidate payload (files at the archive root);- returns the archive's real digest and name.- The digest the manifest carries is the one the staged release directory- is named after (TS install.sh naming)."""- staging = tempfile.mkdtemp(prefix="candidate-")- staging_path = Path(staging)- payload = staging_path / "payload"- payload.mkdir(parents=True, exist_ok=True)- shutil.copy2(binary, payload / "prime-agent")- os.chmod(payload / "prime-agent", 0o755)- (payload / "prime-agent-runtime").mkdir()- (payload / "prime-agent-runtime" / "pyproject.toml").write_text("# battery fixture\n")- for asset in ["skills", "docs"]:- (payload / asset).mkdir()- (payload / "LICENSE").write_text("battery\n")- (payload / "README.md").write_text("battery\n")- archive_name = f"prime-agent-{version}-{PLATFORM}.tar.gz"- archive = server_dir / archive_name- with tarfile.open(archive, "w:gz") as tar:- for entry in sorted(payload.iterdir()):- tar.add(entry, arcname=entry.name)- shutil.rmtree(staging)- return sha256_of(archive), archive_name---def launcher_target(install: Path, link: str) -> str:- return os.readlink(install / "bin" / link)---def run_cli(binary: Path, args: list[str], env: dict, cwd: Path, timeout: float = 180.0) -> dict:- return B.run_cmd([str(binary), *args], env, cwd, timeout=timeout)---def make_rust_side(name: str, binary: str, root: Path, env_extra: dict) -> B.Side:- agent = root / "agent"- work = root / "work"- work.mkdir(parents=True, exist_ok=True)- agent.mkdir(parents=True, exist_ok=True)- mock = B.MockProvider(root, [])- mock.set_responses([{"text": "staged-battery"}])- mock.start()- tmpdir = Path("/tmp") / f"usw-{name}"- if tmpdir.exists():- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- side = B.Side(- name=name,- binary=binary,- root=root,- agent_dir=agent,- work_dir=work,- daemon_socket=root / "daemon.sock",- mock=mock,- )- side.env = B.scrubbed_env(agent, tmpdir, env_extra)- side.env["PRIME_API_KEY"] = "sk-battery"- side.write_models_json()- return side---def default_socket(side: B.Side) -> Path:- """The product-default daemon socket under this side's isolated TMPDIR- (`prime-agent <update>` targets it: TS `resolveDaemonUpdateRestartSocketPath`- with no explicit socket)."""- return Path(side.env["TMPDIR"]) / f"prime-agent-{os.getuid()}" / "daemon.sock"----def ts_fixture_root(root: Path, ts_binary: Path) -> Path:- """A managed fixture install root for the TS binary: the TS asset list- (`native-installation.ts` NATIVE_RELEASE_ASSETS: package.json,- install.sh with the recovery marker, runtime/theme/export stubs,- `.archive-sha256`, `.install-source`), no `bin/previous`."""- version = subprocess.run(- [str(ts_binary), "--version"], capture_output=True, text=True- ).stdout.strip()- sha = "f" * 64- install = root / "ts-install"- release = install / "releases" / f"{version}-{PLATFORM}-{sha}"- release.mkdir(parents=True)- shutil.copy2(ts_binary, release / "prime-agent")- os.chmod(release / "prime-agent", 0o755)- (release / "package.json").write_text(json.dumps({"version": version}))- (release / "install.sh").write_text("# prime-agent-native-recovery-v1\ntrue\n")- os.chmod(release / "install.sh", 0o755)- runtime = release / "prime-agent-runtime" / "src" / "rlm"- runtime.mkdir(parents=True)- (release / "prime-agent-runtime" / "pyproject.toml").write_text("# battery\n")- (runtime / "repl.py").write_text("# battery\n")- theme = release / "theme"- theme.mkdir()- (theme / "prime.json").write_text("{}\n")- export_html = release / "export-html"- export_html.mkdir()- (export_html / "template.html").write_text("<p>battery</p>\n")- (release / "photon_rs_bg.wasm").write_bytes(b"battery")- (release / ".archive-sha256").write_text(sha)- (release / ".install-source").write_text("http://127.0.0.1:1\n")- (install / ".managed").write_text("prime-agent-native-v1")- (install / "bin").mkdir()- os.symlink(f"../releases/{release.name}/prime-agent", install / "bin" / "prime-agent")- return install--def kill_detached_workers_under(root: Path) -> int:- """SIGTERM every process whose cwd is under `root` (the battery's own- detached session workers; scoped so ambient daemons are never touched)."""- killed = 0- import signal as _signal-- root_s = str(root)- for entry in Path("/proc").iterdir():- if not entry.name.isdigit():- continue- try:- cwd = os.readlink(entry / "cwd")- except OSError:- continue- if cwd.startswith(root_s):- try:- os.kill(int(entry.name), _signal.SIGTERM)- killed += 1- except OSError:- pass- return killed---def resident_session_id(wire: B.Wire) -> str | None:- listing = wire.request("ls", {"type": "list"})- sessions = ((listing.get("data") or {}).get("sessions")) or []- for row in sessions:- if row.get("sessionId"):- return row["sessionId"]- return None---def main() -> int:- default_rust = Path(__file__).resolve().parents[2] / "target/release/prime-agent"- parser = argparse.ArgumentParser()- parser.add_argument("--ts-bin", default="prime-agent")- parser.add_argument("--rust-bin", default=str(default_rust))- parser.add_argument("--out", default=None)- args = parser.parse_args()- rust_bin = Path(args.rust_bin).resolve()- if not rust_bin.exists():- print(f"rust binary missing: {rust_bin}", file=sys.stderr)- return 2- ts_bin = shutil.which(args.ts_bin)- if not ts_bin:- print(f"ts binary not found: {args.ts_bin}", file=sys.stderr)- return 2- # Fail fast before any launch: a non-TS ts binary plays a Rust build as- # the "ts" side and reports false parity rows.- ts_identity.assert_ts_side_is_the_ts_product(ts_bin, str(rust_bin))-- stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())- out = Path(args.out) if args.out else Path(__file__).parent / "runs" / f"{stamp}-{FLOW}"- out.mkdir(parents=True, exist_ok=True)-- version = subprocess.run(- [str(rust_bin), "--version"], capture_output=True, text=True- ).stdout.strip()- server = ReleaseServer(out / "server")- (out / "server").mkdir(parents=True, exist_ok=True)- verdicts = []- evidence = {"flow": FLOW, "version": version, "rows": {}}-- try:- # ------------------------------------------------------------------- # F1: the full staged update against the fixture install root.- # ------------------------------------------------------------------- f1_root = out / "rust-f1"- if f1_root.exists():- shutil.rmtree(f1_root)- fixture = build_fixture_root(f1_root, rust_bin, version)- install = fixture["install"]- fixture_bin = install / "bin" / "prime-agent"- side = make_rust_side(- f"rust-f1-{stamp}",- str(fixture_bin),- f1_root,- {- "PRIME_AGENT_DOWNLOAD_BASE_URL": server.base_url,- "PRIME_AGENT_UPDATE_RESTORE_OVERALL_MS": "15000",- },- )- side.daemon_socket = default_socket(side)- # The staged release's install-source points at the battery server.- (fixture["release_a"] / ".install-source").write_text(server.base_url + "\n")- archive_sha, archive_name = build_candidate(out / "server", rust_bin, version)- (out / "server" / "latest.json").write_text(- json.dumps(- {- "version": version,- "binaries": [- {- "platform": PLATFORM,- "file": archive_name,- "sha256": archive_sha,- }- ],- }- )- )- side.start_daemon()- wire = B.Wire(side.daemon_socket)- create = wire.request("c1", {"type": "create", "cwd": str(side.work_dir)})- deadline = time.time() + 30.0- while time.time() < deadline and resident_session_id(wire) is None:- time.sleep(0.5)- session_id = resident_session_id(wire)- socket_dir = side.agent_dir / "update-restarts"- for hashed in socket_dir.glob("*") if socket_dir.exists() else []:- pass- # The update CLI runs from the fixture binary with the daemon live.- update_result = run_cli(- fixture_bin, ["update", "--force"], side.env, side.work_dir- )- status_path = socket_dir / next(socket_dir.glob("*")).name / "status.json" if socket_dir.exists() and any(socket_dir.glob("*")) else None- time.sleep(1.0)- candidate_target = f"../releases/{version}-{PLATFORM}-{archive_sha}/prime-agent"- new_wire = None- try:- new_wire = B.Wire(side.daemon_socket)- restored_id = resident_session_id(new_wire)- except Exception:- restored_id = None- successor_hello_resume = (new_wire.hello or {}).get("updateResume") if new_wire else None- rows = {- "exit_code": update_result["exit_code"],- "stdout": update_result["stdout"],- "stderr": update_result["stderr"],- "current_target": launcher_target(install, "prime-agent"),- "previous_target": launcher_target(install, "previous"),- "activation_state": (install / ".activation-state").exists(),- "restored_session": restored_id,- "original_session": session_id,- }- # F1 assertions.- f1_ok = (- update_result["exit_code"] == 0- and rows["current_target"] == candidate_target- and rows["previous_target"].startswith(f"../releases/{version}-{PLATFORM}-{fixture['sha_a']}")- and not rows["activation_state"]- and rows["restored_session"] == session_id- )- # Status file: terminal complete with the adopted counts.- status_files = sorted(socket_dir.glob("*/status.json")) if socket_dir.exists() else []- status = json.loads(status_files[-1].read_text()) if status_files else {}- rows["status"] = status- f1_status_ok = (- status.get("state") == "complete"- and status.get("counts", {}).get("total") == 1- and status.get("counts", {}).get("restored") == 1- and status.get("message") == TERMINAL_MESSAGE- )- verdicts.append({"row": "F1", "description": "staged update: complete, launcher swapped, session restored", "parity": bool(f1_ok and f1_status_ok)})- evidence["rows"]["F1"] = rows- side.stop_daemon()- side.mock.stop()-- # ------------------------------------------------------------------- # F2: the rollback (the fixture now runs the candidate; roll back).- # ------------------------------------------------------------------- f2_root = out / "rust-f2"- if f2_root.exists():- shutil.rmtree(f2_root)- fixture2 = build_fixture_root(f2_root, rust_bin, version)- install2 = fixture2["install"]- # Simulate the F1 end state: current -> candidate (b), previous -> a.- sha_b = "b" * 64- release_b = build_release_dir(install2 / "releases", version, sha_b, rust_bin)- (release_b / ".install-source").write_text(server.base_url + "\n")- (fixture2["release_a"] / ".install-source").write_text(server.base_url + "\n")- os.remove(install2 / "bin" / "prime-agent")- os.symlink(f"../releases/{release_b.name}/prime-agent", install2 / "bin" / "prime-agent")- os.symlink(- f"../releases/{fixture2['release_a'].name}/prime-agent", install2 / "bin" / "previous"- )- fixture2_bin = install2 / "bin" / "prime-agent"- side2 = make_rust_side(- f"rust-f2-{stamp}",- str(fixture2_bin),- f2_root,- {"PRIME_AGENT_UPDATE_RESTORE_OVERALL_MS": "15000"},- )- side2.daemon_socket = default_socket(side2)- side2.start_daemon()- wire2 = B.Wire(side2.daemon_socket)- create2 = wire2.request("c1", {"type": "create", "cwd": str(side2.work_dir)})- deadline = time.time() + 30.0- while time.time() < deadline and resident_session_id(wire2) is None:- time.sleep(0.5)- session2 = resident_session_id(wire2)- rollback_result = run_cli(- fixture2_bin, ["update", "--rollback"], side2.env, side2.work_dir- )- time.sleep(1.0)- try:- after_rollback = B.Wire(side2.daemon_socket)- restored2 = resident_session_id(after_rollback)- except Exception:- restored2 = None- old_target = f"../releases/{version}-{PLATFORM}-{fixture2['sha_a']}/prime-agent"- f2_rows = {- "exit_code": rollback_result["exit_code"],- "stdout": rollback_result["stdout"],- "stderr": rollback_result["stderr"],- "current_target": launcher_target(install2, "prime-agent"),- "restored_session": restored2,- "original_session": session2,- }- socket2 = side2.agent_dir / "update-restarts"- status2_files = sorted(socket2.glob("*/status.json")) if socket2.exists() else []- status2 = json.loads(status2_files[-1].read_text()) if status2_files else {}- f2_rows["status"] = status2- f2_ok = (- rollback_result["exit_code"] == 0- and f2_rows["current_target"] == old_target- and restored2 == session2- and status2.get("state") == "complete"- )- verdicts.append({"row": "F2", "description": "rollback: launcher restored, session survives, status complete", "parity": bool(f2_ok)})- evidence["rows"]["F2"] = f2_rows- side2.stop_daemon()- side2.mock.stop()-- # ------------------------------------------------------------------- # G1: the boot sweep (spec §6 step 1, invariant I2): stop the update's- # successor daemon over the wire (the Side's process handle is the- # pre-update supervisor, already gone), plant stale scratch (this- # socket's update-restarts subtree + the TS-era legacy names), boot- # fresh, and assert the sweep removed it and the daemon serves.- # ------------------------------------------------------------------- socket_dir = side.agent_dir / "update-restarts"- status_files = sorted(socket_dir.glob("*/status.json")) if socket_dir.exists() else []- f1_update_id = None- stale_prepared = None- legacy_dir = side.agent_dir / "daemon-update-restarts"- legacy_status = side.agent_dir / "daemon-update-restart.json"- sweep_gone = served = False- normal_boot_resume = None- if status_files:- f1_update_id = json.loads(status_files[-1].read_text()).get("updateId")- hash_dir = status_files[-1].parent- stale_prepared = hash_dir / "prepared" / "stale.json"- stale_prepared.parent.mkdir(parents=True, exist_ok=True)- stale_prepared.write_text('{"stale": true}')- legacy_dir.mkdir(parents=True, exist_ok=True)- (legacy_dir / "legacy.json").write_text('{"legacy": true}')- legacy_status.write_text('{"legacy": true}')- # Stop the successor daemon (a graceful wire shutdown).- stop_wire = B.Wire(side.daemon_socket)- stop_wire.request("g1-stop", {"type": "shutdown"})- deadline = time.time() + 15.0- while time.time() < deadline and side.daemon_socket.exists():- try:- with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe:- probe.connect(str(side.daemon_socket))- except OSError:- break- time.sleep(0.2)- # Fresh boot: a new supervisor process, no roster env (normal boot).- side.start_daemon()- sweep_wire = B.Wire(side.daemon_socket)- served = bool(sweep_wire.request("g1-list", {"type": "list", "all": True}).get("success"))- sweep_gone = (- not stale_prepared.exists()- and not stale_prepared.parent.exists()- and not legacy_dir.exists()- and not legacy_status.exists()- )- # The §10.3 contract live: the hello first shows the boot's- # restore/re-arm pass in flight, then settles with no update id.- deadline = time.time() + 20.0- while time.time() < deadline:- normal_boot_resume = (sweep_wire.hello or {}).get("updateResume")- if normal_boot_resume and normal_boot_resume.get("complete"):- break- probe_wire = B.Wire(side.daemon_socket)- normal_boot_resume = (probe_wire.hello or {}).get("updateResume")- probe_wire.sock.close()- if normal_boot_resume and normal_boot_resume.get("complete"):- break- time.sleep(0.5)- side.stop_daemon()- verdicts.append({"row": "G1", "description": "boot sweep: stale update scratch + legacy names gone, daemon serves (I2)", "parity": bool(sweep_gone and served)})- evidence["rows"]["G1"] = {- "stale_prepared_gone": stale_prepared is not None and not stale_prepared.exists(),- "legacy_gone": not legacy_dir.exists() and not legacy_status.exists(),- "list_served": served,- "normal_boot_update_resume": normal_boot_resume,- }-- # ------------------------------------------------------------------- # G2: the hello resume contract (spec §10.3): the update-boot hello- # carries the update id with complete=true; a settled normal boot- # (G1's capture) carries no id with complete=true.- # ------------------------------------------------------------------- g2_ok = (- successor_hello_resume is not None- and successor_hello_resume.get("updateId") == f1_update_id- and successor_hello_resume.get("complete") is True- and normal_boot_resume == {"complete": True}- )- verdicts.append({"row": "G2", "description": "hello.update_resume: update boot carries the id complete, normal boot carries no id", "parity": bool(g2_ok)})- evidence["rows"]["G2"] = {- "update_boot_update_resume": successor_hello_resume,- "update_id": f1_update_id,- "normal_boot_update_resume": normal_boot_resume,- }-- # ------------------------------------------------------------------- # G3: the scheduled-work re-arm (spec §6 step 3): a due active job- # of a session with no live worker wakes the session once on the- # boot pass, and scheduled-jobs.json is never archived.- # ------------------------------------------------------------------- g3_root = out / "rust-g3"- if g3_root.exists():- shutil.rmtree(g3_root)- fixture3 = build_fixture_root(g3_root, rust_bin, version)- install3 = fixture3["install"]- fixture3_bin = install3 / "bin" / "prime-agent"- side3 = make_rust_side(- f"rust-g3-{stamp}",- str(fixture3_bin),- g3_root,- {},- )- side3.daemon_socket = default_socket(side3)- side3.start_daemon()- wire3 = B.Wire(side3.daemon_socket)- wire3.request("g3-create", {"type": "create", "cwd": str(side3.work_dir)})- deadline = time.time() + 30.0- while time.time() < deadline and resident_session_id(wire3) is None:- time.sleep(0.5)- session3 = resident_session_id(wire3)- sessions_dir = side3.agent_dir / "sessions"- session3_file = sessions_dir / f"{session3}.jsonl"- artifacts = side3.agent_dir / "session-artifacts" / session3- artifacts.mkdir(parents=True, exist_ok=True)- due_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 60))- job = {- "id": "job-g3",- "status": "active",- "activeSessionId": session3,- "sessionId": session3,- "sessionFile": str(session3_file),- "cwd": str(side3.work_dir),- "prompt": "heartbeat probe",- "schedule": {"kind": "interval", "expression": "every 5m", "intervalMs": 300000},- "createdAt": due_at,- "updatedAt": due_at,- "nextRunAt": due_at,- }- (artifacts / "scheduled-jobs.json").write_text(json.dumps({"jobs": [job], "dispatches": []}))- side3.stop_daemon()- # The daemon's stop leaves its detached worker alive (batterylib's- # documented behavior); the re-arm row needs the session workerless,- # so kill this side's own worker by its cwd (scoped to the fixture).- killed_workers = kill_detached_workers_under(g3_root)- time.sleep(1.0)- # Normal boot (no roster env): the re-arm pass wakes the session.- side3.start_daemon()- wire3b = B.Wire(side3.daemon_socket)- woke = None- deadline = time.time() + 20.0- while time.time() < deadline:- listing = wire3b.request("g3-list", {"type": "list", "all": True})- rows3 = listing.get("data", {}).get("sessions", []) if listing.get("success") else []- woke = next((row.get("sessionId") for row in rows3 if row.get("sessionId") == session3), None)- if woke:- break- time.sleep(0.5)- g3_ok = (- woke == session3- and (artifacts / "scheduled-jobs.json").exists()- )- verdicts.append({"row": "G3", "description": "scheduled-work re-arm: due job wakes its session once, scheduled-jobs.json never archived", "parity": bool(g3_ok)})- evidence["rows"]["G3"] = {- "woke_session": woke,- "session": session3,- "killed_workers_before_boot": killed_workers,- "job_file_exists": (artifacts / "scheduled-jobs.json").exists(),- }- side3.stop_daemon()- side3.mock.stop()-- # ------------------------------------------------------------------- # F3 + P1: the unmanaged-install refusal, both binaries.- # ------------------------------------------------------------------- rust_refusal = run_cli(rust_bin, ["update", "--force"], B.scrubbed_env(Path("/tmp"), Path("/tmp")), Path("/tmp"))- # The TS binary on the box IS a managed install and bun resolves its- # own exe path through symlinks, so the TS unmanaged refusal cannot- # run live: the row compares the LIVE Rust refusal text against the- # TS source string (the refusal is TS-owned contract text). The- # battery never runs TS `update` against the real install again.- ts_source = Path(- os.environ.get("TS_SOURCE", str(Path.home() / "prime-agent"))- ) / "packages/coding-agent/src/cli/native-update.ts"- ts_source_text = ts_source.read_text() if ts_source.exists() else ""- p1_ok = (- UNMANAGED_REFUSAL in rust_refusal["stderr"] + rust_refusal["stdout"]- and UNMANAGED_REFUSAL in ts_source_text- )- verdicts.append({"row": "P1", "description": "unmanaged-install refusal: live Rust text == TS source string (TS cannot run unmanaged on this box)", "parity": bool(p1_ok)})- evidence["rows"]["P1"] = {- "rust": {"stdout": rust_refusal["stdout"], "stderr": rust_refusal["stderr"], "exit": rust_refusal["exit_code"]},- "ts_source_contains_refusal": UNMANAGED_REFUSAL in ts_source_text,- "ts_source": str(ts_source),- }-- # ------------------------------------------------------------------- # P2: rollback without a previous release, both binaries.- # ------------------------------------------------------------------- f3_root = out / "rust-f3"- if f3_root.exists():- shutil.rmtree(f3_root)- fixture3 = build_fixture_root(f3_root, rust_bin, version)- fixture3_bin = fixture3["install"] / "bin" / "prime-agent"- rust_no_previous = run_cli(- fixture3_bin,- ["update", "--rollback"],- B.scrubbed_env(f3_root / "agent", Path("/tmp")),- Path("/tmp"),- )- ts_fixture = ts_fixture_root(out, Path(ts_bin))- ts_no_previous = run_cli(- str(ts_fixture / "bin" / "prime-agent"),- ["update", "--rollback"],- B.scrubbed_env(Path("/tmp"), Path("/tmp")),- Path("/tmp"),- )- p2_ok = (- NO_PREVIOUS_REFUSAL in rust_no_previous["stderr"] + rust_no_previous["stdout"]- and NO_PREVIOUS_REFUSAL in ts_no_previous["stderr"] + ts_no_previous["stdout"]- )- verdicts.append({"row": "P2", "description": "rollback-without-previous refusal parity (TS message)", "parity": bool(p2_ok)})- evidence["rows"]["P2"] = {- "rust": {"stdout": rust_no_previous["stdout"], "stderr": rust_no_previous["stderr"]},- "ts": {"stdout": ts_no_previous["stdout"], "stderr": ts_no_previous["stderr"]},- }-- # ------------------------------------------------------------------- # P3 + D1: the TS coordinator's status file vs the Rust schema.- # ------------------------------------------------------------------- ts_root = out / "ts-coordinator"- ts_side = make_rust_side(f"ts-coord-{stamp}", ts_bin, ts_root, {})- ts_side.start_daemon()- ts_wire = B.Wire(ts_side.daemon_socket)- ts_wire.request("c1", {"type": "create", "cwd": str(ts_side.work_dir)})- deadline = time.time() + 30.0- while time.time() < deadline and resident_session_id(ts_wire) is None:- time.sleep(0.5)- ts_restarts = ts_side.agent_dir / "update-restarts"- ts_restarts.mkdir(parents=True, exist_ok=True)- ts_wire.close()- ts_status_path = ts_restarts / "battery-ts-coordinator.json"- ts_coord = run_cli(- ts_bin,- [- "update",- "--internal-update-restart-coordinator",- "--daemon-socket",- str(ts_side.daemon_socket),- "--internal-update-restart-status",- str(ts_status_path),- ],- ts_side.env,- ts_side.work_dir,- timeout=240.0,- )- ts_status = (- json.loads(ts_status_path.read_text()) if ts_status_path.exists() else {}- )- evidence["rows"]["P3"] = {- "ts_stdout": ts_coord["stdout"],- "ts_stderr": ts_coord["stderr"],- "ts_status": ts_status,- }- ts_side.stop_daemon()- ts_side.mock.stop()- # The shared schema fields parse, and the terminal message matches.- p3_ok = (- ts_status.get("version") == 1- and isinstance(ts_status.get("socketPath"), str)- and (ts_status.get("coordinator") or {}).get("pid", 0) > 0- and isinstance((ts_status.get("counts") or {}).get("total"), int)- and ts_status.get("phase") == "complete"- and TERMINAL_MESSAGE in json.dumps(ts_status.get("message", ""))- )- verdicts.append({"row": "P3", "description": "TS coordinator status schema + terminal message parity", "parity": bool(p3_ok)})- verdicts.append(- {- "row": "D1",- "description": "TS phase names vs the Rust state vocabulary (spec redesign; schema and report strings stay TS-compatible)",- "divergence": f"ts phases={sorted({ts_status.get('phase')})}; rust states={sorted({status.get('state'), status2.get('state')})}",- }- )- finally:- server.stop()-- (out / f"{FLOW}-report.json").write_text(json.dumps({"flow": FLOW, "version": version, "verdicts": verdicts, **evidence}, indent=1, default=str))- print(f"evidence: {out / f'{FLOW}-report.json'}")- for verdict in verdicts:- state = "PARITY" if verdict.get("parity") else verdict.get("divergence", "MISMATCH")- print(f" [{state}] {verdict['row']}: {verdict['description']}")- failed = [v["row"] for v in verdicts if "parity" in v and not v["parity"]]- if failed:- print(f"FAILED rows: {', '.join(failed)}")- return 1- print("all parity rows match; divergences documented")- return 0---if __name__ == "__main__":- raise SystemExit(main())diff --git a/scripts/bracketed_paste_parity.py b/scripts/bracketed_paste_parity.pydeleted file mode 100755index 6b997da875..0000000000--- a/scripts/bracketed_paste_parity.py+++ /dev/null@@ -1,505 +0,0 @@-#!/usr/bin/env python3-"""Bracketed-paste / enhanced-keys parity verifier: byte-capture the raw-terminal stream of the Rust interactive TUI and the installed TS binary-under a raw pty and prove the enhanced-key contract (audit Tier 1,-`term-enhanced-keys`):-- - startup enables bracketed paste (`ESC[?2004h`) and queries the kitty- keyboard protocol (`ESC[?u`; the Rust side rides crossterm's support- probe, which appends the DA1 query `ESC[c` — accepted delta);- - with no kitty answer in the fallback window, TS arms the xterm- modifyOtherKeys fallback (`ESC[>4;2m`); the Rust side intentionally- does NOT (crossterm cannot parse the resulting `CSI 27;<mods>;<key>~`- sequences — the whole pending buffer drops on the parse error, the- shift-modified-printable bug class) and instead RESETS the mode at- startup (`ESC[>4;0m`, clearing a sticky mode another pane armed);- - a 3-line paste lands as ONE editor update — all three lines render in- the editor and no submission happens (the scripted turn's sentinel text- must not appear before the Enter) — both with bracketed markers and as- a marker-less keystroke burst (the tmux 3.2a `paste-buffer` shape, TS- StdinBuffer's `isRawMultilinePaste` heuristic);- - a 20-line paste COLLAPSES to the `[paste #<id> +N lines]` indicator- (one editor line; the raw lines never render before the send) and the- submitted message carries the full content (editor.ts:1342 parity);- - the shifted-printable range (`shift+1/! shift+/ -> ? shift+' -> "- shift+= -> + shift+; -> :`) lands in the editor BOTH as legacy text- bytes and as kitty CSI-u alternate-key sequences — the shift+= dogfood- bug class (a dropped `+` character);- - Enter submits the whole block (the turn starts exactly once);- - a clean double-Ctrl+C exit disables paste mode (`ESC[?2004l`) and- resets modifyOtherKeys (`ESC[>4;0m`).--tmux would swallow or re-shape the ?2004/kitty bytes (before 3.3 it strips-OSC/CSI probes entirely), so like osc_parity.py this verifier drives both-binaries through the scripted faux session under a raw pty and records-every output byte before any terminal parser sits in between.--Exit code is non-zero when any stage check fails on either binary.-"""--import argparse-import json-import os-import pty-import select-import struct-import subprocess-import sys-import fcntl-import termios-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import visual_parity as vp--WIDTH, HEIGHT = 120, 36--# The turn's scripted answer: a unique marker so the verifier can prove the-# submission fired exactly at the Enter, never per pasted line.-# A unique marker so the verifier can prove the submission fired exactly-# at the Enter, never per pasted line. Checked word-by-word: the diff-# renderers may style each word as its own span (Rust) or repaint the-# response (TS), so contiguous-substring counting overcounts or misses.-SENTINEL = "BRACKETED PASTE PARITY SENTINEL"-SENTINEL_WORDS = ["BRACKETED", "PASTE", "PARITY", "SENTINEL"]-# Both TUIs render the working spinner with this label; a submission that-# started a turn shows it (word-level for the same span-diff reason).-WORKING_LABEL = b"Waiting"-PASTE_LINES = ["alpha line", "beta line", "gamma line"]-# The large-paste block: 20 unique words, one per line — enough to trip the-# >10-lines collapse in both editors (editor.ts:1342).-LARGE_PASTE_LINES = [f"bulk {i:02d} line" for i in range(20)]-LARGE_PASTE_MARKER = b"[paste #1 +20 lines]"-# The shifted-printable range (US layout): shift+1 -> !, shift+/ -> ?,-# shift+' -> ", shift+= -> +, shift+; -> :. Legacy terminals send the-# produced byte; kitty protocol terminals send the CSI-u alternate form-# `CSI <base>:<shifted>;2u` (report alternate keys, modifier shift).-SHIFTED_RANGE = b'+!?"::'[:5] # + ! ? " :-KITTY_CSI_U_ALTERNATES = [- b"\x1b[49:33;2u", # shift+1 -> !- b"\x1b[47:63;2u", # shift+/ -> ?- b"\x1b[39:34;2u", # shift+' -> "- b"\x1b[61:43;2u", # shift+= -> +- b"\x1b[59:58;2u", # shift+; -> :-]--FAUX_SCRIPT = {- "engine": "faux",- "modelId": vp.TS_SCRIPT_MODEL,- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 18,- "responses": [{"content": [{"type": "text", "text": f"{SENTINEL} ack."}]}],-}--BRACKETED_PASTE_ON = b"\x1b[?2004h"-BRACKETED_PASTE_OFF = b"\x1b[?2004l"-KITTY_QUERY = b"\x1b[?u"-MODIFY_OTHER_KEYS_ON = b"\x1b[>4;2m"-MODIFY_OTHER_KEYS_OFF = b"\x1b[>4;0m"---class PtyCapture:- """One binary under a raw pty; output captured stage by stage."""-- def __init__(self, command, env_extra, cwd):- master, slave = pty.openpty()- fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", HEIGHT, WIDTH, 0, 0))- env = dict(os.environ)- env["TERM"] = "xterm-256color"- env.update(env_extra)- self.proc = subprocess.Popen(command, stdin=slave, stdout=slave, stderr=slave, env=env, cwd=cwd)- os.close(slave)- self.master = master- self.stages = []-- def pump(self, seconds):- """Read output for `seconds`, recording the stage's bytes."""- stage = bytearray()- deadline = time.time() + seconds- while time.time() < deadline:- readable, _, _ = select.select([self.master], [], [], 0.1)- if self.master in readable:- try:- chunk = os.read(self.master, 65536)- except OSError:- break- if not chunk:- break- stage.extend(chunk)- self.stages.append(bytes(stage))- return bytes(stage)-- def write(self, data):- os.write(self.master, data)-- def close(self):- try:- self.proc.terminate()- self.proc.wait(5)- except Exception:- self.proc.kill()- try:- os.close(self.master)- except OSError:- pass---def run_scenario(command, env_extra, cwd, kind, markers=True):- """Drive one binary through a scenario; return the stage list.-- `kind`: "paste3" — the 3-line paste (small, inserts inline);- "large_paste" — the 20-line block (the collapse indicator, editor.ts:1342);- "shifted_range" — the shifted-printable range in both encodings.-- `markers=False` simulates a terminal that ignores bracketed paste- (tmux 3.2a's `paste-buffer` forwards the block as raw keystrokes): the- paste arrives as one marker-less burst, the shape TS StdinBuffer's- `isRawMultilinePaste` heuristic and the Rust burst coalescer both- recognize.- """- capture = PtyCapture(command, env_extra, cwd)- try:- # Stage 0: startup. Paste mode on, the kitty query out, the- # fallback armed (nothing answers under a raw pty).- capture.pump(6)- # Stage 1: the scenario's input.- if kind == "paste3":- payload = "\r\n".join(PASTE_LINES)- if markers:- payload = "\x1b[200~" + payload + "\x1b[201~"- capture.write(payload.encode())- elif kind == "large_paste":- payload = "\r\n".join(LARGE_PASTE_LINES)- if markers:- payload = "\x1b[200~" + payload + "\x1b[201~"- capture.write(payload.encode())- else: # shifted_range- # A legacy terminal sends the produced byte; a kitty-protocol- # terminal sends the CSI-u alternate (shifted codepoint) form.- # Both must land the produced character in the editor.- capture.write(SHIFTED_RANGE)- for sequence in KITTY_CSI_U_ALTERNATES:- capture.write(sequence)- capture.pump(4)- # Stage 2: Enter submits the whole block; the scripted turn runs.- capture.write(b"\r")- capture.pump(20)- # Stage 3: a clean double-Ctrl+C exit (drain + teardown sequences).- capture.write(b"\x03")- capture.pump(1)- capture.write(b"\x03")- capture.pump(4)- return capture.stages- finally:- capture.close()--def build_command(binary, sandbox, script_path):- common = {- "HOME": sandbox["home"],- "TMPDIR": sandbox["tmp"],- "PRIME_AGENT_CODING_AGENT_DIR": sandbox["agent"],- "PRIME_AGENT_FAUX_SCRIPT": script_path,- "PRIME_AGENT_DISABLE_ANALYTICS": "1",- }- if binary == "ts":- command = [- "prime-agent",- "--daemon-socket",- os.path.join(sandbox["agent"], "daemon.sock"),- "--model",- vp.TS_SCRIPT_MODEL,- ]- else:- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)),- "..",- "target",- "debug",- "prime-agent",- ),- )- common["PI_PACKAGE_DIR"] = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- command = [- rust,- "--daemon-socket",- os.path.join(sandbox["agent"], "daemon.sock"),- "--model",- vp.TS_SCRIPT_MODEL,- ]- return command, common---def check_stages(name, stages, raw_out, binary, kind, markers, suffix=""):- failures = []- startup, input_stage = stages[0], stages[1]- # The exit path spans the two Ctrl+C stages (the first press shows the- # exit hint, the second runs teardown).- exit_bytes = stages[3] + stages[4]- whole = b"".join(stages)-- if BRACKETED_PASTE_ON not in startup:- failures.append(f"startup never enables bracketed paste (no {BRACKETED_PASTE_ON!r})")- if KITTY_QUERY not in startup:- failures.append(f"startup never queries the kitty protocol (no {KITTY_QUERY!r})")- if binary == "ts":- # The fallback rides a 150ms timer: TS arms it from the event- # loop, so a busy startup (daemon attach, extension load) can push- # the write past the startup stage; it only has to be armed before- # the first Enter.- if MODIFY_OTHER_KEYS_ON not in stages[0] + stages[1]:- failures.append(f"the modifyOtherKeys fallback never armed (no {MODIFY_OTHER_KEYS_ON!r})")- else:- # The Rust side never arms mode 2 (crossterm drops the resulting- # CSI 27 sequences) and instead resets the mode at every start,- # clearing a sticky mode another pane or process left armed.- if MODIFY_OTHER_KEYS_ON in whole:- failures.append(f"the Rust side armed modifyOtherKeys mode 2 ({MODIFY_OTHER_KEYS_ON!r})")- if MODIFY_OTHER_KEYS_OFF not in startup:- failures.append(- f"the Rust startup never resets modifyOtherKeys (no {MODIFY_OTHER_KEYS_OFF!r})"- )-- if kind == "paste3":- # One editor update: every pasted word is on screen (the diff- # renderer may write a row word-by-word, so check words, not whole- # lines) and no submission may have happened while the paste sits- # in the editor. A per-line submit (the audit's dogfood class)- # would consume the first line as its prompt: its user-message zone- # marker and the turn would both show up before the Enter.- for word in ("alpha", "beta", "gamma"):- if word.encode() not in input_stage:- failures.append(f"the editor never rendered the pasted word {word!r}")- if WORKING_LABEL in input_stage or any(- word.encode() in input_stage for word in SENTINEL_WORDS- ):- failures.append("a turn started before Enter — a pasted line submitted on its own")- elif kind == "large_paste":- # The collapse indicator (editor.ts:1342): >10 lines collapses to- # the `[paste #<id> +N lines]` marker — one editor line, the raw- # bulk never renders before the send (the grown-editor bug class).- # The diff renderers may write the row word-by-word with cursor- # positioning between segments, so check the marker's words.- for part in (b"[paste", b"#1", b"+20", b"lines]"):- if part not in input_stage:- failures.append(- f"the editor never collapsed the large paste (no {part!r} of the marker)"- )- if b"bulk" in input_stage:- failures.append("the large paste grew the editor — a bulk line rendered before the send")- if WORKING_LABEL in input_stage or any(- word.encode() in input_stage for word in SENTINEL_WORDS- ):- failures.append("a turn started before Enter — a pasted line submitted on its own")- else: # shifted_range- # Every shifted character must reach the editor (a dropped char is- # the shift+= dogfood class); nothing may submit before the Enter.- for ch in SHIFTED_RANGE:- if ch.to_bytes(1, "big") not in input_stage:- failures.append(f"the shifted char {chr(ch)!r} never rendered in the editor")- if WORKING_LABEL in input_stage or any(- word.encode() in input_stage for word in SENTINEL_WORDS- ):- failures.append("a turn started before Enter — a shifted char submitted on its own")-- # Enter submits the whole block: the turn starts, and the echoed- # message carries the full content. The response may still be- # streaming at the stage boundary (or land in the exit flush), so the- # post-Enter stages are checked as one window.- post_enter = stages[2] + stages[3] + stages[4]- if not all(word.encode() in post_enter for word in SENTINEL_WORDS):- failures.append("the scripted turn never ran after Enter")- if kind == "paste3":- for line in PASTE_LINES:- if line.encode() not in post_enter:- failures.append(f"the submitted message lost the pasted line {line!r}")- elif kind == "large_paste":- # The submitted message carries the FULL pasted content (the- # indicator ships the stored text with the send).- for line in LARGE_PASTE_LINES:- if line.encode() not in post_enter:- failures.append(f"the submitted message lost the pasted line {line!r}")- else: # shifted_range- # The submitted message carries the typed characters.- for ch in SHIFTED_RANGE:- if ch.to_bytes(1, "big") not in post_enter:- failures.append(- f"the submitted message lost the shifted char {chr(ch)!r}"- )-- # A clean exit tears the modes down.- if BRACKETED_PASTE_OFF not in exit_bytes:- failures.append(f"exit never disables bracketed paste (no {BRACKETED_PASTE_OFF!r})")- if MODIFY_OTHER_KEYS_OFF not in exit_bytes:- failures.append(f"exit never resets modifyOtherKeys (no {MODIFY_OTHER_KEYS_OFF!r})")-- counts = {- "paste_on": whole.count(BRACKETED_PASTE_ON),- "paste_off": whole.count(BRACKETED_PASTE_OFF),- "kitty_query": whole.count(KITTY_QUERY),- }- print(- f"{name}: {len(whole)} bytes; "- f"?2004h x{counts['paste_on']}, ?2004l x{counts['paste_off']}, "- f"kitty query x{counts['kitty_query']}"- )- if raw_out:- with open(os.path.join(raw_out, f"{binary}{suffix}-raw.bin"), "wb") as f:- f.write(whole)- with open(os.path.join(raw_out, f"{binary}{suffix}-stages.json"), "w") as f:- json.dump([len(s) for s in stages], f)- if counts["paste_on"] != 1:- failures.append(f"bracketed paste enabled {counts['paste_on']} times (expected 1)")- if counts["paste_off"] != 1:- failures.append(f"bracketed paste disabled {counts['paste_off']} times (expected 1)")- return failures--def tmux(*args):- """Run tmux with TMUX unset (default socket only, the harness rules)."""- env = {k: v for k, v in os.environ.items() if k != "TMUX"}- return subprocess.run(["tmux"] + list(args), capture_output=True, text=True, env=env)---def run_tmux_scenario(binary, sandbox, script_path, shared_cwd):- """The user-level tmux test: paste a 3-line block into a real pane.-- tmux 3.2a (the box's version, the audit's reference) does not wrap- `paste-buffer` in bracketed markers, so the block reaches the pane as a- marker-less keystroke burst — the dogfood shape this lane fixes. The- editor must hold all three lines with no submission.- """- session = f"bpp-termkeys-{binary}"- tmux("kill-session", "-t", session)- tmux("new-session", "-d", "-s", session, "-x", str(WIDTH), "-y", str(HEIGHT), "-c", shared_cwd)- command, env = build_command(binary, sandbox, script_path)- env["TERM"] = "xterm-256color"- prefix = " ".join(f"{k}={v}" for k, v in env.items() if k != "TERM")- tmux("send-keys", "-t", session, f"{prefix} {subprocess.list2cmdline(command)}", "Enter")- time.sleep(8)-- buf_file = os.path.join(os.path.dirname(script_path), "paste.txt")- with open(buf_file, "w") as f:- f.write("\n".join(PASTE_LINES) + "\n")- tmux("load-buffer", "-b", "bpp-paste", buf_file)- tmux("paste-buffer", "-b", "bpp-paste", "-t", session)- time.sleep(3)- pane = tmux("capture-pane", "-p", "-t", session).stdout- tmux("kill-session", "-t", session)-- failures = []- for line in PASTE_LINES:- if line not in pane:- failures.append(f"the tmux paste never reached the editor ({line!r} missing)")- if pane.count(PASTE_LINES[0]) != 1:- failures.append(- f"{PASTE_LINES[0]!r} appears {pane.count(PASTE_LINES[0])} times "- f"(a submitted line echoes in the transcript; expected the editor copy only)"- )- if "SENTINEL" in pane:- failures.append("the turn started from the paste — a line submitted on its own")- if "Steering" in pane:- failures.append("a line queued as steering — a line submitted mid-paste")- print(f"{binary}/tmux pane: {sum(1 for _ in pane.splitlines())} rows")- return failures---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--keep", action="store_true", help="keep the sandbox dir")- parser.add_argument("--raw-out", default=None, help="directory for raw captures")- parser.add_argument(- "--binary", choices=("ts", "rust"), default=None, help="run one side only"- )- parser.add_argument(- "--tmux",- action="store_true",- help="also run the user-level tmux pane test (paste-buffer through tmux 3.2a)",- )- args = parser.parse_args()-- import tempfile- import shutil-- # Fail fast before any launch: a non-TS `prime-agent` on PATH plays a- # Rust build as the "ts" side and reports false divergences.- vp.ts_identity.assert_ts_side_is_the_ts_product()-- base = tempfile.mkdtemp(prefix="bracketed-paste-parity-")- out_dir = args.raw_out or tempfile.mkdtemp(prefix="bracketed-paste-raw-")- os.makedirs(out_dir, exist_ok=True)-- import visual_parity as vpm-- script_path = os.path.join(base, "faux-script.json")- with open(script_path, "w") as f:- json.dump(FAUX_SCRIPT, f, indent=2)- shared_cwd, _, sandboxes = vpm.prepare_sandbox(base)- # prepare_sandbox writes its own (tool-call heavy) faux script at the- # same path; the paste scenario needs the single-response one above.- with open(script_path, "w") as f:- json.dump(FAUX_SCRIPT, f, indent=2)- try:- failures = {}- binaries = ("ts", "rust") if not args.binary else (args.binary,)- for binary in binaries:- command, env = build_command(binary, sandboxes[binary], script_path)- failures[binary] = []- for markers in (True, False):- scenario = "bracketed" if markers else "marker-less burst"- stages = run_scenario(command, env, shared_cwd, "paste3", markers=markers)- suffix = "" if markers else "-burst"- failures[binary] += check_stages(- f"{binary}/{scenario}", stages, out_dir, binary,- "paste3", markers, suffix,- )- # The large-paste collapse (bracketed markers only: the shape- # real terminals send).- stages = run_scenario(command, env, shared_cwd, "large_paste")- failures[binary] += check_stages(- f"{binary}/large-paste", stages, out_dir, binary,- "large_paste", True, "-large",- )- # The shifted-printable range (both encodings).- stages = run_scenario(command, env, shared_cwd, "shifted_range")- failures[binary] += check_stages(- f"{binary}/shifted-range", stages, out_dir, binary,- "shifted_range", True, "-shifted",- )-- if args.tmux:- for binary in binaries:- failures[binary] += run_tmux_scenario(- binary, sandboxes[binary], script_path, shared_cwd- )-- ok = True- for binary, per_binary in failures.items():- if per_binary:- ok = False- for failure in per_binary:- print(f"FAIL {binary}: {failure}")- if ok:- print(- "PASS: both binaries bracket the paste (?2004h/l), keep "- "their modifyOtherKeys stance (TS arms the mode-2 fallback, "- "Rust resets it), land the 3-line paste as ONE editor "- "update with no per-line submissions (bracketed and "- "marker-less), collapse the 20-line paste to the indicator "- "and ship the full content at Enter, land the shifted-"- "printable range in both encodings, and submit the whole "- "block at Enter"- )- return 0 if ok else 1- finally:- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if not args.keep:- shutil.rmtree(base, ignore_errors=True)---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/clipboard_parity.py b/scripts/clipboard_parity.pydeleted file mode 100755index ca21d06c1f..0000000000--- a/scripts/clipboard_parity.py+++ /dev/null@@ -1,208 +0,0 @@-#!/usr/bin/env python3-"""Clipboard OSC 52 parity verifier: byte-capture the raw terminal stream of-the Rust interactive TUI and the installed TS binary while `/copy` runs, and-compare the OSC 52 clipboard sequences they emit (TS `utils/clipboard.ts`-`emitOsc52`: `ESC ] 52 ; c ; <base64> BEL`).--tmux parses (and swallows) OSC 52 like it does OSC 133, so both binaries run-under a raw pty with every byte recorded before any terminal parser sits in-between (the same capture contract scripts/osc_parity.py uses). The scenario-runs the scripted faux turn both sides consume, so the last assistant text —-and therefore the OSC 52 payload — must be byte-identical.--The clipboard tool chain is neutralized on both sides (no DISPLAY, no-WAYLAND_DISPLAY, no SSH transport), which is the TS fallback condition that-reaches the OSC 52 emitter.--Exit code is non-zero when the sequences differ or either side emits none.-"""--import argparse-import base64-import fcntl-import os-import pty-import re-import select-import shutil-import struct-import subprocess-import sys-import tempfile-import termios-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)-import visual_parity as vp # noqa: E402 (the shared sandbox/faux fixtures)--WIDTH, HEIGHT = 120, 36--# The OSC 52 clipboard-set sequence: ESC ] 52 ; c ; <base64> BEL.-OSC52 = re.compile(rb"\x1b\]52;c;([A-Za-z0-9+/=]*)\x07")---def run_pty(command, env_extra, cwd, keys_script, total_seconds):- """Run `command` under a raw pty; return every output byte."""- master, slave = pty.openpty()- fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", HEIGHT, WIDTH, 0, 0))- env = dict(os.environ)- env["TERM"] = "xterm-256color"- # The copy must reach the OSC 52 fallback: no platform clipboard tools- # answer without a display, and no SSH transport marks the session- # remote (which would ALSO emit — but both sides then race their local- # tool chain; the deterministic capture removes both).- for var in (- "DISPLAY",- "WAYLAND_DISPLAY",- "SSH_CONNECTION",- "SSH_CLIENT",- "MOSH_CONNECTION",- "TERMUX_VERSION",- ):- env.pop(var, None)- env.update(env_extra)- proc = subprocess.Popen(- command, stdin=slave, stdout=slave, stderr=slave, env=env, cwd=cwd- )- os.close(slave)- out = bytearray()-- def pump(dur):- deadline = time.time() + dur- while time.time() < deadline:- readable, _, _ = select.select([master], [], [], 0.1)- if master in readable:- try:- chunk = os.read(master, 65536)- except OSError:- return False- if not chunk:- return False- out.extend(chunk)- return True-- keys_script(master, pump)- time.sleep(0.5)- try:- proc.terminate()- proc.wait(5)- except Exception:- proc.kill()- os.close(master)- return bytes(out)---def copy_keys(master, pump):- """Drive the scripted turn, then `/copy` once the answer settles."""- pump(8)- os.write(master, vp.PROMPT.encode() + b"\r")- pump(30)- # The turn's final answer is on screen; the status row after the copy is- # the settle signal, but the raw stream is what matters — `/copy` now.- os.write(master, b"/copy\r")- pump(3)---def capture(binary, sandbox, shared_cwd, script_path):- agent = sandbox["agent"]- common = {- "HOME": sandbox["home"],- "TMPDIR": sandbox["tmp"],- "PRIME_AGENT_CODING_AGENT_DIR": agent,- "PRIME_AGENT_FAUX_SCRIPT": script_path,- "PRIME_AGENT_DISABLE_ANALYTICS": "1",- }- if binary == "ts":- command = [- "prime-agent",- "--daemon-socket",- os.path.join(agent, "daemon.sock"),- "--model",- vp.TS_SCRIPT_MODEL,- ]- else:- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)),- "..",- "target",- "debug",- "prime-agent",- ),- )- common["PI_PACKAGE_DIR"] = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- command = [- rust,- "--daemon-socket",- os.path.join(agent, "daemon.sock"),- "--model",- vp.TS_SCRIPT_MODEL,- ]- return run_pty(command, common, shared_cwd, copy_keys, 45)---def osc52_sequences(raw):- return [m.group(0) for m in OSC52.finditer(raw)]---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--keep", action="store_true", help="keep the sandbox dir")- parser.add_argument("--raw-out", default=None, help="directory for raw captures")- args = parser.parse_args()-- # Fail fast before any launch: a non-TS `prime-agent` on PATH plays a- # Rust build as the "ts" side and reports false parity.- vp.ts_identity.assert_ts_side_is_the_ts_product()-- base = tempfile.mkdtemp(prefix="clipboard-parity-sandbox-")- out_dir = args.raw_out or tempfile.mkdtemp(prefix="clipboard-parity-raw-")- os.makedirs(out_dir, exist_ok=True)- shared_cwd, script_path, sandboxes = vp.prepare_sandbox(base)- try:- raw = {}- for binary in ("ts", "rust"):- raw[binary] = capture(binary, sandboxes[binary], shared_cwd, script_path)- with open(os.path.join(out_dir, f"{binary}-raw.bin"), "wb") as f:- f.write(raw[binary])- sequences = osc52_sequences(raw[binary])- print(f"{binary}: {len(raw[binary])} bytes; {len(sequences)} OSC 52 sequence(s)")- for sequence in sequences:- encoded = OSC52.search(sequence).group(1)- text = base64.b64decode(encoded)- print(f" payload: {text!r}")-- ts_sequences = osc52_sequences(raw["ts"])- rust_sequences = osc52_sequences(raw["rust"])- if not ts_sequences:- print("FAIL: the TS binary emitted no OSC 52 sequence (the tool chain found a clipboard?)")- return 1- if not rust_sequences:- print("FAIL: the Rust binary emitted no OSC 52 sequence")- return 1- if ts_sequences != rust_sequences:- print("FAIL: the OSC 52 sequences differ")- for side in ("ts", "rust"):- print(f" {side}: {osc52_sequences(raw[side])}")- return 1- # The payload must be the scripted turn's final answer.- text = base64.b64decode(OSC52.search(ts_sequences[0]).group(1))- if vp.TURN1_FINAL_ANSWER.encode() not in text:- print(f"FAIL: the payload is not the scripted answer: {text!r}")- return 1- print(f"PASS: both binaries copied the same text via the same OSC 52 bytes ({text!r})")- return 0- finally:- # Rmtree alone leaks the scenario daemons: sweep every daemon this- # run spawned before deleting the sandbox.- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if not args.keep:- shutil.rmtree(base, ignore_errors=True)---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/command_dispatch_parity.py b/scripts/command_dispatch_parity.pydeleted file mode 100644index 811e19559c..0000000000--- a/scripts/command_dispatch_parity.py+++ /dev/null@@ -1,269 +0,0 @@-#!/usr/bin/env python3-"""Command-dispatch parity harness: the daemon-response timeout class from-the 2026-09-22 dogfood (/system-prompt timing out at the client's 10s-bound). One driver, two sides:--- ts: the TS daemon (node ~/prime-agent/packages/coding-agent/dist/cli-main.js- --mode daemon --daemon-socket <sock>) on a slow-streaming mock provider-- rust: the Rust supervisor (pa-daemon supervisor --socket <sock>)--Each side gets a created + attached session, an idle command matrix, then a-turn whose provider streams one chunk and holds it open (12s) while the same-matrix runs mid-turn. The printed tables are the parity evidence: the TS bar-is that every client command answers fast while a turn streams.-"""--import argparse-import http.server-import json-import os-import shutil-import socket-import subprocess-import tempfile-import threading-import time-import urllib.parse--TURN_HOLD_MS = 12_000--MATRIX = [- ("get_session_stats", "/session"),- ("get_context_tree", "/context, /usage"),- ("get_session_context", "wire: get_session_context"),- ("get_system_prompt", "/system-prompt"),- ("get_tool_definition", "wire: get_tool_definition"),- ("get_resource_snapshot", "wire: get_resource_snapshot"),-]---class SlowMock(http.server.BaseHTTPRequestHandler):- protocol_version = "HTTP/1.1"-- def log_message(self, *args):- pass-- def do_POST(self):- length = int(self.headers.get("Content-Length", 0))- self.rfile.read(length)- chunk = json.dumps({- "id": "chatcmpl-test",- "object": "chat.completion.chunk",- "created": 1750000000,- "model": "mock-1",- "choices": [{"index": 0, "delta": {"role": "assistant", "content": "streaming"}, "finish_reason": None}],- })- tail = json.dumps({- "id": "chatcmpl-test",- "object": "chat.completion.chunk",- "created": 1750000000,- "model": "mock-1",- "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],- })- # Plain connection-close SSE (no chunked framing): the first- # chunk streams immediately so the assistant message_start- # reaches the client; the hold keeps the turn mid-flight.- self.send_response(200)- self.send_header("Content-Type", "text/event-stream")- self.send_header("Connection", "close")- self.end_headers()- self.wfile.write(f"data: {chunk}\n\n".encode())- self.wfile.flush()- time.sleep(TURN_HOLD_MS / 1000.0)- rest = f"data: {tail}\n\ndata: [DONE]\n\n".encode()- self.wfile.write(rest)- self.wfile.flush()---def start_mock():- server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), SlowMock)- thread = threading.Thread(target=server.serve_forever, daemon=True)- thread.start()- return f"http://127.0.0.1:{server.server_address[1]}/v1", server---class Client:- def __init__(self, path):- self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- self.sock.settimeout(1.0)- self.sock.connect(path)- self.buffer = b""- self.hello = self.read_line()- assert self.hello["type"] == "daemon_hello", self.hello-- def read_line(self, timeout=60.0):- deadline = time.time() + timeout- while b"\n" not in self.buffer:- if time.time() > deadline:- raise TimeoutError("no daemon line within timeout")- try:- data = self.sock.recv(65536)- except socket.timeout:- continue- if not data:- raise EOFError("daemon closed the connection")- self.buffer += data- line, self.buffer = self.buffer.split(b"\n", 1)- return json.loads(line)-- def send(self, id_, command):- envelope = json.dumps({- "type": "command",- "id": id_,- "protocol": {"name": "prime-agent.daemon", "version": 7},- "command": command,- })- self.sock.sendall((envelope + "\n").encode())-- def request(self, id_, command):- started = time.monotonic()- self.send(id_, command)- while True:- line = self.read_line()- if line.get("id") == id_:- return line, (time.monotonic() - started) * 1000.0-- def wait_for(self, predicate, timeout=60.0):- deadline = time.time() + timeout- while time.time() < deadline:- line = self.read_line(deadline - time.time())- if predicate(line):- return line- raise TimeoutError("event never arrived")---def is_event(line, event_type, role=None):- if line.get("type") != "session_event":- return False- event = line.get("event", {})- if event.get("type") != event_type:- return False- if role is None:- return True- return event.get("message", {}).get("role") == role---def run_matrix(client, session_id, phase):- rows = []- for index, (command, surface) in enumerate(MATRIX):- payload = {"type": command, "activeSessionId": session_id}- if command == "get_tool_definition":- payload["name"] = "bash"- response, elapsed = client.request(f"matrix-{phase}-{index}", payload)- rows.append((f"{command} ({surface})", elapsed, bool(response.get("success"))))- print(f"== response-time table ({phase}) ==")- for name, elapsed, ok in rows:- print(f"{name:<45} {elapsed:>10.0f} ms {'ok' if ok else 'FAILED'}")- return rows---def write_agent_config(agent_dir, mock_url):- os.makedirs(agent_dir, exist_ok=True)- os.makedirs(os.path.join(agent_dir, "sessions"), exist_ok=True)- with open(os.path.join(agent_dir, "models.json"), "w") as f:- json.dump({- "providers": {- "prime-inference": {- "api": "openai-completions",- "baseUrl": mock_url,- "apiKey": "sk-battery",- "models": [{- "id": "mock-1",- "name": "Mock 1",- "api": "openai-completions",- "contextWindow": 128000,- "maxTokens": 4096,- }],- }- }- }, f)- with open(os.path.join(agent_dir, "settings.json"), "w") as f:- json.dump({"onboardingCompleted": True}, f)---def run_side(side, daemon_command, sock, home, cwd, env_extra):- agent_dir = os.path.join(home, ".prime")- env = dict(os.environ)- env["HOME"] = home- env.update(env_extra)- proc = subprocess.Popen(- daemon_command,- cwd=cwd,- env=env,- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- )- try:- deadline = time.time() + 15- while not os.path.exists(sock) and time.time() < deadline:- time.sleep(0.05)- if not os.path.exists(sock):- raise SystemExit(f"[{side}] daemon socket never appeared")- client = Client(sock)- client.send("c1", {- "type": "create",- "config": {- "cwd": cwd,- "sessionDir": os.path.join(agent_dir, "sessions"),- "provider": "prime-inference",- "model": "mock-1",- },- })- created = client.wait_for(lambda line: line.get("id") == "c1")- if not created.get("success"):- raise SystemExit(f"[{side}] create failed: {created}")- session_id = (created.get("data", {}).get("id")- or created.get("data", {}).get("sessionId"))- client.send("a1", {"type": "attach", "activeSessionId": session_id})- attached = client.wait_for(lambda line: line.get("id") == "a1")- if not attached.get("success"):- raise SystemExit(f"[{side}] attach failed: {attached}")-- print(f"\n===== side: {side} =====")- run_matrix(client, session_id, "idle")-- client.send("p1", {"type": "prompt", "activeSessionId": session_id, "message": "hello"})- client.wait_for(lambda line: is_event(line, "message_start", "assistant"))- run_matrix(client, session_id, "mid-turn")- client.wait_for(lambda line: is_event(line, "agent_end"), timeout=60)- finally:- proc.terminate()- try:- proc.wait(timeout=5)- except subprocess.TimeoutExpired:- proc.kill()---def main():- parser = argparse.ArgumentParser()- parser.add_argument("--side", choices=["ts", "rust"], required=True)- parser.add_argument("--rust-bin", default="target/debug/pa-daemon")- args = parser.parse_args()-- mock_url, server = start_mock()- base = tempfile.mkdtemp(prefix=f"cmd-dispatch-{args.side}-")- home = os.path.join(base, "home")- cwd = os.path.join(base, "cwd")- os.makedirs(home)- os.makedirs(cwd)- agent_dir = os.path.join(home, ".prime")- write_agent_config(agent_dir, mock_url)- sock = os.path.join(base, "daemon.sock")- try:- if args.side == "ts":- repo = os.path.expanduser("~/prime-agent/packages/coding-agent")- command = ["node", os.path.join(repo, "dist", "cli-main.js"),- "--mode", "daemon", "--daemon-socket", sock]- run_side("ts", command, sock, home, cwd, {})- else:- repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- run_side("rust", [os.path.join(repo, args.rust_bin), "supervisor",- "--socket", sock, "--agent-dir", agent_dir],- sock, home, cwd, {})- finally:- shutil.rmtree(base, ignore_errors=True)- server.shutdown()---if __name__ == "__main__":- main()diff --git a/scripts/command_dispatch_ts_repro.py b/scripts/command_dispatch_ts_repro.pydeleted file mode 100644index 6fa6ccce5a..0000000000--- a/scripts/command_dispatch_ts_repro.py+++ /dev/null@@ -1,207 +0,0 @@-#!/usr/bin/env python3-"""tmux-driven TS interactive repro for the daemon-response timeout class:-while a turn streams against a slow mock provider (one chunk, then a 12s-hold), `/system-prompt` must render immediately — the TS bar for the Rust-fix. Prints the command-to-render time and the captured frame-set.-"""--import argparse-import http.server-import json-import os-import shutil-import subprocess-import tempfile-import threading-import time--TURN_HOLD_MS = 12_000---class SlowMock(http.server.BaseHTTPRequestHandler):- protocol_version = "HTTP/1.1"-- def log_message(self, *args):- pass-- def do_POST(self):- length = int(self.headers.get("Content-Length", 0))- self.rfile.read(length)- chunk = json.dumps({- "id": "chatcmpl-test", "object": "chat.completion.chunk",- "created": 1750000000, "model": "mock-1",- "choices": [{"index": 0, "delta": {"role": "assistant", "content": "streaming"}, "finish_reason": None}],- })- tail = json.dumps({- "id": "chatcmpl-test", "object": "chat.completion.chunk",- "created": 1750000000, "model": "mock-1",- "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],- })- # Plain connection-close SSE (no chunked framing): the first- # chunk streams immediately so the assistant message_start- # reaches the client; the hold keeps the turn mid-flight.- self.send_response(200)- self.send_header("Content-Type", "text/event-stream")- self.send_header("Connection", "close")- self.end_headers()- self.wfile.write(f"data: {chunk}\n\n".encode())- self.wfile.flush()- time.sleep(TURN_HOLD_MS / 1000.0)- rest = f"data: {tail}\n\ndata: [DONE]\n\n".encode()- self.wfile.write(rest)- self.wfile.flush()---def tmux(*args, check=True):- return subprocess.run(["tmux", *args], capture_output=True, text=True, check=check)---def capture(session):- result = tmux("capture-pane", "-p", "-t", session, check=False)- return result.stdout---def wait_stable(session, quiet_ms=700, timeout=60):- deadline = time.time() + timeout- last = capture(session)- last_change = time.time()- while time.time() < deadline:- time.sleep(0.15)- current = capture(session)- if current != last:- last = current- last_change = time.time()- elif (time.time() - last_change) * 1000 >= quiet_ms:- return last- raise SystemExit("pane never settled")---def main():- parser = argparse.ArgumentParser()- parser.add_argument("--side", choices=["ts", "rust"], default="ts")- parser.add_argument("--rust-bin", default="target/debug/prime-agent")- args = parser.parse_args()-- server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), SlowMock)- threading.Thread(target=server.serve_forever, daemon=True).start()- mock_url = f"http://127.0.0.1:{server.server_address[1]}/v1"-- base = tempfile.mkdtemp(prefix=f"cmd-dispatch-tmux-{args.side}-")- home = os.path.join(base, "home")- cwd = os.path.join(base, "cwd")- tmp = os.path.join(base, "tmp")- agent_dir = os.path.join(base, "agent")- for path in (home, cwd, tmp, os.path.join(agent_dir, "sessions")):- os.makedirs(path, exist_ok=True)- with open(os.path.join(agent_dir, "models.json"), "w") as f:- json.dump({- "providers": {- "prime-inference": {- "api": "openai-completions", "baseUrl": mock_url,- "apiKey": "sk-battery",- "models": [{"id": "mock-1", "name": "Mock 1", "api": "openai-completions",- "contextWindow": 128000, "maxTokens": 4096}],- }- }- }, f)- with open(os.path.join(agent_dir, "settings.json"), "w") as f:- # Both keys (the release binary may predate the `onboardingShown`- # rename): the splash and its trace-consent question must stay- # away so the repro drives a settled interactive session.- json.dump({"onboardingCompleted": True, "onboardingShown": True,- "agentTraces": {"enabled": False}}, f)-- session = f"cmd-dispatch-{args.side}"- tmux("kill-session", "-t", session, check=False)- if args.side == "ts":- # The installed TS product binary on PATH (the standing pattern for- # the parity harnesses; it is the packaged node SEA build).- ts_bin = shutil.which("prime-agent")- if not ts_bin:- raise SystemExit("prime-agent (TS product) not on PATH")- command = [ts_bin, "--provider", "prime-inference", "--model", "mock-1"]- else:- repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- command = [os.path.join(repo, args.rust_bin),- "--provider", "prime-inference", "--model", "mock-1"]- command += ["--daemon-socket", os.path.join(base, "daemon.sock")]- # Isolate from any embedding daemon env (this harness may itself run- # inside a worker, and the tmux server replays its own environment):- # a leaked socket/env would connect the sandbox TUI to the live daemon- # instead of a fresh sandboxed one.- unset = [- key for key in os.environ- if key.startswith("PRIME_AGENT_INTERNAL_")- ] + ["PI_PACKAGE_DIR", "PRIME_API_KEY", "PI_CODING_AGENT"]- prefix = ("env " + " ".join(f"-u {key}" for key in unset)- + f" HOME={home} TMPDIR={tmp}"- + f" PRIME_AGENT_CODING_AGENT_DIR={agent_dir}"- + " PRIME_AGENT_DISABLE_ANALYTICS=1 ")- subprocess.run(- ["tmux", "new-session", "-d", "-s", session, "-x", "120", "-y", "40", "-c", cwd,- prefix + " ".join(command) + " 2>" + os.path.join(base, "err.log")],- check=True)- try:- wait_stable(session, timeout=90)- # The boot sequence keeps painting transient notices after the- # logo settles; a second settle window keeps the first keystrokes- # from being swallowed by a notice that eats Enter.- time.sleep(2)- wait_stable(session, timeout=30)- # Fallback: an onboarding dialog still up gets dismissed with- # "Not now" (Down, Enter), then the pane must settle again.- if "Share agent traces" in capture(session):- tmux("send-keys", "-t", session, "Down", "Enter")- wait_stable(session, timeout=30)- tmux("send-keys", "-t", session, "-l", "hello")- time.sleep(0.5)- tmux("send-keys", "-t", session, "Enter")- # Wait for the streamed first chunk (the assistant row holds- # "streaming" while the mock keeps the turn open).- deadline = time.time() + 60- while time.time() < deadline:- pane = capture(session)- if "streaming" in pane:- break- time.sleep(0.1)- else:- raise SystemExit("the turn never streamed:\n" + capture(session))- started = time.monotonic()- tmux("send-keys", "-t", session, "-l", "/system-prompt")- time.sleep(0.3)- tmux("send-keys", "-t", session, "Enter")- # The header row renders as soon as the command answers; a long- # prompt scrolls the header off the pane, so any assembled-prompt- # body line (the skills inventory section) counts as rendered.- deadline = time.time() + 30- elapsed = None- pane_at_render = None- while time.time() < deadline:- pane = capture(session)- # The whole prompt block paints in one frame and the view- # shows its tail, so the closing tag of the skills inventory- # is the always-visible marker (the header scrolled off).- if ("System Prompt (" in pane or "<available_skills>" in pane- or "</available_skills>" in pane):- elapsed = (time.monotonic() - started) * 1000.0- pane_at_render = pane- break- time.sleep(0.05)- if elapsed is None:- raise SystemExit("/system-prompt never rendered:\n" + capture(session))- print(f"[{args.side}] /system-prompt mid-turn render time: {elapsed:.0f} ms")- # The streaming turn is still open at render time (the mock holds- # for {TURN_HOLD_MS} ms; the render must land well inside it).- print(f"[{args.side}] turn-hold window: {TURN_HOLD_MS} ms (render inside it: {elapsed < TURN_HOLD_MS})")- print("---- pane at render ----")- for line in pane_at_render.splitlines():- if line.strip():- print(line)- finally:- tmux("kill-session", "-t", session, check=False)- shutil.rmtree(base, ignore_errors=True)- server.shutdown()---if __name__ == "__main__":- main()diff --git a/scripts/compact_parity.py b/scripts/compact_parity.pydeleted file mode 100644index e76feb5a22..0000000000--- a/scripts/compact_parity.py+++ /dev/null@@ -1,623 +0,0 @@-#!/usr/bin/env python3-"""Compaction-feedback parity verifier: frame-diff the Rust interactive UI-against the installed TS prime-agent binary for the /compact visible-outcome, over one shared faux script under isolated HOME/agent-dir-sandboxes in tmux at 100x30 (the interactive e2e's headless geometry):-- - the fresh-session skip: /compact on a new session shows the durable- warning row (TS compaction_end errorMessage, warning severity),- - the in-flight loader: the muted `Compacting context (focus: ...)- ... (Ctrl+C to cancel)` row while the summarizer streams (TS- startCompactionLoader),- - the settled outcome: the `◆ Context compacted` summary row heading the- rebuilt transcript (TS CompactionSummaryMessageComponent +- rebuildChatFromMessages), with the compacted-away first turn gone,- - the expanded block: Ctrl+O twice (overview -> details -> all) swaps the- collapsed two-line EventSummary for the markdown body plus the dim- `Compacted from N tokens` metadata row, and the third press re-collapses- it (TS applyChatExpansion fanning toolOutputExpanded into- CompactionSummaryMessageComponent).--Both sides run the same token-paced faux provider script; the sandbox-settings.json pins compaction.keepRecentTokens=10 so the kept tail after-the cut is a few rows and the summary row lands on screen in the default-bottom-follow view on both sides (no keybinding-dependent scrolling).-One documented divergence (Kevin/Sebastian directive 2026-09-23, product-improvement BEYOND TS): the expanded compaction block hangs on the branch-grammar — the markdown body carries the dim `╰─ ` gutter on-its first row hanging off the `◆` header, every row after the-four-space continuation indent, the metadata row on the continuation-indent — instead of the TS `ExpandableEventMessage`'s plain one-column-chat inset. The expanded state therefore compares by content, not bytes:-from the `◆ Context compacted` header down, every visible word must match-with whitespace collapsed — the intended divergence is the indentation and-the wrap points it forces, never the summary text itself, so a truncated,-omitted, or changed body fails the run instead of hiding behind the-divergence. The run separately asserts the Rust expanded rows carry the-branch and the TS frames keep the plain-inset baseline; the collapsed-states keep the byte-for-byte frame diff.-Frames are normalized for volatile content (versions, session ids,-durations, spinners) and diffed; the exit code is non-zero when any state-differs.--tmux rules: a private `-L` socket (the shared server's panes inherit the-box daemon env and hijack the Rust side's supervisor socket), cpparity-*-session names on it; the private server dies with the run.-"""--import argparse-import difflib-import json-import os-import re-import shutil-import subprocess-import sys-import tempfile-import time--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--SIZES = [("100", "30")]--WIDTH, HEIGHT = SIZES[0]--# One shared faux script (the TS sandbox extension and the Rust-# PRIME_AGENT_FAUX_SCRIPT harness read the same contract): a large first-# turn gives the compactor history to summarize, a small second turn is-# kept intact in full, and the third response is the summarizer's summary,-# padded so the token-paced stream holds the loader on screen long enough-# to capture on both sides.-FILLER = "history " * 600-SUMMARY_CORE = "## Summary\nthe session story of the compacted parity session, told at deliberate length so the token-paced faux stream holds the compaction loader on screen long enough for the harness to capture it on both sides. "-SUMMARY = SUMMARY_CORE + "Padding sentence to pace the stream. " * 18--FAUX_SCRIPT = {- "engine": "faux",- "modelId": "faux-1",- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 100,- "responses": [- {"text": FILLER},- {"text": "second turn done, kept intact"},- {"text": SUMMARY},- ],-}--# Shared with tool_card_parity.py: one extension source for every harness.-TS_FAUX_EXTENSION = open(- os.path.join(os.path.dirname(os.path.abspath(__file__)), "ts_faux_extension.js"),- encoding="utf-8",-).read()--# Sandbox settings pin the cut budget: keepRecentTokens=10 keeps only the-# small second turn after the cut, so the rebuilt transcript is a few rows-# and the summary row is visible in the bottom-follow view on both sides.-SETTINGS = {"onboardingCompleted": True, "compaction": {"keepRecentTokens": 10}}--FIRST_PROMPT = "first"-SECOND_PROMPT = "second, and please keep this second parity turn short and intact"-COMPACT_COMMAND = "/compact focus on the goal"--SPINNER_CLASS = "[\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f\u25f4\u25f7\u25f6\u25f5\u25cb\u25f8\u25fb\u25fc]"--STATES = [- # The skip warning on a fresh session (durable warning row).- ("a_skip_warning", "the fresh-session /compact skip warning"),- # The in-flight compaction loader (muted spinner + label + cancel hint).- ("b_loader", "the compaction loader while the summarizer streams"),- # The settled outcome: summary row heading the rebuilt transcript.- ("c_post_compact", "the post-compaction rebuilt transcript"),- # The expanded block: Ctrl+O twice (overview -> details -> all) turns- # the collapsed `EventSummary` into the markdown body + the dim- # `Compacted from N tokens` metadata row.- ("d_expanded", "the summary block expanded by the Ctrl+O detail cycle"),-]---# An isolated tmux server: panes inherit the SERVER's environment, and a-# server started from an agent session carries that agent's environment —-# a herdr `SHELL` auto-launches a live agent in every pane, and a-# `PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_SOCKET` makes the Rust TUI-# attach to a foreign supervisor instead of the harness's own sandbox-# daemon. The private socket plus the scrubbed client environment below-# keep the harness panes self-contained; the server dies with the run.-TMUX_SOCKET = f"compact-parity-{os.getpid()}"---def tmux_client_env():- """The environment the harness's private tmux server and panes run- with: this process's environment minus every prime-agent/herdr- variable, and a plain login shell as the pane default (the first- installed one; the box has zsh, a bare VM has bash)."""- env = {key: value for key, value in os.environ.items() if not key.startswith(("PRIME_AGENT_", "HERDR_"))}- env.pop("TMUX", None)- env.pop("TMUX_PANE", None)- env["SHELL"] = next(- (shell for shell in ("/bin/zsh", "/bin/bash") if os.path.exists(shell)),- "/bin/sh",- )- return env---def tmux(*args, check=True):- result = subprocess.run(- ["tmux", "-L", TMUX_SOCKET, *args],- capture_output=True,- text=True,- env=tmux_client_env(),- )- if check and result.returncode != 0:- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")- return result.stdout---def capture(session):- return tmux("capture-pane", "-e", "-p", "-t", session)---def capture_plain(session):- return tmux("capture-pane", "-p", "-t", session)---def capture_plain_text(frame):- """Strip ANSI codes so content assertions match the visible text."""- return re.sub(r"\x1b\[[0-9;]*[A-Za-z]", "", frame)---def normalize(frame, root):- frame = frame.replace(root, "<SANDBOX>")- frame = re.sub(r"v\d+\.\d+\.\d+", "vX.X.X", frame)- frame = re.sub(r"\b[0-9a-f]{12}\b", "<SID>", frame)- frame = re.sub(r"\b\d+(\.\d+)?(ms|s)\b", "<T>", frame)- frame = re.sub(r"\d+(\.\d+)?[kM]? \(\d+%\)", "<TOK> (<PCT>)", frame)- frame = re.sub(r"[\u2193\u2191] [\d.kM]+ tokens", "<DIR> <TOK> tokens", frame)- frame = re.sub(r"\b\d+s\b", "<S>", frame)- spinners = "".join("\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f")- frame = re.sub("[" + spinners + "]", "<SPIN>", frame)- # The TS product's ripgrep notice (a startup environment notice when- # rg is missing under PI_OFFLINE; the Rust build has no equivalent- # row yet) is box environment, not transcript parity.- kept = []- notice = False- for line in frame.split("\n"):- if any(- needle in line- for needle in (- "ripgrep (rg) is an optional search helper",- "Install it with: brew install ripgrep",- "Automatic installation was skipped because PI_OFFLINE",- "and subagents remain available.",- )- ):- # The notice's trailing blank row drops with it (the block- # is notice + one blank on the TS side).- notice = True- continue- if notice and line.strip() == "":- notice = False- continue- notice = False- kept.append(line)- frame = "\n".join(kept)- pulses = "".join("\u25f4\u25f7\u25f6\u25f5\u25cb\u25f8\u25fb\u25fc")- frame = re.sub("[" + pulses + "]", "<PULSE>", frame)- # tmux places trailing resets (foreground 39m, background 49m) at either- # the end of the row whose styled text just ended or before the next- # row's default margin; both describe default cells, so drop them.- frame = re.sub(r"\x1b\[39m\n", "\n", frame)- frame = re.sub(r"\n\x1b\[39m(?= )", "\n", frame)- frame = re.sub(r"\x1b\[49m\n", "\n", frame)- frame = re.sub(r"\n\x1b\[49m(?= )", "\n", frame)- # The tray right side is right-aligned against differing token counts;- # collapse the alignment padding so the row compares by content.- frame = re.sub(- r" +((?:\x1b\[[0-9;]*m)*(?:faux-1 \u00b7 )?<TOK> \(<PCT>\)\s*)$",- r" <TRAY-RIGHT>\1",- frame,- flags=re.MULTILINE,- )- # The expanded block's metadata reports the pre-compaction context size,- # which each side estimates with its own token counter (the shape and- # the focus text are the parity claim; the number is per-implementation).- frame = re.sub(r"Compacted from [0-9,]+ tokens", "Compacted from <N> tokens", frame)- return frame---def expanded_block_signature(frame):- """The expanded compaction block's content signature: every visible- word from the `◆ Context compacted` header down, ANSI-stripped, the- branch gutter glyphs dropped, whitespace collapsed.-- The expanded state's intended divergence is indentation (the branch- grammar vs the TS plain inset) plus the wrap points the narrower- branch content width forces; the block's CONTENT — the heading, the- summary body, the metadata row, the focus text — must match word for- word. Comparing by collapsed content is what makes that a real check:- a byte diff of the diverged block can only fail by design, and- dropping the block's rows from the comparison would let a truncated- or changed summary body pass. Rows above the header stay out of the- signature: the bottom-pinned windows sit at different tops when the- diverged block's row counts differ (a window artifact, not content),- and those transcript rows are byte-diffed by the settled- `c_post_compact` state."""- plain = capture_plain_text(frame)- rows = plain.split("\n")- start = next((i for i, row in enumerate(rows) if "Context compacted" in row), None)- if start is None:- return None- block = "\n".join(rows[start:]).replace("╰─", " ")- return re.sub(r"\s+", " ", block).strip()---def assert_compaction_branch(ts_expanded, rust_expanded):- """The carried divergence: the Rust expanded block hangs on the branch- grammar (`╰─ ` gutter off the `◆` header, the- four-space continuation indent); the TS binary keeps the plain- one-column chat inset (the baseline)."""- gutter = "╰─ "- assert " " + gutter + "Summary" in rust_expanded, (- "rust: the expanded heading row missing the branch gutter"- )- # The faux summary opens with `## Summary`, so the heading row is- # the one row the gutter hangs on (the branch grammar's first- # content row); the story paragraph sits on the continuation indent- # behind it.- assert " the session story" in rust_expanded, (- "rust: the expanded body missing the continuation indent"- )- assert " Compacted from" in rust_expanded, (- "rust: the metadata row missing the continuation indent"- )- assert " Summary" in ts_expanded, "ts: expanded heading missing (baseline)"- assert gutter + "Summary" not in ts_expanded, "ts: unexpectedly renders the branch"- assert " Compacted from" in ts_expanded, "ts: metadata row missing (baseline)"---def align_frame_tops(left, right):- """Trim the scroll-leak rows a bottom-pinned viewport shows, and only- those.-- The compared frames are bottom-pinned viewport windows; a row-count- delta anywhere in the content shifts one window's top over the- other's — the longer frame's top rows are rows the shorter side- scrolled off, a window artifact, not a row-shape divergence. The- bottom is the anchor: the trailing rows are the same pane tail on- both sides, so a proven common suffix must cover the whole length- difference before any top row is dropped, and then only the length- difference itself comes off the longer frame's top. No row is ever- dropped because it exists somewhere in the other frame — a real- top-of-screen regression still diffs."""- left_rows, right_rows = left.split("\n"), right.split("\n")- n, m = len(left_rows), len(right_rows)- if n == m:- return left, right- longer, shorter = (left_rows, right_rows) if n > m else (right_rows, left_rows)- delta = abs(n - m)- # Prove the bottoms correspond: count the longest common suffix.- suffix = 0- while suffix < min(n, m) and longer[len(longer) - 1 - suffix] == shorter[len(shorter) - 1 - suffix]:- suffix += 1- if suffix < delta:- # No proven bottom anchor covering the leak: leave both frames- # whole so the diff surfaces every differing row.- return left, right- if n > m:- return "\n".join(left_rows[delta:]), right- return left, "\n".join(right_rows[delta:])---def diff_lines(left, right):- return "\n".join(- difflib.unified_diff(left.split("\n"), right.split("\n"), fromfile="ts", tofile="rust", lineterm="", n=1)- )---def diff_words(left, right):- """A readable report for the content-signature compare: a word-level- unified diff (the signatures are single collapsed lines)."""- return "\n".join(- difflib.unified_diff(- (left or "").split(), (right or "").split(), fromfile="ts", tofile="rust", lineterm="", n=2- )- )---def find_runtime_package_dir():- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- if not os.path.isdir(releases):- raise SystemExit("cannot find the prime-agent-runtime sidecar; set PI_PACKAGE_DIR")- candidates = [- entry- for entry in sorted(os.listdir(releases))- if os.path.isdir(os.path.join(releases, entry, "prime-agent-runtime"))- ]- if not candidates:- raise SystemExit("no release with prime-agent-runtime/ under " + releases)- return os.path.join(releases, candidates[-1])---def prepare_sandbox(base):- shared_cwd = os.path.join(base, "shared-cwd")- os.makedirs(shared_cwd, exist_ok=True)- script_path = os.path.join(base, "faux-script.json")- with open(script_path, "w") as f:- json.dump(FAUX_SCRIPT, f, indent=2)- sandboxes = {}- for binary in ("ts", "rust"):- home = os.path.join(base, binary, "home")- agent = os.path.join(base, binary, "agent")- tmp = os.path.join(base, binary, "tmp")- os.makedirs(home, exist_ok=True)- os.makedirs(tmp, exist_ok=True)- os.makedirs(os.path.join(agent, "extensions"), exist_ok=True)- os.makedirs(os.path.join(agent, "sessions"), exist_ok=True)- with open(os.path.join(agent, "settings.json"), "w") as f:- json.dump(SETTINGS, f)- # The isolated TMPDIR keeps the TS supervisor's socket (the- # default daemon-socket dir) off the shared box root, so the- # cleanup reap can sweep this side's daemons by path alone.- sandboxes[binary] = {"home": home, "agent": agent, "tmp": tmp}- with open(os.path.join(sandboxes["ts"]["agent"], "extensions", "compact-faux.js"), "w") as f:- f.write(TS_FAUX_EXTENSION)- return shared_cwd, script_path, sandboxes---def wait_for(session, needle, timeout):- deadline = time.time() + timeout- while time.time() < deadline:- if needle in capture_plain(session):- return- time.sleep(0.3)- raise TimeoutError(f"session {session} never showed {needle!r}")---def mode_label(session):- """The conversation-detail label in the prompt-context row- (Collapsed / Details / Expanded)."""- match = re.search(r"(Collapsed|Details|Expanded) mode \(Ctrl\+O", capture_plain(session))- return match.group(1) if match else None---def press_until_mode(session, target, max_presses=4):- """Ctrl+O until the conversation-detail label reads `target`.-- The two products' resume detail levels differ (the TS resume starts- at details, the Rust at overview), so fixed press counts desync the- compared states: drive both sides to the same label instead."""- for _ in range(max_presses):- if mode_label(session) == target:- return True- tmux("send-keys", "-t", session, "C-o")- time.sleep(1.2)- return mode_label(session) == target---# The ts-identity guard (refuse when the PATH `prime-agent` is this repo's-# Rust product) is shared with every PATH-driven parity harness: see-# scripts/battery/ts_identity.py.---def launch(binary, sandbox, shared_cwd, script_path, out_dir):- """Drive the whole compaction scenario; return the captured states."""- session = f"cpparity-{binary}-{WIDTH}x{HEIGHT}"- tmux("kill-session", "-t", session, check=False)- tmux(- "new-session",- "-d",- "-s",- session,- "-x",- WIDTH,- "-y",- HEIGHT,- "-c",- shared_cwd,- # The scrubbed client environment keeps the pane a plain shell (a- # herdr `SHELL` auto-launches a live agent in every pane); the- # explicit opt-out belt-and-braces covers a server started- # outside the harness with the wrapper still installed.- "-e",- "HERDR_PLAIN_SHELL=1",- )- env = (- f"HOME={sandbox['home']} "- f"TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"PRIME_AGENT_FAUX_SCRIPT={script_path} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- if binary == "ts":- command = (- f"prime-agent --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model faux-1"- )- else:- rust = ts_identity.default_rust_binary()- package_dir = os.environ.get("PI_PACKAGE_DIR") or find_runtime_package_dir()- command = (- f"PI_PACKAGE_DIR={package_dir} "- f"{rust} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model faux-1"- )- tmux("send-keys", "-t", session, f"{env} {command}", "Enter")-- frames = {}- wait_for(session, "mode (Ctrl+O", timeout=60)- time.sleep(1.0)- # Park both sides at Collapsed: the TS resume starts at details, the- # Rust at overview — fixed press counts desync the compared states.- if not press_until_mode(session, "Collapsed"):- raise TimeoutError(f"session {session} never reached Collapsed mode")-- # a_skip_warning: /compact on the fresh session skips (warning row).- tmux("send-keys", "-t", session, COMPACT_COMMAND.split()[0], "Enter")- wait_for(session, "too short to compact", timeout=60)- time.sleep(0.5)- frames["a_skip_warning"] = capture(session)-- # Grow the session: the first turn streams the big filler.- tmux("send-keys", "-t", session, FIRST_PROMPT, "Enter")- wait_for(session, "history history", timeout=180)- deadline = time.time() + 120- while time.time() < deadline:- pane = capture_plain(session)- if "history history" in pane and not re.search(SPINNER_CLASS, pane):- break- time.sleep(0.5)- time.sleep(1.0)- # The second turn's reply is short; wait for it to settle.- tmux("send-keys", "-t", session, SECOND_PROMPT, "Enter")- deadline = time.time() + 120- while time.time() < deadline:- pane = capture_plain(session)- if "second turn done" in pane and "second, and please keep" in pane and not re.search(SPINNER_CLASS, pane):- break- time.sleep(0.5)- time.sleep(1.0)-- # b_loader: the compaction loader while the summarizer streams (the- # collapsed pane; Ctrl+O reaches `all` only after the run settles on- # the Rust side, so this state stays the TS-parity spinner row).- tmux("send-keys", "-t", session, COMPACT_COMMAND, "Enter")- deadline = time.time() + 60- while time.time() < deadline:- if "Compacting context" in capture_plain(session):- frames["b_loader"] = capture(session)- break- time.sleep(0.05)- if "b_loader" not in frames:- raise TimeoutError(f"session {session} never showed the compaction loader")-- # c_post_compact: the summary row heading the rebuilt transcript.- wait_for(session, "Context compacted", timeout=120)- time.sleep(1.0)- for _ in range(20):- if not re.search(SPINNER_CLASS, capture_plain(session)):- break- time.sleep(0.5)- frames["c_post_compact"] = capture(session)- # The compacted-away first turn dropped from the rebuilt transcript.- pane = capture_plain(session)- if "history history" in pane:- raise AssertionError("the compacted-away filler still renders post-compaction")-- # d_expanded: the Ctrl+O detail cycle expands the compaction block- # (TS `applyChatExpansion` fans `toolOutputExpanded` into- # `CompactionSummaryMessageComponent`); drive to the Expanded label so- # both sides reach it from wherever their cycle sits.- if not press_until_mode(session, "Expanded"):- raise TimeoutError(f"session {session} never reached Expanded mode")- wait_for(session, "Compacted from", timeout=60)- time.sleep(1.0)- for _ in range(20):- if not re.search(SPINNER_CLASS, capture_plain(session)):- break- time.sleep(0.5)- frames["d_expanded"] = capture(session)- # The expanded metadata rides below the markdown summary body, and the- # block collapses again on the cycle back to Collapsed.- pane = capture_plain(session)- if "Context compacted" not in pane:- raise AssertionError("the expanded state lost the compaction header")- if not press_until_mode(session, "Collapsed"):- raise TimeoutError(f"session {session} never re-collapsed")- pane = capture_plain(session)- if "Compacted from" in pane:- raise AssertionError("the detail cycle back to Collapsed did not re-collapse the block")-- tmux("send-keys", "-t", session, "C-c")- time.sleep(0.5)- tmux("send-keys", "-t", session, "C-c")- time.sleep(1.0)- tmux("kill-session", "-t", session, check=False)-- os.makedirs(out_dir, exist_ok=True)- for state, frame in frames.items():- with open(os.path.join(out_dir, f"{binary}-{state}-{WIDTH}x{HEIGHT}.txt"), "w") as f:- f.write(frame)- return frames---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--keep", action="store_true")- parser.add_argument("--out", default=None)- parser.add_argument("--only", default=None, choices=["ts", "rust"])- args = parser.parse_args()-- base = tempfile.mkdtemp(prefix="compact-parity-")- out_dir = args.out or tempfile.mkdtemp(prefix="compact-captures-")- shared_cwd, script_path, sandboxes = prepare_sandbox(base)- failures = []- try:- if args.only in (None, "ts"):- # Fail fast before the scenario: a non-TS `prime-agent` on PATH- # produces false parity failures (see the guard's docstring).- ts_identity.assert_ts_side_is_the_ts_product()- if args.only:- launch(args.only, sandboxes[args.only], shared_cwd, script_path, out_dir)- print(f"captures for {args.only} in {out_dir}")- return 0- ts_frames = launch("ts", sandboxes["ts"], shared_cwd, script_path, out_dir)- rust_frames = launch("rust", sandboxes["rust"], shared_cwd, script_path, out_dir)- if "d_expanded" in ts_frames and "d_expanded" in rust_frames:- assert_compaction_branch(- capture_plain_text(ts_frames["d_expanded"]),- capture_plain_text(rust_frames["d_expanded"]),- )- for state, _ in STATES:- if state not in ts_frames or state not in rust_frames:- continue- ts_norm = normalize(ts_frames[state], base)- rust_norm = normalize(rust_frames[state], base)- name = f"{state}-{WIDTH}x{HEIGHT}"- if state == "d_expanded":- # The expanded block hangs on the branch grammar (the- # documented divergence): its content is compared, not- # its bytes — see `expanded_block_signature`.- ts_sig = expanded_block_signature(ts_norm)- rust_sig = expanded_block_signature(rust_norm)- if ts_sig is not None and ts_sig == rust_sig:- print(f"PASS {name}")- else:- print(f"FAIL {name}")- report = os.path.join(out_dir, f"diff-{name}.txt")- with open(report, "w") as f:- f.write(diff_words(ts_sig, rust_sig))- print(f" diff: {report}")- failures.append(name)- continue- ts_norm, rust_norm = align_frame_tops(ts_norm, rust_norm)- if ts_norm == rust_norm:- print(f"PASS {name}")- else:- print(f"FAIL {name}")- report = os.path.join(out_dir, f"diff-{name}.txt")- with open(report, "w") as f:- f.write(diff_lines(ts_norm, rust_norm))- print(f" diff: {report}")- failures.append(name)- finally:- # The private tmux server dies with the run (its sessions were- # killed individually in launch(); this only sweeps the socket).- tmux("kill-server", check=False)- # Rmtree alone leaks the scenario daemons (a killed TUI pane does- # not take its detached daemon/supervisor pair down; #223): sweep- # every daemon this run spawned before deleting the sandbox.- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if not args.keep:- shutil.rmtree(base, ignore_errors=True)- if failures:- print(f"{len(failures)} state(s) differ; captures in {out_dir}")- return 1- print(f"all states match; captures in {out_dir}")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/compaction_abort_parity.py b/scripts/compaction_abort_parity.pydeleted file mode 100644index 93a154d8a5..0000000000--- a/scripts/compaction_abort_parity.py+++ /dev/null@@ -1,322 +0,0 @@-#!/usr/bin/env python3-"""Compaction-abort wire parity verifier (TS vs Rust): abort_compaction-on an in-flight AUTOMATIC threshold compaction.--Both sides run the identical daemon flow over the shared battery mock-provider (the f14-auto battery shape: one mock-reported 126k-usage turn-crosses the 500-token reserve headroom, the summarizer request is held-open by a scripted delayMs, and `abort_compaction` cancels it mid-flight):-- 1. the `compaction_start` (threshold) broadcast,- 2. the durable `compaction_outcome` row broadcast as its- `message_start`/`message_end` pair with the `cancelled` outcome and- the `Compaction cancelled` disclosure,- 3. the `aborted` `compaction_end` (no errorMessage, no errorSeverity,- no result),- 4. the durable session-file row and the absence of a committed- compaction entry (TS `_runAutoCompaction`'s aborted arm ->- `_endCompactionUnsuccessfully`).--Volatile fields (timestamps, ids, sequences, socket paths) are normalized-away; the two sides' captures are printed side by side and the exit code-is non-zero on any shape or content diff. Evidence is written under-scripts/battery/runs/<stamp>-compaction-abort/<side>/.-"""--import json-import os-import sys-import time-from pathlib import Path--sys.path.insert(0, str(Path(__file__).resolve().parent / "battery"))-import batterylib as B # noqa: E402-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--REPO = Path(__file__).resolve().parents[1]--# The volatile fields stripped from wire events and durable rows before-# the diff (per-run identity, ordering metadata, timing).-VOLATILE = ("timestamp", "id", "parentId", "sessionId", "activeSessionId",- "sequence", "meta", "generation", "createdAt", "updatedAt")--SUMMARIZER_MARKER = "context summarization assistant"--SEED_REPLY = "abort parity seed reply"-CROSSING_REPLY = "abort parity crossing reply"-# The held summarizer: delayMs keeps the request open long enough for the-# abort to land mid-flight on both sides (the dropped request kills the-# mock connection; the mock thread exits on its failed write).-HELD_SUMMARY = {"text": "the aborted parity summary", "delayMs": 25000}--CROSSING_USAGE = {- "prompt_tokens": 126000,- "completion_tokens": 10,- "total_tokens": 126010,- "prompt_tokens_details": {"cached_tokens": 80},-}---def normalize(value):- """Recursively drop volatile keys and scrub volatile strings."""- if isinstance(value, dict):- return {- k: normalize(v)- for k, v in value.items()- if k not in VOLATILE- }- if isinstance(value, list):- return [normalize(v) for v in value]- if isinstance(value, str):- # Session ids and ports leak into strings only through fields that- # are already dropped; nothing else in the capture is volatile.- return value- return value---def relevant_event(event: dict) -> dict | None:- """The compaction-related session events, normalized."""- if event.get("type") == "compaction_start":- return normalize(event)- if event.get("type") == "compaction_end":- return normalize(event)- if event.get("type") in ("message_start", "message_end"):- message = event.get("message", {})- if message.get("customType") == "compaction_outcome":- return {"type": event["type"], "message": normalize(message)}- return None---def durable_rows(side: B.Side) -> dict:- """The compaction rows in the side's durable session file."""- for path in side.session_files():- text = path.read_text(errors="replace")- if "compaction_outcome" not in text and '"compaction"' not in text:- continue- rows = []- compaction_entries = 0- for line in text.splitlines():- line = line.strip()- if not line:- continue- try:- entry = json.loads(line)- except json.JSONDecodeError:- continue- if entry.get("type") == "custom_message" and entry.get("customType") == "compaction_outcome":- rows.append(normalize(entry))- if entry.get("type") == "compaction":- compaction_entries += 1- if rows or compaction_entries:- return {"outcome_rows": rows, "compaction_entries": compaction_entries}- return {"outcome_rows": [], "compaction_entries": 0}---def read_response_for(wire: B.Wire, command_id: str, timeout: float = 120.0) -> dict:- """Read lines until the response for `command_id` (command already sent)."""- deadline = time.time() + timeout- while True:- remaining = deadline - time.time()- if remaining <= 0:- raise TimeoutError(f"no response for command {command_id}")- line = wire.read_line(timeout=remaining)- if line.get("id") == command_id:- return line- wire.events.append(line)---def run_side(name: str, binary: str, root: Path) -> dict:- """Run the abort flow on one side; returns the normalized capture."""- root.mkdir(parents=True, exist_ok=True)- agent = root / "agent"- work = root / "work"- work.mkdir(parents=True, exist_ok=True)- if agent.exists():- import shutil- shutil.rmtree(agent)- agent.mkdir(parents=True)- mock = B.MockProvider(root, [])- # The mock process reads the script file at startup (the battery's- # make_side order): write one response before starting.- mock.set_responses([{"text": SEED_REPLY}])- mock.start()- tmpdir = Path("/tmp") / f"compaction-abort-{name}-{os.getpid()}"- if tmpdir.exists():- import shutil- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- side = B.Side(- name=name,- binary=binary,- root=root,- agent_dir=agent,- work_dir=work,- daemon_socket=root / "daemon.sock",- mock=mock,- )- side.env = B.scrubbed_env(agent, tmpdir)- if name == "rust":- side.env["PI_PACKAGE_DIR"] = str(REPO)- side.env["PRIME_API_KEY"] = "sk-battery"- side.write_models_json()- # The f14-auto battery settings shape: the mock-reported 126k usage- # crosses on both products (TS at window - reserve = 123904, Rust at- # the combined input+output ceiling 128000 - 4096 - 4096 = 119808),- # and a tiny keep-recent budget keeps the seeded turns summarizable.- (agent / "settings.json").write_text(json.dumps(- {"compaction": {"enabled": True, "reserveTokens": 4096, "keepRecentTokens": 10}}- ))- capture: dict = {}- try:- side.start_daemon()- wire = B.Wire(side.daemon_socket)- created = wire.request(- "c1",- {- "type": "create",- "name": f"compaction-abort-{name}",- "config": {- "cwd": str(side.work_dir),- "sessionDir": str(side.agent_dir / "sessions"),- "provider": "prime-inference",- "model": "mock-1",- "executionMode": "print",- },- },- timeout=120,- )- if created.get("success") is not True:- raise RuntimeError(f"create failed: {json.dumps(created)[:400]}")- session_id = (created.get("data", {}).get("activeSessionId")- or created.get("data", {}).get("id") or "")-- # Attach the wire so the session's broadcast events flow to this- # connection (the daemon only broadcasts to attached clients).- attached = wire.request(- "a1",- {"type": "attach", "activeSessionId": session_id},- timeout=120,- )- if attached.get("success") is not True:- raise RuntimeError(f"attach failed: {json.dumps(attached)[:400]}")-- # Seed turn (small usage): the threshold stays silent.- mock.set_responses([- {"text": SEED_REPLY},- {"text": CROSSING_REPLY, "usage": CROSSING_USAGE},- dict(HELD_SUMMARY),- ])- seeded = wire.request(- "p1",- {"type": "prompt_and_wait", "activeSessionId": session_id,- "message": "abort parity seed turn"},- timeout=240,- )- if seeded.get("success") is not True:- raise RuntimeError(f"seed prompt failed: {json.dumps(seeded)[:400]}")-- # The crossing turn fires the threshold compaction; its summarizer- # request is held open by the scripted delay.- seed_requests = len(mock.requests())- wire.send_command(- "p2",- {"type": "prompt_and_wait", "activeSessionId": session_id,- "message": "abort parity crossing turn"},- )- deadline = time.time() + 30- while time.time() < deadline:- new_requests = mock.requests()[seed_requests:]- if any(- SUMMARIZER_MARKER in json.dumps(body)- for body in new_requests- ):- break- time.sleep(0.2)- else:- raise RuntimeError(f"{name}: the compaction summarizer request never arrived")-- # Abort the in-flight compaction over the daemon wire (a second- # connection, exactly like the TUI interrupt key's fire-and-forget- # abort_compaction).- abort_wire = B.Wire(side.daemon_socket)- aborted = abort_wire.request(- "ab1",- {"type": "abort_compaction", "activeSessionId": session_id},- timeout=120,- )- capture["abort_response"] = {- "success": aborted.get("success"),- "command": aborted.get("command"),- "has_data": "data" in aborted,- }-- # The turn completes after the cancelled compaction.- crossed = read_response_for(wire, "p2", timeout=120)- capture["prompt_response"] = {"success": crossed.get("success")}- wire.drain(3.0)- abort_wire.drain(1.0)-- # wire.events holds full frames; extract the event payloads.- events = []- for frame in wire.events + abort_wire.events:- if frame.get("type") == "session_event":- kept = relevant_event(frame.get("event", {}))- if kept is not None:- events.append(kept)- capture["events"] = events- capture["durable"] = durable_rows(side)- finally:- side.stop_daemon()- mock.stop()- import shutil- if tmpdir.exists():- shutil.rmtree(tmpdir, ignore_errors=True)- # Evidence for the run.- evidence = root / "capture.json"- evidence.write_text(json.dumps(capture, indent=1))- return capture---def main() -> int:- ts_binary = os.environ.get("PA_PARITY_TS", "prime-agent")- rust_binary = os.environ.get(- "PA_PARITY_RUST", str(REPO / "target" / "release" / "prime-agent")- )- # The run root must keep the daemon-socket path under the 107-char- # AF_UNIX limit (the battery's own stamp run dirs fit with one side- # directory of margin): a short `-abort` suffix, no more.- # Fail fast before any launch: a non-TS `prime-agent` on PATH plays a- # Rust build as the "ts" side and reports false divergences.- ts_identity.assert_ts_side_is_the_ts_product(ts_binary, rust_binary)- # Fail fast on a stale rust build: a binary older than the checkout's- # newest product commit reproduces "summarizer request never arrived"- # class false failures (the 20260920 main run: the checkout's binary- # predated the auto-compaction merge).- stale = B.rust_binary_staleness(Path(rust_binary), REPO)- if stale:- print(f"[parity] STALE RUST BINARY: {stale}")- return 2- stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())- run_root = REPO / "scripts" / "battery" / "runs" / f"{stamp}-abort"- print(f"[parity] run root: {run_root}")- ts = run_side("ts", ts_binary, run_root / "ts")- print(f"[parity] ts capture: {json.dumps(ts)[:200]}...")- rust = run_side("rust", rust_binary, run_root / "rust")- print(f"[parity] rust capture: {json.dumps(rust)[:200]}...")-- ok = True- if ts != rust:- ok = False- print("[parity] DIFF: the two sides' captures differ")- for key in sorted(set(ts) | set(rust)):- if ts.get(key) != rust.get(key):- print(f"--- {key} ts ----\n{json.dumps(ts.get(key), indent=1)}")- print(f"--- {key} rust ----\n{json.dumps(rust.get(key), indent=1)}")- else:- print("[parity] OK: TS and Rust captures are identical after normalization")- print(f"[parity] exit {'0' if ok else '1'}")- return 0 if ok else 1---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/custom_message_parity.py b/scripts/custom_message_parity.pydeleted file mode 100755index 6988a66852..0000000000--- a/scripts/custom_message_parity.py+++ /dev/null@@ -1,1144 +0,0 @@-#!/usr/bin/env python3-"""Custom-message decoration parity verifier: frame-diff the Rust TUI-against the installed TS prime-agent binary rendering the SAME session-transcript containing every decorated custom-message row:-- - a received agent message (icon + label + participant + body),- - an ipython cell that sent an agent message (the sent receipt rows- render below the code, body in the expanded view),- - a heartbeat prompt (pulse + schedule),- - a goal-context continuation row,- - a restored-python-kernel row,- - the three RLM child rows (a finished terminal notice, a failed child,- a cancelled terminal notice),- - a background-shell completion,- - a compaction outcome,- - a refinement outcome,- - an autonomous-status row (the generic custom box),- - a skill invocation user message (the persisted `<skill>` block a- user-typed `/skill:<name> [args]` expands into: the compact- expandable `[skill]` card collapsed, the markdown body expanded, the- args as their own user block, never the raw block text).--The session JSONL is assembled from real captured rows and resumed in the-TS binary (`prime-agent -r <path>`) and replayed in the Rust TUI-(`pa-tui-replay <path>`), both live in tmux at 120x90 (tall enough that-the expanded transcript stays in the viewport for the reach checks). States: the idle-transcript (collapsed) and the expanded view (Ctrl+O twice, where the-agent-message bodies and shell-completion output open up). Frames are-normalized for volatile content and diffed; the exit code is non-zero when-any state differs.--One documented divergence (operator directive 2026-09-25): the-agent-message rows render the viewer-relative notice on the Rust side —-the shared `Agent message` label, the ↑/↓ arrow from the row's-actual direction (↓ received, ↑ sent/queued), and the-counterpart agent's name only, with no collapsed body preview — where the-TS frames render the direction word plus the `from/to <role> <name>`-participant. The collapsed body preview the Rust side used to render (the-Kevin directive 2026-09-21 divergence) is gone with it, so its strip and-assert are retired. The diff canonicalizes the whole summary composition-to one marker per frame and the run separately asserts each side's exact-row; the TS side is expected to adopt the same shape so the-canonicalization can be dropped.--Second documented divergence (Kevin directive 2026-09-23, product-improvement BEYOND TS): the RLM child rows render the-`\u25c6 Subagent <name> finished|failed|cancelled` diamond rows on the Rust-side (the diamond marker carries the row's semantic color — the same style-the label renders in, success green / error red / cancelled yellow, per the-same directive's icon-follows-text rule — plus the failure error and the-cancellation reason as the expandable body, no reply-preview anywhere),-where the TS binary still shows the generic muted `RLM child status` label-over the full content markdown. The diff drops the RLM child rows from-BOTH frames and the run separately asserts the Rust diamond rows ARE-present (collapsed labels, expanded reason bodies, no preview, and the-diamond sharing the label's exact SGR color run per outcome) and the TS-frames show the old generic label (the baseline the TS team is expected to-adopt).--Third documented divergence (operator directive 2026-09-23): the heartbeat-prompt row renders the `\u25f7` clock glyph — the unified activity dock's-Heartbeats group icon — on the Rust side, where the TS binary still-renders the `\u2665` heart. The diff canonicalizes the row's glyph on both-frames (the label and schedule still diff) and the run separately asserts-each side's glyph (Rust clock, TS heart baseline).--Fourth documented divergence (Kevin directive 2026-09-24): the-agent-message rows render the `\u2709` mail envelope as the row icon — the-a2a rows read as agent mail — on the Rust side (the received transcript-rows and the ipython sent/queued receipt rows share the one summary-line), where the TS binary still renders the `\u25c6` diamond. The diff-canonicalizes the row's glyph on both frames (the label and participant-still diff; the glyph sits in its own accent SGR run, so the-canonicalization spans the escapes between the glyph and the label) and-the run separately asserts each side's glyph (Rust envelope, TS diamond-baseline).---Fifth documented divergence (Kevin/Sebastian directive 2026-09-23, product-improvement BEYOND TS): the expanded refinement outcome hangs on the-branch grammar — the expanded content carries the dim `╰─ `-gutter on the first row hanging off the `◆` header and a-four-space continuation indent after, instead of the TS-`ExpandableEventMessage`'s plain one-column chat inset (the same grammar-the expanded ipython cells and the agent-message bodies use). The diff-drops the refinement row's expanded rows from BOTH frames (the collapsed-row keeps byte-parity), but the dropped rows do not leave the comparison:-their visible content must match word for word (whitespace collapsed, the-gutter glyphs dropped — the intended divergence is the indentation and-the wrap points it forces, never the Title/Description/section values-themselves). The run separately asserts the Rust expanded rows carry the-branch and the TS frames keep the plain-inset baseline (the shape the TS-team is expected to adopt).--tmux rules: default socket only (`env -u TMUX`), cmparity-* session names,-no kill-server; sessions are killed individually at the end.-"""--import argparse-import difflib-import glob-import json-import os-import re-import shutil-import subprocess-import sys-import tempfile-import time--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--SIZES = [("120", "90")]--# The transcript skeleton (entries copied from real captured sessions so-# both binaries parse byte-identical payloads). Timestamps are re-stamped-# sequentially; the parent chain is linear.-# (custom_type, content, extra fields): the content lives per row so the-# two terminal-notice shapes (finished, cancelled) and the failure row all-# carry their own wire content.-CUSTOM_ROWS = [- ("agent_message",- "[agent-message from child:model-probe]\n\nDecorations parity: the received row renders with the diamond, label, and participant.",- {"display": True, "details": {- "id": "agentmsg_cmparity",- "message": "Decorations parity: the received row renders with the diamond, label, and participant.",- "from": {"sessionName": "model-probe", "sessionId": "sess-probe", "activeSessionId": "aaa111", "runtimeKind": "subagent"},- "fromRelationship": "child",- }}),- ("heartbeat_prompt", "[heartbeat: every 10m run#3]\n\nContinue the mission.", {"display": True, "details": {- "jobId": "job-1", "schedule": "every 10m", "status": "running", "runCount": 3,- }}),- ("goal_context", "[goal: continuation]\n\nContinue the goal.", {"display": True, "details": {- "kind": "continuation", "goalId": "goal-1",- "objective": "Keep the parity harnesses green.",- "status": "active", "continuationsUsed": 1,- }}),- ("ipython_state_restored", "[python-state-restored]\n\nKernel state revived.", {"display": True, "details": {"restored": True}}),- # The three RLM child rows (the product-improvement divergence): a- # finished child (the reply preview stays out of the row), a failed- # child, a cancelled child. The reasons double as the strip needles.- ("rlm_child_terminal_notice",- "[child-exited: no-reply child:lane-decorations]\n\nLast assistant text: the legacy preview that must not render",- {"display": True, "details": {- "kind": "completed_without_reply", "childId": "sub-1", "sessionName": "lane-decorations",- "lastAssistantTextPreview": "the legacy preview that must not render",- }}),- ("rlm_child_failure",- "[child-failed child:boom-worker]\n\nthe model stream died",- {"display": True, "details": {- "childId": "sub-2", "sessionName": "boom-worker", "error": "the model stream died",- }}),- ("rlm_child_terminal_notice",- "[child-exited: cancelled child:cancel-worker]\n\nDeleted by parent orchestrator",- {"display": True, "details": {- "kind": "cancelled", "childId": "sub-3", "sessionName": "cancel-worker",- "reason": "Deleted by parent orchestrator",- }}),- ("async_bash_completion", "[bash-done pid:4371 exit:0]\n\nCommand: \"seq 1 3\"", {"display": True, "details": {"pid": 4371, "command": "seq 1 3", "exitCode": 0}}),- ("compaction_outcome", "Compaction skipped: below the token threshold.", {"display": True, "details": {"reason": "threshold", "outcome": "skipped"}}),- ("refinement_outcome", "Refinement complete: Create one local memory.", {"display": True, "details": {- "refinementId": "refine_cmparity", "summary": "Create one local memory.", "scope": "local",- "edits": [{- "action": "create", "kind": "memory", "id": "cmparity-memory", "applied": True,- "title": "Parity memory", "content": "The harness stays green.",- "after": {"id": "cmparity-memory", "kind": "memory", "title": "Parity memory",- "content": "The harness stays green.", "scope": "local"},- }],- }}),- ("autonomous_status", "[autonomous-status: off]\n\nContinuations: 0/0. Turns: 0/0.", {"display": True, "details": {"enabled": False}}),-]--MARKER_TEXT = "decorations parity transcript complete"--# The persisted shape of a user-typed `/skill:web-search find rust tuis`-# submission (TS `_expandSkillCommand` output): the card renders the name-# collapsed and the content expanded; the args render as their own user-# block below it.-SKILL_BLOCK_MESSAGE = (- "<skill name=\"web-search\" location=\"/skills/web-search/SKILL.md\">\n"- "References are relative to /skills/web-search.\n\n"- "Run one web search and report the titles.\n"- "</skill>\n\n"- "find rust tuis"-)-SKILL_CARD_SUMMARY = "[skill] web-search"-SKILL_CARD_BODY = "Run one web search and report the titles."-SKILL_ARGS = "find rust tuis"---def newest_assistant_message(sessions):- """A real assistant message envelope (api/provider/usage fields) so the- synthetic replies deserialize in BOTH loaders: the Rust loader degrades- a malformed message to an unknown entry that renders nothing, which- would silently drop the rows the verifier waits for. The SMALLEST- captured envelope wins: replaying a large one ballooned the TS daemon- to ~12GB RSS on this fixture. The provider/model fields are rewritten- to a model the TS daemon can restore, so the resumed session does not- render a model-restore warning the Rust replay would not show."""- best = None- for path in reversed(sessions):- with open(path, encoding="utf-8") as f:- for line in f:- try:- row = json.loads(line)- except ValueError:- continue- message = row.get("message") if row.get("type") == "message" else None- if (- isinstance(message, dict)- and message.get("role") == "assistant"- and isinstance(message.get("content"), list)- and any(- isinstance(block, dict) and block.get("type") == "text"- and len(block.get("text", "")) < 200- for block in message["content"]- )- and (best is None or len(line) < best[0])- ):- best = (len(line), message)- if best is None:- raise SystemExit("no assistant message found in captured sessions")- return json.loads(json.dumps(best[1]))---def session_paths():- return sorted(- glob.glob(os.path.expanduser("~/.prime/agent/sessions/**/*.jsonl"), recursive=True),- key=os.path.getmtime,- )---def assistant_with(template, text, ms):- """Clone the captured assistant envelope around one text block. The- provider/model point at the model the TS daemon restores by default, so- the resume never renders a model-restore warning."""- message = json.loads(json.dumps(template))- message["content"] = [{"type": "text", "text": text}]- message["provider"] = "prime-inference"- message["model"] = "z-ai/glm-5.3"- message["timestamp"] = ms- return message---def build_session(path, source_header, assistant_template, cwd):- """Assemble the parity session: one user turn, one assistant reply,- then every custom row, then a closing assistant reply. The header cwd- must match the sandbox cwd: the TS resume rejects sessions that belong- to a different project."""- # A synthetic root-session header: the TS resume follows a cloned real- # session id (and its parentSession chain) into the live multi-GB- # sessions on this box, which ballooned the resume client to ~12GB- # RSS and wedged the render. Only the wire shape is preserved.- header = {- "type": "session",- "version": source_header.get("version", 3),- "id": "cmparity-session",- "cwd": cwd,- "timestamp": source_header.get("timestamp", "2026-09-18T00:00:00.000Z"),- }- entries = [header]- base_ms = 1_700_000_000_000- def entry(type_, fields, ms):- row = {"type": type_}- row.update(fields)- # Unique sequential ids: the TS resume follows the parentId chain,- # and a self-referential id (an earlier bug produced `e0000` for- # every row) made the TS loader loop until the process ballooned- # to ~12GB RSS.- row["id"] = f"e{ms - 1_700_000_000_000:04d}"- row["parentId"] = entries[-1]["id"]- row["timestamp"] = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(ms / 1000))- return row- entries.append(entry("message", {- "message": {"role": "user", "content": "Run the decoration checks.", "timestamp": base_ms},- }, base_ms))- base_ms += 1- entries.append(entry("message", {- "message": assistant_with(- assistant_template, "Rows below cover every decorated custom message.", base_ms- ),- }, base_ms))- # One ipython turn that sent an agent message: the sent receipt rows- # (summary always, body expanded) render inside the tool card on both- # sides (TS `renderSentAgentMessages`).- base_ms += 1- sender = assistant_with(assistant_template, "", base_ms)- sender["content"] = [- {"type": "text", "text": "Sending one receipt now."},- {- "type": "toolCall",- "name": "ipython",- "id": "toolu_sent01",- "arguments": {"code": "await agent_message.send(\"Ping.\", receiver_role=\"parent\")"},- },- ]- sender["stopReason"] = "toolUse"- entries.append(entry("message", {"message": sender}, base_ms))- base_ms += 1- entries.append(entry("message", {- "message": {- "role": "toolResult",- "toolCallId": "toolu_sent01",- "toolName": "ipython",- "content": [{"type": "text", "text": ""}],- "details": {- "status": "ok",- "durationMs": 3,- "sentAgentMessages": [- {- "id": "agentmsg_sent01",- "message": "Ping.\nThen report back.",- "deliveryStatus": "delivered",- "receiverRole": "parent",- "target": {- "activeSessionId": "worker-active",- "sessionId": "worker-session",- "sessionName": "Worker",- },- }- ],- },- "isError": False,- "timestamp": base_ms,- },- }, base_ms))- for custom_type, content, extra in CUSTOM_ROWS:- base_ms += 1- fields = {"customType": custom_type, "content": content}- fields.update(extra)- entries.append(entry("custom_message", fields, base_ms))- base_ms += 1- entries.append(entry("message", {- "message": {"role": "user", "content": SKILL_BLOCK_MESSAGE, "timestamp": base_ms},- }, base_ms))- base_ms += 1- entries.append(entry("message", {- "message": assistant_with(assistant_template, MARKER_TEXT, base_ms),- }, base_ms))- with open(path, "w") as f:- for row in entries:- f.write(json.dumps(row) + "\n")- return path---def newest_session_header():- """A real session header (current on-disk format) for the synthetic file."""- sessions = session_paths()- for path in reversed(sessions):- with open(path, encoding="utf-8") as f:- first = f.readline()- try:- header = json.loads(first)- except ValueError:- continue- if header.get("type") == "session":- return header- raise SystemExit("no captured session header found under ~/.prime/agent/sessions")---def tmux(*args, check=True):- result = subprocess.run(["env", "-u", "TMUX", "tmux", *args], capture_output=True, text=True)- if check and result.returncode != 0:- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")- return result.stdout---def capture(session):- return tmux("capture-pane", "-e", "-p", "-t", session)---def capture_plain(session):- return tmux("capture-pane", "-p", "-t", session)---def normalize(frame, root):- frame = frame.replace(root, "<SANDBOX>")- # Pre-existing replay-binary chrome gap (reproduced on origin/main with- # the box debug binary): the TS resume splash prints its version, the- # restored model, and the session cwd on the art rows; the Rust replay- # splash prints `prime agent v` (build-provided version, empty in- # sandbox builds) and no model/cwd echo, so the splash cannot match- # row-for-row. The whole splash block (art + label rows) drops from- # BOTH frames; the diff covers the transcript, which is what this- # harness owns.- def chrome_row(line):- plain = re.sub(r"\x1b\[[0-9;]*m", "", line)- # The splash ASCII art rows carry the labels, so the whole splash- # block (any block-element glyph row, plus the label rows) drops- # from both frames.- return (- "prime agent" in plain- or "cwd" in plain- or plain.strip().startswith("model ")- or re.search("[\u2580-\u259f]", plain) is not None- )- frame = re.sub(r"v\d+\.\d+\.\d+", "vX.X.X", frame)- frame = re.sub(r"\b[0-9a-f]{12}\b", "<SID>", frame)- frame = re.sub(r"\b\d+(\.\d+)?(ms|s)\b", "<T>", frame)- frame = re.sub(r"\d+(\.\d+)?[kM]? \(\d+%\)", "<TOK> (<PCT>)", frame)- frame = re.sub(r"[\u2193\u2191] [\d.kM]+ tokens", "<DIR> <TOK> tokens", frame)- spinners = "".join("\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f")- frame = re.sub("[" + spinners + "]", "<SPIN>", frame)- # Third carried divergence (see the module docstring): the heartbeat- # prompt row's glyph — Rust renders the ◷ clock, TS the ♥ heart. The- # glyph and its label live in separate styled spans, so the frames- # compare ANSI-ful: canonicalize the single chars to one marker (no- # other row carries either glyph in this fixture) so the row's label- # and schedule still diff; the run separately asserts each side's- # glyph.- frame = frame.replace("\u2665", "<HBICON>")- frame = frame.replace("\u25f7", "<HBICON>")- # Fourth carried divergence (see the module docstring): the- # agent-message rows' icon — Rust renders the ✉ mail envelope, TS the- # ◆ diamond. The diamond ALSO fronts the refinement header row (and- # the dropped RLM child rows), so the canonicalization is scoped to- # the agent-message compositions: the glyph followed by its SGR runs- # and the margin space up to the row label (received/sent/queued all- # start `Agent message`). The run separately asserts each side's- # glyph.- frame = re.sub(- "[\u25c6\u2709]((?:\x1b\[[0-9;]*m| )*)Agent message",- r"<AMICON>\1Agent message",- frame,- )- # The label/participant composition (see the module docstring, the- # operator's 2026-09-25 directive): Rust renders the shared- # `Agent message` label with the viewer-relative arrow plus the- # counterpart name only (↓ received, ↑ sent/queued), TS the direction- # word plus the `from/to <role> <name>` participant. The summary row- # is its own line, so the whole composition canonicalizes to one- # marker per frame; the run separately asserts each side's exact row.- frame = re.sub(r"<AMICON>[^\n]*", "<AMICON><AMROW>", frame)- # The TS product's ripgrep notice (a startup environment notice when- # rg is missing under PI_OFFLINE; the Rust build has no equivalent- # row yet) is box environment, not transcript parity.- kept = []- notice = False- for line in frame.split("\n"):- if any(- needle in line- for needle in (- "ripgrep (rg) is an optional search helper",- "Install it with: brew install ripgrep",- "Automatic installation was skipped because PI_OFFLINE",- "and subagents remain available.",- )- ):- # The notice's trailing blank row drops with it (the block- # is notice + one blank on the TS side).- notice = True- continue- if notice and line.strip() == "":- notice = False- continue- notice = False- kept.append(line)- frame = "\n".join(kept)- pulses = "".join("\u25f4\u25f7\u25f6\u25f5\u25cb\u25f8\u25fb\u25fc")- frame = re.sub("[" + pulses + "]", "<PULSE>", frame)- frame = re.sub("\x1b\[39m\n", "\n", frame)- frame = re.sub("\n\x1b\[39m(?= )", "\n", frame)- frame = re.sub("\x1b\[49m\n", "\n", frame)- frame = re.sub("\n\x1b\[49m(?= )", "\n", frame)- frame = re.sub(- r" +((?:\x1b\[[0-9;]*m)*(?:faux-1 \u00b7 )?<TOK> \(<PCT>\)\s*)$",- r" <TRAY-RIGHT>\1",- frame,- flags=re.MULTILINE,- )- # The Rust replay harness renders the transcript without the TS- # client chrome: the top info bar (`cwd ... $0.00`) and the bottom nav- # bar (`← manage ...`). Drop those rows and trim the viewport blank- # rows at the frame edges so the diff covers the transcript only.- kept = []- for line in frame.split("\n"):- if "cwd" in line and "$0.00" in line:- continue- # The nav arrow and the manage label are separated by ANSI color- # codes in the capture, so match them independently.- if "←" in line and "manage" in line:- continue- if chrome_row(line):- continue- kept.append(line)- while kept and not kept[0].strip():- kept.pop(0)- while kept and not kept[-1].strip():- kept.pop()- return "\n".join(kept)---def capture_plain_text(frame):- """Strip ANSI codes so content assertions match the visible text."""- return re.sub(r"\x1b\[[0-9;]*[A-Za-z]", "", frame)---# The fixture agent-message body (the expandable body of the received-# row; the collapsed row carries no preview since the 2026-09-25-# directive — see the module docstring).-AGENT_MESSAGE_BODY = (- "Decorations parity: the received row renders with the diamond, "- "label, and participant."-)--# The RLM child rows (the second carried divergence, see the module-# docstring): the Rust diamond rows replace the TS generic label.-RLM_CHILD_LABELS = [- ("lane-decorations", "finished"),- ("boom-worker", "failed"),- ("cancel-worker", "cancelled"),-]-RLM_CHILD_REASONS = ["the model stream died", "Deleted by parent orchestrator"]-RLM_CHILD_NEEDLES = (- ["RLM child status", "Last assistant text", "[child-failed", "[child-exited"]- + RLM_CHILD_REASONS- + [f"Subagent {name} {outcome}" for name, outcome in RLM_CHILD_LABELS]-)---def strip_rlm_child_rows(frame):- """Drop the RLM child row lines from BOTH frames: the Rust side renders- the diamond rows (the headers plus the reason bodies expanded), the TS- side renders the generic label and the full content markdown. The- harness separately asserts each side's shapes.-- The row-count divergence also shifts the bottom-anchored viewport: the- Rust window covers more of the splash region above the transcript than- the TS one, so background-color escapes land on different rows around- the first transcript row and extra visually-blank splash spacers leak- into the normalized frame. Both are anchor artifacts, not render- regressions, so background escapes drop and blank runs collapse to one- row (visually blank = whitespace once the ANSI codes are stripped)."""- def visually_blank(line):- return re.sub(r"\x1b\[[0-9;]*m", "", line).strip() == ""-- kept = []- blank = False- for line in frame.split("\n"):- plain = re.sub(r"\x1b\[[0-9;]*m", "", line)- if any(needle in plain for needle in RLM_CHILD_NEEDLES):- continue- # Anchor artifact: background escapes whose placement shifts- # across the row boundary when the window anchors differently.- line = re.sub(r"\x1b\[4[0-9;]*m", "", line)- if not visually_blank(line):- kept.append(line)- blank = False- continue- # Both sides render different row counts here (the Rust rows are- # one line plus the reason body, the TS side the full content- # markdown), so blank runs collapse to one blank row before the- # diff; the dedicated assertions below own the row shapes.- if not blank:- kept.append(line)- blank = True- # The window-anchor shift shows as extra visually-blank spacers at- # the frame edges; drop them (normalize's own edge trim only sees- # ASCII whitespace, not ANSI-only rows).- while kept and visually_blank(kept[0]):- kept.pop(0)- while kept and visually_blank(kept[-1]):- kept.pop()- # Keep a trailing newline: normalize's line-boundary escape rules- # (the `\x1b[39m\n` / `\x1b[49m\n` cleanups) must see the same frame- # shape on both sides even when the trailing blank rows popped here- # made the last content row the frame's final line.- return "\n".join(kept) + ("\n" if kept else "")---def assert_heartbeat_row(side, collapsed, expanded):- """The heartbeat prompt row contract per side: the Rust frames show the- ◷ clock glyph (the unified activity dock's Heartbeats icon, the- operator-directed 2026-09-23 divergence); the TS frames show the ♥- heart (the baseline the improvement diverges from)."""- row = " Heartbeat prompt \u00b7 every 10m"- if side == "rust":- assert "\u25f7" + row in collapsed, "rust: clock heartbeat row missing collapsed"- assert "\u25f7" + row in expanded, "rust: clock heartbeat row missing expanded"- assert "\u2665" not in collapsed, "rust: heart glyph rendered"- assert "\u2665" not in expanded, "rust: heart glyph rendered expanded"- else:- assert "\u2665" + row in collapsed, "ts: heart row missing (baseline)"- assert "\u2665" + row in expanded, "ts: heart row missing expanded (baseline)"- assert "\u25f7" + row not in collapsed, "ts: clock glyph rendered"- assert "\u25f7" + row not in expanded, "ts: clock glyph rendered expanded"---def assert_agent_message_rows(side, collapsed, expanded):- """The agent-message row contract per side. Icon divergence (the- Kevin-directed 2026-09-24 directive): the Rust frames render the- \u2709 mail envelope on every agent-message row (the received- transcript row and the sent receipt row); the TS frames render the- \u25c6 diamond (the baseline the divergence moves away from). The- \u25c6 stays correct on the OTHER diamond rows (the refinement- header renders on both sides). Label/participant divergence (the- operator's 2026-09-25 directive): the Rust rows render the shared- `Agent message` label with the viewer-relative arrow plus the- counterpart agent's name only (\u2193 received, \u2191 sent/queued);- the TS rows keep the direction word plus the `from/to <role> <name>`- participant, and the collapsed Rust row carries no body preview."""- if side == "rust":- received = "Agent message \u00b7 \u2193 model-probe"- sent = "Agent message \u00b7 \u2191 Worker"- assert "\u2709 " + received in collapsed, (- "rust: envelope received row missing collapsed"- )- assert "\u2709 " + sent in collapsed, "rust: envelope sent row missing collapsed"- assert "\u25c6 " + received not in collapsed, "rust: diamond received row rendered"- assert "\u25c6 " + sent not in collapsed, "rust: diamond sent row rendered"- else:- received = "Agent message received \u00b7 from child model-probe"- sent = "Agent message sent \u00b7 to parent Worker"- assert "\u25c6 " + received in collapsed, "ts: diamond received row missing (baseline)"- assert "\u25c6 " + sent in collapsed, "ts: diamond sent row missing (baseline)"- assert "\u2709 " not in collapsed, "ts: envelope glyph rendered"- assert "\u2709 " not in expanded, "ts: envelope glyph rendered expanded"---def assert_rlm_child_rows(side, collapsed, expanded):- """The RLM child row contract per side: the Rust frames show the three- diamond rows (collapsed labels, reason bodies expanded, no reply- preview anywhere); the TS frames show the old generic label (the- baseline the improvement diverges from)."""- if side == "rust":- for name, outcome in RLM_CHILD_LABELS:- label = f"\u25c6 Subagent {name} {outcome}"- assert label in collapsed, f"rust: {label!r} missing collapsed"- assert label in expanded, f"rust: {label!r} missing expanded"- for reason in RLM_CHILD_REASONS:- assert reason not in collapsed, f"rust: reason body visible collapsed: {reason!r}"- assert reason in expanded, f"rust: reason body missing expanded: {reason!r}"- assert "Last assistant text" not in collapsed, "rust: reply preview rendered"- assert "Last assistant text" not in expanded, "rust: reply preview rendered expanded"- assert "RLM child status" not in collapsed, "rust: old generic label rendered"- else:- assert "RLM child status" in collapsed, "ts: generic label missing (baseline)"- assert "RLM child status" in expanded, "ts: generic label missing expanded (baseline)"- for name, _outcome in RLM_CHILD_LABELS:- assert f"Subagent {name}" not in collapsed, "ts: diamond row rendered"----def _sgr_fg_color(run):- """The foreground color parameter inside one SGR run (truecolor- `38;2;r;g;b` or 256-color `38;5;N`), None when the run sets no fg."""- found = re.search(r"38;2;\d+;\d+;\d+|38;5;\d+", run or "")- return found.group(0) if found else None---def _row_header_runs(frame, label):- """The SGR runs directly before the diamond marker and the label text- of one rendered `◆ <label>` header row (the escape-bearing frame):- (icon_run, label_run) or None when the row never renders."""- for line in frame.split("\n"):- plain = re.sub(r"\x1b\[[0-9;]*m", "", line)- if f"\u25c6 {label}" in plain:- icon = re.search(r"((?:\x1b\[[0-9;]*m)+)\u25c6", line)- text = re.search(r"((?:\x1b\[[0-9;]*m)+)" + re.escape(label), line)- if icon and text:- return icon.group(1), text.group(1)- return None---def assert_rlm_child_icon_colors(frames):- """The icon-follows-text color contract for the Rust RLM child rows- (Kevin directive 2026-09-23, same directive as the row divergence):- the diamond marker renders in the row's semantic color — the exact fg- run the label uses — so the icon no longer stays on the fixed accent.- The kernel-restored row in the same fixture keeps its accent diamond- (TS parity), which doubles as the accent baseline the three semantic- colors must differ from."""- for state in ("a_collapsed", "b_expanded"):- frame = frames[state]- kernel = _row_header_runs(frame, "Restored Python kernel state")- assert kernel, f"rust: kernel-restored header missing in {state}"- accent_fg = _sgr_fg_color(kernel[0])- assert accent_fg, f"rust: kernel diamond carries no fg color in {state}"- icon_fgs = {}- for name, outcome in RLM_CHILD_LABELS:- label = f"Subagent {name} {outcome}"- runs = _row_header_runs(frame, label)- assert runs, f"rust: diamond header for {label!r} missing in {state}"- icon_fg = _sgr_fg_color(runs[0])- label_fg = _sgr_fg_color(runs[1])- assert icon_fg, f"rust: {label} diamond carries no fg color in {state}"- assert label_fg, f"rust: {label} label carries no fg color in {state}"- assert icon_fg == label_fg, (- f"rust: {label} diamond fg {icon_fg} != label fg {label_fg} in {state}"- )- assert icon_fg != accent_fg, (- f"rust: {label} diamond still on the accent color in {state}"- )- icon_fgs[label] = icon_fg- assert len(set(icon_fgs.values())) == len(RLM_CHILD_LABELS), (- f"rust: the three RLM child outcomes share one icon color in {state}: {icon_fgs}"- )---def assert_sent_reach(side, collapsed, expanded):- """The Ctrl+O contract for this fixture: collapsed frames show the- agent-message and sent-receipt summaries only; the expanded frames show- the \u2570\u2500-guttered bodies. Any miss means the expand toggle- does not reach the agent-message rows. The summary strings follow the- per-side row contract (see assert_agent_message_rows)."""- if side == "rust":- assert "Agent message \u00b7 \u2193 model-probe" in collapsed, (- f"{side}: summary missing collapsed"- )- assert "Agent message \u00b7 \u2191 Worker" in collapsed, (- f"{side}: sent receipt summary missing collapsed"- )- else:- assert "Agent message received" in collapsed, f"{side}: summary missing collapsed"- assert "Agent message sent \u00b7 to parent Worker" in collapsed, (- f"{side}: sent receipt summary missing collapsed"- )- assert "\u2570\u2500 Decorations parity" not in collapsed, (- f"{side}: received body visible while collapsed"- )- assert "\u2570\u2500 Ping." not in collapsed, f"{side}: sent body visible while collapsed"- assert "\u2570\u2500 Decorations parity" in expanded, (- f"{side}: Ctrl+O did not expand the received body"- )- assert "\u2570\u2500 Ping." in expanded, (- f"{side}: Ctrl+O did not expand the sent body"- )---def assert_skill_reach(side, collapsed, expanded):- """The skill-invocation card contract: collapsed shows the one-line- `[skill] <name>` card and the args user block; expanded adds the- markdown body; the raw block text never floods either state."""- assert SKILL_CARD_SUMMARY in collapsed, f"{side}: skill card summary missing collapsed"- assert SKILL_ARGS in collapsed, f"{side}: skill args missing collapsed"- assert SKILL_CARD_BODY not in collapsed, f"{side}: skill body visible while collapsed"- assert "<skill name=" not in collapsed, f"{side}: raw skill block visible collapsed"- assert SKILL_CARD_BODY in expanded, f"{side}: Ctrl+O did not expand the skill body"- assert "<skill name=" not in expanded, f"{side}: raw skill block visible expanded"- assert SKILL_ARGS in expanded, f"{side}: skill args missing expanded"---# The refinement row's expanded content (the third carried divergence, see-# the module docstring): the needles cover the expanded block's rows —-# the expanded summary, the meta, the edit section (label, fields, diff-# content) — all unique to the expanded state; the collapsed rows carry no-# branch geometry and stay in the byte diff.-REFINEMENT_EXPANSION_NEEDLES = [- "Create one local memory.", # the expanded summary (branch-guttered Rust)- "Refinement refine_cmparity", # the meta row- "cmparity-memory", # the edit-section label- "Parity memory", # the Title diff content- "The harness stays green.", # the Description value-]---def split_refinement_expansion(frame, state):- """Split the refinement row's expanded rows out of the frame,- returning `(kept, removed)`.-- The kept rows byte-diff (the expanded state's rows hang on the- branch grammar on the Rust side — the carried indent divergence; the- collapsed state is untouched). The removed rows do NOT leave the- comparison: `assert_refinement_content` matches their visible- content word for word, so a truncated, omitted, or changed- Title/Description/section value fails the run instead of vanishing- from the byte diff. The field-label rows match by exact stripped- text (an indented `Title` on the Rust side, a plain-inset `Title` on- the TS side)."""- if state != "b_expanded":- return frame, []- kept, removed = [], []- for line in frame.split("\n"):- plain = re.sub(r"\x1b\[[0-9;]*m", "", line)- if any(needle in plain for needle in REFINEMENT_EXPANSION_NEEDLES):- removed.append(line)- continue- if plain.strip() in ("Title", "Description"):- removed.append(line)- continue- kept.append(line)- return "\n".join(kept), removed---def assert_refinement_content(ts_removed, rust_removed):- """The removed expansion rows' visible content must match between the- products: ANSI-stripped, the branch gutter glyphs dropped, whitespace- collapsed. The intended divergence is the indentation and the wrap- points the narrower branch content width forces — never the values- themselves, so the comparison is over words, not bytes. A frame that- never rendered the block fails loudly (the removed set is empty)."""-- def collapsed_content(rows):- text = capture_plain_text("\n".join(rows))- return re.sub(r"\s+", " ", text.replace("╰─", " ")).strip()-- ts = collapsed_content(ts_removed)- rust = collapsed_content(rust_removed)- assert ts, "ts: the refinement expansion rows are missing from the frame"- assert rust, "rust: the refinement expansion rows are missing from the frame"- assert ts == rust, (- "the refinement expansion content differs:\n"- f" ts: {ts}\n"- f" rust: {rust}"- )---def assert_refinement_branch(side, collapsed, expanded):- """The third carried divergence: the Rust expanded refinement block- hangs on the branch grammar (the `╰─ ` gutter off the- `◆` header, four-space continuation indent); the TS binary keeps- the plain one-column chat inset (the baseline)."""- summary = "Create one local memory."- meta = "Harness refined · 1 memory created · Refinement refine_cmparity · local"- gutter = "╰─ "- indent = " "- if side == "rust":- # Collapsed keeps the TS shape: plain inset, no branch.- assert " " + summary in collapsed, f"rust: summary missing collapsed"- assert gutter + summary not in collapsed, "rust: branch rendered collapsed"- # Expanded hangs the summary on the gutter, the meta on the- # continuation indent, the edit section re-branches.- assert " " + gutter + summary in expanded, "rust: expanded summary missing the branch gutter"- assert indent + meta in expanded, "rust: meta missing the continuation indent"- assert " " + gutter + "Created local memory `cmparity-memory`" in expanded, (- "rust: edit-section label missing the branch gutter"- )- assert indent + "Compacted" not in expanded- else:- assert " " + summary in expanded, "ts: summary missing expanded (baseline)"- assert gutter + summary not in expanded, "ts: unexpectedly renders the branch"- assert " " + meta in expanded, "ts: meta missing expanded (baseline)"- assert " " + "Created local memory `cmparity-memory`" in expanded, (- "ts: edit-section label missing expanded (baseline)"- )---def align_frame_tops(left, right):- """Trim the scroll-leak rows a bottom-pinned viewport shows, and only- those.-- The compared frames are bottom-pinned viewport windows; a row-count- delta anywhere in the content shifts one window's top over the- other's — the longer frame's top rows are rows the shorter side- scrolled off, a window artifact, not a row-shape divergence. The- bottom is the anchor: the trailing rows are the same pane tail on- both sides, so a proven common suffix must cover the whole length- difference before any top row is dropped, and then only the length- difference itself comes off the longer frame's top. No row is ever- dropped because it exists somewhere in the other frame — a real- top-of-screen regression still diffs."""- left_rows, right_rows = left.split("\n"), right.split("\n")- n, m = len(left_rows), len(right_rows)- if n == m:- return left, right- longer, shorter = (left_rows, right_rows) if n > m else (right_rows, left_rows)- delta = abs(n - m)- # Prove the bottoms correspond: count the longest common suffix.- suffix = 0- while suffix < min(n, m) and longer[len(longer) - 1 - suffix] == shorter[len(shorter) - 1 - suffix]:- suffix += 1- if suffix < delta:- # No proven bottom anchor covering the leak: leave both frames- # whole so the diff surfaces every differing row.- return left, right- if n > m:- return "\n".join(left_rows[delta:]), right- return left, "\n".join(right_rows[delta:])---def diff_lines(left, right):- return "\n".join(- difflib.unified_diff(left.split("\n"), right.split("\n"), fromfile="ts", tofile="rust", lineterm="", n=1)- )---def wait_for(session, needle, timeout):- deadline = time.time() + timeout- while time.time() < deadline:- if needle in capture_plain(session):- return- time.sleep(0.3)- raise TimeoutError(f"session {session} never showed {needle!r}")---def mode_label(session):- """The conversation-detail label in the prompt-context row- (Collapsed / Details / Expanded)."""- match = re.search(r"(Collapsed|Details|Expanded) mode \(Ctrl\+O", capture_plain(session))- return match.group(1) if match else None---def press_until_mode(session, target, max_presses=4):- """Ctrl+O until the conversation-detail label reads `target`.-- The two products' resume detail levels differ (the TS resume starts- at details, the Rust replay at overview), so fixed press counts- desync the compared states: drive both sides to the same label- instead."""- for _ in range(max_presses):- if mode_label(session) == target:- return True- tmux("send-keys", "-t", session, "C-o")- time.sleep(1.2)- return mode_label(session) == target---def find_runtime_package_dir():- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- candidates = [- entry- for entry in sorted(os.listdir(releases))- if os.path.isdir(os.path.join(releases, entry, "prime-agent-runtime"))- ]- if not candidates:- raise SystemExit("no release with prime-agent-runtime/ under " + releases)- return os.path.join(releases, candidates[-1])---def run_ts(session_path, sandbox, size, out_dir):- session = f"cmparity-ts-{size[0]}x{size[1]}"- tmux("kill-session", "-t", session, check=False)- tmux(- "new-session",- "-d",- "-s",- session,- "-x",- size[0],- "-y",- size[1],- "-c",- sandbox["cwd"],- # A plain shell: the box tmux default-shell is herdr's prime-agent- # launcher (every new pane boots a live agent TUI, hijacking the- # harness's send-keys contract). herdr's documented opt-out keeps- # the pane a plain interactive shell.- "-e",- "HERDR_PLAIN_SHELL=1",- )- env = (- f"HOME={sandbox['home']} "- f"TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- # A dedicated daemon socket keeps the sandbox main daemon off the- # shared socket path; the isolated TMPDIR keeps its supervisor off- # the shared box root too, so the cleanup reap can sweep both.- command = (- f"{env} prime-agent --daemon-socket {sandbox['agent']}/daemon.sock "- f"--offline -r {session_path}"- )- tmux("send-keys", "-t", session, command, "Enter")- wait_for(session, MARKER_TEXT, timeout=60)- time.sleep(1.5)- # Label-driven states: both sides park at Collapsed for the first- # capture, then drive to Expanded for the second (fixed press counts- # desync: the TS resume starts at details, the Rust at overview).- if not press_until_mode(session, "Collapsed"):- raise TimeoutError(f"session {session} never reached Collapsed mode")- frames = {"a_collapsed": capture(session)}- if not press_until_mode(session, "Expanded"):- raise TimeoutError(f"session {session} never reached Expanded mode")- time.sleep(0.5)- frames["b_expanded"] = capture(session)- tmux("kill-session", "-t", session, check=False)- for state, frame in frames.items():- with open(os.path.join(out_dir, f"ts-{state}-{size[0]}x{size[1]}.txt"), "w") as f:- f.write(frame)- return frames---def run_rust(session_path, sandbox, size, out_dir):- session = f"cmparity-rust-{size[0]}x{size[1]}"- tmux("kill-session", "-t", session, check=False)- tmux(- "new-session",- "-d",- "-s",- session,- "-x",- size[0],- "-y",- size[1],- "-c",- sandbox["cwd"],- # A plain shell: the box tmux default-shell is herdr's prime-agent- # launcher (every new pane boots a live agent TUI, hijacking the- # harness's send-keys contract). herdr's documented opt-out keeps- # the pane a plain interactive shell.- "-e",- "HERDR_PLAIN_SHELL=1",- )- rust = os.environ.get(- "PA_RUST_REPLAY",- os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "target", "debug", "pa-tui-replay"),- )- env = f"HOME={sandbox['home']}"- command = f"{env} {rust} {session_path}"- tmux("send-keys", "-t", session, command, "Enter")- wait_for(session, MARKER_TEXT, timeout=60)- time.sleep(1.5)- if not press_until_mode(session, "Collapsed"):- raise TimeoutError(f"session {session} never reached Collapsed mode")- frames = {"a_collapsed": capture(session)}- if not press_until_mode(session, "Expanded"):- raise TimeoutError(f"session {session} never reached Expanded mode")- time.sleep(0.5)- frames["b_expanded"] = capture(session)- tmux("kill-session", "-t", session, check=False)- for state, frame in frames.items():- with open(os.path.join(out_dir, f"rust-{state}-{size[0]}x{size[1]}.txt"), "w") as f:- f.write(frame)- return frames---def prepare_sandbox(base):- cwd = os.path.join(base, "cwd")- os.makedirs(cwd, exist_ok=True)- sandboxes = {}- for binary in ("ts", "rust"):- home = os.path.join(base, binary, "home")- agent = os.path.join(base, binary, "agent")- tmp = os.path.join(base, binary, "tmp")- os.makedirs(home, exist_ok=True)- os.makedirs(tmp, exist_ok=True)- os.makedirs(os.path.join(agent, "sessions"), exist_ok=True)- with open(os.path.join(agent, "settings.json"), "w") as f:- json.dump({"onboardingCompleted": True}, f)- # The isolated TMPDIR keeps the TS supervisor's socket (the- # default daemon-socket dir) off the shared box root, so the- # cleanup reap can sweep the side's daemons by path alone.- sandboxes[binary] = {"home": home, "agent": agent, "cwd": cwd, "tmp": tmp}- return sandboxes---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--sizes", default=",".join(f"{w}x{h}" for w, h in SIZES))- parser.add_argument("--keep", action="store_true")- parser.add_argument("--out", default=None)- parser.add_argument("--only", default=None, choices=["ts", "rust"])- args = parser.parse_args()- sizes = [tuple(entry.split("x")) for entry in args.sizes.split(",")]-- # Fail fast before any launch: a non-TS `prime-agent` on PATH plays a- # Rust build as the "ts" side and reports false divergences.- if args.only in (None, "ts"):- ts_identity.assert_ts_side_is_the_ts_product()-- base = tempfile.mkdtemp(prefix="custom-message-parity-")- out_dir = args.out or tempfile.mkdtemp(prefix="custom-message-captures-")- sandboxes = prepare_sandbox(base)- sessions = session_paths()- session_path = build_session(- os.path.join(base, "parity-session.jsonl"),- newest_session_header(),- newest_assistant_message(sessions),- os.path.join(base, "cwd"),- )- print(f"session: {session_path}")- failures = []- try:- if args.only:- runner = run_ts if args.only == "ts" else run_rust- frames = runner(session_path, sandboxes[args.only], sizes[0], out_dir)- print(f"captures for {args.only} in {out_dir}: {sorted(frames)}")- return 0- for size in sizes:- ts_frames = run_ts(session_path, sandboxes["ts"], size, out_dir)- rust_frames = run_rust(session_path, sandboxes["rust"], size, out_dir)- # The Ctrl+O reach check: the agent-message bodies (the- # \u2570\u2500 gutter) must be absent collapsed and present- # expanded on BOTH sides.- for side, frames in (("ts", ts_frames), ("rust", rust_frames)):- collapsed = capture_plain_text(frames["a_collapsed"])- expanded = capture_plain_text(frames["b_expanded"])- assert_sent_reach(side, collapsed, expanded)- assert_rlm_child_rows(side, collapsed, expanded)- assert_heartbeat_row(side, collapsed, expanded)- assert_agent_message_rows(side, collapsed, expanded)- assert_skill_reach(side, collapsed, expanded)- assert_refinement_branch(side, collapsed, expanded)- # The icon-follows-text color contract (the same directive as- # the row divergence): the escape-bearing Rust frames carry- # it; the TS frames have no icon to check (the generic label).- assert_rlm_child_icon_colors(rust_frames)- for state in ("a_collapsed", "b_expanded"):- ts_kept, ts_removed = split_refinement_expansion(- strip_rlm_child_rows(ts_frames[state]), state- )- rust_kept, rust_removed = split_refinement_expansion(- strip_rlm_child_rows(rust_frames[state]),- state,- )- # The expanded block's rows leave the byte diff (the- # carried indent divergence) but not the comparison: their- # content must match word for word.- if state == "b_expanded":- assert_refinement_content(ts_removed, rust_removed)- ts_norm = normalize(ts_kept, base)- rust_norm = normalize(rust_kept, base)- # The carried label/arrow divergence: the collapsed Rust- # row carries no body preview (the 2026-09-25 directive),- # exactly like the TS header — the body only opens up in- # the expanded view (the `\u2570\u2500` gutter, never the- # `\u00b7` preview segment).- rust_plain = capture_plain_text(rust_frames[state])- assert " \u00b7 " + AGENT_MESSAGE_BODY[:40] not in rust_plain, (- f"rust preview rendered in {state}"- )- assert " \u00b7 " + AGENT_MESSAGE_BODY[:40] not in capture_plain_text(- ts_frames[state]- ), f"ts unexpectedly renders the preview in {state}"- name = f"{state}-{size[0]}x{size[1]}"- ts_norm, rust_norm = align_frame_tops(ts_norm, rust_norm)- if ts_norm == rust_norm:- print(f"PASS {name}")- else:- print(f"FAIL {name}")- report = os.path.join(out_dir, f"diff-{name}.txt")- with open(report, "w") as f:- f.write(diff_lines(ts_norm, rust_norm))- print(f" diff: {report}")- failures.append(name)- finally:- # Rmtree alone leaks the scenario daemons (a killed TUI pane does- # not take its detached daemon/supervisor pair down; #223): sweep- # every daemon this run spawned before deleting the sandbox.- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if not args.keep:- shutil.rmtree(base, ignore_errors=True)- if failures:- print(f"{len(failures)} state(s) differ; captures in {out_dir}")- return 1- print(f"all states match; captures in {out_dir}")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/daemon_autorefine_parity.py b/scripts/daemon_autorefine_parity.pydeleted file mode 100644index 30f9e29e73..0000000000--- a/scripts/daemon_autorefine_parity.py+++ /dev/null@@ -1,304 +0,0 @@-#!/usr/bin/env python3-"""Compact-trigger auto-refine parity on the daemon surface: after the-`compact` wire command, TS schedules the auto-refine review-(agent-session.ts `_scheduleAutoRefineAfterCompaction` ->-`_scheduleAutoRefine("compact")` -> `_maybeAutoRefine("compact")`), and-the Rust daemon worker now does the same-(pa-daemon/src/compact_autorefine.rs). The review is an LLM request the-mock provider sees, so the two sides are differentially compared on:-- - the compact command response (success, same result keys),- - exactly one review request per side, whose shape must match:- the review system prompt (the "automatic /refine review gate") and- the trigger line ("compact; N assistant turns since last- auto-refine review" with the same settled-turn count),- - no `refine_complete`/`refine_failed` wire event on either side- (the mock's plain-text reply fails the review JSON parse; both- surfaces treat that as a silent failure that stamps the cooldown),- - a follow-up prompt still answers on both sides (the session is- healthy after the round).--Exit code is non-zero when any check fails; evidence lands in the run-dir given by --out (default a tempdir under /tmp).-"""--import argparse-import json-import os-import sys-import time-from pathlib import Path--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib as B # noqa: E402-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--TURNS = 6-TURN_TEXT = "Turn {n} of the parity battery. " * 800-REVIEW_SYSTEM_MARKER = "automatic /refine review gate"-TRIGGER_PREFIX = "<trigger>"-COMPACT_TIMEOUT = 240---def message_text(message):- """One request message's text content (list-of-blocks or string)."""- content = message.get("content")- if isinstance(content, str):- return content- if isinstance(content, list):- return "\n".join(- block.get("text", "") for block in content if isinstance(block, dict)- )- return ""---def review_request(log):- """The auto-refine review request in a mock request log, if any."""- for record in log:- body = record.get("body", {})- messages = body.get("messages", [])- system_text = "\n".join(- message_text(message)- for message in messages- if message.get("role") == "system"- )- for message in messages:- text = message_text(message)- if text.startswith(TRIGGER_PREFIX):- return {- "trigger_line": text.split("</trigger>")[0]- .removeprefix(TRIGGER_PREFIX)- .strip("\n")- .strip(),- "system_is_review_gate": REVIEW_SYSTEM_MARKER in system_text,- "harness_state_block": "<current_harness_state>"- in text,- }- return None---def run_side(name, binary, root, pi_package_dir=None):- agent = root / "agent"- agent.mkdir(parents=True, exist_ok=True)- work = root / "work"- work.mkdir(parents=True, exist_ok=True)- mock = B.MockProvider(root, [])- mock.set_responses([{"text": "hello"}])- mock.start()- side = B.Side(- name=name,- binary=str(binary),- root=root,- agent_dir=agent,- work_dir=work,- daemon_socket=root / "daemon.sock",- mock=mock,- )- tmpdir = Path("/tmp") / f"autorefine-parity-{name}-{root.name}"- if tmpdir.exists():- import shutil-- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- side.env = B.scrubbed_env(agent, tmpdir)- if pi_package_dir:- # The Rust binary resolves the kernel runtime sidecar through- # PI_PACKAGE_DIR (a cargo build bakes a nonexistent source path).- side.env["PI_PACKAGE_DIR"] = pi_package_dir- side.write_models_json()- side.start_daemon()- try:- wire = B.Wire(side.daemon_socket)- create = wire.request(- "c1",- {- "type": "create",- "name": f"autorefine-parity-{name}",- "config": {- "cwd": str(work),- "sessionDir": str(agent / "sessions"),- "provider": "prime-inference",- "model": "mock-1",- "executionMode": "print",- },- },- timeout=120,- )- assert create.get("success") is True, f"{name}: create failed: {create}"- session_id = (- create.get("data", {}).get("activeSessionId")- or create.get("data", {}).get("id")- or ""- )- # An attached client receives the session events (the review- # failure must stay silent on the wire on both sides).- attacher = B.Wire(side.daemon_socket)- attach = attacher.request(- "a1", {"type": "attach", "activeSessionId": session_id}, timeout=60- )- assert attach.get("success") is True, f"{name}: attach failed: {attach}"- mock.set_responses(- [{"text": f"pre-compaction reply {i}"} for i in range(TURNS + 8)]- )- for turn in range(1, TURNS + 1):- reply = wire.request(- f"p{turn}",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": TURN_TEXT.format(n=turn),- },- timeout=240,- )- assert reply.get("success") is True, f"{name}: prompt {turn} failed"- compact = wire.request(- "k1",- {"type": "compact", "activeSessionId": session_id},- timeout=COMPACT_TIMEOUT,- )- # Let the background round settle (the review is scheduled after- # the compaction answers).- deadline = time.time() + 30- while time.time() < deadline:- log = mock.requests()- if any(- record.get("body", {}).get("messages")- and any(- isinstance(block, dict)- and block.get("text", "").startswith(TRIGGER_PREFIX)- for message in record["body"]["messages"]- for block in message.get("content", []) or []- )- for record in log- ):- break- time.sleep(0.5)- time.sleep(2)- # A second compact within the review cooldown: both sides stamped- # the cooldown on the first review attempt (the mock's plain-text- # reply fails the review JSON parse, which every attempt stamps),- # so no second review request may run.- second = wire.request(- "k2",- {"type": "compact", "activeSessionId": session_id},- timeout=COMPACT_TIMEOUT,- )- time.sleep(3)- review_count = sum(- 1- for record in mock.requests()- if any(- message_text(message).startswith(TRIGGER_PREFIX)- for message in record.get("body", {}).get("messages", [])- )- )- # Drain any queued wire events (best-effort; the socket stays- # open, so only a bounded window is read).- time.sleep(2)- wire.close()- attacher.close()- return {- "compact_success": compact.get("success") is True,- "compact_data_keys": sorted((compact.get("data") or {}).keys()),- "compact_result": (compact.get("data") or {}).get("result"),- "review": review_request(mock.requests()),- "second_compact_success": second.get("success") is True,- "review_count": review_count,- }- finally:- side.stop_daemon()- mock.stop()---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--ts-bin", default="prime-agent")- parser.add_argument(- "--rust-bin",- default=os.environ.get(- "PA_PARITY_RUST",- str(- Path(__file__).resolve().parents[1]- / "target"- / "debug"- / "prime-agent"- ),- ),- )- parser.add_argument(- "--out",- default=None,- help="evidence dir (default: scripts/battery/runs/<stamp>-autorefine)",- )- parser.add_argument(- "--pi-package-dir",- default=os.environ.get("PI_PACKAGE_DIR", "/home/ubuntu/.local/share/prime-agent"),- )- options = parser.parse_args()- ts_identity.assert_ts_side_is_the_ts_product(options.ts_bin, options.rust_bin)- if not Path(options.rust_bin).exists():- print(f"rust binary missing: {options.rust_bin}")- return 2- stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())- out = Path(options.out) if options.out else (- Path(__file__).resolve().parents[1]- / "scripts"- / "battery"- / "runs"- / f"{stamp}-autorefine"- )- out.mkdir(parents=True, exist_ok=True)-- ts_result = run_side("ts", options.ts_bin, out / "ts")- (out / "ts" / "result.json").write_text(json.dumps(ts_result, indent=1))- rust_result = run_side(- "rust", options.rust_bin, out / "rust", pi_package_dir=options.pi_package_dir- )- (out / "rust" / "result.json").write_text(json.dumps(rust_result, indent=1))-- failures = []-- def check(name, condition, detail=""):- print(("PASS " if condition else "FAIL ") + name + (f" :: {detail}" if detail else ""))- if not condition:- failures.append(name)-- check("both compacts succeeded", ts_result["compact_success"] and rust_result["compact_success"])- check(- "compact result keys match",- ts_result["compact_data_keys"] == rust_result["compact_data_keys"],- f"ts={ts_result['compact_data_keys']} rust={rust_result['compact_data_keys']}",- )- check("both sides scheduled the review", ts_result["review"] and rust_result["review"])- if ts_result["review"] and rust_result["review"]:- check(- "the review trigger line matches",- ts_result["review"]["trigger_line"] == rust_result["review"]["trigger_line"],- f"ts={ts_result['review']['trigger_line']!r} rust={rust_result['review']['trigger_line']!r}",- )- check(- "both review requests use the review-gate system prompt",- ts_result["review"]["system_is_review_gate"]- and rust_result["review"]["system_is_review_gate"],- )- check(- "both review prompts carry the harness state",- ts_result["review"]["harness_state_block"]- and rust_result["review"]["harness_state_block"],- )- check(- "the second compact answers identically on both sides",- ts_result["second_compact_success"] == rust_result["second_compact_success"],- f"ts={ts_result['second_compact_success']} rust={rust_result['second_compact_success']}",- )- check(- "the cooldown holds the second round: one review per side",- ts_result["review_count"] == 1 and rust_result["review_count"] == 1,- f"ts={ts_result['review_count']} rust={rust_result['review_count']}",- )- print(f"evidence: {out}")- return 1 if failures else 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/daemon_verify.py b/scripts/daemon_verify.pydeleted file mode 100644index 1e6c316af9..0000000000--- a/scripts/daemon_verify.py+++ /dev/null@@ -1,239 +0,0 @@-#!/usr/bin/env python3-"""Daemon lane integration verifier.--Starts the pa-daemon supervisor headlessly, creates a session worker running a-scripted faux session, sends prompts, verifies persistence; then kill -9 the-supervisor, restarts it, reattaches, and verifies history + queue state intact.-Also verifies worker kill -9 supervision: restart + backoff + rehydration.-"""-import json, os, socket, subprocess, sys, tempfile, time, uuid--BIN = os.path.expanduser("~/lane-worktrees/daemon/target/debug/pa-daemon")-ENV = {- "PATH": "/usr/bin:/bin",- "HOME": os.environ.get("HOME", "/home/ubuntu"),-}-PROTO = {"name": "prime-agent.daemon", "version": 7}--failures = []--def check(name, condition, detail=""):- print(f"{'PASS' if condition else 'FAIL'}: {name}" + (f" -- {detail}" if detail and not condition else ""))- if not condition:- failures.append(name)--class Client:- def __init__(self, sock_path):- self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- self.sock.connect(sock_path)- self.f = self.sock.makefile("rw")- hello = json.loads(self.f.readline())- assert hello["type"] == "daemon_hello", hello- self.client_id = hello["clientId"]- self.events = []-- def send(self, command, cmd_id=None, **fields):- cid = cmd_id or str(uuid.uuid4())- line = json.dumps({"type": "command", "id": cid, "protocol": PROTO,- "command": {"type": command, **fields}})- self.f.write(line + "\n")- self.f.flush()-- def recv_until_response(self, command, cmd_id, timeout=60):- """Read frames until the response for cmd_id; events are collected."""- self.sock.settimeout(timeout)- while True:- frame = json.loads(self.f.readline())- if frame.get("type") == "response" and frame.get("id") == cmd_id:- return frame- if frame.get("type") != "response":- self.events.append(frame)-- def close(self):- self.f.close()- self.sock.close()-- def call(self, command, timeout=60, **fields):- cid = str(uuid.uuid4())- self.send(command, cid, **fields)- return self.recv_until_response(command, cid, timeout)--def wait_socket(path, timeout=20):- deadline = time.time() + timeout- while time.time() < deadline:- try:- s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- s.connect(path)- s.close()- return True- except OSError:- time.sleep(0.05)- return False--def start_supervisor(sock, agent_dir, script_path=None):- env = dict(ENV)- env["PRIME_AGENT_CODING_AGENT_DIR"] = agent_dir- env["PRIME_AGENT_SESSION_DIR"] = os.path.join(agent_dir, "sessions")- if script_path:- env["PA_TEST_SCRIPT"] = script_path- proc = subprocess.Popen([BIN, "supervisor", "--socket", sock, "--agent-dir", agent_dir],- env=env, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)- assert wait_socket(sock), "supervisor socket never came up"- return proc--def main():- root = tempfile.mkdtemp(prefix="pa-daemon-verify-")- agent_dir = os.path.join(root, "agent")- sessions = os.path.join(agent_dir, "sessions")- os.makedirs(sessions)- sock = os.path.join(root, "daemon.sock")- script_path = os.path.join(root, "script.json")- with open(script_path, "w") as f:- json.dump({"responses": [- "faux reply one",- {"text": "faux reply two (slow)", "delayMs": 2500},- "faux reply three",- {"text": "faux reply four (slow)", "delayMs": 2500},- ]}, f)-- sup = start_supervisor(sock, agent_dir)- print(f"supervisor pid {sup.pid}, socket {sock}")-- # --- 1. create session with scripted faux engine ---------------------- c1 = Client(sock)- check("hello protocol v7", Client.__init__ and True) # constructed without error- r = c1.call("create", config={"cwd": root, "script": script_path}, name="faux-session")- check("create succeeds", r["success"], json.dumps(r))- summary = r.get("data") or {}- session_id = summary.get("activeSessionId") or summary.get("id")- session_file = summary.get("sessionFile")- check("create returns session id", bool(session_id), json.dumps(summary))- check("session file exists", bool(session_file) and os.path.exists(session_file), str(session_file))-- # --- 2. attach + prompt_and_wait --------------------------------------- r = c1.call("attach", activeSessionId=session_id)- check("attach succeeds", r["success"], json.dumps(r))- attach = r.get("data") or {}- check("attach snapshot has replay", attach.get("replay", {}).get("status") in ("complete", None), json.dumps(attach.get("replay")))-- r = c1.call("prompt_and_wait", activeSessionId=session_id, message="hello one", timeout=90)- check("prompt_and_wait succeeds", r["success"], json.dumps(r))-- r = c1.call("get_messages", activeSessionId=session_id)- msgs = (r.get("data") or {}).get("messages", [])- check("history has 2 messages", len(msgs) == 2, json.dumps(msgs))- check("user message persisted", any(m.get("role") == "user" and m.get("content") == "hello one" for m in msgs))-- # --- 3. queue lanes while busy ---------------------------------------- c1.send("prompt", activeSessionId=session_id, message="hello two")- time.sleep(0.5) # turn is running (2.5s scripted delay)- r = c1.call("get_queue", activeSessionId=session_id)- # prompt enqueues in follow-up lane while busy- r = c1.call("steer", activeSessionId=session_id, message="steer this")- check("steer accepted", r["success"], json.dumps(r))- r = c1.call("follow_up", activeSessionId=session_id, message="follow me later")- check("follow_up accepted", r["success"], json.dumps(r))- r = c1.call("get_queue", activeSessionId=session_id)- q = r.get("data") or {}- check("steering lane holds steer", q.get("steering") == ["steer this"], json.dumps(q))- check("followUp lane holds follow-up", "follow me later" in (q.get("followUp") or []), json.dumps(q))-- # persist a deliberate queue snapshot marker for later check- c1.close() # TUI exit: sessions must survive client exit-- r_ = None- c1b = Client(sock)- r = c1b.call("get_state", activeSessionId=session_id)- check("session survives client exit", r["success"] and (r["data"] or {}).get("isSessionActive"), json.dumps(r))-- # wait for the turn + queue drain- time.sleep(6)- r = c1b.call("get_messages", activeSessionId=session_id)- msgs = (r.get("data") or {}).get("messages", [])- texts = [m.get("content") for m in msgs]- check("steer delivered after turn boundary", "steer this" in texts, json.dumps(texts))-- # queue two follow-ups and verify they persist on disk (queue snapshot)- r = c1b.call("follow_up", activeSessionId=session_id, message="persisted follow A")- r = c1b.call("follow_up", activeSessionId=session_id, message="persisted follow B")- # busy? no; they will drain immediately. Instead check disk persistence differently:- # read the session file for a queue_snapshot custom entry- time.sleep(0.5)- with open(session_file) as f:- lines = [json.loads(l) for l in f if l.strip()]- snapshots = [e for e in lines if e.get("type") == "custom" and (e.get("customType") == "prime-agent-rs.queue_snapshot")]- check("queue snapshot persisted to session store", len(snapshots) >= 1, str(len(snapshots)))-- # --- 4. kill -9 supervisor, restart, reattach -------------------------- sup_pid = sup.pid- subprocess.run(["kill", "-9", str(sup_pid)])- sup.wait()- print(f"supervisor kill -9'd (pid {sup_pid})")- time.sleep(0.5)- sup2 = start_supervisor(sock, agent_dir)- print(f"supervisor restarted pid {sup2.pid}")-- c2 = Client(sock)- r = c2.call("list")- sessions_list = (r.get("data") or {}).get("sessions", [])- check("list shows adopted session after restart", any(s.get("id") == session_id for s in sessions_list), json.dumps(sessions_list))-- r = c2.call("attach", activeSessionId=session_id)- check("reattach after supervisor restart", r["success"], json.dumps(r))- attach = r.get("data") or {}- msgs = (attach.get("messages") or [])- texts = [m.get("content") for m in msgs]- check("history intact after supervisor kill -9", "hello one" in texts and "faux reply one" in texts and "steer this" in texts, json.dumps(texts))-- # queue state: prompt starts a slow scripted turn; the follow-up is- # enqueued while busy and must be visible in the queue snapshot.- r = c2.call("prompt", activeSessionId=session_id, message="hello three")- r = c2.call("follow_up", activeSessionId=session_id, message="post-restart follow")- r = c2.call("get_queue", activeSessionId=session_id)- q = r.get("data") or {}- check("queue state queryable after restart", "post-restart follow" in (q.get("followUp") or []), json.dumps(q))-- # wait for queue to settle, verify final assistant text- time.sleep(6)- r = c2.call("get_last_assistant_text", activeSessionId=session_id)- text = (r.get("data") or {}).get("text")- check("assistant text after queue drain", text == "faux reply three" or bool(text), repr(text))-- # --- 5. worker kill -9: supervision with restart + backoff ------------ # find the worker process: child of nobody, command contains 'worker'- out = subprocess.run(["pgrep", "-f", "pa-daemon worker"], capture_output=True, text=True, env=ENV).stdout.split()- check("worker process exists", len(out) >= 1, out)- worker_pid = int(out[0])- subprocess.run(["kill", "-9", str(worker_pid)])- print(f"worker kill -9'd (pid {worker_pid})")- deadline = time.time() + 30- respawned = False- while time.time() < deadline:- out = subprocess.run(["pgrep", "-f", "pa-daemon worker"], capture_output=True, text=True, env=ENV).stdout.split()- if out and int(out[0]) != worker_pid:- respawned = True- break- time.sleep(0.2)- check("supervisor respawns dead worker (backoff)", respawned)- # allow reconnect + rehydrate- time.sleep(2)- c3 = Client(sock)- r = c3.call("get_messages", activeSessionId=session_id)- msgs = (r.get("data") or {}).get("messages", [])- texts = [m.get("content") for m in msgs]- check("history intact after worker respawn", "hello one" in texts, json.dumps(texts))-- # --- 6. shutdown -------------------------------------------------------- r = c3.call("shutdown")- check("shutdown responds", r["success"], json.dumps(r))- time.sleep(1)- out = subprocess.run(["pgrep", "-f", "pa-daemon worker"], capture_output=True, text=True, env=ENV).stdout.split()- check("workers exit on shutdown", len(out) == 0, out)-- print()- if failures:- print(f"FAILURES ({len(failures)}): {failures}")- sys.exit(1)- print("ALL CHECKS PASSED")--main()diff --git a/scripts/drag_select_parity.py b/scripts/drag_select_parity.pydeleted file mode 100755index 62ac3f55a9..0000000000--- a/scripts/drag_select_parity.py+++ /dev/null@@ -1,372 +0,0 @@-#!/usr/bin/env python3-"""Drag-select verifier on a large session (extends the mouse/parity tmux-harness family, Rust side only — the drag bars are the flagship perf work).--Builds a ~40MB transcript session, resumes it in tmux, and drives a-press-drag-release sweep with byte-identical SGR mouse reports through the-same decode-and-dispatch path a terminal mouse takes. The verifier asserts-the flagship drag-select contract:-- * the highlight tracks the cursor: after every drag step, the reversed- span at the dragged columns appears in the pane within the coalesced- frame budget (zero visible lag — the per-step latency is measured and- reported as evidence, not just asserted);- * the drag events coalesce: every step's paint lands inside one frame- interval plus capture overhead, never one transcript-sized layout per- mouse-move;- * the release copies the dragged text (OSC 52 in the pane's raw stream)- and the "Copied selection to clipboard" row lands without a geometry- resolve stall;- * the same sweep runs while the view is paused mid-history (wheel up)- as while following the tail.--Before/after pane captures, the per-step latency table, and the copy text-land in scripts/drag-select-runs/<timestamp>/ as evidence.--tmux rules: default socket only (`env -u TMUX`), dragp-* session names,-no kill-server; the session is killed individually at the end.-"""--import argparse-import base64-import json-import os-import re-import shutil-import subprocess-import sys-import time-from datetime import datetime, timezone-from pathlib import Path--REPO = Path(__file__).resolve().parent.parent-T0 = 1789584016603--# The transcript corpus: TURNS pairs of user/assistant messages, the-# assistant body ~11KB so the session file lands near 40MB (the dogfood-# scale the drag bar targets). The last assistant message carries the drag-# needle so the sweep targets a known row.-TURNS = 1800-BODY_KB = 11-NEEDLE = "drag target alpha bravo charlie delta echo"--CAPTURE_POLL_S = 0.005-STEP_TIMEOUT_S = 3.0-# One coalesced frame (16ms) plus tmux capture overhead, with CI headroom:-# a per-step highlight latency above this is visible lag.-STEP_BUDGET_S = 0.35---def tmux(*args, check=True):- result = subprocess.run(- ["env", "-u", "TMUX", "tmux", *args],- capture_output=True,- text=True,- )- if check and result.returncode != 0:- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")- return result.stdout---def capture(session, escape=True):- flag = "-e" if escape else "-p"- return tmux("capture-pane", flag, "-p", "-t", session)---def locate_plain(pane_text, needle):- for row, line in enumerate(pane_text.split("\n")):- col = line.find(needle)- if col >= 0:- return row, col- return None---def corpus_path(run_dir: Path) -> Path:- """Write (or reuse) the large drag corpus under `run_dir`."""- # v2: assistant records carry a full provider usage block — the TS- # resume path reads usage without a guard (`usage.input`), so a corpus- # without usage crashes the TS binary on --resume (seen on 0.9.5).- path = run_dir / f"drag-corpus-{TURNS}-v2.jsonl"- if path.exists():- return path- header = {- "type": "session",- "id": "drag-select-corpus",- "version": 3,- "timestamp": "2026-09-16T18:40:16.600Z",- "cwd": "/tmp",- "rlmDepth": 0,- }- body = ("corpus payload line with stable width. " * (BODY_KB * 1024 // 41)).strip()- usage = {- "input": 4096,- "output": 2048,- "cacheRead": 0,- "cacheWrite": 0,- "totalTokens": 6144,- "cost": {"input": 0.01, "output": 0.02, "cacheRead": 0, "cacheWrite": 0, "total": 0.03},- }- lines = [json.dumps(header)]- parent = None- counter = 0-- def next_id():- nonlocal counter- counter += 1- return f"{counter:08x}"-- for turn in range(TURNS):- for role, text in (- ("user", f"please do task number {turn}"),- ("assistant", NEEDLE if turn == TURNS - 1 else f"answer {turn}: {body}"),- ):- message = {- "role": role,- "content": [{"type": "text", "text": text}],- "timestamp": T0 + turn,- }- if role == "assistant":- message["stopReason"] = "stop"- message["usage"] = usage- record = {- "type": "message",- "id": next_id(),- "parentId": parent,- "timestamp": "2026-09-16T18:40:%02d.%03dZ" % (turn % 60, counter % 1000),- "message": message,- }- lines.append(json.dumps(record))- parent = record["id"]- path.write_text("\n".join(lines) + "\n")- return path---def find_runtime_package_dir():- node_modules = Path.home() / "prime-agent" / "node_modules"- if (node_modules / "prime-agent-runtime").is_dir():- return str(node_modules / "prime-agent-runtime")- raise RuntimeError("prime-agent-runtime not found (set PI_PACKAGE_DIR)")---def sgr_hex(sequence):- return [f"{byte:02x}" for byte in sequence.encode()]---def send_mouse(session, sequence):- tmux("send-keys", "-t", session, "-H", *sgr_hex(sequence))---def mouse_press(col, row):- return f"\x1b[<0;{col};{row}M"---def mouse_drag(col, row):- return f"\x1b[<32;{col};{row}M"---def mouse_release(col, row):- return f"\x1b[<0;{col};{row}m"---def wheel_up(row):- return f"\x1b[<64;1;{row}M"---def wait_for(session, needle, timeout):- deadline = time.time() + timeout- while time.time() < deadline:- pane = capture(session, escape=False)- if needle in pane:- return- time.sleep(0.3)- raise TimeoutError(f"session {session} never showed {needle!r}")---def reversed_runs(row):- """The text carried by the row's reversed-video runs (the highlight).-- A reversed span may carry its own SGR sequences inside (a default-fg- reset before the text: `ESC[7m ESC[39m c ESC[0m`), so the run's text- is captured with the inner escapes stripped — a raw capture group- would keep them and fragment prefix checks fail against plain text.- """- runs = re.findall(r"\x1b\[7m((?:\x1b\[[0-9;]*m)*[^\x1b]*)", row)- return [re.sub(r"\x1b\[[0-9;]*m", "", run) for run in runs]---def sweep(session, out_dir, label, target_row, needle_col, needle):- """One press-drag-release sweep over the needle row: drag the columns- forward one per step, and after every step wait for the pane to show- the expected reversed fragment. Returns the per-step latencies."""- pane_rows = capture(session, escape=False).split("\n")- assert target_row < len(pane_rows), "target row left the pane"- press_col = needle_col + 1 # 1-based report columns- steps = []- send_mouse(session, mouse_press(press_col, target_row + 1))- fragment = ""- for offset in range(1, min(len(needle) - 2, 26) + 1):- col = press_col + offset- expected = needle[:offset]- send_mouse(session, mouse_drag(col, target_row + 1))- started = time.monotonic()- raw = None- while time.monotonic() - started < STEP_TIMEOUT_S:- raw = capture(session)- row = raw.split("\n")[target_row]- if any(run.startswith(expected) for run in reversed_runs(row)):- break- time.sleep(CAPTURE_POLL_S)- else:- Path(out_dir / f"{label}-stuck-step{offset}.raw").write_text(raw or "")- raise AssertionError(- f"{label}: the highlight never reached column {col} "- f"(expected reversed fragment {expected!r})"- )- steps.append(time.monotonic() - started)- send_mouse(session, mouse_release(press_col + len(steps), target_row + 1))- return steps---def main():- parser = argparse.ArgumentParser()- parser.add_argument("--width", type=int, default=120)- parser.add_argument("--height", type=int, default=36)- args = parser.parse_args()-- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")- run_dir = Path(__file__).resolve().parent / "drag-select-runs" / stamp- run_dir.mkdir(parents=True)- corpus = corpus_path(run_dir.parent)- size_mb = corpus.stat().st_size / (1024 * 1024)- print(f"corpus: {corpus} ({size_mb:.0f}MB)")-- home = run_dir / "home"- agent = run_dir / "agent"- tmp = run_dir / "tmp"- for path in (home, agent / "sessions", tmp):- path.mkdir(parents=True, exist_ok=True)- (agent / "settings.json").write_text(json.dumps({"onboardingCompleted": True}))-- rust = os.environ.get(- "PA_RUST_BINARY", str(REPO / "target" / "release" / "prime-agent")- )- package_dir = os.environ.get("PI_PACKAGE_DIR") or find_runtime_package_dir()- session = f"dragp-{stamp}"- tmux("kill-session", "-t", session, check=False)- tmux(- "new-session", "-d", "-s", session,- "-x", str(args.width), "-y", str(args.height), "-c", "/tmp",- )- # The raw pane stream: tmux >= 3.3 no longer surfaces OSC passthrough- # through `capture-pane -e`, so the OSC 52 copy is verified from the- # pane's byte stream instead.- stream_path = run_dir / "pane-stream.bin"- tmux("pipe-pane", "-t", session, "-o", f"cat > {stream_path}")- command = (- f"HOME={home} TMPDIR={tmp} PRIME_AGENT_CODING_AGENT_DIR={agent} "- f"PI_PACKAGE_DIR={package_dir} {rust} "- f"--daemon-socket {agent}/daemon.sock --resume {corpus}"- )- tmux("send-keys", "-t", session, command, "Enter")- try:- # The needle row renders at the tail (the last message); the first- # frame walks the whole transcript once, so allow a long settle.- wait_for(session, NEEDLE, timeout=120)- time.sleep(0.5)- plain = capture(session, escape=False)- located = locate_plain(plain, NEEDLE)- if located is None:- raise AssertionError("the needle left the pane")- target_row, needle_col = located- (run_dir / "before-follow.txt").write_text(capture(session))-- # Sweep 1: following the tail.- follow_steps = sweep(session, run_dir, "follow", target_row, needle_col, NEEDLE)-- # The release copies: the raw pane stream (the pipe-pane capture)- # carries the OSC 52 write and the status row lands.- wait_for(session, "Copied selection to clipboard", timeout=10)- raw = capture(session)- copies = re.findall(- rb"\x1b\]52;c;([A-Za-z0-9+/=]+)(?:\x07|\x1b\\)",- stream_path.read_bytes(),- )- if not copies:- raise AssertionError("the release never wrote an OSC 52 copy")- copied = base64.b64decode(copies[-1]).decode()- expected_copy = NEEDLE[: len(follow_steps)]- if not copied.strip().startswith(expected_copy.strip()):- raise AssertionError(- f"the copy read {copied[:40]!r}, expected {expected_copy!r}"- )- (run_dir / "after-follow.txt").write_text(raw)-- # Sweep 2: paused mid-history — wheel up a few screens, then drag- # a visible transcript row (the corpus is far taller than a dozen- # screens, so the pane shows some mid-history turn's rows, not the- # transcript head; the needle leaving the pane proves the pause).- for _ in range(12):- send_mouse(session, wheel_up(5))- time.sleep(0.5)- plain = capture(session, escape=False)- pane_rows = plain.split("\n")- # The pane shows wrapped body rows (the corpus body fills ~90 rows- # per turn, so a screenful rarely contains an "answer" heading- # row); any distinctive corpus row is a drag target. The needle- # must be the row text from the anchor column on — the sweep- # expects the highlight to grow over exactly that text.- anchor = None- for index, line in enumerate(pane_rows):- col = line.find("corpus payload")- if col < 0:- col = line.find("answer ")- if col >= 0:- anchor = (index, col)- break- if anchor is None or NEEDLE in plain:- raise AssertionError("the wheel-up never paused into history")- (run_dir / "before-paused.txt").write_text(capture(session))- row, col = anchor- needle_row_text = pane_rows[row][col:]- paused_steps = sweep(- session, run_dir, "paused", row, col, needle_row_text.strip()- )- send_mouse(session, mouse_release(col + 1 + len(paused_steps), row + 1))- (run_dir / "after-paused.txt").write_text(capture(session))-- evidence = {- "corpus": {- "path": str(corpus),- "size_mb": round(size_mb, 1),- "turns": TURNS,- },- "follow_steps_s": [round(step, 4) for step in follow_steps],- "paused_steps_s": [round(step, 4) for step in paused_steps],- "follow_max_s": round(max(follow_steps), 4),- "follow_median_s": round(sorted(follow_steps)[len(follow_steps) // 2], 4),- "paused_max_s": round(max(paused_steps), 4),- "copy": copied,- }- (run_dir / "evidence.json").write_text(json.dumps(evidence, indent=2))-- worst = max(max(follow_steps), max(paused_steps))- print(- f"follow: median {evidence['follow_median_s']*1000:.0f}ms "- f"max {evidence['follow_max_s']*1000:.0f}ms | "- f"paused: max {evidence['paused_max_s']*1000:.0f}ms | "- f"copy: {copied[:30]!r}"- )- if worst > STEP_BUDGET_S:- print(- f"FAIL: a drag step took {worst*1000:.0f}ms "- f"(budget {STEP_BUDGET_S*1000:.0f}ms) — visible lag"- )- return 1- print(f"PASS: the highlight tracked {len(follow_steps) + len(paused_steps)} drag steps")- return 0- finally:- tmux("kill-session", "-t", session, check=False)---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/editor_unicode_parity.py b/scripts/editor_unicode_parity.pydeleted file mode 100755index 2de2f2cecc..0000000000--- a/scripts/editor_unicode_parity.py+++ /dev/null@@ -1,416 +0,0 @@-#!/usr/bin/env python3-"""Editor Unicode/grapheme wrap parity verifier (the `editor-wrap-unicode`-lane): frame-diff the Rust interactive-TUI against the installed TS binary in tmux over a golden Unicode corpus.--Two tmux sessions per binary (each pane its own transcript):-- - CORE (gating): CJK prose past the editor width (the audit's crash- class), Thai/Lao AM rows in the editor AND in a rendered response with- a literal tab (the paint-time decomposition + tab cells), wide box- drawing, a pure-ASCII wrap regression, and editing states over- cluster-safe text (cursor steps, a whole-cluster backspace, a word- kill). Every state must frame-match.- - CLUSTERS (known-gap, non-gating): multi-char clusters — ZWJ families,- flag pairs, keycaps, skin tones, halfwidth voicing marks, Devanagari- spacing matras, zero-width chars. KNOWN GAP (root-caused 2026-09-22):- the Rust paint is a per-cell ratatui diff that assumes- grapheme-joined cells (family = 2 cells) while the box's tmux 3.2a- predates cluster joining, so the post-cluster MoveTo lands inside the- cluster's tmux footprint and overwrites its halves; the TS paint- writes whole rows so its capture degrades by column shift only. The- editor buffer, the submitted text, and the wrap/width model are- byte-exact (unit goldens + a raw-pty byte capture); the paint seam- needs a row-write backend (a follow-up paint lane). Cluster states- are compared and reported, but do not gate.--Both binaries run through the scripted faux provider; frames are captured-with escape sequences and compared through the `visual_parity.py` helpers-(`capture`/`normalize`/`diff_lines`). Exit code is non-zero when any CORE-state differs.--tmux rules: default socket only (`env -u TMUX`), euplane-* session names,-no kill-server; sessions are killed individually at the end.-"""--import argparse-import json-import os-import re-import shutil-import sys-import tempfile-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)-import visual_parity as vp # noqa: E402 (capture/normalize/diff helpers)--TS_SCRIPT_MODEL = vp.TS_SCRIPT_MODEL-# One narrow and one comfortable size: the narrow pane forces wrap-# opportunities in every corpus row; the comfortable one keeps long CJK runs-# wrapped and the rest whole.-SIZES = [("100", "30"), ("80", "24")]--WORKING_LABEL = re.compile(r"Thinking \u00b7|Waiting")--# The gating corpus: every row renders identically on both binaries.-CORE_PROMPTS = [- # CJK prose wider than the editor (the audit's panic class).- ("cjk", "这是一段很长的中文文本,超过了编辑器的宽度,会触发换行逻辑的边界情况,看看两边渲染是否一致。"),- # Thai/Lao AM (paint-time decomposition) in the editor AND in the- # response (which also carries a literal tab: three cells at paint).- ("thai_lao", "ทดสอบภาษาไทยำ สระอำ และພາສາລາວຳ ผ่าน"),- # Wide box drawing (single-codepoint wide chars).- ("box", "─━┏━━━━━┓─ box drawing row ┗━━━━━┛ ✅ done"),- # Pure-ASCII wrap regression (wrap opportunities must not change).- ("ascii", "the plain ascii wrapping sanity check paragraph spans several word boundaries and must wrap at the same opportunities on both binaries without any unicode involvement at all"),-]--# The known-gap cluster corpus (multi-char clusters; see the module doc).-CLUSTER_PROMPTS = [- ("emoji", "family 👨👩👧👦 flags 🇯🇵🇺🇸 keycap #️⃣ skin 👍🏽 more 👨👩👧👦 ok"),- ("clusters", "café café café ガギグゲ नमस्ते स्वागत है"),- ("zero_box", "─━┏━━━━━┓─ zero\u200bwidth ┗━━━━━┛ ✅ done"),- ("mixed", "hello 안녕하세요 world 안녕 你好 👨👩👧👦 mixed content wrapping row"),-]--# The editing-behavior line (typed, never submitted): BMP-safe clusters so-# the editing states gate — wide CJK, a precomposed accented char, and Thai-# (Mn marks cluster with their base and paint cleanly).-EDIT_LINE = "ab你好 café สวัสดี"--# Cluster-editing line (known-gap session): family emoji + combining marks.-EDIT_LINE_CLUSTERS = "ab你好 👨👩👧👦 café क"-LEFT_STEPS = 4-WORD_KILLS = 1--# The responses, one per submitted prompt (consumed in submit order). The-# Thai row's response carries the paint-normalization probes (AM + tab).-def core_responses():- responses = [- {"content": [{"type": "text", "text": f"ack {i}: confirmed."}]}- for i in range(1, len(CORE_PROMPTS) + 1)- ]- responses[1] = {- "content": [{"type": "text", "text": "ack 2: ทำงาน\ttabbed ผ่าน all done."}]- }- return responses---def cluster_responses():- return [- {"content": [{"type": "text", "text": f"ack {i}: confirmed."}]}- for i in range(1, len(CLUSTER_PROMPTS) + 1)- ]---def faux_script(responses):- return {- "engine": "faux",- "modelId": TS_SCRIPT_MODEL,- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 400,- "responses": responses,- }---def type_text(session, text):- """Type literal text into the editor pane (UTF-8 keystrokes)."""- vp.tmux("send-keys", "-t", session, "-l", text)---def wait_for_settled(session, needle, timeout=60):- """Wait for `needle` and a quiet loader row (the turn finished)."""- deadline = time.time() + timeout- while time.time() < deadline:- pane = vp.capture(session, escape=False)- if needle in pane and not WORKING_LABEL.search(pane):- return True- time.sleep(0.3)- raise TimeoutError(f"session {session} never settled on {needle!r}")---def wait_for_stability(session, timeout=30):- """Wait until the pane stops changing (known-gap cluster rows never show- their intact tail on the Rust side, so settle on frame stability)."""- deadline = time.time() + timeout- previous = vp.capture(session, escape=False)- while time.time() < deadline:- time.sleep(0.4)- current = vp.capture(session, escape=False)- if current == previous:- return True- previous = current- return False---def wait_for_typed(session, tail, timeout=30):- """Wait for the last chars of a typed row (typing lag tolerance).-- The pane shows the paint-normalized form, so a Thai/Lao AM char in the- tail matches its decomposed rendering too (normalizeTerminalOutput).- """- needles = [tail]- if "\u0e33" in tail or "\u0eb3" in tail:- normalized = tail.replace("\u0e33", "\u0e4d\u0e32").replace("\u0eb3", "\u0ecd\u0eb2")- needles.append(normalized)- deadline = time.time() + timeout- while time.time() < deadline:- pane = vp.capture(session, escape=False)- if any(needle in pane for needle in needles):- return True- time.sleep(0.2)- raise TimeoutError(f"session {session} never showed typed tail {tail!r}")---def run_session(- binary,- sandbox,- shared_cwd,- script_path,- size,- out_dir,- session_prefix,- ts_bin,- prompts,- edit_line,- exact_settle=True,-):- """Drive one binary through the corpus, capturing each frame."""- width, height = size- session = f"euplane-{session_prefix}-{binary}-{width}x{height}"- vp.tmux("kill-session", "-t", session, check=False)- vp.tmux("new-session", "-d", "-s", session, "-x", width, "-y", height, "-c", shared_cwd)- env = (- f"HOME={sandbox['home']} "- f"TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"PRIME_AGENT_FAUX_SCRIPT={script_path} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- if binary == "ts":- # The ts side defaults to the PATH binary but the box install is a- # Rust dogfood build — pass the deployed TS release explicitly- # (`--ts-bin`), like the other harnesses.- command = (- f"{ts_bin} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {TS_SCRIPT_MODEL}"- )- else:- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)), "..", "target", "debug", "prime-agent"- ),- )- package_dir = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- command = (- f"PI_PACKAGE_DIR={package_dir} "- f"{rust} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {TS_SCRIPT_MODEL}"- )- vp.tmux("send-keys", "-t", session, f"{env} {command}", "Enter")-- frames = {}- try:- # (a) fresh start: splash + empty editor.- vp.wait_for(session, "Collapsed mode", timeout=40)- time.sleep(1.0)- frames["a_fresh_start"] = vp.capture(session)-- # (b) the corpus: type each row, capture the editor wrap mid-edit,- # then submit and capture the settled post-turn frame (user echo +- # assistant render).- for idx, (name, text) in enumerate(prompts):- type_text(session, text)- if exact_settle:- wait_for_typed(session, text[-6:])- else:- wait_for_stability(session)- time.sleep(0.5)- frames[f"b_{name}_editor"] = vp.capture(session)- vp.tmux("send-keys", "-t", session, "Enter")- wait_for_settled(session, f"ack {idx + 1}:")- time.sleep(1.0)- frames[f"c_{name}_settled"] = vp.capture(session)-- # (d) editing behavior over clusters: cursor-left steps across- # cluster boundaries, a backspace over a whole cluster, a word-kill- # over the run, then deleteToLineStart clears the draft.- type_text(session, edit_line)- if exact_settle:- wait_for_typed(session, edit_line[-6:])- else:- wait_for_stability(session)- time.sleep(0.5)- frames["d_edit_typed"] = vp.capture(session)- for _ in range(LEFT_STEPS):- vp.tmux("send-keys", "-t", session, "Left")- time.sleep(0.6)- frames["e_cursor_left"] = vp.capture(session)- vp.tmux("send-keys", "-t", session, "BSpace")- time.sleep(0.6)- frames["f_backspace_cluster"] = vp.capture(session)- for _ in range(WORD_KILLS):- vp.tmux("send-keys", "-t", session, "C-w")- time.sleep(0.6)- frames["g_word_kill"] = vp.capture(session)- vp.tmux("send-keys", "-t", session, "C-u")- time.sleep(0.6)- frames["h_line_cleared"] = vp.capture(session)-- for state, frame in frames.items():- with open(- os.path.join(out_dir, f"{binary}-{width}x{height}-{state}.ansi"), "w"- ) as f:- f.write(frame)- finally:- # A wait timeout must not leak the detached pane (and the shell and- # daemon inside it) past the run (Macroscope, PR #2600). The kill is- # idempotent cleanup: a session that already died (binary crash, or- # the settle timeout fired after the pane vanished) must not raise- # and mask the original error.- vp.tmux("kill-session", "-t", session, check=False)- return frames---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--keep", action="store_true", help="keep the sandbox dir")- parser.add_argument(- "--out", default=None, help="captures directory (default: a fresh temp dir)"- )- parser.add_argument("--binary", choices=("ts", "rust"), default=None, help="run one side only")- parser.add_argument("--sizes", default=",".join(f"{w}x{h}" for w, h in SIZES))- parser.add_argument(- "--ts-bin",- default="prime-agent",- help="the ts-side binary (default: the PATH prime-agent)",- )- parser.add_argument(- "--session-prefix",- default="eu",- help="tmux session-name prefix (euplane-<prefix>-<binary>-WxH)",- )- args = parser.parse_args()-- import visual_parity as vpm-- sizes = []- for entry in args.sizes.split(","):- width, height = entry.split("x")- sizes.append((width, height))-- # Fail fast before any launch: a non-TS `prime-agent` (the box PATH- # install is a Rust dogfood build of this repo) plays a Rust build as- # the "ts" side and reports false divergences.- if args.binary in (None, "ts"):- ts_identity.assert_ts_side_is_the_ts_product(args.ts_bin)-- base = tempfile.mkdtemp(prefix="eu-parity-")- out_dir = args.out or tempfile.mkdtemp(prefix="editor-unicode-captures-")- os.makedirs(out_dir, exist_ok=True)-- shared_cwd, _, sandboxes = vpm.prepare_sandbox(base)-- failures = []- known_gaps = []- try:- if args.binary:- run_session(- args.binary,- sandboxes[args.binary],- shared_cwd,- core_script_path(base),- sizes[0],- out_dir,- args.session_prefix,- args.ts_bin,- CORE_PROMPTS,- EDIT_LINE,- )- print(f"captures for {args.binary} in {out_dir}")- return 0- for size in sizes:- for kind, prompts, edit_line, responses in (- ("core", CORE_PROMPTS, EDIT_LINE, core_responses()),- ("clusters", CLUSTER_PROMPTS, EDIT_LINE_CLUSTERS, cluster_responses()),- ):- script_path = os.path.join(base, f"faux-{kind}.json")- with open(script_path, "w") as f:- json.dump(faux_script(responses), f, indent=2)- ts_frames = run_session(- "ts",- sandboxes["ts"],- shared_cwd,- script_path,- size,- out_dir,- f"{args.session_prefix}-{kind}",- args.ts_bin,- prompts,- edit_line,- exact_settle=(kind == "core"),- )- rust_frames = run_session(- "rust",- sandboxes["rust"],- shared_cwd,- script_path,- size,- out_dir,- f"{args.session_prefix}-{kind}",- args.ts_bin,- prompts,- edit_line,- exact_settle=(kind == "core"),- )- for state in ts_frames:- name = f"{kind}/{state}-{size[0]}x{size[1]}"- if state not in rust_frames:- (failures if kind == "core" else known_gaps).append(name)- print(f"FAIL {name} (absent on rust)")- continue- ts_norm = vp.normalize(ts_frames[state], base)- rust_norm = vp.normalize(rust_frames[state], base)- if ts_norm == rust_norm:- print(f"PASS {name}")- else:- print(f"{'FAIL' if kind == 'core' else 'GAP'} {name}")- report = os.path.join(- out_dir, f"diff-{kind}-{state}-{size[0]}x{size[1]}.txt"- )- with open(report, "w") as f:- f.write(vp.diff_lines(ts_norm, rust_norm))- print(f" diff: {report}")- (failures if kind == "core" else known_gaps).append(name)- finally:- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if not args.keep:- shutil.rmtree(base, ignore_errors=True)- if known_gaps:- print(- f"{len(known_gaps)} cluster state(s) differ (KNOWN GAP: tmux 3.2a "- "predates grapheme joining; see the module doc) — non-gating"- )- if failures:- print(f"{len(failures)} CORE state(s) differ; captures in {out_dir}")- return 1- print("all CORE states match; captures in", out_dir)- return 0---def core_script_path(base):- path = os.path.join(base, "faux-core.json")- with open(path, "w") as f:- json.dump(faux_script(core_responses()), f, indent=2)- return path---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/force_shutdown_parity.py b/scripts/force_shutdown_parity.pydeleted file mode 100644index e576e3d956..0000000000--- a/scripts/force_shutdown_parity.py+++ /dev/null@@ -1,219 +0,0 @@-#!/usr/bin/env python3-"""Force-shutdown parity verifier: `shutdown --force` against a live daemon-under both binaries (R6's audit lane).--For each binary (TS via --ts-bin, Rust via --rust-bin) this harness:-- 1. boots the interactive TUI in a raw pty with a sandboxed state root- long enough for the CLI to spawn its background daemon;- 2. leaves the daemon alive with a clean double-Ctrl+C exit;- 3. runs `shutdown --force --json` and `shutdown --force` (text) against- the same state root and captures every byte;- 4. runs `shutdown --json` without --force and captures the- confirmation-required JSON failure.--The JSON reports are compared after pids and socket paths are normalized:-both binaries must produce the same `{stopped, failed}` shape with the-same action strings, and the same text report. The one deliberate-divergence (a daemon that SURVIVES SIGKILL is reported as failed on the-Rust side while TS reports it stopped) cannot occur against a killable-daemon, so this harness pins the healthy path; the survived path is a-documented hardening divergence (see the PR/PORTING notes).--Exit code is non-zero when any stage check fails on either binary.-"""--import argparse-import json-import os-import pty-import re-import select-import struct-import subprocess-import sys-import tempfile-import time-import fcntl-import termios--WIDTH, HEIGHT = 120, 36--CONFIRMATION_ERROR = (- "confirmation required; use \"prime-agent shutdown --force --json\""-)---def sandbox(base):- home = os.path.join(base, "home")- agent = os.path.join(base, "agent")- tmp = os.path.join(base, "tmp")- for d in (home, agent, tmp):- os.makedirs(d)- return {"home": home, "agent": agent, "tmp": tmp}---def env_for(sb):- env = dict(os.environ)- env.update(- {- "HOME": sb["home"],- "TMPDIR": sb["tmp"],- "PRIME_AGENT_CODING_AGENT_DIR": sb["agent"],- "PRIME_AGENT_DISABLE_ANALYTICS": "1",- "TERM": "xterm-256color",- }- )- return env---def pty_boot(binary, sb, seconds):- """Boot the TUI under a raw pty until its daemon socket binds (polled,- not fixed-time: a loaded machine can take many seconds to spawn the- daemon), then leave with a clean double-Ctrl+C."""- master, slave = pty.openpty()- fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", HEIGHT, WIDTH, 0, 0))- env = env_for(sb)- sock = os.path.join(sb["agent"], "daemon.sock")- proc = subprocess.Popen(- [binary, "--daemon-socket", sock],- stdin=slave, stdout=slave, stderr=slave, env=env,- )- os.close(slave)- deadline = time.time() + seconds- while time.time() < deadline:- if os.path.exists(sock):- break- r, _, _ = select.select([master], [], [], 0.2)- if master in r:- try:- os.read(master, 65536)- except OSError:- break- time.sleep(2.0)- os.write(master, b"\x03")- time.sleep(1.0)- os.write(master, b"\x03")- time.sleep(2.0)- try:- proc.wait(5)- except Exception:- proc.kill()- os.close(master)- return os.path.exists(sock)---def run_cli(binary, sb, args):- """Run one CLI command on the plain pipes; return stdout/stderr."""- out = subprocess.run(- [binary] + args,- capture_output=True,- text=True,- env=env_for(sb),- timeout=120,- )- return out.returncode, out.stdout, out.stderr---def normalize(text):- """Erase pids and sandbox paths so runs are comparable."""- text = re.sub(r"\b\d{2,}\b", "<pid>", text)- text = re.sub(r"/tmp/[^ \"',\n]+", "<tmp>", text)- return text---def scenario(binary, base, name, attempts=2):- """One binary through the three scenarios. `attempts` rides the- environmental flakiness of a shared machine (a slow daemon spawn or a- TS-side admission race), never the compared outputs: every attempt- runs the full scenario and the first fully-clean one wins."""- results = {}- for attempt in range(attempts):- suffix = "" if attempt == 0 else f"-retry{attempt}"- results = scenario_once(binary, base, name + suffix)- clean = (- "boot" not in results- and not results.get("errors")- and results.get("json", {}).get("code") == 0- and results.get("json", {}).get("out")- and results.get("text", {}).get("code") == 0- and results.get("text", {}).get("out")- and results.get("confirm", {}).get("code") == 1- )- if clean:- return results- results["attempt"] = attempt- return results---def scenario_once(binary, base, name):- sb = sandbox(os.path.join(base, name))- results = {}- if not pty_boot(binary, sb, 30):- results["boot"] = "daemon socket never appeared"- return results- # JSON mode against the live daemon.- code, out, err = run_cli(binary, sb, ["shutdown", "--force", "--json"])- results["json"] = {"code": code, "out": normalize(out.strip()), "err": normalize(err.strip())}- # Text mode needs a fresh daemon.- sb2 = sandbox(os.path.join(base, name + "2"))- if pty_boot(binary, sb2, 30):- code, out, err = run_cli(binary, sb2, ["shutdown", "--force"])- results["text"] = {"code": code, "out": normalize(out.strip())}- # The confirmation error (JSON without --force, stdin not a TTY).- sb3 = sandbox(os.path.join(base, name + "3"))- if pty_boot(binary, sb3, 30):- code, out, err = run_cli(binary, sb3, ["shutdown", "--json"])- results["confirm"] = {"code": code, "out": normalize(out.strip())}- # The confirmation refusal is a pinned invariant (TS text, same- # quote style): JSON without --force over a non-tty stdin must- # carry it as the failed entry's reason.- reasons = [- entry.get("reason", "")- for entry in json.loads(out).get("failed", [])- ]- if CONFIRMATION_ERROR not in reasons:- results.setdefault("errors", []).append(- "confirmation error string missing from the failed reasons"- )- return results---def main():- parser = argparse.ArgumentParser()- parser.add_argument("--ts-bin", required=True)- parser.add_argument("--rust-bin", required=True)- parser.add_argument("--keep", action="store_true")- args = parser.parse_args()-- base = tempfile.mkdtemp(prefix="force-shutdown-parity-")- ts = scenario(args.ts_bin, base, "ts")- rust = scenario(args.rust_bin, base, "rust")- print("== TS ==")- print(json.dumps(ts, indent=2))- print("== RUST ==")- print(json.dumps(rust, indent=2))-- failures = []- for side, results in (("ts", ts), ("rust", rust)):- for error in results.get("errors", []):- failures.append(f"{side} side: {error}")- for mode in ("json", "text", "confirm"):- if mode not in ts or mode not in rust:- failures.append(f"{mode} missing on one side")- continue- if ts[mode] != rust[mode]:- failures.append(f"{mode} outputs differ:\n TS: {ts[mode]}\n RUST: {rust[mode]}")- if failures:- print("FAIL")- for failure in failures:- print(failure)- return 1- print("PASS: json/text/confirm outputs identical after normalization")- if not args.keep:- subprocess.run(["rm", "-rf", base])- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/heartbeat-fire-runs/rust/01-agent-heartbeat-turn.json b/scripts/heartbeat-fire-runs/rust/01-agent-heartbeat-turn.jsondeleted file mode 100644index 48b023caab..0000000000--- a/scripts/heartbeat-fire-runs/rust/01-agent-heartbeat-turn.json+++ /dev/null@@ -1,6 +0,0 @@-{- "id": "hb-agent",- "type": "response",- "command": "prompt_and_wait",- "success": true-}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/rust/02-fired-catalog.json b/scripts/heartbeat-fire-runs/rust/02-fired-catalog.jsondeleted file mode 100644index e1bcc748ca..0000000000--- a/scripts/heartbeat-fire-runs/rust/02-fired-catalog.json+++ /dev/null@@ -1,28 +0,0 @@-[- {- "job": {- "id": "e8692e75-e60f-436a-ba5c-c5b57e9f6a4a",- "status": "active",- "source": "rlm_heartbeat",- "deliveryMode": "steer",- "activeSessionId": "6976ebac942d",- "sessionId": "01a0c5da-30de-765e-8f59-5bb56234b693",- "sessionFile": "/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/agent/sessions/01a0c5da-30de-765e-8f59-5bb56234b693.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/work",- "label": "hb-fire",- "prompt": "agent heartbeat fire probe instruction",- "schedule": {- "kind": "interval",- "expression": "every 30s",- "intervalMs": 30000- },- "createdAt": "2026-09-21T21:23:26.370Z",- "updatedAt": "2026-09-21T21:23:56.553Z",- "nextRunAt": "2026-09-21T21:24:26.371Z",- "lastRunAt": "2026-09-21T21:23:56.553Z",- "runCount": 1- },- "sessionName": "hb-fire-verifier",- "firstMessage": "verifier seed turn"- }-]\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/rust/03-transcript-hit.txt b/scripts/heartbeat-fire-runs/rust/03-transcript-hit.txtdeleted file mode 100644index 01d52f1e25..0000000000--- a/scripts/heartbeat-fire-runs/rust/03-transcript-hit.txt+++ /dev/null@@ -1,2 +0,0 @@-01a0c5da-30de-765e-8f59-5bb56234b693.jsonl-instruction: agent heartbeat fire probe instruction\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/rust/agent/auth.json b/scripts/heartbeat-fire-runs/rust/agent/auth.jsondeleted file mode 100644index 9e26dfeeb6..0000000000--- a/scripts/heartbeat-fire-runs/rust/agent/auth.json+++ /dev/null@@ -1 +0,0 @@-{}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/rust/agent/daemon-workers/f186383144c5/6976ebac942d.recovery.jsonl b/scripts/heartbeat-fire-runs/rust/agent/daemon-workers/f186383144c5/6976ebac942d.recovery.jsonldeleted file mode 100644index 7b79ba6b25..0000000000--- a/scripts/heartbeat-fire-runs/rust/agent/daemon-workers/f186383144c5/6976ebac942d.recovery.jsonl+++ /dev/null@@ -1,7 +0,0 @@-{"activeSessionId":"6976ebac942d","sessionId":"01a0c5da-30de-765e-8f59-5bb56234b693","sessionFile":"/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/agent/sessions/01a0c5da-30de-765e-8f59-5bb56234b693.jsonl","busy":true,"operation":"create","recordedAt":"2026-09-21T21:23:26.077Z"}-{"version":1,"type":"queue_snapshot","active_session_id":"6976ebac942d","steering":["verifier seed turn"],"follow_up":[],"recorded_at":"2026-09-21T21:23:26.113Z"}-{"version":1,"type":"queue_snapshot","active_session_id":"6976ebac942d","steering":[],"follow_up":[],"recorded_at":"2026-09-21T21:23:26.279Z"}-{"version":1,"type":"queue_snapshot","active_session_id":"6976ebac942d","steering":["create the agent heartbeat"],"follow_up":[],"recorded_at":"2026-09-21T21:23:26.284Z"}-{"version":1,"type":"queue_snapshot","active_session_id":"6976ebac942d","steering":[],"follow_up":[],"recorded_at":"2026-09-21T21:23:26.462Z"}-{"version":1,"type":"queue_snapshot","active_session_id":"6976ebac942d","steering":[],"follow_up":[],"recorded_at":"2026-09-21T21:23:56.552Z"}-{"activeSessionId":"6976ebac942d","sessionId":"01a0c5da-30de-765e-8f59-5bb56234b693","sessionFile":"/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/agent/sessions/01a0c5da-30de-765e-8f59-5bb56234b693.jsonl","busy":false,"operation":"shutdown","recordedAt":"2026-09-21T21:23:56.927Z"}diff --git a/scripts/heartbeat-fire-runs/rust/agent/daemon-workers/f186383144c5/supervisor-config b/scripts/heartbeat-fire-runs/rust/agent/daemon-workers/f186383144c5/supervisor-configdeleted file mode 100644index dcca85f237..0000000000--- a/scripts/heartbeat-fire-runs/rust/agent/daemon-workers/f186383144c5/supervisor-config+++ /dev/null@@ -1,5 +0,0 @@-{- "version": 1,- "socketPath": "/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/daemon.sock",- "defaultSessionDir": "/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/agent/sessions"-}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/rust/agent/logs/daemon.sock.f1863831.log b/scripts/heartbeat-fire-runs/rust/agent/logs/daemon.sock.f1863831.logdeleted file mode 100644index a12265fbd8..0000000000--- a/scripts/heartbeat-fire-runs/rust/agent/logs/daemon.sock.f1863831.log+++ /dev/null@@ -1,3 +0,0 @@-supervisor started pid 2845572-[2026-09-21T21:23:25.994Z] session worker 6976ebac942d registered (epoch 1, pid 2845577)-[2026-09-21T21:23:26.084Z] session worker 6976ebac942d re-registered (epoch 2, pid 2845577)diff --git a/scripts/heartbeat-fire-runs/rust/agent/models.json b/scripts/heartbeat-fire-runs/rust/agent/models.jsondeleted file mode 100644index 99772a0d2c..0000000000--- a/scripts/heartbeat-fire-runs/rust/agent/models.json+++ /dev/null@@ -1,19 +0,0 @@-{- "providers": {- "prime-inference": {- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:34151/v1",- "apiKey": "sk-battery",- "models": [- {- "id": "mock-1",- "name": "Mock 1",- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:34151/v1",- "contextWindow": 128000,- "maxTokens": 4096- }- ]- }- }-}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/rust/agent/prime-inference-models-cache.json b/scripts/heartbeat-fire-runs/rust/agent/prime-inference-models-cache.jsondeleted file mode 100644index 2affae47b1..0000000000--- a/scripts/heartbeat-fire-runs/rust/agent/prime-inference-models-cache.json+++ /dev/null@@ -1 +0,0 @@-{"object":"list","data":[{"id":"alibaba/qwen3.5-flash","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.568539+00:00"},"specs":null},{"id":"alibaba/qwen3.7-max","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":3.75,"output_usd_per_mtok":11.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.639598+00:00"},"specs":null},{"id":"alibaba/qwen3.7-plus","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.717208+00:00"},"specs":null},{"id":"alibaba/qwen3.8-flash","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.225,"output_usd_per_mtok":0.705,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.787469+00:00"},"specs":null},{"id":"anthropic/claude-fable-5","object":"model","owned_by":"","created":1783031626,"display_name":"Claude Fable 5","pricing":{"input_usd_per_mtok":10.0,"output_usd_per_mtok":50.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-02T22:33:46.495072+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-fable-5.1","object":"model","owned_by":"","created":1788556514,"display_name":"Claude Fable 5.1","pricing":{"input_usd_per_mtok":10.0,"output_usd_per_mtok":50.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.113341+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-haiku-4.5","object":"model","owned_by":"","created":1761030860,"display_name":"Claude Haiku 4.5","pricing":{"input_usd_per_mtok":1.0,"output_usd_per_mtok":5.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:20.826034+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-opus-4.1","object":"model","owned_by":"","created":1761157329,"display_name":"Claude Opus 4.1","pricing":{"input_usd_per_mtok":15.0,"output_usd_per_mtok":75.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-22T18:22:09.605939+00:00"},"specs":{"context_window":200000,"max_output_tokens":32000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-opus-4.5","object":"model","owned_by":"","created":1764746904,"display_name":"Claude Opus 4.5","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":25.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-03T07:28:24.760458+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","verbosity"]},{"id":"anthropic/claude-opus-4.6","object":"model","owned_by":"","created":1772938679,"display_name":"Claude Opus 4.6","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":25.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-08T02:57:59.615639+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p","verbosity"]},{"id":"anthropic/claude-opus-4.7","object":"model","owned_by":"","created":1776679634,"display_name":"Claude Opus 4.7","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":25.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-20T10:07:14.028142+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-opus-4.8","object":"model","owned_by":"","created":1780660082,"display_name":"Claude Opus 4.8","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":25.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-05T11:48:02.246650+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-opus-5","object":"model","owned_by":"","created":1784919442,"display_name":"Claude Opus 5","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":25.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-24T18:57:22.868734+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-sonnet-4","object":"model","owned_by":"","created":1761029716,"display_name":"Claude Sonnet 4","pricing":{"input_usd_per_mtok":3.0,"output_usd_per_mtok":15.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:16.611551+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-sonnet-4.5","object":"model","owned_by":"","created":1759212031,"display_name":"Claude Sonnet 4.5","pricing":{"input_usd_per_mtok":3.0,"output_usd_per_mtok":15.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T06:00:31.866675+00:00"},"specs":{"context_window":1000000,"max_output_tokens":64000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-sonnet-4.6","object":"model","owned_by":"","created":1772054770,"display_name":"Claude Sonnet 4.6","pricing":{"input_usd_per_mtok":3.0,"output_usd_per_mtok":15.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:10.104879+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","medium","low"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p","verbosity"]},{"id":"anthropic/claude-sonnet-5","object":"model","owned_by":"","created":1783031448,"display_name":"Claude Sonnet 5","pricing":{"input_usd_per_mtok":2.0,"output_usd_per_mtok":10.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-02T22:30:48.220566+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"deepseek/deepseek-chat-v3.1","object":"model","owned_by":"","created":1761029725,"display_name":"DeepSeek V3.1","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":1.7,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:25.583563+00:00"},"specs":{"context_window":163840,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v3.1-terminus","object":"model","owned_by":"","created":1759198118,"display_name":"DeepSeek V3.1 Terminus","pricing":{"input_usd_per_mtok":0.27,"output_usd_per_mtok":1.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:08:38.000459+00:00"},"specs":{"context_window":163840,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"deepseek/deepseek-v3.2","object":"model","owned_by":"","created":1764658428,"display_name":"DeepSeek V3.2","pricing":{"input_usd_per_mtok":0.3705,"output_usd_per_mtok":1.1115,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-02T06:53:48.223623+00:00"},"specs":{"context_window":163840,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":false,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v3.2-exp","object":"model","owned_by":"","created":1759198146,"display_name":"DeepSeek V3.2 Exp","pricing":{"input_usd_per_mtok":0.27,"output_usd_per_mtok":0.41,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:09:06.170541+00:00"},"specs":{"context_window":163840,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4.1-flash","object":"model","owned_by":"","created":1789152253,"display_name":"DeepSeek V4.1 Flash","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-11T18:44:13.104931+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-flash","object":"model","owned_by":"","created":1778785963,"display_name":"DeepSeek V4 Flash 0423","pricing":{"input_usd_per_mtok":0.44,"output_usd_per_mtok":1.32,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T19:12:43.449839+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_completion_tokens","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-flash-0731","object":"model","owned_by":"","created":1785777617,"display_name":"DeepSeek V4 Flash 0731","pricing":{"input_usd_per_mtok":0.44,"output_usd_per_mtok":1.32,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T17:20:17.849313+00:00"},"specs":{"context_window":1310720,"max_output_tokens":943718,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-pro","object":"model","owned_by":"","created":1778785932,"display_name":"DeepSeek V4 Pro 0423","pricing":{"input_usd_per_mtok":1.91,"output_usd_per_mtok":3.83,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T19:12:12.010236+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_completion_tokens","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"google/gemini-2.5-flash","object":"model","owned_by":"","created":1761029715,"display_name":"Gemini 2.5 Flash","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":2.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:15.585176+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65535,"modalities":{"input":["file","image","text","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-2.5-flash-lite","object":"model","owned_by":"","created":1761029721,"display_name":"Gemini 2.5 Flash Lite","pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:21.403298+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65535,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-2.5-pro","object":"model","owned_by":"","created":1761029717,"display_name":"Gemini 2.5 Pro","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:17.621295+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.1-pro-preview","object":"model","owned_by":"","created":1772054806,"display_name":"Gemini 3.1 Pro Preview","pricing":{"input_usd_per_mtok":2.0,"output_usd_per_mtok":12.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:46.169413+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["audio","file","image","text","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.5-flash","object":"model","owned_by":"","created":1781958981,"display_name":"Gemini 3.5 Flash","pricing":{"input_usd_per_mtok":1.5,"output_usd_per_mtok":9.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-20T12:36:21.024091+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.6-flash","object":"model","owned_by":"","created":1784918138,"display_name":"Gemini 3.6 Flash","pricing":{"input_usd_per_mtok":1.5,"output_usd_per_mtok":7.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-24T18:35:38.706927+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.7-flash","object":"model","owned_by":"","created":1787848124,"display_name":"Gemini 3.7 Flash","pricing":{"input_usd_per_mtok":1.35,"output_usd_per_mtok":6.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-27T16:28:44.601830+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.8-flash","object":"model","owned_by":"","created":1788556514,"display_name":"Gemini 3.8 Flash","pricing":{"input_usd_per_mtok":0.75,"output_usd_per_mtok":3.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.212597+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3-flash-preview","object":"model","owned_by":"","created":1766202374,"display_name":"Gemini 3 Flash Preview","pricing":{"input_usd_per_mtok":0.5,"output_usd_per_mtok":3.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-20T03:46:14.305378+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemma-3-27b-it","object":"model","owned_by":"","created":1761030851,"display_name":"Gemma 3 27B","pricing":{"input_usd_per_mtok":0.119,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:11.952792+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"meta-llama/Llama-3.2-1B-Instruct","object":"model","owned_by":"","created":1771939296,"display_name":"Llama 3.2 1B Instruct","pricing":{"input_usd_per_mtok":0.027,"output_usd_per_mtok":0.201,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T13:21:36.921319+00:00"},"specs":{"context_window":60000,"max_output_tokens":54000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","max_tokens","min_p","presence_penalty","repetition_penalty","seed","stop","temperature","top_k","top_p"]},{"id":"meta-llama/Llama-3.2-3B-Instruct","object":"model","owned_by":"","created":1771939312,"display_name":"Llama 3.2 3B Instruct","pricing":{"input_usd_per_mtok":0.0509,"output_usd_per_mtok":0.335,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T13:21:52.649872+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","seed","stop","structured_outputs","temperature","top_k","top_logprobs","top_p"]},{"id":"meta-llama/llama-3.3-70b-instruct","object":"model","owned_by":"","created":1759196298,"display_name":"Llama 3.3 70B Instruct","pricing":{"input_usd_per_mtok":1.04,"output_usd_per_mtok":2.253,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T01:38:18.545960+00:00"},"specs":{"context_window":131072,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"meta-llama/llama-4-maverick","object":"model","owned_by":"","created":1761030850,"display_name":"Llama 4 Maverick","pricing":{"input_usd_per_mtok":0.35,"output_usd_per_mtok":1.15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:10.101027+00:00"},"specs":{"context_window":1048576,"max_output_tokens":16384,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m2.5","object":"model","owned_by":"","created":1771374795,"display_name":"MiniMax M2.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-18T00:33:15.739871+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m2.7","object":"model","owned_by":"","created":1775779870,"display_name":"MiniMax M2.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:10.312006+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m3","object":"model","owned_by":"","created":1780311536,"display_name":"MiniMax M3","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-01T10:58:56.335485+00:00"},"specs":{"context_window":1048576,"max_output_tokens":512000,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"mistralai/mistral-large-2512","object":"model","owned_by":"","created":1764689752,"display_name":null,"pricing":{"input_usd_per_mtok":0.5,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-02T15:35:52.296516+00:00"},"specs":null},{"id":"mistralai/mistral-nemo","object":"model","owned_by":"","created":1761030857,"display_name":"Mistral Nemo","pricing":{"input_usd_per_mtok":0.165,"output_usd_per_mtok":0.17,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:17.801302+00:00"},"specs":{"context_window":131072,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"mistralai/mistral-small-2603","object":"model","owned_by":"","created":1775779872,"display_name":"Mistral Small 4","pricing":{"input_usd_per_mtok":0.165,"output_usd_per_mtok":0.66,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:12.604966+00:00"},"specs":{"context_window":262144,"max_output_tokens":209715,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","none"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"mistralai/mixtral-8x22b-instruct","object":"model","owned_by":"","created":1759198003,"display_name":"Mixtral 8x22B Instruct","pricing":{"input_usd_per_mtok":2.2,"output_usd_per_mtok":6.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:06:43.614656+00:00"},"specs":{"context_window":65536,"max_output_tokens":52428,"modalities":{"input":["text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","max_tokens","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"moonshotai/kimi-k2-0905","object":"model","owned_by":"","created":1759907126,"display_name":"Kimi K2 0905","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:26.057085+00:00"},"specs":{"context_window":262144,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"moonshotai/kimi-k2.5","object":"model","owned_by":"","created":1769800671,"display_name":"Kimi K2.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-30T19:17:51.210047+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k2.6","object":"model","owned_by":"","created":1776733288,"display_name":"Kimi K2.6","pricing":{"input_usd_per_mtok":0.95,"output_usd_per_mtok":4.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-21T01:01:28.804384+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k2.7-code","object":"model","owned_by":"","created":1781282432,"display_name":"Kimi K2.7 Code","pricing":{"input_usd_per_mtok":1.9,"output_usd_per_mtok":8.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-12T16:40:32.168235+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k3","object":"model","owned_by":"","created":1784248110,"display_name":"Kimi K3","pricing":{"input_usd_per_mtok":3.45,"output_usd_per_mtok":17.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-17T00:28:30.162170+00:00"},"specs":{"context_window":1048576,"max_output_tokens":943718,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"max","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"nvidia/nemotron-3-nano-30b-a3b","object":"model","owned_by":"","created":1775779886,"display_name":"Nemotron 3 Nano 30B A3B","pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.24,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:26.952299+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"openai/gpt-4.1","object":"model","owned_by":"","created":1759401802,"display_name":"GPT-4.1","pricing":{"input_usd_per_mtok":2.0,"output_usd_per_mtok":8.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:22.496353+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4.1-mini","object":"model","owned_by":"","created":1759401806,"display_name":"GPT-4.1 Mini","pricing":{"input_usd_per_mtok":0.4,"output_usd_per_mtok":1.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:26.911016+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4.1-nano","object":"model","owned_by":"","created":1759401808,"display_name":"GPT-4.1 Nano","pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:28.011794+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4o","object":"model","owned_by":"","created":1761029734,"display_name":"GPT-4o","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":10.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:34.447350+00:00"},"specs":{"context_window":128000,"max_output_tokens":16384,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_completion_tokens","max_tokens","prediction","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p","web_search_options"]},{"id":"openai/gpt-4o-mini","object":"model","owned_by":"","created":1761029722,"display_name":"GPT-4o-mini","pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:22.331052+00:00"},"specs":{"context_window":128000,"max_output_tokens":16384,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_completion_tokens","max_tokens","prediction","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p","web_search_options"]},{"id":"openai/gpt-5","object":"model","owned_by":"","created":1759211784,"display_name":"GPT-5","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T05:56:24.831437+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.1","object":"model","owned_by":"","created":1763426084,"display_name":"GPT-5.1","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-11-18T00:34:44.949671+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","none"],"default_effort":"none","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.2","object":"model","owned_by":"","created":1765611176,"display_name":"GPT-5.2","pricing":{"input_usd_per_mtok":1.75,"output_usd_per_mtok":14.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-13T07:32:56.544785+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.2-pro","object":"model","owned_by":"","created":1765611177,"display_name":"GPT-5.2 Pro","pricing":{"input_usd_per_mtok":21.0,"output_usd_per_mtok":168.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-13T07:32:57.583455+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.3-codex","object":"model","owned_by":"","created":1772054791,"display_name":"GPT-5.3-Codex","pricing":{"input_usd_per_mtok":1.75,"output_usd_per_mtok":14.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:31.496994+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4","object":"model","owned_by":"","created":1773713673,"display_name":"GPT-5.4","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-17T02:14:33.278960+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-mini","object":"model","owned_by":"","created":1775779863,"display_name":"GPT-5.4 Mini","pricing":{"input_usd_per_mtok":0.75,"output_usd_per_mtok":4.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:03.742760+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-nano","object":"model","owned_by":"","created":1775779866,"display_name":"GPT-5.4 Nano","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:06.153745+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-pro","object":"model","owned_by":"","created":1773713674,"display_name":"GPT-5.4 Pro","pricing":{"input_usd_per_mtok":30.0,"output_usd_per_mtok":180.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-17T02:14:34.995439+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.5","object":"model","owned_by":"","created":1777306094,"display_name":"GPT-5.5","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":30.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-27T16:08:14.065946+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6","object":"model","owned_by":"","created":1783751214,"display_name":null,"pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":30.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:26:54.495544+00:00"},"specs":null},{"id":"openai/gpt-5.6-luna","object":"model","owned_by":"","created":1783751321,"display_name":"GPT-5.6 Luna","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:41.639902+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-luna-pro","object":"model","owned_by":"","created":1783751322,"display_name":"GPT-5.6 Luna Pro","pricing":{"input_usd_per_mtok":1.0,"output_usd_per_mtok":6.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:42.459149+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-sol","object":"model","owned_by":"","created":1783751318,"display_name":"GPT-5.6 Sol","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":30.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:38.262869+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-sol-pro","object":"model","owned_by":"","created":1783751319,"display_name":"GPT-5.6 Sol Pro","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":30.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:39.039507+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-terra","object":"model","owned_by":"","created":1783751319,"display_name":"GPT-5.6 Terra","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:39.851751+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-terra-pro","object":"model","owned_by":"","created":1783751320,"display_name":"GPT-5.6 Terra Pro","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:40.628845+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5-mini","object":"model","owned_by":"","created":1759401800,"display_name":"GPT-5 Mini","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":2.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:20.338354+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5-nano","object":"model","owned_by":"","created":1759401801,"display_name":"GPT-5 Nano","pricing":{"input_usd_per_mtok":0.05,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:21.418908+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-6-astra","object":"model","owned_by":"","created":1788556514,"display_name":"GPT-6 Astra","pricing":{"input_usd_per_mtok":10.0,"output_usd_per_mtok":50.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.299026+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-oss-120b","object":"model","owned_by":"","created":1760042083,"display_name":"gpt-oss-120b","pricing":{"input_usd_per_mtok":0.35,"output_usd_per_mtok":0.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-09T20:34:43.236004+00:00"},"specs":{"context_window":131072,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"openai/gpt-oss-20b","object":"model","owned_by":"","created":1761030856,"display_name":"gpt-oss-20b","pricing":{"input_usd_per_mtok":0.07,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:16.897238+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"poolside/laguna-s-2.1","object":"model","owned_by":"","created":1785726826,"display_name":"Laguna S 2.1","pricing":{"input_usd_per_mtok":0.09,"output_usd_per_mtok":0.18,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T03:13:46.654853+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","temperature","tool_choice","tools"]},{"id":"poolside/laguna-xs-2.1","object":"model","owned_by":"","created":1785726826,"display_name":"Laguna XS 2.1","pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.12,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T03:13:46.740724+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","temperature","tool_choice","tools"]},{"id":"qwen/qwen3-235b-a22b-2507","object":"model","owned_by":"","created":1759198117,"display_name":"Qwen3 235B A22B Instruct 2507","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:08:37.415647+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-235B-A22B-Instruct-2507","object":"model","owned_by":"","created":1771937600,"display_name":"Qwen3 235B A22B Instruct 2507","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:20.866004+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-235B-A22B-Thinking-2507","object":"model","owned_by":"","created":1771937601,"display_name":"Qwen3 235B A22B Thinking 2507","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":3.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:21.703567+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-30b-a3b-instruct-2507","object":"model","owned_by":"","created":1759401803,"display_name":"Qwen3 30B A3B Instruct 2507","pricing":{"input_usd_per_mtok":0.13,"output_usd_per_mtok":0.52,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:23.646850+00:00"},"specs":{"context_window":262144,"max_output_tokens":32000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-30B-A3B-Thinking-2507","object":"model","owned_by":"","created":1771937592,"display_name":"Qwen3 30B A3B Thinking 2507","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:12.163500+00:00"},"specs":{"context_window":81920,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"Qwen/Qwen3.5-0.8B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.04,"output_usd_per_mtok":0.08,"cache_read_usd_per_mtok":0.036,"cache_write_usd_per_mtok":0.04,"effective_at":"2026-04-27T14:12:40.112195+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-122B-A10B","object":"model","owned_by":"","created":1787974367,"display_name":null,"pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":0.9,"cache_read_usd_per_mtok":0.27,"cache_write_usd_per_mtok":0.3,"effective_at":"2026-08-29T03:32:47.538747+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-2B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.18,"cache_read_usd_per_mtok":0.054,"cache_write_usd_per_mtok":0.06,"effective_at":"2026-04-27T14:12:40.311797+00:00"},"specs":null},{"id":"qwen/qwen3.5-35b-a3b","object":"model","owned_by":"","created":1778742870,"display_name":"Qwen3.5-35B-A3B","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T07:14:30.333413+00:00"},"specs":{"context_window":262144,"max_output_tokens":16384,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.5-397b-a17b","object":"model","owned_by":"","created":1775696599,"display_name":"Qwen3.5 397B A17B","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-09T01:03:19.130519+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3.5-4B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":0.09,"cache_write_usd_per_mtok":0.1,"effective_at":"2026-04-27T14:12:40.492113+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-9B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.18,"output_usd_per_mtok":0.54,"cache_read_usd_per_mtok":0.162,"cache_write_usd_per_mtok":0.18,"effective_at":"2026-04-27T14:12:40.664813+00:00"},"specs":null},{"id":"qwen/qwen3.6-27b","object":"model","owned_by":"","created":1779244080,"display_name":"Qwen3.6 27B","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-20T02:28:00.420376+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.6-35b-a3b","object":"model","owned_by":"","created":1778092324,"display_name":"Qwen3.6 35B A3B","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:32:04.441666+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.7-flash","object":"model","owned_by":"","created":1785422211,"display_name":"Qwen3.7 Flash","pricing":{"input_usd_per_mtok":0.03,"output_usd_per_mtok":0.13,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-30T14:36:51.013707+00:00"},"specs":{"context_window":1000000,"max_output_tokens":65536,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","response_format","seed","temperature","tool_choice","tools","top_logprobs","top_p"]},{"id":"qwen/qwen3-8b","object":"model","owned_by":"","created":1767847988,"display_name":"Qwen3 8B","pricing":{"input_usd_per_mtok":0.117,"output_usd_per_mtok":0.455,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-08T04:53:08.134989+00:00"},"specs":{"context_window":131072,"max_output_tokens":8192,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"qwen/qwen3.8-max","object":"model","owned_by":"","created":1786408084,"display_name":null,"pricing":{"input_usd_per_mtok":2.0,"output_usd_per_mtok":6.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-11T00:28:04.248858+00:00"},"specs":null},{"id":"qwen/qwen3-coder","object":"model","owned_by":"","created":1761030855,"display_name":"Qwen3 Coder 480B A35B","pricing":{"input_usd_per_mtok":0.975,"output_usd_per_mtok":4.875,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:15.022804+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-coder-next","object":"model","owned_by":"","created":1772054821,"display_name":"Qwen3 Coder Next","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:27:01.126222+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-max","object":"model","owned_by":"","created":1764463224,"display_name":"Qwen3 Max","pricing":{"input_usd_per_mtok":1.2,"output_usd_per_mtok":6.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-11-30T00:40:24.859337+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","logprobs","max_tokens","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-235b-a22b-instruct","object":"model","owned_by":"","created":1761030856,"display_name":"Qwen3 VL 235B A22B Instruct","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:16.011386+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-235b-a22b-thinking","object":"model","owned_by":"","created":1764830992,"display_name":"Qwen3 VL 235B A22B Thinking","pricing":{"input_usd_per_mtok":0.98,"output_usd_per_mtok":4.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:52.368716+00:00"},"specs":{"context_window":131072,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-30b-a3b-instruct","object":"model","owned_by":"","created":1764830991,"display_name":"Qwen3 VL 30B A3B Instruct","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":0.7,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:51.204281+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-VL-30B-A3B-Thinking","object":"model","owned_by":"","created":1771937598,"display_name":"Qwen3 VL 30B A3B Thinking","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:18.456091+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-8b-instruct","object":"model","owned_by":"","created":1764830989,"display_name":"Qwen3 VL 8B Instruct","pricing":{"input_usd_per_mtok":0.117,"output_usd_per_mtok":0.455,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:49.046332+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["image","text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"x-ai/grok-4.20","object":"model","owned_by":"","created":1775779880,"display_name":"Grok 4.20","pricing":{"input_usd_per_mtok":2.0,"output_usd_per_mtok":6.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:20.257314+00:00"},"specs":{"context_window":2000000,"max_output_tokens":1800000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p"]},{"id":"x-ai/grok-4.20-multi-agent","object":"model","owned_by":"","created":1775779882,"display_name":"Grok 4.20 Multi-Agent","pricing":{"input_usd_per_mtok":2.0,"output_usd_per_mtok":6.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:22.350470+00:00"},"specs":{"context_window":2000000,"max_output_tokens":1800000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","temperature","top_logprobs","top_p"]},{"id":"x-ai/grok-4.6","object":"model","owned_by":"","created":1787959644,"display_name":"Grok 4.6","pricing":{"input_usd_per_mtok":2.0,"output_usd_per_mtok":6.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-28T23:27:24.930899+00:00"},"specs":{"context_window":500000,"max_output_tokens":450000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"xiaomi/mimo-v2.5","object":"model","owned_by":"","created":1778092300,"display_name":"MiMo-V2.5","pricing":{"input_usd_per_mtok":0.168,"output_usd_per_mtok":0.336,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:31:40.102605+00:00"},"specs":{"context_window":1050000,"max_output_tokens":131072,"modalities":{"input":["text","audio","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"xiaomi/mimo-v2.5-pro","object":"model","owned_by":"","created":1778092285,"display_name":"MiMo-V2.5-Pro","pricing":{"input_usd_per_mtok":0.48024,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:31:25.388731+00:00"},"specs":{"context_window":1050000,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-4.5","object":"model","owned_by":"","created":1759907123,"display_name":"GLM 4.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:23.880304+00:00"},"specs":{"context_window":131072,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.5-air","object":"model","owned_by":"","created":1759907122,"display_name":"GLM 4.5 Air","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.1,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:22.754541+00:00"},"specs":{"context_window":131072,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","repetition_penalty","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.6","object":"model","owned_by":"","created":1759907125,"display_name":"GLM 4.6","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:25.067849+00:00"},"specs":{"context_window":204800,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.7","object":"model","owned_by":"","created":1768006861,"display_name":"GLM 4.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-10T01:01:01.166455+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_p"]},{"id":"z-ai/glm-4.7-flash","object":"model","owned_by":"","created":1770082685,"display_name":"GLM 4.7 Flash","pricing":{"input_usd_per_mtok":0.07,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-03T01:38:05.842638+00:00"},"specs":{"context_window":200000,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5","object":"model","owned_by":"","created":1771374834,"display_name":"GLM 5","pricing":{"input_usd_per_mtok":1.0,"output_usd_per_mtok":3.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-18T00:33:54.765331+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.1","object":"model","owned_by":"","created":1775779875,"display_name":"GLM 5.1","pricing":{"input_usd_per_mtok":1.4,"output_usd_per_mtok":4.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:15.012238+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.2","object":"model","owned_by":"","created":1781738425,"display_name":"GLM 5.2","pricing":{"input_usd_per_mtok":1.54,"output_usd_per_mtok":4.84,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-17T23:20:25.382141+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.3","object":"model","owned_by":"","created":1787267428,"display_name":"GLM 5.3","pricing":{"input_usd_per_mtok":1.4,"output_usd_per_mtok":4.4,"cache_read_usd_per_mtok":1.26,"cache_write_usd_per_mtok":1.4,"effective_at":"2026-08-20T23:10:28.976971+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["low","high","max"],"default_effort":"max","default_enabled":true,"mandatory":true},"supported_parameters":["max_tokens","temperature","top_p","tools","tool_choice","reasoning","reasoning_effort"]},{"id":"z-ai/glm-5.3-flash","object":"model","owned_by":"","created":1787848124,"display_name":"GLM 5.3 Flash","pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-27T16:28:44.680637+00:00"},"specs":{"context_window":1310720,"max_output_tokens":102400,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"max","default_enabled":true,"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"zai-org/GLM-4.7","object":"model","owned_by":"","created":1771937590,"display_name":"GLM 4.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:10.608022+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_p"]}]}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/rust/agent/session-artifacts/01a0c5da-30de-765e-8f59-5bb56234b693/kernel-state.dill b/scripts/heartbeat-fire-runs/rust/agent/session-artifacts/01a0c5da-30de-765e-8f59-5bb56234b693/kernel-state.dilldeleted file mode 100644index 97aeaa3720..0000000000Binary files a/scripts/heartbeat-fire-runs/rust/agent/session-artifacts/01a0c5da-30de-765e-8f59-5bb56234b693/kernel-state.dill and /dev/null differdiff --git a/scripts/heartbeat-fire-runs/rust/agent/session-artifacts/01a0c5da-30de-765e-8f59-5bb56234b693/kernel-state.json b/scripts/heartbeat-fire-runs/rust/agent/session-artifacts/01a0c5da-30de-765e-8f59-5bb56234b693/kernel-state.jsondeleted file mode 100644index a61e452cb9..0000000000--- a/scripts/heartbeat-fire-runs/rust/agent/session-artifacts/01a0c5da-30de-765e-8f59-5bb56234b693/kernel-state.json+++ /dev/null@@ -1 +0,0 @@-{"version": 1, "savedNames": ["agent_message", "agent_observe", "goal", "hb", "rlm_heartbeat"], "skipped": [{"name": "attach_image", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "compact", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "edit", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "refine", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "websearch", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}], "pruned": [], "bytes": 5371, "pythonVersion": "3.11.16", "timestamp": "2026-09-21T21:23:56.905695+00:00"}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/rust/agent/session-artifacts/01a0c5da-30de-765e-8f59-5bb56234b693/kernel-stderr.log b/scripts/heartbeat-fire-runs/rust/agent/session-artifacts/01a0c5da-30de-765e-8f59-5bb56234b693/kernel-stderr.logdeleted file mode 100644index e69de29bb2..0000000000diff --git a/scripts/heartbeat-fire-runs/rust/agent/session-artifacts/01a0c5da-30de-765e-8f59-5bb56234b693/scheduled-jobs.json b/scripts/heartbeat-fire-runs/rust/agent/session-artifacts/01a0c5da-30de-765e-8f59-5bb56234b693/scheduled-jobs.jsondeleted file mode 100644index dbe7149298..0000000000--- a/scripts/heartbeat-fire-runs/rust/agent/session-artifacts/01a0c5da-30de-765e-8f59-5bb56234b693/scheduled-jobs.json+++ /dev/null@@ -1,27 +0,0 @@-{- "jobs": [- {- "id": "e8692e75-e60f-436a-ba5c-c5b57e9f6a4a",- "status": "active",- "source": "rlm_heartbeat",- "deliveryMode": "steer",- "activeSessionId": "6976ebac942d",- "sessionId": "01a0c5da-30de-765e-8f59-5bb56234b693",- "sessionFile": "/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/agent/sessions/01a0c5da-30de-765e-8f59-5bb56234b693.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/work",- "label": "hb-fire",- "prompt": "agent heartbeat fire probe instruction",- "schedule": {- "kind": "interval",- "expression": "every 30s",- "intervalMs": 30000- },- "createdAt": "2026-09-21T21:23:26.370Z",- "updatedAt": "2026-09-21T21:23:56.553Z",- "nextRunAt": "2026-09-21T21:24:26.371Z",- "lastRunAt": "2026-09-21T21:23:56.553Z",- "runCount": 1- }- ],- "dispatches": []-}diff --git a/scripts/heartbeat-fire-runs/rust/agent/sessions/01a0c5da-30de-765e-8f59-5bb56234b693.jsonl b/scripts/heartbeat-fire-runs/rust/agent/sessions/01a0c5da-30de-765e-8f59-5bb56234b693.jsonldeleted file mode 100644index 01102e5c26..0000000000--- a/scripts/heartbeat-fire-runs/rust/agent/sessions/01a0c5da-30de-765e-8f59-5bb56234b693.jsonl+++ /dev/null@@ -1,14 +0,0 @@-{"type":"session","version":3,"id":"01a0c5da-30de-765e-8f59-5bb56234b693","timestamp":"2026-09-21T21:23:26.046Z","cwd":"/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/work","rlmDepth":0}-{"type":"model_change","id":"9a22e3e8","parentId":null,"timestamp":"2026-09-21T21:23:26.061Z","provider":"prime-inference","modelId":"mock-1"}-{"type":"thinking_level_change","id":"460e34ed","parentId":"9a22e3e8","timestamp":"2026-09-21T21:23:26.061Z","thinkingLevel":"off"}-{"type":"service_tier_change","id":"30dd42d4","parentId":"460e34ed","timestamp":"2026-09-21T21:23:26.061Z","serviceTier":"default"}-{"type":"session_state","id":"7a698551","parentId":"30dd42d4","timestamp":"2026-09-21T21:23:26.061Z","state":{"status":"active"}}-{"type":"session_info","id":"745c810d","parentId":"7a698551","timestamp":"2026-09-21T21:23:26.063Z","name":"hb-fire-verifier"}-{"type":"message","id":"f1372840","parentId":"745c810d","timestamp":"2026-09-21T21:23:26.143Z","message":{"role":"user","content":[{"type":"text","text":"verifier seed turn"}],"timestamp":1790025806143}}-{"type":"message","id":"3e2a794f","parentId":"f1372840","timestamp":"2026-09-21T21:23:26.240Z","message":{"role":"assistant","content":[{"type":"text","text":"heartbeat fire verifier seed reply"}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","responseId":"chatcmpl-battery","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790025806214}}-{"type":"message","id":"482cadf3","parentId":"3e2a794f","timestamp":"2026-09-21T21:23:26.307Z","message":{"role":"user","content":[{"type":"text","text":"create the agent heartbeat"}],"timestamp":1790025806307}}-{"type":"message","id":"cb58346a","parentId":"482cadf3","timestamp":"2026-09-21T21:23:26.371Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"call_battery_1","name":"ipython","arguments":{"code":"import rlm_heartbeat\nhb = await rlm_heartbeat.create(\n 'agent heartbeat fire probe instruction',\n interval='every 30s',\n label='hb-fire',\n)\nprint('created', hb['id'])"}}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","responseId":"chatcmpl-battery","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790025806365}}-{"type":"message","id":"0da2865f","parentId":"cb58346a","timestamp":"2026-09-21T21:23:26.377Z","message":{"role":"toolResult","toolCallId":"call_battery_1","toolName":"ipython","content":[{"text":"Traceback (most recent call last):\n\n File \"<cell-2>\", line 7, in <module>\n print('created', hb['id'])\n ~~^^^^^^\n\nKeyError: 'id'\n","type":"text"}],"details":{"status":"error","kernelRestarted":false,"durationMs":4,"error":{"ename":"KeyError","evalue":"'id'","traceback":["Traceback (most recent call last):\n"," File \"<cell-2>\", line 7, in <module>\n print('created', hb['id'])\n ~~^^^^^^\n","KeyError: 'id'\n"]},"errorEname":"KeyError"},"isError":false,"timestamp":1790025806375}}-{"type":"message","id":"fc07b740","parentId":"0da2865f","timestamp":"2026-09-21T21:23:26.436Z","message":{"role":"assistant","content":[{"type":"text","text":"agent heartbeat created"}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","responseId":"chatcmpl-battery","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790025806376}}-{"type":"message","id":"72cd53b6","parentId":"fc07b740","timestamp":"2026-09-21T21:23:56.394Z","message":{"role":"user","content":[{"type":"text","text":"agent heartbeat fire probe instruction"}],"timestamp":1790025836394}}-{"type":"message","id":"de2bbc9a","parentId":"72cd53b6","timestamp":"2026-09-21T21:23:56.504Z","message":{"role":"assistant","content":[{"type":"text","text":"agent heartbeat created"}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","responseId":"chatcmpl-battery","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790025836481}}diff --git a/scripts/heartbeat-fire-runs/rust/agent/settings.json b/scripts/heartbeat-fire-runs/rust/agent/settings.jsondeleted file mode 100644index 539978831e..0000000000--- a/scripts/heartbeat-fire-runs/rust/agent/settings.json+++ /dev/null@@ -1 +0,0 @@-{"onboardingShown": true, "telemetry": {"noticeShown": true}}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/rust/agent/telemetry.json b/scripts/heartbeat-fire-runs/rust/agent/telemetry.jsondeleted file mode 100644index a6da7d5e55..0000000000--- a/scripts/heartbeat-fire-runs/rust/agent/telemetry.json+++ /dev/null@@ -1,4 +0,0 @@-{- "version": 1,- "installationId": "96c2a049-f66e-4954-9b26-aff3c3f44c19"-}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/rust/agent/telemetry.jsonl b/scripts/heartbeat-fire-runs/rust/agent/telemetry.jsonldeleted file mode 100644index 9e231b7880..0000000000--- a/scripts/heartbeat-fire-runs/rust/agent/telemetry.jsonl+++ /dev/null@@ -1,7 +0,0 @@-{"name":"agent started","timestamp":"2026-09-21T21:23:26.114Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"daemon","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"5.15.0-185-generic","os_product_version":"unknown","session_id":"a47f3176-0ea9-48ee-b8d9-bdc9e4cd1923","skill_count":11,"python_skill_count":9},"distinct_id":"96c2a049-f66e-4954-9b26-aff3c3f44c19"}-{"name":"kernel bootstrap","timestamp":"2026-09-21T21:23:26.352Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"daemon","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"5.15.0-185-generic","os_product_version":"unknown","cold":true,"outcome":"success","duration_ms":237},"distinct_id":"96c2a049-f66e-4954-9b26-aff3c3f44c19"}-{"name":"agent run completed","timestamp":"2026-09-21T21:23:26.364Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"daemon","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"5.15.0-185-generic","os_product_version":"unknown","session_id":"a47f3176-0ea9-48ee-b8d9-bdc9e4cd1923","outcome":"success","duration_ms":27,"visible_ttft_ms":7,"first_model_event_ms":6,"model_latency_ms":8,"max_model_latency_ms":8,"model_call_count":1,"turn_count":1,"tool_call_count":0,"tool_error_count":0,"input_tokens":20,"output_tokens":10,"cache_read_tokens":80,"cache_write_tokens":0,"total_tokens":110,"compaction_count":0,"retry_count":0,"failover_count":0,"provider_category":"prime","model_category":"custom","error_category":null},"distinct_id":"96c2a049-f66e-4954-9b26-aff3c3f44c19"}-{"name":"tool executed","timestamp":"2026-09-21T21:23:26.375Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"daemon","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"5.15.0-185-generic","os_product_version":"unknown","session_id":"a47f3176-0ea9-48ee-b8d9-bdc9e4cd1923","tool_name":"ipython","duration_ms":6,"is_error":false},"distinct_id":"96c2a049-f66e-4954-9b26-aff3c3f44c19"}-{"name":"agent run completed","timestamp":"2026-09-21T21:23:56.480Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"daemon","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"5.15.0-185-generic","os_product_version":"unknown","session_id":"a47f3176-0ea9-48ee-b8d9-bdc9e4cd1923","outcome":"success","duration_ms":72,"visible_ttft_ms":59,"first_model_event_ms":5,"model_latency_ms":54,"max_model_latency_ms":49,"model_call_count":2,"turn_count":2,"tool_call_count":1,"tool_error_count":0,"input_tokens":40,"output_tokens":20,"cache_read_tokens":160,"cache_write_tokens":0,"total_tokens":220,"compaction_count":0,"retry_count":0,"failover_count":0,"provider_category":"prime","model_category":"custom","error_category":null},"distinct_id":"96c2a049-f66e-4954-9b26-aff3c3f44c19"}-{"name":"agent run completed","timestamp":"2026-09-21T21:23:56.926Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"daemon","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"5.15.0-185-generic","os_product_version":"unknown","session_id":"a47f3176-0ea9-48ee-b8d9-bdc9e4cd1923","outcome":"success","duration_ms":23,"visible_ttft_ms":4,"first_model_event_ms":4,"model_latency_ms":5,"max_model_latency_ms":5,"model_call_count":1,"turn_count":1,"tool_call_count":0,"tool_error_count":0,"input_tokens":20,"output_tokens":10,"cache_read_tokens":80,"cache_write_tokens":0,"total_tokens":110,"compaction_count":0,"retry_count":0,"failover_count":0,"provider_category":"prime","model_category":"custom","error_category":null},"distinct_id":"96c2a049-f66e-4954-9b26-aff3c3f44c19"}-{"name":"agent session ended","timestamp":"2026-09-21T21:23:56.926Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"daemon","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"5.15.0-185-generic","os_product_version":"unknown","session_id":"a47f3176-0ea9-48ee-b8d9-bdc9e4cd1923","duration_ms":30812,"prompt_count":3,"run_count":3,"successful_run_count":3,"failed_run_count":0,"aborted_run_count":0,"tool_call_count":2,"compaction_count":0,"model_call_count":4,"input_tokens":80,"output_tokens":40,"cache_read_tokens":320,"cache_write_tokens":0,"total_tokens":440},"distinct_id":"96c2a049-f66e-4954-9b26-aff3c3f44c19"}diff --git a/scripts/heartbeat-fire-runs/rust/daemon.log b/scripts/heartbeat-fire-runs/rust/daemon.logdeleted file mode 100644index 1c0a3d3a53..0000000000--- a/scripts/heartbeat-fire-runs/rust/daemon.log+++ /dev/null@@ -1 +0,0 @@-pa-daemon client connection error: Broken pipe (os error 32)diff --git a/scripts/heartbeat-fire-runs/rust/mock-script.json b/scripts/heartbeat-fire-runs/rust/mock-script.jsondeleted file mode 100644index 1c2587ac90..0000000000--- a/scripts/heartbeat-fire-runs/rust/mock-script.json+++ /dev/null@@ -1 +0,0 @@-{"responses": [{"toolCall": {"name": "ipython", "arguments": {"code": "import rlm_heartbeat\nhb = await rlm_heartbeat.create(\n 'agent heartbeat fire probe instruction',\n interval='every 30s',\n label='hb-fire',\n)\nprint('created', hb['id'])"}}}, {"text": "agent heartbeat created"}]}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/rust/mock-script.json.requests.jsonl b/scripts/heartbeat-fire-runs/rust/mock-script.json.requests.jsonldeleted file mode 100644index 8e12ce7c69..0000000000--- a/scripts/heartbeat-fire-runs/rust/mock-script.json.requests.jsonl+++ /dev/null@@ -1,5 +0,0 @@-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "# prime-agent harness\n\nThe prime-agent harness has one tool: `ipython`, a persistent CPython REPL. All other tools are \"programmatic tools\", functions inside the Python REPL called via \"programmatic tool calling\" (PTC). All programmatic tools are async unless described otherwise and can be run in the background. `await` works directly and globally in the REPL.\n\nThe harness often sends messages to the agent. These are user messages starting with `[<kind>(: <qualifier>)( <address>)]` followed by a newline and then the content. They are not user-generated.\n\n## Core tools\n\n- `bash(command: str) -> BashHandle`: synchronous, returns immediately and runs the command in the background; when a command is finished outside the calling `ipython` block, a notification is sent to the agent; each `bash()` call is its own process, so shell state does not persist between calls\n - `BashHandle`:\n - `.pid: int`\n - `.running: bool`\n - `.command: str`\n - `.tail(n: int = 50) -> str`\n - `.output() -> str`\n - `.poll() -> BashResult | None`\n - `.kill(sig: int = SIGTERM, grace: float = 5.0) -> None`: SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive\n - `await handle -> BashResult`: the handle is awaitable even after command completion, so agents can run commands non-blocking and await them after being notified of them finishing\n - `BashResult`\n - `.exit_code: int`\n - `.output: str`\n - `.duration: float`\n- `edit.run(path: str, old_str: str, new_str: str) -> str`: the primary method for editing files. async, exact-unique-match; the `edit` module is callable with the same arguments (`await edit(path=..., old_str=..., new_str=...)`)\n- `websearch.run(query: str, *, max_output: int = 8192, timeout: int | None, num_results: int | None) -> str`: search the web; the `websearch` module is callable with the same arguments\n- `attach_image(*paths: str) -> str`: loads images directly into context if the agent's model is vision-capable, errors otherwise\n\n## Subagents\n\nprime-agent is a recursive harness. Each session builds a tree of agents, starting at depth 0. Each agent up to a user-configured limit can launch subagents. These subagents are persistent, just like the root session. Each agent can communicate with its nuclear family: its singular parent (except for depth 0 sessions which have no parent), its siblings (other subagents under the same parent), and its children (its own subagents).\n\nThe following programmatic tools are available in the REPL for subagent management:\n\n- `rlm.spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None) -> RLMSpawnHandle`: spawns a new subagent one level deeper than the caller; returns immediately; errors when the caller cannot create subagents; if not given, `model` and `thinking` are inherited from the parent; results never arrive as `rlm.spawn()` return values, they arrive only via agent_message; `name` must be unique among the spawned agent's siblings, and be meaningful and descriptive but short\n- `rlm.create_session(prompt: str, name: str | None = None, model: str | None = None, thinking: str | None = None, cwd: str | None = None) -> RLMCreateSessionHandle`: creates another depth-0 session; only available to agents at depth 0 backed by a daemon; returns after the session is successfully created and the first prompt sent\n- `rlm.find_models(query: str = '', limit: int = 8) -> list[RLMModel]`\n- `rlm.list_subagents() -> list[RLMSubagent]`: direct child handles\n- `rlm.delete_subagent(target: str | RLMSubagent) -> RLMSubagent`\n- `rlm.collect(targets=None, *, timeout_ms: int = 0) -> list[RLMChildResult]`: typed snapshots of direct children (status, settled flag, answer preview, error) without steering anyone; `timeout_ms=0` returns a non-blocking snapshot; a positive timeout blocks only this call until the children settle or the deadline passes\n- `rlm.progress_note(message: str) -> dict`: report brief in-flight progress to the parent orchestrator (at most 512 characters, throttled to about one note per 10 seconds); the parent sees notes without needing a reply\n- `RLMSpawnHandle`\n - `rlm_child_id: str`\n - `name: str`\n - `session_dir: Path`\n - `model: str`: provider/model, full resolved model name\n- `RLMCreateSessionHandle`\n - `active_session_id: str`: live daemon-instance id\n - `session_id: str`: durable on-disk session identity\n - `name: str`\n - `session_file: Path`: path to persisted session log\n - `model: str`: provider/model, full resolved model name\n- `RLMSubagent`\n - `rlm_child_id: str`\n - `active_session_id: str | None`\n - `session_id: str | None`\n - `session_name: str`\n - `session_dir: Path`\n - `status: Literal[\"running\", \"completed\", \"error\"]`\n - rows also carry live activity detail (current activity, tool use count, duration, answer preview, latest progress note)\n- `RLMModel`\n - `provider: str`\n - `id: str`\n - `name: str`\n - `selector: str`: the exact string to spawn the model\n\nThe following programmatic tools are available in the REPL for a2a communication:\n\n- `agent_message.send(message: str, *, receiver_role: Literal[\"parent\", \"sibling\", \"child\"], receiver_name: str | None) -> dict`: send a message to the receiver; returns a receipt with the message id and a delivery status (delivered or queued); all root sessions are siblings; `send(\"all\", broadcast_message)` broadcasts to the family roster and returns `{receipts: [...]}`\n- `agent_observe.list_agents() -> dict`: list nuclear family\n- `agent_observe.get_agent(target: str) -> dict`: one agent's status detail\n- `agent_observe.recent_messages(target: str, limit: int = 8, max_chars: int = 800) -> dict`: transcript preview; `limit` errors outside [1-50], `max_chars` outside [80-2000]\n\n## Continual Harness\n\nprime-agent is a continual harness. During a session, persistent memories can be written and read. These stay available even after multiple compactions.\n\nMemories are created by two mechanisms:\n\n- Refinement\n - Mechanism:\n - Another model suggests a refinement based on the transcript\n - The suggested edits are applied to the harness state\n - The main agent is notified by a structured harness message and the applied edits are saved\n - Triggered by:\n - Calling the programmatic tool `refine.run()`\n - By the user command `/refine`\n - Effect:\n - The refinement event is always saved in the harness state's refinement history\n - A harness message is sent to the agent with the refinement result\n- Active memory management by the agent\n - `refine.run(instructions: str | None = None, global_: bool = False) -> dict`: agent-triggered refinement (see above); returns immediately and runs when the current turn ends\n- `refine.status() -> dict`: whether a refinement is already pending for this turn or currently in flight\n - `rlm.harness.create_memory(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: creates a memory; use `global_=True` for cross-session entries (Python reserves `global`, so the parameter is spelled `global_`)\n - `rlm.harness.update_memory(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_memory(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_prompt_note(title: str, content: str, *, id: str | None = None, path: str = \"policy\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_prompt_note(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_prompt_note(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_skill(title: str, content: str, *, id: str | None = None, path: str = \"general\", reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: `reference`/`arguments` describe the Python callable (`reference` requires `{\"type\": \"python\"}`, a Python import, and a callable or call pattern)\n - `rlm.harness.update_skill(id: str, title: str, content: str, *, path: str | None = None, reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_skill(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_subagent(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_subagent(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_subagent(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.record_refinement(trigger: str, changes: list[str], *, evidence: str = \"\", outcome: str = \"\", id: str | None = None, global_: bool = False) -> RefinementEvent`\n - `rlm.harness.plan_refinement(observation: str, *, failing_component: str = \"\", next_step: str = \"\") -> list[str]`: a suggested diagnose -> update -> validate plan\n - `rlm.harness.overview(*, max_entries_per_kind: int = 20, global_: bool = False) -> str`: memory overview\n - `rlm.harness.search(query: str, kind: str | None = None, limit: int = 10, *, global_: bool = False) -> list[HarnessEntry]`: ranked term search over entries\n - `rlm.get_harness_state(state_dir: str | Path | None = None, *, global_: bool = False) -> HarnessState`: full memory details for the selected scope. Can read another agent's `HarnessState` by passing the path to it in `state_dir`\n - `HarnessEntry`\n - `id: str`\n - `kind: Literal[\"prompt\", \"memory\", \"skill\", \"subagent\"]`\n - `title: str`\n - `content: str`\n - `path: str`: category path (\"general\" for memories, \"policy\" for prompt notes)\n - `scope: Literal[\"local\", \"global\"]`\n - `reference: dict[str, Any]`: for skills\n - `arguments: dict[str, Any]`: for skills\n - `metadata: dict`\n - `source: Literal[\"agent\", \"refine\"]`\n - `created_at: str`: ISO timestamp of creation\n - `updated_at: str`: ISO timestamp of latest update\n - `version: int`: increments with every update, starting at 1\n - `HarnessState`\n - `scope: Literal[\"global\", \"local\"]`\n - `file_path: Path`\n - `entries: dict[kind, dict[id, HarnessEntry]]`\n - `refinements: list[RefinementEvent]`\n - `RefinementEvent`\n - `id: str`\n - `trigger: str`: what caused the refinement\n - `changes: list[str]`: applied edits; empty if never edited\n - `evidence: str`\n - `outcome: str`\n - `created_at: str`\n\n## Compaction\n\nprime-agent compacts automatically when there is only a given number of tokens left in the context window (default: 16384), when the user triggers compaction, or when the agent triggers compaction. REPL state persists across compactions, but compaction removes individual variables whose serialized form exceeds 16 MiB.\n\n- `compact.run(instructions: str | None = None) -> dict`: schedule a compaction at the next assistant turn boundary\n- `compact.status() -> dict`: context usage & threshold before auto-compaction\n\n## Goal\n\nIn goal mode prime-agent helps an agent stay on track until a task is fully finished, and handles interruptions and other issues. Goals can be user- or agent-created.\n\n- `goal.create(objective: str, token_budget: int | None = None) -> dict`: create goal and return goal state\n- `goal.get() -> dict`: get goal status (only one goal can be active at a time)\n- `goal.complete() -> dict`: mark goal as completed and get final goal status\n\n## Heartbeat\n\nIn prime-agent, agents can create heartbeats to wake themselves up after a given period of time with remembered instructions, recurrently on a given schedule.\n\n- `rlm_heartbeat.create(instruction: str, interval: str | None = None, label: str | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`: new recurring heartbeat for this session; `interval` is a schedule string (default: every 5 minutes); `delivery_mode`: steer (default) interrupts a busy session's current turn, follow_up waits for it to finish\n- `rlm_heartbeat.list(include_inactive: bool = False) -> dict`\n- `rlm_heartbeat.update(id: str, instruction: str | None = None, interval: str | None = None, label: str | None = None, status: Literal[\"pause\", \"resume\"] | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`\n- `rlm_heartbeat.delete(id: str) -> dict`\n\n## MCP\n\nprime-agent has support for programmatic tools that are defined in the MCP format. Their schema is discovered at runtime.\n\n- `mcp.list_tools(server: str) -> list[dict]`: returns tool schemas\n- `mcp.call_tool(server: str, tool: str, arguments: dict | None = None) -> Any`\n\n## Skills\n\nprime-agent provides multiple executable skills, described by their SKILL.md and executable code. A skill's module can be inspected with `help(<skill>)` or `dir(<skill>)`, and the callable with `inspect.signature(<skill>.<function>)`, if information is missing. The executable code is always pre-imported in the REPL as a programmatic tool, and a callable skill module can be called directly (`await <skill>(...)`).\n\nAll programmatic tools described above except for `bash`, `rlm.*`, and `mcp.*` are implemented as executable skills and will be listed again in the dynamic tail of this prompt. Additional executable and non-executable skills may exist as well; non-executable (markdown) skills are documentation read from disk, and each skill is also available as a shell command by the same name.\n\nThe following are mandatory rules, only to be overridden by clear user intent.\n\n- Memories must be kept lean and up-to-date.\n- `goal.complete()` must only be called once the goal is fully and unambiguously achieved.\n- Goals must only be created at a user's request.\n- Agents run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n- `bash(\"\"\"...\"\"\")` should be used over `bash(\"...\")` because it makes using quotation marks inside bash easy.\n- Bash commands must be run in the background; if they are quick, or the agent is doing other heavy work in the same `ipython` call, they should be awaited or polled in the same `ipython` call interleaved with other work, or a subsequent one; otherwise, the agent should wait for the notification; blocking calls reduce user responsiveness.\n- Shell state does not persist between calls, but agents can use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls through POSIX process inheritance (since each bash call is a fresh process, Python does not inherit environment variables from bash).\n- Edits of existing files must be performed using `edit` with exact old/new strings; if the text contains triple double quotes (\"\"\"), the agent should use triple single-quoted variables or build `old`/`new` from inspected file slices.\n- Agents use Python for reading files and searching in them \u2014 it gives them reusable variables they can slice, filter, and act on without re-reading; using Python variables to find or produce, and to save the strings used in `edit` is also encouraged.\n- Agents always assign read/search results to named variables so they can revisit them later.\n- Agents must report assumptions they made and constants they changed to the user.\n- When an agent is done, they stop calling tools and state their final answer.\n- When delegation is available and useful, an agent assigns independent substantive tasks to separate workers. They start independent workers without waiting for each other sequentially, and let them run in parallel.\n- Agents do not keep the turn open by polling with `time.sleep()` or shell `sleep`, and they do not replace polling with a long blocking `await`. They await only the short operation needed to start work or inspect a result that is already available; otherwise they end the turn.\n- Agents use the Python REPL to keep intermediate variables, inspect and transform outputs, and write small helper functions.\n- Since compaction removes individual variables whose serialized form exceeds 16 MiB, agents can keep large source data on disk and reload it when needed.\n- Python is the orchestration language: agents use Python for loops, conditionals, parsing, and state. They use `bash()` to invoke programs, not to write shell programs, shell loops, or heredocs; those are done directly in Python.\n- Agents do not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Agents evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n- Agents do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, they run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Agents treat failures from that native environment as the relevant result.\n- Rules for root agents (depth 0):\n - Only message siblings if you are certain that it is necessary.\n - When work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n- Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n- Agents treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: they diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. They use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so agents continue working normally after calling it. Agents do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n- Instructions to agents for multi-agent work:\n - When spawning a subagent, keep the handle to stop or inspect the child later.\n - Ask for an explicit reply when needed; not every message needs a reply.\n - Use `await rlm.list_subagents()` after kernel restart or compaction.\n - Have children write files and read those files for fan-in.\n - Delegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\n\nThe following guidelines to agents have been shown to improve results on average. Agents should consider using them where appropriate. Clear user instructions always override these defaults.\n\n- Agents can use the following patterns to make better use of the REPL:\n - Write wrappers around `rlm.spawn` to have quick templates for subagents with arbitrary args: for text to programmatically pass and put into the prompt, for conditional behavior prompts, etc.\n - Use f-strings (`f\"\"\"...\"\"\"` or `f\"...\"`) in `bash` to programmatically fill in important parameters that are already present in Python code.\n- When writing or explaining something:\n - Agents use simplified technical English by default for user-facing prose: short sentences, common words, and concrete verbs; one main action or fact per sentence when practical; lists for steps or conditions. Necessary technical terms, names, commands, code, paths, and exact quoted text stay unchanged, and uncertainty is stated directly.\n - Agents use ordinary or established wording. They do not coin a term, label, acronym, mechanism, principle, effect, or named category when the idea can be stated clearly using ordinary language or terminology already established in the context. If a new term is genuinely useful, they explicitly define it and do not imply that it is standard terminology.\n - Agents keep names and terms consistent. If the prompt or preceding context already uses a name or term for something, the response should use the same wording. Agents do not switch to a synonym, alternative label, or newly invented term unless there is a reason for the change.\n- Agents take care and effort to avoid the following pitfalls while coding:\n - over-engineered solutions\n - overly defensive programming\n - hyper-fixation on rare/fictitious edge cases\n - overlapping subsystem responsibilities\n - solving problems at the wrong architectural layer\n - duplication of sources of truth, then inventing machinery to synchronize them\n - prematurely generalizing one-off flows\n - timeouts on everything\n - production code that exists purely to satisfy tests\n - patching bad premises additively instead of stepping back and deleting or adjusting them\n - tests for magic strings\n - excessive tests\n - comments that describe anything already described by the code\n - comments narrating the coding process instead of supporting the written code\n - fallbacks, legacy support, compatibility shims where not strictly needed; when in doubt, these should be discussed with the user\n - in UI, descriptions on everything\n\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/hb-fire/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/websearch/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/compact/SKILL.md</location>\n </skill>\n</available_skills>\n\nCurrent date: 2026-09-21\nWorking directory: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/work\nConversation log: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/agent/sessions/01a0c5da-30de-765e-8f59-5bb56234b693.jsonl\nImage input: this model cannot see images; `attach_image` errors for it.\n\nRecursive agent depth: 0 (root)"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "# prime-agent harness\n\nThe prime-agent harness has one tool: `ipython`, a persistent CPython REPL. All other tools are \"programmatic tools\", functions inside the Python REPL called via \"programmatic tool calling\" (PTC). All programmatic tools are async unless described otherwise and can be run in the background. `await` works directly and globally in the REPL.\n\nThe harness often sends messages to the agent. These are user messages starting with `[<kind>(: <qualifier>)( <address>)]` followed by a newline and then the content. They are not user-generated.\n\n## Core tools\n\n- `bash(command: str) -> BashHandle`: synchronous, returns immediately and runs the command in the background; when a command is finished outside the calling `ipython` block, a notification is sent to the agent; each `bash()` call is its own process, so shell state does not persist between calls\n - `BashHandle`:\n - `.pid: int`\n - `.running: bool`\n - `.command: str`\n - `.tail(n: int = 50) -> str`\n - `.output() -> str`\n - `.poll() -> BashResult | None`\n - `.kill(sig: int = SIGTERM, grace: float = 5.0) -> None`: SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive\n - `await handle -> BashResult`: the handle is awaitable even after command completion, so agents can run commands non-blocking and await them after being notified of them finishing\n - `BashResult`\n - `.exit_code: int`\n - `.output: str`\n - `.duration: float`\n- `edit.run(path: str, old_str: str, new_str: str) -> str`: the primary method for editing files. async, exact-unique-match; the `edit` module is callable with the same arguments (`await edit(path=..., old_str=..., new_str=...)`)\n- `websearch.run(query: str, *, max_output: int = 8192, timeout: int | None, num_results: int | None) -> str`: search the web; the `websearch` module is callable with the same arguments\n- `attach_image(*paths: str) -> str`: loads images directly into context if the agent's model is vision-capable, errors otherwise\n\n## Subagents\n\nprime-agent is a recursive harness. Each session builds a tree of agents, starting at depth 0. Each agent up to a user-configured limit can launch subagents. These subagents are persistent, just like the root session. Each agent can communicate with its nuclear family: its singular parent (except for depth 0 sessions which have no parent), its siblings (other subagents under the same parent), and its children (its own subagents).\n\nThe following programmatic tools are available in the REPL for subagent management:\n\n- `rlm.spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None) -> RLMSpawnHandle`: spawns a new subagent one level deeper than the caller; returns immediately; errors when the caller cannot create subagents; if not given, `model` and `thinking` are inherited from the parent; results never arrive as `rlm.spawn()` return values, they arrive only via agent_message; `name` must be unique among the spawned agent's siblings, and be meaningful and descriptive but short\n- `rlm.create_session(prompt: str, name: str | None = None, model: str | None = None, thinking: str | None = None, cwd: str | None = None) -> RLMCreateSessionHandle`: creates another depth-0 session; only available to agents at depth 0 backed by a daemon; returns after the session is successfully created and the first prompt sent\n- `rlm.find_models(query: str = '', limit: int = 8) -> list[RLMModel]`\n- `rlm.list_subagents() -> list[RLMSubagent]`: direct child handles\n- `rlm.delete_subagent(target: str | RLMSubagent) -> RLMSubagent`\n- `rlm.collect(targets=None, *, timeout_ms: int = 0) -> list[RLMChildResult]`: typed snapshots of direct children (status, settled flag, answer preview, error) without steering anyone; `timeout_ms=0` returns a non-blocking snapshot; a positive timeout blocks only this call until the children settle or the deadline passes\n- `rlm.progress_note(message: str) -> dict`: report brief in-flight progress to the parent orchestrator (at most 512 characters, throttled to about one note per 10 seconds); the parent sees notes without needing a reply\n- `RLMSpawnHandle`\n - `rlm_child_id: str`\n - `name: str`\n - `session_dir: Path`\n - `model: str`: provider/model, full resolved model name\n- `RLMCreateSessionHandle`\n - `active_session_id: str`: live daemon-instance id\n - `session_id: str`: durable on-disk session identity\n - `name: str`\n - `session_file: Path`: path to persisted session log\n - `model: str`: provider/model, full resolved model name\n- `RLMSubagent`\n - `rlm_child_id: str`\n - `active_session_id: str | None`\n - `session_id: str | None`\n - `session_name: str`\n - `session_dir: Path`\n - `status: Literal[\"running\", \"completed\", \"error\"]`\n - rows also carry live activity detail (current activity, tool use count, duration, answer preview, latest progress note)\n- `RLMModel`\n - `provider: str`\n - `id: str`\n - `name: str`\n - `selector: str`: the exact string to spawn the model\n\nThe following programmatic tools are available in the REPL for a2a communication:\n\n- `agent_message.send(message: str, *, receiver_role: Literal[\"parent\", \"sibling\", \"child\"], receiver_name: str | None) -> dict`: send a message to the receiver; returns a receipt with the message id and a delivery status (delivered or queued); all root sessions are siblings; `send(\"all\", broadcast_message)` broadcasts to the family roster and returns `{receipts: [...]}`\n- `agent_observe.list_agents() -> dict`: list nuclear family\n- `agent_observe.get_agent(target: str) -> dict`: one agent's status detail\n- `agent_observe.recent_messages(target: str, limit: int = 8, max_chars: int = 800) -> dict`: transcript preview; `limit` errors outside [1-50], `max_chars` outside [80-2000]\n\n## Continual Harness\n\nprime-agent is a continual harness. During a session, persistent memories can be written and read. These stay available even after multiple compactions.\n\nMemories are created by two mechanisms:\n\n- Refinement\n - Mechanism:\n - Another model suggests a refinement based on the transcript\n - The suggested edits are applied to the harness state\n - The main agent is notified by a structured harness message and the applied edits are saved\n - Triggered by:\n - Calling the programmatic tool `refine.run()`\n - By the user command `/refine`\n - Effect:\n - The refinement event is always saved in the harness state's refinement history\n - A harness message is sent to the agent with the refinement result\n- Active memory management by the agent\n - `refine.run(instructions: str | None = None, global_: bool = False) -> dict`: agent-triggered refinement (see above); returns immediately and runs when the current turn ends\n- `refine.status() -> dict`: whether a refinement is already pending for this turn or currently in flight\n - `rlm.harness.create_memory(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: creates a memory; use `global_=True` for cross-session entries (Python reserves `global`, so the parameter is spelled `global_`)\n - `rlm.harness.update_memory(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_memory(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_prompt_note(title: str, content: str, *, id: str | None = None, path: str = \"policy\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_prompt_note(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_prompt_note(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_skill(title: str, content: str, *, id: str | None = None, path: str = \"general\", reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: `reference`/`arguments` describe the Python callable (`reference` requires `{\"type\": \"python\"}`, a Python import, and a callable or call pattern)\n - `rlm.harness.update_skill(id: str, title: str, content: str, *, path: str | None = None, reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_skill(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_subagent(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_subagent(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_subagent(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.record_refinement(trigger: str, changes: list[str], *, evidence: str = \"\", outcome: str = \"\", id: str | None = None, global_: bool = False) -> RefinementEvent`\n - `rlm.harness.plan_refinement(observation: str, *, failing_component: str = \"\", next_step: str = \"\") -> list[str]`: a suggested diagnose -> update -> validate plan\n - `rlm.harness.overview(*, max_entries_per_kind: int = 20, global_: bool = False) -> str`: memory overview\n - `rlm.harness.search(query: str, kind: str | None = None, limit: int = 10, *, global_: bool = False) -> list[HarnessEntry]`: ranked term search over entries\n - `rlm.get_harness_state(state_dir: str | Path | None = None, *, global_: bool = False) -> HarnessState`: full memory details for the selected scope. Can read another agent's `HarnessState` by passing the path to it in `state_dir`\n - `HarnessEntry`\n - `id: str`\n - `kind: Literal[\"prompt\", \"memory\", \"skill\", \"subagent\"]`\n - `title: str`\n - `content: str`\n - `path: str`: category path (\"general\" for memories, \"policy\" for prompt notes)\n - `scope: Literal[\"local\", \"global\"]`\n - `reference: dict[str, Any]`: for skills\n - `arguments: dict[str, Any]`: for skills\n - `metadata: dict`\n - `source: Literal[\"agent\", \"refine\"]`\n - `created_at: str`: ISO timestamp of creation\n - `updated_at: str`: ISO timestamp of latest update\n - `version: int`: increments with every update, starting at 1\n - `HarnessState`\n - `scope: Literal[\"global\", \"local\"]`\n - `file_path: Path`\n - `entries: dict[kind, dict[id, HarnessEntry]]`\n - `refinements: list[RefinementEvent]`\n - `RefinementEvent`\n - `id: str`\n - `trigger: str`: what caused the refinement\n - `changes: list[str]`: applied edits; empty if never edited\n - `evidence: str`\n - `outcome: str`\n - `created_at: str`\n\n## Compaction\n\nprime-agent compacts automatically when there is only a given number of tokens left in the context window (default: 16384), when the user triggers compaction, or when the agent triggers compaction. REPL state persists across compactions, but compaction removes individual variables whose serialized form exceeds 16 MiB.\n\n- `compact.run(instructions: str | None = None) -> dict`: schedule a compaction at the next assistant turn boundary\n- `compact.status() -> dict`: context usage & threshold before auto-compaction\n\n## Goal\n\nIn goal mode prime-agent helps an agent stay on track until a task is fully finished, and handles interruptions and other issues. Goals can be user- or agent-created.\n\n- `goal.create(objective: str, token_budget: int | None = None) -> dict`: create goal and return goal state\n- `goal.get() -> dict`: get goal status (only one goal can be active at a time)\n- `goal.complete() -> dict`: mark goal as completed and get final goal status\n\n## Heartbeat\n\nIn prime-agent, agents can create heartbeats to wake themselves up after a given period of time with remembered instructions, recurrently on a given schedule.\n\n- `rlm_heartbeat.create(instruction: str, interval: str | None = None, label: str | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`: new recurring heartbeat for this session; `interval` is a schedule string (default: every 5 minutes); `delivery_mode`: steer (default) interrupts a busy session's current turn, follow_up waits for it to finish\n- `rlm_heartbeat.list(include_inactive: bool = False) -> dict`\n- `rlm_heartbeat.update(id: str, instruction: str | None = None, interval: str | None = None, label: str | None = None, status: Literal[\"pause\", \"resume\"] | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`\n- `rlm_heartbeat.delete(id: str) -> dict`\n\n## MCP\n\nprime-agent has support for programmatic tools that are defined in the MCP format. Their schema is discovered at runtime.\n\n- `mcp.list_tools(server: str) -> list[dict]`: returns tool schemas\n- `mcp.call_tool(server: str, tool: str, arguments: dict | None = None) -> Any`\n\n## Skills\n\nprime-agent provides multiple executable skills, described by their SKILL.md and executable code. A skill's module can be inspected with `help(<skill>)` or `dir(<skill>)`, and the callable with `inspect.signature(<skill>.<function>)`, if information is missing. The executable code is always pre-imported in the REPL as a programmatic tool, and a callable skill module can be called directly (`await <skill>(...)`).\n\nAll programmatic tools described above except for `bash`, `rlm.*`, and `mcp.*` are implemented as executable skills and will be listed again in the dynamic tail of this prompt. Additional executable and non-executable skills may exist as well; non-executable (markdown) skills are documentation read from disk, and each skill is also available as a shell command by the same name.\n\nThe following are mandatory rules, only to be overridden by clear user intent.\n\n- Memories must be kept lean and up-to-date.\n- `goal.complete()` must only be called once the goal is fully and unambiguously achieved.\n- Goals must only be created at a user's request.\n- Agents run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n- `bash(\"\"\"...\"\"\")` should be used over `bash(\"...\")` because it makes using quotation marks inside bash easy.\n- Bash commands must be run in the background; if they are quick, or the agent is doing other heavy work in the same `ipython` call, they should be awaited or polled in the same `ipython` call interleaved with other work, or a subsequent one; otherwise, the agent should wait for the notification; blocking calls reduce user responsiveness.\n- Shell state does not persist between calls, but agents can use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls through POSIX process inheritance (since each bash call is a fresh process, Python does not inherit environment variables from bash).\n- Edits of existing files must be performed using `edit` with exact old/new strings; if the text contains triple double quotes (\"\"\"), the agent should use triple single-quoted variables or build `old`/`new` from inspected file slices.\n- Agents use Python for reading files and searching in them \u2014 it gives them reusable variables they can slice, filter, and act on without re-reading; using Python variables to find or produce, and to save the strings used in `edit` is also encouraged.\n- Agents always assign read/search results to named variables so they can revisit them later.\n- Agents must report assumptions they made and constants they changed to the user.\n- When an agent is done, they stop calling tools and state their final answer.\n- When delegation is available and useful, an agent assigns independent substantive tasks to separate workers. They start independent workers without waiting for each other sequentially, and let them run in parallel.\n- Agents do not keep the turn open by polling with `time.sleep()` or shell `sleep`, and they do not replace polling with a long blocking `await`. They await only the short operation needed to start work or inspect a result that is already available; otherwise they end the turn.\n- Agents use the Python REPL to keep intermediate variables, inspect and transform outputs, and write small helper functions.\n- Since compaction removes individual variables whose serialized form exceeds 16 MiB, agents can keep large source data on disk and reload it when needed.\n- Python is the orchestration language: agents use Python for loops, conditionals, parsing, and state. They use `bash()` to invoke programs, not to write shell programs, shell loops, or heredocs; those are done directly in Python.\n- Agents do not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Agents evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n- Agents do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, they run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Agents treat failures from that native environment as the relevant result.\n- Rules for root agents (depth 0):\n - Only message siblings if you are certain that it is necessary.\n - When work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n- Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n- Agents treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: they diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. They use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so agents continue working normally after calling it. Agents do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n- Instructions to agents for multi-agent work:\n - When spawning a subagent, keep the handle to stop or inspect the child later.\n - Ask for an explicit reply when needed; not every message needs a reply.\n - Use `await rlm.list_subagents()` after kernel restart or compaction.\n - Have children write files and read those files for fan-in.\n - Delegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\n\nThe following guidelines to agents have been shown to improve results on average. Agents should consider using them where appropriate. Clear user instructions always override these defaults.\n\n- Agents can use the following patterns to make better use of the REPL:\n - Write wrappers around `rlm.spawn` to have quick templates for subagents with arbitrary args: for text to programmatically pass and put into the prompt, for conditional behavior prompts, etc.\n - Use f-strings (`f\"\"\"...\"\"\"` or `f\"...\"`) in `bash` to programmatically fill in important parameters that are already present in Python code.\n- When writing or explaining something:\n - Agents use simplified technical English by default for user-facing prose: short sentences, common words, and concrete verbs; one main action or fact per sentence when practical; lists for steps or conditions. Necessary technical terms, names, commands, code, paths, and exact quoted text stay unchanged, and uncertainty is stated directly.\n - Agents use ordinary or established wording. They do not coin a term, label, acronym, mechanism, principle, effect, or named category when the idea can be stated clearly using ordinary language or terminology already established in the context. If a new term is genuinely useful, they explicitly define it and do not imply that it is standard terminology.\n - Agents keep names and terms consistent. If the prompt or preceding context already uses a name or term for something, the response should use the same wording. Agents do not switch to a synonym, alternative label, or newly invented term unless there is a reason for the change.\n- Agents take care and effort to avoid the following pitfalls while coding:\n - over-engineered solutions\n - overly defensive programming\n - hyper-fixation on rare/fictitious edge cases\n - overlapping subsystem responsibilities\n - solving problems at the wrong architectural layer\n - duplication of sources of truth, then inventing machinery to synchronize them\n - prematurely generalizing one-off flows\n - timeouts on everything\n - production code that exists purely to satisfy tests\n - patching bad premises additively instead of stepping back and deleting or adjusting them\n - tests for magic strings\n - excessive tests\n - comments that describe anything already described by the code\n - comments narrating the coding process instead of supporting the written code\n - fallbacks, legacy support, compatibility shims where not strictly needed; when in doubt, these should be discussed with the user\n - in UI, descriptions on everything\n\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/hb-fire/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/websearch/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/compact/SKILL.md</location>\n </skill>\n</available_skills>\n\nCurrent date: 2026-09-21\nWorking directory: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/work\nConversation log: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/agent/sessions/01a0c5da-30de-765e-8f59-5bb56234b693.jsonl\nImage input: this model cannot see images; `attach_image` errors for it.\n\nRecursive agent depth: 0 (root)"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}, {"role": "assistant", "content": "heartbeat fire verifier seed reply"}, {"role": "user", "content": [{"type": "text", "text": "create the agent heartbeat"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "# prime-agent harness\n\nThe prime-agent harness has one tool: `ipython`, a persistent CPython REPL. All other tools are \"programmatic tools\", functions inside the Python REPL called via \"programmatic tool calling\" (PTC). All programmatic tools are async unless described otherwise and can be run in the background. `await` works directly and globally in the REPL.\n\nThe harness often sends messages to the agent. These are user messages starting with `[<kind>(: <qualifier>)( <address>)]` followed by a newline and then the content. They are not user-generated.\n\n## Core tools\n\n- `bash(command: str) -> BashHandle`: synchronous, returns immediately and runs the command in the background; when a command is finished outside the calling `ipython` block, a notification is sent to the agent; each `bash()` call is its own process, so shell state does not persist between calls\n - `BashHandle`:\n - `.pid: int`\n - `.running: bool`\n - `.command: str`\n - `.tail(n: int = 50) -> str`\n - `.output() -> str`\n - `.poll() -> BashResult | None`\n - `.kill(sig: int = SIGTERM, grace: float = 5.0) -> None`: SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive\n - `await handle -> BashResult`: the handle is awaitable even after command completion, so agents can run commands non-blocking and await them after being notified of them finishing\n - `BashResult`\n - `.exit_code: int`\n - `.output: str`\n - `.duration: float`\n- `edit.run(path: str, old_str: str, new_str: str) -> str`: the primary method for editing files. async, exact-unique-match; the `edit` module is callable with the same arguments (`await edit(path=..., old_str=..., new_str=...)`)\n- `websearch.run(query: str, *, max_output: int = 8192, timeout: int | None, num_results: int | None) -> str`: search the web; the `websearch` module is callable with the same arguments\n- `attach_image(*paths: str) -> str`: loads images directly into context if the agent's model is vision-capable, errors otherwise\n\n## Subagents\n\nprime-agent is a recursive harness. Each session builds a tree of agents, starting at depth 0. Each agent up to a user-configured limit can launch subagents. These subagents are persistent, just like the root session. Each agent can communicate with its nuclear family: its singular parent (except for depth 0 sessions which have no parent), its siblings (other subagents under the same parent), and its children (its own subagents).\n\nThe following programmatic tools are available in the REPL for subagent management:\n\n- `rlm.spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None) -> RLMSpawnHandle`: spawns a new subagent one level deeper than the caller; returns immediately; errors when the caller cannot create subagents; if not given, `model` and `thinking` are inherited from the parent; results never arrive as `rlm.spawn()` return values, they arrive only via agent_message; `name` must be unique among the spawned agent's siblings, and be meaningful and descriptive but short\n- `rlm.create_session(prompt: str, name: str | None = None, model: str | None = None, thinking: str | None = None, cwd: str | None = None) -> RLMCreateSessionHandle`: creates another depth-0 session; only available to agents at depth 0 backed by a daemon; returns after the session is successfully created and the first prompt sent\n- `rlm.find_models(query: str = '', limit: int = 8) -> list[RLMModel]`\n- `rlm.list_subagents() -> list[RLMSubagent]`: direct child handles\n- `rlm.delete_subagent(target: str | RLMSubagent) -> RLMSubagent`\n- `rlm.collect(targets=None, *, timeout_ms: int = 0) -> list[RLMChildResult]`: typed snapshots of direct children (status, settled flag, answer preview, error) without steering anyone; `timeout_ms=0` returns a non-blocking snapshot; a positive timeout blocks only this call until the children settle or the deadline passes\n- `rlm.progress_note(message: str) -> dict`: report brief in-flight progress to the parent orchestrator (at most 512 characters, throttled to about one note per 10 seconds); the parent sees notes without needing a reply\n- `RLMSpawnHandle`\n - `rlm_child_id: str`\n - `name: str`\n - `session_dir: Path`\n - `model: str`: provider/model, full resolved model name\n- `RLMCreateSessionHandle`\n - `active_session_id: str`: live daemon-instance id\n - `session_id: str`: durable on-disk session identity\n - `name: str`\n - `session_file: Path`: path to persisted session log\n - `model: str`: provider/model, full resolved model name\n- `RLMSubagent`\n - `rlm_child_id: str`\n - `active_session_id: str | None`\n - `session_id: str | None`\n - `session_name: str`\n - `session_dir: Path`\n - `status: Literal[\"running\", \"completed\", \"error\"]`\n - rows also carry live activity detail (current activity, tool use count, duration, answer preview, latest progress note)\n- `RLMModel`\n - `provider: str`\n - `id: str`\n - `name: str`\n - `selector: str`: the exact string to spawn the model\n\nThe following programmatic tools are available in the REPL for a2a communication:\n\n- `agent_message.send(message: str, *, receiver_role: Literal[\"parent\", \"sibling\", \"child\"], receiver_name: str | None) -> dict`: send a message to the receiver; returns a receipt with the message id and a delivery status (delivered or queued); all root sessions are siblings; `send(\"all\", broadcast_message)` broadcasts to the family roster and returns `{receipts: [...]}`\n- `agent_observe.list_agents() -> dict`: list nuclear family\n- `agent_observe.get_agent(target: str) -> dict`: one agent's status detail\n- `agent_observe.recent_messages(target: str, limit: int = 8, max_chars: int = 800) -> dict`: transcript preview; `limit` errors outside [1-50], `max_chars` outside [80-2000]\n\n## Continual Harness\n\nprime-agent is a continual harness. During a session, persistent memories can be written and read. These stay available even after multiple compactions.\n\nMemories are created by two mechanisms:\n\n- Refinement\n - Mechanism:\n - Another model suggests a refinement based on the transcript\n - The suggested edits are applied to the harness state\n - The main agent is notified by a structured harness message and the applied edits are saved\n - Triggered by:\n - Calling the programmatic tool `refine.run()`\n - By the user command `/refine`\n - Effect:\n - The refinement event is always saved in the harness state's refinement history\n - A harness message is sent to the agent with the refinement result\n- Active memory management by the agent\n - `refine.run(instructions: str | None = None, global_: bool = False) -> dict`: agent-triggered refinement (see above); returns immediately and runs when the current turn ends\n- `refine.status() -> dict`: whether a refinement is already pending for this turn or currently in flight\n - `rlm.harness.create_memory(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: creates a memory; use `global_=True` for cross-session entries (Python reserves `global`, so the parameter is spelled `global_`)\n - `rlm.harness.update_memory(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_memory(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_prompt_note(title: str, content: str, *, id: str | None = None, path: str = \"policy\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_prompt_note(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_prompt_note(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_skill(title: str, content: str, *, id: str | None = None, path: str = \"general\", reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: `reference`/`arguments` describe the Python callable (`reference` requires `{\"type\": \"python\"}`, a Python import, and a callable or call pattern)\n - `rlm.harness.update_skill(id: str, title: str, content: str, *, path: str | None = None, reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_skill(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_subagent(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_subagent(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_subagent(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.record_refinement(trigger: str, changes: list[str], *, evidence: str = \"\", outcome: str = \"\", id: str | None = None, global_: bool = False) -> RefinementEvent`\n - `rlm.harness.plan_refinement(observation: str, *, failing_component: str = \"\", next_step: str = \"\") -> list[str]`: a suggested diagnose -> update -> validate plan\n - `rlm.harness.overview(*, max_entries_per_kind: int = 20, global_: bool = False) -> str`: memory overview\n - `rlm.harness.search(query: str, kind: str | None = None, limit: int = 10, *, global_: bool = False) -> list[HarnessEntry]`: ranked term search over entries\n - `rlm.get_harness_state(state_dir: str | Path | None = None, *, global_: bool = False) -> HarnessState`: full memory details for the selected scope. Can read another agent's `HarnessState` by passing the path to it in `state_dir`\n - `HarnessEntry`\n - `id: str`\n - `kind: Literal[\"prompt\", \"memory\", \"skill\", \"subagent\"]`\n - `title: str`\n - `content: str`\n - `path: str`: category path (\"general\" for memories, \"policy\" for prompt notes)\n - `scope: Literal[\"local\", \"global\"]`\n - `reference: dict[str, Any]`: for skills\n - `arguments: dict[str, Any]`: for skills\n - `metadata: dict`\n - `source: Literal[\"agent\", \"refine\"]`\n - `created_at: str`: ISO timestamp of creation\n - `updated_at: str`: ISO timestamp of latest update\n - `version: int`: increments with every update, starting at 1\n - `HarnessState`\n - `scope: Literal[\"global\", \"local\"]`\n - `file_path: Path`\n - `entries: dict[kind, dict[id, HarnessEntry]]`\n - `refinements: list[RefinementEvent]`\n - `RefinementEvent`\n - `id: str`\n - `trigger: str`: what caused the refinement\n - `changes: list[str]`: applied edits; empty if never edited\n - `evidence: str`\n - `outcome: str`\n - `created_at: str`\n\n## Compaction\n\nprime-agent compacts automatically when there is only a given number of tokens left in the context window (default: 16384), when the user triggers compaction, or when the agent triggers compaction. REPL state persists across compactions, but compaction removes individual variables whose serialized form exceeds 16 MiB.\n\n- `compact.run(instructions: str | None = None) -> dict`: schedule a compaction at the next assistant turn boundary\n- `compact.status() -> dict`: context usage & threshold before auto-compaction\n\n## Goal\n\nIn goal mode prime-agent helps an agent stay on track until a task is fully finished, and handles interruptions and other issues. Goals can be user- or agent-created.\n\n- `goal.create(objective: str, token_budget: int | None = None) -> dict`: create goal and return goal state\n- `goal.get() -> dict`: get goal status (only one goal can be active at a time)\n- `goal.complete() -> dict`: mark goal as completed and get final goal status\n\n## Heartbeat\n\nIn prime-agent, agents can create heartbeats to wake themselves up after a given period of time with remembered instructions, recurrently on a given schedule.\n\n- `rlm_heartbeat.create(instruction: str, interval: str | None = None, label: str | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`: new recurring heartbeat for this session; `interval` is a schedule string (default: every 5 minutes); `delivery_mode`: steer (default) interrupts a busy session's current turn, follow_up waits for it to finish\n- `rlm_heartbeat.list(include_inactive: bool = False) -> dict`\n- `rlm_heartbeat.update(id: str, instruction: str | None = None, interval: str | None = None, label: str | None = None, status: Literal[\"pause\", \"resume\"] | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`\n- `rlm_heartbeat.delete(id: str) -> dict`\n\n## MCP\n\nprime-agent has support for programmatic tools that are defined in the MCP format. Their schema is discovered at runtime.\n\n- `mcp.list_tools(server: str) -> list[dict]`: returns tool schemas\n- `mcp.call_tool(server: str, tool: str, arguments: dict | None = None) -> Any`\n\n## Skills\n\nprime-agent provides multiple executable skills, described by their SKILL.md and executable code. A skill's module can be inspected with `help(<skill>)` or `dir(<skill>)`, and the callable with `inspect.signature(<skill>.<function>)`, if information is missing. The executable code is always pre-imported in the REPL as a programmatic tool, and a callable skill module can be called directly (`await <skill>(...)`).\n\nAll programmatic tools described above except for `bash`, `rlm.*`, and `mcp.*` are implemented as executable skills and will be listed again in the dynamic tail of this prompt. Additional executable and non-executable skills may exist as well; non-executable (markdown) skills are documentation read from disk, and each skill is also available as a shell command by the same name.\n\nThe following are mandatory rules, only to be overridden by clear user intent.\n\n- Memories must be kept lean and up-to-date.\n- `goal.complete()` must only be called once the goal is fully and unambiguously achieved.\n- Goals must only be created at a user's request.\n- Agents run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n- `bash(\"\"\"...\"\"\")` should be used over `bash(\"...\")` because it makes using quotation marks inside bash easy.\n- Bash commands must be run in the background; if they are quick, or the agent is doing other heavy work in the same `ipython` call, they should be awaited or polled in the same `ipython` call interleaved with other work, or a subsequent one; otherwise, the agent should wait for the notification; blocking calls reduce user responsiveness.\n- Shell state does not persist between calls, but agents can use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls through POSIX process inheritance (since each bash call is a fresh process, Python does not inherit environment variables from bash).\n- Edits of existing files must be performed using `edit` with exact old/new strings; if the text contains triple double quotes (\"\"\"), the agent should use triple single-quoted variables or build `old`/`new` from inspected file slices.\n- Agents use Python for reading files and searching in them \u2014 it gives them reusable variables they can slice, filter, and act on without re-reading; using Python variables to find or produce, and to save the strings used in `edit` is also encouraged.\n- Agents always assign read/search results to named variables so they can revisit them later.\n- Agents must report assumptions they made and constants they changed to the user.\n- When an agent is done, they stop calling tools and state their final answer.\n- When delegation is available and useful, an agent assigns independent substantive tasks to separate workers. They start independent workers without waiting for each other sequentially, and let them run in parallel.\n- Agents do not keep the turn open by polling with `time.sleep()` or shell `sleep`, and they do not replace polling with a long blocking `await`. They await only the short operation needed to start work or inspect a result that is already available; otherwise they end the turn.\n- Agents use the Python REPL to keep intermediate variables, inspect and transform outputs, and write small helper functions.\n- Since compaction removes individual variables whose serialized form exceeds 16 MiB, agents can keep large source data on disk and reload it when needed.\n- Python is the orchestration language: agents use Python for loops, conditionals, parsing, and state. They use `bash()` to invoke programs, not to write shell programs, shell loops, or heredocs; those are done directly in Python.\n- Agents do not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Agents evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n- Agents do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, they run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Agents treat failures from that native environment as the relevant result.\n- Rules for root agents (depth 0):\n - Only message siblings if you are certain that it is necessary.\n - When work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n- Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n- Agents treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: they diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. They use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so agents continue working normally after calling it. Agents do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n- Instructions to agents for multi-agent work:\n - When spawning a subagent, keep the handle to stop or inspect the child later.\n - Ask for an explicit reply when needed; not every message needs a reply.\n - Use `await rlm.list_subagents()` after kernel restart or compaction.\n - Have children write files and read those files for fan-in.\n - Delegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\n\nThe following guidelines to agents have been shown to improve results on average. Agents should consider using them where appropriate. Clear user instructions always override these defaults.\n\n- Agents can use the following patterns to make better use of the REPL:\n - Write wrappers around `rlm.spawn` to have quick templates for subagents with arbitrary args: for text to programmatically pass and put into the prompt, for conditional behavior prompts, etc.\n - Use f-strings (`f\"\"\"...\"\"\"` or `f\"...\"`) in `bash` to programmatically fill in important parameters that are already present in Python code.\n- When writing or explaining something:\n - Agents use simplified technical English by default for user-facing prose: short sentences, common words, and concrete verbs; one main action or fact per sentence when practical; lists for steps or conditions. Necessary technical terms, names, commands, code, paths, and exact quoted text stay unchanged, and uncertainty is stated directly.\n - Agents use ordinary or established wording. They do not coin a term, label, acronym, mechanism, principle, effect, or named category when the idea can be stated clearly using ordinary language or terminology already established in the context. If a new term is genuinely useful, they explicitly define it and do not imply that it is standard terminology.\n - Agents keep names and terms consistent. If the prompt or preceding context already uses a name or term for something, the response should use the same wording. Agents do not switch to a synonym, alternative label, or newly invented term unless there is a reason for the change.\n- Agents take care and effort to avoid the following pitfalls while coding:\n - over-engineered solutions\n - overly defensive programming\n - hyper-fixation on rare/fictitious edge cases\n - overlapping subsystem responsibilities\n - solving problems at the wrong architectural layer\n - duplication of sources of truth, then inventing machinery to synchronize them\n - prematurely generalizing one-off flows\n - timeouts on everything\n - production code that exists purely to satisfy tests\n - patching bad premises additively instead of stepping back and deleting or adjusting them\n - tests for magic strings\n - excessive tests\n - comments that describe anything already described by the code\n - comments narrating the coding process instead of supporting the written code\n - fallbacks, legacy support, compatibility shims where not strictly needed; when in doubt, these should be discussed with the user\n - in UI, descriptions on everything\n\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/hb-fire/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/websearch/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/compact/SKILL.md</location>\n </skill>\n</available_skills>\n\nCurrent date: 2026-09-21\nWorking directory: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/work\nConversation log: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/agent/sessions/01a0c5da-30de-765e-8f59-5bb56234b693.jsonl\nImage input: this model cannot see images; `attach_image` errors for it.\n\nRecursive agent depth: 0 (root)"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}, {"role": "assistant", "content": "heartbeat fire verifier seed reply"}, {"role": "user", "content": [{"type": "text", "text": "create the agent heartbeat"}]}, {"role": "assistant", "content": null, "tool_calls": [{"id": "call_battery_1", "type": "function", "function": {"name": "ipython", "arguments": "{\"code\":\"import rlm_heartbeat\\nhb = await rlm_heartbeat.create(\\n 'agent heartbeat fire probe instruction',\\n interval='every 30s',\\n label='hb-fire',\\n)\\nprint('created', hb['id'])\"}"}}]}, {"role": "tool", "content": "Traceback (most recent call last):\n\n File \"<cell-2>\", line 7, in <module>\n print('created', hb['id'])\n ~~^^^^^^\n\nKeyError: 'id'\n", "tool_call_id": "call_battery_1"}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "qwen/qwen3-30b-a3b-instruct-2507", "messages": [{"role": "system", "content": "You generate a status line for an AI coding agent dashboard. You are given the recent conversation between a user and the agent, plus whether the agent is currently working or idle.\n\nOutput ONLY these two tags, nothing before, between, or after. Do not think out loud, explain, or count words.\n<recap>a present-tense clause, at most 12 words, saying what the agent is doing or just did, no trailing period</recap>\n<status>one of NEEDS_INPUT, COMPLETED</status>\n\nSTATUS meaning:\n- COMPLETED: the agent finished its turn AND the user's request is fully done with nothing left.\n- NEEDS_INPUT: the agent finished its turn but the task is not fully done \u2014 it asked a question, hit a blocker, or needs more prompting.\nWhen you are unsure between COMPLETED and NEEDS_INPUT, choose NEEDS_INPUT.\n\nExample:\n<recap>Refactoring the auth middleware and updating its tests</recap>\n<status>NEEDS_INPUT</status>"}, {"role": "user", "content": "<agent-state>idle (finished its turn)</agent-state>\n<conversation>\nuser: verifier seed turn\nassistant: heartbeat fire verifier seed reply\nuser: create the agent heartbeat\ntoolResult: Traceback (most recent call last): File \"<cell-2>\", line 7, in <module> print('created', hb['id']) ~~^^^^^^ KeyError: 'id'\nassistant: agent heartbeat created\n</conversation>"}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 400}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "# prime-agent harness\n\nThe prime-agent harness has one tool: `ipython`, a persistent CPython REPL. All other tools are \"programmatic tools\", functions inside the Python REPL called via \"programmatic tool calling\" (PTC). All programmatic tools are async unless described otherwise and can be run in the background. `await` works directly and globally in the REPL.\n\nThe harness often sends messages to the agent. These are user messages starting with `[<kind>(: <qualifier>)( <address>)]` followed by a newline and then the content. They are not user-generated.\n\n## Core tools\n\n- `bash(command: str) -> BashHandle`: synchronous, returns immediately and runs the command in the background; when a command is finished outside the calling `ipython` block, a notification is sent to the agent; each `bash()` call is its own process, so shell state does not persist between calls\n - `BashHandle`:\n - `.pid: int`\n - `.running: bool`\n - `.command: str`\n - `.tail(n: int = 50) -> str`\n - `.output() -> str`\n - `.poll() -> BashResult | None`\n - `.kill(sig: int = SIGTERM, grace: float = 5.0) -> None`: SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive\n - `await handle -> BashResult`: the handle is awaitable even after command completion, so agents can run commands non-blocking and await them after being notified of them finishing\n - `BashResult`\n - `.exit_code: int`\n - `.output: str`\n - `.duration: float`\n- `edit.run(path: str, old_str: str, new_str: str) -> str`: the primary method for editing files. async, exact-unique-match; the `edit` module is callable with the same arguments (`await edit(path=..., old_str=..., new_str=...)`)\n- `websearch.run(query: str, *, max_output: int = 8192, timeout: int | None, num_results: int | None) -> str`: search the web; the `websearch` module is callable with the same arguments\n- `attach_image(*paths: str) -> str`: loads images directly into context if the agent's model is vision-capable, errors otherwise\n\n## Subagents\n\nprime-agent is a recursive harness. Each session builds a tree of agents, starting at depth 0. Each agent up to a user-configured limit can launch subagents. These subagents are persistent, just like the root session. Each agent can communicate with its nuclear family: its singular parent (except for depth 0 sessions which have no parent), its siblings (other subagents under the same parent), and its children (its own subagents).\n\nThe following programmatic tools are available in the REPL for subagent management:\n\n- `rlm.spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None) -> RLMSpawnHandle`: spawns a new subagent one level deeper than the caller; returns immediately; errors when the caller cannot create subagents; if not given, `model` and `thinking` are inherited from the parent; results never arrive as `rlm.spawn()` return values, they arrive only via agent_message; `name` must be unique among the spawned agent's siblings, and be meaningful and descriptive but short\n- `rlm.create_session(prompt: str, name: str | None = None, model: str | None = None, thinking: str | None = None, cwd: str | None = None) -> RLMCreateSessionHandle`: creates another depth-0 session; only available to agents at depth 0 backed by a daemon; returns after the session is successfully created and the first prompt sent\n- `rlm.find_models(query: str = '', limit: int = 8) -> list[RLMModel]`\n- `rlm.list_subagents() -> list[RLMSubagent]`: direct child handles\n- `rlm.delete_subagent(target: str | RLMSubagent) -> RLMSubagent`\n- `rlm.collect(targets=None, *, timeout_ms: int = 0) -> list[RLMChildResult]`: typed snapshots of direct children (status, settled flag, answer preview, error) without steering anyone; `timeout_ms=0` returns a non-blocking snapshot; a positive timeout blocks only this call until the children settle or the deadline passes\n- `rlm.progress_note(message: str) -> dict`: report brief in-flight progress to the parent orchestrator (at most 512 characters, throttled to about one note per 10 seconds); the parent sees notes without needing a reply\n- `RLMSpawnHandle`\n - `rlm_child_id: str`\n - `name: str`\n - `session_dir: Path`\n - `model: str`: provider/model, full resolved model name\n- `RLMCreateSessionHandle`\n - `active_session_id: str`: live daemon-instance id\n - `session_id: str`: durable on-disk session identity\n - `name: str`\n - `session_file: Path`: path to persisted session log\n - `model: str`: provider/model, full resolved model name\n- `RLMSubagent`\n - `rlm_child_id: str`\n - `active_session_id: str | None`\n - `session_id: str | None`\n - `session_name: str`\n - `session_dir: Path`\n - `status: Literal[\"running\", \"completed\", \"error\"]`\n - rows also carry live activity detail (current activity, tool use count, duration, answer preview, latest progress note)\n- `RLMModel`\n - `provider: str`\n - `id: str`\n - `name: str`\n - `selector: str`: the exact string to spawn the model\n\nThe following programmatic tools are available in the REPL for a2a communication:\n\n- `agent_message.send(message: str, *, receiver_role: Literal[\"parent\", \"sibling\", \"child\"], receiver_name: str | None) -> dict`: send a message to the receiver; returns a receipt with the message id and a delivery status (delivered or queued); all root sessions are siblings; `send(\"all\", broadcast_message)` broadcasts to the family roster and returns `{receipts: [...]}`\n- `agent_observe.list_agents() -> dict`: list nuclear family\n- `agent_observe.get_agent(target: str) -> dict`: one agent's status detail\n- `agent_observe.recent_messages(target: str, limit: int = 8, max_chars: int = 800) -> dict`: transcript preview; `limit` errors outside [1-50], `max_chars` outside [80-2000]\n\n## Continual Harness\n\nprime-agent is a continual harness. During a session, persistent memories can be written and read. These stay available even after multiple compactions.\n\nMemories are created by two mechanisms:\n\n- Refinement\n - Mechanism:\n - Another model suggests a refinement based on the transcript\n - The suggested edits are applied to the harness state\n - The main agent is notified by a structured harness message and the applied edits are saved\n - Triggered by:\n - Calling the programmatic tool `refine.run()`\n - By the user command `/refine`\n - Effect:\n - The refinement event is always saved in the harness state's refinement history\n - A harness message is sent to the agent with the refinement result\n- Active memory management by the agent\n - `refine.run(instructions: str | None = None, global_: bool = False) -> dict`: agent-triggered refinement (see above); returns immediately and runs when the current turn ends\n- `refine.status() -> dict`: whether a refinement is already pending for this turn or currently in flight\n - `rlm.harness.create_memory(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: creates a memory; use `global_=True` for cross-session entries (Python reserves `global`, so the parameter is spelled `global_`)\n - `rlm.harness.update_memory(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_memory(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_prompt_note(title: str, content: str, *, id: str | None = None, path: str = \"policy\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_prompt_note(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_prompt_note(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_skill(title: str, content: str, *, id: str | None = None, path: str = \"general\", reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: `reference`/`arguments` describe the Python callable (`reference` requires `{\"type\": \"python\"}`, a Python import, and a callable or call pattern)\n - `rlm.harness.update_skill(id: str, title: str, content: str, *, path: str | None = None, reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_skill(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_subagent(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_subagent(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_subagent(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.record_refinement(trigger: str, changes: list[str], *, evidence: str = \"\", outcome: str = \"\", id: str | None = None, global_: bool = False) -> RefinementEvent`\n - `rlm.harness.plan_refinement(observation: str, *, failing_component: str = \"\", next_step: str = \"\") -> list[str]`: a suggested diagnose -> update -> validate plan\n - `rlm.harness.overview(*, max_entries_per_kind: int = 20, global_: bool = False) -> str`: memory overview\n - `rlm.harness.search(query: str, kind: str | None = None, limit: int = 10, *, global_: bool = False) -> list[HarnessEntry]`: ranked term search over entries\n - `rlm.get_harness_state(state_dir: str | Path | None = None, *, global_: bool = False) -> HarnessState`: full memory details for the selected scope. Can read another agent's `HarnessState` by passing the path to it in `state_dir`\n - `HarnessEntry`\n - `id: str`\n - `kind: Literal[\"prompt\", \"memory\", \"skill\", \"subagent\"]`\n - `title: str`\n - `content: str`\n - `path: str`: category path (\"general\" for memories, \"policy\" for prompt notes)\n - `scope: Literal[\"local\", \"global\"]`\n - `reference: dict[str, Any]`: for skills\n - `arguments: dict[str, Any]`: for skills\n - `metadata: dict`\n - `source: Literal[\"agent\", \"refine\"]`\n - `created_at: str`: ISO timestamp of creation\n - `updated_at: str`: ISO timestamp of latest update\n - `version: int`: increments with every update, starting at 1\n - `HarnessState`\n - `scope: Literal[\"global\", \"local\"]`\n - `file_path: Path`\n - `entries: dict[kind, dict[id, HarnessEntry]]`\n - `refinements: list[RefinementEvent]`\n - `RefinementEvent`\n - `id: str`\n - `trigger: str`: what caused the refinement\n - `changes: list[str]`: applied edits; empty if never edited\n - `evidence: str`\n - `outcome: str`\n - `created_at: str`\n\n## Compaction\n\nprime-agent compacts automatically when there is only a given number of tokens left in the context window (default: 16384), when the user triggers compaction, or when the agent triggers compaction. REPL state persists across compactions, but compaction removes individual variables whose serialized form exceeds 16 MiB.\n\n- `compact.run(instructions: str | None = None) -> dict`: schedule a compaction at the next assistant turn boundary\n- `compact.status() -> dict`: context usage & threshold before auto-compaction\n\n## Goal\n\nIn goal mode prime-agent helps an agent stay on track until a task is fully finished, and handles interruptions and other issues. Goals can be user- or agent-created.\n\n- `goal.create(objective: str, token_budget: int | None = None) -> dict`: create goal and return goal state\n- `goal.get() -> dict`: get goal status (only one goal can be active at a time)\n- `goal.complete() -> dict`: mark goal as completed and get final goal status\n\n## Heartbeat\n\nIn prime-agent, agents can create heartbeats to wake themselves up after a given period of time with remembered instructions, recurrently on a given schedule.\n\n- `rlm_heartbeat.create(instruction: str, interval: str | None = None, label: str | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`: new recurring heartbeat for this session; `interval` is a schedule string (default: every 5 minutes); `delivery_mode`: steer (default) interrupts a busy session's current turn, follow_up waits for it to finish\n- `rlm_heartbeat.list(include_inactive: bool = False) -> dict`\n- `rlm_heartbeat.update(id: str, instruction: str | None = None, interval: str | None = None, label: str | None = None, status: Literal[\"pause\", \"resume\"] | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`\n- `rlm_heartbeat.delete(id: str) -> dict`\n\n## MCP\n\nprime-agent has support for programmatic tools that are defined in the MCP format. Their schema is discovered at runtime.\n\n- `mcp.list_tools(server: str) -> list[dict]`: returns tool schemas\n- `mcp.call_tool(server: str, tool: str, arguments: dict | None = None) -> Any`\n\n## Skills\n\nprime-agent provides multiple executable skills, described by their SKILL.md and executable code. A skill's module can be inspected with `help(<skill>)` or `dir(<skill>)`, and the callable with `inspect.signature(<skill>.<function>)`, if information is missing. The executable code is always pre-imported in the REPL as a programmatic tool, and a callable skill module can be called directly (`await <skill>(...)`).\n\nAll programmatic tools described above except for `bash`, `rlm.*`, and `mcp.*` are implemented as executable skills and will be listed again in the dynamic tail of this prompt. Additional executable and non-executable skills may exist as well; non-executable (markdown) skills are documentation read from disk, and each skill is also available as a shell command by the same name.\n\nThe following are mandatory rules, only to be overridden by clear user intent.\n\n- Memories must be kept lean and up-to-date.\n- `goal.complete()` must only be called once the goal is fully and unambiguously achieved.\n- Goals must only be created at a user's request.\n- Agents run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n- `bash(\"\"\"...\"\"\")` should be used over `bash(\"...\")` because it makes using quotation marks inside bash easy.\n- Bash commands must be run in the background; if they are quick, or the agent is doing other heavy work in the same `ipython` call, they should be awaited or polled in the same `ipython` call interleaved with other work, or a subsequent one; otherwise, the agent should wait for the notification; blocking calls reduce user responsiveness.\n- Shell state does not persist between calls, but agents can use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls through POSIX process inheritance (since each bash call is a fresh process, Python does not inherit environment variables from bash).\n- Edits of existing files must be performed using `edit` with exact old/new strings; if the text contains triple double quotes (\"\"\"), the agent should use triple single-quoted variables or build `old`/`new` from inspected file slices.\n- Agents use Python for reading files and searching in them \u2014 it gives them reusable variables they can slice, filter, and act on without re-reading; using Python variables to find or produce, and to save the strings used in `edit` is also encouraged.\n- Agents always assign read/search results to named variables so they can revisit them later.\n- Agents must report assumptions they made and constants they changed to the user.\n- When an agent is done, they stop calling tools and state their final answer.\n- When delegation is available and useful, an agent assigns independent substantive tasks to separate workers. They start independent workers without waiting for each other sequentially, and let them run in parallel.\n- Agents do not keep the turn open by polling with `time.sleep()` or shell `sleep`, and they do not replace polling with a long blocking `await`. They await only the short operation needed to start work or inspect a result that is already available; otherwise they end the turn.\n- Agents use the Python REPL to keep intermediate variables, inspect and transform outputs, and write small helper functions.\n- Since compaction removes individual variables whose serialized form exceeds 16 MiB, agents can keep large source data on disk and reload it when needed.\n- Python is the orchestration language: agents use Python for loops, conditionals, parsing, and state. They use `bash()` to invoke programs, not to write shell programs, shell loops, or heredocs; those are done directly in Python.\n- Agents do not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Agents evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n- Agents do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, they run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Agents treat failures from that native environment as the relevant result.\n- Rules for root agents (depth 0):\n - Only message siblings if you are certain that it is necessary.\n - When work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n- Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n- Agents treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: they diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. They use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so agents continue working normally after calling it. Agents do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n- Instructions to agents for multi-agent work:\n - When spawning a subagent, keep the handle to stop or inspect the child later.\n - Ask for an explicit reply when needed; not every message needs a reply.\n - Use `await rlm.list_subagents()` after kernel restart or compaction.\n - Have children write files and read those files for fan-in.\n - Delegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\n\nThe following guidelines to agents have been shown to improve results on average. Agents should consider using them where appropriate. Clear user instructions always override these defaults.\n\n- Agents can use the following patterns to make better use of the REPL:\n - Write wrappers around `rlm.spawn` to have quick templates for subagents with arbitrary args: for text to programmatically pass and put into the prompt, for conditional behavior prompts, etc.\n - Use f-strings (`f\"\"\"...\"\"\"` or `f\"...\"`) in `bash` to programmatically fill in important parameters that are already present in Python code.\n- When writing or explaining something:\n - Agents use simplified technical English by default for user-facing prose: short sentences, common words, and concrete verbs; one main action or fact per sentence when practical; lists for steps or conditions. Necessary technical terms, names, commands, code, paths, and exact quoted text stay unchanged, and uncertainty is stated directly.\n - Agents use ordinary or established wording. They do not coin a term, label, acronym, mechanism, principle, effect, or named category when the idea can be stated clearly using ordinary language or terminology already established in the context. If a new term is genuinely useful, they explicitly define it and do not imply that it is standard terminology.\n - Agents keep names and terms consistent. If the prompt or preceding context already uses a name or term for something, the response should use the same wording. Agents do not switch to a synonym, alternative label, or newly invented term unless there is a reason for the change.\n- Agents take care and effort to avoid the following pitfalls while coding:\n - over-engineered solutions\n - overly defensive programming\n - hyper-fixation on rare/fictitious edge cases\n - overlapping subsystem responsibilities\n - solving problems at the wrong architectural layer\n - duplication of sources of truth, then inventing machinery to synchronize them\n - prematurely generalizing one-off flows\n - timeouts on everything\n - production code that exists purely to satisfy tests\n - patching bad premises additively instead of stepping back and deleting or adjusting them\n - tests for magic strings\n - excessive tests\n - comments that describe anything already described by the code\n - comments narrating the coding process instead of supporting the written code\n - fallbacks, legacy support, compatibility shims where not strictly needed; when in doubt, these should be discussed with the user\n - in UI, descriptions on everything\n\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/hb-fire/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/websearch/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/lane-worktrees/hb-fire/skills/compact/SKILL.md</location>\n </skill>\n</available_skills>\n\nCurrent date: 2026-09-21\nWorking directory: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/work\nConversation log: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/rust/agent/sessions/01a0c5da-30de-765e-8f59-5bb56234b693.jsonl\nImage input: this model cannot see images; `attach_image` errors for it.\n\nRecursive agent depth: 0 (root)"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}, {"role": "assistant", "content": "heartbeat fire verifier seed reply"}, {"role": "user", "content": [{"type": "text", "text": "create the agent heartbeat"}]}, {"role": "assistant", "content": null, "tool_calls": [{"id": "call_battery_1", "type": "function", "function": {"name": "ipython", "arguments": "{\"code\":\"import rlm_heartbeat\\nhb = await rlm_heartbeat.create(\\n 'agent heartbeat fire probe instruction',\\n interval='every 30s',\\n label='hb-fire',\\n)\\nprint('created', hb['id'])\"}"}}]}, {"role": "tool", "content": "Traceback (most recent call last):\n\n File \"<cell-2>\", line 7, in <module>\n print('created', hb['id'])\n ~~^^^^^^\n\nKeyError: 'id'\n", "tool_call_id": "call_battery_1"}, {"role": "assistant", "content": "agent heartbeat created"}, {"role": "user", "content": [{"type": "text", "text": "agent heartbeat fire probe instruction"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}diff --git a/scripts/heartbeat-fire-runs/rust/summary.json b/scripts/heartbeat-fire-runs/rust/summary.jsondeleted file mode 100644index 36afb0f8d8..0000000000--- a/scripts/heartbeat-fire-runs/rust/summary.json+++ /dev/null@@ -1,56 +0,0 @@-[- {- "side": "rust",- "ok": true,- "summary": "seed turn ran",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "agent heartbeat turn ran",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "catalog lists the agent heartbeat",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "created job is active and unrun",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "created job runCount is 0",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "the heartbeat fired within the interval (runCount >= 1, runCount=1)",- "evidence": "02-fired-catalog.json"- },- {- "side": "rust",- "ok": true,- "summary": "the fire stamped lastRunAt",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "the fire rolled nextRunAt past the boundary",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "the fired prompt landed in the session transcript",- "evidence": "03-transcript-hit.txt"- }-]\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/ts/01-agent-heartbeat-turn.json b/scripts/heartbeat-fire-runs/ts/01-agent-heartbeat-turn.jsondeleted file mode 100644index 48b023caab..0000000000--- a/scripts/heartbeat-fire-runs/ts/01-agent-heartbeat-turn.json+++ /dev/null@@ -1,6 +0,0 @@-{- "id": "hb-agent",- "type": "response",- "command": "prompt_and_wait",- "success": true-}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/ts/02-fired-catalog.json b/scripts/heartbeat-fire-runs/ts/02-fired-catalog.jsondeleted file mode 100644index 8ab2253a5d..0000000000--- a/scripts/heartbeat-fire-runs/ts/02-fired-catalog.json+++ /dev/null@@ -1,29 +0,0 @@-[- {- "job": {- "id": "89608760-0332-4575-b842-20771d6c8c98",- "status": "active",- "source": "rlm_heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "0f673d7d862d",- "sessionId": "01a0c5da-c327-72be-89c5-905d51187775",- "sessionFile": "/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/agent/sessions/01a0c5da-c327-72be-89c5-905d51187775.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/work",- "label": "hb-fire",- "prompt": "agent heartbeat fire probe instruction",- "schedule": {- "kind": "interval",- "expression": "every 30s",- "intervalMs": 30000- },- "createdAt": "2026-09-21T21:24:08.560Z",- "updatedAt": "2026-09-21T21:24:38.593Z",- "nextRunAt": "2026-09-21T21:25:08.560Z",- "runCount": 1,- "lastRunAt": "2026-09-21T21:24:38.593Z"- },- "sessionName": "hb-fire-verifier",- "firstMessage": "verifier seed turn"- }-]\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/ts/03-transcript-hit.txt b/scripts/heartbeat-fire-runs/ts/03-transcript-hit.txtdeleted file mode 100644index 54a9f1c1f4..0000000000--- a/scripts/heartbeat-fire-runs/ts/03-transcript-hit.txt+++ /dev/null@@ -1,2 +0,0 @@-01a0c5da-c327-72be-89c5-905d51187775.jsonl-instruction: agent heartbeat fire probe instruction\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/ts/agent/auth.json b/scripts/heartbeat-fire-runs/ts/agent/auth.jsondeleted file mode 100644index 9e26dfeeb6..0000000000--- a/scripts/heartbeat-fire-runs/ts/agent/auth.json+++ /dev/null@@ -1 +0,0 @@-{}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/ts/agent/daemon-workers/7fc8ba629507/command-journal.jsonl b/scripts/heartbeat-fire-runs/ts/agent/daemon-workers/7fc8ba629507/command-journal.jsonldeleted file mode 100644index ec1b3159a5..0000000000--- a/scripts/heartbeat-fire-runs/ts/agent/daemon-workers/7fc8ba629507/command-journal.jsonl+++ /dev/null@@ -1,8 +0,0 @@-{"version":1,"type":"received","key":"[\"a9f6084a70e6\",\"hb-create\"]","clientId":"a9f6084a70e6","commandId":"hb-create","commandType":"create","recordedAt":"2026-09-21T21:24:03.260Z"}-{"version":1,"type":"result","key":"[\"a9f6084a70e6\",\"hb-create\"]","response":{"id":"hb-create","type":"response","command":"create","success":true,"data":{"id":"0f673d7d862d","lifecycle":"draft","activity":"idle","isSessionActive":false,"lastActivityAt":"2026-09-21T21:24:03.563Z","runtimeKind":"top-level","rlmDepth":0,"activeSessionId":"0f673d7d862d","sessionId":"01a0c5da-c327-72be-89c5-905d51187775","sessionFile":"/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/agent/sessions/01a0c5da-c327-72be-89c5-905d51187775.jsonl","sessionName":"hb-fire-verifier","cwd":"/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/work","model":{"id":"mock-1","name":"Mock 1","api":"openai-completions","provider":"prime-inference","baseUrl":"http://127.0.0.1:38781/v1","reasoning":false,"input":["text"],"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0},"contextWindow":128000,"maxTokens":4096},"thinkingLevel":"off","isStreaming":false,"isCompacting":false,"isBashRunning":false,"hasRunningRlmChildren":false,"isRunningTools":false,"attachedClients":0,"messageCount":0,"unfinishedActionCount":0,"created":"2026-09-21T21:24:03.495Z","modified":"2026-09-21T21:24:03.563Z","sessionActions":{"queuedCount":0,"steering":[],"followUps":[]},"rosterStatus":"idle","workerState":"ready","workerPid":2845796}},"recordedAt":"2026-09-21T21:24:03.577Z"}-{"version":1,"type":"received","key":"[\"a9f6084a70e6\",\"hb-seed\"]","clientId":"a9f6084a70e6","commandId":"hb-seed","commandType":"prompt_and_wait","recordedAt":"2026-09-21T21:24:03.583Z"}-{"version":1,"type":"result","key":"[\"a9f6084a70e6\",\"hb-seed\"]","response":{"id":"hb-seed","type":"response","command":"prompt_and_wait","success":true},"recordedAt":"2026-09-21T21:24:03.654Z"}-{"version":1,"type":"received","key":"[\"a9f6084a70e6\",\"hb-agent\"]","clientId":"a9f6084a70e6","commandId":"hb-agent","commandType":"prompt_and_wait","recordedAt":"2026-09-21T21:24:03.656Z"}-{"version":1,"type":"result","key":"[\"a9f6084a70e6\",\"hb-agent\"]","response":{"id":"hb-agent","type":"response","command":"prompt_and_wait","success":true},"recordedAt":"2026-09-21T21:24:08.590Z"}-{"version":1,"type":"received","key":"[\"97d972bb6302\",\"sd\"]","clientId":"97d972bb6302","commandId":"sd","commandType":"shutdown","recordedAt":"2026-09-21T21:24:38.650Z"}-{"version":1,"type":"result","key":"[\"97d972bb6302\",\"sd\"]","response":{"id":"sd","type":"response","command":"shutdown","success":true},"recordedAt":"2026-09-21T21:24:38.651Z"}diff --git a/scripts/heartbeat-fire-runs/ts/agent/logs/agent.jsonl b/scripts/heartbeat-fire-runs/ts/agent/logs/agent.jsonldeleted file mode 100644index 277cca8cb7..0000000000--- a/scripts/heartbeat-fire-runs/ts/agent/logs/agent.jsonl+++ /dev/null@@ -1,5 +0,0 @@-{"socketPath":"/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/daemon.sock","ts":"2026-09-21T21:24:03.259Z","level":"warn","component":"coding-agent.daemon-supervisor","msg":"Prime Agent daemon supervisor 5fd8a55d-f393-4f9e-8cf5-22105c79adaa listening on /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/daemon.sock","pid":2845769,"mode":"daemon"}-{"socketPath":"/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/daemon.sock","ts":"2026-09-21T21:24:03.481Z","level":"warn","component":"coding-agent.daemon-supervisor","msg":"Session worker a403535b1748 stderr: Prime Agent daemon listening on /tmp/hbf20260921T212401Z-ts/prime-agent-1000/worker-7fc8ba629507-a403535b1748.sock","pid":2845769,"mode":"daemon"}-{"socketPath":"/tmp/hbf20260921T212401Z-ts/prime-agent-1000/worker-7fc8ba629507-a403535b1748.sock","ts":"2026-09-21T21:24:03.481Z","level":"warn","component":"coding-agent.daemon","msg":"Prime Agent daemon listening on /tmp/hbf20260921T212401Z-ts/prime-agent-1000/worker-7fc8ba629507-a403535b1748.sock","pid":2845796,"mode":"daemon"}-{"socketPath":"/tmp/hbf20260921T212401Z-ts/prime-agent-1000/worker-7fc8ba629507-a403535b1748.sock","ts":"2026-09-21T21:24:38.825Z","level":"warn","component":"coding-agent.daemon","msg":"shutting down (exit 0); closing 0 active session(s)","pid":2845796,"mode":"daemon"}-{"socketPath":"/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/daemon.sock","ts":"2026-09-21T21:24:38.826Z","level":"warn","component":"coding-agent.daemon-supervisor","msg":"Session worker a403535b1748 stderr: shutting down (exit 0); closing 0 active session(s)","pid":2845769,"mode":"daemon"}diff --git a/scripts/heartbeat-fire-runs/ts/agent/logs/daemon.sock.7fc8ba62.log b/scripts/heartbeat-fire-runs/ts/agent/logs/daemon.sock.7fc8ba62.logdeleted file mode 100644index c6c9ad998c..0000000000--- a/scripts/heartbeat-fire-runs/ts/agent/logs/daemon.sock.7fc8ba62.log+++ /dev/null@@ -1,3 +0,0 @@-[2026-09-21T21:24:03.259Z] supervisor: Prime Agent daemon supervisor 5fd8a55d-f393-4f9e-8cf5-22105c79adaa listening on /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/daemon.sock-[2026-09-21T21:24:03.481Z] supervisor: Session worker a403535b1748 stderr: Prime Agent daemon listening on /tmp/hbf20260921T212401Z-ts/prime-agent-1000/worker-7fc8ba629507-a403535b1748.sock-[2026-09-21T21:24:38.826Z] supervisor: Session worker a403535b1748 stderr: shutting down (exit 0); closing 0 active session(s)diff --git a/scripts/heartbeat-fire-runs/ts/agent/logs/worker-7fc8ba629507-a403535b1748.sock.fe140197.log b/scripts/heartbeat-fire-runs/ts/agent/logs/worker-7fc8ba629507-a403535b1748.sock.fe140197.logdeleted file mode 100644index dc2afda6a9..0000000000--- a/scripts/heartbeat-fire-runs/ts/agent/logs/worker-7fc8ba629507-a403535b1748.sock.fe140197.log+++ /dev/null@@ -1,2 +0,0 @@-[2026-09-21T21:24:03.482Z] Prime Agent daemon listening on /tmp/hbf20260921T212401Z-ts/prime-agent-1000/worker-7fc8ba629507-a403535b1748.sock-[2026-09-21T21:24:38.826Z] shutting down (exit 0); closing 0 active session(s)diff --git a/scripts/heartbeat-fire-runs/ts/agent/models.json b/scripts/heartbeat-fire-runs/ts/agent/models.jsondeleted file mode 100644index 0a1f252a85..0000000000--- a/scripts/heartbeat-fire-runs/ts/agent/models.json+++ /dev/null@@ -1,19 +0,0 @@-{- "providers": {- "prime-inference": {- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:38781/v1",- "apiKey": "sk-battery",- "models": [- {- "id": "mock-1",- "name": "Mock 1",- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:38781/v1",- "contextWindow": 128000,- "maxTokens": 4096- }- ]- }- }-}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/ts/agent/session-artifacts/01a0c5da-c327-72be-89c5-905d51187775/kernel-state.dill b/scripts/heartbeat-fire-runs/ts/agent/session-artifacts/01a0c5da-c327-72be-89c5-905d51187775/kernel-state.dilldeleted file mode 100644index fc73d0fb36..0000000000Binary files a/scripts/heartbeat-fire-runs/ts/agent/session-artifacts/01a0c5da-c327-72be-89c5-905d51187775/kernel-state.dill and /dev/null differdiff --git a/scripts/heartbeat-fire-runs/ts/agent/session-artifacts/01a0c5da-c327-72be-89c5-905d51187775/kernel-state.json b/scripts/heartbeat-fire-runs/ts/agent/session-artifacts/01a0c5da-c327-72be-89c5-905d51187775/kernel-state.jsondeleted file mode 100644index 0e3605f9e4..0000000000--- a/scripts/heartbeat-fire-runs/ts/agent/session-artifacts/01a0c5da-c327-72be-89c5-905d51187775/kernel-state.json+++ /dev/null@@ -1 +0,0 @@-{"version": 1, "savedNames": ["agent_message", "agent_observe", "goal", "hb", "rlm_heartbeat"], "skipped": [{"name": "refine", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "compact", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "attach_image", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "edit", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "websearch", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}], "pruned": [], "bytes": 6475, "pythonVersion": "3.11.16", "timestamp": "2026-09-21T21:24:38.665166+00:00"}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/ts/agent/session-artifacts/01a0c5da-c327-72be-89c5-905d51187775/kernel-stderr.log b/scripts/heartbeat-fire-runs/ts/agent/session-artifacts/01a0c5da-c327-72be-89c5-905d51187775/kernel-stderr.logdeleted file mode 100644index e69de29bb2..0000000000diff --git a/scripts/heartbeat-fire-runs/ts/agent/session-artifacts/01a0c5da-c327-72be-89c5-905d51187775/scheduled-jobs.json b/scripts/heartbeat-fire-runs/ts/agent/session-artifacts/01a0c5da-c327-72be-89c5-905d51187775/scheduled-jobs.jsondeleted file mode 100644index 564be19659..0000000000--- a/scripts/heartbeat-fire-runs/ts/agent/session-artifacts/01a0c5da-c327-72be-89c5-905d51187775/scheduled-jobs.json+++ /dev/null@@ -1,27 +0,0 @@-{- "jobs": [- {- "id": "89608760-0332-4575-b842-20771d6c8c98",- "status": "cancelled",- "source": "rlm_heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "0f673d7d862d",- "sessionId": "01a0c5da-c327-72be-89c5-905d51187775",- "sessionFile": "/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/agent/sessions/01a0c5da-c327-72be-89c5-905d51187775.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/work",- "label": "hb-fire",- "prompt": "agent heartbeat fire probe instruction",- "schedule": {- "kind": "interval",- "expression": "every 30s",- "intervalMs": 30000- },- "createdAt": "2026-09-21T21:24:08.560Z",- "updatedAt": "2026-09-21T21:24:38.656Z",- "runCount": 1,- "lastRunAt": "2026-09-21T21:24:38.593Z"- }- ],- "dispatches": []-}diff --git a/scripts/heartbeat-fire-runs/ts/agent/session-artifacts/01a0c5da-c327-72be-89c5-905d51187775/semantic-edges.jsonl b/scripts/heartbeat-fire-runs/ts/agent/session-artifacts/01a0c5da-c327-72be-89c5-905d51187775/semantic-edges.jsonldeleted file mode 100644index dd1ccdeb7e..0000000000--- a/scripts/heartbeat-fire-runs/ts/agent/session-artifacts/01a0c5da-c327-72be-89c5-905d51187775/semantic-edges.jsonl+++ /dev/null@@ -1,9 +0,0 @@-{"type":"session_registered","session_id":"01a0c5da-c327-72be-89c5-905d51187775"}-{"type":"request_started","request_id":"d45a848a4d4f4a5cb1810bdf13fb12d3","session_id":"01a0c5da-c327-72be-89c5-905d51187775"}-{"type":"request_finished","request_id":"d45a848a4d4f4a5cb1810bdf13fb12d3"}-{"type":"request_started","request_id":"6f53ac671a364a41b8c5e179b1902cce","session_id":"01a0c5da-c327-72be-89c5-905d51187775"}-{"type":"request_finished","request_id":"6f53ac671a364a41b8c5e179b1902cce"}-{"type":"request_started","request_id":"bb391f5e8e4a40889811e4f8169e7b12","session_id":"01a0c5da-c327-72be-89c5-905d51187775"}-{"type":"request_finished","request_id":"bb391f5e8e4a40889811e4f8169e7b12"}-{"type":"request_started","request_id":"56fe6e406abd47f5bcd4c56bc1b1c958","session_id":"01a0c5da-c327-72be-89c5-905d51187775"}-{"type":"request_finished","request_id":"56fe6e406abd47f5bcd4c56bc1b1c958"}diff --git a/scripts/heartbeat-fire-runs/ts/agent/sessions/01a0c5da-c327-72be-89c5-905d51187775.jsonl b/scripts/heartbeat-fire-runs/ts/agent/sessions/01a0c5da-c327-72be-89c5-905d51187775.jsonldeleted file mode 100644index e4b9f33ab5..0000000000--- a/scripts/heartbeat-fire-runs/ts/agent/sessions/01a0c5da-c327-72be-89c5-905d51187775.jsonl+++ /dev/null@@ -1,16 +0,0 @@-{"type":"session","version":3,"id":"01a0c5da-c327-72be-89c5-905d51187775","timestamp":"2026-09-21T21:24:03.495Z","cwd":"/home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/work","rlmDepth":0,"git":{"repoUrl":"https://github.com/kevinjosethomas/prime-agent-rs.git","commit":"465e82014c3fc9e8419d7e09dd4b5b472b525b84","branch":"lane/hb-fire"}}-{"type":"model_change","id":"78fbc6a0","parentId":null,"timestamp":"2026-09-21T21:24:03.525Z","provider":"prime-inference","modelId":"mock-1"}-{"type":"thinking_level_change","id":"dacc2844","parentId":"78fbc6a0","timestamp":"2026-09-21T21:24:03.525Z","thinkingLevel":"off"}-{"type":"service_tier_change","id":"fd37ecdc","parentId":"dacc2844","timestamp":"2026-09-21T21:24:03.525Z","serviceTier":"default"}-{"type":"session_info","id":"1d020055","parentId":"fd37ecdc","timestamp":"2026-09-21T21:24:03.566Z","name":"hb-fire-verifier"}-{"type":"session_state","id":"d9a2edc4","parentId":"1d020055","timestamp":"2026-09-21T21:24:03.567Z","state":{"status":"active"}}-{"type":"custom_message","customType":"harness_digest","content":"[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>","display":false,"details":{"digest":"# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0"},"id":"e08f232a","parentId":"d9a2edc4","timestamp":"2026-09-21T21:24:03.604Z"}-{"type":"message","id":"881cfce0","parentId":"e08f232a","timestamp":"2026-09-21T21:24:03.608Z","message":{"role":"user","content":[{"type":"text","text":"verifier seed turn"}],"timestamp":1790025843585}}-{"type":"message","id":"17a9f11b","parentId":"881cfce0","timestamp":"2026-09-21T21:24:03.634Z","message":{"role":"assistant","content":[{"type":"text","text":"heartbeat fire verifier seed reply"}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790025843610,"responseId":"chatcmpl-battery"}}-{"type":"message","id":"39f21a88","parentId":"17a9f11b","timestamp":"2026-09-21T21:24:03.674Z","message":{"role":"user","content":[{"type":"text","text":"create the agent heartbeat"}],"timestamp":1790025843660}}-{"type":"message","id":"1203b17c","parentId":"39f21a88","timestamp":"2026-09-21T21:24:03.682Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"call_battery_1","name":"ipython","arguments":{"code":"import rlm_heartbeat\nhb = await rlm_heartbeat.create(\n 'agent heartbeat fire probe instruction',\n interval='every 30s',\n label='hb-fire',\n)\nprint('created', hb['id'])"}}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790025843674,"responseId":"chatcmpl-battery"}}-{"type":"message","id":"2cb7dc12","parentId":"1203b17c","timestamp":"2026-09-21T21:24:08.572Z","message":{"role":"toolResult","toolCallId":"call_battery_1","toolName":"ipython","content":[{"type":"text","text":"Traceback (most recent call last):\n\n File \"<cell-2>\", line 7, in <module>\n print('created', hb['id'])\n ~~^^^^^^\n\nKeyError: 'id'\n"}],"details":{"durationMs":6,"status":"error","errorEname":"KeyError","stdout":"","stderr":"","kernelRestarted":false,"error":{"ename":"KeyError","evalue":"'id'","traceback":["Traceback (most recent call last):\n"," File \"<cell-2>\", line 7, in <module>\n print('created', hb['id'])\n ~~^^^^^^\n","KeyError: 'id'\n"]}},"isError":false,"timestamp":1790025848569}}-{"type":"message","id":"5325afe2","parentId":"2cb7dc12","timestamp":"2026-09-21T21:24:08.581Z","message":{"role":"assistant","content":[{"type":"text","text":"agent heartbeat created"}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790025848575,"responseId":"chatcmpl-battery"}}-{"type":"custom_message","customType":"heartbeat_prompt","content":"[heartbeat: every 30s run#0]\n\nagent heartbeat fire probe instruction","display":true,"details":{"jobId":"89608760-0332-4575-b842-20771d6c8c98","schedule":"every 30s","status":"active","runCount":0,"nextRunAt":"2026-09-21T21:25:08.560Z"},"id":"bf486c54","parentId":"5325afe2","timestamp":"2026-09-21T21:24:38.579Z"}-{"type":"message","id":"937fb910","parentId":"bf486c54","timestamp":"2026-09-21T21:24:38.584Z","message":{"role":"assistant","content":[{"type":"text","text":"agent heartbeat created"}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790025878579,"responseId":"chatcmpl-battery"}}-{"type":"session_state","id":"c77cacfa","parentId":"937fb910","timestamp":"2026-09-21T21:24:38.659Z","state":{"status":"archived"}}diff --git a/scripts/heartbeat-fire-runs/ts/agent/settings.json b/scripts/heartbeat-fire-runs/ts/agent/settings.jsondeleted file mode 100644index 539978831e..0000000000--- a/scripts/heartbeat-fire-runs/ts/agent/settings.json+++ /dev/null@@ -1 +0,0 @@-{"onboardingShown": true, "telemetry": {"noticeShown": true}}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/ts/agent/telemetry.json b/scripts/heartbeat-fire-runs/ts/agent/telemetry.jsondeleted file mode 100644index 2fdfe6a29e..0000000000--- a/scripts/heartbeat-fire-runs/ts/agent/telemetry.json+++ /dev/null@@ -1,4 +0,0 @@-{- "version": 1,- "installationId": "8aea60c4-9586-40b1-b103-187dc0e3c65c"-}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/ts/daemon.log b/scripts/heartbeat-fire-runs/ts/daemon.logdeleted file mode 100644index 7fd17c4041..0000000000--- a/scripts/heartbeat-fire-runs/ts/daemon.log+++ /dev/null@@ -1,3 +0,0 @@-Prime Agent daemon supervisor 5fd8a55d-f393-4f9e-8cf5-22105c79adaa listening on /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/daemon.sock-Session worker a403535b1748 stderr: Prime Agent daemon listening on /tmp/hbf20260921T212401Z-ts/prime-agent-1000/worker-7fc8ba629507-a403535b1748.sock-Session worker a403535b1748 stderr: shutting down (exit 0); closing 0 active session(s)diff --git a/scripts/heartbeat-fire-runs/ts/mock-script.json b/scripts/heartbeat-fire-runs/ts/mock-script.jsondeleted file mode 100644index 1c2587ac90..0000000000--- a/scripts/heartbeat-fire-runs/ts/mock-script.json+++ /dev/null@@ -1 +0,0 @@-{"responses": [{"toolCall": {"name": "ipython", "arguments": {"code": "import rlm_heartbeat\nhb = await rlm_heartbeat.create(\n 'agent heartbeat fire probe instruction',\n interval='every 30s',\n label='hb-fire',\n)\nprint('created', hb['id'])"}}}, {"text": "agent heartbeat created"}]}\ No newline at end of filediff --git a/scripts/heartbeat-fire-runs/ts/mock-script.json.requests.jsonl b/scripts/heartbeat-fire-runs/ts/mock-script.json.requests.jsonldeleted file mode 100644index 344b836175..0000000000--- a/scripts/heartbeat-fire-runs/ts/mock-script.json.requests.jsonl+++ /dev/null@@ -1,7 +0,0 @@-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "You are a general purpose agent that uses code to solve tasks.\nYou solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.\nWhen you are done, stop calling tools and state your final answer.\n\nFor slow or independently completing work, use a nonblocking control loop: start the work, record its handle or output location, then end your turn. A `bash()` handle left running beyond its creating cell sends a completion follow-up; when it arrives, inspect the saved handle and continue. Reading a finished handle's result first cancels that follow-up.\nWhen delegation is available and useful, assign independent substantive tasks to separate workers. Start independent workers without waiting for each one sequentially, and let them run in parallel.\nDo not keep the turn open by polling with `time.sleep()` or shell `sleep`, and do not replace polling with a long blocking `await`. Await only the short operation needed to start work or inspect a result that is already available; otherwise end the turn.\n\nAs the user-facing root agent, when work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n\nUse simplified technical English by default for user-facing prose.\nPrefer short sentences, common words, and concrete verbs. State one main action or fact per sentence when practical. Use lists for steps or conditions.\nKeep necessary technical terms, names, commands, code, paths, and exact quoted text unchanged. State uncertainty directly.\nTreat this as clarity guidance, not a claim of formal ASD-STE100 compliance. Preserve a user-requested format, tone, terminology, and necessary precision.\n\nWorking directory: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/work\nConversation log: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/agent/sessions/01a0c5da-c327-72be-89c5-905d51187775.jsonl\nRecursive agent depth: 0\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nInstalled Python skill modules (pre-imported): `refine`, `compact`, `agent_observe`, `attach_image`, `edit`, `agent_message`, `rlm_heartbeat`, `goal`, `websearch`.\nRead each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.\nEach skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.\nFor targeted existing-file edits, prefer the pre-imported async `edit` skill from the REPL: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.\nAgent messaging is restricted to your parent, siblings, and direct children; roots are siblings, and deeper communication relays through the intermediate child.\nAgent observation is restricted to your parent, siblings, and direct children; roots are siblings, and deeper inspection relays through the intermediate child.\n\nFrom a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm.spawn(...)` still creates a child.\n\nAn `rlm` object is already in your global namespace. `await rlm.spawn('sub-task', name='api-reviewer')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.\n`name` is required: choose a stable child name that is unique among siblings.\nA child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.\nUse `await agent_observe.list_agents()` to discover family, including inactive members, and `await rlm.list_subagents()` to recover direct child handles.\nChildren reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.\nUse `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.\nUse `agent_observe` to inspect a child's rollout. Observation is restricted to your parent, siblings, and direct children; relay through the intermediate child for deeper descendants.\nSpawn independent children in separate calls and end your turn instead of awaiting completion. Multiple replies may arrive over multiple turns. Delete a direct child explicitly with `await rlm.delete_subagent(child)` when it is no longer needed.\n\nThe `ipython` tool is a persistent Python REPL \u2014 the agent's long-lived control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Top-level `await` works directly. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.\n\nPython is the orchestration language: use Python for loops, conditionals, parsing, and state. Use `bash()` to invoke programs, not to write shell programs \u2014 no shell loops or heredocs; do those in Python.\n\nDo not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n\n`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working. Run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n\nImportant: do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.\n\nUse Python for reading, searching, and editing files \u2014 it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.\n\nEach `bash()` call is its own process, so shell state does not persist between calls; use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls.\n\nPython state in the kernel persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.\n\nContinual harness state is available as `rlm.harness` and `rlm.get_harness_state()`. CRUD calls are local to this Prime Agent session by default: `rlm.harness.create_memory(...)`, `rlm.harness.update_memory(...)`, `rlm.harness.delete_memory(...)`, `rlm.harness.create_skill(...)`, `rlm.harness.update_skill(...)`, `rlm.harness.delete_skill(...)`, `rlm.harness.create_subagent(...)`, `rlm.harness.update_subagent(...)`, `rlm.harness.delete_subagent(...)`, `rlm.harness.create_prompt_note(...)`, `rlm.harness.update_prompt_note(...)`, `rlm.harness.delete_prompt_note(...)`, plus `rlm.harness.record_refinement(...)` and `rlm.harness.overview()`. Use `global_=True` only for stable cross-session lessons; Python reserves `global`, so literal `global=True` is invalid syntax.\n\nTerminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n\nRLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm.spawn('sub-task', name='worker')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm.spawn()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.\n\nTreat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n\n# Delegating to sub-agents\n\nSpawn independent, self-contained work with `handle = await rlm.spawn('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.\nAsk for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.\nUse `await rlm.list_subagents()` after kernel restart or compaction.\nLong-running children can report in-flight status with `await rlm.progress_note(...)`; `rlm.list_subagents()` shows each child's activity, latest progress note, and staleness.\nUse `agent_observe` for bounded transcript inspection.\nFan-in results with `await rlm.collect(targets, timeout_ms=0)`: it returns typed snapshots of direct children (status, answer preview, error) without steering anyone; an explicit timeout blocks only that call until the children settle or the deadline passes.\nLarge child outputs belong in files that you read selectively; `collect` snapshots are previews, not full results.\nDelegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\nPersist genuinely reusable delegation patterns with `await refine.run()`.\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/hb-fire/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/websearch/SKILL.md</location>\n </skill>\n</available_skills>"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "You are a general purpose agent that uses code to solve tasks.\nYou solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.\nWhen you are done, stop calling tools and state your final answer.\n\nFor slow or independently completing work, use a nonblocking control loop: start the work, record its handle or output location, then end your turn. A `bash()` handle left running beyond its creating cell sends a completion follow-up; when it arrives, inspect the saved handle and continue. Reading a finished handle's result first cancels that follow-up.\nWhen delegation is available and useful, assign independent substantive tasks to separate workers. Start independent workers without waiting for each one sequentially, and let them run in parallel.\nDo not keep the turn open by polling with `time.sleep()` or shell `sleep`, and do not replace polling with a long blocking `await`. Await only the short operation needed to start work or inspect a result that is already available; otherwise end the turn.\n\nAs the user-facing root agent, when work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n\nUse simplified technical English by default for user-facing prose.\nPrefer short sentences, common words, and concrete verbs. State one main action or fact per sentence when practical. Use lists for steps or conditions.\nKeep necessary technical terms, names, commands, code, paths, and exact quoted text unchanged. State uncertainty directly.\nTreat this as clarity guidance, not a claim of formal ASD-STE100 compliance. Preserve a user-requested format, tone, terminology, and necessary precision.\n\nWorking directory: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/work\nConversation log: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/agent/sessions/01a0c5da-c327-72be-89c5-905d51187775.jsonl\nRecursive agent depth: 0\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nInstalled Python skill modules (pre-imported): `refine`, `compact`, `agent_observe`, `attach_image`, `edit`, `agent_message`, `rlm_heartbeat`, `goal`, `websearch`.\nRead each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.\nEach skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.\nFor targeted existing-file edits, prefer the pre-imported async `edit` skill from the REPL: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.\nAgent messaging is restricted to your parent, siblings, and direct children; roots are siblings, and deeper communication relays through the intermediate child.\nAgent observation is restricted to your parent, siblings, and direct children; roots are siblings, and deeper inspection relays through the intermediate child.\n\nFrom a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm.spawn(...)` still creates a child.\n\nAn `rlm` object is already in your global namespace. `await rlm.spawn('sub-task', name='api-reviewer')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.\n`name` is required: choose a stable child name that is unique among siblings.\nA child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.\nUse `await agent_observe.list_agents()` to discover family, including inactive members, and `await rlm.list_subagents()` to recover direct child handles.\nChildren reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.\nUse `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.\nUse `agent_observe` to inspect a child's rollout. Observation is restricted to your parent, siblings, and direct children; relay through the intermediate child for deeper descendants.\nSpawn independent children in separate calls and end your turn instead of awaiting completion. Multiple replies may arrive over multiple turns. Delete a direct child explicitly with `await rlm.delete_subagent(child)` when it is no longer needed.\n\nThe `ipython` tool is a persistent Python REPL \u2014 the agent's long-lived control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Top-level `await` works directly. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.\n\nPython is the orchestration language: use Python for loops, conditionals, parsing, and state. Use `bash()` to invoke programs, not to write shell programs \u2014 no shell loops or heredocs; do those in Python.\n\nDo not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n\n`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working. Run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n\nImportant: do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.\n\nUse Python for reading, searching, and editing files \u2014 it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.\n\nEach `bash()` call is its own process, so shell state does not persist between calls; use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls.\n\nPython state in the kernel persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.\n\nContinual harness state is available as `rlm.harness` and `rlm.get_harness_state()`. CRUD calls are local to this Prime Agent session by default: `rlm.harness.create_memory(...)`, `rlm.harness.update_memory(...)`, `rlm.harness.delete_memory(...)`, `rlm.harness.create_skill(...)`, `rlm.harness.update_skill(...)`, `rlm.harness.delete_skill(...)`, `rlm.harness.create_subagent(...)`, `rlm.harness.update_subagent(...)`, `rlm.harness.delete_subagent(...)`, `rlm.harness.create_prompt_note(...)`, `rlm.harness.update_prompt_note(...)`, `rlm.harness.delete_prompt_note(...)`, plus `rlm.harness.record_refinement(...)` and `rlm.harness.overview()`. Use `global_=True` only for stable cross-session lessons; Python reserves `global`, so literal `global=True` is invalid syntax.\n\nTerminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n\nRLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm.spawn('sub-task', name='worker')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm.spawn()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.\n\nTreat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n\n# Delegating to sub-agents\n\nSpawn independent, self-contained work with `handle = await rlm.spawn('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.\nAsk for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.\nUse `await rlm.list_subagents()` after kernel restart or compaction.\nLong-running children can report in-flight status with `await rlm.progress_note(...)`; `rlm.list_subagents()` shows each child's activity, latest progress note, and staleness.\nUse `agent_observe` for bounded transcript inspection.\nFan-in results with `await rlm.collect(targets, timeout_ms=0)`: it returns typed snapshots of direct children (status, answer preview, error) without steering anyone; an explicit timeout blocks only that call until the children settle or the deadline passes.\nLarge child outputs belong in files that you read selectively; `collect` snapshots are previews, not full results.\nDelegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\nPersist genuinely reusable delegation patterns with `await refine.run()`.\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/hb-fire/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/websearch/SKILL.md</location>\n </skill>\n</available_skills>"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}, {"role": "assistant", "content": "heartbeat fire verifier seed reply"}, {"role": "user", "content": [{"type": "text", "text": "create the agent heartbeat"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "qwen/qwen3-30b-a3b-instruct-2507", "messages": [{"role": "system", "content": "You generate a status line for an AI coding agent dashboard. You are given the recent conversation between a user and the agent, plus whether the agent is currently working or idle.\n\nOutput ONLY these two tags, nothing before, between, or after. Do not think out loud, explain, or count words.\n<recap>a present-tense clause, at most 12 words, saying what the agent is doing or just did, no trailing period</recap>\n<status>one of NEEDS_INPUT, COMPLETED</status>\n\nSTATUS meaning:\n- COMPLETED: the agent finished its turn AND the user's request is fully done with nothing left.\n- NEEDS_INPUT: the agent finished its turn but the task is not fully done \u2014 it asked a question, hit a blocker, or needs more prompting.\nWhen you are unsure between COMPLETED and NEEDS_INPUT, choose NEEDS_INPUT.\n\nExample:\n<recap>Refactoring the auth middleware and updating its tests</recap>\n<status>NEEDS_INPUT</status>"}, {"role": "user", "content": [{"type": "text", "text": "<agent-state>working</agent-state>\n<conversation>\ncustom: [harness-digest] The persistent memories produced across this session so far: <harness_state> # Continual Harness State Local continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions. The continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters. Default to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual ha\u2026\nuser: verifier seed turn\nassistant: heartbeat fire verifier seed reply\nuser: create the agent heartbeat\n</conversation>"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 400}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "You are a general purpose agent that uses code to solve tasks.\nYou solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.\nWhen you are done, stop calling tools and state your final answer.\n\nFor slow or independently completing work, use a nonblocking control loop: start the work, record its handle or output location, then end your turn. A `bash()` handle left running beyond its creating cell sends a completion follow-up; when it arrives, inspect the saved handle and continue. Reading a finished handle's result first cancels that follow-up.\nWhen delegation is available and useful, assign independent substantive tasks to separate workers. Start independent workers without waiting for each one sequentially, and let them run in parallel.\nDo not keep the turn open by polling with `time.sleep()` or shell `sleep`, and do not replace polling with a long blocking `await`. Await only the short operation needed to start work or inspect a result that is already available; otherwise end the turn.\n\nAs the user-facing root agent, when work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n\nUse simplified technical English by default for user-facing prose.\nPrefer short sentences, common words, and concrete verbs. State one main action or fact per sentence when practical. Use lists for steps or conditions.\nKeep necessary technical terms, names, commands, code, paths, and exact quoted text unchanged. State uncertainty directly.\nTreat this as clarity guidance, not a claim of formal ASD-STE100 compliance. Preserve a user-requested format, tone, terminology, and necessary precision.\n\nWorking directory: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/work\nConversation log: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/agent/sessions/01a0c5da-c327-72be-89c5-905d51187775.jsonl\nRecursive agent depth: 0\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nInstalled Python skill modules (pre-imported): `refine`, `compact`, `agent_observe`, `attach_image`, `edit`, `agent_message`, `rlm_heartbeat`, `goal`, `websearch`.\nRead each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.\nEach skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.\nFor targeted existing-file edits, prefer the pre-imported async `edit` skill from the REPL: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.\nAgent messaging is restricted to your parent, siblings, and direct children; roots are siblings, and deeper communication relays through the intermediate child.\nAgent observation is restricted to your parent, siblings, and direct children; roots are siblings, and deeper inspection relays through the intermediate child.\n\nFrom a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm.spawn(...)` still creates a child.\n\nAn `rlm` object is already in your global namespace. `await rlm.spawn('sub-task', name='api-reviewer')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.\n`name` is required: choose a stable child name that is unique among siblings.\nA child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.\nUse `await agent_observe.list_agents()` to discover family, including inactive members, and `await rlm.list_subagents()` to recover direct child handles.\nChildren reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.\nUse `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.\nUse `agent_observe` to inspect a child's rollout. Observation is restricted to your parent, siblings, and direct children; relay through the intermediate child for deeper descendants.\nSpawn independent children in separate calls and end your turn instead of awaiting completion. Multiple replies may arrive over multiple turns. Delete a direct child explicitly with `await rlm.delete_subagent(child)` when it is no longer needed.\n\nThe `ipython` tool is a persistent Python REPL \u2014 the agent's long-lived control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Top-level `await` works directly. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.\n\nPython is the orchestration language: use Python for loops, conditionals, parsing, and state. Use `bash()` to invoke programs, not to write shell programs \u2014 no shell loops or heredocs; do those in Python.\n\nDo not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n\n`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working. Run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n\nImportant: do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.\n\nUse Python for reading, searching, and editing files \u2014 it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.\n\nEach `bash()` call is its own process, so shell state does not persist between calls; use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls.\n\nPython state in the kernel persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.\n\nContinual harness state is available as `rlm.harness` and `rlm.get_harness_state()`. CRUD calls are local to this Prime Agent session by default: `rlm.harness.create_memory(...)`, `rlm.harness.update_memory(...)`, `rlm.harness.delete_memory(...)`, `rlm.harness.create_skill(...)`, `rlm.harness.update_skill(...)`, `rlm.harness.delete_skill(...)`, `rlm.harness.create_subagent(...)`, `rlm.harness.update_subagent(...)`, `rlm.harness.delete_subagent(...)`, `rlm.harness.create_prompt_note(...)`, `rlm.harness.update_prompt_note(...)`, `rlm.harness.delete_prompt_note(...)`, plus `rlm.harness.record_refinement(...)` and `rlm.harness.overview()`. Use `global_=True` only for stable cross-session lessons; Python reserves `global`, so literal `global=True` is invalid syntax.\n\nTerminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n\nRLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm.spawn('sub-task', name='worker')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm.spawn()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.\n\nTreat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n\n# Delegating to sub-agents\n\nSpawn independent, self-contained work with `handle = await rlm.spawn('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.\nAsk for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.\nUse `await rlm.list_subagents()` after kernel restart or compaction.\nLong-running children can report in-flight status with `await rlm.progress_note(...)`; `rlm.list_subagents()` shows each child's activity, latest progress note, and staleness.\nUse `agent_observe` for bounded transcript inspection.\nFan-in results with `await rlm.collect(targets, timeout_ms=0)`: it returns typed snapshots of direct children (status, answer preview, error) without steering anyone; an explicit timeout blocks only that call until the children settle or the deadline passes.\nLarge child outputs belong in files that you read selectively; `collect` snapshots are previews, not full results.\nDelegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\nPersist genuinely reusable delegation patterns with `await refine.run()`.\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/hb-fire/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/websearch/SKILL.md</location>\n </skill>\n</available_skills>"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}, {"role": "assistant", "content": "heartbeat fire verifier seed reply"}, {"role": "user", "content": [{"type": "text", "text": "create the agent heartbeat"}]}, {"role": "assistant", "content": null, "tool_calls": [{"id": "call_battery_1", "type": "function", "function": {"name": "ipython", "arguments": "{\"code\":\"import rlm_heartbeat\\nhb = await rlm_heartbeat.create(\\n 'agent heartbeat fire probe instruction',\\n interval='every 30s',\\n label='hb-fire',\\n)\\nprint('created', hb['id'])\"}"}}]}, {"role": "tool", "content": "Traceback (most recent call last):\n\n File \"<cell-2>\", line 7, in <module>\n print('created', hb['id'])\n ~~^^^^^^\n\nKeyError: 'id'\n", "tool_call_id": "call_battery_1"}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "qwen/qwen3-30b-a3b-instruct-2507", "messages": [{"role": "system", "content": "You generate a status line for an AI coding agent dashboard. You are given the recent conversation between a user and the agent, plus whether the agent is currently working or idle.\n\nOutput ONLY these two tags, nothing before, between, or after. Do not think out loud, explain, or count words.\n<recap>a present-tense clause, at most 12 words, saying what the agent is doing or just did, no trailing period</recap>\n<status>one of NEEDS_INPUT, COMPLETED</status>\n\nSTATUS meaning:\n- COMPLETED: the agent finished its turn AND the user's request is fully done with nothing left.\n- NEEDS_INPUT: the agent finished its turn but the task is not fully done \u2014 it asked a question, hit a blocker, or needs more prompting.\nWhen you are unsure between COMPLETED and NEEDS_INPUT, choose NEEDS_INPUT.\n\nExample:\n<recap>Refactoring the auth middleware and updating its tests</recap>\n<status>NEEDS_INPUT</status>"}, {"role": "user", "content": [{"type": "text", "text": "<agent-state>idle (finished its turn)</agent-state>\n<conversation>\ncustom: [harness-digest] The persistent memories produced across this session so far: <harness_state> # Continual Harness State Local continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions. The continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters. Default to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual ha\u2026\nuser: verifier seed turn\nassistant: heartbeat fire verifier seed reply\nuser: create the agent heartbeat\ntoolResult: Traceback (most recent call last): File \"<cell-2>\", line 7, in <module> print('created', hb['id']) ~~^^^^^^ KeyError: 'id'\nassistant: agent heartbeat created\n</conversation>"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 400}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "qwen/qwen3-30b-a3b-instruct-2507", "messages": [{"role": "system", "content": "You generate a status line for an AI coding agent dashboard. You are given the recent conversation between a user and the agent, plus whether the agent is currently working or idle.\n\nOutput ONLY these two tags, nothing before, between, or after. Do not think out loud, explain, or count words.\n<recap>a present-tense clause, at most 12 words, saying what the agent is doing or just did, no trailing period</recap>\n<status>one of NEEDS_INPUT, COMPLETED</status>\n\nSTATUS meaning:\n- COMPLETED: the agent finished its turn AND the user's request is fully done with nothing left.\n- NEEDS_INPUT: the agent finished its turn but the task is not fully done \u2014 it asked a question, hit a blocker, or needs more prompting.\nWhen you are unsure between COMPLETED and NEEDS_INPUT, choose NEEDS_INPUT.\n\nExample:\n<recap>Refactoring the auth middleware and updating its tests</recap>\n<status>NEEDS_INPUT</status>"}, {"role": "user", "content": [{"type": "text", "text": "<agent-state>idle (finished its turn)</agent-state>\n<conversation>\ncustom: [harness-digest] The persistent memories produced across this session so far: <harness_state> # Continual Harness State Local continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions. The continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters. Default to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual ha\u2026\nuser: verifier seed turn\nassistant: heartbeat fire verifier seed reply\nuser: create the agent heartbeat\ntoolResult: Traceback (most recent call last): File \"<cell-2>\", line 7, in <module> print('created', hb['id']) ~~^^^^^^ KeyError: 'id'\nassistant: agent heartbeat created\n</conversation>"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 400}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "You are a general purpose agent that uses code to solve tasks.\nYou solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.\nWhen you are done, stop calling tools and state your final answer.\n\nFor slow or independently completing work, use a nonblocking control loop: start the work, record its handle or output location, then end your turn. A `bash()` handle left running beyond its creating cell sends a completion follow-up; when it arrives, inspect the saved handle and continue. Reading a finished handle's result first cancels that follow-up.\nWhen delegation is available and useful, assign independent substantive tasks to separate workers. Start independent workers without waiting for each one sequentially, and let them run in parallel.\nDo not keep the turn open by polling with `time.sleep()` or shell `sleep`, and do not replace polling with a long blocking `await`. Await only the short operation needed to start work or inspect a result that is already available; otherwise end the turn.\n\nAs the user-facing root agent, when work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n\nUse simplified technical English by default for user-facing prose.\nPrefer short sentences, common words, and concrete verbs. State one main action or fact per sentence when practical. Use lists for steps or conditions.\nKeep necessary technical terms, names, commands, code, paths, and exact quoted text unchanged. State uncertainty directly.\nTreat this as clarity guidance, not a claim of formal ASD-STE100 compliance. Preserve a user-requested format, tone, terminology, and necessary precision.\n\nWorking directory: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/work\nConversation log: /home/ubuntu/lane-worktrees/hb-fire/scripts/heartbeat-fire-runs/ts/agent/sessions/01a0c5da-c327-72be-89c5-905d51187775.jsonl\nRecursive agent depth: 0\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nInstalled Python skill modules (pre-imported): `refine`, `compact`, `agent_observe`, `attach_image`, `edit`, `agent_message`, `rlm_heartbeat`, `goal`, `websearch`.\nRead each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.\nEach skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.\nFor targeted existing-file edits, prefer the pre-imported async `edit` skill from the REPL: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.\nAgent messaging is restricted to your parent, siblings, and direct children; roots are siblings, and deeper communication relays through the intermediate child.\nAgent observation is restricted to your parent, siblings, and direct children; roots are siblings, and deeper inspection relays through the intermediate child.\n\nFrom a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm.spawn(...)` still creates a child.\n\nAn `rlm` object is already in your global namespace. `await rlm.spawn('sub-task', name='api-reviewer')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.\n`name` is required: choose a stable child name that is unique among siblings.\nA child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.\nUse `await agent_observe.list_agents()` to discover family, including inactive members, and `await rlm.list_subagents()` to recover direct child handles.\nChildren reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.\nUse `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.\nUse `agent_observe` to inspect a child's rollout. Observation is restricted to your parent, siblings, and direct children; relay through the intermediate child for deeper descendants.\nSpawn independent children in separate calls and end your turn instead of awaiting completion. Multiple replies may arrive over multiple turns. Delete a direct child explicitly with `await rlm.delete_subagent(child)` when it is no longer needed.\n\nThe `ipython` tool is a persistent Python REPL \u2014 the agent's long-lived control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Top-level `await` works directly. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.\n\nPython is the orchestration language: use Python for loops, conditionals, parsing, and state. Use `bash()` to invoke programs, not to write shell programs \u2014 no shell loops or heredocs; do those in Python.\n\nDo not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n\n`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working. Run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n\nImportant: do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.\n\nUse Python for reading, searching, and editing files \u2014 it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.\n\nEach `bash()` call is its own process, so shell state does not persist between calls; use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls.\n\nPython state in the kernel persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.\n\nContinual harness state is available as `rlm.harness` and `rlm.get_harness_state()`. CRUD calls are local to this Prime Agent session by default: `rlm.harness.create_memory(...)`, `rlm.harness.update_memory(...)`, `rlm.harness.delete_memory(...)`, `rlm.harness.create_skill(...)`, `rlm.harness.update_skill(...)`, `rlm.harness.delete_skill(...)`, `rlm.harness.create_subagent(...)`, `rlm.harness.update_subagent(...)`, `rlm.harness.delete_subagent(...)`, `rlm.harness.create_prompt_note(...)`, `rlm.harness.update_prompt_note(...)`, `rlm.harness.delete_prompt_note(...)`, plus `rlm.harness.record_refinement(...)` and `rlm.harness.overview()`. Use `global_=True` only for stable cross-session lessons; Python reserves `global`, so literal `global=True` is invalid syntax.\n\nTerminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n\nRLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm.spawn('sub-task', name='worker')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm.spawn()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.\n\nTreat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n\n# Delegating to sub-agents\n\nSpawn independent, self-contained work with `handle = await rlm.spawn('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.\nAsk for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.\nUse `await rlm.list_subagents()` after kernel restart or compaction.\nLong-running children can report in-flight status with `await rlm.progress_note(...)`; `rlm.list_subagents()` shows each child's activity, latest progress note, and staleness.\nUse `agent_observe` for bounded transcript inspection.\nFan-in results with `await rlm.collect(targets, timeout_ms=0)`: it returns typed snapshots of direct children (status, answer preview, error) without steering anyone; an explicit timeout blocks only that call until the children settle or the deadline passes.\nLarge child outputs belong in files that you read selectively; `collect` snapshots are previews, not full results.\nDelegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\nPersist genuinely reusable delegation patterns with `await refine.run()`.\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/hb-fire/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/websearch/SKILL.md</location>\n </skill>\n</available_skills>"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}, {"role": "assistant", "content": "heartbeat fire verifier seed reply"}, {"role": "user", "content": [{"type": "text", "text": "create the agent heartbeat"}]}, {"role": "assistant", "content": null, "tool_calls": [{"id": "call_battery_1", "type": "function", "function": {"name": "ipython", "arguments": "{\"code\":\"import rlm_heartbeat\\nhb = await rlm_heartbeat.create(\\n 'agent heartbeat fire probe instruction',\\n interval='every 30s',\\n label='hb-fire',\\n)\\nprint('created', hb['id'])\"}"}}]}, {"role": "tool", "content": "Traceback (most recent call last):\n\n File \"<cell-2>\", line 7, in <module>\n print('created', hb['id'])\n ~~^^^^^^\n\nKeyError: 'id'\n", "tool_call_id": "call_battery_1"}, {"role": "assistant", "content": "agent heartbeat created"}, {"role": "user", "content": [{"type": "text", "text": "[heartbeat: every 30s run#0]\n\nagent heartbeat fire probe instruction"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}diff --git a/scripts/heartbeat-fire-runs/ts/summary.json b/scripts/heartbeat-fire-runs/ts/summary.jsondeleted file mode 100644index 595bc2bc4a..0000000000--- a/scripts/heartbeat-fire-runs/ts/summary.json+++ /dev/null@@ -1,56 +0,0 @@-[- {- "side": "ts",- "ok": true,- "summary": "seed turn ran",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "agent heartbeat turn ran",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "catalog lists the agent heartbeat",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "created job is active and unrun",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "created job runCount is 0",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "the heartbeat fired within the interval (runCount >= 1, runCount=1)",- "evidence": "02-fired-catalog.json"- },- {- "side": "ts",- "ok": true,- "summary": "the fire stamped lastRunAt",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "the fire rolled nextRunAt past the boundary",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "the fired prompt landed in the session transcript",- "evidence": "03-transcript-hit.txt"- }-]\ No newline at end of filediff --git a/scripts/heartbeat_fire_parity.py b/scripts/heartbeat_fire_parity.pydeleted file mode 100755index 7c275958d8..0000000000--- a/scripts/heartbeat_fire_parity.py+++ /dev/null@@ -1,298 +0,0 @@-#!/usr/bin/env python3-"""Heartbeat-fire verifier (lane: hb-fire, dogfood P0).--Wire-level user test proving the kernel heartbeat FIRE chain on both-products (TS parity diff): a daemon session whose kernel creates an-`rlm_heartbeat` (the rlm-heartbeat skill host request, `every 30s`,-delivery steer) must actually FIRE within the interval —-- 1. the fire lands its prompt in the session (the session file gains- the instruction as a user message, the visible "Heartbeat prompt"- row source),- 2. the store records the run (`runCount` bumps to >= 1, `lastRunAt`- sets, `nextRunAt` rolls past the boundary),- 3. the wire catalog (`heartbeats_list`) reflects the fired state.--This is the exact repro of the dogfood P0 (a heartbeat created 20:47:23-with next_run_at 20:48:00 that never fired): a job created after the-bind-time scheduler arm must re-arm the timer (TS-`cronScheduler.wake()` at the controller call sites) and fire.--Runs one side at a time (`--side rust` or `--side ts`); both sides must-pass every step. Timing information (nextRunAt/lastRunAt) is recorded-for the diff but never asserted equal to the second.--Usage:- python3 scripts/heartbeat_fire_parity.py --side rust --binary <path> \- --repo <checkout> [--out <dir>]-"""--from __future__ import annotations--import argparse-import json-import re-import shutil-import sys-import time-from datetime import datetime, timezone-from pathlib import Path--REPO = Path(__file__).resolve().parents[1]-sys.path.insert(0, str(REPO / "scripts" / "battery"))-import batterylib as B # noqa: E402--AGENT_HB_INSTRUCTION = "agent heartbeat fire probe instruction"-AGENT_HB_LABEL = "hb-fire"-AGENT_INTERVAL = "every 30s"-SEED_REPLY = "heartbeat fire verifier seed reply"-FIRE_TIMEOUT_S = 120.0 # the interval plus turn-settle slack---class Verifier:- def __init__(self, side_name: str, binary: str, out: Path):- self.name = side_name- self.out = out- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")- self.runid = "hbf" + stamp- root = out / self.name- root.mkdir(parents=True, exist_ok=True)- agent = root / "agent"- work = root / "work"- work.mkdir(parents=True, exist_ok=True)- if agent.exists():- shutil.rmtree(agent)- agent.mkdir(parents=True)- mock = B.MockProvider(root, [])- mock.set_responses([{"text": SEED_REPLY}])- mock.start()- tmpdir = Path("/tmp") / f"{self.runid}-{self.name}"- if tmpdir.exists():- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- self.side = B.Side(- name=side_name,- binary=binary,- root=root,- agent_dir=agent,- work_dir=work,- daemon_socket=root / "daemon.sock",- mock=mock,- )- self.side.env = B.scrubbed_env(agent, tmpdir)- if side_name == "rust":- self.side.env["PI_PACKAGE_DIR"] = str(REPO)- self.side.env["PRIME_API_KEY"] = "sk-battery"- self.side.write_models_json()- settings_path = agent / "settings.json"- settings = json.loads(settings_path.read_text()) if settings_path.exists() else {}- settings["onboardingShown"] = True- settings["telemetry"] = {**(settings.get("telemetry") or {}), "noticeShown": True}- settings_path.write_text(json.dumps(settings))- self.findings: list[dict] = []-- def record(self, summary: str, ok: bool, evidence: str = "") -> None:- self.findings.append(- {"side": self.name, "ok": ok, "summary": summary, "evidence": evidence}- )- print(f"[{'ok ' if ok else 'FAIL'}] {self.name}: {summary}")-- def evidence(self, name: str, text: str) -> Path:- path = self.out / self.name- path.mkdir(parents=True, exist_ok=True)- target = path / name- target.write_text(text)- return target-- def evidence_json(self, name: str, obj) -> Path:- return self.evidence(name, json.dumps(obj, indent=2))-- def ensure_daemon(self) -> None:- try:- probe = B.Wire(self.side.daemon_socket)- probe.close()- return- except (OSError, EOFError):- pass- self.side.start_daemon()-- def catalog(self, session_id: str) -> list:- wire = B.Wire(self.side.daemon_socket)- try:- data = wire.request(- "hb-list",- {"type": "heartbeats_list", "activeSessionId": session_id},- timeout=30,- )- finally:- wire.close()- return (data.get("data") or {}).get("heartbeats") or []-- def run(self) -> bool:- self.ensure_daemon()- wire = B.Wire(self.side.daemon_socket)- create = wire.request(- "hb-create",- {- "type": "create",- "name": "hb-fire-verifier",- "config": {- "cwd": str(self.side.work_dir),- "sessionDir": str(self.side.agent_dir / "sessions"),- "provider": "prime-inference",- "model": "mock-1",- "executionMode": "print",- },- },- timeout=120,- )- if create.get("success") is not True:- self.record("daemon create failed: " + json.dumps(create)[:200], ok=False)- wire.close()- return False- session_id = (- (create.get("data") or {}).get("activeSessionId")- or (create.get("data") or {}).get("id")- or ""- )-- # Seed turn: the session becomes created + persisted and the kernel- # (the rlm-heartbeat skill host requests) is live.- self.side.mock.set_responses([{"text": SEED_REPLY}])- seeded = wire.request(- "hb-seed",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": "verifier seed turn",- },- timeout=240,- )- self.record("seed turn ran", seeded.get("success") is True)-- # The kernel creates the heartbeat (the rlm-heartbeat skill host- # request): the same path the dogfood session drove.- code = (- "import rlm_heartbeat\n"- "hb = await rlm_heartbeat.create(\n"- f" {AGENT_HB_INSTRUCTION!r},\n"- f" interval={AGENT_INTERVAL!r},\n"- f" label={AGENT_HB_LABEL!r},\n"- ")\n"- "print('created', hb['id'])"- )- self.side.mock.set_responses(- [- {"toolCall": {"name": "ipython", "arguments": {"code": code}}},- {"text": "agent heartbeat created"},- ]- )- agent_reply = wire.request(- "hb-agent",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": "create the agent heartbeat",- },- timeout=240,- )- self.record("agent heartbeat turn ran", agent_reply.get("success") is True)- self.evidence_json("01-agent-heartbeat-turn.json", agent_reply)-- # The catalog must carry the job, active, not yet run.- job = self.wait_job(session_id)- if job is None:- self.record("catalog lists the agent heartbeat", ok=False)- wire.close()- return False- self.record("catalog lists the agent heartbeat", True)- self.record("created job is active and unrun", job.get("status") == "active")- self.record("created job runCount is 0", (job.get("runCount") or 0) == 0)-- # THE FIRE: within the interval (+ slack) the job must run.- fired = self.wait_fire(session_id, job.get("id") or "")- self.evidence_json("02-fired-catalog.json", self.catalog(session_id))- if fired is None:- self.record(- "the heartbeat fired within the interval (runCount >= 1)",- ok=False,- evidence="02-fired-catalog.json",- )- wire.close()- return False- self.record(- f"the heartbeat fired within the interval (runCount >= 1, "- f"runCount={fired.get('runCount')})",- True,- evidence="02-fired-catalog.json",- )- self.record("the fire stamped lastRunAt", bool(fired.get("lastRunAt")))- self.record(- "the fire rolled nextRunAt past the boundary",- bool(fired.get("nextRunAt")),- )- wire.close()-- # The fired prompt reached the session: the instruction is a user- # message in the session file (the "Heartbeat prompt" row source).- session_dir = self.side.agent_dir / "sessions"- hits = []- for path in sorted(session_dir.glob("*.jsonl")):- if AGENT_HB_INSTRUCTION in path.read_text(errors="replace"):- hits.append(path.name)- self.evidence(- "03-transcript-hit.txt",- "\n".join(hits) + f"\ninstruction: {AGENT_HB_INSTRUCTION}",- )- self.record(- "the fired prompt landed in the session transcript",- bool(hits),- evidence="03-transcript-hit.txt",- )- return all(finding["ok"] for finding in self.findings)-- def wait_job(self, session_id: str, timeout: float = 60.0) -> dict | None:- deadline = time.time() + timeout- while time.time() < deadline:- for entry in self.catalog(session_id):- job = entry.get("job") or {}- if job.get("source") == "rlm_heartbeat":- return job- time.sleep(1.0)- return None-- def wait_fire(self, session_id: str, job_id: str) -> dict | None:- deadline = time.time() + FIRE_TIMEOUT_S- while time.time() < deadline:- for entry in self.catalog(session_id):- job = entry.get("job") or {}- if job.get("id") == job_id and (job.get("runCount") or 0) >= 1:- return job- time.sleep(2.0)- return None---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--side", required=True, choices=["rust", "ts"])- parser.add_argument("--binary", required=True)- parser.add_argument("--repo", default=str(REPO))- parser.add_argument("--out", default=str(REPO / "scripts" / "heartbeat-fire-runs"))- args = parser.parse_args()-- verifier = Verifier(args.side, args.binary, Path(args.out))- try:- ok = verifier.run()- finally:- try:- verifier.side.stop_daemon()- except Exception:- pass- verifier.evidence_json("summary.json", verifier.findings)- failed = [f for f in verifier.findings if not f["ok"]]- print(f"\n{args.side}: {len(verifier.findings) - len(failed)}/{len(verifier.findings)} steps ok")- return 0 if ok else 1---if __name__ == "__main__":- raise SystemExit(main())diff --git a/scripts/heartbeats-runs/20260921T165945Z/findings.json b/scripts/heartbeats-runs/20260921T165945Z/findings.jsondeleted file mode 100644index 780341fce4..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/findings.json+++ /dev/null@@ -1,68 +0,0 @@-[- {- "side": "ts",- "ok": true,- "summary": "seed turn ran",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "user heartbeat set through the wire",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "agent heartbeat turn ran",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "wire catalog lists the user and agent heartbeat",- "evidence": "02-wire-catalog.json"- },- {- "side": "ts",- "ok": true,- "summary": "/heartbeats renders the list with both heartbeats",- "evidence": "04-opened.txt"- },- {- "side": "ts",- "ok": false,- "summary": "down moves the inline selection",- "evidence": "05-navigated.txt"- },- {- "side": "ts",- "ok": true,- "summary": "enter opens the action pane with the TS actions",- "evidence": "06-actions.txt"- },- {- "side": "ts",- "ok": true,- "summary": "applying the action returns to the list with the paused status",- "evidence": "07-applied.txt"- },- {- "side": "ts",- "ok": true,- "summary": "the pause reached the daemon catalog",- "evidence": "08-applied-catalog.json"- },- {- "side": "ts",- "ok": true,- "summary": "escape closes the view (the transcript returns)",- "evidence": "09-closed.txt"- },- {- "side": "ts",- "ok": true,- "summary": "the tray heartbeat label renders after close",- "evidence": "09-closed.txt"- }-]\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/00-heartbeat-set.json b/scripts/heartbeats-runs/20260921T165945Z/ts/00-heartbeat-set.jsondeleted file mode 100644index 29f3a6a1aa..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/00-heartbeat-set.json+++ /dev/null@@ -1,29 +0,0 @@-{- "id": "hb-set",- "type": "response",- "command": "heartbeat_set",- "success": true,- "data": {- "heartbeat": {- "id": "07e1e9d2-8a2d-4abd-a50d-20d650eeca37",- "status": "active",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "3d985e69dce5",- "sessionId": "01a0c4e8-d25e-77ef-8f2d-a807e9add380",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T16:59:47.788Z",- "updatedAt": "2026-09-21T16:59:47.788Z",- "nextRunAt": "2026-09-21T17:29:47.788Z",- "runCount": 0- }- }-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/01-agent-heartbeat-turn.json b/scripts/heartbeats-runs/20260921T165945Z/ts/01-agent-heartbeat-turn.jsondeleted file mode 100644index 48b023caab..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/01-agent-heartbeat-turn.json+++ /dev/null@@ -1,6 +0,0 @@-{- "id": "hb-agent",- "type": "response",- "command": "prompt_and_wait",- "success": true-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/02-wire-catalog.json b/scripts/heartbeats-runs/20260921T165945Z/ts/02-wire-catalog.jsondeleted file mode 100644index 1dd8a9cb9f..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/02-wire-catalog.json+++ /dev/null@@ -1,53 +0,0 @@-[- {- "job": {- "id": "07e1e9d2-8a2d-4abd-a50d-20d650eeca37",- "status": "active",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "3d985e69dce5",- "sessionId": "01a0c4e8-d25e-77ef-8f2d-a807e9add380",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T16:59:47.788Z",- "updatedAt": "2026-09-21T16:59:47.788Z",- "nextRunAt": "2026-09-21T17:29:47.788Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- },- {- "job": {- "id": "4f327415-8d7b-4634-bf84-2770799927c8",- "status": "active",- "source": "rlm_heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "3d985e69dce5",- "sessionId": "01a0c4e8-d25e-77ef-8f2d-a807e9add380",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work",- "label": "agent hb",- "prompt": "agent heartbeat check instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T16:59:52.280Z",- "updatedAt": "2026-09-21T16:59:52.280Z",- "nextRunAt": "2026-09-21T17:29:52.280Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- }-]\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/03-attached.txt b/scripts/heartbeats-runs/20260921T165945Z/ts/03-attached.txtdeleted file mode 100644index 58a9bef345..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/03-attached.txt+++ /dev/null@@ -1,36 +0,0 @@- heartbeats-verifier $0.00-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent v0.9.5- ▗█▛ ▟██▙▄██▛ ▟▛ model mock-1- ▗▟▌ ▐███▛▘▗▄█▖ cwd ~/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--- verifier seed turn--- heartbeats verifier seed reply--- create the agent heartbeat--- ✓ python · await rlm_heartbeat.create( · ↑ 7 ↓ 1 lines · 14ms-- agent heartbeat created--------- Collapsed mode (Ctrl+O to expand)-- >--← manage 2 heartbeats (Ctrl+R) · mock-1 · 110 (0%)diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/04-opened.txt b/scripts/heartbeats-runs/20260921T165945Z/ts/04-opened.txtdeleted file mode 100644index e964b13bad..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/04-opened.txt+++ /dev/null@@ -1,36 +0,0 @@------------- Heartbeats- 2 heartbeats. Select a heartbeat to manage.--- user heartbeat ping instruction active- Created by you · heartbeats-verifier · every 30m · steer-- agent hb active- Created by agent · heartbeats-verifier · every 30m · steer--- Esc close------------diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/05-navigated.txt b/scripts/heartbeats-runs/20260921T165945Z/ts/05-navigated.txtdeleted file mode 100644index e964b13bad..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/05-navigated.txt+++ /dev/null@@ -1,36 +0,0 @@------------- Heartbeats- 2 heartbeats. Select a heartbeat to manage.--- user heartbeat ping instruction active- Created by you · heartbeats-verifier · every 30m · steer-- agent hb active- Created by agent · heartbeats-verifier · every 30m · steer--- Esc close------------diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/06-actions.txt b/scripts/heartbeats-runs/20260921T165945Z/ts/06-actions.txtdeleted file mode 100644index dc0a1fcfcf..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/06-actions.txt+++ /dev/null@@ -1,36 +0,0 @@------------ agent hb- agent heartbeat check instruction-- Created by agent · heartbeats-verifier · active · every 30m · ste...--- Pause heartbeat- Stop deliveries until resumed-- Stop heartbeat- Permanently remove this heartbeat--- ← back Esc close-----------diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/07-applied.txt b/scripts/heartbeats-runs/20260921T165945Z/ts/07-applied.txtdeleted file mode 100644index 69297f1119..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/07-applied.txt+++ /dev/null@@ -1,36 +0,0 @@------------- Heartbeats- 2 heartbeats · 1 paused. Select a heartbeat to manage.--- user heartbeat ping instruction active- Created by you · heartbeats-verifier · every 30m · steer-- agent hb paused- Created by agent · heartbeats-verifier · every 30m · steer--- Esc close------------diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/08-applied-catalog.json b/scripts/heartbeats-runs/20260921T165945Z/ts/08-applied-catalog.jsondeleted file mode 100644index ecbc48937d..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/08-applied-catalog.json+++ /dev/null@@ -1,52 +0,0 @@-[- {- "job": {- "id": "07e1e9d2-8a2d-4abd-a50d-20d650eeca37",- "status": "active",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "3d985e69dce5",- "sessionId": "01a0c4e8-d25e-77ef-8f2d-a807e9add380",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T16:59:47.788Z",- "updatedAt": "2026-09-21T16:59:47.788Z",- "nextRunAt": "2026-09-21T17:29:47.788Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- },- {- "job": {- "id": "4f327415-8d7b-4634-bf84-2770799927c8",- "status": "paused",- "source": "rlm_heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "3d985e69dce5",- "sessionId": "01a0c4e8-d25e-77ef-8f2d-a807e9add380",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work",- "label": "agent hb",- "prompt": "agent heartbeat check instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T16:59:52.280Z",- "updatedAt": "2026-09-21T17:00:01.063Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- }-]\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/09-closed.txt b/scripts/heartbeats-runs/20260921T165945Z/ts/09-closed.txtdeleted file mode 100644index 9f09690b2f..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/09-closed.txt+++ /dev/null@@ -1,36 +0,0 @@- heartbeats-verifier $0.00-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent v0.9.5- ▗█▛ ▟██▙▄██▛ ▟▛ model mock-1- ▗▟▌ ▐███▛▘▗▄█▖ cwd ~/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--- verifier seed turn--- heartbeats verifier seed reply--- create the agent heartbeat--- ✓ python · await rlm_heartbeat.create( · ↑ 7 ↓ 1 lines · 14ms-- agent heartbeat created--------- Collapsed mode (Ctrl+O to expand)-- >--← manage 2 heartbeats · 1 paused (Ctrl+R) · mock-1 · 110 (0%)diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/auth.json b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/auth.jsondeleted file mode 100644index 9e26dfeeb6..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/auth.json+++ /dev/null@@ -1 +0,0 @@-{}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/bin/fd b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/bin/fddeleted file mode 100755index 57405df9ea..0000000000Binary files a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/bin/fd and /dev/null differdiff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/daemon-workers/cd70e10b2a10/command-journal.jsonl b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/daemon-workers/cd70e10b2a10/command-journal.jsonldeleted file mode 100644index ab8d9cd3a9..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/daemon-workers/cd70e10b2a10/command-journal.jsonl+++ /dev/null@@ -1,13 +0,0 @@-{"version":1,"type":"received","key":"[\"75839afb3ef2\",\"hb-create\"]","clientId":"75839afb3ef2","commandId":"hb-create","commandType":"create","recordedAt":"2026-09-21T16:59:47.437Z"}-{"version":1,"type":"result","key":"[\"75839afb3ef2\",\"hb-create\"]","response":{"id":"hb-create","type":"response","command":"create","success":true,"data":{"id":"3d985e69dce5","lifecycle":"draft","activity":"idle","isSessionActive":false,"lastActivityAt":"2026-09-21T16:59:47.722Z","runtimeKind":"top-level","rlmDepth":0,"activeSessionId":"3d985e69dce5","sessionId":"01a0c4e8-d25e-77ef-8f2d-a807e9add380","sessionFile":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl","sessionName":"heartbeats-verifier","cwd":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work","model":{"id":"mock-1","name":"Mock 1","api":"openai-completions","provider":"prime-inference","baseUrl":"http://127.0.0.1:38085/v1","reasoning":false,"input":["text"],"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0},"contextWindow":128000,"maxTokens":4096},"thinkingLevel":"off","isStreaming":false,"isCompacting":false,"isBashRunning":false,"hasRunningRlmChildren":false,"isRunningTools":false,"attachedClients":0,"messageCount":0,"unfinishedActionCount":0,"created":"2026-09-21T16:59:47.678Z","modified":"2026-09-21T16:59:47.722Z","sessionActions":{"queuedCount":0,"steering":[],"followUps":[]},"rosterStatus":"idle","workerState":"ready","workerPid":2312105}},"recordedAt":"2026-09-21T16:59:47.733Z"}-{"version":1,"type":"received","key":"[\"75839afb3ef2\",\"hb-seed\"]","clientId":"75839afb3ef2","commandId":"hb-seed","commandType":"prompt_and_wait","recordedAt":"2026-09-21T16:59:47.737Z"}-{"version":1,"type":"result","key":"[\"75839afb3ef2\",\"hb-seed\"]","response":{"id":"hb-seed","type":"response","command":"prompt_and_wait","success":true},"recordedAt":"2026-09-21T16:59:47.784Z"}-{"version":1,"type":"received","key":"[\"75839afb3ef2\",\"hb-set\"]","clientId":"75839afb3ef2","commandId":"hb-set","commandType":"heartbeat_set","recordedAt":"2026-09-21T16:59:47.785Z"}-{"version":1,"type":"result","key":"[\"75839afb3ef2\",\"hb-set\"]","response":{"id":"hb-set","type":"response","command":"heartbeat_set","success":true,"data":{"heartbeat":{"id":"07e1e9d2-8a2d-4abd-a50d-20d650eeca37","status":"active","source":"heartbeat","runtimeKind":"top-level","deliveryMode":"steer","activeSessionId":"3d985e69dce5","sessionId":"01a0c4e8-d25e-77ef-8f2d-a807e9add380","sessionFile":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl","cwd":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work","prompt":"user heartbeat ping instruction","schedule":{"kind":"interval","expression":"every 30m","intervalMs":1800000},"createdAt":"2026-09-21T16:59:47.788Z","updatedAt":"2026-09-21T16:59:47.788Z","nextRunAt":"2026-09-21T17:29:47.788Z","runCount":0}}},"recordedAt":"2026-09-21T16:59:47.797Z"}-{"version":1,"type":"received","key":"[\"75839afb3ef2\",\"hb-agent\"]","clientId":"75839afb3ef2","commandId":"hb-agent","commandType":"prompt_and_wait","recordedAt":"2026-09-21T16:59:47.799Z"}-{"version":1,"type":"result","key":"[\"75839afb3ef2\",\"hb-agent\"]","response":{"id":"hb-agent","type":"response","command":"prompt_and_wait","success":true},"recordedAt":"2026-09-21T16:59:52.380Z"}-{"version":1,"type":"received","key":"[\"daemon-client:a763980a-b93f-4c26-8ab5-aa7900d3497a\",\"daemon_6\"]","clientId":"daemon-client:a763980a-b93f-4c26-8ab5-aa7900d3497a","commandId":"daemon_6","commandType":"heartbeat_manage","recordedAt":"2026-09-21T17:00:01.058Z"}-{"version":1,"type":"result","key":"[\"daemon-client:a763980a-b93f-4c26-8ab5-aa7900d3497a\",\"daemon_6\"]","response":{"id":"daemon_6","type":"response","command":"heartbeat_manage","success":true,"data":{"heartbeat":{"id":"4f327415-8d7b-4634-bf84-2770799927c8","status":"paused","source":"rlm_heartbeat","runtimeKind":"top-level","deliveryMode":"steer","activeSessionId":"3d985e69dce5","sessionId":"01a0c4e8-d25e-77ef-8f2d-a807e9add380","sessionFile":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl","cwd":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work","label":"agent hb","prompt":"agent heartbeat check instruction","schedule":{"kind":"interval","expression":"every 30m","intervalMs":1800000},"createdAt":"2026-09-21T16:59:52.280Z","updatedAt":"2026-09-21T17:00:01.063Z","runCount":0}}},"recordedAt":"2026-09-21T17:00:01.067Z"}-{"version":1,"type":"acknowledged","key":"[\"daemon-client:a763980a-b93f-4c26-8ab5-aa7900d3497a\",\"daemon_6\"]","recordedAt":"2026-09-21T17:00:01.072Z"}-{"version":1,"type":"received","key":"[\"1107d976e36d\",\"sd\"]","clientId":"1107d976e36d","commandId":"sd","commandType":"shutdown","recordedAt":"2026-09-21T17:00:04.646Z"}-{"version":1,"type":"result","key":"[\"1107d976e36d\",\"sd\"]","response":{"id":"sd","type":"response","command":"shutdown","success":true},"recordedAt":"2026-09-21T17:00:04.648Z"}diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/logs/agent.jsonl b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/logs/agent.jsonldeleted file mode 100644index 98b38ee055..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/logs/agent.jsonl+++ /dev/null@@ -1,5 +0,0 @@-{"socketPath":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/daemon.sock","ts":"2026-09-21T16:59:47.435Z","level":"warn","component":"coding-agent.daemon-supervisor","msg":"Prime Agent daemon supervisor 3927ebb5-9fe4-4791-82dd-47af86c4cc21 listening on /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/daemon.sock","pid":2312015,"mode":"daemon"}-{"socketPath":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/daemon.sock","ts":"2026-09-21T16:59:47.666Z","level":"warn","component":"coding-agent.daemon-supervisor","msg":"Session worker 63d663549f34 stderr: Prime Agent daemon listening on /tmp/hbv20260921T165945Z-ts/prime-agent-1000/worker-cd70e10b2a10-63d663549f34.sock","pid":2312015,"mode":"daemon"}-{"socketPath":"/tmp/hbv20260921T165945Z-ts/prime-agent-1000/worker-cd70e10b2a10-63d663549f34.sock","ts":"2026-09-21T16:59:47.666Z","level":"warn","component":"coding-agent.daemon","msg":"Prime Agent daemon listening on /tmp/hbv20260921T165945Z-ts/prime-agent-1000/worker-cd70e10b2a10-63d663549f34.sock","pid":2312105,"mode":"daemon"}-{"socketPath":"/tmp/hbv20260921T165945Z-ts/prime-agent-1000/worker-cd70e10b2a10-63d663549f34.sock","ts":"2026-09-21T17:00:04.880Z","level":"warn","component":"coding-agent.daemon","msg":"shutting down (exit 0); closing 0 active session(s)","pid":2312105,"mode":"daemon"}-{"socketPath":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/daemon.sock","ts":"2026-09-21T17:00:04.882Z","level":"warn","component":"coding-agent.daemon-supervisor","msg":"Session worker 63d663549f34 stderr: shutting down (exit 0); closing 0 active session(s)","pid":2312015,"mode":"daemon"}diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/logs/daemon.sock.cd70e10b.log b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/logs/daemon.sock.cd70e10b.logdeleted file mode 100644index f3d1d145d4..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/logs/daemon.sock.cd70e10b.log+++ /dev/null@@ -1,3 +0,0 @@-[2026-09-21T16:59:47.436Z] supervisor: Prime Agent daemon supervisor 3927ebb5-9fe4-4791-82dd-47af86c4cc21 listening on /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/daemon.sock-[2026-09-21T16:59:47.666Z] supervisor: Session worker 63d663549f34 stderr: Prime Agent daemon listening on /tmp/hbv20260921T165945Z-ts/prime-agent-1000/worker-cd70e10b2a10-63d663549f34.sock-[2026-09-21T17:00:04.882Z] supervisor: Session worker 63d663549f34 stderr: shutting down (exit 0); closing 0 active session(s)diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/logs/worker-cd70e10b2a10-63d663549f34.sock.d936f2e4.log b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/logs/worker-cd70e10b2a10-63d663549f34.sock.d936f2e4.logdeleted file mode 100644index b46e969204..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/logs/worker-cd70e10b2a10-63d663549f34.sock.d936f2e4.log+++ /dev/null@@ -1,2 +0,0 @@-[2026-09-21T16:59:47.666Z] Prime Agent daemon listening on /tmp/hbv20260921T165945Z-ts/prime-agent-1000/worker-cd70e10b2a10-63d663549f34.sock-[2026-09-21T17:00:04.880Z] shutting down (exit 0); closing 0 active session(s)diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/models.json b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/models.jsondeleted file mode 100644index e85b4cab56..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/models.json+++ /dev/null@@ -1,19 +0,0 @@-{- "providers": {- "prime-inference": {- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:38085/v1",- "apiKey": "sk-battery",- "models": [- {- "id": "mock-1",- "name": "Mock 1",- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:38085/v1",- "contextWindow": 128000,- "maxTokens": 4096- }- ]- }- }-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/prime-inference-models-cache.json b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/prime-inference-models-cache.jsondeleted file mode 100644index 7974b2aeb7..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/prime-inference-models-cache.json+++ /dev/null@@ -1 +0,0 @@-{"object":"list","data":[{"id":"alibaba/qwen3.5-flash","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.568539+00:00"},"specs":null},{"id":"alibaba/qwen3.7-max","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":3.75,"output_usd_per_mtok":11.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.639598+00:00"},"specs":null},{"id":"alibaba/qwen3.7-plus","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.717208+00:00"},"specs":null},{"id":"alibaba/qwen3.8-flash","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.225,"output_usd_per_mtok":0.705,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.787469+00:00"},"specs":null},{"id":"anthropic/claude-fable-5","object":"model","owned_by":"","created":1783031626,"display_name":"Claude Fable 5","pricing":{"input_usd_per_mtok":10,"output_usd_per_mtok":50,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-02T22:33:46.495072+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-fable-5.1","object":"model","owned_by":"","created":1788556514,"display_name":"Claude Fable 5.1","pricing":{"input_usd_per_mtok":10,"output_usd_per_mtok":50,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.113341+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-haiku-4.5","object":"model","owned_by":"","created":1761030860,"display_name":"Claude Haiku 4.5","pricing":{"input_usd_per_mtok":1,"output_usd_per_mtok":5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:20.826034+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-opus-4.1","object":"model","owned_by":"","created":1761157329,"display_name":"Claude Opus 4.1","pricing":{"input_usd_per_mtok":15,"output_usd_per_mtok":75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-22T18:22:09.605939+00:00"},"specs":{"context_window":200000,"max_output_tokens":32000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-opus-4.5","object":"model","owned_by":"","created":1764746904,"display_name":"Claude Opus 4.5","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-03T07:28:24.760458+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","verbosity"]},{"id":"anthropic/claude-opus-4.6","object":"model","owned_by":"","created":1772938679,"display_name":"Claude Opus 4.6","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-08T02:57:59.615639+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p","verbosity"]},{"id":"anthropic/claude-opus-4.7","object":"model","owned_by":"","created":1776679634,"display_name":"Claude Opus 4.7","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-20T10:07:14.028142+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-opus-4.8","object":"model","owned_by":"","created":1780660082,"display_name":"Claude Opus 4.8","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-05T11:48:02.246650+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-opus-5","object":"model","owned_by":"","created":1784919442,"display_name":"Claude Opus 5","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-24T18:57:22.868734+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-sonnet-4","object":"model","owned_by":"","created":1761029716,"display_name":"Claude Sonnet 4","pricing":{"input_usd_per_mtok":3,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:16.611551+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-sonnet-4.5","object":"model","owned_by":"","created":1759212031,"display_name":"Claude Sonnet 4.5","pricing":{"input_usd_per_mtok":3,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T06:00:31.866675+00:00"},"specs":{"context_window":1000000,"max_output_tokens":64000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-sonnet-4.6","object":"model","owned_by":"","created":1772054770,"display_name":"Claude Sonnet 4.6","pricing":{"input_usd_per_mtok":3,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:10.104879+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","medium","low"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p","verbosity"]},{"id":"anthropic/claude-sonnet-5","object":"model","owned_by":"","created":1783031448,"display_name":"Claude Sonnet 5","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-02T22:30:48.220566+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"deepseek/deepseek-chat-v3.1","object":"model","owned_by":"","created":1761029725,"display_name":"DeepSeek V3.1","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":1.7,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:25.583563+00:00"},"specs":{"context_window":163840,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v3.1-terminus","object":"model","owned_by":"","created":1759198118,"display_name":"DeepSeek V3.1 Terminus","pricing":{"input_usd_per_mtok":0.27,"output_usd_per_mtok":1,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:08:38.000459+00:00"},"specs":{"context_window":163840,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"deepseek/deepseek-v3.2","object":"model","owned_by":"","created":1764658428,"display_name":"DeepSeek V3.2","pricing":{"input_usd_per_mtok":0.3705,"output_usd_per_mtok":1.1115,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-02T06:53:48.223623+00:00"},"specs":{"context_window":163840,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":false,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v3.2-exp","object":"model","owned_by":"","created":1759198146,"display_name":"DeepSeek V3.2 Exp","pricing":{"input_usd_per_mtok":0.27,"output_usd_per_mtok":0.41,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:09:06.170541+00:00"},"specs":{"context_window":163840,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4.1-flash","object":"model","owned_by":"","created":1789152253,"display_name":"DeepSeek V4.1 Flash","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-11T18:44:13.104931+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-flash","object":"model","owned_by":"","created":1778785963,"display_name":"DeepSeek V4 Flash 0423","pricing":{"input_usd_per_mtok":0.44,"output_usd_per_mtok":1.32,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T19:12:43.449839+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_completion_tokens","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-flash-0731","object":"model","owned_by":"","created":1785777617,"display_name":"DeepSeek V4 Flash 0731","pricing":{"input_usd_per_mtok":0.44,"output_usd_per_mtok":1.32,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T17:20:17.849313+00:00"},"specs":{"context_window":1310720,"max_output_tokens":943718,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-pro","object":"model","owned_by":"","created":1778785932,"display_name":"DeepSeek V4 Pro 0423","pricing":{"input_usd_per_mtok":1.91,"output_usd_per_mtok":3.83,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T19:12:12.010236+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_completion_tokens","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"google/gemini-2.5-flash","object":"model","owned_by":"","created":1761029715,"display_name":"Gemini 2.5 Flash","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":2.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:15.585176+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65535,"modalities":{"input":["file","image","text","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-2.5-flash-lite","object":"model","owned_by":"","created":1761029721,"display_name":"Gemini 2.5 Flash Lite","pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:21.403298+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65535,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-2.5-pro","object":"model","owned_by":"","created":1761029717,"display_name":"Gemini 2.5 Pro","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:17.621295+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.1-pro-preview","object":"model","owned_by":"","created":1772054806,"display_name":"Gemini 3.1 Pro Preview","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":12,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:46.169413+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["audio","file","image","text","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.5-flash","object":"model","owned_by":"","created":1781958981,"display_name":"Gemini 3.5 Flash","pricing":{"input_usd_per_mtok":1.5,"output_usd_per_mtok":9,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-20T12:36:21.024091+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.6-flash","object":"model","owned_by":"","created":1784918138,"display_name":"Gemini 3.6 Flash","pricing":{"input_usd_per_mtok":1.5,"output_usd_per_mtok":7.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-24T18:35:38.706927+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.7-flash","object":"model","owned_by":"","created":1787848124,"display_name":"Gemini 3.7 Flash","pricing":{"input_usd_per_mtok":1.35,"output_usd_per_mtok":6.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-27T16:28:44.601830+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.8-flash","object":"model","owned_by":"","created":1788556514,"display_name":"Gemini 3.8 Flash","pricing":{"input_usd_per_mtok":0.75,"output_usd_per_mtok":3.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.212597+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3-flash-preview","object":"model","owned_by":"","created":1766202374,"display_name":"Gemini 3 Flash Preview","pricing":{"input_usd_per_mtok":0.5,"output_usd_per_mtok":3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-20T03:46:14.305378+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemma-3-27b-it","object":"model","owned_by":"","created":1761030851,"display_name":"Gemma 3 27B","pricing":{"input_usd_per_mtok":0.119,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:11.952792+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"meta-llama/Llama-3.2-1B-Instruct","object":"model","owned_by":"","created":1771939296,"display_name":"Llama 3.2 1B Instruct","pricing":{"input_usd_per_mtok":0.027,"output_usd_per_mtok":0.201,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T13:21:36.921319+00:00"},"specs":{"context_window":60000,"max_output_tokens":54000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","max_tokens","min_p","presence_penalty","repetition_penalty","seed","stop","temperature","top_k","top_p"]},{"id":"meta-llama/Llama-3.2-3B-Instruct","object":"model","owned_by":"","created":1771939312,"display_name":"Llama 3.2 3B Instruct","pricing":{"input_usd_per_mtok":0.0509,"output_usd_per_mtok":0.335,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T13:21:52.649872+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","seed","stop","structured_outputs","temperature","top_k","top_logprobs","top_p"]},{"id":"meta-llama/llama-3.3-70b-instruct","object":"model","owned_by":"","created":1759196298,"display_name":"Llama 3.3 70B Instruct","pricing":{"input_usd_per_mtok":1.04,"output_usd_per_mtok":2.253,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T01:38:18.545960+00:00"},"specs":{"context_window":131072,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"meta-llama/llama-4-maverick","object":"model","owned_by":"","created":1761030850,"display_name":"Llama 4 Maverick","pricing":{"input_usd_per_mtok":0.35,"output_usd_per_mtok":1.15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:10.101027+00:00"},"specs":{"context_window":1048576,"max_output_tokens":16384,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m2.5","object":"model","owned_by":"","created":1771374795,"display_name":"MiniMax M2.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-18T00:33:15.739871+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m2.7","object":"model","owned_by":"","created":1775779870,"display_name":"MiniMax M2.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:10.312006+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m3","object":"model","owned_by":"","created":1780311536,"display_name":"MiniMax M3","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-01T10:58:56.335485+00:00"},"specs":{"context_window":1048576,"max_output_tokens":512000,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"mistralai/mistral-large-2512","object":"model","owned_by":"","created":1764689752,"display_name":null,"pricing":{"input_usd_per_mtok":0.5,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-02T15:35:52.296516+00:00"},"specs":null},{"id":"mistralai/mistral-nemo","object":"model","owned_by":"","created":1761030857,"display_name":"Mistral Nemo","pricing":{"input_usd_per_mtok":0.165,"output_usd_per_mtok":0.17,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:17.801302+00:00"},"specs":{"context_window":131072,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"mistralai/mistral-small-2603","object":"model","owned_by":"","created":1775779872,"display_name":"Mistral Small 4","pricing":{"input_usd_per_mtok":0.165,"output_usd_per_mtok":0.66,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:12.604966+00:00"},"specs":{"context_window":262144,"max_output_tokens":209715,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","none"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"mistralai/mixtral-8x22b-instruct","object":"model","owned_by":"","created":1759198003,"display_name":"Mixtral 8x22B Instruct","pricing":{"input_usd_per_mtok":2.2,"output_usd_per_mtok":6.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:06:43.614656+00:00"},"specs":{"context_window":65536,"max_output_tokens":52428,"modalities":{"input":["text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","max_tokens","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"moonshotai/kimi-k2-0905","object":"model","owned_by":"","created":1759907126,"display_name":"Kimi K2 0905","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:26.057085+00:00"},"specs":{"context_window":262144,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"moonshotai/kimi-k2.5","object":"model","owned_by":"","created":1769800671,"display_name":"Kimi K2.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-30T19:17:51.210047+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k2.6","object":"model","owned_by":"","created":1776733288,"display_name":"Kimi K2.6","pricing":{"input_usd_per_mtok":0.95,"output_usd_per_mtok":4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-21T01:01:28.804384+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k2.7-code","object":"model","owned_by":"","created":1781282432,"display_name":"Kimi K2.7 Code","pricing":{"input_usd_per_mtok":1.9,"output_usd_per_mtok":8,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-12T16:40:32.168235+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k3","object":"model","owned_by":"","created":1784248110,"display_name":"Kimi K3","pricing":{"input_usd_per_mtok":3.45,"output_usd_per_mtok":17.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-17T00:28:30.162170+00:00"},"specs":{"context_window":1048576,"max_output_tokens":943718,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"max","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"nvidia/nemotron-3-nano-30b-a3b","object":"model","owned_by":"","created":1775779886,"display_name":"Nemotron 3 Nano 30B A3B","pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.24,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:26.952299+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"openai/gpt-4.1","object":"model","owned_by":"","created":1759401802,"display_name":"GPT-4.1","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":8,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:22.496353+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4.1-mini","object":"model","owned_by":"","created":1759401806,"display_name":"GPT-4.1 Mini","pricing":{"input_usd_per_mtok":0.4,"output_usd_per_mtok":1.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:26.911016+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4.1-nano","object":"model","owned_by":"","created":1759401808,"display_name":"GPT-4.1 Nano","pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:28.011794+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4o","object":"model","owned_by":"","created":1761029734,"display_name":"GPT-4o","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:34.447350+00:00"},"specs":{"context_window":128000,"max_output_tokens":16384,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_completion_tokens","max_tokens","prediction","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p","web_search_options"]},{"id":"openai/gpt-4o-mini","object":"model","owned_by":"","created":1761029722,"display_name":"GPT-4o-mini","pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:22.331052+00:00"},"specs":{"context_window":128000,"max_output_tokens":16384,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_completion_tokens","max_tokens","prediction","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p","web_search_options"]},{"id":"openai/gpt-5","object":"model","owned_by":"","created":1759211784,"display_name":"GPT-5","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T05:56:24.831437+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.1","object":"model","owned_by":"","created":1763426084,"display_name":"GPT-5.1","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-11-18T00:34:44.949671+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","none"],"default_effort":"none","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.2","object":"model","owned_by":"","created":1765611176,"display_name":"GPT-5.2","pricing":{"input_usd_per_mtok":1.75,"output_usd_per_mtok":14,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-13T07:32:56.544785+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.2-pro","object":"model","owned_by":"","created":1765611177,"display_name":"GPT-5.2 Pro","pricing":{"input_usd_per_mtok":21,"output_usd_per_mtok":168,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-13T07:32:57.583455+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.3-codex","object":"model","owned_by":"","created":1772054791,"display_name":"GPT-5.3-Codex","pricing":{"input_usd_per_mtok":1.75,"output_usd_per_mtok":14,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:31.496994+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4","object":"model","owned_by":"","created":1773713673,"display_name":"GPT-5.4","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-17T02:14:33.278960+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-mini","object":"model","owned_by":"","created":1775779863,"display_name":"GPT-5.4 Mini","pricing":{"input_usd_per_mtok":0.75,"output_usd_per_mtok":4.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:03.742760+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-nano","object":"model","owned_by":"","created":1775779866,"display_name":"GPT-5.4 Nano","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:06.153745+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-pro","object":"model","owned_by":"","created":1773713674,"display_name":"GPT-5.4 Pro","pricing":{"input_usd_per_mtok":30,"output_usd_per_mtok":180,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-17T02:14:34.995439+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.5","object":"model","owned_by":"","created":1777306094,"display_name":"GPT-5.5","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":30,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-27T16:08:14.065946+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6","object":"model","owned_by":"","created":1783751214,"display_name":null,"pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":30,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:26:54.495544+00:00"},"specs":null},{"id":"openai/gpt-5.6-luna","object":"model","owned_by":"","created":1783751321,"display_name":"GPT-5.6 Luna","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:41.639902+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-luna-pro","object":"model","owned_by":"","created":1783751322,"display_name":"GPT-5.6 Luna Pro","pricing":{"input_usd_per_mtok":1,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:42.459149+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-sol","object":"model","owned_by":"","created":1783751318,"display_name":"GPT-5.6 Sol","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":30,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:38.262869+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-sol-pro","object":"model","owned_by":"","created":1783751319,"display_name":"GPT-5.6 Sol Pro","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":30,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:39.039507+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-terra","object":"model","owned_by":"","created":1783751319,"display_name":"GPT-5.6 Terra","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:39.851751+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-terra-pro","object":"model","owned_by":"","created":1783751320,"display_name":"GPT-5.6 Terra Pro","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:40.628845+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5-mini","object":"model","owned_by":"","created":1759401800,"display_name":"GPT-5 Mini","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:20.338354+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5-nano","object":"model","owned_by":"","created":1759401801,"display_name":"GPT-5 Nano","pricing":{"input_usd_per_mtok":0.05,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:21.418908+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-6-astra","object":"model","owned_by":"","created":1788556514,"display_name":"GPT-6 Astra","pricing":{"input_usd_per_mtok":10,"output_usd_per_mtok":50,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.299026+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-oss-120b","object":"model","owned_by":"","created":1760042083,"display_name":"gpt-oss-120b","pricing":{"input_usd_per_mtok":0.35,"output_usd_per_mtok":0.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-09T20:34:43.236004+00:00"},"specs":{"context_window":131072,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"openai/gpt-oss-20b","object":"model","owned_by":"","created":1761030856,"display_name":"gpt-oss-20b","pricing":{"input_usd_per_mtok":0.07,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:16.897238+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"poolside/laguna-s-2.1","object":"model","owned_by":"","created":1785726826,"display_name":"Laguna S 2.1","pricing":{"input_usd_per_mtok":0.09,"output_usd_per_mtok":0.18,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T03:13:46.654853+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","temperature","tool_choice","tools"]},{"id":"poolside/laguna-xs-2.1","object":"model","owned_by":"","created":1785726826,"display_name":"Laguna XS 2.1","pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.12,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T03:13:46.740724+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","temperature","tool_choice","tools"]},{"id":"qwen/qwen3-235b-a22b-2507","object":"model","owned_by":"","created":1759198117,"display_name":"Qwen3 235B A22B Instruct 2507","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:08:37.415647+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-235B-A22B-Instruct-2507","object":"model","owned_by":"","created":1771937600,"display_name":"Qwen3 235B A22B Instruct 2507","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:20.866004+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-235B-A22B-Thinking-2507","object":"model","owned_by":"","created":1771937601,"display_name":"Qwen3 235B A22B Thinking 2507","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:21.703567+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-30b-a3b-instruct-2507","object":"model","owned_by":"","created":1759401803,"display_name":"Qwen3 30B A3B Instruct 2507","pricing":{"input_usd_per_mtok":0.13,"output_usd_per_mtok":0.52,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:23.646850+00:00"},"specs":{"context_window":262144,"max_output_tokens":32000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-30B-A3B-Thinking-2507","object":"model","owned_by":"","created":1771937592,"display_name":"Qwen3 30B A3B Thinking 2507","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:12.163500+00:00"},"specs":{"context_window":81920,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"Qwen/Qwen3.5-0.8B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.04,"output_usd_per_mtok":0.08,"cache_read_usd_per_mtok":0.036,"cache_write_usd_per_mtok":0.04,"effective_at":"2026-04-27T14:12:40.112195+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-122B-A10B","object":"model","owned_by":"","created":1787974367,"display_name":null,"pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":0.9,"cache_read_usd_per_mtok":0.27,"cache_write_usd_per_mtok":0.3,"effective_at":"2026-08-29T03:32:47.538747+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-2B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.18,"cache_read_usd_per_mtok":0.054,"cache_write_usd_per_mtok":0.06,"effective_at":"2026-04-27T14:12:40.311797+00:00"},"specs":null},{"id":"qwen/qwen3.5-35b-a3b","object":"model","owned_by":"","created":1778742870,"display_name":"Qwen3.5-35B-A3B","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T07:14:30.333413+00:00"},"specs":{"context_window":262144,"max_output_tokens":16384,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.5-397b-a17b","object":"model","owned_by":"","created":1775696599,"display_name":"Qwen3.5 397B A17B","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-09T01:03:19.130519+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3.5-4B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":0.09,"cache_write_usd_per_mtok":0.1,"effective_at":"2026-04-27T14:12:40.492113+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-9B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.18,"output_usd_per_mtok":0.54,"cache_read_usd_per_mtok":0.162,"cache_write_usd_per_mtok":0.18,"effective_at":"2026-04-27T14:12:40.664813+00:00"},"specs":null},{"id":"qwen/qwen3.6-27b","object":"model","owned_by":"","created":1779244080,"display_name":"Qwen3.6 27B","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-20T02:28:00.420376+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.6-35b-a3b","object":"model","owned_by":"","created":1778092324,"display_name":"Qwen3.6 35B A3B","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:32:04.441666+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.7-flash","object":"model","owned_by":"","created":1785422211,"display_name":"Qwen3.7 Flash","pricing":{"input_usd_per_mtok":0.03,"output_usd_per_mtok":0.13,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-30T14:36:51.013707+00:00"},"specs":{"context_window":1000000,"max_output_tokens":65536,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","response_format","seed","temperature","tool_choice","tools","top_logprobs","top_p"]},{"id":"qwen/qwen3-8b","object":"model","owned_by":"","created":1767847988,"display_name":"Qwen3 8B","pricing":{"input_usd_per_mtok":0.117,"output_usd_per_mtok":0.455,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-08T04:53:08.134989+00:00"},"specs":{"context_window":131072,"max_output_tokens":8192,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"qwen/qwen3.8-max","object":"model","owned_by":"","created":1786408084,"display_name":null,"pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-11T00:28:04.248858+00:00"},"specs":null},{"id":"qwen/qwen3-coder","object":"model","owned_by":"","created":1761030855,"display_name":"Qwen3 Coder 480B A35B","pricing":{"input_usd_per_mtok":0.975,"output_usd_per_mtok":4.875,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:15.022804+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-coder-next","object":"model","owned_by":"","created":1772054821,"display_name":"Qwen3 Coder Next","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:27:01.126222+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-max","object":"model","owned_by":"","created":1764463224,"display_name":"Qwen3 Max","pricing":{"input_usd_per_mtok":1.2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-11-30T00:40:24.859337+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","logprobs","max_tokens","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-235b-a22b-instruct","object":"model","owned_by":"","created":1761030856,"display_name":"Qwen3 VL 235B A22B Instruct","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:16.011386+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-235b-a22b-thinking","object":"model","owned_by":"","created":1764830992,"display_name":"Qwen3 VL 235B A22B Thinking","pricing":{"input_usd_per_mtok":0.98,"output_usd_per_mtok":4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:52.368716+00:00"},"specs":{"context_window":131072,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-30b-a3b-instruct","object":"model","owned_by":"","created":1764830991,"display_name":"Qwen3 VL 30B A3B Instruct","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":0.7,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:51.204281+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-VL-30B-A3B-Thinking","object":"model","owned_by":"","created":1771937598,"display_name":"Qwen3 VL 30B A3B Thinking","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:18.456091+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-8b-instruct","object":"model","owned_by":"","created":1764830989,"display_name":"Qwen3 VL 8B Instruct","pricing":{"input_usd_per_mtok":0.117,"output_usd_per_mtok":0.455,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:49.046332+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["image","text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"x-ai/grok-4.20","object":"model","owned_by":"","created":1775779880,"display_name":"Grok 4.20","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:20.257314+00:00"},"specs":{"context_window":2000000,"max_output_tokens":1800000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p"]},{"id":"x-ai/grok-4.20-multi-agent","object":"model","owned_by":"","created":1775779882,"display_name":"Grok 4.20 Multi-Agent","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:22.350470+00:00"},"specs":{"context_window":2000000,"max_output_tokens":1800000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","temperature","top_logprobs","top_p"]},{"id":"x-ai/grok-4.6","object":"model","owned_by":"","created":1787959644,"display_name":"Grok 4.6","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-28T23:27:24.930899+00:00"},"specs":{"context_window":500000,"max_output_tokens":450000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"xiaomi/mimo-v2.5","object":"model","owned_by":"","created":1778092300,"display_name":"MiMo-V2.5","pricing":{"input_usd_per_mtok":0.168,"output_usd_per_mtok":0.336,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:31:40.102605+00:00"},"specs":{"context_window":1050000,"max_output_tokens":131072,"modalities":{"input":["text","audio","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"xiaomi/mimo-v2.5-pro","object":"model","owned_by":"","created":1778092285,"display_name":"MiMo-V2.5-Pro","pricing":{"input_usd_per_mtok":0.48024,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:31:25.388731+00:00"},"specs":{"context_window":1050000,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-4.5","object":"model","owned_by":"","created":1759907123,"display_name":"GLM 4.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:23.880304+00:00"},"specs":{"context_window":131072,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.5-air","object":"model","owned_by":"","created":1759907122,"display_name":"GLM 4.5 Air","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.1,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:22.754541+00:00"},"specs":{"context_window":131072,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","repetition_penalty","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.6","object":"model","owned_by":"","created":1759907125,"display_name":"GLM 4.6","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:25.067849+00:00"},"specs":{"context_window":204800,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.7","object":"model","owned_by":"","created":1768006861,"display_name":"GLM 4.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-10T01:01:01.166455+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_p"]},{"id":"z-ai/glm-4.7-flash","object":"model","owned_by":"","created":1770082685,"display_name":"GLM 4.7 Flash","pricing":{"input_usd_per_mtok":0.07,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-03T01:38:05.842638+00:00"},"specs":{"context_window":200000,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5","object":"model","owned_by":"","created":1771374834,"display_name":"GLM 5","pricing":{"input_usd_per_mtok":1,"output_usd_per_mtok":3.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-18T00:33:54.765331+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.1","object":"model","owned_by":"","created":1775779875,"display_name":"GLM 5.1","pricing":{"input_usd_per_mtok":1.4,"output_usd_per_mtok":4.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:15.012238+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.2","object":"model","owned_by":"","created":1781738425,"display_name":"GLM 5.2","pricing":{"input_usd_per_mtok":1.54,"output_usd_per_mtok":4.84,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-17T23:20:25.382141+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.3","object":"model","owned_by":"","created":1787267428,"display_name":"GLM 5.3","pricing":{"input_usd_per_mtok":1.4,"output_usd_per_mtok":4.4,"cache_read_usd_per_mtok":1.26,"cache_write_usd_per_mtok":1.4,"effective_at":"2026-08-20T23:10:28.976971+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["low","high","max"],"default_effort":"max","default_enabled":true,"mandatory":true},"supported_parameters":["max_tokens","temperature","top_p","tools","tool_choice","reasoning","reasoning_effort"]},{"id":"z-ai/glm-5.3-flash","object":"model","owned_by":"","created":1787848124,"display_name":"GLM 5.3 Flash","pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-27T16:28:44.680637+00:00"},"specs":{"context_window":1310720,"max_output_tokens":131072,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"max","default_enabled":true,"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"zai-org/GLM-4.7","object":"model","owned_by":"","created":1771937590,"display_name":"GLM 4.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:10.608022+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_p"]}]}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/session-artifacts/01a0c4e8-d25e-77ef-8f2d-a807e9add380/kernel-state.dill b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/session-artifacts/01a0c4e8-d25e-77ef-8f2d-a807e9add380/kernel-state.dilldeleted file mode 100644index f8c435d169..0000000000Binary files a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/session-artifacts/01a0c4e8-d25e-77ef-8f2d-a807e9add380/kernel-state.dill and /dev/null differdiff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/session-artifacts/01a0c4e8-d25e-77ef-8f2d-a807e9add380/kernel-state.json b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/session-artifacts/01a0c4e8-d25e-77ef-8f2d-a807e9add380/kernel-state.jsondeleted file mode 100644index 5c272916dc..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/session-artifacts/01a0c4e8-d25e-77ef-8f2d-a807e9add380/kernel-state.json+++ /dev/null@@ -1 +0,0 @@-{"version": 1, "savedNames": ["agent_message", "agent_observe", "goal", "rlm_heartbeat"], "skipped": [{"name": "refine", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "compact", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "attach_image", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "edit", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "websearch", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}], "pruned": [], "bytes": 6036, "pythonVersion": "3.11.16", "timestamp": "2026-09-21T17:00:04.661940+00:00"}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/session-artifacts/01a0c4e8-d25e-77ef-8f2d-a807e9add380/kernel-stderr.log b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/session-artifacts/01a0c4e8-d25e-77ef-8f2d-a807e9add380/kernel-stderr.logdeleted file mode 100644index e69de29bb2..0000000000diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/session-artifacts/01a0c4e8-d25e-77ef-8f2d-a807e9add380/scheduled-jobs.json b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/session-artifacts/01a0c4e8-d25e-77ef-8f2d-a807e9add380/scheduled-jobs.jsondeleted file mode 100644index c4dfb17967..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/session-artifacts/01a0c4e8-d25e-77ef-8f2d-a807e9add380/scheduled-jobs.json+++ /dev/null@@ -1,46 +0,0 @@-{- "jobs": [- {- "id": "07e1e9d2-8a2d-4abd-a50d-20d650eeca37",- "status": "cancelled",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "3d985e69dce5",- "sessionId": "01a0c4e8-d25e-77ef-8f2d-a807e9add380",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T16:59:47.788Z",- "updatedAt": "2026-09-21T17:00:04.652Z",- "runCount": 0- },- {- "id": "4f327415-8d7b-4634-bf84-2770799927c8",- "status": "cancelled",- "source": "rlm_heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "3d985e69dce5",- "sessionId": "01a0c4e8-d25e-77ef-8f2d-a807e9add380",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work",- "label": "agent hb",- "prompt": "agent heartbeat check instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T16:59:52.280Z",- "updatedAt": "2026-09-21T17:00:04.652Z",- "runCount": 0- }- ],- "dispatches": []-}diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/session-artifacts/01a0c4e8-d25e-77ef-8f2d-a807e9add380/semantic-edges.jsonl b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/session-artifacts/01a0c4e8-d25e-77ef-8f2d-a807e9add380/semantic-edges.jsonldeleted file mode 100644index fcc0b65350..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/session-artifacts/01a0c4e8-d25e-77ef-8f2d-a807e9add380/semantic-edges.jsonl+++ /dev/null@@ -1,7 +0,0 @@-{"type":"session_registered","session_id":"01a0c4e8-d25e-77ef-8f2d-a807e9add380"}-{"type":"request_started","request_id":"990e397622f24857805899efc794609b","session_id":"01a0c4e8-d25e-77ef-8f2d-a807e9add380"}-{"type":"request_finished","request_id":"990e397622f24857805899efc794609b"}-{"type":"request_started","request_id":"a865746abef24ecd82e020711c2cab95","session_id":"01a0c4e8-d25e-77ef-8f2d-a807e9add380"}-{"type":"request_finished","request_id":"a865746abef24ecd82e020711c2cab95"}-{"type":"request_started","request_id":"3d6f1674d4724ac5b9e42b094e950fa3","session_id":"01a0c4e8-d25e-77ef-8f2d-a807e9add380"}-{"type":"request_finished","request_id":"3d6f1674d4724ac5b9e42b094e950fa3"}diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonldeleted file mode 100644index e5f7966509..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl+++ /dev/null@@ -1,14 +0,0 @@-{"type":"session","version":3,"id":"01a0c4e8-d25e-77ef-8f2d-a807e9add380","timestamp":"2026-09-21T16:59:47.678Z","cwd":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work","rlmDepth":0,"git":{"repoUrl":"https://github.com/kevinjosethomas/prime-agent-rs.git","commit":"c38af5bb4bd6152681cfe2afb79904f46a24f6ec","branch":"lane/heartbeats-menu"}}-{"type":"model_change","id":"5910d490","parentId":null,"timestamp":"2026-09-21T16:59:47.709Z","provider":"prime-inference","modelId":"mock-1"}-{"type":"thinking_level_change","id":"770bb3c8","parentId":"5910d490","timestamp":"2026-09-21T16:59:47.709Z","thinkingLevel":"off"}-{"type":"service_tier_change","id":"dc25abe6","parentId":"770bb3c8","timestamp":"2026-09-21T16:59:47.709Z","serviceTier":"default"}-{"type":"session_info","id":"5777a741","parentId":"dc25abe6","timestamp":"2026-09-21T16:59:47.725Z","name":"heartbeats-verifier"}-{"type":"session_state","id":"772bceb8","parentId":"5777a741","timestamp":"2026-09-21T16:59:47.726Z","state":{"status":"active"}}-{"type":"custom_message","customType":"harness_digest","content":"[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>","display":false,"details":{"digest":"# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0"},"id":"c8b667a6","parentId":"772bceb8","timestamp":"2026-09-21T16:59:47.754Z"}-{"type":"message","id":"ee79e6f8","parentId":"c8b667a6","timestamp":"2026-09-21T16:59:47.758Z","message":{"role":"user","content":[{"type":"text","text":"verifier seed turn"}],"timestamp":1790009987739}}-{"type":"message","id":"06ac33de","parentId":"ee79e6f8","timestamp":"2026-09-21T16:59:47.774Z","message":{"role":"assistant","content":[{"type":"text","text":"heartbeats verifier seed reply"}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790009987760,"responseId":"chatcmpl-battery"}}-{"type":"message","id":"dbe11334","parentId":"06ac33de","timestamp":"2026-09-21T16:59:47.819Z","message":{"role":"user","content":[{"type":"text","text":"create the agent heartbeat"}],"timestamp":1790009987801}}-{"type":"message","id":"72fb2285","parentId":"dbe11334","timestamp":"2026-09-21T16:59:47.828Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"call_battery_1","name":"ipython","arguments":{"code":"import rlm_heartbeat\nawait rlm_heartbeat.create(\n 'agent heartbeat check instruction',\n interval='every 30m',\n label='agent hb',\n)\nprint('created')"}}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790009987819,"responseId":"chatcmpl-battery"}}-{"type":"message","id":"6414c960","parentId":"72fb2285","timestamp":"2026-09-21T16:59:52.306Z","message":{"role":"toolResult","toolCallId":"call_battery_1","toolName":"ipython","content":[{"type":"text","text":"created\n"}],"details":{"durationMs":14,"status":"ok","stdout":"created\n","stderr":"","kernelRestarted":false},"isError":false,"timestamp":1790009992290}}-{"type":"message","id":"c26b0370","parentId":"6414c960","timestamp":"2026-09-21T16:59:52.317Z","message":{"role":"assistant","content":[{"type":"text","text":"agent heartbeat created"}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790009992310,"responseId":"chatcmpl-battery"}}-{"type":"session_state","id":"dfaa2614","parentId":"c26b0370","timestamp":"2026-09-21T17:00:04.655Z","state":{"status":"archived"}}diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/settings.json b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/settings.jsondeleted file mode 100644index 539978831e..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/settings.json+++ /dev/null@@ -1 +0,0 @@-{"onboardingShown": true, "telemetry": {"noticeShown": true}}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/telemetry.json b/scripts/heartbeats-runs/20260921T165945Z/ts/agent/telemetry.jsondeleted file mode 100644index f6ce3a2055..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/agent/telemetry.json+++ /dev/null@@ -1,4 +0,0 @@-{- "version": 1,- "installationId": "e34cd5ff-d0bf-4176-b2c2-d1c07c3ff3a1"-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/daemon.log b/scripts/heartbeats-runs/20260921T165945Z/ts/daemon.logdeleted file mode 100644index 552e13e20f..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/daemon.log+++ /dev/null@@ -1,3 +0,0 @@-Prime Agent daemon supervisor 3927ebb5-9fe4-4791-82dd-47af86c4cc21 listening on /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/daemon.sock-Session worker 63d663549f34 stderr: Prime Agent daemon listening on /tmp/hbv20260921T165945Z-ts/prime-agent-1000/worker-cd70e10b2a10-63d663549f34.sock-Session worker 63d663549f34 stderr: shutting down (exit 0); closing 0 active session(s)diff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/mock-script.json b/scripts/heartbeats-runs/20260921T165945Z/ts/mock-script.jsondeleted file mode 100644index 85e336d9d6..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/mock-script.json+++ /dev/null@@ -1 +0,0 @@-{"responses": [{"toolCall": {"name": "ipython", "arguments": {"code": "import rlm_heartbeat\nawait rlm_heartbeat.create(\n 'agent heartbeat check instruction',\n interval='every 30m',\n label='agent hb',\n)\nprint('created')"}}}, {"text": "agent heartbeat created"}]}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T165945Z/ts/mock-script.json.requests.jsonl b/scripts/heartbeats-runs/20260921T165945Z/ts/mock-script.json.requests.jsonldeleted file mode 100644index 4d28b009cc..0000000000--- a/scripts/heartbeats-runs/20260921T165945Z/ts/mock-script.json.requests.jsonl+++ /dev/null@@ -1,5 +0,0 @@-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "You are a general purpose agent that uses code to solve tasks.\nYou solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.\nWhen you are done, stop calling tools and state your final answer.\n\nFor slow or independently completing work, use a nonblocking control loop: start the work, record its handle or output location, then end your turn. A `bash()` handle left running beyond its creating cell sends a completion follow-up; when it arrives, inspect the saved handle and continue. Reading a finished handle's result first cancels that follow-up.\nWhen delegation is available and useful, assign independent substantive tasks to separate workers. Start independent workers without waiting for each one sequentially, and let them run in parallel.\nDo not keep the turn open by polling with `time.sleep()` or shell `sleep`, and do not replace polling with a long blocking `await`. Await only the short operation needed to start work or inspect a result that is already available; otherwise end the turn.\n\nAs the user-facing root agent, when work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n\nUse simplified technical English by default for user-facing prose.\nPrefer short sentences, common words, and concrete verbs. State one main action or fact per sentence when practical. Use lists for steps or conditions.\nKeep necessary technical terms, names, commands, code, paths, and exact quoted text unchanged. State uncertainty directly.\nTreat this as clarity guidance, not a claim of formal ASD-STE100 compliance. Preserve a user-requested format, tone, terminology, and necessary precision.\n\nWorking directory: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work\nConversation log: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl\nRecursive agent depth: 0\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nInstalled Python skill modules (pre-imported): `refine`, `compact`, `agent_observe`, `attach_image`, `edit`, `agent_message`, `rlm_heartbeat`, `goal`, `websearch`.\nRead each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.\nEach skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.\nFor targeted existing-file edits, prefer the pre-imported async `edit` skill from the REPL: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.\nAgent messaging is restricted to your parent, siblings, and direct children; roots are siblings, and deeper communication relays through the intermediate child.\nAgent observation is restricted to your parent, siblings, and direct children; roots are siblings, and deeper inspection relays through the intermediate child.\n\nFrom a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm.spawn(...)` still creates a child.\n\nAn `rlm` object is already in your global namespace. `await rlm.spawn('sub-task', name='api-reviewer')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.\n`name` is required: choose a stable child name that is unique among siblings.\nA child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.\nUse `await agent_observe.list_agents()` to discover family, including inactive members, and `await rlm.list_subagents()` to recover direct child handles.\nChildren reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.\nUse `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.\nUse `agent_observe` to inspect a child's rollout. Observation is restricted to your parent, siblings, and direct children; relay through the intermediate child for deeper descendants.\nSpawn independent children in separate calls and end your turn instead of awaiting completion. Multiple replies may arrive over multiple turns. Delete a direct child explicitly with `await rlm.delete_subagent(child)` when it is no longer needed.\n\nThe `ipython` tool is a persistent Python REPL \u2014 the agent's long-lived control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Top-level `await` works directly. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.\n\nPython is the orchestration language: use Python for loops, conditionals, parsing, and state. Use `bash()` to invoke programs, not to write shell programs \u2014 no shell loops or heredocs; do those in Python.\n\nDo not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n\n`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working. Run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n\nImportant: do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.\n\nUse Python for reading, searching, and editing files \u2014 it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.\n\nEach `bash()` call is its own process, so shell state does not persist between calls; use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls.\n\nPython state in the kernel persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.\n\nContinual harness state is available as `rlm.harness` and `rlm.get_harness_state()`. CRUD calls are local to this Prime Agent session by default: `rlm.harness.create_memory(...)`, `rlm.harness.update_memory(...)`, `rlm.harness.delete_memory(...)`, `rlm.harness.create_skill(...)`, `rlm.harness.update_skill(...)`, `rlm.harness.delete_skill(...)`, `rlm.harness.create_subagent(...)`, `rlm.harness.update_subagent(...)`, `rlm.harness.delete_subagent(...)`, `rlm.harness.create_prompt_note(...)`, `rlm.harness.update_prompt_note(...)`, `rlm.harness.delete_prompt_note(...)`, plus `rlm.harness.record_refinement(...)` and `rlm.harness.overview()`. Use `global_=True` only for stable cross-session lessons; Python reserves `global`, so literal `global=True` is invalid syntax.\n\nTerminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n\nRLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm.spawn('sub-task', name='worker')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm.spawn()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.\n\nTreat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n\n# Delegating to sub-agents\n\nSpawn independent, self-contained work with `handle = await rlm.spawn('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.\nAsk for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.\nUse `await rlm.list_subagents()` after kernel restart or compaction.\nLong-running children can report in-flight status with `await rlm.progress_note(...)`; `rlm.list_subagents()` shows each child's activity, latest progress note, and staleness.\nUse `agent_observe` for bounded transcript inspection.\nFan-in results with `await rlm.collect(targets, timeout_ms=0)`: it returns typed snapshots of direct children (status, answer preview, error) without steering anyone; an explicit timeout blocks only that call until the children settle or the deadline passes.\nLarge child outputs belong in files that you read selectively; `collect` snapshots are previews, not full results.\nDelegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\nPersist genuinely reusable delegation patterns with `await refine.run()`.\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/heartbeats-menu/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/websearch/SKILL.md</location>\n </skill>\n</available_skills>"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "You are a general purpose agent that uses code to solve tasks.\nYou solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.\nWhen you are done, stop calling tools and state your final answer.\n\nFor slow or independently completing work, use a nonblocking control loop: start the work, record its handle or output location, then end your turn. A `bash()` handle left running beyond its creating cell sends a completion follow-up; when it arrives, inspect the saved handle and continue. Reading a finished handle's result first cancels that follow-up.\nWhen delegation is available and useful, assign independent substantive tasks to separate workers. Start independent workers without waiting for each one sequentially, and let them run in parallel.\nDo not keep the turn open by polling with `time.sleep()` or shell `sleep`, and do not replace polling with a long blocking `await`. Await only the short operation needed to start work or inspect a result that is already available; otherwise end the turn.\n\nAs the user-facing root agent, when work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n\nUse simplified technical English by default for user-facing prose.\nPrefer short sentences, common words, and concrete verbs. State one main action or fact per sentence when practical. Use lists for steps or conditions.\nKeep necessary technical terms, names, commands, code, paths, and exact quoted text unchanged. State uncertainty directly.\nTreat this as clarity guidance, not a claim of formal ASD-STE100 compliance. Preserve a user-requested format, tone, terminology, and necessary precision.\n\nWorking directory: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work\nConversation log: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl\nRecursive agent depth: 0\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nInstalled Python skill modules (pre-imported): `refine`, `compact`, `agent_observe`, `attach_image`, `edit`, `agent_message`, `rlm_heartbeat`, `goal`, `websearch`.\nRead each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.\nEach skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.\nFor targeted existing-file edits, prefer the pre-imported async `edit` skill from the REPL: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.\nAgent messaging is restricted to your parent, siblings, and direct children; roots are siblings, and deeper communication relays through the intermediate child.\nAgent observation is restricted to your parent, siblings, and direct children; roots are siblings, and deeper inspection relays through the intermediate child.\n\nFrom a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm.spawn(...)` still creates a child.\n\nAn `rlm` object is already in your global namespace. `await rlm.spawn('sub-task', name='api-reviewer')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.\n`name` is required: choose a stable child name that is unique among siblings.\nA child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.\nUse `await agent_observe.list_agents()` to discover family, including inactive members, and `await rlm.list_subagents()` to recover direct child handles.\nChildren reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.\nUse `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.\nUse `agent_observe` to inspect a child's rollout. Observation is restricted to your parent, siblings, and direct children; relay through the intermediate child for deeper descendants.\nSpawn independent children in separate calls and end your turn instead of awaiting completion. Multiple replies may arrive over multiple turns. Delete a direct child explicitly with `await rlm.delete_subagent(child)` when it is no longer needed.\n\nThe `ipython` tool is a persistent Python REPL \u2014 the agent's long-lived control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Top-level `await` works directly. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.\n\nPython is the orchestration language: use Python for loops, conditionals, parsing, and state. Use `bash()` to invoke programs, not to write shell programs \u2014 no shell loops or heredocs; do those in Python.\n\nDo not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n\n`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working. Run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n\nImportant: do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.\n\nUse Python for reading, searching, and editing files \u2014 it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.\n\nEach `bash()` call is its own process, so shell state does not persist between calls; use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls.\n\nPython state in the kernel persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.\n\nContinual harness state is available as `rlm.harness` and `rlm.get_harness_state()`. CRUD calls are local to this Prime Agent session by default: `rlm.harness.create_memory(...)`, `rlm.harness.update_memory(...)`, `rlm.harness.delete_memory(...)`, `rlm.harness.create_skill(...)`, `rlm.harness.update_skill(...)`, `rlm.harness.delete_skill(...)`, `rlm.harness.create_subagent(...)`, `rlm.harness.update_subagent(...)`, `rlm.harness.delete_subagent(...)`, `rlm.harness.create_prompt_note(...)`, `rlm.harness.update_prompt_note(...)`, `rlm.harness.delete_prompt_note(...)`, plus `rlm.harness.record_refinement(...)` and `rlm.harness.overview()`. Use `global_=True` only for stable cross-session lessons; Python reserves `global`, so literal `global=True` is invalid syntax.\n\nTerminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n\nRLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm.spawn('sub-task', name='worker')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm.spawn()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.\n\nTreat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n\n# Delegating to sub-agents\n\nSpawn independent, self-contained work with `handle = await rlm.spawn('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.\nAsk for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.\nUse `await rlm.list_subagents()` after kernel restart or compaction.\nLong-running children can report in-flight status with `await rlm.progress_note(...)`; `rlm.list_subagents()` shows each child's activity, latest progress note, and staleness.\nUse `agent_observe` for bounded transcript inspection.\nFan-in results with `await rlm.collect(targets, timeout_ms=0)`: it returns typed snapshots of direct children (status, answer preview, error) without steering anyone; an explicit timeout blocks only that call until the children settle or the deadline passes.\nLarge child outputs belong in files that you read selectively; `collect` snapshots are previews, not full results.\nDelegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\nPersist genuinely reusable delegation patterns with `await refine.run()`.\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/heartbeats-menu/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/websearch/SKILL.md</location>\n </skill>\n</available_skills>"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}, {"role": "assistant", "content": "heartbeats verifier seed reply"}, {"role": "user", "content": [{"type": "text", "text": "create the agent heartbeat"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "qwen/qwen3-30b-a3b-instruct-2507", "messages": [{"role": "system", "content": "You generate a status line for an AI coding agent dashboard. You are given the recent conversation between a user and the agent, plus whether the agent is currently working or idle.\n\nOutput ONLY these two tags, nothing before, between, or after. Do not think out loud, explain, or count words.\n<recap>a present-tense clause, at most 12 words, saying what the agent is doing or just did, no trailing period</recap>\n<status>one of NEEDS_INPUT, COMPLETED</status>\n\nSTATUS meaning:\n- COMPLETED: the agent finished its turn AND the user's request is fully done with nothing left.\n- NEEDS_INPUT: the agent finished its turn but the task is not fully done \u2014 it asked a question, hit a blocker, or needs more prompting.\nWhen you are unsure between COMPLETED and NEEDS_INPUT, choose NEEDS_INPUT.\n\nExample:\n<recap>Refactoring the auth middleware and updating its tests</recap>\n<status>NEEDS_INPUT</status>"}, {"role": "user", "content": [{"type": "text", "text": "<agent-state>working</agent-state>\n<conversation>\ncustom: [harness-digest] The persistent memories produced across this session so far: <harness_state> # Continual Harness State Local continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions. The continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters. Default to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual ha\u2026\nuser: verifier seed turn\nassistant: heartbeats verifier seed reply\nuser: create the agent heartbeat\n</conversation>"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 400}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "You are a general purpose agent that uses code to solve tasks.\nYou solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.\nWhen you are done, stop calling tools and state your final answer.\n\nFor slow or independently completing work, use a nonblocking control loop: start the work, record its handle or output location, then end your turn. A `bash()` handle left running beyond its creating cell sends a completion follow-up; when it arrives, inspect the saved handle and continue. Reading a finished handle's result first cancels that follow-up.\nWhen delegation is available and useful, assign independent substantive tasks to separate workers. Start independent workers without waiting for each one sequentially, and let them run in parallel.\nDo not keep the turn open by polling with `time.sleep()` or shell `sleep`, and do not replace polling with a long blocking `await`. Await only the short operation needed to start work or inspect a result that is already available; otherwise end the turn.\n\nAs the user-facing root agent, when work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n\nUse simplified technical English by default for user-facing prose.\nPrefer short sentences, common words, and concrete verbs. State one main action or fact per sentence when practical. Use lists for steps or conditions.\nKeep necessary technical terms, names, commands, code, paths, and exact quoted text unchanged. State uncertainty directly.\nTreat this as clarity guidance, not a claim of formal ASD-STE100 compliance. Preserve a user-requested format, tone, terminology, and necessary precision.\n\nWorking directory: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/work\nConversation log: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T165945Z/ts/agent/sessions/01a0c4e8-d25e-77ef-8f2d-a807e9add380.jsonl\nRecursive agent depth: 0\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nInstalled Python skill modules (pre-imported): `refine`, `compact`, `agent_observe`, `attach_image`, `edit`, `agent_message`, `rlm_heartbeat`, `goal`, `websearch`.\nRead each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.\nEach skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.\nFor targeted existing-file edits, prefer the pre-imported async `edit` skill from the REPL: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.\nAgent messaging is restricted to your parent, siblings, and direct children; roots are siblings, and deeper communication relays through the intermediate child.\nAgent observation is restricted to your parent, siblings, and direct children; roots are siblings, and deeper inspection relays through the intermediate child.\n\nFrom a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm.spawn(...)` still creates a child.\n\nAn `rlm` object is already in your global namespace. `await rlm.spawn('sub-task', name='api-reviewer')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.\n`name` is required: choose a stable child name that is unique among siblings.\nA child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.\nUse `await agent_observe.list_agents()` to discover family, including inactive members, and `await rlm.list_subagents()` to recover direct child handles.\nChildren reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.\nUse `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.\nUse `agent_observe` to inspect a child's rollout. Observation is restricted to your parent, siblings, and direct children; relay through the intermediate child for deeper descendants.\nSpawn independent children in separate calls and end your turn instead of awaiting completion. Multiple replies may arrive over multiple turns. Delete a direct child explicitly with `await rlm.delete_subagent(child)` when it is no longer needed.\n\nThe `ipython` tool is a persistent Python REPL \u2014 the agent's long-lived control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Top-level `await` works directly. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.\n\nPython is the orchestration language: use Python for loops, conditionals, parsing, and state. Use `bash()` to invoke programs, not to write shell programs \u2014 no shell loops or heredocs; do those in Python.\n\nDo not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n\n`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working. Run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n\nImportant: do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.\n\nUse Python for reading, searching, and editing files \u2014 it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.\n\nEach `bash()` call is its own process, so shell state does not persist between calls; use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls.\n\nPython state in the kernel persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.\n\nContinual harness state is available as `rlm.harness` and `rlm.get_harness_state()`. CRUD calls are local to this Prime Agent session by default: `rlm.harness.create_memory(...)`, `rlm.harness.update_memory(...)`, `rlm.harness.delete_memory(...)`, `rlm.harness.create_skill(...)`, `rlm.harness.update_skill(...)`, `rlm.harness.delete_skill(...)`, `rlm.harness.create_subagent(...)`, `rlm.harness.update_subagent(...)`, `rlm.harness.delete_subagent(...)`, `rlm.harness.create_prompt_note(...)`, `rlm.harness.update_prompt_note(...)`, `rlm.harness.delete_prompt_note(...)`, plus `rlm.harness.record_refinement(...)` and `rlm.harness.overview()`. Use `global_=True` only for stable cross-session lessons; Python reserves `global`, so literal `global=True` is invalid syntax.\n\nTerminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n\nRLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm.spawn('sub-task', name='worker')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm.spawn()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.\n\nTreat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n\n# Delegating to sub-agents\n\nSpawn independent, self-contained work with `handle = await rlm.spawn('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.\nAsk for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.\nUse `await rlm.list_subagents()` after kernel restart or compaction.\nLong-running children can report in-flight status with `await rlm.progress_note(...)`; `rlm.list_subagents()` shows each child's activity, latest progress note, and staleness.\nUse `agent_observe` for bounded transcript inspection.\nFan-in results with `await rlm.collect(targets, timeout_ms=0)`: it returns typed snapshots of direct children (status, answer preview, error) without steering anyone; an explicit timeout blocks only that call until the children settle or the deadline passes.\nLarge child outputs belong in files that you read selectively; `collect` snapshots are previews, not full results.\nDelegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\nPersist genuinely reusable delegation patterns with `await refine.run()`.\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/heartbeats-menu/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/websearch/SKILL.md</location>\n </skill>\n</available_skills>"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}, {"role": "assistant", "content": "heartbeats verifier seed reply"}, {"role": "user", "content": [{"type": "text", "text": "create the agent heartbeat"}]}, {"role": "assistant", "content": null, "tool_calls": [{"id": "call_battery_1", "type": "function", "function": {"name": "ipython", "arguments": "{\"code\":\"import rlm_heartbeat\\nawait rlm_heartbeat.create(\\n 'agent heartbeat check instruction',\\n interval='every 30m',\\n label='agent hb',\\n)\\nprint('created')\"}"}}]}, {"role": "tool", "content": "created\n", "tool_call_id": "call_battery_1"}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "qwen/qwen3-30b-a3b-instruct-2507", "messages": [{"role": "system", "content": "You generate a status line for an AI coding agent dashboard. You are given the recent conversation between a user and the agent, plus whether the agent is currently working or idle.\n\nOutput ONLY these two tags, nothing before, between, or after. Do not think out loud, explain, or count words.\n<recap>a present-tense clause, at most 12 words, saying what the agent is doing or just did, no trailing period</recap>\n<status>one of NEEDS_INPUT, COMPLETED</status>\n\nSTATUS meaning:\n- COMPLETED: the agent finished its turn AND the user's request is fully done with nothing left.\n- NEEDS_INPUT: the agent finished its turn but the task is not fully done \u2014 it asked a question, hit a blocker, or needs more prompting.\nWhen you are unsure between COMPLETED and NEEDS_INPUT, choose NEEDS_INPUT.\n\nExample:\n<recap>Refactoring the auth middleware and updating its tests</recap>\n<status>NEEDS_INPUT</status>"}, {"role": "user", "content": [{"type": "text", "text": "<agent-state>idle (finished its turn)</agent-state>\n<conversation>\ncustom: [harness-digest] The persistent memories produced across this session so far: <harness_state> # Continual Harness State Local continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions. The continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters. Default to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual ha\u2026\nuser: verifier seed turn\nassistant: heartbeats verifier seed reply\nuser: create the agent heartbeat\ntoolResult: created\nassistant: agent heartbeat created\n</conversation>"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 400}, "auth": "Bearer sk-battery", "queue": "default"}diff --git a/scripts/heartbeats-runs/20260921T170018Z/findings.json b/scripts/heartbeats-runs/20260921T170018Z/findings.jsondeleted file mode 100644index 184d877861..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/findings.json+++ /dev/null@@ -1,62 +0,0 @@-[- {- "side": "ts",- "ok": true,- "summary": "seed turn ran",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "user heartbeat set through the wire",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "agent heartbeat turn ran",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "wire catalog lists the user and agent heartbeat",- "evidence": "02-wire-catalog.json"- },- {- "side": "ts",- "ok": true,- "summary": "/heartbeats renders the list with both heartbeats",- "evidence": "04-opened.txt"- },- {- "side": "ts",- "ok": true,- "summary": "down navigates to the agent heartbeat and enter opens the TS action pane",- "evidence": "06-actions.txt"- },- {- "side": "ts",- "ok": true,- "summary": "applying the action returns to the list with the paused status",- "evidence": "07-applied.txt"- },- {- "side": "ts",- "ok": true,- "summary": "the pause reached the daemon catalog",- "evidence": "08-applied-catalog.json"- },- {- "side": "ts",- "ok": true,- "summary": "escape closes the view (the transcript returns)",- "evidence": "09-closed.txt"- },- {- "side": "ts",- "ok": true,- "summary": "the tray heartbeat label renders after close",- "evidence": "09-closed.txt"- }-]\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/00-heartbeat-set.json b/scripts/heartbeats-runs/20260921T170018Z/ts/00-heartbeat-set.jsondeleted file mode 100644index ed375e6c27..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/00-heartbeat-set.json+++ /dev/null@@ -1,29 +0,0 @@-{- "id": "hb-set",- "type": "response",- "command": "heartbeat_set",- "success": true,- "data": {- "heartbeat": {- "id": "a1edc23e-9974-4201-a0d6-3f7595b1f368",- "status": "active",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "b6d528dd888d",- "sessionId": "01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T17:00:19.285Z",- "updatedAt": "2026-09-21T17:00:19.285Z",- "nextRunAt": "2026-09-21T17:30:19.285Z",- "runCount": 0- }- }-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/01-agent-heartbeat-turn.json b/scripts/heartbeats-runs/20260921T170018Z/ts/01-agent-heartbeat-turn.jsondeleted file mode 100644index 48b023caab..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/01-agent-heartbeat-turn.json+++ /dev/null@@ -1,6 +0,0 @@-{- "id": "hb-agent",- "type": "response",- "command": "prompt_and_wait",- "success": true-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/02-wire-catalog.json b/scripts/heartbeats-runs/20260921T170018Z/ts/02-wire-catalog.jsondeleted file mode 100644index 72e45e6801..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/02-wire-catalog.json+++ /dev/null@@ -1,53 +0,0 @@-[- {- "job": {- "id": "a1edc23e-9974-4201-a0d6-3f7595b1f368",- "status": "active",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "b6d528dd888d",- "sessionId": "01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T17:00:19.285Z",- "updatedAt": "2026-09-21T17:00:19.285Z",- "nextRunAt": "2026-09-21T17:30:19.285Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- },- {- "job": {- "id": "6bf0e7f4-9e82-48bb-bcea-b318427ea501",- "status": "active",- "source": "rlm_heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "b6d528dd888d",- "sessionId": "01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work",- "label": "agent hb",- "prompt": "agent heartbeat check instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T17:00:25.401Z",- "updatedAt": "2026-09-21T17:00:25.401Z",- "nextRunAt": "2026-09-21T17:30:25.401Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- }-]\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/03-attached.txt b/scripts/heartbeats-runs/20260921T170018Z/ts/03-attached.txtdeleted file mode 100644index 4f570accca..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/03-attached.txt+++ /dev/null@@ -1,36 +0,0 @@- heartbeats-verifier $0.00-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent v0.9.5- ▗█▛ ▟██▙▄██▛ ▟▛ model mock-1- ▗▟▌ ▐███▛▘▗▄█▖ cwd ~/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--- verifier seed turn--- heartbeats verifier seed reply--- create the agent heartbeat--- ✓ python · await rlm_heartbeat.create( · ↑ 7 ↓ 1 lines · 9ms-- agent heartbeat created--------- Collapsed mode (Ctrl+O to expand)-- >--← manage 2 heartbeats (Ctrl+R) · mock-1 · 110 (0%)diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/04-opened.txt b/scripts/heartbeats-runs/20260921T170018Z/ts/04-opened.txtdeleted file mode 100644index e964b13bad..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/04-opened.txt+++ /dev/null@@ -1,36 +0,0 @@------------- Heartbeats- 2 heartbeats. Select a heartbeat to manage.--- user heartbeat ping instruction active- Created by you · heartbeats-verifier · every 30m · steer-- agent hb active- Created by agent · heartbeats-verifier · every 30m · steer--- Esc close------------diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/05-navigated.txt b/scripts/heartbeats-runs/20260921T170018Z/ts/05-navigated.txtdeleted file mode 100644index e964b13bad..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/05-navigated.txt+++ /dev/null@@ -1,36 +0,0 @@------------- Heartbeats- 2 heartbeats. Select a heartbeat to manage.--- user heartbeat ping instruction active- Created by you · heartbeats-verifier · every 30m · steer-- agent hb active- Created by agent · heartbeats-verifier · every 30m · steer--- Esc close------------diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/06-actions.txt b/scripts/heartbeats-runs/20260921T170018Z/ts/06-actions.txtdeleted file mode 100644index dc0a1fcfcf..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/06-actions.txt+++ /dev/null@@ -1,36 +0,0 @@------------ agent hb- agent heartbeat check instruction-- Created by agent · heartbeats-verifier · active · every 30m · ste...--- Pause heartbeat- Stop deliveries until resumed-- Stop heartbeat- Permanently remove this heartbeat--- ← back Esc close-----------diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/07-applied.txt b/scripts/heartbeats-runs/20260921T170018Z/ts/07-applied.txtdeleted file mode 100644index 69297f1119..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/07-applied.txt+++ /dev/null@@ -1,36 +0,0 @@------------- Heartbeats- 2 heartbeats · 1 paused. Select a heartbeat to manage.--- user heartbeat ping instruction active- Created by you · heartbeats-verifier · every 30m · steer-- agent hb paused- Created by agent · heartbeats-verifier · every 30m · steer--- Esc close------------diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/08-applied-catalog.json b/scripts/heartbeats-runs/20260921T170018Z/ts/08-applied-catalog.jsondeleted file mode 100644index 9ec794da74..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/08-applied-catalog.json+++ /dev/null@@ -1,52 +0,0 @@-[- {- "job": {- "id": "a1edc23e-9974-4201-a0d6-3f7595b1f368",- "status": "active",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "b6d528dd888d",- "sessionId": "01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T17:00:19.285Z",- "updatedAt": "2026-09-21T17:00:19.285Z",- "nextRunAt": "2026-09-21T17:30:19.285Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- },- {- "job": {- "id": "6bf0e7f4-9e82-48bb-bcea-b318427ea501",- "status": "paused",- "source": "rlm_heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "b6d528dd888d",- "sessionId": "01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work",- "label": "agent hb",- "prompt": "agent heartbeat check instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T17:00:25.401Z",- "updatedAt": "2026-09-21T17:00:33.077Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- }-]\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/09-closed.txt b/scripts/heartbeats-runs/20260921T170018Z/ts/09-closed.txtdeleted file mode 100644index 383ce9ff23..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/09-closed.txt+++ /dev/null@@ -1,36 +0,0 @@- heartbeats-verifier $0.00-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent v0.9.5- ▗█▛ ▟██▙▄██▛ ▟▛ model mock-1- ▗▟▌ ▐███▛▘▗▄█▖ cwd ~/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--- verifier seed turn--- heartbeats verifier seed reply--- create the agent heartbeat--- ✓ python · await rlm_heartbeat.create( · ↑ 7 ↓ 1 lines · 9ms-- agent heartbeat created--------- Collapsed mode (Ctrl+O to expand)-- >--← manage 2 heartbeats · 1 paused (Ctrl+R) · mock-1 · 110 (0%)diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/auth.json b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/auth.jsondeleted file mode 100644index 9e26dfeeb6..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/auth.json+++ /dev/null@@ -1 +0,0 @@-{}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/bin/fd b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/bin/fddeleted file mode 100755index 57405df9ea..0000000000Binary files a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/bin/fd and /dev/null differdiff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/daemon-workers/ea916b05d16e/command-journal.jsonl b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/daemon-workers/ea916b05d16e/command-journal.jsonldeleted file mode 100644index 5032e8142c..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/daemon-workers/ea916b05d16e/command-journal.jsonl+++ /dev/null@@ -1,13 +0,0 @@-{"version":1,"type":"received","key":"[\"c99873d70bbe\",\"hb-create\"]","clientId":"c99873d70bbe","commandId":"hb-create","commandType":"create","recordedAt":"2026-09-21T17:00:18.789Z"}-{"version":1,"type":"result","key":"[\"c99873d70bbe\",\"hb-create\"]","response":{"id":"hb-create","type":"response","command":"create","success":true,"data":{"id":"b6d528dd888d","lifecycle":"draft","activity":"idle","isSessionActive":false,"lastActivityAt":"2026-09-21T17:00:19.162Z","runtimeKind":"top-level","rlmDepth":0,"activeSessionId":"b6d528dd888d","sessionId":"01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766","sessionFile":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl","sessionName":"heartbeats-verifier","cwd":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work","model":{"id":"mock-1","name":"Mock 1","api":"openai-completions","provider":"prime-inference","baseUrl":"http://127.0.0.1:38729/v1","reasoning":false,"input":["text"],"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0},"contextWindow":128000,"maxTokens":4096},"thinkingLevel":"off","isStreaming":false,"isCompacting":false,"isBashRunning":false,"hasRunningRlmChildren":false,"isRunningTools":false,"attachedClients":0,"messageCount":0,"unfinishedActionCount":0,"created":"2026-09-21T17:00:19.101Z","modified":"2026-09-21T17:00:19.162Z","sessionActions":{"queuedCount":0,"steering":[],"followUps":[]},"rosterStatus":"idle","workerState":"ready","workerPid":2313177}},"recordedAt":"2026-09-21T17:00:19.178Z"}-{"version":1,"type":"received","key":"[\"c99873d70bbe\",\"hb-seed\"]","clientId":"c99873d70bbe","commandId":"hb-seed","commandType":"prompt_and_wait","recordedAt":"2026-09-21T17:00:19.182Z"}-{"version":1,"type":"result","key":"[\"c99873d70bbe\",\"hb-seed\"]","response":{"id":"hb-seed","type":"response","command":"prompt_and_wait","success":true},"recordedAt":"2026-09-21T17:00:19.281Z"}-{"version":1,"type":"received","key":"[\"c99873d70bbe\",\"hb-set\"]","clientId":"c99873d70bbe","commandId":"hb-set","commandType":"heartbeat_set","recordedAt":"2026-09-21T17:00:19.283Z"}-{"version":1,"type":"result","key":"[\"c99873d70bbe\",\"hb-set\"]","response":{"id":"hb-set","type":"response","command":"heartbeat_set","success":true,"data":{"heartbeat":{"id":"a1edc23e-9974-4201-a0d6-3f7595b1f368","status":"active","source":"heartbeat","runtimeKind":"top-level","deliveryMode":"steer","activeSessionId":"b6d528dd888d","sessionId":"01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766","sessionFile":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl","cwd":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work","prompt":"user heartbeat ping instruction","schedule":{"kind":"interval","expression":"every 30m","intervalMs":1800000},"createdAt":"2026-09-21T17:00:19.285Z","updatedAt":"2026-09-21T17:00:19.285Z","nextRunAt":"2026-09-21T17:30:19.285Z","runCount":0}}},"recordedAt":"2026-09-21T17:00:19.289Z"}-{"version":1,"type":"received","key":"[\"c99873d70bbe\",\"hb-agent\"]","clientId":"c99873d70bbe","commandId":"hb-agent","commandType":"prompt_and_wait","recordedAt":"2026-09-21T17:00:19.291Z"}-{"version":1,"type":"result","key":"[\"c99873d70bbe\",\"hb-agent\"]","response":{"id":"hb-agent","type":"response","command":"prompt_and_wait","success":true},"recordedAt":"2026-09-21T17:00:25.451Z"}-{"version":1,"type":"received","key":"[\"daemon-client:f9b2b3c2-d9f9-47d5-90ca-700bcc39edeb\",\"daemon_6\"]","clientId":"daemon-client:f9b2b3c2-d9f9-47d5-90ca-700bcc39edeb","commandId":"daemon_6","commandType":"heartbeat_manage","recordedAt":"2026-09-21T17:00:33.072Z"}-{"version":1,"type":"result","key":"[\"daemon-client:f9b2b3c2-d9f9-47d5-90ca-700bcc39edeb\",\"daemon_6\"]","response":{"id":"daemon_6","type":"response","command":"heartbeat_manage","success":true,"data":{"heartbeat":{"id":"6bf0e7f4-9e82-48bb-bcea-b318427ea501","status":"paused","source":"rlm_heartbeat","runtimeKind":"top-level","deliveryMode":"steer","activeSessionId":"b6d528dd888d","sessionId":"01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766","sessionFile":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl","cwd":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work","label":"agent hb","prompt":"agent heartbeat check instruction","schedule":{"kind":"interval","expression":"every 30m","intervalMs":1800000},"createdAt":"2026-09-21T17:00:25.401Z","updatedAt":"2026-09-21T17:00:33.077Z","runCount":0}}},"recordedAt":"2026-09-21T17:00:33.082Z"}-{"version":1,"type":"acknowledged","key":"[\"daemon-client:f9b2b3c2-d9f9-47d5-90ca-700bcc39edeb\",\"daemon_6\"]","recordedAt":"2026-09-21T17:00:33.084Z"}-{"version":1,"type":"received","key":"[\"19bef912edab\",\"sd\"]","clientId":"19bef912edab","commandId":"sd","commandType":"shutdown","recordedAt":"2026-09-21T17:00:36.680Z"}-{"version":1,"type":"result","key":"[\"19bef912edab\",\"sd\"]","response":{"id":"sd","type":"response","command":"shutdown","success":true},"recordedAt":"2026-09-21T17:00:36.683Z"}diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/logs/agent.jsonl b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/logs/agent.jsonldeleted file mode 100644index 75088b2b60..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/logs/agent.jsonl+++ /dev/null@@ -1,5 +0,0 @@-{"socketPath":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/daemon.sock","ts":"2026-09-21T17:00:18.787Z","level":"warn","component":"coding-agent.daemon-supervisor","msg":"Prime Agent daemon supervisor 843b8930-0f22-4aa9-8f73-f4fcff982ec6 listening on /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/daemon.sock","pid":2313149,"mode":"daemon"}-{"socketPath":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/daemon.sock","ts":"2026-09-21T17:00:19.097Z","level":"warn","component":"coding-agent.daemon-supervisor","msg":"Session worker 3fd83c79e6a7 stderr: Prime Agent daemon listening on /tmp/hbv20260921T170018Z-ts/prime-agent-1000/worker-ea916b05d16e-3fd83c79e6a7.sock","pid":2313149,"mode":"daemon"}-{"socketPath":"/tmp/hbv20260921T170018Z-ts/prime-agent-1000/worker-ea916b05d16e-3fd83c79e6a7.sock","ts":"2026-09-21T17:00:19.097Z","level":"warn","component":"coding-agent.daemon","msg":"Prime Agent daemon listening on /tmp/hbv20260921T170018Z-ts/prime-agent-1000/worker-ea916b05d16e-3fd83c79e6a7.sock","pid":2313177,"mode":"daemon"}-{"socketPath":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/daemon.sock","ts":"2026-09-21T17:00:36.917Z","level":"warn","component":"coding-agent.daemon-supervisor","msg":"Session worker 3fd83c79e6a7 stderr: shutting down (exit 0); closing 0 active session(s)","pid":2313149,"mode":"daemon"}-{"socketPath":"/tmp/hbv20260921T170018Z-ts/prime-agent-1000/worker-ea916b05d16e-3fd83c79e6a7.sock","ts":"2026-09-21T17:00:36.917Z","level":"warn","component":"coding-agent.daemon","msg":"shutting down (exit 0); closing 0 active session(s)","pid":2313177,"mode":"daemon"}diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/logs/daemon.sock.ea916b05.log b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/logs/daemon.sock.ea916b05.logdeleted file mode 100644index 3a29518e71..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/logs/daemon.sock.ea916b05.log+++ /dev/null@@ -1,3 +0,0 @@-[2026-09-21T17:00:18.787Z] supervisor: Prime Agent daemon supervisor 843b8930-0f22-4aa9-8f73-f4fcff982ec6 listening on /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/daemon.sock-[2026-09-21T17:00:19.097Z] supervisor: Session worker 3fd83c79e6a7 stderr: Prime Agent daemon listening on /tmp/hbv20260921T170018Z-ts/prime-agent-1000/worker-ea916b05d16e-3fd83c79e6a7.sock-[2026-09-21T17:00:36.917Z] supervisor: Session worker 3fd83c79e6a7 stderr: shutting down (exit 0); closing 0 active session(s)diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/logs/worker-ea916b05d16e-3fd83c79e6a7.sock.43ec0f56.log b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/logs/worker-ea916b05d16e-3fd83c79e6a7.sock.43ec0f56.logdeleted file mode 100644index c4f60623d9..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/logs/worker-ea916b05d16e-3fd83c79e6a7.sock.43ec0f56.log+++ /dev/null@@ -1,2 +0,0 @@-[2026-09-21T17:00:19.097Z] Prime Agent daemon listening on /tmp/hbv20260921T170018Z-ts/prime-agent-1000/worker-ea916b05d16e-3fd83c79e6a7.sock-[2026-09-21T17:00:36.917Z] shutting down (exit 0); closing 0 active session(s)diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/models.json b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/models.jsondeleted file mode 100644index 1d8e7bc36f..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/models.json+++ /dev/null@@ -1,19 +0,0 @@-{- "providers": {- "prime-inference": {- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:38729/v1",- "apiKey": "sk-battery",- "models": [- {- "id": "mock-1",- "name": "Mock 1",- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:38729/v1",- "contextWindow": 128000,- "maxTokens": 4096- }- ]- }- }-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/prime-inference-models-cache.json b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/prime-inference-models-cache.jsondeleted file mode 100644index 7974b2aeb7..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/prime-inference-models-cache.json+++ /dev/null@@ -1 +0,0 @@-{"object":"list","data":[{"id":"alibaba/qwen3.5-flash","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.568539+00:00"},"specs":null},{"id":"alibaba/qwen3.7-max","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":3.75,"output_usd_per_mtok":11.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.639598+00:00"},"specs":null},{"id":"alibaba/qwen3.7-plus","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.717208+00:00"},"specs":null},{"id":"alibaba/qwen3.8-flash","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.225,"output_usd_per_mtok":0.705,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.787469+00:00"},"specs":null},{"id":"anthropic/claude-fable-5","object":"model","owned_by":"","created":1783031626,"display_name":"Claude Fable 5","pricing":{"input_usd_per_mtok":10,"output_usd_per_mtok":50,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-02T22:33:46.495072+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-fable-5.1","object":"model","owned_by":"","created":1788556514,"display_name":"Claude Fable 5.1","pricing":{"input_usd_per_mtok":10,"output_usd_per_mtok":50,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.113341+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-haiku-4.5","object":"model","owned_by":"","created":1761030860,"display_name":"Claude Haiku 4.5","pricing":{"input_usd_per_mtok":1,"output_usd_per_mtok":5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:20.826034+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-opus-4.1","object":"model","owned_by":"","created":1761157329,"display_name":"Claude Opus 4.1","pricing":{"input_usd_per_mtok":15,"output_usd_per_mtok":75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-22T18:22:09.605939+00:00"},"specs":{"context_window":200000,"max_output_tokens":32000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-opus-4.5","object":"model","owned_by":"","created":1764746904,"display_name":"Claude Opus 4.5","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-03T07:28:24.760458+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","verbosity"]},{"id":"anthropic/claude-opus-4.6","object":"model","owned_by":"","created":1772938679,"display_name":"Claude Opus 4.6","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-08T02:57:59.615639+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p","verbosity"]},{"id":"anthropic/claude-opus-4.7","object":"model","owned_by":"","created":1776679634,"display_name":"Claude Opus 4.7","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-20T10:07:14.028142+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-opus-4.8","object":"model","owned_by":"","created":1780660082,"display_name":"Claude Opus 4.8","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-05T11:48:02.246650+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-opus-5","object":"model","owned_by":"","created":1784919442,"display_name":"Claude Opus 5","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-24T18:57:22.868734+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-sonnet-4","object":"model","owned_by":"","created":1761029716,"display_name":"Claude Sonnet 4","pricing":{"input_usd_per_mtok":3,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:16.611551+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-sonnet-4.5","object":"model","owned_by":"","created":1759212031,"display_name":"Claude Sonnet 4.5","pricing":{"input_usd_per_mtok":3,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T06:00:31.866675+00:00"},"specs":{"context_window":1000000,"max_output_tokens":64000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-sonnet-4.6","object":"model","owned_by":"","created":1772054770,"display_name":"Claude Sonnet 4.6","pricing":{"input_usd_per_mtok":3,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:10.104879+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","medium","low"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p","verbosity"]},{"id":"anthropic/claude-sonnet-5","object":"model","owned_by":"","created":1783031448,"display_name":"Claude Sonnet 5","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-02T22:30:48.220566+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"deepseek/deepseek-chat-v3.1","object":"model","owned_by":"","created":1761029725,"display_name":"DeepSeek V3.1","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":1.7,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:25.583563+00:00"},"specs":{"context_window":163840,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v3.1-terminus","object":"model","owned_by":"","created":1759198118,"display_name":"DeepSeek V3.1 Terminus","pricing":{"input_usd_per_mtok":0.27,"output_usd_per_mtok":1,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:08:38.000459+00:00"},"specs":{"context_window":163840,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"deepseek/deepseek-v3.2","object":"model","owned_by":"","created":1764658428,"display_name":"DeepSeek V3.2","pricing":{"input_usd_per_mtok":0.3705,"output_usd_per_mtok":1.1115,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-02T06:53:48.223623+00:00"},"specs":{"context_window":163840,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":false,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v3.2-exp","object":"model","owned_by":"","created":1759198146,"display_name":"DeepSeek V3.2 Exp","pricing":{"input_usd_per_mtok":0.27,"output_usd_per_mtok":0.41,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:09:06.170541+00:00"},"specs":{"context_window":163840,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4.1-flash","object":"model","owned_by":"","created":1789152253,"display_name":"DeepSeek V4.1 Flash","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-11T18:44:13.104931+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-flash","object":"model","owned_by":"","created":1778785963,"display_name":"DeepSeek V4 Flash 0423","pricing":{"input_usd_per_mtok":0.44,"output_usd_per_mtok":1.32,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T19:12:43.449839+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_completion_tokens","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-flash-0731","object":"model","owned_by":"","created":1785777617,"display_name":"DeepSeek V4 Flash 0731","pricing":{"input_usd_per_mtok":0.44,"output_usd_per_mtok":1.32,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T17:20:17.849313+00:00"},"specs":{"context_window":1310720,"max_output_tokens":943718,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-pro","object":"model","owned_by":"","created":1778785932,"display_name":"DeepSeek V4 Pro 0423","pricing":{"input_usd_per_mtok":1.91,"output_usd_per_mtok":3.83,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T19:12:12.010236+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_completion_tokens","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"google/gemini-2.5-flash","object":"model","owned_by":"","created":1761029715,"display_name":"Gemini 2.5 Flash","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":2.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:15.585176+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65535,"modalities":{"input":["file","image","text","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-2.5-flash-lite","object":"model","owned_by":"","created":1761029721,"display_name":"Gemini 2.5 Flash Lite","pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:21.403298+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65535,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-2.5-pro","object":"model","owned_by":"","created":1761029717,"display_name":"Gemini 2.5 Pro","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:17.621295+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.1-pro-preview","object":"model","owned_by":"","created":1772054806,"display_name":"Gemini 3.1 Pro Preview","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":12,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:46.169413+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["audio","file","image","text","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.5-flash","object":"model","owned_by":"","created":1781958981,"display_name":"Gemini 3.5 Flash","pricing":{"input_usd_per_mtok":1.5,"output_usd_per_mtok":9,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-20T12:36:21.024091+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.6-flash","object":"model","owned_by":"","created":1784918138,"display_name":"Gemini 3.6 Flash","pricing":{"input_usd_per_mtok":1.5,"output_usd_per_mtok":7.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-24T18:35:38.706927+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.7-flash","object":"model","owned_by":"","created":1787848124,"display_name":"Gemini 3.7 Flash","pricing":{"input_usd_per_mtok":1.35,"output_usd_per_mtok":6.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-27T16:28:44.601830+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.8-flash","object":"model","owned_by":"","created":1788556514,"display_name":"Gemini 3.8 Flash","pricing":{"input_usd_per_mtok":0.75,"output_usd_per_mtok":3.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.212597+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3-flash-preview","object":"model","owned_by":"","created":1766202374,"display_name":"Gemini 3 Flash Preview","pricing":{"input_usd_per_mtok":0.5,"output_usd_per_mtok":3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-20T03:46:14.305378+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemma-3-27b-it","object":"model","owned_by":"","created":1761030851,"display_name":"Gemma 3 27B","pricing":{"input_usd_per_mtok":0.119,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:11.952792+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"meta-llama/Llama-3.2-1B-Instruct","object":"model","owned_by":"","created":1771939296,"display_name":"Llama 3.2 1B Instruct","pricing":{"input_usd_per_mtok":0.027,"output_usd_per_mtok":0.201,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T13:21:36.921319+00:00"},"specs":{"context_window":60000,"max_output_tokens":54000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","max_tokens","min_p","presence_penalty","repetition_penalty","seed","stop","temperature","top_k","top_p"]},{"id":"meta-llama/Llama-3.2-3B-Instruct","object":"model","owned_by":"","created":1771939312,"display_name":"Llama 3.2 3B Instruct","pricing":{"input_usd_per_mtok":0.0509,"output_usd_per_mtok":0.335,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T13:21:52.649872+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","seed","stop","structured_outputs","temperature","top_k","top_logprobs","top_p"]},{"id":"meta-llama/llama-3.3-70b-instruct","object":"model","owned_by":"","created":1759196298,"display_name":"Llama 3.3 70B Instruct","pricing":{"input_usd_per_mtok":1.04,"output_usd_per_mtok":2.253,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T01:38:18.545960+00:00"},"specs":{"context_window":131072,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"meta-llama/llama-4-maverick","object":"model","owned_by":"","created":1761030850,"display_name":"Llama 4 Maverick","pricing":{"input_usd_per_mtok":0.35,"output_usd_per_mtok":1.15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:10.101027+00:00"},"specs":{"context_window":1048576,"max_output_tokens":16384,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m2.5","object":"model","owned_by":"","created":1771374795,"display_name":"MiniMax M2.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-18T00:33:15.739871+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m2.7","object":"model","owned_by":"","created":1775779870,"display_name":"MiniMax M2.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:10.312006+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m3","object":"model","owned_by":"","created":1780311536,"display_name":"MiniMax M3","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-01T10:58:56.335485+00:00"},"specs":{"context_window":1048576,"max_output_tokens":512000,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"mistralai/mistral-large-2512","object":"model","owned_by":"","created":1764689752,"display_name":null,"pricing":{"input_usd_per_mtok":0.5,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-02T15:35:52.296516+00:00"},"specs":null},{"id":"mistralai/mistral-nemo","object":"model","owned_by":"","created":1761030857,"display_name":"Mistral Nemo","pricing":{"input_usd_per_mtok":0.165,"output_usd_per_mtok":0.17,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:17.801302+00:00"},"specs":{"context_window":131072,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"mistralai/mistral-small-2603","object":"model","owned_by":"","created":1775779872,"display_name":"Mistral Small 4","pricing":{"input_usd_per_mtok":0.165,"output_usd_per_mtok":0.66,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:12.604966+00:00"},"specs":{"context_window":262144,"max_output_tokens":209715,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","none"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"mistralai/mixtral-8x22b-instruct","object":"model","owned_by":"","created":1759198003,"display_name":"Mixtral 8x22B Instruct","pricing":{"input_usd_per_mtok":2.2,"output_usd_per_mtok":6.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:06:43.614656+00:00"},"specs":{"context_window":65536,"max_output_tokens":52428,"modalities":{"input":["text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","max_tokens","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"moonshotai/kimi-k2-0905","object":"model","owned_by":"","created":1759907126,"display_name":"Kimi K2 0905","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:26.057085+00:00"},"specs":{"context_window":262144,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"moonshotai/kimi-k2.5","object":"model","owned_by":"","created":1769800671,"display_name":"Kimi K2.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-30T19:17:51.210047+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k2.6","object":"model","owned_by":"","created":1776733288,"display_name":"Kimi K2.6","pricing":{"input_usd_per_mtok":0.95,"output_usd_per_mtok":4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-21T01:01:28.804384+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k2.7-code","object":"model","owned_by":"","created":1781282432,"display_name":"Kimi K2.7 Code","pricing":{"input_usd_per_mtok":1.9,"output_usd_per_mtok":8,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-12T16:40:32.168235+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k3","object":"model","owned_by":"","created":1784248110,"display_name":"Kimi K3","pricing":{"input_usd_per_mtok":3.45,"output_usd_per_mtok":17.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-17T00:28:30.162170+00:00"},"specs":{"context_window":1048576,"max_output_tokens":943718,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"max","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"nvidia/nemotron-3-nano-30b-a3b","object":"model","owned_by":"","created":1775779886,"display_name":"Nemotron 3 Nano 30B A3B","pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.24,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:26.952299+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"openai/gpt-4.1","object":"model","owned_by":"","created":1759401802,"display_name":"GPT-4.1","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":8,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:22.496353+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4.1-mini","object":"model","owned_by":"","created":1759401806,"display_name":"GPT-4.1 Mini","pricing":{"input_usd_per_mtok":0.4,"output_usd_per_mtok":1.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:26.911016+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4.1-nano","object":"model","owned_by":"","created":1759401808,"display_name":"GPT-4.1 Nano","pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:28.011794+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4o","object":"model","owned_by":"","created":1761029734,"display_name":"GPT-4o","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:34.447350+00:00"},"specs":{"context_window":128000,"max_output_tokens":16384,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_completion_tokens","max_tokens","prediction","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p","web_search_options"]},{"id":"openai/gpt-4o-mini","object":"model","owned_by":"","created":1761029722,"display_name":"GPT-4o-mini","pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:22.331052+00:00"},"specs":{"context_window":128000,"max_output_tokens":16384,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_completion_tokens","max_tokens","prediction","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p","web_search_options"]},{"id":"openai/gpt-5","object":"model","owned_by":"","created":1759211784,"display_name":"GPT-5","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T05:56:24.831437+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.1","object":"model","owned_by":"","created":1763426084,"display_name":"GPT-5.1","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-11-18T00:34:44.949671+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","none"],"default_effort":"none","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.2","object":"model","owned_by":"","created":1765611176,"display_name":"GPT-5.2","pricing":{"input_usd_per_mtok":1.75,"output_usd_per_mtok":14,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-13T07:32:56.544785+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.2-pro","object":"model","owned_by":"","created":1765611177,"display_name":"GPT-5.2 Pro","pricing":{"input_usd_per_mtok":21,"output_usd_per_mtok":168,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-13T07:32:57.583455+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.3-codex","object":"model","owned_by":"","created":1772054791,"display_name":"GPT-5.3-Codex","pricing":{"input_usd_per_mtok":1.75,"output_usd_per_mtok":14,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:31.496994+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4","object":"model","owned_by":"","created":1773713673,"display_name":"GPT-5.4","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-17T02:14:33.278960+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-mini","object":"model","owned_by":"","created":1775779863,"display_name":"GPT-5.4 Mini","pricing":{"input_usd_per_mtok":0.75,"output_usd_per_mtok":4.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:03.742760+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-nano","object":"model","owned_by":"","created":1775779866,"display_name":"GPT-5.4 Nano","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:06.153745+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-pro","object":"model","owned_by":"","created":1773713674,"display_name":"GPT-5.4 Pro","pricing":{"input_usd_per_mtok":30,"output_usd_per_mtok":180,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-17T02:14:34.995439+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.5","object":"model","owned_by":"","created":1777306094,"display_name":"GPT-5.5","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":30,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-27T16:08:14.065946+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6","object":"model","owned_by":"","created":1783751214,"display_name":null,"pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":30,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:26:54.495544+00:00"},"specs":null},{"id":"openai/gpt-5.6-luna","object":"model","owned_by":"","created":1783751321,"display_name":"GPT-5.6 Luna","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:41.639902+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-luna-pro","object":"model","owned_by":"","created":1783751322,"display_name":"GPT-5.6 Luna Pro","pricing":{"input_usd_per_mtok":1,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:42.459149+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-sol","object":"model","owned_by":"","created":1783751318,"display_name":"GPT-5.6 Sol","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":30,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:38.262869+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-sol-pro","object":"model","owned_by":"","created":1783751319,"display_name":"GPT-5.6 Sol Pro","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":30,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:39.039507+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-terra","object":"model","owned_by":"","created":1783751319,"display_name":"GPT-5.6 Terra","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:39.851751+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-terra-pro","object":"model","owned_by":"","created":1783751320,"display_name":"GPT-5.6 Terra Pro","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:40.628845+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5-mini","object":"model","owned_by":"","created":1759401800,"display_name":"GPT-5 Mini","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:20.338354+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5-nano","object":"model","owned_by":"","created":1759401801,"display_name":"GPT-5 Nano","pricing":{"input_usd_per_mtok":0.05,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:21.418908+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-6-astra","object":"model","owned_by":"","created":1788556514,"display_name":"GPT-6 Astra","pricing":{"input_usd_per_mtok":10,"output_usd_per_mtok":50,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.299026+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-oss-120b","object":"model","owned_by":"","created":1760042083,"display_name":"gpt-oss-120b","pricing":{"input_usd_per_mtok":0.35,"output_usd_per_mtok":0.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-09T20:34:43.236004+00:00"},"specs":{"context_window":131072,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"openai/gpt-oss-20b","object":"model","owned_by":"","created":1761030856,"display_name":"gpt-oss-20b","pricing":{"input_usd_per_mtok":0.07,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:16.897238+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"poolside/laguna-s-2.1","object":"model","owned_by":"","created":1785726826,"display_name":"Laguna S 2.1","pricing":{"input_usd_per_mtok":0.09,"output_usd_per_mtok":0.18,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T03:13:46.654853+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","temperature","tool_choice","tools"]},{"id":"poolside/laguna-xs-2.1","object":"model","owned_by":"","created":1785726826,"display_name":"Laguna XS 2.1","pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.12,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T03:13:46.740724+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","temperature","tool_choice","tools"]},{"id":"qwen/qwen3-235b-a22b-2507","object":"model","owned_by":"","created":1759198117,"display_name":"Qwen3 235B A22B Instruct 2507","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:08:37.415647+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-235B-A22B-Instruct-2507","object":"model","owned_by":"","created":1771937600,"display_name":"Qwen3 235B A22B Instruct 2507","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:20.866004+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-235B-A22B-Thinking-2507","object":"model","owned_by":"","created":1771937601,"display_name":"Qwen3 235B A22B Thinking 2507","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:21.703567+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-30b-a3b-instruct-2507","object":"model","owned_by":"","created":1759401803,"display_name":"Qwen3 30B A3B Instruct 2507","pricing":{"input_usd_per_mtok":0.13,"output_usd_per_mtok":0.52,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:23.646850+00:00"},"specs":{"context_window":262144,"max_output_tokens":32000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-30B-A3B-Thinking-2507","object":"model","owned_by":"","created":1771937592,"display_name":"Qwen3 30B A3B Thinking 2507","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:12.163500+00:00"},"specs":{"context_window":81920,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"Qwen/Qwen3.5-0.8B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.04,"output_usd_per_mtok":0.08,"cache_read_usd_per_mtok":0.036,"cache_write_usd_per_mtok":0.04,"effective_at":"2026-04-27T14:12:40.112195+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-122B-A10B","object":"model","owned_by":"","created":1787974367,"display_name":null,"pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":0.9,"cache_read_usd_per_mtok":0.27,"cache_write_usd_per_mtok":0.3,"effective_at":"2026-08-29T03:32:47.538747+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-2B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.18,"cache_read_usd_per_mtok":0.054,"cache_write_usd_per_mtok":0.06,"effective_at":"2026-04-27T14:12:40.311797+00:00"},"specs":null},{"id":"qwen/qwen3.5-35b-a3b","object":"model","owned_by":"","created":1778742870,"display_name":"Qwen3.5-35B-A3B","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T07:14:30.333413+00:00"},"specs":{"context_window":262144,"max_output_tokens":16384,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.5-397b-a17b","object":"model","owned_by":"","created":1775696599,"display_name":"Qwen3.5 397B A17B","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-09T01:03:19.130519+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3.5-4B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":0.09,"cache_write_usd_per_mtok":0.1,"effective_at":"2026-04-27T14:12:40.492113+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-9B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.18,"output_usd_per_mtok":0.54,"cache_read_usd_per_mtok":0.162,"cache_write_usd_per_mtok":0.18,"effective_at":"2026-04-27T14:12:40.664813+00:00"},"specs":null},{"id":"qwen/qwen3.6-27b","object":"model","owned_by":"","created":1779244080,"display_name":"Qwen3.6 27B","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-20T02:28:00.420376+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.6-35b-a3b","object":"model","owned_by":"","created":1778092324,"display_name":"Qwen3.6 35B A3B","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:32:04.441666+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.7-flash","object":"model","owned_by":"","created":1785422211,"display_name":"Qwen3.7 Flash","pricing":{"input_usd_per_mtok":0.03,"output_usd_per_mtok":0.13,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-30T14:36:51.013707+00:00"},"specs":{"context_window":1000000,"max_output_tokens":65536,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","response_format","seed","temperature","tool_choice","tools","top_logprobs","top_p"]},{"id":"qwen/qwen3-8b","object":"model","owned_by":"","created":1767847988,"display_name":"Qwen3 8B","pricing":{"input_usd_per_mtok":0.117,"output_usd_per_mtok":0.455,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-08T04:53:08.134989+00:00"},"specs":{"context_window":131072,"max_output_tokens":8192,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"qwen/qwen3.8-max","object":"model","owned_by":"","created":1786408084,"display_name":null,"pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-11T00:28:04.248858+00:00"},"specs":null},{"id":"qwen/qwen3-coder","object":"model","owned_by":"","created":1761030855,"display_name":"Qwen3 Coder 480B A35B","pricing":{"input_usd_per_mtok":0.975,"output_usd_per_mtok":4.875,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:15.022804+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-coder-next","object":"model","owned_by":"","created":1772054821,"display_name":"Qwen3 Coder Next","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:27:01.126222+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-max","object":"model","owned_by":"","created":1764463224,"display_name":"Qwen3 Max","pricing":{"input_usd_per_mtok":1.2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-11-30T00:40:24.859337+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","logprobs","max_tokens","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-235b-a22b-instruct","object":"model","owned_by":"","created":1761030856,"display_name":"Qwen3 VL 235B A22B Instruct","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:16.011386+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-235b-a22b-thinking","object":"model","owned_by":"","created":1764830992,"display_name":"Qwen3 VL 235B A22B Thinking","pricing":{"input_usd_per_mtok":0.98,"output_usd_per_mtok":4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:52.368716+00:00"},"specs":{"context_window":131072,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-30b-a3b-instruct","object":"model","owned_by":"","created":1764830991,"display_name":"Qwen3 VL 30B A3B Instruct","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":0.7,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:51.204281+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-VL-30B-A3B-Thinking","object":"model","owned_by":"","created":1771937598,"display_name":"Qwen3 VL 30B A3B Thinking","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:18.456091+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-8b-instruct","object":"model","owned_by":"","created":1764830989,"display_name":"Qwen3 VL 8B Instruct","pricing":{"input_usd_per_mtok":0.117,"output_usd_per_mtok":0.455,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:49.046332+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["image","text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"x-ai/grok-4.20","object":"model","owned_by":"","created":1775779880,"display_name":"Grok 4.20","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:20.257314+00:00"},"specs":{"context_window":2000000,"max_output_tokens":1800000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p"]},{"id":"x-ai/grok-4.20-multi-agent","object":"model","owned_by":"","created":1775779882,"display_name":"Grok 4.20 Multi-Agent","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:22.350470+00:00"},"specs":{"context_window":2000000,"max_output_tokens":1800000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","temperature","top_logprobs","top_p"]},{"id":"x-ai/grok-4.6","object":"model","owned_by":"","created":1787959644,"display_name":"Grok 4.6","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-28T23:27:24.930899+00:00"},"specs":{"context_window":500000,"max_output_tokens":450000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"xiaomi/mimo-v2.5","object":"model","owned_by":"","created":1778092300,"display_name":"MiMo-V2.5","pricing":{"input_usd_per_mtok":0.168,"output_usd_per_mtok":0.336,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:31:40.102605+00:00"},"specs":{"context_window":1050000,"max_output_tokens":131072,"modalities":{"input":["text","audio","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"xiaomi/mimo-v2.5-pro","object":"model","owned_by":"","created":1778092285,"display_name":"MiMo-V2.5-Pro","pricing":{"input_usd_per_mtok":0.48024,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:31:25.388731+00:00"},"specs":{"context_window":1050000,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-4.5","object":"model","owned_by":"","created":1759907123,"display_name":"GLM 4.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:23.880304+00:00"},"specs":{"context_window":131072,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.5-air","object":"model","owned_by":"","created":1759907122,"display_name":"GLM 4.5 Air","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.1,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:22.754541+00:00"},"specs":{"context_window":131072,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","repetition_penalty","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.6","object":"model","owned_by":"","created":1759907125,"display_name":"GLM 4.6","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:25.067849+00:00"},"specs":{"context_window":204800,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.7","object":"model","owned_by":"","created":1768006861,"display_name":"GLM 4.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-10T01:01:01.166455+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_p"]},{"id":"z-ai/glm-4.7-flash","object":"model","owned_by":"","created":1770082685,"display_name":"GLM 4.7 Flash","pricing":{"input_usd_per_mtok":0.07,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-03T01:38:05.842638+00:00"},"specs":{"context_window":200000,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5","object":"model","owned_by":"","created":1771374834,"display_name":"GLM 5","pricing":{"input_usd_per_mtok":1,"output_usd_per_mtok":3.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-18T00:33:54.765331+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.1","object":"model","owned_by":"","created":1775779875,"display_name":"GLM 5.1","pricing":{"input_usd_per_mtok":1.4,"output_usd_per_mtok":4.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:15.012238+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.2","object":"model","owned_by":"","created":1781738425,"display_name":"GLM 5.2","pricing":{"input_usd_per_mtok":1.54,"output_usd_per_mtok":4.84,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-17T23:20:25.382141+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.3","object":"model","owned_by":"","created":1787267428,"display_name":"GLM 5.3","pricing":{"input_usd_per_mtok":1.4,"output_usd_per_mtok":4.4,"cache_read_usd_per_mtok":1.26,"cache_write_usd_per_mtok":1.4,"effective_at":"2026-08-20T23:10:28.976971+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["low","high","max"],"default_effort":"max","default_enabled":true,"mandatory":true},"supported_parameters":["max_tokens","temperature","top_p","tools","tool_choice","reasoning","reasoning_effort"]},{"id":"z-ai/glm-5.3-flash","object":"model","owned_by":"","created":1787848124,"display_name":"GLM 5.3 Flash","pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-27T16:28:44.680637+00:00"},"specs":{"context_window":1310720,"max_output_tokens":131072,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"max","default_enabled":true,"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"zai-org/GLM-4.7","object":"model","owned_by":"","created":1771937590,"display_name":"GLM 4.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:10.608022+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_p"]}]}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/session-artifacts/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766/kernel-state.dill b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/session-artifacts/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766/kernel-state.dilldeleted file mode 100644index f8c435d169..0000000000Binary files a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/session-artifacts/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766/kernel-state.dill and /dev/null differdiff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/session-artifacts/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766/kernel-state.json b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/session-artifacts/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766/kernel-state.jsondeleted file mode 100644index 1248c055b6..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/session-artifacts/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766/kernel-state.json+++ /dev/null@@ -1 +0,0 @@-{"version": 1, "savedNames": ["agent_message", "agent_observe", "goal", "rlm_heartbeat"], "skipped": [{"name": "refine", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "compact", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "attach_image", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "edit", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "websearch", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}], "pruned": [], "bytes": 6036, "pythonVersion": "3.11.16", "timestamp": "2026-09-21T17:00:36.698437+00:00"}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/session-artifacts/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766/kernel-stderr.log b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/session-artifacts/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766/kernel-stderr.logdeleted file mode 100644index e69de29bb2..0000000000diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/session-artifacts/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766/scheduled-jobs.json b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/session-artifacts/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766/scheduled-jobs.jsondeleted file mode 100644index 1890849cc4..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/session-artifacts/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766/scheduled-jobs.json+++ /dev/null@@ -1,46 +0,0 @@-{- "jobs": [- {- "id": "a1edc23e-9974-4201-a0d6-3f7595b1f368",- "status": "cancelled",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "b6d528dd888d",- "sessionId": "01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T17:00:19.285Z",- "updatedAt": "2026-09-21T17:00:36.687Z",- "runCount": 0- },- {- "id": "6bf0e7f4-9e82-48bb-bcea-b318427ea501",- "status": "cancelled",- "source": "rlm_heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "b6d528dd888d",- "sessionId": "01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work",- "label": "agent hb",- "prompt": "agent heartbeat check instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T17:00:25.401Z",- "updatedAt": "2026-09-21T17:00:36.687Z",- "runCount": 0- }- ],- "dispatches": []-}diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/session-artifacts/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766/semantic-edges.jsonl b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/session-artifacts/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766/semantic-edges.jsonldeleted file mode 100644index 0068a8449f..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/session-artifacts/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766/semantic-edges.jsonl+++ /dev/null@@ -1,7 +0,0 @@-{"type":"session_registered","session_id":"01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766"}-{"type":"request_started","request_id":"f222ee74fd5743ecaeb17196c9c30ce6","session_id":"01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766"}-{"type":"request_finished","request_id":"f222ee74fd5743ecaeb17196c9c30ce6"}-{"type":"request_started","request_id":"d158b81a348c422fab312c218493340d","session_id":"01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766"}-{"type":"request_finished","request_id":"d158b81a348c422fab312c218493340d"}-{"type":"request_started","request_id":"4ad5de77807f4409bb19401eb4d48999","session_id":"01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766"}-{"type":"request_finished","request_id":"4ad5de77807f4409bb19401eb4d48999"}diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonldeleted file mode 100644index b2dde76359..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl+++ /dev/null@@ -1,14 +0,0 @@-{"type":"session","version":3,"id":"01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766","timestamp":"2026-09-21T17:00:19.101Z","cwd":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work","rlmDepth":0,"git":{"repoUrl":"https://github.com/kevinjosethomas/prime-agent-rs.git","commit":"ad36f9621e45c44cfc9549bb879094d60276d79f","branch":"lane/heartbeats-menu"}}-{"type":"model_change","id":"561aaff8","parentId":null,"timestamp":"2026-09-21T17:00:19.148Z","provider":"prime-inference","modelId":"mock-1"}-{"type":"thinking_level_change","id":"215b0b15","parentId":"561aaff8","timestamp":"2026-09-21T17:00:19.148Z","thinkingLevel":"off"}-{"type":"service_tier_change","id":"98d97206","parentId":"215b0b15","timestamp":"2026-09-21T17:00:19.148Z","serviceTier":"default"}-{"type":"session_info","id":"c2ac01cc","parentId":"98d97206","timestamp":"2026-09-21T17:00:19.165Z","name":"heartbeats-verifier"}-{"type":"session_state","id":"87b4e68b","parentId":"c2ac01cc","timestamp":"2026-09-21T17:00:19.166Z","state":{"status":"active"}}-{"type":"custom_message","customType":"harness_digest","content":"[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>","display":false,"details":{"digest":"# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0"},"id":"fa752d76","parentId":"87b4e68b","timestamp":"2026-09-21T17:00:19.239Z"}-{"type":"message","id":"8b5d21f5","parentId":"fa752d76","timestamp":"2026-09-21T17:00:19.242Z","message":{"role":"user","content":[{"type":"text","text":"verifier seed turn"}],"timestamp":1790010019186}}-{"type":"message","id":"b5e3d602","parentId":"8b5d21f5","timestamp":"2026-09-21T17:00:19.263Z","message":{"role":"assistant","content":[{"type":"text","text":"heartbeats verifier seed reply"}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790010019245,"responseId":"chatcmpl-battery"}}-{"type":"message","id":"7082d765","parentId":"b5e3d602","timestamp":"2026-09-21T17:00:19.310Z","message":{"role":"user","content":[{"type":"text","text":"create the agent heartbeat"}],"timestamp":1790010019293}}-{"type":"message","id":"971d9806","parentId":"7082d765","timestamp":"2026-09-21T17:00:19.319Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"call_battery_1","name":"ipython","arguments":{"code":"import rlm_heartbeat\nawait rlm_heartbeat.create(\n 'agent heartbeat check instruction',\n interval='every 30m',\n label='agent hb',\n)\nprint('created')"}}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790010019310,"responseId":"chatcmpl-battery"}}-{"type":"message","id":"de1783f2","parentId":"971d9806","timestamp":"2026-09-21T17:00:25.415Z","message":{"role":"toolResult","toolCallId":"call_battery_1","toolName":"ipython","content":[{"type":"text","text":"created\n"}],"details":{"durationMs":9,"status":"ok","stdout":"created\n","stderr":"","kernelRestarted":false},"isError":false,"timestamp":1790010025412}}-{"type":"message","id":"21b23c98","parentId":"de1783f2","timestamp":"2026-09-21T17:00:25.427Z","message":{"role":"assistant","content":[{"type":"text","text":"agent heartbeat created"}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790010025418,"responseId":"chatcmpl-battery"}}-{"type":"session_state","id":"7908880a","parentId":"21b23c98","timestamp":"2026-09-21T17:00:36.691Z","state":{"status":"archived"}}diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/settings.json b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/settings.jsondeleted file mode 100644index 539978831e..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/settings.json+++ /dev/null@@ -1 +0,0 @@-{"onboardingShown": true, "telemetry": {"noticeShown": true}}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/telemetry.json b/scripts/heartbeats-runs/20260921T170018Z/ts/agent/telemetry.jsondeleted file mode 100644index 39f6453fcc..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/agent/telemetry.json+++ /dev/null@@ -1,4 +0,0 @@-{- "version": 1,- "installationId": "7751d08a-50a6-4bca-b62c-aa7c3fe5f19c"-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/daemon.log b/scripts/heartbeats-runs/20260921T170018Z/ts/daemon.logdeleted file mode 100644index 85b0f89690..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/daemon.log+++ /dev/null@@ -1,3 +0,0 @@-Prime Agent daemon supervisor 843b8930-0f22-4aa9-8f73-f4fcff982ec6 listening on /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/daemon.sock-Session worker 3fd83c79e6a7 stderr: Prime Agent daemon listening on /tmp/hbv20260921T170018Z-ts/prime-agent-1000/worker-ea916b05d16e-3fd83c79e6a7.sock-Session worker 3fd83c79e6a7 stderr: shutting down (exit 0); closing 0 active session(s)diff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/mock-script.json b/scripts/heartbeats-runs/20260921T170018Z/ts/mock-script.jsondeleted file mode 100644index 85e336d9d6..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/mock-script.json+++ /dev/null@@ -1 +0,0 @@-{"responses": [{"toolCall": {"name": "ipython", "arguments": {"code": "import rlm_heartbeat\nawait rlm_heartbeat.create(\n 'agent heartbeat check instruction',\n interval='every 30m',\n label='agent hb',\n)\nprint('created')"}}}, {"text": "agent heartbeat created"}]}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T170018Z/ts/mock-script.json.requests.jsonl b/scripts/heartbeats-runs/20260921T170018Z/ts/mock-script.json.requests.jsonldeleted file mode 100644index 507c11be30..0000000000--- a/scripts/heartbeats-runs/20260921T170018Z/ts/mock-script.json.requests.jsonl+++ /dev/null@@ -1,5 +0,0 @@-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "You are a general purpose agent that uses code to solve tasks.\nYou solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.\nWhen you are done, stop calling tools and state your final answer.\n\nFor slow or independently completing work, use a nonblocking control loop: start the work, record its handle or output location, then end your turn. A `bash()` handle left running beyond its creating cell sends a completion follow-up; when it arrives, inspect the saved handle and continue. Reading a finished handle's result first cancels that follow-up.\nWhen delegation is available and useful, assign independent substantive tasks to separate workers. Start independent workers without waiting for each one sequentially, and let them run in parallel.\nDo not keep the turn open by polling with `time.sleep()` or shell `sleep`, and do not replace polling with a long blocking `await`. Await only the short operation needed to start work or inspect a result that is already available; otherwise end the turn.\n\nAs the user-facing root agent, when work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n\nUse simplified technical English by default for user-facing prose.\nPrefer short sentences, common words, and concrete verbs. State one main action or fact per sentence when practical. Use lists for steps or conditions.\nKeep necessary technical terms, names, commands, code, paths, and exact quoted text unchanged. State uncertainty directly.\nTreat this as clarity guidance, not a claim of formal ASD-STE100 compliance. Preserve a user-requested format, tone, terminology, and necessary precision.\n\nWorking directory: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work\nConversation log: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl\nRecursive agent depth: 0\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nInstalled Python skill modules (pre-imported): `refine`, `compact`, `agent_observe`, `attach_image`, `edit`, `agent_message`, `rlm_heartbeat`, `goal`, `websearch`.\nRead each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.\nEach skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.\nFor targeted existing-file edits, prefer the pre-imported async `edit` skill from the REPL: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.\nAgent messaging is restricted to your parent, siblings, and direct children; roots are siblings, and deeper communication relays through the intermediate child.\nAgent observation is restricted to your parent, siblings, and direct children; roots are siblings, and deeper inspection relays through the intermediate child.\n\nFrom a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm.spawn(...)` still creates a child.\n\nAn `rlm` object is already in your global namespace. `await rlm.spawn('sub-task', name='api-reviewer')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.\n`name` is required: choose a stable child name that is unique among siblings.\nA child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.\nUse `await agent_observe.list_agents()` to discover family, including inactive members, and `await rlm.list_subagents()` to recover direct child handles.\nChildren reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.\nUse `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.\nUse `agent_observe` to inspect a child's rollout. Observation is restricted to your parent, siblings, and direct children; relay through the intermediate child for deeper descendants.\nSpawn independent children in separate calls and end your turn instead of awaiting completion. Multiple replies may arrive over multiple turns. Delete a direct child explicitly with `await rlm.delete_subagent(child)` when it is no longer needed.\n\nThe `ipython` tool is a persistent Python REPL \u2014 the agent's long-lived control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Top-level `await` works directly. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.\n\nPython is the orchestration language: use Python for loops, conditionals, parsing, and state. Use `bash()` to invoke programs, not to write shell programs \u2014 no shell loops or heredocs; do those in Python.\n\nDo not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n\n`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working. Run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n\nImportant: do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.\n\nUse Python for reading, searching, and editing files \u2014 it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.\n\nEach `bash()` call is its own process, so shell state does not persist between calls; use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls.\n\nPython state in the kernel persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.\n\nContinual harness state is available as `rlm.harness` and `rlm.get_harness_state()`. CRUD calls are local to this Prime Agent session by default: `rlm.harness.create_memory(...)`, `rlm.harness.update_memory(...)`, `rlm.harness.delete_memory(...)`, `rlm.harness.create_skill(...)`, `rlm.harness.update_skill(...)`, `rlm.harness.delete_skill(...)`, `rlm.harness.create_subagent(...)`, `rlm.harness.update_subagent(...)`, `rlm.harness.delete_subagent(...)`, `rlm.harness.create_prompt_note(...)`, `rlm.harness.update_prompt_note(...)`, `rlm.harness.delete_prompt_note(...)`, plus `rlm.harness.record_refinement(...)` and `rlm.harness.overview()`. Use `global_=True` only for stable cross-session lessons; Python reserves `global`, so literal `global=True` is invalid syntax.\n\nTerminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n\nRLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm.spawn('sub-task', name='worker')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm.spawn()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.\n\nTreat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n\n# Delegating to sub-agents\n\nSpawn independent, self-contained work with `handle = await rlm.spawn('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.\nAsk for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.\nUse `await rlm.list_subagents()` after kernel restart or compaction.\nLong-running children can report in-flight status with `await rlm.progress_note(...)`; `rlm.list_subagents()` shows each child's activity, latest progress note, and staleness.\nUse `agent_observe` for bounded transcript inspection.\nFan-in results with `await rlm.collect(targets, timeout_ms=0)`: it returns typed snapshots of direct children (status, answer preview, error) without steering anyone; an explicit timeout blocks only that call until the children settle or the deadline passes.\nLarge child outputs belong in files that you read selectively; `collect` snapshots are previews, not full results.\nDelegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\nPersist genuinely reusable delegation patterns with `await refine.run()`.\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/heartbeats-menu/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/websearch/SKILL.md</location>\n </skill>\n</available_skills>"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "You are a general purpose agent that uses code to solve tasks.\nYou solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.\nWhen you are done, stop calling tools and state your final answer.\n\nFor slow or independently completing work, use a nonblocking control loop: start the work, record its handle or output location, then end your turn. A `bash()` handle left running beyond its creating cell sends a completion follow-up; when it arrives, inspect the saved handle and continue. Reading a finished handle's result first cancels that follow-up.\nWhen delegation is available and useful, assign independent substantive tasks to separate workers. Start independent workers without waiting for each one sequentially, and let them run in parallel.\nDo not keep the turn open by polling with `time.sleep()` or shell `sleep`, and do not replace polling with a long blocking `await`. Await only the short operation needed to start work or inspect a result that is already available; otherwise end the turn.\n\nAs the user-facing root agent, when work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n\nUse simplified technical English by default for user-facing prose.\nPrefer short sentences, common words, and concrete verbs. State one main action or fact per sentence when practical. Use lists for steps or conditions.\nKeep necessary technical terms, names, commands, code, paths, and exact quoted text unchanged. State uncertainty directly.\nTreat this as clarity guidance, not a claim of formal ASD-STE100 compliance. Preserve a user-requested format, tone, terminology, and necessary precision.\n\nWorking directory: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work\nConversation log: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl\nRecursive agent depth: 0\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nInstalled Python skill modules (pre-imported): `refine`, `compact`, `agent_observe`, `attach_image`, `edit`, `agent_message`, `rlm_heartbeat`, `goal`, `websearch`.\nRead each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.\nEach skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.\nFor targeted existing-file edits, prefer the pre-imported async `edit` skill from the REPL: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.\nAgent messaging is restricted to your parent, siblings, and direct children; roots are siblings, and deeper communication relays through the intermediate child.\nAgent observation is restricted to your parent, siblings, and direct children; roots are siblings, and deeper inspection relays through the intermediate child.\n\nFrom a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm.spawn(...)` still creates a child.\n\nAn `rlm` object is already in your global namespace. `await rlm.spawn('sub-task', name='api-reviewer')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.\n`name` is required: choose a stable child name that is unique among siblings.\nA child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.\nUse `await agent_observe.list_agents()` to discover family, including inactive members, and `await rlm.list_subagents()` to recover direct child handles.\nChildren reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.\nUse `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.\nUse `agent_observe` to inspect a child's rollout. Observation is restricted to your parent, siblings, and direct children; relay through the intermediate child for deeper descendants.\nSpawn independent children in separate calls and end your turn instead of awaiting completion. Multiple replies may arrive over multiple turns. Delete a direct child explicitly with `await rlm.delete_subagent(child)` when it is no longer needed.\n\nThe `ipython` tool is a persistent Python REPL \u2014 the agent's long-lived control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Top-level `await` works directly. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.\n\nPython is the orchestration language: use Python for loops, conditionals, parsing, and state. Use `bash()` to invoke programs, not to write shell programs \u2014 no shell loops or heredocs; do those in Python.\n\nDo not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n\n`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working. Run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n\nImportant: do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.\n\nUse Python for reading, searching, and editing files \u2014 it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.\n\nEach `bash()` call is its own process, so shell state does not persist between calls; use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls.\n\nPython state in the kernel persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.\n\nContinual harness state is available as `rlm.harness` and `rlm.get_harness_state()`. CRUD calls are local to this Prime Agent session by default: `rlm.harness.create_memory(...)`, `rlm.harness.update_memory(...)`, `rlm.harness.delete_memory(...)`, `rlm.harness.create_skill(...)`, `rlm.harness.update_skill(...)`, `rlm.harness.delete_skill(...)`, `rlm.harness.create_subagent(...)`, `rlm.harness.update_subagent(...)`, `rlm.harness.delete_subagent(...)`, `rlm.harness.create_prompt_note(...)`, `rlm.harness.update_prompt_note(...)`, `rlm.harness.delete_prompt_note(...)`, plus `rlm.harness.record_refinement(...)` and `rlm.harness.overview()`. Use `global_=True` only for stable cross-session lessons; Python reserves `global`, so literal `global=True` is invalid syntax.\n\nTerminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n\nRLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm.spawn('sub-task', name='worker')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm.spawn()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.\n\nTreat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n\n# Delegating to sub-agents\n\nSpawn independent, self-contained work with `handle = await rlm.spawn('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.\nAsk for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.\nUse `await rlm.list_subagents()` after kernel restart or compaction.\nLong-running children can report in-flight status with `await rlm.progress_note(...)`; `rlm.list_subagents()` shows each child's activity, latest progress note, and staleness.\nUse `agent_observe` for bounded transcript inspection.\nFan-in results with `await rlm.collect(targets, timeout_ms=0)`: it returns typed snapshots of direct children (status, answer preview, error) without steering anyone; an explicit timeout blocks only that call until the children settle or the deadline passes.\nLarge child outputs belong in files that you read selectively; `collect` snapshots are previews, not full results.\nDelegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\nPersist genuinely reusable delegation patterns with `await refine.run()`.\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/heartbeats-menu/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/websearch/SKILL.md</location>\n </skill>\n</available_skills>"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}, {"role": "assistant", "content": "heartbeats verifier seed reply"}, {"role": "user", "content": [{"type": "text", "text": "create the agent heartbeat"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "qwen/qwen3-30b-a3b-instruct-2507", "messages": [{"role": "system", "content": "You generate a status line for an AI coding agent dashboard. You are given the recent conversation between a user and the agent, plus whether the agent is currently working or idle.\n\nOutput ONLY these two tags, nothing before, between, or after. Do not think out loud, explain, or count words.\n<recap>a present-tense clause, at most 12 words, saying what the agent is doing or just did, no trailing period</recap>\n<status>one of NEEDS_INPUT, COMPLETED</status>\n\nSTATUS meaning:\n- COMPLETED: the agent finished its turn AND the user's request is fully done with nothing left.\n- NEEDS_INPUT: the agent finished its turn but the task is not fully done \u2014 it asked a question, hit a blocker, or needs more prompting.\nWhen you are unsure between COMPLETED and NEEDS_INPUT, choose NEEDS_INPUT.\n\nExample:\n<recap>Refactoring the auth middleware and updating its tests</recap>\n<status>NEEDS_INPUT</status>"}, {"role": "user", "content": [{"type": "text", "text": "<agent-state>working</agent-state>\n<conversation>\ncustom: [harness-digest] The persistent memories produced across this session so far: <harness_state> # Continual Harness State Local continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions. The continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters. Default to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual ha\u2026\nuser: verifier seed turn\nassistant: heartbeats verifier seed reply\nuser: create the agent heartbeat\n</conversation>"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 400}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "You are a general purpose agent that uses code to solve tasks.\nYou solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.\nWhen you are done, stop calling tools and state your final answer.\n\nFor slow or independently completing work, use a nonblocking control loop: start the work, record its handle or output location, then end your turn. A `bash()` handle left running beyond its creating cell sends a completion follow-up; when it arrives, inspect the saved handle and continue. Reading a finished handle's result first cancels that follow-up.\nWhen delegation is available and useful, assign independent substantive tasks to separate workers. Start independent workers without waiting for each one sequentially, and let them run in parallel.\nDo not keep the turn open by polling with `time.sleep()` or shell `sleep`, and do not replace polling with a long blocking `await`. Await only the short operation needed to start work or inspect a result that is already available; otherwise end the turn.\n\nAs the user-facing root agent, when work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n\nUse simplified technical English by default for user-facing prose.\nPrefer short sentences, common words, and concrete verbs. State one main action or fact per sentence when practical. Use lists for steps or conditions.\nKeep necessary technical terms, names, commands, code, paths, and exact quoted text unchanged. State uncertainty directly.\nTreat this as clarity guidance, not a claim of formal ASD-STE100 compliance. Preserve a user-requested format, tone, terminology, and necessary precision.\n\nWorking directory: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/work\nConversation log: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T170018Z/ts/agent/sessions/01a0c4e9-4d1d-7377-9aa6-22c8e3fa8766.jsonl\nRecursive agent depth: 0\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nInstalled Python skill modules (pre-imported): `refine`, `compact`, `agent_observe`, `attach_image`, `edit`, `agent_message`, `rlm_heartbeat`, `goal`, `websearch`.\nRead each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.\nEach skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.\nFor targeted existing-file edits, prefer the pre-imported async `edit` skill from the REPL: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.\nAgent messaging is restricted to your parent, siblings, and direct children; roots are siblings, and deeper communication relays through the intermediate child.\nAgent observation is restricted to your parent, siblings, and direct children; roots are siblings, and deeper inspection relays through the intermediate child.\n\nFrom a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm.spawn(...)` still creates a child.\n\nAn `rlm` object is already in your global namespace. `await rlm.spawn('sub-task', name='api-reviewer')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.\n`name` is required: choose a stable child name that is unique among siblings.\nA child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.\nUse `await agent_observe.list_agents()` to discover family, including inactive members, and `await rlm.list_subagents()` to recover direct child handles.\nChildren reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.\nUse `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.\nUse `agent_observe` to inspect a child's rollout. Observation is restricted to your parent, siblings, and direct children; relay through the intermediate child for deeper descendants.\nSpawn independent children in separate calls and end your turn instead of awaiting completion. Multiple replies may arrive over multiple turns. Delete a direct child explicitly with `await rlm.delete_subagent(child)` when it is no longer needed.\n\nThe `ipython` tool is a persistent Python REPL \u2014 the agent's long-lived control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Top-level `await` works directly. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.\n\nPython is the orchestration language: use Python for loops, conditionals, parsing, and state. Use `bash()` to invoke programs, not to write shell programs \u2014 no shell loops or heredocs; do those in Python.\n\nDo not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n\n`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working. Run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n\nImportant: do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.\n\nUse Python for reading, searching, and editing files \u2014 it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.\n\nEach `bash()` call is its own process, so shell state does not persist between calls; use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls.\n\nPython state in the kernel persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.\n\nContinual harness state is available as `rlm.harness` and `rlm.get_harness_state()`. CRUD calls are local to this Prime Agent session by default: `rlm.harness.create_memory(...)`, `rlm.harness.update_memory(...)`, `rlm.harness.delete_memory(...)`, `rlm.harness.create_skill(...)`, `rlm.harness.update_skill(...)`, `rlm.harness.delete_skill(...)`, `rlm.harness.create_subagent(...)`, `rlm.harness.update_subagent(...)`, `rlm.harness.delete_subagent(...)`, `rlm.harness.create_prompt_note(...)`, `rlm.harness.update_prompt_note(...)`, `rlm.harness.delete_prompt_note(...)`, plus `rlm.harness.record_refinement(...)` and `rlm.harness.overview()`. Use `global_=True` only for stable cross-session lessons; Python reserves `global`, so literal `global=True` is invalid syntax.\n\nTerminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n\nRLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm.spawn('sub-task', name='worker')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm.spawn()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.\n\nTreat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n\n# Delegating to sub-agents\n\nSpawn independent, self-contained work with `handle = await rlm.spawn('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.\nAsk for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.\nUse `await rlm.list_subagents()` after kernel restart or compaction.\nLong-running children can report in-flight status with `await rlm.progress_note(...)`; `rlm.list_subagents()` shows each child's activity, latest progress note, and staleness.\nUse `agent_observe` for bounded transcript inspection.\nFan-in results with `await rlm.collect(targets, timeout_ms=0)`: it returns typed snapshots of direct children (status, answer preview, error) without steering anyone; an explicit timeout blocks only that call until the children settle or the deadline passes.\nLarge child outputs belong in files that you read selectively; `collect` snapshots are previews, not full results.\nDelegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\nPersist genuinely reusable delegation patterns with `await refine.run()`.\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/heartbeats-menu/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/websearch/SKILL.md</location>\n </skill>\n</available_skills>"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}, {"role": "assistant", "content": "heartbeats verifier seed reply"}, {"role": "user", "content": [{"type": "text", "text": "create the agent heartbeat"}]}, {"role": "assistant", "content": null, "tool_calls": [{"id": "call_battery_1", "type": "function", "function": {"name": "ipython", "arguments": "{\"code\":\"import rlm_heartbeat\\nawait rlm_heartbeat.create(\\n 'agent heartbeat check instruction',\\n interval='every 30m',\\n label='agent hb',\\n)\\nprint('created')\"}"}}]}, {"role": "tool", "content": "created\n", "tool_call_id": "call_battery_1"}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "qwen/qwen3-30b-a3b-instruct-2507", "messages": [{"role": "system", "content": "You generate a status line for an AI coding agent dashboard. You are given the recent conversation between a user and the agent, plus whether the agent is currently working or idle.\n\nOutput ONLY these two tags, nothing before, between, or after. Do not think out loud, explain, or count words.\n<recap>a present-tense clause, at most 12 words, saying what the agent is doing or just did, no trailing period</recap>\n<status>one of NEEDS_INPUT, COMPLETED</status>\n\nSTATUS meaning:\n- COMPLETED: the agent finished its turn AND the user's request is fully done with nothing left.\n- NEEDS_INPUT: the agent finished its turn but the task is not fully done \u2014 it asked a question, hit a blocker, or needs more prompting.\nWhen you are unsure between COMPLETED and NEEDS_INPUT, choose NEEDS_INPUT.\n\nExample:\n<recap>Refactoring the auth middleware and updating its tests</recap>\n<status>NEEDS_INPUT</status>"}, {"role": "user", "content": [{"type": "text", "text": "<agent-state>idle (finished its turn)</agent-state>\n<conversation>\ncustom: [harness-digest] The persistent memories produced across this session so far: <harness_state> # Continual Harness State Local continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions. The continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters. Default to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual ha\u2026\nuser: verifier seed turn\nassistant: heartbeats verifier seed reply\nuser: create the agent heartbeat\ntoolResult: created\nassistant: agent heartbeat created\n</conversation>"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 400}, "auth": "Bearer sk-battery", "queue": "default"}diff --git a/scripts/heartbeats-runs/20260921T193051Z/findings.json b/scripts/heartbeats-runs/20260921T193051Z/findings.jsondeleted file mode 100644index 184d877861..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/findings.json+++ /dev/null@@ -1,62 +0,0 @@-[- {- "side": "ts",- "ok": true,- "summary": "seed turn ran",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "user heartbeat set through the wire",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "agent heartbeat turn ran",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "wire catalog lists the user and agent heartbeat",- "evidence": "02-wire-catalog.json"- },- {- "side": "ts",- "ok": true,- "summary": "/heartbeats renders the list with both heartbeats",- "evidence": "04-opened.txt"- },- {- "side": "ts",- "ok": true,- "summary": "down navigates to the agent heartbeat and enter opens the TS action pane",- "evidence": "06-actions.txt"- },- {- "side": "ts",- "ok": true,- "summary": "applying the action returns to the list with the paused status",- "evidence": "07-applied.txt"- },- {- "side": "ts",- "ok": true,- "summary": "the pause reached the daemon catalog",- "evidence": "08-applied-catalog.json"- },- {- "side": "ts",- "ok": true,- "summary": "escape closes the view (the transcript returns)",- "evidence": "09-closed.txt"- },- {- "side": "ts",- "ok": true,- "summary": "the tray heartbeat label renders after close",- "evidence": "09-closed.txt"- }-]\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/00-heartbeat-set.json b/scripts/heartbeats-runs/20260921T193051Z/ts/00-heartbeat-set.jsondeleted file mode 100644index 9e2c1ba1c3..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/00-heartbeat-set.json+++ /dev/null@@ -1,29 +0,0 @@-{- "id": "hb-set",- "type": "response",- "command": "heartbeat_set",- "success": true,- "data": {- "heartbeat": {- "id": "9a90ee55-3da7-4dbb-96df-4a0fb9b7c951",- "status": "active",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "929182f70ba0",- "sessionId": "01a0c573-2c7b-76ad-89e3-7d9b7e33b35f",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T19:30:55.192Z",- "updatedAt": "2026-09-21T19:30:55.192Z",- "nextRunAt": "2026-09-21T20:00:55.192Z",- "runCount": 0- }- }-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/01-agent-heartbeat-turn.json b/scripts/heartbeats-runs/20260921T193051Z/ts/01-agent-heartbeat-turn.jsondeleted file mode 100644index 48b023caab..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/01-agent-heartbeat-turn.json+++ /dev/null@@ -1,6 +0,0 @@-{- "id": "hb-agent",- "type": "response",- "command": "prompt_and_wait",- "success": true-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/02-wire-catalog.json b/scripts/heartbeats-runs/20260921T193051Z/ts/02-wire-catalog.jsondeleted file mode 100644index 75fc06d3ff..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/02-wire-catalog.json+++ /dev/null@@ -1,53 +0,0 @@-[- {- "job": {- "id": "9a90ee55-3da7-4dbb-96df-4a0fb9b7c951",- "status": "active",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "929182f70ba0",- "sessionId": "01a0c573-2c7b-76ad-89e3-7d9b7e33b35f",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T19:30:55.192Z",- "updatedAt": "2026-09-21T19:30:55.192Z",- "nextRunAt": "2026-09-21T20:00:55.192Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- },- {- "job": {- "id": "dacec1d0-472e-4853-9b2a-ed6fb4df5b35",- "status": "active",- "source": "rlm_heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "929182f70ba0",- "sessionId": "01a0c573-2c7b-76ad-89e3-7d9b7e33b35f",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work",- "label": "agent hb",- "prompt": "agent heartbeat check instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T19:30:55.814Z",- "updatedAt": "2026-09-21T19:30:55.814Z",- "nextRunAt": "2026-09-21T20:00:55.814Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- }-]\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/03-attached.txt b/scripts/heartbeats-runs/20260921T193051Z/ts/03-attached.txtdeleted file mode 100644index 8ca6055089..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/03-attached.txt+++ /dev/null@@ -1,36 +0,0 @@- heartbeats-verifier $0.00-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent v0.9.5- ▗█▛ ▟██▙▄██▛ ▟▛ model mock-1- ▗▟▌ ▐███▛▘▗▄█▖ cwd ~/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--- verifier seed turn--- heartbeats verifier seed reply--- create the agent heartbeat--- ✓ python · await rlm_heartbeat.create( · ↑ 7 ↓ 1 lines · 9ms-- agent heartbeat created--------- Collapsed mode (Ctrl+O to expand)-- >--← manage 2 heartbeats (Ctrl+R) · mock-1 · 110 (0%)diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/04-opened.txt b/scripts/heartbeats-runs/20260921T193051Z/ts/04-opened.txtdeleted file mode 100644index e964b13bad..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/04-opened.txt+++ /dev/null@@ -1,36 +0,0 @@------------- Heartbeats- 2 heartbeats. Select a heartbeat to manage.--- user heartbeat ping instruction active- Created by you · heartbeats-verifier · every 30m · steer-- agent hb active- Created by agent · heartbeats-verifier · every 30m · steer--- Esc close------------diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/05-navigated.txt b/scripts/heartbeats-runs/20260921T193051Z/ts/05-navigated.txtdeleted file mode 100644index e964b13bad..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/05-navigated.txt+++ /dev/null@@ -1,36 +0,0 @@------------- Heartbeats- 2 heartbeats. Select a heartbeat to manage.--- user heartbeat ping instruction active- Created by you · heartbeats-verifier · every 30m · steer-- agent hb active- Created by agent · heartbeats-verifier · every 30m · steer--- Esc close------------diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/06-actions.txt b/scripts/heartbeats-runs/20260921T193051Z/ts/06-actions.txtdeleted file mode 100644index dc0a1fcfcf..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/06-actions.txt+++ /dev/null@@ -1,36 +0,0 @@------------ agent hb- agent heartbeat check instruction-- Created by agent · heartbeats-verifier · active · every 30m · ste...--- Pause heartbeat- Stop deliveries until resumed-- Stop heartbeat- Permanently remove this heartbeat--- ← back Esc close-----------diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/07-applied.txt b/scripts/heartbeats-runs/20260921T193051Z/ts/07-applied.txtdeleted file mode 100644index 69297f1119..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/07-applied.txt+++ /dev/null@@ -1,36 +0,0 @@------------- Heartbeats- 2 heartbeats · 1 paused. Select a heartbeat to manage.--- user heartbeat ping instruction active- Created by you · heartbeats-verifier · every 30m · steer-- agent hb paused- Created by agent · heartbeats-verifier · every 30m · steer--- Esc close------------diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/08-applied-catalog.json b/scripts/heartbeats-runs/20260921T193051Z/ts/08-applied-catalog.jsondeleted file mode 100644index 8797ef8b97..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/08-applied-catalog.json+++ /dev/null@@ -1,52 +0,0 @@-[- {- "job": {- "id": "9a90ee55-3da7-4dbb-96df-4a0fb9b7c951",- "status": "active",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "929182f70ba0",- "sessionId": "01a0c573-2c7b-76ad-89e3-7d9b7e33b35f",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T19:30:55.192Z",- "updatedAt": "2026-09-21T19:30:55.192Z",- "nextRunAt": "2026-09-21T20:00:55.192Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- },- {- "job": {- "id": "dacec1d0-472e-4853-9b2a-ed6fb4df5b35",- "status": "paused",- "source": "rlm_heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "929182f70ba0",- "sessionId": "01a0c573-2c7b-76ad-89e3-7d9b7e33b35f",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work",- "label": "agent hb",- "prompt": "agent heartbeat check instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T19:30:55.814Z",- "updatedAt": "2026-09-21T19:31:04.869Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- }-]\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/09-closed.txt b/scripts/heartbeats-runs/20260921T193051Z/ts/09-closed.txtdeleted file mode 100644index 739ba58289..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/09-closed.txt+++ /dev/null@@ -1,36 +0,0 @@- heartbeats-verifier $0.00-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent v0.9.5- ▗█▛ ▟██▙▄██▛ ▟▛ model mock-1- ▗▟▌ ▐███▛▘▗▄█▖ cwd ~/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--- verifier seed turn--- heartbeats verifier seed reply--- create the agent heartbeat--- ✓ python · await rlm_heartbeat.create( · ↑ 7 ↓ 1 lines · 9ms-- agent heartbeat created--------- Collapsed mode (Ctrl+O to expand)-- >--← manage 2 heartbeats · 1 paused (Ctrl+R) · mock-1 · 110 (0%)diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/auth.json b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/auth.jsondeleted file mode 100644index 9e26dfeeb6..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/auth.json+++ /dev/null@@ -1 +0,0 @@-{}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/daemon-workers/2be8cfc8e2f4/command-journal.jsonl b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/daemon-workers/2be8cfc8e2f4/command-journal.jsonldeleted file mode 100644index 687e8d2a19..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/daemon-workers/2be8cfc8e2f4/command-journal.jsonl+++ /dev/null@@ -1,13 +0,0 @@-{"version":1,"type":"received","key":"[\"ccaa8ccc02b1\",\"hb-create\"]","clientId":"ccaa8ccc02b1","commandId":"hb-create","commandType":"create","recordedAt":"2026-09-21T19:30:53.539Z"}-{"version":1,"type":"result","key":"[\"ccaa8ccc02b1\",\"hb-create\"]","response":{"id":"hb-create","type":"response","command":"create","success":true,"data":{"id":"929182f70ba0","lifecycle":"draft","activity":"idle","isSessionActive":false,"lastActivityAt":"2026-09-21T19:30:54.958Z","runtimeKind":"top-level","rlmDepth":0,"activeSessionId":"929182f70ba0","sessionId":"01a0c573-2c7b-76ad-89e3-7d9b7e33b35f","sessionFile":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl","sessionName":"heartbeats-verifier","cwd":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work","model":{"id":"mock-1","name":"Mock 1","api":"openai-completions","provider":"prime-inference","baseUrl":"http://127.0.0.1:40407/v1","reasoning":false,"input":["text"],"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0},"contextWindow":128000,"maxTokens":4096},"thinkingLevel":"off","isStreaming":false,"isCompacting":false,"isBashRunning":false,"hasRunningRlmChildren":false,"isRunningTools":false,"attachedClients":0,"messageCount":0,"unfinishedActionCount":0,"created":"2026-09-21T19:30:54.715Z","modified":"2026-09-21T19:30:54.958Z","sessionActions":{"queuedCount":0,"steering":[],"followUps":[]},"rosterStatus":"idle","workerState":"ready","workerPid":2647097}},"recordedAt":"2026-09-21T19:30:54.974Z"}-{"version":1,"type":"received","key":"[\"ccaa8ccc02b1\",\"hb-seed\"]","clientId":"ccaa8ccc02b1","commandId":"hb-seed","commandType":"prompt_and_wait","recordedAt":"2026-09-21T19:30:54.980Z"}-{"version":1,"type":"result","key":"[\"ccaa8ccc02b1\",\"hb-seed\"]","response":{"id":"hb-seed","type":"response","command":"prompt_and_wait","success":true},"recordedAt":"2026-09-21T19:30:55.188Z"}-{"version":1,"type":"received","key":"[\"ccaa8ccc02b1\",\"hb-set\"]","clientId":"ccaa8ccc02b1","commandId":"hb-set","commandType":"heartbeat_set","recordedAt":"2026-09-21T19:30:55.191Z"}-{"version":1,"type":"result","key":"[\"ccaa8ccc02b1\",\"hb-set\"]","response":{"id":"hb-set","type":"response","command":"heartbeat_set","success":true,"data":{"heartbeat":{"id":"9a90ee55-3da7-4dbb-96df-4a0fb9b7c951","status":"active","source":"heartbeat","runtimeKind":"top-level","deliveryMode":"steer","activeSessionId":"929182f70ba0","sessionId":"01a0c573-2c7b-76ad-89e3-7d9b7e33b35f","sessionFile":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl","cwd":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work","prompt":"user heartbeat ping instruction","schedule":{"kind":"interval","expression":"every 30m","intervalMs":1800000},"createdAt":"2026-09-21T19:30:55.192Z","updatedAt":"2026-09-21T19:30:55.192Z","nextRunAt":"2026-09-21T20:00:55.192Z","runCount":0}}},"recordedAt":"2026-09-21T19:30:55.196Z"}-{"version":1,"type":"received","key":"[\"ccaa8ccc02b1\",\"hb-agent\"]","clientId":"ccaa8ccc02b1","commandId":"hb-agent","commandType":"prompt_and_wait","recordedAt":"2026-09-21T19:30:55.199Z"}-{"version":1,"type":"result","key":"[\"ccaa8ccc02b1\",\"hb-agent\"]","response":{"id":"hb-agent","type":"response","command":"prompt_and_wait","success":true},"recordedAt":"2026-09-21T19:30:55.923Z"}-{"version":1,"type":"received","key":"[\"daemon-client:03f4fded-1a08-4e1c-b6eb-8b755f1cb710\",\"daemon_6\"]","clientId":"daemon-client:03f4fded-1a08-4e1c-b6eb-8b755f1cb710","commandId":"daemon_6","commandType":"heartbeat_manage","recordedAt":"2026-09-21T19:31:04.843Z"}-{"version":1,"type":"result","key":"[\"daemon-client:03f4fded-1a08-4e1c-b6eb-8b755f1cb710\",\"daemon_6\"]","response":{"id":"daemon_6","type":"response","command":"heartbeat_manage","success":true,"data":{"heartbeat":{"id":"dacec1d0-472e-4853-9b2a-ed6fb4df5b35","status":"paused","source":"rlm_heartbeat","runtimeKind":"top-level","deliveryMode":"steer","activeSessionId":"929182f70ba0","sessionId":"01a0c573-2c7b-76ad-89e3-7d9b7e33b35f","sessionFile":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl","cwd":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work","label":"agent hb","prompt":"agent heartbeat check instruction","schedule":{"kind":"interval","expression":"every 30m","intervalMs":1800000},"createdAt":"2026-09-21T19:30:55.814Z","updatedAt":"2026-09-21T19:31:04.869Z","runCount":0}}},"recordedAt":"2026-09-21T19:31:05.078Z"}-{"version":1,"type":"acknowledged","key":"[\"daemon-client:03f4fded-1a08-4e1c-b6eb-8b755f1cb710\",\"daemon_6\"]","recordedAt":"2026-09-21T19:31:05.166Z"}-{"version":1,"type":"received","key":"[\"335ce112b455\",\"sd\"]","clientId":"335ce112b455","commandId":"sd","commandType":"shutdown","recordedAt":"2026-09-21T19:31:08.491Z"}-{"version":1,"type":"result","key":"[\"335ce112b455\",\"sd\"]","response":{"id":"sd","type":"response","command":"shutdown","success":true},"recordedAt":"2026-09-21T19:31:08.494Z"}diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/logs/agent.jsonl b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/logs/agent.jsonldeleted file mode 100644index 59d413fa10..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/logs/agent.jsonl+++ /dev/null@@ -1,5 +0,0 @@-{"socketPath":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/daemon.sock","ts":"2026-09-21T19:30:53.537Z","level":"warn","component":"coding-agent.daemon-supervisor","msg":"Prime Agent daemon supervisor 28bf4d17-d0a8-4557-833c-d6102e723dba listening on /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/daemon.sock","pid":2647045,"mode":"daemon"}-{"socketPath":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/daemon.sock","ts":"2026-09-21T19:30:54.651Z","level":"warn","component":"coding-agent.daemon-supervisor","msg":"Session worker a11636d00ef2 stderr: Prime Agent daemon listening on /tmp/hbv20260921T193051Z-ts/prime-agent-1000/worker-2be8cfc8e2f4-a11636d00ef2.sock","pid":2647045,"mode":"daemon"}-{"socketPath":"/tmp/hbv20260921T193051Z-ts/prime-agent-1000/worker-2be8cfc8e2f4-a11636d00ef2.sock","ts":"2026-09-21T19:30:54.651Z","level":"warn","component":"coding-agent.daemon","msg":"Prime Agent daemon listening on /tmp/hbv20260921T193051Z-ts/prime-agent-1000/worker-2be8cfc8e2f4-a11636d00ef2.sock","pid":2647097,"mode":"daemon"}-{"socketPath":"/tmp/hbv20260921T193051Z-ts/prime-agent-1000/worker-2be8cfc8e2f4-a11636d00ef2.sock","ts":"2026-09-21T19:31:08.794Z","level":"warn","component":"coding-agent.daemon","msg":"shutting down (exit 0); closing 0 active session(s)","pid":2647097,"mode":"daemon"}-{"socketPath":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/daemon.sock","ts":"2026-09-21T19:31:08.796Z","level":"warn","component":"coding-agent.daemon-supervisor","msg":"Session worker a11636d00ef2 stderr: shutting down (exit 0); closing 0 active session(s)","pid":2647045,"mode":"daemon"}diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/logs/daemon.sock.2be8cfc8.log b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/logs/daemon.sock.2be8cfc8.logdeleted file mode 100644index 3dbb8dc91b..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/logs/daemon.sock.2be8cfc8.log+++ /dev/null@@ -1,3 +0,0 @@-[2026-09-21T19:30:53.537Z] supervisor: Prime Agent daemon supervisor 28bf4d17-d0a8-4557-833c-d6102e723dba listening on /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/daemon.sock-[2026-09-21T19:30:54.651Z] supervisor: Session worker a11636d00ef2 stderr: Prime Agent daemon listening on /tmp/hbv20260921T193051Z-ts/prime-agent-1000/worker-2be8cfc8e2f4-a11636d00ef2.sock-[2026-09-21T19:31:08.796Z] supervisor: Session worker a11636d00ef2 stderr: shutting down (exit 0); closing 0 active session(s)diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/logs/worker-2be8cfc8e2f4-a11636d00ef2.sock.3e90401f.log b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/logs/worker-2be8cfc8e2f4-a11636d00ef2.sock.3e90401f.logdeleted file mode 100644index 252b9abe21..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/logs/worker-2be8cfc8e2f4-a11636d00ef2.sock.3e90401f.log+++ /dev/null@@ -1,2 +0,0 @@-[2026-09-21T19:30:54.651Z] Prime Agent daemon listening on /tmp/hbv20260921T193051Z-ts/prime-agent-1000/worker-2be8cfc8e2f4-a11636d00ef2.sock-[2026-09-21T19:31:08.794Z] shutting down (exit 0); closing 0 active session(s)diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/models.json b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/models.jsondeleted file mode 100644index 34ef613f47..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/models.json+++ /dev/null@@ -1,19 +0,0 @@-{- "providers": {- "prime-inference": {- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:40407/v1",- "apiKey": "sk-battery",- "models": [- {- "id": "mock-1",- "name": "Mock 1",- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:40407/v1",- "contextWindow": 128000,- "maxTokens": 4096- }- ]- }- }-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/prime-inference-models-cache.json b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/prime-inference-models-cache.jsondeleted file mode 100644index 53a058fa12..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/prime-inference-models-cache.json+++ /dev/null@@ -1 +0,0 @@-{"object":"list","data":[{"id":"alibaba/qwen3.5-flash","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.568539+00:00"},"specs":null},{"id":"alibaba/qwen3.7-max","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":3.75,"output_usd_per_mtok":11.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.639598+00:00"},"specs":null},{"id":"alibaba/qwen3.7-plus","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.717208+00:00"},"specs":null},{"id":"alibaba/qwen3.8-flash","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.225,"output_usd_per_mtok":0.705,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.787469+00:00"},"specs":null},{"id":"anthropic/claude-fable-5","object":"model","owned_by":"","created":1783031626,"display_name":"Claude Fable 5","pricing":{"input_usd_per_mtok":10,"output_usd_per_mtok":50,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-02T22:33:46.495072+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-fable-5.1","object":"model","owned_by":"","created":1788556514,"display_name":"Claude Fable 5.1","pricing":{"input_usd_per_mtok":10,"output_usd_per_mtok":50,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.113341+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-haiku-4.5","object":"model","owned_by":"","created":1761030860,"display_name":"Claude Haiku 4.5","pricing":{"input_usd_per_mtok":1,"output_usd_per_mtok":5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:20.826034+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-opus-4.1","object":"model","owned_by":"","created":1761157329,"display_name":"Claude Opus 4.1","pricing":{"input_usd_per_mtok":15,"output_usd_per_mtok":75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-22T18:22:09.605939+00:00"},"specs":{"context_window":200000,"max_output_tokens":32000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-opus-4.5","object":"model","owned_by":"","created":1764746904,"display_name":"Claude Opus 4.5","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-03T07:28:24.760458+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","verbosity"]},{"id":"anthropic/claude-opus-4.6","object":"model","owned_by":"","created":1772938679,"display_name":"Claude Opus 4.6","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-08T02:57:59.615639+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p","verbosity"]},{"id":"anthropic/claude-opus-4.7","object":"model","owned_by":"","created":1776679634,"display_name":"Claude Opus 4.7","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-20T10:07:14.028142+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-opus-4.8","object":"model","owned_by":"","created":1780660082,"display_name":"Claude Opus 4.8","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-05T11:48:02.246650+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-opus-5","object":"model","owned_by":"","created":1784919442,"display_name":"Claude Opus 5","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-24T18:57:22.868734+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-sonnet-4","object":"model","owned_by":"","created":1761029716,"display_name":"Claude Sonnet 4","pricing":{"input_usd_per_mtok":3,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:16.611551+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-sonnet-4.5","object":"model","owned_by":"","created":1759212031,"display_name":"Claude Sonnet 4.5","pricing":{"input_usd_per_mtok":3,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T06:00:31.866675+00:00"},"specs":{"context_window":1000000,"max_output_tokens":64000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-sonnet-4.6","object":"model","owned_by":"","created":1772054770,"display_name":"Claude Sonnet 4.6","pricing":{"input_usd_per_mtok":3,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:10.104879+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","medium","low"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p","verbosity"]},{"id":"anthropic/claude-sonnet-5","object":"model","owned_by":"","created":1783031448,"display_name":"Claude Sonnet 5","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-02T22:30:48.220566+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"deepseek/deepseek-chat-v3.1","object":"model","owned_by":"","created":1761029725,"display_name":"DeepSeek V3.1","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":1.7,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:25.583563+00:00"},"specs":{"context_window":163840,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v3.1-terminus","object":"model","owned_by":"","created":1759198118,"display_name":"DeepSeek V3.1 Terminus","pricing":{"input_usd_per_mtok":0.27,"output_usd_per_mtok":1,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:08:38.000459+00:00"},"specs":{"context_window":163840,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"deepseek/deepseek-v3.2","object":"model","owned_by":"","created":1764658428,"display_name":"DeepSeek V3.2","pricing":{"input_usd_per_mtok":0.3705,"output_usd_per_mtok":1.1115,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-02T06:53:48.223623+00:00"},"specs":{"context_window":163840,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":false,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v3.2-exp","object":"model","owned_by":"","created":1759198146,"display_name":"DeepSeek V3.2 Exp","pricing":{"input_usd_per_mtok":0.27,"output_usd_per_mtok":0.41,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:09:06.170541+00:00"},"specs":{"context_window":163840,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4.1-flash","object":"model","owned_by":"","created":1789152253,"display_name":"DeepSeek V4.1 Flash","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-11T18:44:13.104931+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-flash","object":"model","owned_by":"","created":1778785963,"display_name":"DeepSeek V4 Flash 0423","pricing":{"input_usd_per_mtok":0.44,"output_usd_per_mtok":1.32,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T19:12:43.449839+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_completion_tokens","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-flash-0731","object":"model","owned_by":"","created":1785777617,"display_name":"DeepSeek V4 Flash 0731","pricing":{"input_usd_per_mtok":0.44,"output_usd_per_mtok":1.32,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T17:20:17.849313+00:00"},"specs":{"context_window":1310720,"max_output_tokens":943718,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-pro","object":"model","owned_by":"","created":1778785932,"display_name":"DeepSeek V4 Pro 0423","pricing":{"input_usd_per_mtok":1.91,"output_usd_per_mtok":3.83,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T19:12:12.010236+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_completion_tokens","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"google/gemini-2.5-flash","object":"model","owned_by":"","created":1761029715,"display_name":"Gemini 2.5 Flash","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":2.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:15.585176+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65535,"modalities":{"input":["file","image","text","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-2.5-flash-lite","object":"model","owned_by":"","created":1761029721,"display_name":"Gemini 2.5 Flash Lite","pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:21.403298+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65535,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-2.5-pro","object":"model","owned_by":"","created":1761029717,"display_name":"Gemini 2.5 Pro","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:17.621295+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.1-pro-preview","object":"model","owned_by":"","created":1772054806,"display_name":"Gemini 3.1 Pro Preview","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":12,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:46.169413+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["audio","file","image","text","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.5-flash","object":"model","owned_by":"","created":1781958981,"display_name":"Gemini 3.5 Flash","pricing":{"input_usd_per_mtok":1.5,"output_usd_per_mtok":9,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-20T12:36:21.024091+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.6-flash","object":"model","owned_by":"","created":1784918138,"display_name":"Gemini 3.6 Flash","pricing":{"input_usd_per_mtok":1.5,"output_usd_per_mtok":7.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-24T18:35:38.706927+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.7-flash","object":"model","owned_by":"","created":1787848124,"display_name":"Gemini 3.7 Flash","pricing":{"input_usd_per_mtok":1.35,"output_usd_per_mtok":6.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-27T16:28:44.601830+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.8-flash","object":"model","owned_by":"","created":1788556514,"display_name":"Gemini 3.8 Flash","pricing":{"input_usd_per_mtok":0.75,"output_usd_per_mtok":3.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.212597+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3-flash-preview","object":"model","owned_by":"","created":1766202374,"display_name":"Gemini 3 Flash Preview","pricing":{"input_usd_per_mtok":0.5,"output_usd_per_mtok":3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-20T03:46:14.305378+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemma-3-27b-it","object":"model","owned_by":"","created":1761030851,"display_name":"Gemma 3 27B","pricing":{"input_usd_per_mtok":0.119,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:11.952792+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"meta-llama/Llama-3.2-1B-Instruct","object":"model","owned_by":"","created":1771939296,"display_name":"Llama 3.2 1B Instruct","pricing":{"input_usd_per_mtok":0.027,"output_usd_per_mtok":0.201,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T13:21:36.921319+00:00"},"specs":{"context_window":60000,"max_output_tokens":54000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","max_tokens","min_p","presence_penalty","repetition_penalty","seed","stop","temperature","top_k","top_p"]},{"id":"meta-llama/Llama-3.2-3B-Instruct","object":"model","owned_by":"","created":1771939312,"display_name":"Llama 3.2 3B Instruct","pricing":{"input_usd_per_mtok":0.0509,"output_usd_per_mtok":0.335,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T13:21:52.649872+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","seed","stop","structured_outputs","temperature","top_k","top_logprobs","top_p"]},{"id":"meta-llama/llama-3.3-70b-instruct","object":"model","owned_by":"","created":1759196298,"display_name":"Llama 3.3 70B Instruct","pricing":{"input_usd_per_mtok":1.04,"output_usd_per_mtok":2.253,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T01:38:18.545960+00:00"},"specs":{"context_window":131072,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"meta-llama/llama-4-maverick","object":"model","owned_by":"","created":1761030850,"display_name":"Llama 4 Maverick","pricing":{"input_usd_per_mtok":0.35,"output_usd_per_mtok":1.15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:10.101027+00:00"},"specs":{"context_window":1048576,"max_output_tokens":16384,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m2.5","object":"model","owned_by":"","created":1771374795,"display_name":"MiniMax M2.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-18T00:33:15.739871+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m2.7","object":"model","owned_by":"","created":1775779870,"display_name":"MiniMax M2.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:10.312006+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m3","object":"model","owned_by":"","created":1780311536,"display_name":"MiniMax M3","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-01T10:58:56.335485+00:00"},"specs":{"context_window":1048576,"max_output_tokens":512000,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"mistralai/mistral-large-2512","object":"model","owned_by":"","created":1764689752,"display_name":null,"pricing":{"input_usd_per_mtok":0.5,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-02T15:35:52.296516+00:00"},"specs":null},{"id":"mistralai/mistral-nemo","object":"model","owned_by":"","created":1761030857,"display_name":"Mistral Nemo","pricing":{"input_usd_per_mtok":0.165,"output_usd_per_mtok":0.17,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:17.801302+00:00"},"specs":{"context_window":131072,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"mistralai/mistral-small-2603","object":"model","owned_by":"","created":1775779872,"display_name":"Mistral Small 4","pricing":{"input_usd_per_mtok":0.165,"output_usd_per_mtok":0.66,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:12.604966+00:00"},"specs":{"context_window":262144,"max_output_tokens":209715,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","none"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"mistralai/mixtral-8x22b-instruct","object":"model","owned_by":"","created":1759198003,"display_name":"Mixtral 8x22B Instruct","pricing":{"input_usd_per_mtok":2.2,"output_usd_per_mtok":6.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:06:43.614656+00:00"},"specs":{"context_window":65536,"max_output_tokens":52428,"modalities":{"input":["text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","max_tokens","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"moonshotai/kimi-k2-0905","object":"model","owned_by":"","created":1759907126,"display_name":"Kimi K2 0905","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:26.057085+00:00"},"specs":{"context_window":262144,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"moonshotai/kimi-k2.5","object":"model","owned_by":"","created":1769800671,"display_name":"Kimi K2.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-30T19:17:51.210047+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k2.6","object":"model","owned_by":"","created":1776733288,"display_name":"Kimi K2.6","pricing":{"input_usd_per_mtok":0.95,"output_usd_per_mtok":4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-21T01:01:28.804384+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k2.7-code","object":"model","owned_by":"","created":1781282432,"display_name":"Kimi K2.7 Code","pricing":{"input_usd_per_mtok":1.9,"output_usd_per_mtok":8,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-12T16:40:32.168235+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k3","object":"model","owned_by":"","created":1784248110,"display_name":"Kimi K3","pricing":{"input_usd_per_mtok":3.45,"output_usd_per_mtok":17.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-17T00:28:30.162170+00:00"},"specs":{"context_window":1048576,"max_output_tokens":943718,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"max","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"nvidia/nemotron-3-nano-30b-a3b","object":"model","owned_by":"","created":1775779886,"display_name":"Nemotron 3 Nano 30B A3B","pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.24,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:26.952299+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"openai/gpt-4.1","object":"model","owned_by":"","created":1759401802,"display_name":"GPT-4.1","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":8,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:22.496353+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4.1-mini","object":"model","owned_by":"","created":1759401806,"display_name":"GPT-4.1 Mini","pricing":{"input_usd_per_mtok":0.4,"output_usd_per_mtok":1.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:26.911016+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4.1-nano","object":"model","owned_by":"","created":1759401808,"display_name":"GPT-4.1 Nano","pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:28.011794+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4o","object":"model","owned_by":"","created":1761029734,"display_name":"GPT-4o","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:34.447350+00:00"},"specs":{"context_window":128000,"max_output_tokens":16384,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_completion_tokens","max_tokens","prediction","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p","web_search_options"]},{"id":"openai/gpt-4o-mini","object":"model","owned_by":"","created":1761029722,"display_name":"GPT-4o-mini","pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:22.331052+00:00"},"specs":{"context_window":128000,"max_output_tokens":16384,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_completion_tokens","max_tokens","prediction","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p","web_search_options"]},{"id":"openai/gpt-5","object":"model","owned_by":"","created":1759211784,"display_name":"GPT-5","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T05:56:24.831437+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.1","object":"model","owned_by":"","created":1763426084,"display_name":"GPT-5.1","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-11-18T00:34:44.949671+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","none"],"default_effort":"none","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.2","object":"model","owned_by":"","created":1765611176,"display_name":"GPT-5.2","pricing":{"input_usd_per_mtok":1.75,"output_usd_per_mtok":14,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-13T07:32:56.544785+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.2-pro","object":"model","owned_by":"","created":1765611177,"display_name":"GPT-5.2 Pro","pricing":{"input_usd_per_mtok":21,"output_usd_per_mtok":168,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-13T07:32:57.583455+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.3-codex","object":"model","owned_by":"","created":1772054791,"display_name":"GPT-5.3-Codex","pricing":{"input_usd_per_mtok":1.75,"output_usd_per_mtok":14,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:31.496994+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4","object":"model","owned_by":"","created":1773713673,"display_name":"GPT-5.4","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-17T02:14:33.278960+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-mini","object":"model","owned_by":"","created":1775779863,"display_name":"GPT-5.4 Mini","pricing":{"input_usd_per_mtok":0.75,"output_usd_per_mtok":4.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:03.742760+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-nano","object":"model","owned_by":"","created":1775779866,"display_name":"GPT-5.4 Nano","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:06.153745+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-pro","object":"model","owned_by":"","created":1773713674,"display_name":"GPT-5.4 Pro","pricing":{"input_usd_per_mtok":30,"output_usd_per_mtok":180,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-17T02:14:34.995439+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.5","object":"model","owned_by":"","created":1777306094,"display_name":"GPT-5.5","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":30,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-27T16:08:14.065946+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6","object":"model","owned_by":"","created":1783751214,"display_name":null,"pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":30,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:26:54.495544+00:00"},"specs":null},{"id":"openai/gpt-5.6-luna","object":"model","owned_by":"","created":1783751321,"display_name":"GPT-5.6 Luna","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:41.639902+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-luna-pro","object":"model","owned_by":"","created":1783751322,"display_name":"GPT-5.6 Luna Pro","pricing":{"input_usd_per_mtok":1,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:42.459149+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-sol","object":"model","owned_by":"","created":1783751318,"display_name":"GPT-5.6 Sol","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":30,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:38.262869+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-sol-pro","object":"model","owned_by":"","created":1783751319,"display_name":"GPT-5.6 Sol Pro","pricing":{"input_usd_per_mtok":5,"output_usd_per_mtok":30,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:39.039507+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-terra","object":"model","owned_by":"","created":1783751319,"display_name":"GPT-5.6 Terra","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:39.851751+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-terra-pro","object":"model","owned_by":"","created":1783751320,"display_name":"GPT-5.6 Terra Pro","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:40.628845+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5-mini","object":"model","owned_by":"","created":1759401800,"display_name":"GPT-5 Mini","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:20.338354+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5-nano","object":"model","owned_by":"","created":1759401801,"display_name":"GPT-5 Nano","pricing":{"input_usd_per_mtok":0.05,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:21.418908+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-6-astra","object":"model","owned_by":"","created":1788556514,"display_name":"GPT-6 Astra","pricing":{"input_usd_per_mtok":10,"output_usd_per_mtok":50,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.299026+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-oss-120b","object":"model","owned_by":"","created":1760042083,"display_name":"gpt-oss-120b","pricing":{"input_usd_per_mtok":0.35,"output_usd_per_mtok":0.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-09T20:34:43.236004+00:00"},"specs":{"context_window":131072,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"openai/gpt-oss-20b","object":"model","owned_by":"","created":1761030856,"display_name":"gpt-oss-20b","pricing":{"input_usd_per_mtok":0.07,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:16.897238+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"poolside/laguna-s-2.1","object":"model","owned_by":"","created":1785726826,"display_name":"Laguna S 2.1","pricing":{"input_usd_per_mtok":0.09,"output_usd_per_mtok":0.18,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T03:13:46.654853+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","temperature","tool_choice","tools"]},{"id":"poolside/laguna-xs-2.1","object":"model","owned_by":"","created":1785726826,"display_name":"Laguna XS 2.1","pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.12,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T03:13:46.740724+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","temperature","tool_choice","tools"]},{"id":"qwen/qwen3-235b-a22b-2507","object":"model","owned_by":"","created":1759198117,"display_name":"Qwen3 235B A22B Instruct 2507","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:08:37.415647+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-235B-A22B-Instruct-2507","object":"model","owned_by":"","created":1771937600,"display_name":"Qwen3 235B A22B Instruct 2507","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:20.866004+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-235B-A22B-Thinking-2507","object":"model","owned_by":"","created":1771937601,"display_name":"Qwen3 235B A22B Thinking 2507","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:21.703567+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-30b-a3b-instruct-2507","object":"model","owned_by":"","created":1759401803,"display_name":"Qwen3 30B A3B Instruct 2507","pricing":{"input_usd_per_mtok":0.13,"output_usd_per_mtok":0.52,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:23.646850+00:00"},"specs":{"context_window":262144,"max_output_tokens":32000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-30B-A3B-Thinking-2507","object":"model","owned_by":"","created":1771937592,"display_name":"Qwen3 30B A3B Thinking 2507","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:12.163500+00:00"},"specs":{"context_window":81920,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"Qwen/Qwen3.5-0.8B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.04,"output_usd_per_mtok":0.08,"cache_read_usd_per_mtok":0.036,"cache_write_usd_per_mtok":0.04,"effective_at":"2026-04-27T14:12:40.112195+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-122B-A10B","object":"model","owned_by":"","created":1787974367,"display_name":null,"pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":0.9,"cache_read_usd_per_mtok":0.27,"cache_write_usd_per_mtok":0.3,"effective_at":"2026-08-29T03:32:47.538747+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-2B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.18,"cache_read_usd_per_mtok":0.054,"cache_write_usd_per_mtok":0.06,"effective_at":"2026-04-27T14:12:40.311797+00:00"},"specs":null},{"id":"qwen/qwen3.5-35b-a3b","object":"model","owned_by":"","created":1778742870,"display_name":"Qwen3.5-35B-A3B","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T07:14:30.333413+00:00"},"specs":{"context_window":262144,"max_output_tokens":16384,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.5-397b-a17b","object":"model","owned_by":"","created":1775696599,"display_name":"Qwen3.5 397B A17B","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-09T01:03:19.130519+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3.5-4B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":0.09,"cache_write_usd_per_mtok":0.1,"effective_at":"2026-04-27T14:12:40.492113+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-9B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.18,"output_usd_per_mtok":0.54,"cache_read_usd_per_mtok":0.162,"cache_write_usd_per_mtok":0.18,"effective_at":"2026-04-27T14:12:40.664813+00:00"},"specs":null},{"id":"qwen/qwen3.6-27b","object":"model","owned_by":"","created":1779244080,"display_name":"Qwen3.6 27B","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-20T02:28:00.420376+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.6-35b-a3b","object":"model","owned_by":"","created":1778092324,"display_name":"Qwen3.6 35B A3B","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:32:04.441666+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.7-flash","object":"model","owned_by":"","created":1785422211,"display_name":"Qwen3.7 Flash","pricing":{"input_usd_per_mtok":0.03,"output_usd_per_mtok":0.13,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-30T14:36:51.013707+00:00"},"specs":{"context_window":1000000,"max_output_tokens":65536,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","response_format","seed","temperature","tool_choice","tools","top_logprobs","top_p"]},{"id":"qwen/qwen3-8b","object":"model","owned_by":"","created":1767847988,"display_name":"Qwen3 8B","pricing":{"input_usd_per_mtok":0.117,"output_usd_per_mtok":0.455,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-08T04:53:08.134989+00:00"},"specs":{"context_window":131072,"max_output_tokens":8192,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"qwen/qwen3.8-max","object":"model","owned_by":"","created":1786408084,"display_name":null,"pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-11T00:28:04.248858+00:00"},"specs":null},{"id":"qwen/qwen3-coder","object":"model","owned_by":"","created":1761030855,"display_name":"Qwen3 Coder 480B A35B","pricing":{"input_usd_per_mtok":0.975,"output_usd_per_mtok":4.875,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:15.022804+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-coder-next","object":"model","owned_by":"","created":1772054821,"display_name":"Qwen3 Coder Next","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:27:01.126222+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-max","object":"model","owned_by":"","created":1764463224,"display_name":"Qwen3 Max","pricing":{"input_usd_per_mtok":1.2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-11-30T00:40:24.859337+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","logprobs","max_tokens","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-235b-a22b-instruct","object":"model","owned_by":"","created":1761030856,"display_name":"Qwen3 VL 235B A22B Instruct","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:16.011386+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-235b-a22b-thinking","object":"model","owned_by":"","created":1764830992,"display_name":"Qwen3 VL 235B A22B Thinking","pricing":{"input_usd_per_mtok":0.98,"output_usd_per_mtok":4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:52.368716+00:00"},"specs":{"context_window":131072,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-30b-a3b-instruct","object":"model","owned_by":"","created":1764830991,"display_name":"Qwen3 VL 30B A3B Instruct","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":0.7,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:51.204281+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-VL-30B-A3B-Thinking","object":"model","owned_by":"","created":1771937598,"display_name":"Qwen3 VL 30B A3B Thinking","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:18.456091+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-8b-instruct","object":"model","owned_by":"","created":1764830989,"display_name":"Qwen3 VL 8B Instruct","pricing":{"input_usd_per_mtok":0.117,"output_usd_per_mtok":0.455,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:49.046332+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["image","text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"x-ai/grok-4.20","object":"model","owned_by":"","created":1775779880,"display_name":"Grok 4.20","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:20.257314+00:00"},"specs":{"context_window":2000000,"max_output_tokens":1800000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p"]},{"id":"x-ai/grok-4.20-multi-agent","object":"model","owned_by":"","created":1775779882,"display_name":"Grok 4.20 Multi-Agent","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:22.350470+00:00"},"specs":{"context_window":2000000,"max_output_tokens":1800000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","temperature","top_logprobs","top_p"]},{"id":"x-ai/grok-4.6","object":"model","owned_by":"","created":1787959644,"display_name":"Grok 4.6","pricing":{"input_usd_per_mtok":2,"output_usd_per_mtok":6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-28T23:27:24.930899+00:00"},"specs":{"context_window":500000,"max_output_tokens":450000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"xiaomi/mimo-v2.5","object":"model","owned_by":"","created":1778092300,"display_name":"MiMo-V2.5","pricing":{"input_usd_per_mtok":0.168,"output_usd_per_mtok":0.336,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:31:40.102605+00:00"},"specs":{"context_window":1050000,"max_output_tokens":131072,"modalities":{"input":["text","audio","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"xiaomi/mimo-v2.5-pro","object":"model","owned_by":"","created":1778092285,"display_name":"MiMo-V2.5-Pro","pricing":{"input_usd_per_mtok":0.48024,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:31:25.388731+00:00"},"specs":{"context_window":1050000,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-4.5","object":"model","owned_by":"","created":1759907123,"display_name":"GLM 4.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:23.880304+00:00"},"specs":{"context_window":131072,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.5-air","object":"model","owned_by":"","created":1759907122,"display_name":"GLM 4.5 Air","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.1,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:22.754541+00:00"},"specs":{"context_window":131072,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","repetition_penalty","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.6","object":"model","owned_by":"","created":1759907125,"display_name":"GLM 4.6","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:25.067849+00:00"},"specs":{"context_window":204800,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.7","object":"model","owned_by":"","created":1768006861,"display_name":"GLM 4.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-10T01:01:01.166455+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_p"]},{"id":"z-ai/glm-4.7-flash","object":"model","owned_by":"","created":1770082685,"display_name":"GLM 4.7 Flash","pricing":{"input_usd_per_mtok":0.07,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-03T01:38:05.842638+00:00"},"specs":{"context_window":200000,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5","object":"model","owned_by":"","created":1771374834,"display_name":"GLM 5","pricing":{"input_usd_per_mtok":1,"output_usd_per_mtok":3.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-18T00:33:54.765331+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.1","object":"model","owned_by":"","created":1775779875,"display_name":"GLM 5.1","pricing":{"input_usd_per_mtok":1.4,"output_usd_per_mtok":4.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:15.012238+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.2","object":"model","owned_by":"","created":1781738425,"display_name":"GLM 5.2","pricing":{"input_usd_per_mtok":1.54,"output_usd_per_mtok":4.84,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-17T23:20:25.382141+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.3","object":"model","owned_by":"","created":1787267428,"display_name":"GLM 5.3","pricing":{"input_usd_per_mtok":1.4,"output_usd_per_mtok":4.4,"cache_read_usd_per_mtok":1.26,"cache_write_usd_per_mtok":1.4,"effective_at":"2026-08-20T23:10:28.976971+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["low","high","max"],"default_effort":"max","default_enabled":true,"mandatory":true},"supported_parameters":["max_tokens","temperature","top_p","tools","tool_choice","reasoning","reasoning_effort"]},{"id":"z-ai/glm-5.3-flash","object":"model","owned_by":"","created":1787848124,"display_name":"GLM 5.3 Flash","pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-27T16:28:44.680637+00:00"},"specs":{"context_window":1310720,"max_output_tokens":102400,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"max","default_enabled":true,"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"zai-org/GLM-4.7","object":"model","owned_by":"","created":1771937590,"display_name":"GLM 4.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:10.608022+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_p"]}]}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/session-artifacts/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f/kernel-state.dill b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/session-artifacts/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f/kernel-state.dilldeleted file mode 100644index f8c435d169..0000000000Binary files a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/session-artifacts/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f/kernel-state.dill and /dev/null differdiff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/session-artifacts/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f/kernel-state.json b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/session-artifacts/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f/kernel-state.jsondeleted file mode 100644index 60de9eb326..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/session-artifacts/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f/kernel-state.json+++ /dev/null@@ -1 +0,0 @@-{"version": 1, "savedNames": ["agent_message", "agent_observe", "goal", "rlm_heartbeat"], "skipped": [{"name": "refine", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "compact", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "attach_image", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "edit", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "websearch", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}], "pruned": [], "bytes": 6036, "pythonVersion": "3.11.16", "timestamp": "2026-09-21T19:31:08.508462+00:00"}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/session-artifacts/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f/kernel-stderr.log b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/session-artifacts/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f/kernel-stderr.logdeleted file mode 100644index e69de29bb2..0000000000diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/session-artifacts/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f/scheduled-jobs.json b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/session-artifacts/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f/scheduled-jobs.jsondeleted file mode 100644index d484b0eb0d..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/session-artifacts/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f/scheduled-jobs.json+++ /dev/null@@ -1,46 +0,0 @@-{- "jobs": [- {- "id": "9a90ee55-3da7-4dbb-96df-4a0fb9b7c951",- "status": "cancelled",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "929182f70ba0",- "sessionId": "01a0c573-2c7b-76ad-89e3-7d9b7e33b35f",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T19:30:55.192Z",- "updatedAt": "2026-09-21T19:31:08.498Z",- "runCount": 0- },- {- "id": "dacec1d0-472e-4853-9b2a-ed6fb4df5b35",- "status": "cancelled",- "source": "rlm_heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "929182f70ba0",- "sessionId": "01a0c573-2c7b-76ad-89e3-7d9b7e33b35f",- "sessionFile": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl",- "cwd": "/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work",- "label": "agent hb",- "prompt": "agent heartbeat check instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T19:30:55.814Z",- "updatedAt": "2026-09-21T19:31:08.498Z",- "runCount": 0- }- ],- "dispatches": []-}diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/session-artifacts/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f/semantic-edges.jsonl b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/session-artifacts/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f/semantic-edges.jsonldeleted file mode 100644index 39c4b706e0..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/session-artifacts/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f/semantic-edges.jsonl+++ /dev/null@@ -1,7 +0,0 @@-{"type":"session_registered","session_id":"01a0c573-2c7b-76ad-89e3-7d9b7e33b35f"}-{"type":"request_started","request_id":"75b6b1ad67b047a3b37a9fbc8c75c4a0","session_id":"01a0c573-2c7b-76ad-89e3-7d9b7e33b35f"}-{"type":"request_finished","request_id":"75b6b1ad67b047a3b37a9fbc8c75c4a0"}-{"type":"request_started","request_id":"54418c4a18d84a9bafef0c70ffe29f4f","session_id":"01a0c573-2c7b-76ad-89e3-7d9b7e33b35f"}-{"type":"request_finished","request_id":"54418c4a18d84a9bafef0c70ffe29f4f"}-{"type":"request_started","request_id":"efc849040a614117a887f27514bb5c3c","session_id":"01a0c573-2c7b-76ad-89e3-7d9b7e33b35f"}-{"type":"request_finished","request_id":"efc849040a614117a887f27514bb5c3c"}diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonldeleted file mode 100644index 4c7f08d5bd..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl+++ /dev/null@@ -1,14 +0,0 @@-{"type":"session","version":3,"id":"01a0c573-2c7b-76ad-89e3-7d9b7e33b35f","timestamp":"2026-09-21T19:30:54.715Z","cwd":"/home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work","rlmDepth":0,"git":{"repoUrl":"https://github.com/kevinjosethomas/prime-agent-rs.git","commit":"9f75a2dad4e1aac5804fe012938ca162d526a7fc","branch":"lane/heartbeats-menu"}}-{"type":"model_change","id":"8b612e6d","parentId":null,"timestamp":"2026-09-21T19:30:54.875Z","provider":"prime-inference","modelId":"mock-1"}-{"type":"thinking_level_change","id":"106f0923","parentId":"8b612e6d","timestamp":"2026-09-21T19:30:54.875Z","thinkingLevel":"off"}-{"type":"service_tier_change","id":"f78f2c02","parentId":"106f0923","timestamp":"2026-09-21T19:30:54.875Z","serviceTier":"default"}-{"type":"session_info","id":"ed66c894","parentId":"f78f2c02","timestamp":"2026-09-21T19:30:54.961Z","name":"heartbeats-verifier"}-{"type":"session_state","id":"16ae0891","parentId":"ed66c894","timestamp":"2026-09-21T19:30:54.962Z","state":{"status":"active"}}-{"type":"custom_message","customType":"harness_digest","content":"[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>","display":false,"details":{"digest":"# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0"},"id":"5667eb53","parentId":"16ae0891","timestamp":"2026-09-21T19:30:55.044Z"}-{"type":"message","id":"4afa660c","parentId":"5667eb53","timestamp":"2026-09-21T19:30:55.048Z","message":{"role":"user","content":[{"type":"text","text":"verifier seed turn"}],"timestamp":1790019054992}}-{"type":"message","id":"79525e05","parentId":"4afa660c","timestamp":"2026-09-21T19:30:55.117Z","message":{"role":"assistant","content":[{"type":"text","text":"heartbeats verifier seed reply"}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790019055051,"responseId":"chatcmpl-battery"}}-{"type":"message","id":"9495f320","parentId":"79525e05","timestamp":"2026-09-21T19:30:55.269Z","message":{"role":"user","content":[{"type":"text","text":"create the agent heartbeat"}],"timestamp":1790019055206}}-{"type":"message","id":"4afe21e6","parentId":"9495f320","timestamp":"2026-09-21T19:30:55.278Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"call_battery_1","name":"ipython","arguments":{"code":"import rlm_heartbeat\nawait rlm_heartbeat.create(\n 'agent heartbeat check instruction',\n interval='every 30m',\n label='agent hb',\n)\nprint('created')"}}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790019055270,"responseId":"chatcmpl-battery"}}-{"type":"message","id":"28b80183","parentId":"4afe21e6","timestamp":"2026-09-21T19:30:55.826Z","message":{"role":"toolResult","toolCallId":"call_battery_1","toolName":"ipython","content":[{"type":"text","text":"created\n"}],"details":{"durationMs":9,"status":"ok","stdout":"created\n","stderr":"","kernelRestarted":false},"isError":false,"timestamp":1790019055823}}-{"type":"message","id":"741f34d6","parentId":"28b80183","timestamp":"2026-09-21T19:30:55.843Z","message":{"role":"assistant","content":[{"type":"text","text":"agent heartbeat created"}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790019055836,"responseId":"chatcmpl-battery"}}-{"type":"session_state","id":"f69faf29","parentId":"741f34d6","timestamp":"2026-09-21T19:31:08.501Z","state":{"status":"archived"}}diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/settings.json b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/settings.jsondeleted file mode 100644index 539978831e..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/settings.json+++ /dev/null@@ -1 +0,0 @@-{"onboardingShown": true, "telemetry": {"noticeShown": true}}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/telemetry.json b/scripts/heartbeats-runs/20260921T193051Z/ts/agent/telemetry.jsondeleted file mode 100644index ee56546ffa..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/agent/telemetry.json+++ /dev/null@@ -1,4 +0,0 @@-{- "version": 1,- "installationId": "556cbc6f-f726-4253-9822-533986b81a40"-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/daemon.log b/scripts/heartbeats-runs/20260921T193051Z/ts/daemon.logdeleted file mode 100644index 871ffda553..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/daemon.log+++ /dev/null@@ -1,3 +0,0 @@-Prime Agent daemon supervisor 28bf4d17-d0a8-4557-833c-d6102e723dba listening on /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/daemon.sock-Session worker a11636d00ef2 stderr: Prime Agent daemon listening on /tmp/hbv20260921T193051Z-ts/prime-agent-1000/worker-2be8cfc8e2f4-a11636d00ef2.sock-Session worker a11636d00ef2 stderr: shutting down (exit 0); closing 0 active session(s)diff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/mock-script.json b/scripts/heartbeats-runs/20260921T193051Z/ts/mock-script.jsondeleted file mode 100644index 85e336d9d6..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/mock-script.json+++ /dev/null@@ -1 +0,0 @@-{"responses": [{"toolCall": {"name": "ipython", "arguments": {"code": "import rlm_heartbeat\nawait rlm_heartbeat.create(\n 'agent heartbeat check instruction',\n interval='every 30m',\n label='agent hb',\n)\nprint('created')"}}}, {"text": "agent heartbeat created"}]}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T193051Z/ts/mock-script.json.requests.jsonl b/scripts/heartbeats-runs/20260921T193051Z/ts/mock-script.json.requests.jsonldeleted file mode 100644index a34a9c1246..0000000000--- a/scripts/heartbeats-runs/20260921T193051Z/ts/mock-script.json.requests.jsonl+++ /dev/null@@ -1,4 +0,0 @@-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "You are a general purpose agent that uses code to solve tasks.\nYou solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.\nWhen you are done, stop calling tools and state your final answer.\n\nFor slow or independently completing work, use a nonblocking control loop: start the work, record its handle or output location, then end your turn. A `bash()` handle left running beyond its creating cell sends a completion follow-up; when it arrives, inspect the saved handle and continue. Reading a finished handle's result first cancels that follow-up.\nWhen delegation is available and useful, assign independent substantive tasks to separate workers. Start independent workers without waiting for each one sequentially, and let them run in parallel.\nDo not keep the turn open by polling with `time.sleep()` or shell `sleep`, and do not replace polling with a long blocking `await`. Await only the short operation needed to start work or inspect a result that is already available; otherwise end the turn.\n\nAs the user-facing root agent, when work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n\nUse simplified technical English by default for user-facing prose.\nPrefer short sentences, common words, and concrete verbs. State one main action or fact per sentence when practical. Use lists for steps or conditions.\nKeep necessary technical terms, names, commands, code, paths, and exact quoted text unchanged. State uncertainty directly.\nTreat this as clarity guidance, not a claim of formal ASD-STE100 compliance. Preserve a user-requested format, tone, terminology, and necessary precision.\n\nWorking directory: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work\nConversation log: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl\nRecursive agent depth: 0\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nInstalled Python skill modules (pre-imported): `refine`, `compact`, `agent_observe`, `attach_image`, `edit`, `agent_message`, `rlm_heartbeat`, `goal`, `websearch`.\nRead each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.\nEach skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.\nFor targeted existing-file edits, prefer the pre-imported async `edit` skill from the REPL: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.\nAgent messaging is restricted to your parent, siblings, and direct children; roots are siblings, and deeper communication relays through the intermediate child.\nAgent observation is restricted to your parent, siblings, and direct children; roots are siblings, and deeper inspection relays through the intermediate child.\n\nFrom a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm.spawn(...)` still creates a child.\n\nAn `rlm` object is already in your global namespace. `await rlm.spawn('sub-task', name='api-reviewer')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.\n`name` is required: choose a stable child name that is unique among siblings.\nA child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.\nUse `await agent_observe.list_agents()` to discover family, including inactive members, and `await rlm.list_subagents()` to recover direct child handles.\nChildren reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.\nUse `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.\nUse `agent_observe` to inspect a child's rollout. Observation is restricted to your parent, siblings, and direct children; relay through the intermediate child for deeper descendants.\nSpawn independent children in separate calls and end your turn instead of awaiting completion. Multiple replies may arrive over multiple turns. Delete a direct child explicitly with `await rlm.delete_subagent(child)` when it is no longer needed.\n\nThe `ipython` tool is a persistent Python REPL \u2014 the agent's long-lived control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Top-level `await` works directly. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.\n\nPython is the orchestration language: use Python for loops, conditionals, parsing, and state. Use `bash()` to invoke programs, not to write shell programs \u2014 no shell loops or heredocs; do those in Python.\n\nDo not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n\n`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working. Run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n\nImportant: do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.\n\nUse Python for reading, searching, and editing files \u2014 it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.\n\nEach `bash()` call is its own process, so shell state does not persist between calls; use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls.\n\nPython state in the kernel persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.\n\nContinual harness state is available as `rlm.harness` and `rlm.get_harness_state()`. CRUD calls are local to this Prime Agent session by default: `rlm.harness.create_memory(...)`, `rlm.harness.update_memory(...)`, `rlm.harness.delete_memory(...)`, `rlm.harness.create_skill(...)`, `rlm.harness.update_skill(...)`, `rlm.harness.delete_skill(...)`, `rlm.harness.create_subagent(...)`, `rlm.harness.update_subagent(...)`, `rlm.harness.delete_subagent(...)`, `rlm.harness.create_prompt_note(...)`, `rlm.harness.update_prompt_note(...)`, `rlm.harness.delete_prompt_note(...)`, plus `rlm.harness.record_refinement(...)` and `rlm.harness.overview()`. Use `global_=True` only for stable cross-session lessons; Python reserves `global`, so literal `global=True` is invalid syntax.\n\nTerminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n\nRLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm.spawn('sub-task', name='worker')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm.spawn()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.\n\nTreat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n\n# Delegating to sub-agents\n\nSpawn independent, self-contained work with `handle = await rlm.spawn('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.\nAsk for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.\nUse `await rlm.list_subagents()` after kernel restart or compaction.\nLong-running children can report in-flight status with `await rlm.progress_note(...)`; `rlm.list_subagents()` shows each child's activity, latest progress note, and staleness.\nUse `agent_observe` for bounded transcript inspection.\nFan-in results with `await rlm.collect(targets, timeout_ms=0)`: it returns typed snapshots of direct children (status, answer preview, error) without steering anyone; an explicit timeout blocks only that call until the children settle or the deadline passes.\nLarge child outputs belong in files that you read selectively; `collect` snapshots are previews, not full results.\nDelegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\nPersist genuinely reusable delegation patterns with `await refine.run()`.\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/heartbeats-menu/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/websearch/SKILL.md</location>\n </skill>\n</available_skills>"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "You are a general purpose agent that uses code to solve tasks.\nYou solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.\nWhen you are done, stop calling tools and state your final answer.\n\nFor slow or independently completing work, use a nonblocking control loop: start the work, record its handle or output location, then end your turn. A `bash()` handle left running beyond its creating cell sends a completion follow-up; when it arrives, inspect the saved handle and continue. Reading a finished handle's result first cancels that follow-up.\nWhen delegation is available and useful, assign independent substantive tasks to separate workers. Start independent workers without waiting for each one sequentially, and let them run in parallel.\nDo not keep the turn open by polling with `time.sleep()` or shell `sleep`, and do not replace polling with a long blocking `await`. Await only the short operation needed to start work or inspect a result that is already available; otherwise end the turn.\n\nAs the user-facing root agent, when work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n\nUse simplified technical English by default for user-facing prose.\nPrefer short sentences, common words, and concrete verbs. State one main action or fact per sentence when practical. Use lists for steps or conditions.\nKeep necessary technical terms, names, commands, code, paths, and exact quoted text unchanged. State uncertainty directly.\nTreat this as clarity guidance, not a claim of formal ASD-STE100 compliance. Preserve a user-requested format, tone, terminology, and necessary precision.\n\nWorking directory: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work\nConversation log: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl\nRecursive agent depth: 0\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nInstalled Python skill modules (pre-imported): `refine`, `compact`, `agent_observe`, `attach_image`, `edit`, `agent_message`, `rlm_heartbeat`, `goal`, `websearch`.\nRead each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.\nEach skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.\nFor targeted existing-file edits, prefer the pre-imported async `edit` skill from the REPL: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.\nAgent messaging is restricted to your parent, siblings, and direct children; roots are siblings, and deeper communication relays through the intermediate child.\nAgent observation is restricted to your parent, siblings, and direct children; roots are siblings, and deeper inspection relays through the intermediate child.\n\nFrom a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm.spawn(...)` still creates a child.\n\nAn `rlm` object is already in your global namespace. `await rlm.spawn('sub-task', name='api-reviewer')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.\n`name` is required: choose a stable child name that is unique among siblings.\nA child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.\nUse `await agent_observe.list_agents()` to discover family, including inactive members, and `await rlm.list_subagents()` to recover direct child handles.\nChildren reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.\nUse `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.\nUse `agent_observe` to inspect a child's rollout. Observation is restricted to your parent, siblings, and direct children; relay through the intermediate child for deeper descendants.\nSpawn independent children in separate calls and end your turn instead of awaiting completion. Multiple replies may arrive over multiple turns. Delete a direct child explicitly with `await rlm.delete_subagent(child)` when it is no longer needed.\n\nThe `ipython` tool is a persistent Python REPL \u2014 the agent's long-lived control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Top-level `await` works directly. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.\n\nPython is the orchestration language: use Python for loops, conditionals, parsing, and state. Use `bash()` to invoke programs, not to write shell programs \u2014 no shell loops or heredocs; do those in Python.\n\nDo not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n\n`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working. Run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n\nImportant: do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.\n\nUse Python for reading, searching, and editing files \u2014 it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.\n\nEach `bash()` call is its own process, so shell state does not persist between calls; use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls.\n\nPython state in the kernel persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.\n\nContinual harness state is available as `rlm.harness` and `rlm.get_harness_state()`. CRUD calls are local to this Prime Agent session by default: `rlm.harness.create_memory(...)`, `rlm.harness.update_memory(...)`, `rlm.harness.delete_memory(...)`, `rlm.harness.create_skill(...)`, `rlm.harness.update_skill(...)`, `rlm.harness.delete_skill(...)`, `rlm.harness.create_subagent(...)`, `rlm.harness.update_subagent(...)`, `rlm.harness.delete_subagent(...)`, `rlm.harness.create_prompt_note(...)`, `rlm.harness.update_prompt_note(...)`, `rlm.harness.delete_prompt_note(...)`, plus `rlm.harness.record_refinement(...)` and `rlm.harness.overview()`. Use `global_=True` only for stable cross-session lessons; Python reserves `global`, so literal `global=True` is invalid syntax.\n\nTerminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n\nRLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm.spawn('sub-task', name='worker')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm.spawn()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.\n\nTreat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n\n# Delegating to sub-agents\n\nSpawn independent, self-contained work with `handle = await rlm.spawn('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.\nAsk for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.\nUse `await rlm.list_subagents()` after kernel restart or compaction.\nLong-running children can report in-flight status with `await rlm.progress_note(...)`; `rlm.list_subagents()` shows each child's activity, latest progress note, and staleness.\nUse `agent_observe` for bounded transcript inspection.\nFan-in results with `await rlm.collect(targets, timeout_ms=0)`: it returns typed snapshots of direct children (status, answer preview, error) without steering anyone; an explicit timeout blocks only that call until the children settle or the deadline passes.\nLarge child outputs belong in files that you read selectively; `collect` snapshots are previews, not full results.\nDelegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\nPersist genuinely reusable delegation patterns with `await refine.run()`.\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/heartbeats-menu/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/websearch/SKILL.md</location>\n </skill>\n</available_skills>"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}, {"role": "assistant", "content": "heartbeats verifier seed reply"}, {"role": "user", "content": [{"type": "text", "text": "create the agent heartbeat"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "You are a general purpose agent that uses code to solve tasks.\nYou solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.\nWhen you are done, stop calling tools and state your final answer.\n\nFor slow or independently completing work, use a nonblocking control loop: start the work, record its handle or output location, then end your turn. A `bash()` handle left running beyond its creating cell sends a completion follow-up; when it arrives, inspect the saved handle and continue. Reading a finished handle's result first cancels that follow-up.\nWhen delegation is available and useful, assign independent substantive tasks to separate workers. Start independent workers without waiting for each one sequentially, and let them run in parallel.\nDo not keep the turn open by polling with `time.sleep()` or shell `sleep`, and do not replace polling with a long blocking `await`. Await only the short operation needed to start work or inspect a result that is already available; otherwise end the turn.\n\nAs the user-facing root agent, when work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n\nUse simplified technical English by default for user-facing prose.\nPrefer short sentences, common words, and concrete verbs. State one main action or fact per sentence when practical. Use lists for steps or conditions.\nKeep necessary technical terms, names, commands, code, paths, and exact quoted text unchanged. State uncertainty directly.\nTreat this as clarity guidance, not a claim of formal ASD-STE100 compliance. Preserve a user-requested format, tone, terminology, and necessary precision.\n\nWorking directory: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/work\nConversation log: /home/ubuntu/lane-worktrees/heartbeats-menu/scripts/heartbeats-runs/20260921T193051Z/ts/agent/sessions/01a0c573-2c7b-76ad-89e3-7d9b7e33b35f.jsonl\nRecursive agent depth: 0\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nInstalled Python skill modules (pre-imported): `refine`, `compact`, `agent_observe`, `attach_image`, `edit`, `agent_message`, `rlm_heartbeat`, `goal`, `websearch`.\nRead each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.\nEach skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.\nFor targeted existing-file edits, prefer the pre-imported async `edit` skill from the REPL: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.\nAgent messaging is restricted to your parent, siblings, and direct children; roots are siblings, and deeper communication relays through the intermediate child.\nAgent observation is restricted to your parent, siblings, and direct children; roots are siblings, and deeper inspection relays through the intermediate child.\n\nFrom a daemon-backed depth-0 session, use `await rlm.create_session('task', name='researcher')` to start a separate top-level session. The call returns after the daemon creates the session and accepts its first prompt. Inline and nested sessions cannot use it. `rlm.spawn(...)` still creates a child.\n\nAn `rlm` object is already in your global namespace. `await rlm.spawn('sub-task', name='api-reviewer')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.\n`name` is required: choose a stable child name that is unique among siblings.\nA child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.\nUse `await agent_observe.list_agents()` to discover family, including inactive members, and `await rlm.list_subagents()` to recover direct child handles.\nChildren reply explicitly with `await agent_message.send(message, receiver_role='parent')` when an answer is needed. Replies and follow-ups arrive as ordinary agent messages; not every task requires a reply.\nUse `agent_message.send(..., receiver_role='child', receiver_name=child.name)` for follow-ups.\nUse `agent_observe` to inspect a child's rollout. Observation is restricted to your parent, siblings, and direct children; relay through the intermediate child for deeper descendants.\nSpawn independent children in separate calls and end your turn instead of awaiting completion. Multiple replies may arrive over multiple turns. Delete a direct child explicitly with `await rlm.delete_subagent(child)` when it is no longer needed.\n\nThe `ipython` tool is a persistent Python REPL \u2014 the agent's long-lived control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Top-level `await` works directly. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.\n\nPython is the orchestration language: use Python for loops, conditionals, parsing, and state. Use `bash()` to invoke programs, not to write shell programs \u2014 no shell loops or heredocs; do those in Python.\n\nDo not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n\n`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working. Run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n\nImportant: do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.\n\nUse Python for reading, searching, and editing files \u2014 it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.\n\nEach `bash()` call is its own process, so shell state does not persist between calls; use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls.\n\nPython state in the kernel persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.\n\nContinual harness state is available as `rlm.harness` and `rlm.get_harness_state()`. CRUD calls are local to this Prime Agent session by default: `rlm.harness.create_memory(...)`, `rlm.harness.update_memory(...)`, `rlm.harness.delete_memory(...)`, `rlm.harness.create_skill(...)`, `rlm.harness.update_skill(...)`, `rlm.harness.delete_skill(...)`, `rlm.harness.create_subagent(...)`, `rlm.harness.update_subagent(...)`, `rlm.harness.delete_subagent(...)`, `rlm.harness.create_prompt_note(...)`, `rlm.harness.update_prompt_note(...)`, `rlm.harness.delete_prompt_note(...)`, plus `rlm.harness.record_refinement(...)` and `rlm.harness.overview()`. Use `global_=True` only for stable cross-session lessons; Python reserves `global`, so literal `global=True` is invalid syntax.\n\nTerminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n\nRLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm.spawn('sub-task', name='worker')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm.spawn()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.\n\nTreat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n\n# Delegating to sub-agents\n\nSpawn independent, self-contained work with `handle = await rlm.spawn('task', name='worker')`. This returns at admission, not completion; keep the handle to stop or inspect the child later.\nAsk for an explicit reply when needed. A child replies with `await agent_message.send(message, receiver_role='parent')`; parent follow-ups use `receiver_role='child'` plus the child's name or id. Not every message needs a reply.\nUse `await rlm.list_subagents()` after kernel restart or compaction.\nLong-running children can report in-flight status with `await rlm.progress_note(...)`; `rlm.list_subagents()` shows each child's activity, latest progress note, and staleness.\nUse `agent_observe` for bounded transcript inspection.\nFan-in results with `await rlm.collect(targets, timeout_ms=0)`: it returns typed snapshots of direct children (status, answer preview, error) without steering anyone; an explicit timeout blocks only that call until the children settle or the deadline passes.\nLarge child outputs belong in files that you read selectively; `collect` snapshots are previews, not full results.\nDelegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\nPersist genuinely reusable delegation patterns with `await refine.run()`.\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n## /home/ubuntu/lane-worktrees/heartbeats-menu/AGENTS.md\n\n# AGENTS.md\n\nDevelopment rules for prime-agent-rs. Adapted from the codex-rs and prime-agent (TS) repo rules.\nEvery contributor (human or agent) must read this before working on this repo.\n\n## Style and structure\n\n- Workspace crates are prefixed `pa-`. See ARCHITECTURE.md for the hard ownership rules: one owned\n area per crate, pa-types is the only shared crate, cycle-free dependency direction,\n minimal public APIs, no god-modules.\n- Prefer private modules with an explicitly exported public crate API. Internals are `pub(crate)`.\n- Avoid large modules. Target Rust modules under 500 LoC excluding tests. Past ~800 LoC, put new\n functionality in a new module unless there is a strong documented reason not to. Be hardest on\n high-touch orchestration files (session engine, daemon supervisor, TUI app): those attract\n unrelated changes, so split early.\n- When extracting code from a large module, move the related tests and docs with it so invariants\n stay close to the owning code.\n- Inline format args: always prefer `format!(\"{x}\")` over positional.\n- Collapse if statements per clippy::collapsible_if.\n- Prefer method references over closures per clippy::redundant_closure_for_method_calls.\n- Make `match` statements exhaustive; avoid wildcard arms.\n- New traits need doc comments explaining their role and how implementations are expected to behave.\n- No opaque positional `bool`/`Option` parameters (`foo(false)` is unreadable). Prefer enums,\n named methods, or newtypes. If you must pass an opaque literal by position, use an exact\n `/*param_name*/` comment matching the callee signature.\n- Prefer native RPITIT trait methods with explicit `Send` bounds\n (`fn foo(&self) -> impl Future<Output = T> + Send;`) over `#[async_trait]` or\n `#[allow(async_fn_in_trait)]`. Implementations may use `async fn` when they satisfy the contract.\n- No single-use helper methods. Do not create a helper referenced only once.\n- Instrument async work at the definition (`#[tracing::instrument(...)]`), not with\n `.instrument(...)` at call sites. Check whether the callee is already instrumented first.\n\n## Change hygiene\n\n- If you change dependencies (`Cargo.toml`), regenerate/commit `Cargo.lock` in the same change.\n- If a change starts forcing edits across many crate internals, stop and fix the boundary instead.\n- Cache-prefix stability is first-class: never adopt a pattern without checking its effect on the\n cacheable prompt prefix (see MISSION.md; cross-check against ~/codex).\n\n## Tests\n\n- Prefer whole-object equality comparisons over field-by-field checks.\n- Do not add tests for statically defined values.\n- Do not add negative tests for logic that was removed.\n- Verifiers over self-assessment: tmux user-level tests, differential tests against the TS binary\n on PATH, golden corpora replayed against real captured data. No lane merges without its verifier\n passing, rerun by the reviewer where feasible.\n\n## Merge gates\n\n- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,\n `cargo test --workspace` must pass before every merge. Run `make check` (same gates; the GitHub\n token lacks `workflow` scope, so CI is local/PR-review enforced until then).\n- **Parity-diff evidence is a merge gate** (the port's definition, not optional polish): every PR\n that touches a user-visible surface must include a \"parity-diff evidence\" section in its\n description showing the TS-binary comparison for what it changed: (1) rendered output \u2014\n frame-diff vs the TS binary (extend `scripts/visual_parity.py` or the specific harness); \n (2) interactive behavior \u2014 the same input handled identically (keys, mouse, timing); \n (3) wire parity \u2014 byte-compare the TS daemon's traffic for protocol changes; (4) user-visible\n invariants \u2014 every user action produces the same visible reaction as TS (`/compact` shows\n started+completed; `/model` shows the selector; a refinement shows its decoration). A feature\n that \"works\" but was never diffed against the TS binary does not pass review. If TS shows it,\n Rust shows it identically; if Rust shows something TS does not, that is also a parity bug.\n- PRs must state ownership compliance (crate README scope/non-goals/public API, dependency\n direction).\n\n## Adoption telemetry\n\nEvery user-visible feature ships its adoption telemetry event in the same PR as the feature:\nthe event name + properties are added to `docs/telemetry-events.md` (schema versioned), and a\nseam emits it from day one. Telemetry properties never carry prompt, session, or file content\n(primitives only; see `pa-telemetry` and the privacy contract in `docs/telemetry-design.md`).\n\n## Branding\n\nThe product is Prime Agent - we are not a pi fork. Scrub \"pi\"/\"pi-mono\"/\"pi-ai\"/\n\"Prime Intellect\"-style naming from all user-visible surfaces (docs, READMEs,\nCLI help text, error messages, splash/onboarding strings, keybinding hints, TUI\nlabels, and code comments that quote user-facing strings); brand everything\nPrime Agent. Audit with a repo-wide grep and classify every hit (user-visible\nvs wire-internal vs comment) before scrubbing, and list the preserved wire\nidentifiers in the PR body so the reviewer can verify none were wrongly scrubbed.\n\nEXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible with the TS product (e.g. the PI_PACKAGE_DIR env var, settings keys, provider IDs like prime-inference, harness _meta namespaces like ai.primeintellect.prime-agent, lockfile names) stay until/unless the TS side renames them \u2014 PARITY BEATS BRANDING ON THE WIRE.\n\n## References\n\n- TS prime-agent at ~/prime-agent is the parity ground truth (read-only).\n- OpenAI Codex (~/codex, Apache 2.0) is the design reference for agent internals; attribute ports.\n\n- PRs are squash-merged: one commit per PR, subject `scope: summary (#N)` (`gh pr merge --squash`).\n Do not rewrite merged history - the repo is append-only.\n\n\n\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/home/ubuntu/.local/share/prime-agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/skills/websearch/SKILL.md</location>\n </skill>\n</available_skills>"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}, {"role": "assistant", "content": "heartbeats verifier seed reply"}, {"role": "user", "content": [{"type": "text", "text": "create the agent heartbeat"}]}, {"role": "assistant", "content": null, "tool_calls": [{"id": "call_battery_1", "type": "function", "function": {"name": "ipython", "arguments": "{\"code\":\"import rlm_heartbeat\\nawait rlm_heartbeat.create(\\n 'agent heartbeat check instruction',\\n interval='every 30m',\\n label='agent hb',\\n)\\nprint('created')\"}"}}]}, {"role": "tool", "content": "created\n", "tool_call_id": "call_battery_1"}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "qwen/qwen3-30b-a3b-instruct-2507", "messages": [{"role": "system", "content": "You generate a status line for an AI coding agent dashboard. You are given the recent conversation between a user and the agent, plus whether the agent is currently working or idle.\n\nOutput ONLY these two tags, nothing before, between, or after. Do not think out loud, explain, or count words.\n<recap>a present-tense clause, at most 12 words, saying what the agent is doing or just did, no trailing period</recap>\n<status>one of NEEDS_INPUT, COMPLETED</status>\n\nSTATUS meaning:\n- COMPLETED: the agent finished its turn AND the user's request is fully done with nothing left.\n- NEEDS_INPUT: the agent finished its turn but the task is not fully done \u2014 it asked a question, hit a blocker, or needs more prompting.\nWhen you are unsure between COMPLETED and NEEDS_INPUT, choose NEEDS_INPUT.\n\nExample:\n<recap>Refactoring the auth middleware and updating its tests</recap>\n<status>NEEDS_INPUT</status>"}, {"role": "user", "content": [{"type": "text", "text": "<agent-state>idle (finished its turn)</agent-state>\n<conversation>\ncustom: [harness-digest] The persistent memories produced across this session so far: <harness_state> # Continual Harness State Local continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions. The continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters. Default to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual ha\u2026\nuser: verifier seed turn\nassistant: heartbeats verifier seed reply\nuser: create the agent heartbeat\ntoolResult: created\nassistant: agent heartbeat created\n</conversation>"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 400}, "auth": "Bearer sk-battery", "queue": "default"}diff --git a/scripts/heartbeats-runs/20260921T210542Z/findings.json b/scripts/heartbeats-runs/20260921T210542Z/findings.jsondeleted file mode 100644index 4de15e7b96..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/findings.json+++ /dev/null@@ -1,62 +0,0 @@-[- {- "side": "rust",- "ok": true,- "summary": "seed turn ran",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "user heartbeat set through the wire",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "agent heartbeat turn ran",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "wire catalog lists the user and agent heartbeat",- "evidence": "02-wire-catalog.json"- },- {- "side": "rust",- "ok": true,- "summary": "/heartbeats renders the list with both heartbeats",- "evidence": "04-opened.txt"- },- {- "side": "rust",- "ok": true,- "summary": "down navigates to the agent heartbeat and enter opens the TS action pane",- "evidence": "06-actions.txt"- },- {- "side": "rust",- "ok": true,- "summary": "applying the action returns to the list with the paused status",- "evidence": "07-applied.txt"- },- {- "side": "rust",- "ok": true,- "summary": "the pause reached the daemon catalog",- "evidence": "08-applied-catalog.json"- },- {- "side": "rust",- "ok": true,- "summary": "escape closes the view (the transcript returns)",- "evidence": "09-closed.txt"- },- {- "side": "rust",- "ok": true,- "summary": "the tray heartbeat label renders after close",- "evidence": "09-closed.txt"- }-]\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/00-heartbeat-set.json b/scripts/heartbeats-runs/20260921T210542Z/rust/00-heartbeat-set.jsondeleted file mode 100644index 206fa55e8f..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/00-heartbeat-set.json+++ /dev/null@@ -1,29 +0,0 @@-{- "id": "hb-set",- "type": "response",- "command": "heartbeat_set",- "success": true,- "data": {- "heartbeat": {- "id": "d6922d1b-978b-43d1-8438-946d0e3d5c53",- "status": "active",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "36339c62edcc",- "sessionId": "01a0c5c9-f971-70b4-b6c9-262bdf2b87be",- "sessionFile": "/root/hbv6/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonl",- "cwd": "/root/hbv6/20260921T210542Z/rust/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T21:05:43.539Z",- "updatedAt": "2026-09-21T21:05:43.539Z",- "nextRunAt": "2026-09-21T21:35:43.539Z",- "runCount": 0- }- }-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/01-agent-heartbeat-turn.json b/scripts/heartbeats-runs/20260921T210542Z/rust/01-agent-heartbeat-turn.jsondeleted file mode 100644index 48b023caab..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/01-agent-heartbeat-turn.json+++ /dev/null@@ -1,6 +0,0 @@-{- "id": "hb-agent",- "type": "response",- "command": "prompt_and_wait",- "success": true-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/02-wire-catalog.json b/scripts/heartbeats-runs/20260921T210542Z/rust/02-wire-catalog.jsondeleted file mode 100644index bff0c48c54..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/02-wire-catalog.json+++ /dev/null@@ -1,52 +0,0 @@-[- {- "job": {- "id": "d6922d1b-978b-43d1-8438-946d0e3d5c53",- "status": "active",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "36339c62edcc",- "sessionId": "01a0c5c9-f971-70b4-b6c9-262bdf2b87be",- "sessionFile": "/root/hbv6/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonl",- "cwd": "/root/hbv6/20260921T210542Z/rust/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T21:05:43.539Z",- "updatedAt": "2026-09-21T21:05:43.539Z",- "nextRunAt": "2026-09-21T21:35:43.539Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- },- {- "job": {- "id": "a186301f-b0b3-4eec-86ec-765e67e4672c",- "status": "active",- "source": "rlm_heartbeat",- "deliveryMode": "steer",- "activeSessionId": "36339c62edcc",- "sessionId": "01a0c5c9-f971-70b4-b6c9-262bdf2b87be",- "sessionFile": "/root/hbv6/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonl",- "cwd": "/root/hbv6/20260921T210542Z/rust/work",- "label": "agent hb",- "prompt": "agent heartbeat check instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T21:05:44.025Z",- "updatedAt": "2026-09-21T21:05:44.025Z",- "nextRunAt": "2026-09-21T21:35:44.025Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- }-]\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/03-attached.txt b/scripts/heartbeats-runs/20260921T210542Z/rust/03-attached.txtdeleted file mode 100644index 96a30813fc..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/03-attached.txt+++ /dev/null@@ -1,36 +0,0 @@- heartbeats-verifier $0.00-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent v0.1.0- ▗█▛ ▟██▙▄██▛ ▟▛ model mock-1- ▗▟▌ ▐███▛▘▗▄█▖ cwd ~/hbv6/20260921T210542Z/rust/work- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--- verifier seed turn--- heartbeats verifier seed reply--- create the agent heartbeat--- ✓ python · await rlm_heartbeat.create( · ↑ 7 ↓ 1 lines · 3ms-- agent heartbeat created--------- Collapsed mode (Ctrl+O to expand)-- >--← manage 2 heartbeats (Ctrl+R) · mock-1 · 110 (0%)diff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/04-opened.txt b/scripts/heartbeats-runs/20260921T210542Z/rust/04-opened.txtdeleted file mode 100644index b59f23ebd4..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/04-opened.txt+++ /dev/null@@ -1,36 +0,0 @@- heartbeats-verifier $0.00- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent v0.1.0- ▗█▛ ▟██▙▄██▛ ▟▛ model mock-1- ▗▟▌ ▐███▛▘▗▄█▖ cwd ~/hbv6/20260921T210542Z/rust/work- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--- verifier seed turn--- heartbeats verifier seed reply--- create the agent heartbeat--- ✓ python · await rlm_heartbeat.create( · ↑ 7 ↓ 1 lines · 3ms-- agent heartbeat created-- Collapsed mode (Ctrl+O to expand)-────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────- Heartbeats- 2 heartbeats. Select a heartbeat to manage.--› user heartbeat ping instruction active- Created by you · heartbeats-verifier · every 30m · steer- agent hb active- Created by agent · heartbeats-verifier · every 30m · steer-- Created by you · heartbeats-verifier · active · every 30m · steer · next 2026-09-21 21:35 · 0 runs-- Esc close-────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────diff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/05-navigated.txt b/scripts/heartbeats-runs/20260921T210542Z/rust/05-navigated.txtdeleted file mode 100644index 518d45a1ce..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/05-navigated.txt+++ /dev/null@@ -1,36 +0,0 @@- heartbeats-verifier $0.00- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent v0.1.0- ▗█▛ ▟██▙▄██▛ ▟▛ model mock-1- ▗▟▌ ▐███▛▘▗▄█▖ cwd ~/hbv6/20260921T210542Z/rust/work- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--- verifier seed turn--- heartbeats verifier seed reply--- create the agent heartbeat--- ✓ python · await rlm_heartbeat.create( · ↑ 7 ↓ 1 lines · 3ms-- agent heartbeat created-- Collapsed mode (Ctrl+O to expand)-────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────- Heartbeats- 2 heartbeats. Select a heartbeat to manage.-- user heartbeat ping instruction active- Created by you · heartbeats-verifier · every 30m · steer-› agent hb active- Created by agent · heartbeats-verifier · every 30m · steer-- Created by agent · heartbeats-verifier · active · every 30m · steer · next 2026-09-21 21:35 · 0 runs-- Esc close-────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────diff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/06-actions.txt b/scripts/heartbeats-runs/20260921T210542Z/rust/06-actions.txtdeleted file mode 100644index cef453b336..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/06-actions.txt+++ /dev/null@@ -1,36 +0,0 @@- heartbeats-verifier $0.00-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent v0.1.0- ▗█▛ ▟██▙▄██▛ ▟▛ model mock-1- ▗▟▌ ▐███▛▘▗▄█▖ cwd ~/hbv6/20260921T210542Z/rust/work- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--- verifier seed turn--- heartbeats verifier seed reply--- create the agent heartbeat--- ✓ python · await rlm_heartbeat.create( · ↑ 7 ↓ 1 lines · 3ms-- agent heartbeat created-- Collapsed mode (Ctrl+O to expand)-────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────- agent hb- agent heartbeat check instruction-- Created by agent · heartbeats-verifier · active · every 30m · steer · next 2026-09-21 21:35 · 0 runs--› Pause heartbeat Stop deliveries until resumed- Stop heartbeat Permanently remove this heartbeat-- ← back Esc close-────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────diff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/07-applied.txt b/scripts/heartbeats-runs/20260921T210542Z/rust/07-applied.txtdeleted file mode 100644index d9ba9a4dd5..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/07-applied.txt+++ /dev/null@@ -1,36 +0,0 @@- heartbeats-verifier $0.00- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent v0.1.0- ▗█▛ ▟██▙▄██▛ ▟▛ model mock-1- ▗▟▌ ▐███▛▘▗▄█▖ cwd ~/hbv6/20260921T210542Z/rust/work- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--- verifier seed turn--- heartbeats verifier seed reply--- create the agent heartbeat--- ✓ python · await rlm_heartbeat.create( · ↑ 7 ↓ 1 lines · 3ms-- agent heartbeat created-- Collapsed mode (Ctrl+O to expand)-────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────- Heartbeats- 2 heartbeats · 1 paused. Select a heartbeat to manage.-- user heartbeat ping instruction active- Created by you · heartbeats-verifier · every 30m · steer-› agent hb paused- Created by agent · heartbeats-verifier · every 30m · steer-- Created by agent · heartbeats-verifier · paused · every 30m · steer · next — · 0 runs-- Esc close-────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────diff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/08-applied-catalog.json b/scripts/heartbeats-runs/20260921T210542Z/rust/08-applied-catalog.jsondeleted file mode 100644index 74c6c1db05..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/08-applied-catalog.json+++ /dev/null@@ -1,51 +0,0 @@-[- {- "job": {- "id": "d6922d1b-978b-43d1-8438-946d0e3d5c53",- "status": "active",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "36339c62edcc",- "sessionId": "01a0c5c9-f971-70b4-b6c9-262bdf2b87be",- "sessionFile": "/root/hbv6/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonl",- "cwd": "/root/hbv6/20260921T210542Z/rust/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T21:05:43.539Z",- "updatedAt": "2026-09-21T21:05:43.539Z",- "nextRunAt": "2026-09-21T21:35:43.539Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- },- {- "job": {- "id": "a186301f-b0b3-4eec-86ec-765e67e4672c",- "status": "paused",- "source": "rlm_heartbeat",- "deliveryMode": "steer",- "activeSessionId": "36339c62edcc",- "sessionId": "01a0c5c9-f971-70b4-b6c9-262bdf2b87be",- "sessionFile": "/root/hbv6/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonl",- "cwd": "/root/hbv6/20260921T210542Z/rust/work",- "label": "agent hb",- "prompt": "agent heartbeat check instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T21:05:44.025Z",- "updatedAt": "2026-09-21T21:05:51.449Z",- "runCount": 0- },- "sessionName": "heartbeats-verifier",- "firstMessage": "verifier seed turn"- }-]\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/09-closed.txt b/scripts/heartbeats-runs/20260921T210542Z/rust/09-closed.txtdeleted file mode 100644index e7190aab15..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/09-closed.txt+++ /dev/null@@ -1,36 +0,0 @@- heartbeats-verifier $0.00-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent v0.1.0- ▗█▛ ▟██▙▄██▛ ▟▛ model mock-1- ▗▟▌ ▐███▛▘▗▄█▖ cwd ~/hbv6/20260921T210542Z/rust/work- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--- verifier seed turn--- heartbeats verifier seed reply--- create the agent heartbeat--- ✓ python · await rlm_heartbeat.create( · ↑ 7 ↓ 1 lines · 3ms-- agent heartbeat created--------- Collapsed mode (Ctrl+O to expand)-- >--← manage 2 heartbeats · 1 paused (Ctrl+R) · mock-1 · 110 (0%)diff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/auth.json b/scripts/heartbeats-runs/20260921T210542Z/rust/agent/auth.jsondeleted file mode 100644index 9e26dfeeb6..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/auth.json+++ /dev/null@@ -1 +0,0 @@-{}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/daemon-workers/0ad5c08e3360/36339c62edcc.recovery.jsonl b/scripts/heartbeats-runs/20260921T210542Z/rust/agent/daemon-workers/0ad5c08e3360/36339c62edcc.recovery.jsonldeleted file mode 100644index 9deb2933a5..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/daemon-workers/0ad5c08e3360/36339c62edcc.recovery.jsonl+++ /dev/null@@ -1,6 +0,0 @@-{"activeSessionId":"36339c62edcc","sessionId":"01a0c5c9-f971-70b4-b6c9-262bdf2b87be","sessionFile":"/root/hbv6/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonl","busy":true,"operation":"create","recordedAt":"2026-09-21T21:05:43.316Z"}-{"version":1,"type":"queue_snapshot","active_session_id":"36339c62edcc","steering":["verifier seed turn"],"follow_up":[],"recorded_at":"2026-09-21T21:05:43.373Z"}-{"version":1,"type":"queue_snapshot","active_session_id":"36339c62edcc","steering":[],"follow_up":[],"recorded_at":"2026-09-21T21:05:43.536Z"}-{"version":1,"type":"queue_snapshot","active_session_id":"36339c62edcc","steering":["create the agent heartbeat"],"follow_up":[],"recorded_at":"2026-09-21T21:05:43.543Z"}-{"version":1,"type":"queue_snapshot","active_session_id":"36339c62edcc","steering":[],"follow_up":[],"recorded_at":"2026-09-21T21:05:44.111Z"}-{"activeSessionId":"36339c62edcc","sessionId":"01a0c5c9-f971-70b4-b6c9-262bdf2b87be","sessionFile":"/root/hbv6/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonl","busy":false,"operation":"shutdown","recordedAt":"2026-09-21T21:05:55.136Z"}diff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/daemon-workers/0ad5c08e3360/supervisor-config b/scripts/heartbeats-runs/20260921T210542Z/rust/agent/daemon-workers/0ad5c08e3360/supervisor-configdeleted file mode 100644index 633a7342a4..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/daemon-workers/0ad5c08e3360/supervisor-config+++ /dev/null@@ -1,5 +0,0 @@-{- "version": 1,- "socketPath": "/root/hbv6/20260921T210542Z/rust/daemon.sock",- "defaultSessionDir": "/root/hbv6/20260921T210542Z/rust/agent/sessions"-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/logs/daemon.sock.0ad5c08e.log b/scripts/heartbeats-runs/20260921T210542Z/rust/agent/logs/daemon.sock.0ad5c08e.logdeleted file mode 100644index ba81066b14..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/logs/daemon.sock.0ad5c08e.log+++ /dev/null@@ -1,3 +0,0 @@-supervisor started pid 18933-[2026-09-21T21:05:43.209Z] session worker 36339c62edcc registered (epoch 1, pid 18943)-[2026-09-21T21:05:43.319Z] session worker 36339c62edcc re-registered (epoch 2, pid 18943)diff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/models.json b/scripts/heartbeats-runs/20260921T210542Z/rust/agent/models.jsondeleted file mode 100644index f931951fe4..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/models.json+++ /dev/null@@ -1,19 +0,0 @@-{- "providers": {- "prime-inference": {- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:39524/v1",- "apiKey": "sk-battery",- "models": [- {- "id": "mock-1",- "name": "Mock 1",- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:39524/v1",- "contextWindow": 128000,- "maxTokens": 4096- }- ]- }- }-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/prime-inference-models-cache.json b/scripts/heartbeats-runs/20260921T210542Z/rust/agent/prime-inference-models-cache.jsondeleted file mode 100644index 2affae47b1..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/prime-inference-models-cache.json+++ /dev/null@@ -1 +0,0 @@-{"object":"list","data":[{"id":"alibaba/qwen3.5-flash","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.568539+00:00"},"specs":null},{"id":"alibaba/qwen3.7-max","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":3.75,"output_usd_per_mtok":11.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.639598+00:00"},"specs":null},{"id":"alibaba/qwen3.7-plus","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.717208+00:00"},"specs":null},{"id":"alibaba/qwen3.8-flash","object":"model","owned_by":"","created":1789736362,"display_name":null,"pricing":{"input_usd_per_mtok":0.225,"output_usd_per_mtok":0.705,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-18T12:59:22.787469+00:00"},"specs":null},{"id":"anthropic/claude-fable-5","object":"model","owned_by":"","created":1783031626,"display_name":"Claude Fable 5","pricing":{"input_usd_per_mtok":10.0,"output_usd_per_mtok":50.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-02T22:33:46.495072+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-fable-5.1","object":"model","owned_by":"","created":1788556514,"display_name":"Claude Fable 5.1","pricing":{"input_usd_per_mtok":10.0,"output_usd_per_mtok":50.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.113341+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-haiku-4.5","object":"model","owned_by":"","created":1761030860,"display_name":"Claude Haiku 4.5","pricing":{"input_usd_per_mtok":1.0,"output_usd_per_mtok":5.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:20.826034+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-opus-4.1","object":"model","owned_by":"","created":1761157329,"display_name":"Claude Opus 4.1","pricing":{"input_usd_per_mtok":15.0,"output_usd_per_mtok":75.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-22T18:22:09.605939+00:00"},"specs":{"context_window":200000,"max_output_tokens":32000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-opus-4.5","object":"model","owned_by":"","created":1764746904,"display_name":"Claude Opus 4.5","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":25.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-03T07:28:24.760458+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","verbosity"]},{"id":"anthropic/claude-opus-4.6","object":"model","owned_by":"","created":1772938679,"display_name":"Claude Opus 4.6","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":25.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-08T02:57:59.615639+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p","verbosity"]},{"id":"anthropic/claude-opus-4.7","object":"model","owned_by":"","created":1776679634,"display_name":"Claude Opus 4.7","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":25.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-20T10:07:14.028142+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-opus-4.8","object":"model","owned_by":"","created":1780660082,"display_name":"Claude Opus 4.8","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":25.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-05T11:48:02.246650+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-opus-5","object":"model","owned_by":"","created":1784919442,"display_name":"Claude Opus 5","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":25.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-24T18:57:22.868734+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","verbosity"]},{"id":"anthropic/claude-sonnet-4","object":"model","owned_by":"","created":1761029716,"display_name":"Claude Sonnet 4","pricing":{"input_usd_per_mtok":3.0,"output_usd_per_mtok":15.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:16.611551+00:00"},"specs":{"context_window":200000,"max_output_tokens":64000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-sonnet-4.5","object":"model","owned_by":"","created":1759212031,"display_name":"Claude Sonnet 4.5","pricing":{"input_usd_per_mtok":3.0,"output_usd_per_mtok":15.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T06:00:31.866675+00:00"},"specs":{"context_window":1000000,"max_output_tokens":64000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"anthropic/claude-sonnet-4.6","object":"model","owned_by":"","created":1772054770,"display_name":"Claude Sonnet 4.6","pricing":{"input_usd_per_mtok":3.0,"output_usd_per_mtok":15.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:10.104879+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","medium","low"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p","verbosity"]},{"id":"anthropic/claude-sonnet-5","object":"model","owned_by":"","created":1783031448,"display_name":"Claude Sonnet 5","pricing":{"input_usd_per_mtok":2.0,"output_usd_per_mtok":10.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-02T22:30:48.220566+00:00"},"specs":{"context_window":1000000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","stop","structured_outputs","tool_choice","tools","verbosity"]},{"id":"deepseek/deepseek-chat-v3.1","object":"model","owned_by":"","created":1761029725,"display_name":"DeepSeek V3.1","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":1.7,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:25.583563+00:00"},"specs":{"context_window":163840,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v3.1-terminus","object":"model","owned_by":"","created":1759198118,"display_name":"DeepSeek V3.1 Terminus","pricing":{"input_usd_per_mtok":0.27,"output_usd_per_mtok":1.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:08:38.000459+00:00"},"specs":{"context_window":163840,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"deepseek/deepseek-v3.2","object":"model","owned_by":"","created":1764658428,"display_name":"DeepSeek V3.2","pricing":{"input_usd_per_mtok":0.3705,"output_usd_per_mtok":1.1115,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-02T06:53:48.223623+00:00"},"specs":{"context_window":163840,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":false,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v3.2-exp","object":"model","owned_by":"","created":1759198146,"display_name":"DeepSeek V3.2 Exp","pricing":{"input_usd_per_mtok":0.27,"output_usd_per_mtok":0.41,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:09:06.170541+00:00"},"specs":{"context_window":163840,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4.1-flash","object":"model","owned_by":"","created":1789152253,"display_name":"DeepSeek V4.1 Flash","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-11T18:44:13.104931+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-flash","object":"model","owned_by":"","created":1778785963,"display_name":"DeepSeek V4 Flash 0423","pricing":{"input_usd_per_mtok":0.44,"output_usd_per_mtok":1.32,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T19:12:43.449839+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_completion_tokens","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-flash-0731","object":"model","owned_by":"","created":1785777617,"display_name":"DeepSeek V4 Flash 0731","pricing":{"input_usd_per_mtok":0.44,"output_usd_per_mtok":1.32,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T17:20:17.849313+00:00"},"specs":{"context_window":1310720,"max_output_tokens":943718,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"deepseek/deepseek-v4-pro","object":"model","owned_by":"","created":1778785932,"display_name":"DeepSeek V4 Pro 0423","pricing":{"input_usd_per_mtok":1.91,"output_usd_per_mtok":3.83,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T19:12:12.010236+00:00"},"specs":{"context_window":1048576,"max_output_tokens":384000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_completion_tokens","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"google/gemini-2.5-flash","object":"model","owned_by":"","created":1761029715,"display_name":"Gemini 2.5 Flash","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":2.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:15.585176+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65535,"modalities":{"input":["file","image","text","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-2.5-flash-lite","object":"model","owned_by":"","created":1761029721,"display_name":"Gemini 2.5 Flash Lite","pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:21.403298+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65535,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-2.5-pro","object":"model","owned_by":"","created":1761029717,"display_name":"Gemini 2.5 Pro","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:17.621295+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.1-pro-preview","object":"model","owned_by":"","created":1772054806,"display_name":"Gemini 3.1 Pro Preview","pricing":{"input_usd_per_mtok":2.0,"output_usd_per_mtok":12.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:46.169413+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["audio","file","image","text","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.5-flash","object":"model","owned_by":"","created":1781958981,"display_name":"Gemini 3.5 Flash","pricing":{"input_usd_per_mtok":1.5,"output_usd_per_mtok":9.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-20T12:36:21.024091+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.6-flash","object":"model","owned_by":"","created":1784918138,"display_name":"Gemini 3.6 Flash","pricing":{"input_usd_per_mtok":1.5,"output_usd_per_mtok":7.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-24T18:35:38.706927+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.7-flash","object":"model","owned_by":"","created":1787848124,"display_name":"Gemini 3.7 Flash","pricing":{"input_usd_per_mtok":1.35,"output_usd_per_mtok":6.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-27T16:28:44.601830+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3.8-flash","object":"model","owned_by":"","created":1788556514,"display_name":"Gemini 3.8 Flash","pricing":{"input_usd_per_mtok":0.75,"output_usd_per_mtok":3.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.212597+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","video","file","audio"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemini-3-flash-preview","object":"model","owned_by":"","created":1766202374,"display_name":"Gemini 3 Flash Preview","pricing":{"input_usd_per_mtok":0.5,"output_usd_per_mtok":3.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-20T03:46:14.305378+00:00"},"specs":{"context_window":1048576,"max_output_tokens":65536,"modalities":{"input":["text","image","file","audio","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"google/gemma-3-27b-it","object":"model","owned_by":"","created":1761030851,"display_name":"Gemma 3 27B","pricing":{"input_usd_per_mtok":0.119,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:11.952792+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"meta-llama/Llama-3.2-1B-Instruct","object":"model","owned_by":"","created":1771939296,"display_name":"Llama 3.2 1B Instruct","pricing":{"input_usd_per_mtok":0.027,"output_usd_per_mtok":0.201,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T13:21:36.921319+00:00"},"specs":{"context_window":60000,"max_output_tokens":54000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","max_tokens","min_p","presence_penalty","repetition_penalty","seed","stop","temperature","top_k","top_p"]},{"id":"meta-llama/Llama-3.2-3B-Instruct","object":"model","owned_by":"","created":1771939312,"display_name":"Llama 3.2 3B Instruct","pricing":{"input_usd_per_mtok":0.0509,"output_usd_per_mtok":0.335,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T13:21:52.649872+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","seed","stop","structured_outputs","temperature","top_k","top_logprobs","top_p"]},{"id":"meta-llama/llama-3.3-70b-instruct","object":"model","owned_by":"","created":1759196298,"display_name":"Llama 3.3 70B Instruct","pricing":{"input_usd_per_mtok":1.04,"output_usd_per_mtok":2.253,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T01:38:18.545960+00:00"},"specs":{"context_window":131072,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"meta-llama/llama-4-maverick","object":"model","owned_by":"","created":1761030850,"display_name":"Llama 4 Maverick","pricing":{"input_usd_per_mtok":0.35,"output_usd_per_mtok":1.15,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:10.101027+00:00"},"specs":{"context_window":1048576,"max_output_tokens":16384,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m2.5","object":"model","owned_by":"","created":1771374795,"display_name":"MiniMax M2.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-18T00:33:15.739871+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m2.7","object":"model","owned_by":"","created":1775779870,"display_name":"MiniMax M2.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:10.312006+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"minimax/minimax-m3","object":"model","owned_by":"","created":1780311536,"display_name":"MiniMax M3","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-01T10:58:56.335485+00:00"},"specs":{"context_window":1048576,"max_output_tokens":512000,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"mistralai/mistral-large-2512","object":"model","owned_by":"","created":1764689752,"display_name":null,"pricing":{"input_usd_per_mtok":0.5,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-02T15:35:52.296516+00:00"},"specs":null},{"id":"mistralai/mistral-nemo","object":"model","owned_by":"","created":1761030857,"display_name":"Mistral Nemo","pricing":{"input_usd_per_mtok":0.165,"output_usd_per_mtok":0.17,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:17.801302+00:00"},"specs":{"context_window":131072,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"mistralai/mistral-small-2603","object":"model","owned_by":"","created":1775779872,"display_name":"Mistral Small 4","pricing":{"input_usd_per_mtok":0.165,"output_usd_per_mtok":0.66,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:12.604966+00:00"},"specs":{"context_window":262144,"max_output_tokens":209715,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","none"],"default_effort":"high","default_enabled":false,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"mistralai/mixtral-8x22b-instruct","object":"model","owned_by":"","created":1759198003,"display_name":"Mixtral 8x22B Instruct","pricing":{"input_usd_per_mtok":2.2,"output_usd_per_mtok":6.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:06:43.614656+00:00"},"specs":{"context_window":65536,"max_output_tokens":52428,"modalities":{"input":["text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","max_tokens","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"moonshotai/kimi-k2-0905","object":"model","owned_by":"","created":1759907126,"display_name":"Kimi K2 0905","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:26.057085+00:00"},"specs":{"context_window":262144,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"moonshotai/kimi-k2.5","object":"model","owned_by":"","created":1769800671,"display_name":"Kimi K2.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-30T19:17:51.210047+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k2.6","object":"model","owned_by":"","created":1776733288,"display_name":"Kimi K2.6","pricing":{"input_usd_per_mtok":0.95,"output_usd_per_mtok":4.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-21T01:01:28.804384+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k2.7-code","object":"model","owned_by":"","created":1781282432,"display_name":"Kimi K2.7 Code","pricing":{"input_usd_per_mtok":1.9,"output_usd_per_mtok":8.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-12T16:40:32.168235+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"moonshotai/kimi-k3","object":"model","owned_by":"","created":1784248110,"display_name":"Kimi K3","pricing":{"input_usd_per_mtok":3.45,"output_usd_per_mtok":17.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-17T00:28:30.162170+00:00"},"specs":{"context_window":1048576,"max_output_tokens":943718,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"max","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"nvidia/nemotron-3-nano-30b-a3b","object":"model","owned_by":"","created":1775779886,"display_name":"Nemotron 3 Nano 30B A3B","pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.24,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:26.952299+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"openai/gpt-4.1","object":"model","owned_by":"","created":1759401802,"display_name":"GPT-4.1","pricing":{"input_usd_per_mtok":2.0,"output_usd_per_mtok":8.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:22.496353+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4.1-mini","object":"model","owned_by":"","created":1759401806,"display_name":"GPT-4.1 Mini","pricing":{"input_usd_per_mtok":0.4,"output_usd_per_mtok":1.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:26.911016+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4.1-nano","object":"model","owned_by":"","created":1759401808,"display_name":"GPT-4.1 Nano","pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:28.011794+00:00"},"specs":{"context_window":1047576,"max_output_tokens":32768,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["max_completion_tokens","max_tokens","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_p"]},{"id":"openai/gpt-4o","object":"model","owned_by":"","created":1761029734,"display_name":"GPT-4o","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":10.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:34.447350+00:00"},"specs":{"context_window":128000,"max_output_tokens":16384,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_completion_tokens","max_tokens","prediction","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p","web_search_options"]},{"id":"openai/gpt-4o-mini","object":"model","owned_by":"","created":1761029722,"display_name":"GPT-4o-mini","pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T06:55:22.331052+00:00"},"specs":{"context_window":128000,"max_output_tokens":16384,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_completion_tokens","max_tokens","prediction","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p","web_search_options"]},{"id":"openai/gpt-5","object":"model","owned_by":"","created":1759211784,"display_name":"GPT-5","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T05:56:24.831437+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.1","object":"model","owned_by":"","created":1763426084,"display_name":"GPT-5.1","pricing":{"input_usd_per_mtok":1.25,"output_usd_per_mtok":10.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-11-18T00:34:44.949671+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","none"],"default_effort":"none","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.2","object":"model","owned_by":"","created":1765611176,"display_name":"GPT-5.2","pricing":{"input_usd_per_mtok":1.75,"output_usd_per_mtok":14.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-13T07:32:56.544785+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.2-pro","object":"model","owned_by":"","created":1765611177,"display_name":"GPT-5.2 Pro","pricing":{"input_usd_per_mtok":21.0,"output_usd_per_mtok":168.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-13T07:32:57.583455+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["image","text","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.3-codex","object":"model","owned_by":"","created":1772054791,"display_name":"GPT-5.3-Codex","pricing":{"input_usd_per_mtok":1.75,"output_usd_per_mtok":14.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:26:31.496994+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4","object":"model","owned_by":"","created":1773713673,"display_name":"GPT-5.4","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-17T02:14:33.278960+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-mini","object":"model","owned_by":"","created":1775779863,"display_name":"GPT-5.4 Mini","pricing":{"input_usd_per_mtok":0.75,"output_usd_per_mtok":4.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:03.742760+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-nano","object":"model","owned_by":"","created":1775779866,"display_name":"GPT-5.4 Nano","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:06.153745+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.4-pro","object":"model","owned_by":"","created":1773713674,"display_name":"GPT-5.4 Pro","pricing":{"input_usd_per_mtok":30.0,"output_usd_per_mtok":180.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-03-17T02:14:34.995439+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.5","object":"model","owned_by":"","created":1777306094,"display_name":"GPT-5.5","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":30.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-27T16:08:14.065946+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6","object":"model","owned_by":"","created":1783751214,"display_name":null,"pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":30.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:26:54.495544+00:00"},"specs":null},{"id":"openai/gpt-5.6-luna","object":"model","owned_by":"","created":1783751321,"display_name":"GPT-5.6 Luna","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:41.639902+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-luna-pro","object":"model","owned_by":"","created":1783751322,"display_name":"GPT-5.6 Luna Pro","pricing":{"input_usd_per_mtok":1.0,"output_usd_per_mtok":6.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:42.459149+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-sol","object":"model","owned_by":"","created":1783751318,"display_name":"GPT-5.6 Sol","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":30.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:38.262869+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-sol-pro","object":"model","owned_by":"","created":1783751319,"display_name":"GPT-5.6 Sol Pro","pricing":{"input_usd_per_mtok":5.0,"output_usd_per_mtok":30.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:39.039507+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-terra","object":"model","owned_by":"","created":1783751319,"display_name":"GPT-5.6 Terra","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:39.851751+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5.6-terra-pro","object":"model","owned_by":"","created":1783751320,"display_name":"GPT-5.6 Terra Pro","pricing":{"input_usd_per_mtok":2.5,"output_usd_per_mtok":15.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-11T06:28:40.628845+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low","none"],"default_effort":"medium","default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5-mini","object":"model","owned_by":"","created":1759401800,"display_name":"GPT-5 Mini","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":2.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:20.338354+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-5-nano","object":"model","owned_by":"","created":1759401801,"display_name":"GPT-5 Nano","pricing":{"input_usd_per_mtok":0.05,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:21.418908+00:00"},"specs":{"context_window":400000,"max_output_tokens":128000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low","minimal"],"default_effort":"medium","mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-6-astra","object":"model","owned_by":"","created":1788556514,"display_name":"GPT-6 Astra","pricing":{"input_usd_per_mtok":10.0,"output_usd_per_mtok":50.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-09-04T21:15:14.299026+00:00"},"specs":{"context_window":1050000,"max_output_tokens":128000,"modalities":{"input":["file","image","text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","xhigh","high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","max_completion_tokens","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","tool_choice","tools"]},{"id":"openai/gpt-oss-120b","object":"model","owned_by":"","created":1760042083,"display_name":"gpt-oss-120b","pricing":{"input_usd_per_mtok":0.35,"output_usd_per_mtok":0.75,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-09T20:34:43.236004+00:00"},"specs":{"context_window":131072,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_logprobs","top_p"]},{"id":"openai/gpt-oss-20b","object":"model","owned_by":"","created":1761030856,"display_name":"gpt-oss-20b","pricing":{"input_usd_per_mtok":0.07,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:16.897238+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["high","medium","low"],"default_effort":"medium","mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"poolside/laguna-s-2.1","object":"model","owned_by":"","created":1785726826,"display_name":"Laguna S 2.1","pricing":{"input_usd_per_mtok":0.09,"output_usd_per_mtok":0.18,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T03:13:46.654853+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","temperature","tool_choice","tools"]},{"id":"poolside/laguna-xs-2.1","object":"model","owned_by":"","created":1785726826,"display_name":"Laguna XS 2.1","pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.12,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-03T03:13:46.740724+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","temperature","tool_choice","tools"]},{"id":"qwen/qwen3-235b-a22b-2507","object":"model","owned_by":"","created":1759198117,"display_name":"Qwen3 235B A22B Instruct 2507","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-09-30T02:08:37.415647+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-235B-A22B-Instruct-2507","object":"model","owned_by":"","created":1771937600,"display_name":"Qwen3 235B A22B Instruct 2507","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:20.866004+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-235B-A22B-Thinking-2507","object":"model","owned_by":"","created":1771937601,"display_name":"Qwen3 235B A22B Thinking 2507","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":3.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:21.703567+00:00"},"specs":{"context_window":131072,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-30b-a3b-instruct-2507","object":"model","owned_by":"","created":1759401803,"display_name":"Qwen3 30B A3B Instruct 2507","pricing":{"input_usd_per_mtok":0.13,"output_usd_per_mtok":0.52,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-02T10:43:23.646850+00:00"},"specs":{"context_window":262144,"max_output_tokens":32000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-30B-A3B-Thinking-2507","object":"model","owned_by":"","created":1771937592,"display_name":"Qwen3 30B A3B Thinking 2507","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:12.163500+00:00"},"specs":{"context_window":81920,"max_output_tokens":32768,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"Qwen/Qwen3.5-0.8B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.04,"output_usd_per_mtok":0.08,"cache_read_usd_per_mtok":0.036,"cache_write_usd_per_mtok":0.04,"effective_at":"2026-04-27T14:12:40.112195+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-122B-A10B","object":"model","owned_by":"","created":1787974367,"display_name":null,"pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":0.9,"cache_read_usd_per_mtok":0.27,"cache_write_usd_per_mtok":0.3,"effective_at":"2026-08-29T03:32:47.538747+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-2B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.06,"output_usd_per_mtok":0.18,"cache_read_usd_per_mtok":0.054,"cache_write_usd_per_mtok":0.06,"effective_at":"2026-04-27T14:12:40.311797+00:00"},"specs":null},{"id":"qwen/qwen3.5-35b-a3b","object":"model","owned_by":"","created":1778742870,"display_name":"Qwen3.5-35B-A3B","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1.3,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-14T07:14:30.333413+00:00"},"specs":{"context_window":262144,"max_output_tokens":16384,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.5-397b-a17b","object":"model","owned_by":"","created":1775696599,"display_name":"Qwen3.5 397B A17B","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-09T01:03:19.130519+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3.5-4B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.1,"output_usd_per_mtok":0.3,"cache_read_usd_per_mtok":0.09,"cache_write_usd_per_mtok":0.1,"effective_at":"2026-04-27T14:12:40.492113+00:00"},"specs":null},{"id":"Qwen/Qwen3.5-9B","object":"model","owned_by":"","created":1777299160,"display_name":null,"pricing":{"input_usd_per_mtok":0.18,"output_usd_per_mtok":0.54,"cache_read_usd_per_mtok":0.162,"cache_write_usd_per_mtok":0.18,"effective_at":"2026-04-27T14:12:40.664813+00:00"},"specs":null},{"id":"qwen/qwen3.6-27b","object":"model","owned_by":"","created":1779244080,"display_name":"Qwen3.6 27B","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":3.6,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-20T02:28:00.420376+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.6-35b-a3b","object":"model","owned_by":"","created":1778092324,"display_name":"Qwen3.6 35B A3B","pricing":{"input_usd_per_mtok":0.25,"output_usd_per_mtok":1.25,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:32:04.441666+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3.7-flash","object":"model","owned_by":"","created":1785422211,"display_name":"Qwen3.7 Flash","pricing":{"input_usd_per_mtok":0.03,"output_usd_per_mtok":0.13,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-07-30T14:36:51.013707+00:00"},"specs":{"context_window":1000000,"max_output_tokens":65536,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","response_format","seed","temperature","tool_choice","tools","top_logprobs","top_p"]},{"id":"qwen/qwen3-8b","object":"model","owned_by":"","created":1767847988,"display_name":"Qwen3 8B","pricing":{"input_usd_per_mtok":0.117,"output_usd_per_mtok":0.455,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-08T04:53:08.134989+00:00"},"specs":{"context_window":131072,"max_output_tokens":8192,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","response_format","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"qwen/qwen3.8-max","object":"model","owned_by":"","created":1786408084,"display_name":null,"pricing":{"input_usd_per_mtok":2.0,"output_usd_per_mtok":6.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-11T00:28:04.248858+00:00"},"specs":null},{"id":"qwen/qwen3-coder","object":"model","owned_by":"","created":1761030855,"display_name":"Qwen3 Coder 480B A35B","pricing":{"input_usd_per_mtok":0.975,"output_usd_per_mtok":4.875,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:15.022804+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-coder-next","object":"model","owned_by":"","created":1772054821,"display_name":"Qwen3 Coder Next","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-25T21:27:01.126222+00:00"},"specs":{"context_window":262144,"max_output_tokens":235929,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-max","object":"model","owned_by":"","created":1764463224,"display_name":"Qwen3 Max","pricing":{"input_usd_per_mtok":1.2,"output_usd_per_mtok":6.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-11-30T00:40:24.859337+00:00"},"specs":{"context_window":262144,"max_output_tokens":65536,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":false},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","logprobs","max_tokens","presence_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-235b-a22b-instruct","object":"model","owned_by":"","created":1761030856,"display_name":"Qwen3 VL 235B A22B Instruct","pricing":{"input_usd_per_mtok":0.3,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-21T07:14:16.011386+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-235b-a22b-thinking","object":"model","owned_by":"","created":1764830992,"display_name":"Qwen3 VL 235B A22B Thinking","pricing":{"input_usd_per_mtok":0.98,"output_usd_per_mtok":4.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:52.368716+00:00"},"specs":{"context_window":131072,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-30b-a3b-instruct","object":"model","owned_by":"","created":1764830991,"display_name":"Qwen3 VL 30B A3B Instruct","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":0.7,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:51.204281+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","min_p","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"Qwen/Qwen3-VL-30B-A3B-Thinking","object":"model","owned_by":"","created":1771937598,"display_name":"Qwen3 VL 30B A3B Thinking","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":2.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:18.456091+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["text","image"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"qwen/qwen3-vl-8b-instruct","object":"model","owned_by":"","created":1764830989,"display_name":"Qwen3 VL 8B Instruct","pricing":{"input_usd_per_mtok":0.117,"output_usd_per_mtok":0.455,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-12-04T06:49:49.046332+00:00"},"specs":{"context_window":262144,"max_output_tokens":32768,"modalities":{"input":["image","text"],"output":["text"]},"supports_reasoning":false},"supported_parameters":["frequency_penalty","logit_bias","logprobs","max_tokens","presence_penalty","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"x-ai/grok-4.20","object":"model","owned_by":"","created":1775779880,"display_name":"Grok 4.20","pricing":{"input_usd_per_mtok":2.0,"output_usd_per_mtok":6.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:20.257314+00:00"},"specs":{"context_window":2000000,"max_output_tokens":1800000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":false,"mandatory":false},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","response_format","seed","structured_outputs","temperature","tool_choice","tools","top_logprobs","top_p"]},{"id":"x-ai/grok-4.20-multi-agent","object":"model","owned_by":"","created":1775779882,"display_name":"Grok 4.20 Multi-Agent","pricing":{"input_usd_per_mtok":2.0,"output_usd_per_mtok":6.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:22.350470+00:00"},"specs":{"context_window":2000000,"max_output_tokens":1800000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low"],"default_effort":"medium","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","reasoning_effort","response_format","seed","structured_outputs","temperature","top_logprobs","top_p"]},{"id":"x-ai/grok-4.6","object":"model","owned_by":"","created":1787959644,"display_name":"Grok 4.6","pricing":{"input_usd_per_mtok":2.0,"output_usd_per_mtok":6.0,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-28T23:27:24.930899+00:00"},"specs":{"context_window":500000,"max_output_tokens":450000,"modalities":{"input":["text","image","file"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high","medium","low"],"default_effort":"high","default_enabled":true,"mandatory":true},"supported_parameters":["include_reasoning","logprobs","max_tokens","reasoning","reasoning_effort","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"xiaomi/mimo-v2.5","object":"model","owned_by":"","created":1778092300,"display_name":"MiMo-V2.5","pricing":{"input_usd_per_mtok":0.168,"output_usd_per_mtok":0.336,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:31:40.102605+00:00"},"specs":{"context_window":1050000,"max_output_tokens":131072,"modalities":{"input":["text","audio","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"xiaomi/mimo-v2.5-pro","object":"model","owned_by":"","created":1778092285,"display_name":"MiMo-V2.5-Pro","pricing":{"input_usd_per_mtok":0.48024,"output_usd_per_mtok":1.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-05-06T18:31:25.388731+00:00"},"specs":{"context_window":1050000,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-4.5","object":"model","owned_by":"","created":1759907123,"display_name":"GLM 4.5","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:23.880304+00:00"},"specs":{"context_window":131072,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["include_reasoning","max_tokens","reasoning","response_format","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.5-air","object":"model","owned_by":"","created":1759907122,"display_name":"GLM 4.5 Air","pricing":{"input_usd_per_mtok":0.2,"output_usd_per_mtok":1.1,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:22.754541+00:00"},"specs":{"context_window":131072,"max_output_tokens":98304,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","max_tokens","presence_penalty","reasoning","repetition_penalty","seed","stop","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.6","object":"model","owned_by":"","created":1759907125,"display_name":"GLM 4.6","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2025-10-08T07:05:25.067849+00:00"},"specs":{"context_window":204800,"max_output_tokens":16384,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_p"]},{"id":"z-ai/glm-4.7","object":"model","owned_by":"","created":1768006861,"display_name":"GLM 4.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-01-10T01:01:01.166455+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_p"]},{"id":"z-ai/glm-4.7-flash","object":"model","owned_by":"","created":1770082685,"display_name":"GLM 4.7 Flash","pricing":{"input_usd_per_mtok":0.07,"output_usd_per_mtok":0.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-03T01:38:05.842638+00:00"},"specs":{"context_window":200000,"max_output_tokens":117964,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5","object":"model","owned_by":"","created":1771374834,"display_name":"GLM 5","pricing":{"input_usd_per_mtok":1.0,"output_usd_per_mtok":3.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-18T00:33:54.765331+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logprobs","max_tokens","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.1","object":"model","owned_by":"","created":1775779875,"display_name":"GLM 5.1","pricing":{"input_usd_per_mtok":1.4,"output_usd_per_mtok":4.4,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-04-10T00:11:15.012238+00:00"},"specs":{"context_window":204800,"max_output_tokens":128000,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.2","object":"model","owned_by":"","created":1781738425,"display_name":"GLM 5.2","pricing":{"input_usd_per_mtok":1.54,"output_usd_per_mtok":4.84,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-06-17T23:20:25.382141+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["xhigh","high"],"default_effort":"high","default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"z-ai/glm-5.3","object":"model","owned_by":"","created":1787267428,"display_name":"GLM 5.3","pricing":{"input_usd_per_mtok":1.4,"output_usd_per_mtok":4.4,"cache_read_usd_per_mtok":1.26,"cache_write_usd_per_mtok":1.4,"effective_at":"2026-08-20T23:10:28.976971+00:00"},"specs":{"context_window":1048576,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["low","high","max"],"default_effort":"max","default_enabled":true,"mandatory":true},"supported_parameters":["max_tokens","temperature","top_p","tools","tool_choice","reasoning","reasoning_effort"]},{"id":"z-ai/glm-5.3-flash","object":"model","owned_by":"","created":1787848124,"display_name":"GLM 5.3 Flash","pricing":{"input_usd_per_mtok":0.15,"output_usd_per_mtok":0.5,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-08-27T16:28:44.680637+00:00"},"specs":{"context_window":1310720,"max_output_tokens":102400,"modalities":{"input":["text","image","video"],"output":["text"]},"supports_reasoning":true},"reasoning":{"supported_efforts":["max","high","low"],"default_effort":"max","default_enabled":true,"mandatory":true},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","logprobs","max_tokens","min_p","parallel_tool_calls","presence_penalty","reasoning","reasoning_effort","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_k","top_logprobs","top_p"]},{"id":"zai-org/GLM-4.7","object":"model","owned_by":"","created":1771937590,"display_name":"GLM 4.7","pricing":{"input_usd_per_mtok":0.6,"output_usd_per_mtok":2.2,"cache_read_usd_per_mtok":null,"cache_write_usd_per_mtok":null,"effective_at":"2026-02-24T12:53:10.608022+00:00"},"specs":{"context_window":204800,"max_output_tokens":131072,"modalities":{"input":["text"],"output":["text"]},"supports_reasoning":true},"reasoning":{"default_enabled":true,"mandatory":false},"supported_parameters":["frequency_penalty","include_reasoning","logit_bias","max_tokens","min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed","stop","structured_outputs","temperature","tool_choice","tools","top_a","top_k","top_p"]}]}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/session-artifacts/01a0c5c9-f971-70b4-b6c9-262bdf2b87be/kernel-state.dill b/scripts/heartbeats-runs/20260921T210542Z/rust/agent/session-artifacts/01a0c5c9-f971-70b4-b6c9-262bdf2b87be/kernel-state.dilldeleted file mode 100644index 27bf889b8a..0000000000Binary files a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/session-artifacts/01a0c5c9-f971-70b4-b6c9-262bdf2b87be/kernel-state.dill and /dev/null differdiff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/session-artifacts/01a0c5c9-f971-70b4-b6c9-262bdf2b87be/kernel-state.json b/scripts/heartbeats-runs/20260921T210542Z/rust/agent/session-artifacts/01a0c5c9-f971-70b4-b6c9-262bdf2b87be/kernel-state.jsondeleted file mode 100644index 85a093d539..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/session-artifacts/01a0c5c9-f971-70b4-b6c9-262bdf2b87be/kernel-state.json+++ /dev/null@@ -1 +0,0 @@-{"version": 1, "savedNames": ["agent_message", "agent_observe", "goal", "rlm_heartbeat"], "skipped": [{"name": "attach_image", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "compact", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "edit", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "refine", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}, {"name": "websearch", "reason": "TypeError: cannot pickle '_PrimeAgentCallableSkillModule' object"}], "pruned": [], "bytes": 4572, "pythonVersion": "3.11.16", "timestamp": "2026-09-21T21:05:55.094330+00:00"}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/session-artifacts/01a0c5c9-f971-70b4-b6c9-262bdf2b87be/kernel-stderr.log b/scripts/heartbeats-runs/20260921T210542Z/rust/agent/session-artifacts/01a0c5c9-f971-70b4-b6c9-262bdf2b87be/kernel-stderr.logdeleted file mode 100644index e69de29bb2..0000000000diff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/session-artifacts/01a0c5c9-f971-70b4-b6c9-262bdf2b87be/scheduled-jobs.json b/scripts/heartbeats-runs/20260921T210542Z/rust/agent/session-artifacts/01a0c5c9-f971-70b4-b6c9-262bdf2b87be/scheduled-jobs.jsondeleted file mode 100644index 23570c3c13..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/session-artifacts/01a0c5c9-f971-70b4-b6c9-262bdf2b87be/scheduled-jobs.json+++ /dev/null@@ -1,46 +0,0 @@-{- "jobs": [- {- "id": "a186301f-b0b3-4eec-86ec-765e67e4672c",- "status": "paused",- "source": "rlm_heartbeat",- "deliveryMode": "steer",- "activeSessionId": "36339c62edcc",- "sessionId": "01a0c5c9-f971-70b4-b6c9-262bdf2b87be",- "sessionFile": "/root/hbv6/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonl",- "cwd": "/root/hbv6/20260921T210542Z/rust/work",- "label": "agent hb",- "prompt": "agent heartbeat check instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T21:05:44.025Z",- "updatedAt": "2026-09-21T21:05:51.449Z",- "runCount": 0- },- {- "id": "d6922d1b-978b-43d1-8438-946d0e3d5c53",- "status": "active",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "36339c62edcc",- "sessionId": "01a0c5c9-f971-70b4-b6c9-262bdf2b87be",- "sessionFile": "/root/hbv6/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonl",- "cwd": "/root/hbv6/20260921T210542Z/rust/work",- "prompt": "user heartbeat ping instruction",- "schedule": {- "kind": "interval",- "expression": "every 30m",- "intervalMs": 1800000- },- "createdAt": "2026-09-21T21:05:43.539Z",- "updatedAt": "2026-09-21T21:05:43.539Z",- "nextRunAt": "2026-09-21T21:35:43.539Z",- "runCount": 0- }- ],- "dispatches": []-}diff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonl b/scripts/heartbeats-runs/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonldeleted file mode 100644index 0fae17dc06..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonl+++ /dev/null@@ -1,12 +0,0 @@-{"type":"session","version":3,"id":"01a0c5c9-f971-70b4-b6c9-262bdf2b87be","timestamp":"2026-09-21T21:05:43.281Z","cwd":"/root/hbv6/20260921T210542Z/rust/work","rlmDepth":0}-{"type":"model_change","id":"ad822e9e","parentId":null,"timestamp":"2026-09-21T21:05:43.298Z","provider":"prime-inference","modelId":"mock-1"}-{"type":"thinking_level_change","id":"ca2732b8","parentId":"ad822e9e","timestamp":"2026-09-21T21:05:43.298Z","thinkingLevel":"off"}-{"type":"service_tier_change","id":"b1bf7c53","parentId":"ca2732b8","timestamp":"2026-09-21T21:05:43.299Z","serviceTier":"default"}-{"type":"session_state","id":"fea9da7d","parentId":"b1bf7c53","timestamp":"2026-09-21T21:05:43.299Z","state":{"status":"active"}}-{"type":"session_info","id":"de8ef685","parentId":"fea9da7d","timestamp":"2026-09-21T21:05:43.299Z","name":"heartbeats-verifier"}-{"type":"message","id":"c54c148b","parentId":"de8ef685","timestamp":"2026-09-21T21:05:43.390Z","message":{"role":"user","content":[{"type":"text","text":"verifier seed turn"}],"timestamp":1790024743390}}-{"type":"message","id":"05f4996e","parentId":"c54c148b","timestamp":"2026-09-21T21:05:43.490Z","message":{"role":"assistant","content":[{"type":"text","text":"heartbeats verifier seed reply"}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","responseId":"chatcmpl-battery","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790024743459}}-{"type":"message","id":"d9af31a1","parentId":"05f4996e","timestamp":"2026-09-21T21:05:43.559Z","message":{"role":"user","content":[{"type":"text","text":"create the agent heartbeat"}],"timestamp":1790024743559}}-{"type":"message","id":"da0e6113","parentId":"d9af31a1","timestamp":"2026-09-21T21:05:43.696Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"call_battery_1","name":"ipython","arguments":{"code":"import rlm_heartbeat\nawait rlm_heartbeat.create(\n 'agent heartbeat check instruction',\n interval='every 30m',\n label='agent hb',\n)\nprint('created')"}}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","responseId":"chatcmpl-battery","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790024743688}}-{"type":"message","id":"9c431f7e","parentId":"da0e6113","timestamp":"2026-09-21T21:05:44.029Z","message":{"role":"toolResult","toolCallId":"call_battery_1","toolName":"ipython","content":[{"text":"created\n","type":"text"}],"details":{"status":"ok","kernelRestarted":false,"durationMs":3,"stdout":"created\n"},"isError":false,"timestamp":1790024744028}}-{"type":"message","id":"8f299859","parentId":"9c431f7e","timestamp":"2026-09-21T21:05:44.061Z","message":{"role":"assistant","content":[{"type":"text","text":"agent heartbeat created"}],"api":"openai-completions","provider":"prime-inference","model":"mock-1","responseId":"chatcmpl-battery","usage":{"input":20,"output":10,"cacheRead":80,"cacheWrite":0,"totalTokens":110,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"stop","timestamp":1790024744029}}diff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/settings.json b/scripts/heartbeats-runs/20260921T210542Z/rust/agent/settings.jsondeleted file mode 100644index 539978831e..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/settings.json+++ /dev/null@@ -1 +0,0 @@-{"onboardingShown": true, "telemetry": {"noticeShown": true}}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/telemetry.json b/scripts/heartbeats-runs/20260921T210542Z/rust/agent/telemetry.jsondeleted file mode 100644index 292be68e56..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/telemetry.json+++ /dev/null@@ -1,4 +0,0 @@-{- "version": 1,- "installationId": "96052c4c-a079-4eca-8918-bde26ded42a6"-}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/telemetry.jsonl b/scripts/heartbeats-runs/20260921T210542Z/rust/agent/telemetry.jsonldeleted file mode 100644index 7c507cf869..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/agent/telemetry.jsonl+++ /dev/null@@ -1,9 +0,0 @@-{"name":"startup","timestamp":"2026-09-21T21:05:44.256Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"interactive","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"4.4.0","os_product_version":"unknown","duration_ms":3,"phase_timings":{"daemon_ready":3}},"distinct_id":"96052c4c-a079-4eca-8918-bde26ded42a6"}-{"name":"agent command used","timestamp":"2026-09-21T21:05:46.981Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"interactive","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"4.4.0","os_product_version":"unknown","command_name":"heartbeats"},"distinct_id":"96052c4c-a079-4eca-8918-bde26ded42a6"}-{"name":"agent started","timestamp":"2026-09-21T21:05:43.385Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"daemon","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"4.4.0","os_product_version":"unknown","session_id":"dc87af77-d6f2-4c8a-b986-2348863dcd6a","skill_count":11,"python_skill_count":9},"distinct_id":"96052c4c-a079-4eca-8918-bde26ded42a6"}-{"name":"agent run completed","timestamp":"2026-09-21T21:05:43.687Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"daemon","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"4.4.0","os_product_version":"unknown","session_id":"dc87af77-d6f2-4c8a-b986-2348863dcd6a","outcome":"success","duration_ms":31,"visible_ttft_ms":9,"first_model_event_ms":8,"model_latency_ms":9,"max_model_latency_ms":9,"model_call_count":1,"turn_count":1,"tool_call_count":0,"tool_error_count":0,"input_tokens":20,"output_tokens":10,"cache_read_tokens":80,"cache_write_tokens":0,"total_tokens":110,"compaction_count":0,"retry_count":0,"failover_count":0,"provider_category":"prime","model_category":"custom","error_category":null},"distinct_id":"96052c4c-a079-4eca-8918-bde26ded42a6"}-{"name":"kernel bootstrap","timestamp":"2026-09-21T21:05:43.760Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"daemon","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"4.4.0","os_product_version":"unknown","cold":true,"outcome":"success","duration_ms":373},"distinct_id":"96052c4c-a079-4eca-8918-bde26ded42a6"}-{"name":"kernel bootstrap","timestamp":"2026-09-21T21:05:44.023Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"daemon","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"4.4.0","os_product_version":"unknown","cold":true,"outcome":"success","duration_ms":327},"distinct_id":"96052c4c-a079-4eca-8918-bde26ded42a6"}-{"name":"tool executed","timestamp":"2026-09-21T21:05:44.028Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"daemon","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"4.4.0","os_product_version":"unknown","session_id":"dc87af77-d6f2-4c8a-b986-2348863dcd6a","tool_name":"ipython","duration_ms":333,"is_error":false},"distinct_id":"96052c4c-a079-4eca-8918-bde26ded42a6"}-{"name":"agent run completed","timestamp":"2026-09-21T21:05:55.125Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"daemon","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"4.4.0","os_product_version":"unknown","session_id":"dc87af77-d6f2-4c8a-b986-2348863dcd6a","outcome":"success","duration_ms":373,"visible_ttft_ms":348,"first_model_event_ms":7,"model_latency_ms":14,"max_model_latency_ms":8,"model_call_count":2,"turn_count":2,"tool_call_count":1,"tool_error_count":0,"input_tokens":40,"output_tokens":20,"cache_read_tokens":160,"cache_write_tokens":0,"total_tokens":220,"compaction_count":0,"retry_count":0,"failover_count":0,"provider_category":"prime","model_category":"custom","error_category":null},"distinct_id":"96052c4c-a079-4eca-8918-bde26ded42a6"}-{"name":"agent session ended","timestamp":"2026-09-21T21:05:55.125Z","properties":{"version":"0.1.0","schema_version":1,"os_family":"linux","architecture":"x86_64","install_method":"binary","execution_mode":"daemon","libc":"glibc","libc_version":"unknown","cpu_baseline":"avx2","os_release":"4.4.0","os_product_version":"unknown","session_id":"dc87af77-d6f2-4c8a-b986-2348863dcd6a","duration_ms":11740,"prompt_count":2,"run_count":2,"successful_run_count":2,"failed_run_count":0,"aborted_run_count":0,"tool_call_count":2,"compaction_count":0,"model_call_count":3,"input_tokens":60,"output_tokens":30,"cache_read_tokens":240,"cache_write_tokens":0,"total_tokens":330},"distinct_id":"96052c4c-a079-4eca-8918-bde26ded42a6"}diff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/daemon.log b/scripts/heartbeats-runs/20260921T210542Z/rust/daemon.logdeleted file mode 100644index 1c0a3d3a53..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/daemon.log+++ /dev/null@@ -1 +0,0 @@-pa-daemon client connection error: Broken pipe (os error 32)diff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/mock-script.json b/scripts/heartbeats-runs/20260921T210542Z/rust/mock-script.jsondeleted file mode 100644index 85e336d9d6..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/mock-script.json+++ /dev/null@@ -1 +0,0 @@-{"responses": [{"toolCall": {"name": "ipython", "arguments": {"code": "import rlm_heartbeat\nawait rlm_heartbeat.create(\n 'agent heartbeat check instruction',\n interval='every 30m',\n label='agent hb',\n)\nprint('created')"}}}, {"text": "agent heartbeat created"}]}\ No newline at end of filediff --git a/scripts/heartbeats-runs/20260921T210542Z/rust/mock-script.json.requests.jsonl b/scripts/heartbeats-runs/20260921T210542Z/rust/mock-script.json.requests.jsonldeleted file mode 100644index 2f25844b45..0000000000--- a/scripts/heartbeats-runs/20260921T210542Z/rust/mock-script.json.requests.jsonl+++ /dev/null@@ -1,4 +0,0 @@-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "# prime-agent harness\n\nThe prime-agent harness has one tool: `ipython`, a persistent CPython REPL. All other tools are \"programmatic tools\", functions inside the Python REPL called via \"programmatic tool calling\" (PTC). All programmatic tools are async unless described otherwise and can be run in the background. `await` works directly and globally in the REPL.\n\nThe harness often sends messages to the agent. These are user messages starting with `[<kind>(: <qualifier>)( <address>)]` followed by a newline and then the content. They are not user-generated.\n\n## Core tools\n\n- `bash(command: str) -> BashHandle`: synchronous, returns immediately and runs the command in the background; when a command is finished outside the calling `ipython` block, a notification is sent to the agent; each `bash()` call is its own process, so shell state does not persist between calls\n - `BashHandle`:\n - `.pid: int`\n - `.running: bool`\n - `.command: str`\n - `.tail(n: int = 50) -> str`\n - `.output() -> str`\n - `.poll() -> BashResult | None`\n - `.kill(sig: int = SIGTERM, grace: float = 5.0) -> None`: SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive\n - `await handle -> BashResult`: the handle is awaitable even after command completion, so agents can run commands non-blocking and await them after being notified of them finishing\n - `BashResult`\n - `.exit_code: int`\n - `.output: str`\n - `.duration: float`\n- `edit.run(path: str, old_str: str, new_str: str) -> str`: the primary method for editing files. async, exact-unique-match; the `edit` module is callable with the same arguments (`await edit(path=..., old_str=..., new_str=...)`)\n- `websearch.run(query: str, *, max_output: int = 8192, timeout: int | None, num_results: int | None) -> str`: search the web; the `websearch` module is callable with the same arguments\n- `attach_image(*paths: str) -> str`: loads images directly into context if the agent's model is vision-capable, errors otherwise\n\n## Subagents\n\nprime-agent is a recursive harness. Each session builds a tree of agents, starting at depth 0. Each agent up to a user-configured limit can launch subagents. These subagents are persistent, just like the root session. Each agent can communicate with its nuclear family: its singular parent (except for depth 0 sessions which have no parent), its siblings (other subagents under the same parent), and its children (its own subagents).\n\nThe following programmatic tools are available in the REPL for subagent management:\n\n- `rlm.spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None) -> RLMSpawnHandle`: spawns a new subagent one level deeper than the caller; returns immediately; errors when the caller cannot create subagents; if not given, `model` and `thinking` are inherited from the parent; results never arrive as `rlm.spawn()` return values, they arrive only via agent_message; `name` must be unique among the spawned agent's siblings, and be meaningful and descriptive but short\n- `rlm.create_session(prompt: str, name: str | None = None, model: str | None = None, thinking: str | None = None, cwd: str | None = None) -> RLMCreateSessionHandle`: creates another depth-0 session; only available to agents at depth 0 backed by a daemon; returns after the session is successfully created and the first prompt sent\n- `rlm.find_models(query: str = '', limit: int = 8) -> list[RLMModel]`\n- `rlm.list_subagents() -> list[RLMSubagent]`: direct child handles\n- `rlm.delete_subagent(target: str | RLMSubagent) -> RLMSubagent`\n- `rlm.collect(targets=None, *, timeout_ms: int = 0) -> list[RLMChildResult]`: typed snapshots of direct children (status, settled flag, answer preview, error) without steering anyone; `timeout_ms=0` returns a non-blocking snapshot; a positive timeout blocks only this call until the children settle or the deadline passes\n- `rlm.progress_note(message: str) -> dict`: report brief in-flight progress to the parent orchestrator (at most 512 characters, throttled to about one note per 10 seconds); the parent sees notes without needing a reply\n- `RLMSpawnHandle`\n - `rlm_child_id: str`\n - `name: str`\n - `session_dir: Path`\n - `model: str`: provider/model, full resolved model name\n- `RLMCreateSessionHandle`\n - `active_session_id: str`: live daemon-instance id\n - `session_id: str`: durable on-disk session identity\n - `name: str`\n - `session_file: Path`: path to persisted session log\n - `model: str`: provider/model, full resolved model name\n- `RLMSubagent`\n - `rlm_child_id: str`\n - `active_session_id: str | None`\n - `session_id: str | None`\n - `session_name: str`\n - `session_dir: Path`\n - `status: Literal[\"running\", \"completed\", \"error\"]`\n - rows also carry live activity detail (current activity, tool use count, duration, answer preview, latest progress note)\n- `RLMModel`\n - `provider: str`\n - `id: str`\n - `name: str`\n - `selector: str`: the exact string to spawn the model\n\nThe following programmatic tools are available in the REPL for a2a communication:\n\n- `agent_message.send(message: str, *, receiver_role: Literal[\"parent\", \"sibling\", \"child\"], receiver_name: str | None) -> dict`: send a message to the receiver; returns a receipt with the message id and a delivery status (delivered or queued); all root sessions are siblings; `send(\"all\", broadcast_message)` broadcasts to the family roster and returns `{receipts: [...]}`\n- `agent_observe.list_agents() -> dict`: list nuclear family\n- `agent_observe.get_agent(target: str) -> dict`: one agent's status detail\n- `agent_observe.recent_messages(target: str, limit: int = 8, max_chars: int = 800) -> dict`: transcript preview; `limit` errors outside [1-50], `max_chars` outside [80-2000]\n\n## Continual Harness\n\nprime-agent is a continual harness. During a session, persistent memories can be written and read. These stay available even after multiple compactions.\n\nMemories are created by two mechanisms:\n\n- Refinement\n - Mechanism:\n - Another model suggests a refinement based on the transcript\n - The suggested edits are applied to the harness state\n - The main agent is notified by a structured harness message and the applied edits are saved\n - Triggered by:\n - Calling the programmatic tool `refine.run()`\n - By the user command `/refine`\n - Effect:\n - The refinement event is always saved in the harness state's refinement history\n - A harness message is sent to the agent with the refinement result\n- Active memory management by the agent\n - `refine.run(instructions: str | None = None, global_: bool = False) -> dict`: agent-triggered refinement (see above); returns immediately and runs when the current turn ends\n- `refine.status() -> dict`: whether a refinement is already pending for this turn or currently in flight\n - `rlm.harness.create_memory(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: creates a memory; use `global_=True` for cross-session entries (Python reserves `global`, so the parameter is spelled `global_`)\n - `rlm.harness.update_memory(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_memory(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_prompt_note(title: str, content: str, *, id: str | None = None, path: str = \"policy\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_prompt_note(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_prompt_note(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_skill(title: str, content: str, *, id: str | None = None, path: str = \"general\", reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: `reference`/`arguments` describe the Python callable (`reference` requires `{\"type\": \"python\"}`, a Python import, and a callable or call pattern)\n - `rlm.harness.update_skill(id: str, title: str, content: str, *, path: str | None = None, reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_skill(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_subagent(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_subagent(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_subagent(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.record_refinement(trigger: str, changes: list[str], *, evidence: str = \"\", outcome: str = \"\", id: str | None = None, global_: bool = False) -> RefinementEvent`\n - `rlm.harness.plan_refinement(observation: str, *, failing_component: str = \"\", next_step: str = \"\") -> list[str]`: a suggested diagnose -> update -> validate plan\n - `rlm.harness.overview(*, max_entries_per_kind: int = 20, global_: bool = False) -> str`: memory overview\n - `rlm.harness.search(query: str, kind: str | None = None, limit: int = 10, *, global_: bool = False) -> list[HarnessEntry]`: ranked term search over entries\n - `rlm.get_harness_state(state_dir: str | Path | None = None, *, global_: bool = False) -> HarnessState`: full memory details for the selected scope. Can read another agent's `HarnessState` by passing the path to it in `state_dir`\n - `HarnessEntry`\n - `id: str`\n - `kind: Literal[\"prompt\", \"memory\", \"skill\", \"subagent\"]`\n - `title: str`\n - `content: str`\n - `path: str`: category path (\"general\" for memories, \"policy\" for prompt notes)\n - `scope: Literal[\"local\", \"global\"]`\n - `reference: dict[str, Any]`: for skills\n - `arguments: dict[str, Any]`: for skills\n - `metadata: dict`\n - `source: Literal[\"agent\", \"refine\"]`\n - `created_at: str`: ISO timestamp of creation\n - `updated_at: str`: ISO timestamp of latest update\n - `version: int`: increments with every update, starting at 1\n - `HarnessState`\n - `scope: Literal[\"global\", \"local\"]`\n - `file_path: Path`\n - `entries: dict[kind, dict[id, HarnessEntry]]`\n - `refinements: list[RefinementEvent]`\n - `RefinementEvent`\n - `id: str`\n - `trigger: str`: what caused the refinement\n - `changes: list[str]`: applied edits; empty if never edited\n - `evidence: str`\n - `outcome: str`\n - `created_at: str`\n\n## Compaction\n\nprime-agent compacts automatically when there is only a given number of tokens left in the context window (default: 16384), when the user triggers compaction, or when the agent triggers compaction. REPL state persists across compactions, but compaction removes individual variables whose serialized form exceeds 16 MiB.\n\n- `compact.run(instructions: str | None = None) -> dict`: schedule a compaction at the next assistant turn boundary\n- `compact.status() -> dict`: context usage & threshold before auto-compaction\n\n## Goal\n\nIn goal mode prime-agent helps an agent stay on track until a task is fully finished, and handles interruptions and other issues. Goals can be user- or agent-created.\n\n- `goal.create(objective: str, token_budget: int | None = None) -> dict`: create goal and return goal state\n- `goal.get() -> dict`: get goal status (only one goal can be active at a time)\n- `goal.complete() -> dict`: mark goal as completed and get final goal status\n\n## Heartbeat\n\nIn prime-agent, agents can create heartbeats to wake themselves up after a given period of time with remembered instructions, recurrently on a given schedule.\n\n- `rlm_heartbeat.create(instruction: str, interval: str | None = None, label: str | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`: new recurring heartbeat for this session; `interval` is a schedule string (default: every 5 minutes); `delivery_mode`: steer (default) interrupts a busy session's current turn, follow_up waits for it to finish\n- `rlm_heartbeat.list(include_inactive: bool = False) -> dict`\n- `rlm_heartbeat.update(id: str, instruction: str | None = None, interval: str | None = None, label: str | None = None, status: Literal[\"pause\", \"resume\"] | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`\n- `rlm_heartbeat.delete(id: str) -> dict`\n\n## MCP\n\nprime-agent has support for programmatic tools that are defined in the MCP format. Their schema is discovered at runtime.\n\n- `mcp.list_tools(server: str) -> list[dict]`: returns tool schemas\n- `mcp.call_tool(server: str, tool: str, arguments: dict | None = None) -> Any`\n\n## Skills\n\nprime-agent provides multiple executable skills, described by their SKILL.md and executable code. A skill's module can be inspected with `help(<skill>)` or `dir(<skill>)`, and the callable with `inspect.signature(<skill>.<function>)`, if information is missing. The executable code is always pre-imported in the REPL as a programmatic tool, and a callable skill module can be called directly (`await <skill>(...)`).\n\nAll programmatic tools described above except for `bash`, `rlm.*`, and `mcp.*` are implemented as executable skills and will be listed again in the dynamic tail of this prompt. Additional executable and non-executable skills may exist as well; non-executable (markdown) skills are documentation read from disk, and each skill is also available as a shell command by the same name.\n\nThe following are mandatory rules, only to be overridden by clear user intent.\n\n- Memories must be kept lean and up-to-date.\n- `goal.complete()` must only be called once the goal is fully and unambiguously achieved.\n- Goals must only be created at a user's request.\n- Agents run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n- `bash(\"\"\"...\"\"\")` should be used over `bash(\"...\")` because it makes using quotation marks inside bash easy.\n- Bash commands must be run in the background; if they are quick, or the agent is doing other heavy work in the same `ipython` call, they should be awaited or polled in the same `ipython` call interleaved with other work, or a subsequent one; otherwise, the agent should wait for the notification; blocking calls reduce user responsiveness.\n- Shell state does not persist between calls, but agents can use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls through POSIX process inheritance (since each bash call is a fresh process, Python does not inherit environment variables from bash).\n- Edits of existing files must be performed using `edit` with exact old/new strings; if the text contains triple double quotes (\"\"\"), the agent should use triple single-quoted variables or build `old`/`new` from inspected file slices.\n- Agents use Python for reading files and searching in them \u2014 it gives them reusable variables they can slice, filter, and act on without re-reading; using Python variables to find or produce, and to save the strings used in `edit` is also encouraged.\n- Agents always assign read/search results to named variables so they can revisit them later.\n- Agents must report assumptions they made and constants they changed to the user.\n- When an agent is done, they stop calling tools and state their final answer.\n- When delegation is available and useful, an agent assigns independent substantive tasks to separate workers. They start independent workers without waiting for each other sequentially, and let them run in parallel.\n- Agents do not keep the turn open by polling with `time.sleep()` or shell `sleep`, and they do not replace polling with a long blocking `await`. They await only the short operation needed to start work or inspect a result that is already available; otherwise they end the turn.\n- Agents use the Python REPL to keep intermediate variables, inspect and transform outputs, and write small helper functions.\n- Since compaction removes individual variables whose serialized form exceeds 16 MiB, agents can keep large source data on disk and reload it when needed.\n- Python is the orchestration language: agents use Python for loops, conditionals, parsing, and state. They use `bash()` to invoke programs, not to write shell programs, shell loops, or heredocs; those are done directly in Python.\n- Agents do not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Agents evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n- Agents do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, they run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Agents treat failures from that native environment as the relevant result.\n- Rules for root agents (depth 0):\n - Only message siblings if you are certain that it is necessary.\n - When work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n- Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n- Agents treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: they diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. They use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so agents continue working normally after calling it. Agents do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n- Instructions to agents for multi-agent work:\n - When spawning a subagent, keep the handle to stop or inspect the child later.\n - Ask for an explicit reply when needed; not every message needs a reply.\n - Use `await rlm.list_subagents()` after kernel restart or compaction.\n - Have children write files and read those files for fan-in.\n - Delegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\n\nThe following guidelines to agents have been shown to improve results on average. Agents should consider using them where appropriate. Clear user instructions always override these defaults.\n\n- Agents can use the following patterns to make better use of the REPL:\n - Write wrappers around `rlm.spawn` to have quick templates for subagents with arbitrary args: for text to programmatically pass and put into the prompt, for conditional behavior prompts, etc.\n - Use f-strings (`f\"\"\"...\"\"\"` or `f\"...\"`) in `bash` to programmatically fill in important parameters that are already present in Python code.\n- When writing or explaining something:\n - Agents use simplified technical English by default for user-facing prose: short sentences, common words, and concrete verbs; one main action or fact per sentence when practical; lists for steps or conditions. Necessary technical terms, names, commands, code, paths, and exact quoted text stay unchanged, and uncertainty is stated directly.\n - Agents use ordinary or established wording. They do not coin a term, label, acronym, mechanism, principle, effect, or named category when the idea can be stated clearly using ordinary language or terminology already established in the context. If a new term is genuinely useful, they explicitly define it and do not imply that it is standard terminology.\n - Agents keep names and terms consistent. If the prompt or preceding context already uses a name or term for something, the response should use the same wording. Agents do not switch to a synonym, alternative label, or newly invented term unless there is a reason for the change.\n- Agents take care and effort to avoid the following pitfalls while coding:\n - over-engineered solutions\n - overly defensive programming\n - hyper-fixation on rare/fictitious edge cases\n - overlapping subsystem responsibilities\n - solving problems at the wrong architectural layer\n - duplication of sources of truth, then inventing machinery to synchronize them\n - prematurely generalizing one-off flows\n - timeouts on everything\n - production code that exists purely to satisfy tests\n - patching bad premises additively instead of stepping back and deleting or adjusting them\n - tests for magic strings\n - excessive tests\n - comments that describe anything already described by the code\n - comments narrating the coding process instead of supporting the written code\n - fallbacks, legacy support, compatibility shims where not strictly needed; when in doubt, these should be discussed with the user\n - in UI, descriptions on everything\n\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/lane/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/lane/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/lane/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/lane/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/lane/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/lane/skills/websearch/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/lane/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/lane/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/lane/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/lane/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/lane/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n</available_skills>\n\nCurrent date: 2026-09-21\nWorking directory: /root/hbv6/20260921T210542Z/rust/work\nConversation log: /root/hbv6/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonl\nImage input: this model cannot see images; `attach_image` errors for it.\n\nRecursive agent depth: 0 (root)"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "# prime-agent harness\n\nThe prime-agent harness has one tool: `ipython`, a persistent CPython REPL. All other tools are \"programmatic tools\", functions inside the Python REPL called via \"programmatic tool calling\" (PTC). All programmatic tools are async unless described otherwise and can be run in the background. `await` works directly and globally in the REPL.\n\nThe harness often sends messages to the agent. These are user messages starting with `[<kind>(: <qualifier>)( <address>)]` followed by a newline and then the content. They are not user-generated.\n\n## Core tools\n\n- `bash(command: str) -> BashHandle`: synchronous, returns immediately and runs the command in the background; when a command is finished outside the calling `ipython` block, a notification is sent to the agent; each `bash()` call is its own process, so shell state does not persist between calls\n - `BashHandle`:\n - `.pid: int`\n - `.running: bool`\n - `.command: str`\n - `.tail(n: int = 50) -> str`\n - `.output() -> str`\n - `.poll() -> BashResult | None`\n - `.kill(sig: int = SIGTERM, grace: float = 5.0) -> None`: SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive\n - `await handle -> BashResult`: the handle is awaitable even after command completion, so agents can run commands non-blocking and await them after being notified of them finishing\n - `BashResult`\n - `.exit_code: int`\n - `.output: str`\n - `.duration: float`\n- `edit.run(path: str, old_str: str, new_str: str) -> str`: the primary method for editing files. async, exact-unique-match; the `edit` module is callable with the same arguments (`await edit(path=..., old_str=..., new_str=...)`)\n- `websearch.run(query: str, *, max_output: int = 8192, timeout: int | None, num_results: int | None) -> str`: search the web; the `websearch` module is callable with the same arguments\n- `attach_image(*paths: str) -> str`: loads images directly into context if the agent's model is vision-capable, errors otherwise\n\n## Subagents\n\nprime-agent is a recursive harness. Each session builds a tree of agents, starting at depth 0. Each agent up to a user-configured limit can launch subagents. These subagents are persistent, just like the root session. Each agent can communicate with its nuclear family: its singular parent (except for depth 0 sessions which have no parent), its siblings (other subagents under the same parent), and its children (its own subagents).\n\nThe following programmatic tools are available in the REPL for subagent management:\n\n- `rlm.spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None) -> RLMSpawnHandle`: spawns a new subagent one level deeper than the caller; returns immediately; errors when the caller cannot create subagents; if not given, `model` and `thinking` are inherited from the parent; results never arrive as `rlm.spawn()` return values, they arrive only via agent_message; `name` must be unique among the spawned agent's siblings, and be meaningful and descriptive but short\n- `rlm.create_session(prompt: str, name: str | None = None, model: str | None = None, thinking: str | None = None, cwd: str | None = None) -> RLMCreateSessionHandle`: creates another depth-0 session; only available to agents at depth 0 backed by a daemon; returns after the session is successfully created and the first prompt sent\n- `rlm.find_models(query: str = '', limit: int = 8) -> list[RLMModel]`\n- `rlm.list_subagents() -> list[RLMSubagent]`: direct child handles\n- `rlm.delete_subagent(target: str | RLMSubagent) -> RLMSubagent`\n- `rlm.collect(targets=None, *, timeout_ms: int = 0) -> list[RLMChildResult]`: typed snapshots of direct children (status, settled flag, answer preview, error) without steering anyone; `timeout_ms=0` returns a non-blocking snapshot; a positive timeout blocks only this call until the children settle or the deadline passes\n- `rlm.progress_note(message: str) -> dict`: report brief in-flight progress to the parent orchestrator (at most 512 characters, throttled to about one note per 10 seconds); the parent sees notes without needing a reply\n- `RLMSpawnHandle`\n - `rlm_child_id: str`\n - `name: str`\n - `session_dir: Path`\n - `model: str`: provider/model, full resolved model name\n- `RLMCreateSessionHandle`\n - `active_session_id: str`: live daemon-instance id\n - `session_id: str`: durable on-disk session identity\n - `name: str`\n - `session_file: Path`: path to persisted session log\n - `model: str`: provider/model, full resolved model name\n- `RLMSubagent`\n - `rlm_child_id: str`\n - `active_session_id: str | None`\n - `session_id: str | None`\n - `session_name: str`\n - `session_dir: Path`\n - `status: Literal[\"running\", \"completed\", \"error\"]`\n - rows also carry live activity detail (current activity, tool use count, duration, answer preview, latest progress note)\n- `RLMModel`\n - `provider: str`\n - `id: str`\n - `name: str`\n - `selector: str`: the exact string to spawn the model\n\nThe following programmatic tools are available in the REPL for a2a communication:\n\n- `agent_message.send(message: str, *, receiver_role: Literal[\"parent\", \"sibling\", \"child\"], receiver_name: str | None) -> dict`: send a message to the receiver; returns a receipt with the message id and a delivery status (delivered or queued); all root sessions are siblings; `send(\"all\", broadcast_message)` broadcasts to the family roster and returns `{receipts: [...]}`\n- `agent_observe.list_agents() -> dict`: list nuclear family\n- `agent_observe.get_agent(target: str) -> dict`: one agent's status detail\n- `agent_observe.recent_messages(target: str, limit: int = 8, max_chars: int = 800) -> dict`: transcript preview; `limit` errors outside [1-50], `max_chars` outside [80-2000]\n\n## Continual Harness\n\nprime-agent is a continual harness. During a session, persistent memories can be written and read. These stay available even after multiple compactions.\n\nMemories are created by two mechanisms:\n\n- Refinement\n - Mechanism:\n - Another model suggests a refinement based on the transcript\n - The suggested edits are applied to the harness state\n - The main agent is notified by a structured harness message and the applied edits are saved\n - Triggered by:\n - Calling the programmatic tool `refine.run()`\n - By the user command `/refine`\n - Effect:\n - The refinement event is always saved in the harness state's refinement history\n - A harness message is sent to the agent with the refinement result\n- Active memory management by the agent\n - `refine.run(instructions: str | None = None, global_: bool = False) -> dict`: agent-triggered refinement (see above); returns immediately and runs when the current turn ends\n- `refine.status() -> dict`: whether a refinement is already pending for this turn or currently in flight\n - `rlm.harness.create_memory(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: creates a memory; use `global_=True` for cross-session entries (Python reserves `global`, so the parameter is spelled `global_`)\n - `rlm.harness.update_memory(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_memory(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_prompt_note(title: str, content: str, *, id: str | None = None, path: str = \"policy\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_prompt_note(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_prompt_note(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_skill(title: str, content: str, *, id: str | None = None, path: str = \"general\", reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: `reference`/`arguments` describe the Python callable (`reference` requires `{\"type\": \"python\"}`, a Python import, and a callable or call pattern)\n - `rlm.harness.update_skill(id: str, title: str, content: str, *, path: str | None = None, reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_skill(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_subagent(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_subagent(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_subagent(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.record_refinement(trigger: str, changes: list[str], *, evidence: str = \"\", outcome: str = \"\", id: str | None = None, global_: bool = False) -> RefinementEvent`\n - `rlm.harness.plan_refinement(observation: str, *, failing_component: str = \"\", next_step: str = \"\") -> list[str]`: a suggested diagnose -> update -> validate plan\n - `rlm.harness.overview(*, max_entries_per_kind: int = 20, global_: bool = False) -> str`: memory overview\n - `rlm.harness.search(query: str, kind: str | None = None, limit: int = 10, *, global_: bool = False) -> list[HarnessEntry]`: ranked term search over entries\n - `rlm.get_harness_state(state_dir: str | Path | None = None, *, global_: bool = False) -> HarnessState`: full memory details for the selected scope. Can read another agent's `HarnessState` by passing the path to it in `state_dir`\n - `HarnessEntry`\n - `id: str`\n - `kind: Literal[\"prompt\", \"memory\", \"skill\", \"subagent\"]`\n - `title: str`\n - `content: str`\n - `path: str`: category path (\"general\" for memories, \"policy\" for prompt notes)\n - `scope: Literal[\"local\", \"global\"]`\n - `reference: dict[str, Any]`: for skills\n - `arguments: dict[str, Any]`: for skills\n - `metadata: dict`\n - `source: Literal[\"agent\", \"refine\"]`\n - `created_at: str`: ISO timestamp of creation\n - `updated_at: str`: ISO timestamp of latest update\n - `version: int`: increments with every update, starting at 1\n - `HarnessState`\n - `scope: Literal[\"global\", \"local\"]`\n - `file_path: Path`\n - `entries: dict[kind, dict[id, HarnessEntry]]`\n - `refinements: list[RefinementEvent]`\n - `RefinementEvent`\n - `id: str`\n - `trigger: str`: what caused the refinement\n - `changes: list[str]`: applied edits; empty if never edited\n - `evidence: str`\n - `outcome: str`\n - `created_at: str`\n\n## Compaction\n\nprime-agent compacts automatically when there is only a given number of tokens left in the context window (default: 16384), when the user triggers compaction, or when the agent triggers compaction. REPL state persists across compactions, but compaction removes individual variables whose serialized form exceeds 16 MiB.\n\n- `compact.run(instructions: str | None = None) -> dict`: schedule a compaction at the next assistant turn boundary\n- `compact.status() -> dict`: context usage & threshold before auto-compaction\n\n## Goal\n\nIn goal mode prime-agent helps an agent stay on track until a task is fully finished, and handles interruptions and other issues. Goals can be user- or agent-created.\n\n- `goal.create(objective: str, token_budget: int | None = None) -> dict`: create goal and return goal state\n- `goal.get() -> dict`: get goal status (only one goal can be active at a time)\n- `goal.complete() -> dict`: mark goal as completed and get final goal status\n\n## Heartbeat\n\nIn prime-agent, agents can create heartbeats to wake themselves up after a given period of time with remembered instructions, recurrently on a given schedule.\n\n- `rlm_heartbeat.create(instruction: str, interval: str | None = None, label: str | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`: new recurring heartbeat for this session; `interval` is a schedule string (default: every 5 minutes); `delivery_mode`: steer (default) interrupts a busy session's current turn, follow_up waits for it to finish\n- `rlm_heartbeat.list(include_inactive: bool = False) -> dict`\n- `rlm_heartbeat.update(id: str, instruction: str | None = None, interval: str | None = None, label: str | None = None, status: Literal[\"pause\", \"resume\"] | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`\n- `rlm_heartbeat.delete(id: str) -> dict`\n\n## MCP\n\nprime-agent has support for programmatic tools that are defined in the MCP format. Their schema is discovered at runtime.\n\n- `mcp.list_tools(server: str) -> list[dict]`: returns tool schemas\n- `mcp.call_tool(server: str, tool: str, arguments: dict | None = None) -> Any`\n\n## Skills\n\nprime-agent provides multiple executable skills, described by their SKILL.md and executable code. A skill's module can be inspected with `help(<skill>)` or `dir(<skill>)`, and the callable with `inspect.signature(<skill>.<function>)`, if information is missing. The executable code is always pre-imported in the REPL as a programmatic tool, and a callable skill module can be called directly (`await <skill>(...)`).\n\nAll programmatic tools described above except for `bash`, `rlm.*`, and `mcp.*` are implemented as executable skills and will be listed again in the dynamic tail of this prompt. Additional executable and non-executable skills may exist as well; non-executable (markdown) skills are documentation read from disk, and each skill is also available as a shell command by the same name.\n\nThe following are mandatory rules, only to be overridden by clear user intent.\n\n- Memories must be kept lean and up-to-date.\n- `goal.complete()` must only be called once the goal is fully and unambiguously achieved.\n- Goals must only be created at a user's request.\n- Agents run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n- `bash(\"\"\"...\"\"\")` should be used over `bash(\"...\")` because it makes using quotation marks inside bash easy.\n- Bash commands must be run in the background; if they are quick, or the agent is doing other heavy work in the same `ipython` call, they should be awaited or polled in the same `ipython` call interleaved with other work, or a subsequent one; otherwise, the agent should wait for the notification; blocking calls reduce user responsiveness.\n- Shell state does not persist between calls, but agents can use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls through POSIX process inheritance (since each bash call is a fresh process, Python does not inherit environment variables from bash).\n- Edits of existing files must be performed using `edit` with exact old/new strings; if the text contains triple double quotes (\"\"\"), the agent should use triple single-quoted variables or build `old`/`new` from inspected file slices.\n- Agents use Python for reading files and searching in them \u2014 it gives them reusable variables they can slice, filter, and act on without re-reading; using Python variables to find or produce, and to save the strings used in `edit` is also encouraged.\n- Agents always assign read/search results to named variables so they can revisit them later.\n- Agents must report assumptions they made and constants they changed to the user.\n- When an agent is done, they stop calling tools and state their final answer.\n- When delegation is available and useful, an agent assigns independent substantive tasks to separate workers. They start independent workers without waiting for each other sequentially, and let them run in parallel.\n- Agents do not keep the turn open by polling with `time.sleep()` or shell `sleep`, and they do not replace polling with a long blocking `await`. They await only the short operation needed to start work or inspect a result that is already available; otherwise they end the turn.\n- Agents use the Python REPL to keep intermediate variables, inspect and transform outputs, and write small helper functions.\n- Since compaction removes individual variables whose serialized form exceeds 16 MiB, agents can keep large source data on disk and reload it when needed.\n- Python is the orchestration language: agents use Python for loops, conditionals, parsing, and state. They use `bash()` to invoke programs, not to write shell programs, shell loops, or heredocs; those are done directly in Python.\n- Agents do not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Agents evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n- Agents do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, they run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Agents treat failures from that native environment as the relevant result.\n- Rules for root agents (depth 0):\n - Only message siblings if you are certain that it is necessary.\n - When work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n- Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n- Agents treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: they diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. They use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so agents continue working normally after calling it. Agents do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n- Instructions to agents for multi-agent work:\n - When spawning a subagent, keep the handle to stop or inspect the child later.\n - Ask for an explicit reply when needed; not every message needs a reply.\n - Use `await rlm.list_subagents()` after kernel restart or compaction.\n - Have children write files and read those files for fan-in.\n - Delegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\n\nThe following guidelines to agents have been shown to improve results on average. Agents should consider using them where appropriate. Clear user instructions always override these defaults.\n\n- Agents can use the following patterns to make better use of the REPL:\n - Write wrappers around `rlm.spawn` to have quick templates for subagents with arbitrary args: for text to programmatically pass and put into the prompt, for conditional behavior prompts, etc.\n - Use f-strings (`f\"\"\"...\"\"\"` or `f\"...\"`) in `bash` to programmatically fill in important parameters that are already present in Python code.\n- When writing or explaining something:\n - Agents use simplified technical English by default for user-facing prose: short sentences, common words, and concrete verbs; one main action or fact per sentence when practical; lists for steps or conditions. Necessary technical terms, names, commands, code, paths, and exact quoted text stay unchanged, and uncertainty is stated directly.\n - Agents use ordinary or established wording. They do not coin a term, label, acronym, mechanism, principle, effect, or named category when the idea can be stated clearly using ordinary language or terminology already established in the context. If a new term is genuinely useful, they explicitly define it and do not imply that it is standard terminology.\n - Agents keep names and terms consistent. If the prompt or preceding context already uses a name or term for something, the response should use the same wording. Agents do not switch to a synonym, alternative label, or newly invented term unless there is a reason for the change.\n- Agents take care and effort to avoid the following pitfalls while coding:\n - over-engineered solutions\n - overly defensive programming\n - hyper-fixation on rare/fictitious edge cases\n - overlapping subsystem responsibilities\n - solving problems at the wrong architectural layer\n - duplication of sources of truth, then inventing machinery to synchronize them\n - prematurely generalizing one-off flows\n - timeouts on everything\n - production code that exists purely to satisfy tests\n - patching bad premises additively instead of stepping back and deleting or adjusting them\n - tests for magic strings\n - excessive tests\n - comments that describe anything already described by the code\n - comments narrating the coding process instead of supporting the written code\n - fallbacks, legacy support, compatibility shims where not strictly needed; when in doubt, these should be discussed with the user\n - in UI, descriptions on everything\n\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/lane/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/lane/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/lane/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/lane/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/lane/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/lane/skills/websearch/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/lane/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/lane/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/lane/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/lane/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/lane/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n</available_skills>\n\nCurrent date: 2026-09-21\nWorking directory: /root/hbv6/20260921T210542Z/rust/work\nConversation log: /root/hbv6/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonl\nImage input: this model cannot see images; `attach_image` errors for it.\n\nRecursive agent depth: 0 (root)"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}, {"role": "assistant", "content": "heartbeats verifier seed reply"}, {"role": "user", "content": [{"type": "text", "text": "create the agent heartbeat"}]}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "mock-1", "messages": [{"role": "system", "content": "# prime-agent harness\n\nThe prime-agent harness has one tool: `ipython`, a persistent CPython REPL. All other tools are \"programmatic tools\", functions inside the Python REPL called via \"programmatic tool calling\" (PTC). All programmatic tools are async unless described otherwise and can be run in the background. `await` works directly and globally in the REPL.\n\nThe harness often sends messages to the agent. These are user messages starting with `[<kind>(: <qualifier>)( <address>)]` followed by a newline and then the content. They are not user-generated.\n\n## Core tools\n\n- `bash(command: str) -> BashHandle`: synchronous, returns immediately and runs the command in the background; when a command is finished outside the calling `ipython` block, a notification is sent to the agent; each `bash()` call is its own process, so shell state does not persist between calls\n - `BashHandle`:\n - `.pid: int`\n - `.running: bool`\n - `.command: str`\n - `.tail(n: int = 50) -> str`\n - `.output() -> str`\n - `.poll() -> BashResult | None`\n - `.kill(sig: int = SIGTERM, grace: float = 5.0) -> None`: SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive\n - `await handle -> BashResult`: the handle is awaitable even after command completion, so agents can run commands non-blocking and await them after being notified of them finishing\n - `BashResult`\n - `.exit_code: int`\n - `.output: str`\n - `.duration: float`\n- `edit.run(path: str, old_str: str, new_str: str) -> str`: the primary method for editing files. async, exact-unique-match; the `edit` module is callable with the same arguments (`await edit(path=..., old_str=..., new_str=...)`)\n- `websearch.run(query: str, *, max_output: int = 8192, timeout: int | None, num_results: int | None) -> str`: search the web; the `websearch` module is callable with the same arguments\n- `attach_image(*paths: str) -> str`: loads images directly into context if the agent's model is vision-capable, errors otherwise\n\n## Subagents\n\nprime-agent is a recursive harness. Each session builds a tree of agents, starting at depth 0. Each agent up to a user-configured limit can launch subagents. These subagents are persistent, just like the root session. Each agent can communicate with its nuclear family: its singular parent (except for depth 0 sessions which have no parent), its siblings (other subagents under the same parent), and its children (its own subagents).\n\nThe following programmatic tools are available in the REPL for subagent management:\n\n- `rlm.spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None) -> RLMSpawnHandle`: spawns a new subagent one level deeper than the caller; returns immediately; errors when the caller cannot create subagents; if not given, `model` and `thinking` are inherited from the parent; results never arrive as `rlm.spawn()` return values, they arrive only via agent_message; `name` must be unique among the spawned agent's siblings, and be meaningful and descriptive but short\n- `rlm.create_session(prompt: str, name: str | None = None, model: str | None = None, thinking: str | None = None, cwd: str | None = None) -> RLMCreateSessionHandle`: creates another depth-0 session; only available to agents at depth 0 backed by a daemon; returns after the session is successfully created and the first prompt sent\n- `rlm.find_models(query: str = '', limit: int = 8) -> list[RLMModel]`\n- `rlm.list_subagents() -> list[RLMSubagent]`: direct child handles\n- `rlm.delete_subagent(target: str | RLMSubagent) -> RLMSubagent`\n- `rlm.collect(targets=None, *, timeout_ms: int = 0) -> list[RLMChildResult]`: typed snapshots of direct children (status, settled flag, answer preview, error) without steering anyone; `timeout_ms=0` returns a non-blocking snapshot; a positive timeout blocks only this call until the children settle or the deadline passes\n- `rlm.progress_note(message: str) -> dict`: report brief in-flight progress to the parent orchestrator (at most 512 characters, throttled to about one note per 10 seconds); the parent sees notes without needing a reply\n- `RLMSpawnHandle`\n - `rlm_child_id: str`\n - `name: str`\n - `session_dir: Path`\n - `model: str`: provider/model, full resolved model name\n- `RLMCreateSessionHandle`\n - `active_session_id: str`: live daemon-instance id\n - `session_id: str`: durable on-disk session identity\n - `name: str`\n - `session_file: Path`: path to persisted session log\n - `model: str`: provider/model, full resolved model name\n- `RLMSubagent`\n - `rlm_child_id: str`\n - `active_session_id: str | None`\n - `session_id: str | None`\n - `session_name: str`\n - `session_dir: Path`\n - `status: Literal[\"running\", \"completed\", \"error\"]`\n - rows also carry live activity detail (current activity, tool use count, duration, answer preview, latest progress note)\n- `RLMModel`\n - `provider: str`\n - `id: str`\n - `name: str`\n - `selector: str`: the exact string to spawn the model\n\nThe following programmatic tools are available in the REPL for a2a communication:\n\n- `agent_message.send(message: str, *, receiver_role: Literal[\"parent\", \"sibling\", \"child\"], receiver_name: str | None) -> dict`: send a message to the receiver; returns a receipt with the message id and a delivery status (delivered or queued); all root sessions are siblings; `send(\"all\", broadcast_message)` broadcasts to the family roster and returns `{receipts: [...]}`\n- `agent_observe.list_agents() -> dict`: list nuclear family\n- `agent_observe.get_agent(target: str) -> dict`: one agent's status detail\n- `agent_observe.recent_messages(target: str, limit: int = 8, max_chars: int = 800) -> dict`: transcript preview; `limit` errors outside [1-50], `max_chars` outside [80-2000]\n\n## Continual Harness\n\nprime-agent is a continual harness. During a session, persistent memories can be written and read. These stay available even after multiple compactions.\n\nMemories are created by two mechanisms:\n\n- Refinement\n - Mechanism:\n - Another model suggests a refinement based on the transcript\n - The suggested edits are applied to the harness state\n - The main agent is notified by a structured harness message and the applied edits are saved\n - Triggered by:\n - Calling the programmatic tool `refine.run()`\n - By the user command `/refine`\n - Effect:\n - The refinement event is always saved in the harness state's refinement history\n - A harness message is sent to the agent with the refinement result\n- Active memory management by the agent\n - `refine.run(instructions: str | None = None, global_: bool = False) -> dict`: agent-triggered refinement (see above); returns immediately and runs when the current turn ends\n- `refine.status() -> dict`: whether a refinement is already pending for this turn or currently in flight\n - `rlm.harness.create_memory(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: creates a memory; use `global_=True` for cross-session entries (Python reserves `global`, so the parameter is spelled `global_`)\n - `rlm.harness.update_memory(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_memory(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_prompt_note(title: str, content: str, *, id: str | None = None, path: str = \"policy\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_prompt_note(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_prompt_note(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_skill(title: str, content: str, *, id: str | None = None, path: str = \"general\", reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: `reference`/`arguments` describe the Python callable (`reference` requires `{\"type\": \"python\"}`, a Python import, and a callable or call pattern)\n - `rlm.harness.update_skill(id: str, title: str, content: str, *, path: str | None = None, reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_skill(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_subagent(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_subagent(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_subagent(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.record_refinement(trigger: str, changes: list[str], *, evidence: str = \"\", outcome: str = \"\", id: str | None = None, global_: bool = False) -> RefinementEvent`\n - `rlm.harness.plan_refinement(observation: str, *, failing_component: str = \"\", next_step: str = \"\") -> list[str]`: a suggested diagnose -> update -> validate plan\n - `rlm.harness.overview(*, max_entries_per_kind: int = 20, global_: bool = False) -> str`: memory overview\n - `rlm.harness.search(query: str, kind: str | None = None, limit: int = 10, *, global_: bool = False) -> list[HarnessEntry]`: ranked term search over entries\n - `rlm.get_harness_state(state_dir: str | Path | None = None, *, global_: bool = False) -> HarnessState`: full memory details for the selected scope. Can read another agent's `HarnessState` by passing the path to it in `state_dir`\n - `HarnessEntry`\n - `id: str`\n - `kind: Literal[\"prompt\", \"memory\", \"skill\", \"subagent\"]`\n - `title: str`\n - `content: str`\n - `path: str`: category path (\"general\" for memories, \"policy\" for prompt notes)\n - `scope: Literal[\"local\", \"global\"]`\n - `reference: dict[str, Any]`: for skills\n - `arguments: dict[str, Any]`: for skills\n - `metadata: dict`\n - `source: Literal[\"agent\", \"refine\"]`\n - `created_at: str`: ISO timestamp of creation\n - `updated_at: str`: ISO timestamp of latest update\n - `version: int`: increments with every update, starting at 1\n - `HarnessState`\n - `scope: Literal[\"global\", \"local\"]`\n - `file_path: Path`\n - `entries: dict[kind, dict[id, HarnessEntry]]`\n - `refinements: list[RefinementEvent]`\n - `RefinementEvent`\n - `id: str`\n - `trigger: str`: what caused the refinement\n - `changes: list[str]`: applied edits; empty if never edited\n - `evidence: str`\n - `outcome: str`\n - `created_at: str`\n\n## Compaction\n\nprime-agent compacts automatically when there is only a given number of tokens left in the context window (default: 16384), when the user triggers compaction, or when the agent triggers compaction. REPL state persists across compactions, but compaction removes individual variables whose serialized form exceeds 16 MiB.\n\n- `compact.run(instructions: str | None = None) -> dict`: schedule a compaction at the next assistant turn boundary\n- `compact.status() -> dict`: context usage & threshold before auto-compaction\n\n## Goal\n\nIn goal mode prime-agent helps an agent stay on track until a task is fully finished, and handles interruptions and other issues. Goals can be user- or agent-created.\n\n- `goal.create(objective: str, token_budget: int | None = None) -> dict`: create goal and return goal state\n- `goal.get() -> dict`: get goal status (only one goal can be active at a time)\n- `goal.complete() -> dict`: mark goal as completed and get final goal status\n\n## Heartbeat\n\nIn prime-agent, agents can create heartbeats to wake themselves up after a given period of time with remembered instructions, recurrently on a given schedule.\n\n- `rlm_heartbeat.create(instruction: str, interval: str | None = None, label: str | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`: new recurring heartbeat for this session; `interval` is a schedule string (default: every 5 minutes); `delivery_mode`: steer (default) interrupts a busy session's current turn, follow_up waits for it to finish\n- `rlm_heartbeat.list(include_inactive: bool = False) -> dict`\n- `rlm_heartbeat.update(id: str, instruction: str | None = None, interval: str | None = None, label: str | None = None, status: Literal[\"pause\", \"resume\"] | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`\n- `rlm_heartbeat.delete(id: str) -> dict`\n\n## MCP\n\nprime-agent has support for programmatic tools that are defined in the MCP format. Their schema is discovered at runtime.\n\n- `mcp.list_tools(server: str) -> list[dict]`: returns tool schemas\n- `mcp.call_tool(server: str, tool: str, arguments: dict | None = None) -> Any`\n\n## Skills\n\nprime-agent provides multiple executable skills, described by their SKILL.md and executable code. A skill's module can be inspected with `help(<skill>)` or `dir(<skill>)`, and the callable with `inspect.signature(<skill>.<function>)`, if information is missing. The executable code is always pre-imported in the REPL as a programmatic tool, and a callable skill module can be called directly (`await <skill>(...)`).\n\nAll programmatic tools described above except for `bash`, `rlm.*`, and `mcp.*` are implemented as executable skills and will be listed again in the dynamic tail of this prompt. Additional executable and non-executable skills may exist as well; non-executable (markdown) skills are documentation read from disk, and each skill is also available as a shell command by the same name.\n\nThe following are mandatory rules, only to be overridden by clear user intent.\n\n- Memories must be kept lean and up-to-date.\n- `goal.complete()` must only be called once the goal is fully and unambiguously achieved.\n- Goals must only be created at a user's request.\n- Agents run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n- `bash(\"\"\"...\"\"\")` should be used over `bash(\"...\")` because it makes using quotation marks inside bash easy.\n- Bash commands must be run in the background; if they are quick, or the agent is doing other heavy work in the same `ipython` call, they should be awaited or polled in the same `ipython` call interleaved with other work, or a subsequent one; otherwise, the agent should wait for the notification; blocking calls reduce user responsiveness.\n- Shell state does not persist between calls, but agents can use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables \u2014 both persist in the REPL and apply to later `bash()` calls through POSIX process inheritance (since each bash call is a fresh process, Python does not inherit environment variables from bash).\n- Edits of existing files must be performed using `edit` with exact old/new strings; if the text contains triple double quotes (\"\"\"), the agent should use triple single-quoted variables or build `old`/`new` from inspected file slices.\n- Agents use Python for reading files and searching in them \u2014 it gives them reusable variables they can slice, filter, and act on without re-reading; using Python variables to find or produce, and to save the strings used in `edit` is also encouraged.\n- Agents always assign read/search results to named variables so they can revisit them later.\n- Agents must report assumptions they made and constants they changed to the user.\n- When an agent is done, they stop calling tools and state their final answer.\n- When delegation is available and useful, an agent assigns independent substantive tasks to separate workers. They start independent workers without waiting for each other sequentially, and let them run in parallel.\n- Agents do not keep the turn open by polling with `time.sleep()` or shell `sleep`, and they do not replace polling with a long blocking `await`. They await only the short operation needed to start work or inspect a result that is already available; otherwise they end the turn.\n- Agents use the Python REPL to keep intermediate variables, inspect and transform outputs, and write small helper functions.\n- Since compaction removes individual variables whose serialized form exceeds 16 MiB, agents can keep large source data on disk and reload it when needed.\n- Python is the orchestration language: agents use Python for loops, conditionals, parsing, and state. They use `bash()` to invoke programs, not to write shell programs, shell loops, or heredocs; those are done directly in Python.\n- Agents do not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Agents evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n- Agents do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, they run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Agents treat failures from that native environment as the relevant result.\n- Rules for root agents (depth 0):\n - Only message siblings if you are certain that it is necessary.\n - When work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n- Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n- Agents treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: they diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. They use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so agents continue working normally after calling it. Agents do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n- Instructions to agents for multi-agent work:\n - When spawning a subagent, keep the handle to stop or inspect the child later.\n - Ask for an explicit reply when needed; not every message needs a reply.\n - Use `await rlm.list_subagents()` after kernel restart or compaction.\n - Have children write files and read those files for fan-in.\n - Delegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\n\nThe following guidelines to agents have been shown to improve results on average. Agents should consider using them where appropriate. Clear user instructions always override these defaults.\n\n- Agents can use the following patterns to make better use of the REPL:\n - Write wrappers around `rlm.spawn` to have quick templates for subagents with arbitrary args: for text to programmatically pass and put into the prompt, for conditional behavior prompts, etc.\n - Use f-strings (`f\"\"\"...\"\"\"` or `f\"...\"`) in `bash` to programmatically fill in important parameters that are already present in Python code.\n- When writing or explaining something:\n - Agents use simplified technical English by default for user-facing prose: short sentences, common words, and concrete verbs; one main action or fact per sentence when practical; lists for steps or conditions. Necessary technical terms, names, commands, code, paths, and exact quoted text stay unchanged, and uncertainty is stated directly.\n - Agents use ordinary or established wording. They do not coin a term, label, acronym, mechanism, principle, effect, or named category when the idea can be stated clearly using ordinary language or terminology already established in the context. If a new term is genuinely useful, they explicitly define it and do not imply that it is standard terminology.\n - Agents keep names and terms consistent. If the prompt or preceding context already uses a name or term for something, the response should use the same wording. Agents do not switch to a synonym, alternative label, or newly invented term unless there is a reason for the change.\n- Agents take care and effort to avoid the following pitfalls while coding:\n - over-engineered solutions\n - overly defensive programming\n - hyper-fixation on rare/fictitious edge cases\n - overlapping subsystem responsibilities\n - solving problems at the wrong architectural layer\n - duplication of sources of truth, then inventing machinery to synchronize them\n - prematurely generalizing one-off flows\n - timeouts on everything\n - production code that exists purely to satisfy tests\n - patching bad premises additively instead of stepping back and deleting or adjusting them\n - tests for magic strings\n - excessive tests\n - comments that describe anything already described by the code\n - comments narrating the coding process instead of supporting the written code\n - fallbacks, legacy support, compatibility shims where not strictly needed; when in doubt, these should be discussed with the user\n - in UI, descriptions on everything\n\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location>/lane/skills/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location>/lane/skills/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location>/lane/skills/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent's parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location>/lane/skills/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent's parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location>/lane/skills/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location>/lane/skills/websearch/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location>/lane/skills/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location>/lane/skills/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location>/lane/skills/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model's context as a viewable attachment so the model can directly SEE it \u2014 for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image's visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location>/lane/skills/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.</description>\n <location>/lane/skills/rlm-heartbeat/SKILL.md</location>\n </skill>\n</available_skills>\n\nCurrent date: 2026-09-21\nWorking directory: /root/hbv6/20260921T210542Z/rust/work\nConversation log: /root/hbv6/20260921T210542Z/rust/agent/sessions/01a0c5c9-f971-70b4-b6c9-262bdf2b87be.jsonl\nImage input: this model cannot see images; `attach_image` errors for it.\n\nRecursive agent depth: 0 (root)"}, {"role": "user", "content": [{"type": "text", "text": "[harness-digest]\n\nThe persistent memories produced across this session so far:\n\n<harness_state>\n# Continual Harness State\n\nLocal continual harness entries belong to this Prime Agent session. Global continual harness entries persist across Prime Agent sessions.\nThe continual harness entries below are compact summaries, not full descriptions. Use them as routing/context hints; inspect or refine the underlying continual harness entry only when detail matters.\nDefault to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.\nUse these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.\n\nWhen to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed.\n\nCall contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm.spawn('sub-task', name='worker')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.\n\nprompt: 0\n\nmemory: 0\n\nskill: 0\n\nsubagent: 0\n\nNo saved harness entries yet.\n\nrecent refinements: 0\n</harness_state>"}]}, {"role": "user", "content": [{"type": "text", "text": "verifier seed turn"}]}, {"role": "assistant", "content": "heartbeats verifier seed reply"}, {"role": "user", "content": [{"type": "text", "text": "create the agent heartbeat"}]}, {"role": "assistant", "content": null, "tool_calls": [{"id": "call_battery_1", "type": "function", "function": {"name": "ipython", "arguments": "{\"code\":\"import rlm_heartbeat\\nawait rlm_heartbeat.create(\\n 'agent heartbeat check instruction',\\n interval='every 30m',\\n label='agent hb',\\n)\\nprint('created')\"}"}}]}, {"role": "tool", "content": "created\n", "tool_call_id": "call_battery_1"}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 4096, "tools": [{"type": "function", "function": {"name": "ipython", "description": "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.", "parameters": {"type": "object", "required": ["code"], "properties": {"code": {"type": "string", "description": "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports."}}}}}]}, "auth": "Bearer sk-battery", "queue": "default"}-{"path": "/v1/chat/completions", "body": {"model": "qwen/qwen3-30b-a3b-instruct-2507", "messages": [{"role": "system", "content": "You generate a status line for an AI coding agent dashboard. You are given the recent conversation between a user and the agent, plus whether the agent is currently working or idle.\n\nOutput ONLY these two tags, nothing before, between, or after. Do not think out loud, explain, or count words.\n<recap>a present-tense clause, at most 12 words, saying what the agent is doing or just did, no trailing period</recap>\n<status>one of NEEDS_INPUT, COMPLETED</status>\n\nSTATUS meaning:\n- COMPLETED: the agent finished its turn AND the user's request is fully done with nothing left.\n- NEEDS_INPUT: the agent finished its turn but the task is not fully done \u2014 it asked a question, hit a blocker, or needs more prompting.\nWhen you are unsure between COMPLETED and NEEDS_INPUT, choose NEEDS_INPUT.\n\nExample:\n<recap>Refactoring the auth middleware and updating its tests</recap>\n<status>NEEDS_INPUT</status>"}, {"role": "user", "content": "<agent-state>idle (finished its turn)</agent-state>\n<conversation>\nuser: verifier seed turn\nassistant: heartbeats verifier seed reply\nuser: create the agent heartbeat\ntoolResult: created\nassistant: agent heartbeat created\n</conversation>"}], "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 400}, "auth": "Bearer sk-battery", "queue": "default"}diff --git a/scripts/heartbeats_parity.py b/scripts/heartbeats_parity.pydeleted file mode 100644index 08495b7d1a..0000000000--- a/scripts/heartbeats_parity.py+++ /dev/null@@ -1,608 +0,0 @@-#!/usr/bin/env python3-"""Heartbeats-view verifier (lane: heartbeats-menu; extended by the-hb-viewer dogfood lane for unlabeled rows and the tray count).--tmux user-level test driving `/heartbeats` with a user heartbeat (wire-`heartbeat_set`, no label) and two agent heartbeats (kernel-`rlm_heartbeat.create` tool-call turns: one labeled, one unlabeled — the-dogfood repro) registered on the same daemon session, then attaching the-interactive TUI and checking the management surface:-- 1. The tray counts every scoped heartbeat (labeled or not) before the- view is ever opened.- 2. `/heartbeats` opens the view: title, count label, one row per- heartbeat with its status, source labels, schedule; unlabeled rows- identify themselves by their instruction preview (TS- `primary: label || prompt || default name`).- 3. Down navigates the inline list (the selection marker moves).- 4. Enter opens the actions pane (Pause/Resume, Stop with the TS- descriptions).- 5. Enter applies Pause: the view returns to the list and the paused- status shows; the wire catalog confirms the applied status.- 6. Escape closes the view; the tray heartbeat label stays.- 7. The unlabeled agent heartbeat's action pane titles it with the- default name and rides the instruction as the subtitle.--Runs one side at a time (`--side rust` or `--side ts`) so the same steps-produce evidence frames on both products for the parity diff; the-informational tokens (labels, statuses, action names) must match, with the-deliberate style divergence documented: the Rust view is inline-picker-style (the lane directive), TS renders its full-pane overlay.--Usage:- python3 scripts/heartbeats_parity.py --side rust --binary <path> \- --repo <checkout> [--out <dir>]-"""--from __future__ import annotations--import argparse-import json-import shutil-import sys-import time-from datetime import datetime, timezone-from pathlib import Path--REPO = Path(__file__).resolve().parents[1]-sys.path.insert(0, str(REPO / "scripts" / "battery"))-import batterylib as B # noqa: E402--HEARTBEAT_PROMPT = "user heartbeat ping instruction"-AGENT_HB_INSTRUCTION = "agent heartbeat check instruction"-AGENT_HB_LABEL = "agent hb"-AGENT_UNLABELED_INSTRUCTION = "agent unlabeled heartbeat watch instruction"-USER_SCHEDULE = "every 30m"-AGENT_INTERVAL = "every 30m"-SEED_REPLY = "heartbeats verifier seed reply"---class Verifier:- def __init__(self, side_name: str, binary: str, out: Path):- self.name = side_name- self.out = out- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")- self.runid = "hbv" + stamp- root = out / self.name- root.mkdir(parents=True, exist_ok=True)- agent = root / "agent"- work = root / "work"- work.mkdir(parents=True, exist_ok=True)- if agent.exists():- shutil.rmtree(agent)- agent.mkdir(parents=True)- mock = B.MockProvider(root, [])- self._script_mock(mock)- mock.start()- tmpdir = Path("/tmp") / f"{self.runid}-{self.name}"- if tmpdir.exists():- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- self.side = B.Side(- name=side_name,- binary=binary,- root=root,- agent_dir=agent,- work_dir=work,- daemon_socket=root / "daemon.sock",- mock=mock,- )- self.side.env = B.scrubbed_env(agent, tmpdir)- # The Rust binary resolves the kernel runtime through PI_PACKAGE_DIR- # (battery make_side precedent): point it at this checkout.- if side_name == "rust":- self.side.env["PI_PACKAGE_DIR"] = str(REPO)- self.side.env["PRIME_API_KEY"] = "sk-battery"- self.side.write_models_json()- # Suppress first-run overlays (battery suppress_first_run_notices).- settings_path = agent / "settings.json"- settings = json.loads(settings_path.read_text()) if settings_path.exists() else {}- settings["onboardingShown"] = True- settings["telemetry"] = {**(settings.get("telemetry") or {}), "noticeShown": True}- settings_path.write_text(json.dumps(settings))- self.findings: list[dict] = []-- # -- helpers -------------------------------------------------------------- def record(self, summary: str, ok: bool, evidence: str = "") -> None:- self.findings.append(- {"side": self.name, "ok": ok, "summary": summary, "evidence": evidence}- )- print(f"[{'ok ' if ok else 'FAIL'}] {self.name}: {summary}")-- def evidence(self, name: str, text: str) -> Path:- path = self.out / self.name- path.mkdir(parents=True, exist_ok=True)- target = path / name- target.write_text(text)- return target-- def evidence_json(self, name: str, obj) -> Path:- return self.evidence(name, json.dumps(obj, indent=2))-- def ensure_daemon(self) -> None:- try:- probe = B.Wire(self.side.daemon_socket)- probe.close()- return- except (OSError, EOFError):- pass- self.side.start_daemon()-- def settle_frame(self, session: str, quiet_s: float = 2.0, timeout: float = 40.0) -> str:- deadline = time.time() + timeout- last = B.tmux_capture(session)- last_change = time.time()- while time.time() < deadline:- time.sleep(0.5)- frame = B.tmux_capture(session)- if frame != last:- last = frame- last_change = time.time()- elif time.time() - last_change >= quiet_s:- return frame- return last-- def ready(self, session: str, marker: str, timeout: float = 90.0) -> str:- """Wait past first-run notices into the stable ready marker."""- deadline = time.time() + timeout- frame = ""- stable_since: float | None = None- while time.time() < deadline:- frame = B.tmux_capture(session)- if "Share agent traces" in frame:- B.tmux_send(session, "Down")- time.sleep(0.5)- B.tmux_send(session, "Enter")- time.sleep(1.5)- stable_since = None- continue- if marker in frame:- if stable_since is None:- stable_since = time.time()- elif time.time() - stable_since >= 2.0:- return frame- else:- stable_since = None- time.sleep(0.5)- return frame-- def send(self, session: str, keys: str, enter: bool = True) -> None:- frame = B.tmux_capture(session)- if "Share agent traces" in frame:- B.tmux_send(session, "Down")- time.sleep(0.5)- B.tmux_send(session, "Enter")- time.sleep(1.5)- B.tmux_send(session, keys, enter=enter)-- def wait_catalog(self, session_id: str, expect: int, timeout: float = 60.0) -> list | None:- """Poll the wire catalog until `expect` scoped heartbeats list."""- deadline = time.time() + timeout- while time.time() < deadline:- wire = B.Wire(self.side.daemon_socket)- try:- data = wire.request(- "hb-list",- {- "type": "heartbeats_list",- "activeSessionId": session_id,- },- timeout=30,- )- finally:- wire.close()- heartbeats = (data.get("data") or {}).get("heartbeats") or []- if len(heartbeats) >= expect:- return heartbeats- time.sleep(1.0)- return None-- def _script_mock(self, mock) -> None:- """Script the whole run once (before the mock starts): per-turn- queues matched on the turn's prompt, a catch-all queue for the- session-summary model (the wrap-up calls), and an idle default.- Order matters: the later turn's marker is checked first, because- a later conversation's history contains the earlier prompts.- """- mock.set_responses(- [{"text": "battery idle filler"}],- queues=[- {- "name": "session-summary",- "matchModels": ["qwen/qwen3-30b-a3b-instruct-2507"],- "responses": [{"text": "summary filler"}],- },- {- "name": "turn-unlabeled-agent-heartbeat",- "match": ["create the unlabeled agent heartbeat"],- "responses": [- {- "toolCall": {- "name": "ipython",- "arguments": {- "code": (- "import rlm_heartbeat\n"- "await rlm_heartbeat.create(\n"- f" {AGENT_UNLABELED_INSTRUCTION!r},\n"- f" interval={AGENT_INTERVAL!r},\n"- ")\n"- "print('created')\n"- )- },- }- },- {"text": "unlabeled agent heartbeat created"},- ],- },- {- "name": "turn-agent-heartbeat",- "match": ["create the agent heartbeat"],- "responses": [- {- "toolCall": {- "name": "ipython",- "arguments": {- "code": (- "import rlm_heartbeat\n"- "await rlm_heartbeat.create(\n"- f" {AGENT_HB_INSTRUCTION!r},\n"- f" interval={AGENT_INTERVAL!r},\n"- f" label={AGENT_HB_LABEL!r},\n"- ")\n"- "print('created')\n"- )- },- }- },- {"text": "agent heartbeat created"},- ],- },- {- "name": "turn-seed",- "match": ["verifier seed turn"],- "responses": [{"text": SEED_REPLY}],- },- ],- )-- # -- the flow ------------------------------------------------------------- def run(self) -> bool:- self.ensure_daemon()- wire = B.Wire(self.side.daemon_socket)- create = wire.request(- "hb-create",- {- "type": "create",- "name": "heartbeats-verifier",- "config": {- "cwd": str(self.side.work_dir),- "sessionDir": str(self.side.agent_dir / "sessions"),- "provider": "prime-inference",- "model": "mock-1",- "executionMode": "print",- },- },- timeout=120,- )- if create.get("success") is not True:- self.record("daemon create failed: " + json.dumps(create)[:200], ok=False)- wire.close()- return False- session_id = (- (create.get("data") or {}).get("activeSessionId")- or (create.get("data") or {}).get("id")- or ""- )-- seeded = wire.request(- "hb-seed",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": "verifier seed turn",- },- timeout=240,- )- self.record("seed turn ran", seeded.get("success") is True)-- # User heartbeat through the wire (the /heartbeat set arm).- set_reply = wire.request(- "hb-set",- {- "type": "heartbeat_set",- "activeSessionId": session_id,- "schedule": USER_SCHEDULE,- "prompt": HEARTBEAT_PROMPT,- },- timeout=60,- )- self.evidence_json("00-heartbeat-set.json", set_reply)- self.record(- "user heartbeat set through the wire",- set_reply.get("success") is True,- )-- # Agent heartbeat through the kernel: one ipython tool-call turn- # creates an rlm_heartbeat (the rlm-heartbeat skill host request).- # The create tool call rides the turn queue scripted above.- agent_reply = wire.request(- "hb-agent",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": "create the agent heartbeat",- },- timeout=240,- )- self.evidence_json("01-agent-heartbeat-turn.json", agent_reply)- self.record("agent heartbeat turn ran", agent_reply.get("success") is True)-- # The create-without-label path (the dogfood repro): a second agent- # heartbeat with no label. Its row must identify itself by its- # instruction preview (TS `primary: label || prompt || default name`).- # The create tool call rides the turn queue scripted above.- unlabeled_reply = wire.request(- "hb-agent-unlabeled",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": "create the unlabeled agent heartbeat",- },- timeout=240,- )- self.evidence_json("01b-unlabeled-heartbeat-turn.json", unlabeled_reply)- self.record("unlabeled agent heartbeat turn ran", unlabeled_reply.get("success") is True)-- # The wire catalog must now carry all three scoped heartbeats.- catalog = self.wait_catalog(session_id, 3)- self.evidence_json("02-wire-catalog.json", catalog)- sources = sorted(- (entry.get("job") or {}).get("source") or "" for entry in catalog or []- )- self.record(- "wire catalog lists the user and both agent heartbeats",- sources == ["heartbeat", "rlm_heartbeat", "rlm_heartbeat"],- evidence="02-wire-catalog.json",- )- unlabeled_rows = [- entry- for entry in catalog or []- if (entry.get("job") or {}).get("label") in (None, "")- and (entry.get("job") or {}).get("source") == "rlm_heartbeat"- ]- self.record(- "the wire row keeps the unlabeled agent heartbeat unlabeled",- len(unlabeled_rows) == 1,- evidence="02-wire-catalog.json",- )- wire.close()-- # Attach the interactive TUI to the live session.- tmux = f"{self.runid}-{self.name}"- argv = [- self.side.binary,- "--daemon-socket",- str(self.side.daemon_socket),- "--resume",- session_id,- ]- B.tmux_launch(tmux, argv, self.side.env, self.side.work_dir)- frame = self.ready(tmux, ">")- self.evidence("03-attached.txt", frame)-- # The tray counts every scoped heartbeat before the view is ever- # opened (the dogfood repro: unlabeled heartbeats fired on schedule- # while the tray showed none of them).- tray = frame- deadline = time.time() + 20- while time.time() < deadline and "3 heartbeats" not in tray:- time.sleep(0.5)- tray = B.tmux_capture(tmux)- self.evidence("03b-tray.txt", tray)- self.record(- "the tray counts the labeled and unlabeled heartbeats before the view opens",- "3 heartbeats" in tray,- evidence="03b-tray.txt",- )-- # /heartbeats opens the management view.- self.send(tmux, "/heartbeats")- time.sleep(2.5)- opened = B.tmux_capture(tmux)- # Wait for the catalog-driven rows (the fetch is bounded-async).- deadline = time.time() + 20- while time.time() < deadline and HEARTBEAT_PROMPT.split()[0] not in opened:- time.sleep(0.5)- opened = B.tmux_capture(tmux)- self.evidence("04-opened.txt", opened)- checks = {- "title": "Heartbeats" in opened,- "count label": "3 heartbeats" in opened,- "user source": "Created by you" in opened,- "agent source": "Created by agent" in opened,- "schedule": USER_SCHEDULE in opened,- "status": "active" in opened,- "labeled agent row": AGENT_HB_LABEL in opened,- "unlabeled agent row preview": AGENT_UNLABELED_INSTRUCTION in opened,- "unlabeled user row preview": HEARTBEAT_PROMPT in opened,- }- failed = [name for name, ok in checks.items() if not ok]- self.record(- "/heartbeats renders the list with both heartbeats"- + (f" (missing: {', '.join(failed)})" if failed else ""),- not failed,- evidence="04-opened.txt",- )-- # Down navigates the inline list: the selection moves to the second- # row (the marker/highlight is a color change, so the proof is the- # actions pane the next Enter opens: it must target the agent- # heartbeat, the second row, not the first).- self.send(tmux, "Down", enter=False)- time.sleep(0.8)- moved = B.tmux_capture(tmux)- self.evidence("05-navigated.txt", moved)-- # Enter opens the actions pane.- self.send(tmux, "Enter", enter=False)- time.sleep(1.0)- actions = B.tmux_capture(tmux)- self.evidence("06-actions.txt", actions)- action_checks = {- "navigation reached the second row": (- AGENT_HB_LABEL in actions or AGENT_HB_INSTRUCTION in actions- ),- "pause or resume row": ("Pause heartbeat" in actions) or ("Resume heartbeat" in actions),- "stop row": "Stop heartbeat" in actions,- }- failed = [name for name, ok in action_checks.items() if not ok]- self.record(- "down navigates to the agent heartbeat and enter opens the TS action pane"- + (f" (missing: {', '.join(failed)})" if failed else ""),- not failed,- evidence="06-actions.txt",- )-- # Enter applies the pause: the view returns to the list with the- # paused status and the count label carries it.- self.send(tmux, "Enter", enter=False)- time.sleep(2.5)- applied = B.tmux_capture(tmux)- self.evidence("07-applied.txt", applied)- self.record(- "applying the action returns to the list with the paused status",- "paused" in applied and "1 paused" in applied,- evidence="07-applied.txt",- )-- # The wire catalog confirms the applied status (a real mutation, not- # a local-only flip).- paused_catalog = self.wait_catalog_status(session_id, expected_paused=1)- self.evidence_json("08-applied-catalog.json", paused_catalog)- self.record(- "the pause reached the daemon catalog",- paused_catalog is not None,- evidence="08-applied-catalog.json",- )-- # Escape closes the view; the tray heartbeat label stays.- self.send(tmux, "Escape", enter=False)- time.sleep(1.0)- closed = B.tmux_capture(tmux)- self.evidence("09-closed.txt", closed)- self.record(- "escape closes the view (the transcript returns)",- closed != applied,- evidence="09-closed.txt",- )- tray_ok = "3 heartbeats" in closed and "1 paused" in closed- self.record(- "the tray heartbeat label renders after close",- tray_ok,- evidence="09-closed.txt",- )-- # Reopen and inspect the unlabeled agent heartbeat's action pane: the- # title falls back to the default name (TS- # `label?.trim() || defaultHeartbeatName`), the instruction rides as- # the subtitle.- self.send(tmux, "/heartbeats")- time.sleep(2.5)- reopened = B.tmux_capture(tmux)- deadline = time.time() + 20- while time.time() < deadline and AGENT_UNLABELED_INSTRUCTION not in reopened:- time.sleep(0.5)- reopened = B.tmux_capture(tmux)- self.send(tmux, "Down", enter=False)- time.sleep(0.8)- self.send(tmux, "Down", enter=False)- time.sleep(0.8)- self.send(tmux, "Enter", enter=False)- time.sleep(1.0)- unlabeled_actions = B.tmux_capture(tmux)- self.evidence("10-unlabeled-actions.txt", unlabeled_actions)- unlabeled_checks = {- "default-name title": "Agent-created heartbeat" in unlabeled_actions,- "instruction subtitle": AGENT_UNLABELED_INSTRUCTION in unlabeled_actions,- "pause or resume row": (- "Pause heartbeat" in unlabeled_actions- )- or ("Resume heartbeat" in unlabeled_actions),- }- failed = [name for name, ok in unlabeled_checks.items() if not ok]- self.record(- "the unlabeled heartbeat's action pane names it by the default name with the instruction subtitle"- + (f" (missing: {', '.join(failed)})" if failed else ""),- not failed,- evidence="10-unlabeled-actions.txt",- )-- B.tmux_kill(tmux)- ok = all(f["ok"] for f in self.findings)- return ok-- def wait_catalog_status(self, session_id: str, expected_paused: int, timeout: float = 30.0):- deadline = time.time() + timeout- while time.time() < deadline:- wire = B.Wire(self.side.daemon_socket)- try:- data = wire.request(- "hb-status",- {"type": "heartbeats_list", "activeSessionId": session_id},- timeout=30,- )- finally:- wire.close()- heartbeats = (data.get("data") or {}).get("heartbeats") or []- paused = [- entry- for entry in heartbeats- if (entry.get("job") or {}).get("status") == "paused"- ]- if len(paused) == expected_paused:- return heartbeats- time.sleep(1.0)- return None-- def stop(self) -> None:- try:- wire = B.Wire(self.side.daemon_socket)- wire.send_command("sd", {"type": "shutdown"})- wire.close()- time.sleep(2)- except Exception:- pass- B.reap_daemons(socket_paths=[self.side.daemon_socket], needles=[str(self.side.daemon_socket)])- self.side.mock.stop()- if self.side.daemon_proc and self.side.daemon_proc.poll() is None:- self.side.daemon_proc.terminate()---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--side", choices=["rust", "ts"], required=True)- parser.add_argument("--binary", required=True)- parser.add_argument("--repo", default=str(REPO))- parser.add_argument("--out", default=str(REPO / "scripts" / "heartbeats-runs"))- args = parser.parse_args()-- globals()["REPO"] = Path(args.repo).resolve()-- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")- out = Path(args.out) / stamp- out.mkdir(parents=True, exist_ok=True)- verifier = Verifier(args.side, args.binary, out)- ok = False- try:- ok = verifier.run()- finally:- verifier.stop()- (out / "findings.json").write_text(json.dumps(verifier.findings, indent=2))- print(f"\n{'PASS' if ok else 'FAIL'} — evidence: {out / args.side}")- return 0 if ok else 1---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/info_commands_parity.py b/scripts/info_commands_parity.pydeleted file mode 100644index 8934f1884f..0000000000--- a/scripts/info_commands_parity.py+++ /dev/null@@ -1,553 +0,0 @@-#!/usr/bin/env python3-"""Info-command parity verifier: frame-diff the Rust interactive client-against the installed TS prime-agent binary on the SAME resumed session-for the six info displays (the KEVIN-DIRECTIVE client-command audit):-- - /session (Session Info block over get_session_stats)- - /context (formatContextTree agent/token/cost/context table)- - /usage (the /context alias)- - /system-prompt (header + the exact assembled prompt; the bodies are- the two products' own prompts — the layered rewrite supersedes TS- byte-parity — so the header shape is diffed and the bodies recorded)- - /logs (the agent-dir logs listing; planted files compare- byte-for-byte, daemon-written rows are dropped from the diff)- - /changelog (the shipped CHANGELOG.md entries panel; both sides read- the same file — the Rust side through PI_PACKAGE_DIR, the TS-side- package override mechanism itself)--Both binaries resume the same fixture session (a real captured assistant-envelope rewritten with deterministic usage/cost) in isolated-HOME/agent-dir sandboxes in tmux at 120x36, one command per captured-state. Frames are normalized for volatile content and diffed; the exit-code is non-zero when any state differs.--tmux rules: default socket only (`env -u TMUX`), icparity-* session names,-no kill-server; sessions are killed individually at the end.-"""--import argparse-import difflib-import glob-import json-import os-import re-import shutil-import subprocess-import sys-import tempfile-import time--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--SIZES = [("120", "36"), ("120", "400")]--MARKER_TEXT = "info parity transcript complete"--# The fixture session's deterministic usage/cost: both /session and-# /context totals render from these numbers.-USAGE_1 = {"input": 900, "output": 90, "cacheRead": 0, "cacheWrite": 10,- "cost": {"input": 0.0312, "output": 0.0, "cacheRead": 0.0, "cacheWrite": 0.0, "total": 0.0312}}-USAGE_2 = {"input": 100, "output": 10, "cacheRead": 0, "cacheWrite": 0,- "cost": {"input": 0.0002, "output": 0.0, "cacheRead": 0.0, "cacheWrite": 0.0, "total": 0.0002}}--# Logs the harness plants with FIXED sizes so the /logs listing compares-# byte-for-byte; daemon-written rows are dropped from the diff instead.-PLANTED_LOGS = [("harness-planted.log", 2048), ("client-errors.log", 512)]--# One state per command: (state, command, wait marker, minimum pane rows-# below which the state's block scrolls out of the capture). The compact-# displays run at both sizes; the tall ones (the full prompt, the whole-# changelog) only against a tall pane so their markers stay visible.-# (state, command, wait marker or None for stability, minimum pane rows,-# scroll-to-top before capture). The system-prompt display is taller than-# any pane: both products bind `tui.viewport.top` to shift+alt+up, so the-# harness scrolls after the render to bring the header row into view.-# The scroll-to-top state runs last: it leaves the viewport at the top,-# which would hide the following displays' appends from the wait markers.-# The scroll-to-top state runs second-to-last and scrolls back to-# follow afterwards: it leaves the viewport at the top otherwise, which-# would hide the following displays' appends from the wait markers.-STATES = [- ("session", "/session", "Session Info", 0, False),- ("context", "/context", "Tokens", 400, False),- ("usage", "/usage", None, 400, False),- ("logs", "/logs", "Daemon crashes log to", 0, False),- ("system-prompt", "/system-prompt", "</available_skills>", 400, True),- ("changelog", "/changelog", None, 400, False),-]--# The raw crossterm sequences for shift+alt+up (scroll to top) and-# ctrl+shift+down (scroll to bottom and follow); tmux has no key names-# for them.-SCROLL_TOP_SEQUENCE = ["-H", "1b", "5b", "31", "3b", "34", "41"]-SCROLL_FOLLOW_SEQUENCE = ["-H", "1b", "5b", "31", "3b", "36", "42"]---def session_paths():- return sorted(- glob.glob(os.path.expanduser("~/.prime/agent/sessions/**/*.jsonl"), recursive=True),- key=os.path.getmtime,- )---def newest_assistant_message(sessions):- """A real assistant message envelope (api/provider/usage fields) so the- synthetic replies deserialize in BOTH loaders; see- custom_message_parity.py for the size-bounded scan rationale."""- best = None- for path in reversed(sessions):- with open(path, encoding="utf-8") as f:- for line in f:- try:- row = json.loads(line)- except ValueError:- continue- message = row.get("message") if row.get("type") == "message" else None- if (- isinstance(message, dict)- and message.get("role") == "assistant"- and isinstance(message.get("content"), list)- and any(- isinstance(block, dict) and block.get("type") == "text"- and len(block.get("text", "")) < 200- for block in message["content"]- )- and (best is None or len(line) < best[0])- ):- best = (len(line), message)- if best is None:- raise SystemExit("no assistant message found in captured sessions")- return json.loads(json.dumps(best[1]))---def assistant_with(template, text, usage, ms):- message = json.loads(json.dumps(template))- message["content"] = [{"type": "text", "text": text}]- message["provider"] = "prime-inference"- message["model"] = "z-ai/glm-5.3"- message["usage"] = json.loads(json.dumps(usage))- message["timestamp"] = ms- return message---def build_session(path, source_header, assistant_template, cwd):- """The parity session: one user turn, two assistant replies with the- deterministic usage/cost (the /context and /session totals source).- The header cwd matches the sandbox cwd (the TS resume rejects foreign- projects)."""- header = {- "type": "session",- "version": source_header.get("version", 3),- "id": "icparity-session",- "cwd": cwd,- "timestamp": source_header.get("timestamp", "2026-09-21T00:00:00.000Z"),- }- entries = [header]- base_ms = 1_700_000_000_000-- def entry(type_, fields, ms):- row = {"type": type_}- row.update(fields)- row["id"] = f"e{ms - 1_700_000_000_000:04d}"- row["parentId"] = entries[-1]["id"]- row["timestamp"] = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(ms / 1000))- return row-- entries.append(entry("message", {- "message": {"role": "user", "content": "Run the info-command checks.", "timestamp": base_ms},- }, base_ms))- base_ms += 1- entries.append(entry("message", {- "message": assistant_with(assistant_template, "The info rows follow.", USAGE_1, base_ms),- }, base_ms))- base_ms += 1- entries.append(entry("message", {- "message": assistant_with(assistant_template, MARKER_TEXT, USAGE_2, base_ms),- }, base_ms))- with open(path, "w", encoding="utf-8") as f:- for row in entries:- f.write(json.dumps(row) + "\n")- return path---def newest_session_header():- sessions = session_paths()- for path in reversed(sessions):- with open(path, encoding="utf-8") as f:- first = f.readline()- try:- header = json.loads(first)- except ValueError:- continue- if header.get("type") == "session":- return header- raise SystemExit("no captured session header found under ~/.prime/agent/sessions")---def tmux(*args, check=True):- result = subprocess.run(["env", "-u", "TMUX", "tmux", *args], capture_output=True, text=True)- if check and result.returncode != 0:- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")- return result.stdout---def capture(session):- return tmux("capture-pane", "-e", "-p", "-t", session)---def capture_plain(session):- return tmux("capture-pane", "-p", "-t", session)---def wait_for(session, needle, timeout):- deadline = time.time() + timeout- while time.time() < deadline:- # ANSI-stripped match: the echo rows style the slash-command- # token, so the raw capture splits the marker with SGR codes.- if needle in re.sub(ANSI, "", capture_plain(session)):- return- time.sleep(0.3)- raise TimeoutError(f"session {session} never showed {needle!r}")---def wait_stable(session, timeout, baseline=None):- """Wait until the pane stops changing: for displays taller than the- pane (the full system prompt, the whole changelog) no marker stays- visible, so render completion is detected by frame stability. When a- `baseline` is given, the frame must first move away from it (the- render landed), which keeps a slow round-trip from reading as an- already-settled frame."""- deadline = time.time() + timeout- if baseline is not None:- while time.time() < deadline:- if capture_plain(session) != baseline:- break- time.sleep(0.3)- else:- raise TimeoutError(f"session {session} never left its baseline")- previous = capture_plain(session)- while time.time() < deadline:- time.sleep(1.0)- current = capture_plain(session)- if current == previous:- return- previous = current- raise TimeoutError(f"session {session} never settled")---ANSI = r"(?:\x1b\[[0-9;]*m)?"---def normalize(frame, root, planted_names, state):- frame = frame.replace(root, "<SANDBOX>")- frame = re.sub(r"v\d+\.\d+\.\d+", "vX.X.X", frame)- frame = re.sub(r"\b[0-9a-f]{12}\b", "<SID>", frame)- # Daemon log files: hashed socket names, growing sizes.- frame = re.sub(r"(\.[0-9a-f]{8}\.log)", ".<H>.log", frame)- frame = re.sub(r"\(\d+(\.\d+)? KB\)", "(<KB>)", frame)- lines = frame.split("\n")- kept = []- for line in lines:- # /logs rows the daemons themselves wrote (everything not- # planted) drop out of every state's diff: the two daemons log- # different file sets, and the /logs output lingers in the later- # states' panes.- if "\u2022" in line and not any(name in line for name in planted_names):- continue- # Startup surfaces outside these six commands: the tmux- # extended-keys warning (this build renders it in the session- # transcript, TS surfaces it on the agents view instead).- if "tmux extended-keys is off" in line or "restart tmux." in line:- continue- # Escape-only rows (block surface rows cut at the pane edge when- # the two sides scroll one or two rows apart) carry no text.- if not re.sub(ANSI, "", line).strip():- continue- # The brand splash rows (TS renders the splash on resume, this- # port does not, so the two panes sit a few rows apart at 36- # rows) drop out; the displays below compare row-for-row.- if re.search(r"[\u2597\u2580\u2584\u2588\u259b\u2598\u2593\u2591\u258c\u2599\u2596\u259d\u258f\u259f\u25b2\u25bc\u2590\u2595]{3,}", line):- continue- if "cwd " in line and "$" not in line:- continue- kept.append(line)- frame = "\n".join(kept)- # The context column and the Current line depend on the model's- # context-window estimate (the TS resume injects a harness-digest- # message this port does not count): mask the utilization numbers,- # keep the structure (the unit tests pin the exact numbers).- # The context-column masks run for every state: the /context and- # /usage outputs linger in the later states' panes.- frame = re.sub(- f"[\u2593\u2591]+{ANSI} {ANSI}\d+%{ANSI} {ANSI}\([\d.kM]+/[\d.kM]+\)",- "<BAR> <PCT> (<TOK>)", frame)- frame = re.sub(- f"{ANSI}\d+%{ANSI} {ANSI}\([\d.kM]+/[\d.kM]+\)",- "<PCT> (<TOK>)", frame)- frame = re.sub(- f"Current:{ANSI} {ANSI}[\d,]+{ANSI} /{ANSI} [\d,]+{ANSI} \({ANSI}[\d.]+%{ANSI}\)",- "Current: <TOK> / <WIN> (<PCT>%)", frame)- if state == "system-prompt":- # The header compares (shape); the prompt body is the product's own- # assembled prompt (the layered rewrite supersedes TS byte-parity).- frame = re.sub(- f"System Prompt {ANSI}\(\d+ chars{ANSI}\)",- "System Prompt (<N> chars)", frame)- lines = frame.split("\n")- header_index = next(- (i for i, line in enumerate(lines) if "System Prompt (<N> chars)" in line),- None,- )- if header_index is not None:- frame = "\n".join(lines[: header_index + 1] + ["<PROMPT-BODY>"])- # totalMessages includes the TS resume-injected harness-digest row- # (this port does not count it); the per-kind rows still compare. The- # mask runs for every state: the /session output stays visible in the- # later states' panes.- frame = re.sub(- f"(Tool Results:{ANSI} {ANSI}\d+\n ?{ANSI}?)Total:{ANSI} {ANSI}\d+",- r"\1Total: <N>", frame)- # The tray-right cell (model/effort + token estimate) tracks the same- # estimate gap; the bottom bar keeps its left side.- frame = re.sub(r"(\u2190(?:\x1b\[[0-9;]*m)? manage).*", r"\1 <TRAY-RIGHT>", frame)- frame = re.sub(r"[\u2193\u2191] [\d.,]+[kM]? tokens", "<DIR> <TOK> tokens", frame)- frame = re.sub(r"\b\d+(\.\d+)?(ms|s)\b", "<T>", frame)- spinners = "".join("\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f")- frame = re.sub("[" + spinners + "]", "<SPIN>", frame)- pulses = "".join("\u25f4\u25f7\u25f6\u25f5\u25cb\u25f8\u25fb\u25fc")- frame = re.sub("[" + pulses + "]", "<PULSE>", frame)- frame = re.sub("\x1b\[39m\n", "\n", frame)- frame = re.sub("\n\x1b\[39m(?= )", "\n", frame)- frame = re.sub("\x1b\[49m\n", "\n", frame)- frame = re.sub("\n\x1b\[49m(?= )", "\n", frame)- # TS border rows carry a leftover bg reset before the rule glyph.- frame = re.sub("\x1b\[49m(?=\u2500)", "", frame)- # The scroll gap between the transcript end and the bottom chrome is- # blank rows (the counts differ with content height); collapse runs.- frame = re.sub(r"\n{3,}", "\n\n<BLANKS>\n\n", frame)- if state == "changelog":- # The changelog panel's own structure (borders, the What's New- # title, entry order) is pinned by the pa-tui unit tests; here the- # diff covers the entry CONTENT. The shared markdown renderer- # styles bullets differently from TS (bullet color, hanging- # indent — that divergence belongs to the markdown surface), so- # this state compares the ANSI-stripped word sequence. The two- # renders differ by a few rows in height (the indent wraps), so- # the top rows sit misaligned in the panes: compare the bottom- # half (both panes are bottom-anchored), word-wise.- lines = frame.split("\n")- chrome = next(- (i for i in range(len(lines) - 1, -1, -1) if "Collapsed mode" in lines[i]),- len(lines),- )- content = lines[:chrome]- # Markdown-renderer artifacts mask away (tracked for the markdown- # surface, not this lane): a space trimmed at a wrap edge after an- # open paren on one side but kept mid-row on the other; hyphen- # breaks at a wrap edge (one side splits the word); and intraword- # underscore emphasis (this port strips the underscores, TS keeps- # them).- stripped = re.sub(ANSI, "", " ".join(content))- frame = re.sub(r"\( +", "(", re.sub(r"\s+", " ", stripped)).strip()- frame = frame.replace("- ", "-").replace("_", "")- lines = frame.split("\n")- while lines and not lines[-1].strip():- lines.pop()- return "\n".join(lines)---def diff_lines(left, right):- return "\n".join(- difflib.unified_diff(left.split("\n"), right.split("\n"), fromfile="ts", tofile="rust", lineterm="", n=1)- )---def find_runtime_package_dir():- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- candidates = [- entry- for entry in sorted(os.listdir(releases))- if os.path.isdir(os.path.join(releases, entry, "prime-agent-runtime"))- ]- if not candidates:- raise SystemExit("no release with prime-agent-runtime/ under " + releases)- return os.path.join(releases, candidates[-1])---def prepare_sandbox(base, side):- cwd = os.path.join(base, side, "cwd")- home = os.path.join(base, side, "home")- agent = os.path.join(base, side, "agent")- tmp = os.path.join(base, side, "tmp")- for path in (cwd, home, tmp, os.path.join(agent, "sessions")):- os.makedirs(path, exist_ok=True)- with open(os.path.join(agent, "settings.json"), "w", encoding="utf-8") as f:- json.dump({"onboardingCompleted": True}, f)- logs = os.path.join(agent, "logs")- os.makedirs(logs, exist_ok=True)- for name, size in PLANTED_LOGS:- with open(os.path.join(logs, name), "wb") as f:- f.write(b"x" * size)- return {"cwd": cwd, "home": home, "agent": agent, "tmp": tmp}---def run_side(side_name, binary, sandbox, session_path, size, out_dir, package_dir=None):- session = f"icparity-{side_name}-{size[0]}x{size[1]}"- tmux("kill-session", "-t", session, check=False)- tmux("new-session", "-d", "-s", session, "-x", size[0], "-y", size[1], "-c", sandbox["cwd"])- states = [- (state, command, marker, scroll_top)- for state, command, marker, min_rows, scroll_top in STATES- if int(size[1]) >= min_rows- ]- env = (- f"HOME={sandbox['home']} "- f"TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- if package_dir:- env += f" PI_PACKAGE_DIR={package_dir}"- command = (- f"{env} {binary} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--offline -r {session_path}"- )- tmux("send-keys", "-t", session, command, "Enter")- wait_for(session, MARKER_TEXT, timeout=90)- time.sleep(1.5)- frames = {}- for state, command_text, marker, scroll_top in states:- baseline = capture_plain(session)- tmux("send-keys", "-t", session, command_text, "Enter")- if marker is None:- if state == "changelog":- # The whole-changelog render scrolls the pane past every- # stable marker (the echo included): anchor on a frame- # CHANGE from the pre-command baseline, then stability.- wait_stable(session, timeout=90, baseline=baseline)- else:- # Other stability waits anchor on the echo row first.- wait_for(session, f" {command_text}", timeout=60)- wait_stable(session, timeout=60)- else:- wait_for(session, marker, timeout=60)- time.sleep(1.2)- if scroll_top:- tmux("send-keys", "-t", session, *SCROLL_TOP_SEQUENCE)- time.sleep(1.5)- frames[f"{state}@{size[0]}x{size[1]}"] = capture(session)- # Back to following output: the later displays append below- # the scrolled viewport.- tmux("send-keys", "-t", session, *SCROLL_FOLLOW_SEQUENCE)- time.sleep(1.5)- continue- frames[f"{state}@{size[0]}x{size[1]}"] = capture(session)- tmux("kill-session", "-t", session, check=False)- for key, frame in frames.items():- with open(os.path.join(out_dir, f"{side_name}-{key}.txt"), "w", encoding="utf-8") as f:- f.write(frame)- return frames---def main():- parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])- parser.add_argument("--rust-bin", default=os.environ.get("PA_RUST_BIN"))- parser.add_argument("--out-dir", default=None)- parser.add_argument("--keep", action="store_true", help="keep the sandbox tree")- parser.add_argument("--size", default=None, help="single WxH override")- args = parser.parse_args()- if not args.rust_bin:- raise SystemExit("pass --rust-bin (the built Rust prime-agent binary)")- ts_identity.assert_ts_side_is_the_ts_product()- sizes = [tuple(args.size.split("x"))] if args.size else SIZES-- base = tempfile.mkdtemp(prefix="icparity-")- out_dir = args.out_dir or os.path.join(base, "evidence")- os.makedirs(out_dir, exist_ok=True)- sandbox_ts = prepare_sandbox(base, "ts")- sandbox_rust = prepare_sandbox(base, "rust")-- source_header = newest_session_header()- assistant_template = newest_assistant_message(session_paths())- session_ts = build_session(- os.path.join(sandbox_ts["agent"], "sessions", "icparity.jsonl"),- source_header, assistant_template, sandbox_ts["cwd"],- )- session_rust = build_session(- os.path.join(sandbox_rust["agent"], "sessions", "icparity.jsonl"),- source_header, assistant_template, sandbox_rust["cwd"],- )-- ts_bin = shutil.which("prime-agent")- package_dir = find_runtime_package_dir()- # Both products warn when tmux runs without extended-keys; the Rust- # client renders the warning in the session transcript, which shifts- # every pane one side three rows against the other. Enable it for the- # run (restored in the finally below) so both sides render warning-free.- previous_extended_keys = tmux("show", "-s", "-v", "extended-keys", check=False).strip()- tmux("set", "-s", "extended-keys", "on")- # The Rust side reads the SAME CHANGELOG.md the TS product ships- # (PI_PACKAGE_DIR is the TS package-dir override mechanism).- ts_frames = {}- rust_frames = {}- failures = []- previous_extended_keys = ""- try:- for width, height in sizes:- size = (width, height)- ts_frames.update(run_side("ts", ts_bin, sandbox_ts, session_ts, size, out_dir))- rust_frames.update(run_side(- "rust", args.rust_bin, sandbox_rust, session_rust, size, out_dir,- package_dir=package_dir,- ))- planted_names = [name for name, _size in PLANTED_LOGS]- for key in sorted(ts_frames):- if key not in rust_frames:- continue- state = key.split("@")[0]- normalized_ts = normalize(ts_frames[key], os.path.join(base, "ts"), planted_names, state)- normalized_rust = normalize(rust_frames[key], os.path.join(base, "rust"), planted_names, state)- with open(os.path.join(out_dir, f"diff-{key}.txt"), "w", encoding="utf-8") as f:- f.write(diff_lines(normalized_ts, normalized_rust))- if normalized_ts != normalized_rust:- if state == "changelog":- # The two markdown renders differ a few rows in height,- # so the bottom-anchored panes show windows of slightly- # different edges. The content agrees when the two- # word sequences share a long common tail (the visible- # entries, their order, and their wording all match);- # only the window edges differ.- lo, hi = 0, min(len(normalized_ts), len(normalized_rust))- while lo < hi:- mid = (lo + hi + 1) // 2- if normalized_ts[-mid:] == normalized_rust[-mid:]:- lo = mid- else:- hi = mid - 1- if lo > 0.9 * min(len(normalized_ts), len(normalized_rust)):- continue- failures.append(key)- finally:- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if previous_extended_keys:- tmux("set", "-s", "extended-keys", previous_extended_keys, check=False)- if not args.keep:- shutil.rmtree(base, ignore_errors=True)-- report = os.path.join(out_dir, "report.md")- with open(report, "w", encoding="utf-8") as f:- f.write("# Info-command parity report\n\n")- for key in sorted(ts_frames):- f.write(f"- {key}: {'PASS' if key not in failures else 'FAIL'}\n")- print(open(report, encoding="utf-8").read())- if failures:- print("FAILED states:", ", ".join(failures))- return 1- print("All info-command states match.")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/keybinding_dispatch_parity.py b/scripts/keybinding_dispatch_parity.pydeleted file mode 100644index 8485f87503..0000000000--- a/scripts/keybinding_dispatch_parity.py+++ /dev/null@@ -1,699 +0,0 @@-#!/usr/bin/env python3-"""Keybinding-dispatch parity (TS vs Rust), tmux frame-diff.--The declared-keybindings audit table's dispatched actions (the Phase A/B/C-lanes of the keybindings PR): every key below was declared (and several-advertised in /hotkeys) without a dispatch site on the base, so this-harness drives the SAME keys into both products and normalized-diffs the-rows each state changes.--States (plan.md "tmux parity recipe"; ctrl+s stays upstream #3072's):--Chat surface (one session run):-- C-g VISUAL: a draft handed to $VISUAL's script comes back into the- editor row (the temp-file round trip).-- C-g unset: neither $VISUAL nor $EDITOR: the warning row.-- C-l: the model picker opens over the editor.-- interrupt: app.interrupt rebound via keybindings.json: a slow turn- aborts and the tray shows the exit hint.-- new session: app.session.new rebound: a fresh session starts (the- status text is a KNOWN divergence: TS "New session- started", Rust "started session <id>").--Scoped models (a second run with two models.json models + --models):-- M-m: forward cycle -> "Model: <p>/<id>".-- M-M: backward cycle -> "Model: <p>/<id>".-- M-m single: one scoped model -> "No other models available to cycle".-- C-l then M-s: the picker's scope row.--Agents view (a third run over a session that exists):-- C-o with code: a parent whose children carry spawnCode shows the code- rows inside the expanded list.-- C-o without: a parent without code reports it.-- C-r: the rename composer (header + hint).-- Esc: the composer exits back to the search prompt.--Exit code is non-zero when any state differs beyond the recorded-divergences.--Reuses the visual_parity faux-provider harness (tmux rules: default-socket, vplane-* session names, sessions killed individually) and the-#226 shared daemon reap.-"""--import argparse-import difflib-import glob-import json-import os-import re-import shutil-import sys-import tempfile-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-import visual_parity as vp-import queue_parity as qp--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--DRAFT = "parity draft text"-EDITED = "edited by parity script"-EDITOR_WARNING = "No editor configured. Set $VISUAL or $EDITOR environment variable."-PICKER_SEARCH = "Search models"-EXIT_HINT = "again to exit"-NO_OTHER_MODELS = "No other models available to cycle"-SCOPE_ROW = "Scope: "-RENAME_HEADER = "Rename agent session"-RENAME_HINT = "save"-NEW_SESSION_RUST = "started session"-NEW_SESSION_TS = "New session started"-SPINNERS = "".join("\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f")-SPINNER_CLASS = "[" + SPINNERS + "]"--# The user-rebound chat actions ride a keybindings.json fixture both-# products read at startup (TS KeybindingsManager.create / the Rust port).-REBOUND_KEYBINDINGS = {- # Plain alt letters (no default collisions): the ctrl+alt+<letter>- # legacy ESC-encodings fold differently per side under tmux without- # kitty negotiation, and ESC+p/n/b/f fold to the rxvt alt+arrow rows.- "app.interrupt": "alt+i",- "app.session.new": "alt+u",-}--# The slow streaming turn for the interrupt state: a long thinking block-# at 6 tokens/second keeps the loader alive until the interrupt key lands.-STREAMING_FAUX_SCRIPT = {- "engine": "faux",- "modelId": vp.TS_SCRIPT_MODEL,- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 6,- "responses": [- {- "content": [- {- "type": "thinking",- "thinking": "A long slow thinking pass keeps the turn streaming until the "- "interrupt key lands, so the abort is observable as the exit hint and the "- "turn settles. " * 2,- },- {"type": "text", "text": "the interrupted turn never finishes"},- ]- },- {"content": [{"type": "text", "text": "quick reply"}]},- ],-}--# Two custom models (models.json) so the --models scope resolves and-# cycling has two candidates.-TWO_MODEL_MODELS_JSON = {- "providers": {- "test-provider": {- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:9/v1",- "apiKey": "sk-test",- "models": [- {- "id": "mock-1",- "name": "Mock 1",- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:9/v1",- "contextWindow": 128000,- "maxTokens": 4096,- },- {- "id": "mock-2",- "name": "Mock 2",- "api": "openai-completions",- "baseUrl": "http://127.0.0.1:9/v1",- "contextWindow": 128000,- "maxTokens": 4096,- },- ],- }- }-}--# Known divergences this harness EXPECTS (recorded, not failed):-KNOWN_DIVERGENCES = [- "new-session status text: TS 'New session started' vs Rust "- "'started session <id>' (pre-existing; the parity diff lists it)",- "Rust status rows never expire and render in the error tone; TS "- "clears after 4.5s in muted tone (SF6, pre-existing machinery)",- "shift+alt+m under tmux without kitty: v0.9.7's TS parses only the "- "kitty CSI-u form for the shift+alt modifier, while the Rust port "- "also accepts the legacy ESC+uppercase fold (its documented "- "crossterm fold; see keys.rs) and does not parse CSI-u until kitty "- "is active; a kitty-capable terminal delivers the same CSI-u bytes "- "to both",- "the faux turn is not paced (the thinking pass renders instantly), "- "so the interrupt usually lands after the turn settles; the "- "dispatch (abort + shared exit hint) is identical",- "c4_interrupt's trailing tray cell: TS reports the faux turn's "- "usage estimate at capture, Rust's snapshot reads 0 - the "- "pre-existing footer usage display (chrome.rs / session_stats.rs, "- "untouched by this PR) under a faux engine that ships no usage "- "blocks; the hint text itself is byte-identical",-]--# States whose TS/Rust row diff is documented as expected (each entry-# pairs with a KNOWN_DIVERGENCES line above). Any OTHER state that-# diverges fails the run: main() exits non-zero.-EXPECTED_DIVERGENT_STATES = {- "c4_interrupt": (- "the trailing tray usage cell under the usage-less faux engine "- "(see the c4 entry above)"- ),- "c5_new_session": (- "the new-session status text ('New session started' vs "- "'started session <id>', pre-existing)"- ),-}---def default_ts_binary():- """The ts side's launch command (queue_edit_parity's resolution):- PA_TS_BINARY, then the TS-main bundle, then a deployed release."""- override = os.environ.get("PA_TS_BINARY")- if override:- return override- ts_main_cli = os.path.join(- "/home/ubuntu/prime-agent", "packages", "coding-agent", "dist", "bundle", "cli.js"- )- if os.path.exists(ts_main_cli):- return f"node {ts_main_cli}"- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- candidates = sorted(glob.glob(os.path.join(releases, "0.9.5-linux-x64-*", "prime-agent")))- if not candidates:- raise SystemExit("neither the TS-main checkout nor a deployed TS release found; set PA_TS_BINARY")- return candidates[-1]---def make_sandbox(base, binary, name):- """One isolated sandbox (home/agent/tmp + socket) per state family: a- models.json fixture narrows the DAEMON's registry for the process's- lifetime, so the scoped-models runs and the faux-chat runs must not- share a daemon."""- home = os.path.join(base, name, binary, "home")- agent = os.path.join(base, name, binary, "agent")- tmp = os.path.join(base, name, binary, "tmp")- os.makedirs(home, exist_ok=True)- os.makedirs(tmp, exist_ok=True)- os.makedirs(os.path.join(agent, "extensions"), exist_ok=True)- os.makedirs(os.path.join(agent, "sessions"), exist_ok=True)- with open(os.path.join(agent, "settings.json"), "w") as f:- json.dump({"onboardingCompleted": True}, f)- return {"home": home, "agent": agent, "tmp": tmp}---def settle(session, samples=2, gap=0.4):- """Wait until two captures agree (the attach chrome settles before any- typed key dispatches on a transcript the attach rebuilds)."""- last = vp.capture(session)- stable = 0- for _ in range(120):- time.sleep(gap)- current = vp.capture(session)- if current == last:- stable += 1- if stable >= samples:- return- else:- stable = 0- last = current- raise RuntimeError("the pane never settled after attach")---def editor_rows(frame, markers):- """The rows of one frame containing any marker, ANSI bytes intact."""- return qp.styled_rows(frame, markers)---def require_absent(frame, text, state):- if text in qp.strip_ansi(frame):- raise RuntimeError(f"scenario drift in {state}: {text!r} still on screen")---def launch_command(binary, sandbox, extra_args, extra_env):- # A subcommand (the `agents` view) must lead: a trailing positional- # rides the prompt-argument slot instead.- if binary == "ts":- return (- f"{default_ts_binary()} {extra_args} "- f"--daemon-socket {sandbox['agent']}/daemon.sock"- )- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)), "..", "target", "release", "prime-agent"- ),- )- package_dir = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- return (- f"PI_PACKAGE_DIR={package_dir} "- f"{rust} {extra_args} "- f"--daemon-socket {sandbox['agent']}/daemon.sock"- )---def new_pane(session_name, sandbox, binary, extra_args, extra_env, script_path, size, shared_cwd, pre_cmd=""):- width, height = size- session = f"vplane-{session_name}-{binary}-{width}x{height}"- vp.tmux("kill-session", "-t", session, check=False)- vp.tmux("new-session", "-d", "-s", session, "-x", width, "-y", height, "-c", shared_cwd)- faux_env = f"PRIME_AGENT_FAUX_SCRIPT={script_path} " if script_path else ""- env = (- f"HOME={sandbox['home']} "- f"TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"{faux_env}"- "PRIME_AGENT_DISABLE_ANALYTICS=1 "- f"{extra_env} "- )- command = launch_command(binary, sandbox, extra_args, extra_env)- vp.tmux("send-keys", "-t", session, f"{pre_cmd}{env} {command}", "Enter")- return session---def boot_marker(binary):- """Mode-neutral boot marker: both products open with the- Details/Collapsed (Ctrl+O to expand) row (v0.9.7's TS boots in- Details mode with the same hint text)."""- return "mode (Ctrl+O to expand)"---def run_no_editor_state(binary, sandbox, shared_cwd, script_path, size):- """The no-editor warning: a separate launch without $VISUAL/$EDITOR in- the pane env (the editor-configured run exports VISUAL for its own- pane, and a pane's env is fixed at the shell's start). The leading- `unset` clears a host-exported VISUAL/EDITOR too, so the launch can- never inherit one."""- session = new_pane(- "kdisp-noeditor",- sandbox,- binary,- f"--model {vp.TS_SCRIPT_MODEL}",- "",- script_path,- size,- shared_cwd,- pre_cmd="unset VISUAL EDITOR; ",- )- try:- vp.wait_for(session, boot_marker(binary), timeout=120)- settle(session)- vp.tmux("send-keys", "-t", session, "-l", DRAFT)- time.sleep(0.4)- vp.tmux("send-keys", "-t", session, "C-g")- qp.wait_plain(session, EDITOR_WARNING, timeout=30)- time.sleep(0.4)- return {"c2_no_editor_warning": vp.capture(session)}- finally:- vp.tmux("kill-session", "-t", session, check=False)---def run_chat_states(binary, sandbox, shared_cwd, script_path, size, extra_env):- """The chat surface: ctrl+g (VISUAL set), ctrl+l, interrupt, new- session. The no-editor warning runs in its own pane (see- run_no_editor_state) because $VISUAL rides the pane env."""- session = new_pane(- "kdisp-chat",- sandbox,- binary,- f"--model {vp.TS_SCRIPT_MODEL}",- extra_env,- script_path,- size,- shared_cwd,- )- try:- vp.wait_for(session, boot_marker(binary), timeout=120)- settle(session)-- # A visible draft, then ctrl+g hands it to $VISUAL's script.- vp.tmux("send-keys", "-t", session, "-l", DRAFT)- time.sleep(0.4)- vp.tmux("send-keys", "-t", session, "C-g")- try:- qp.wait_plain(session, EDITED, timeout=30)- except RuntimeError:- print(f"[{binary}] ctrl+g never replaced the draft; pane:")- print(qp.strip_ansi(vp.capture(session)))- raise- time.sleep(0.4)- frames = {"c1_editor_external": vp.capture(session)}- print(f"[{binary}] chat c1_editor_external captured")-- # ctrl+l: the model picker (v0.9.7's selector and the Rust- # picker both render the "Search models" placeholder row).- vp.tmux("send-keys", "-t", session, "C-l")- qp.wait_plain(session, PICKER_SEARCH, timeout=30)- time.sleep(0.4)- frames["c3_model_picker"] = vp.capture(session)- print(f"[{binary}] chat c3_model_picker captured")- vp.tmux("send-keys", "-t", session, "Escape")- qp.wait_plain(session, PICKER_SEARCH, gone=True, timeout=30)-- # The slow turn streams; the rebound interrupt aborts it and the- # exit hint shows.- vp.tmux("send-keys", "-t", session, "interrupt me")- vp.tmux("send-keys", "-t", session, "Enter")- # The faux turn finishes fast (its thinking pass is not paced), so- # the interrupt usually lands on the just-settled turn; the- # dispatch (abort + shared exit hint) is the same either way.- qp.wait_plain(session, "interrupt me", timeout=60)- # The exit hint is transient (~2s): land the interrupt mid-turn- # and capture immediately.- vp.tmux("send-keys", "-t", session, "M-i")- try:- qp.wait_plain(session, EXIT_HINT, timeout=30)- except RuntimeError:- print(f"[{binary}] c4 interrupt produced no exit hint; pane follows:")- print(vp.capture(session))- raise- frames["c4_interrupt"] = vp.capture(session)- print(f"[{binary}] chat c4_interrupt captured")-- # The interrupt is handled: a second ctrl+c press within the exit- # window exits the app on both products (the force-quit contract).- # (B1's tmux guard: the process must still be alive after the- # interrupt - captured here as the exit hint showing, then a- # deliberate second press exits.)-- # The rebound new-session key starts a fresh session. A ctrl+c- # here would be the second press of the interrupted pair (the- # hint window is still open) and shut the app down, so wait out- # the exit hint first.- qp.wait_plain(session, EXIT_HINT, gone=True, timeout=15)- vp.tmux("send-keys", "-t", session, "M-u")- # TS resets to the fresh-session state without rendering a- # persistent notice (the resync after the daemon's replacement- # clears it); Rust keeps a "started session <id>" note.- if binary == "ts":- qp.wait_plain(session, "interrupt me", gone=True, timeout=30)- else:- qp.wait_plain(session, NEW_SESSION_RUST, timeout=30)- time.sleep(0.6)- frames["c5_new_session"] = vp.capture(session)- print(f"[{binary}] chat c5_new_session captured")- return frames- finally:- vp.tmux("kill-session", "-t", session, check=False)---def run_scoped_model_states(binary, sandbox, shared_cwd, script_path, single, size, extra_env):- """The scoped-models surface: alt+m cycling, the single-model refusal,- and the picker's scope row. The models.json catalog rides this run- alone (a models.json narrows the registry, so the chat/agents runs- must not carry it)."""- with open(os.path.join(sandbox["agent"], "models.json"), "w") as f:- json.dump(TWO_MODEL_MODELS_JSON, f, indent=2)- args = "--models test-provider/mock-2" if single else "--models test-provider/mock-1,test-provider/mock-2"- # The scope runs never submit a turn, so no faux script rides the- # pane. The explicit --model pins the session to an in-scope mock- # either way, so the cycle keys behave deterministically.- model_arg = " --model test-provider/mock-2" if single else " --model test-provider/mock-1"- session = new_pane(- "kdisp-scope", sandbox, binary, args + model_arg, extra_env, "", size, shared_cwd- )- try:- vp.wait_for(session, boot_marker(binary), timeout=120)- settle(session)- frames = {}- if single:- vp.tmux("send-keys", "-t", session, "M-m")- qp.wait_plain(session, NO_OTHER_MODELS, timeout=30)- time.sleep(0.4)- frames["b1_single_cycle_refused"] = vp.capture(session)- else:- vp.tmux("send-keys", "-t", session, "M-m")- qp.wait_plain(session, "Model: test-provider/mock-2", timeout=30)- # The daemon's setModel from the forward cycle must settle- # before the backward cycle lands (a rapid second press- # rides the in-flight switch and does nothing).- time.sleep(1.5)- frames["b1_cycle_forward"] = vp.capture(session)- # shift+alt+m has no legacy encoding TS matches: under tmux- # without kitty, v0.9.7's TS parses only the CSI-u form for- # the shift+alt modifier, while the Rust port resolves the- # legacy ESC+uppercase fold (its documented crossterm fold)- # and does not parse CSI-u without kitty active. Each side- # gets the form its decoder accepts.- if binary == "ts":- vp.tmux("send-keys", "-t", session, "-l", "\x1b[109;4u")- else:- vp.tmux("send-keys", "-t", session, "M-M")- try:- qp.wait_plain(session, "Model: test-provider/mock-1", timeout=30)- except RuntimeError:- print(f"[{binary}] b2 backward cycle never showed mock-1; pane follows:")- print(vp.capture(session))- raise- time.sleep(0.4)- frames["b2_cycle_backward"] = vp.capture(session)- # ctrl+l then alt+s: the picker's scope row. The launch- # --models scope bounds the picker's all view too, so the- # listed rows are the same before and after; the toggle's- # observable is the ACTIVE-SCOPE MARKER: the accent moves- # from "all" to "scoped" in the styled row (the normalized- # text is constant). A no-op toggle leaves the styled row- # byte-identical and fails here.- vp.tmux("send-keys", "-t", session, "C-l")- qp.wait_plain(session, SCOPE_ROW, timeout=30)- time.sleep(0.4)- before_scope = editor_rows(vp.capture(session), (SCOPE_ROW,))- vp.tmux("send-keys", "-t", session, "M-s")- settle(session)- after_scope = editor_rows(vp.capture(session), (SCOPE_ROW,))- if after_scope == before_scope:- raise RuntimeError(- f"[{binary}] alt+s never toggled the scope marker "- f"(the styled row is unchanged: {before_scope[:1]!r})"- )- time.sleep(0.4)- frames["b3_picker_scope_row"] = vp.capture(session)- vp.tmux("send-keys", "-t", session, "Escape")- return frames- finally:- vp.tmux("kill-session", "-t", session, check=False)- # The catalog is scoped to this run: the next chat/agents run- # must see the full registry again.- try:- os.remove(os.path.join(sandbox["agent"], "models.json"))- except OSError:- pass---def run_agents_view_states(binary, sandbox, shared_cwd, script_path, size, extra_env):- """The agents-view surface: ctrl+o's program rows (with and without- spawn code), ctrl+r's rename composer, Esc. Reached the way a user- reaches it: a quick turn in the chat, then /resume (the agents view- lists the just-used session)."""- session = new_pane(- "kdisp-agents",- sandbox,- binary,- f"--model {vp.TS_SCRIPT_MODEL}",- extra_env,- script_path,- size,- shared_cwd,- )- try:- vp.wait_for(session, boot_marker(binary), timeout=120)- settle(session)- vp.tmux("send-keys", "-t", session, "seed")- vp.tmux("send-keys", "-t", session, "Enter")- qp.wait_plain(session, "never finishes", timeout=90)- # The `agents` subcommand launches straight into the roster view- # (the flicker parity's entry path); the seeded session shows as- # its row.- vp.tmux("kill-session", "-t", session, check=False)- session = new_pane(- "kdisp-agents2",- sandbox,- binary,- "agents",- extra_env,- script_path,- size,- shared_cwd,- )- vp.wait_for(session, "Search sessions", timeout=120)- settle(session)- frames = {}- # ctrl+o on a parent without spawned subagents: TS stays silent on- # an empty roster; the Rust build reports the missing program- # (known divergence #5 - captured, not failed).- vp.tmux("send-keys", "-t", session, "C-o")- time.sleep(0.8)- frames["c1_ctrl_o_no_code"] = vp.capture(session)- # ctrl+r: the rename composer over the prompt. A missing header- # is a dispatch regression on that product - fail, don't capture- # whatever else the pane shows.- vp.tmux("send-keys", "-t", session, "C-r")- qp.wait_plain(session, RENAME_HEADER, timeout=30)- time.sleep(0.4)- frames["c2_rename_header"] = vp.capture(session)- # Esc exits the composer back to the roster.- vp.tmux("send-keys", "-t", session, "Escape")- qp.wait_plain(session, RENAME_HEADER, gone=True, timeout=30)- time.sleep(0.4)- frames["c3_rename_escape"] = vp.capture(session)- return frames- finally:- vp.tmux("kill-session", "-t", session, check=False)---def compare_state(name, ts_frame, rust_frame, markers, divergences):- # The normalized compare: the plan's recipe diffs the ANSI-stripped- # rows, so styling-only differences do not register as divergences.- ts_rows = [qp.strip_ansi(r) for r in editor_rows(ts_frame, markers)]- rust_rows = [qp.strip_ansi(r) for r in editor_rows(rust_frame, markers)]- if ts_rows == rust_rows:- print(f"PASS {name}: {len(ts_rows)} row(s) match (ts vs rust)")- for row in ts_rows:- print(f" | {row.rstrip()}")- return None- diff = "\n".join(- difflib.unified_diff(- [r.rstrip() for r in ts_rows],- [r.rstrip() for r in rust_rows],- fromfile="ts", tofile="rust", lineterm="", n=1,- )- )- print(f"DIFF {name} (ts vs rust)")- print(diff)- divergences.append(f"{name}:\n{diff}")- return name---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--size", default="120x36")- parser.add_argument("--only", default=None, choices=("ts", "rust"))- parser.add_argument("--states", default=None, choices=("chat", "scope", "agents"))- args = parser.parse_args()- width, height = args.size.split("x")- size = (str(width), str(height))-- if args.only in (None, "ts"):- ts_identity.assert_ts_side_is_the_ts_product(ts_bin=f"{default_ts_binary()} 2>&1")-- base = tempfile.mkdtemp(prefix="kd-", dir="/tmp")- script_path = os.path.join(base, "kd-faux-script.json")- with open(script_path, "w") as f:- json.dump(STREAMING_FAUX_SCRIPT, f, indent=2)- shared_cwd = os.path.join(base, "shared-cwd")- os.makedirs(shared_cwd, exist_ok=True)- # Each state family gets its own sandbox per binary (its own daemon- # socket): a models.json fixture narrows the daemon's registry for- # the process's lifetime, so the scoped-models family and the- # faux-chat families never share one. The chat family's- # keybindings.json rebinds interrupt/new-session; the scope and- # agents families keep the default bindings (their keys are the- # stock alt+m/alt+s/ctrl+o/ctrl+r).- sandboxes = {- family: {binary: make_sandbox(base, binary, family) for binary in ("ts", "rust")}- for family in ("chat", "scope", "agents")- }- for binary in ("ts", "rust"):- with open(- os.path.join(sandboxes["chat"][binary]["agent"], "keybindings.json"), "w"- ) as f:- json.dump(REBOUND_KEYBINDINGS, f, indent=2)- # The TS side reads the faux script through the extension (the- # families that run turns: chat, agents).- for family in ("chat", "agents"):- with open(- os.path.join(sandboxes[family][binary]["agent"], "extensions", "visual-faux.js"),- "w",- ) as f:- f.write(vp.TS_FAUX_EXTENSION)- # The external-editor script: reads the temp file, writes the new text.- editor_path = os.path.join(base, "parity-editor.sh")- with open(editor_path, "w") as f:- f.write("#!/bin/sh\nprintf 'edited by parity script\\n' > \"$1\"\n")- os.chmod(editor_path, 0o755)- extra_env = f"VISUAL={editor_path}"-- divergences = list(KNOWN_DIVERGENCES)- sides = (args.only,) if args.only else ("ts", "rust")- try:- selected = args.states or ("chat", "scope", "agents")- frames = {}- for binary in sides:- if "chat" in selected:- frames.setdefault(binary, {})["chat"] = run_chat_states(- binary, sandboxes["chat"][binary], shared_cwd, script_path, size, extra_env- )- frames[binary]["chat"]["c2_no_editor_warning"] = run_no_editor_state(- binary, sandboxes["chat"][binary], shared_cwd, script_path, size- )["c2_no_editor_warning"]- if "scope" in selected:- frames.setdefault(binary, {})["scope"] = run_scoped_model_states(- binary, sandboxes["scope"][binary], shared_cwd, script_path, False, size, ""- )- frames[binary]["scope_single"] = run_scoped_model_states(- binary, sandboxes["scope"][binary], shared_cwd, script_path, True, size, ""- )- if "agents" in selected:- frames.setdefault(binary, {})["agents"] = run_agents_view_states(- binary, sandboxes["agents"][binary], shared_cwd, script_path, size, ""- )- if args.only:- print(f"captures recorded for {args.only}; rerun without --only to diff")- return 0- ts_frames, rust_frames = frames["ts"], frames["rust"]- if "chat" in selected:- compare_state("c1_editor_external", ts_frames["chat"]["c1_editor_external"], rust_frames["chat"]["c1_editor_external"], (EDITED, DRAFT), divergences)- compare_state("c2_no_editor_warning", ts_frames["chat"]["c2_no_editor_warning"], rust_frames["chat"]["c2_no_editor_warning"], (EDITOR_WARNING,), divergences)- compare_state("c3_model_picker", ts_frames["chat"]["c3_model_picker"], rust_frames["chat"]["c3_model_picker"], (PICKER_SEARCH,), divergences)- compare_state("c4_interrupt", ts_frames["chat"]["c4_interrupt"], rust_frames["chat"]["c4_interrupt"], (EXIT_HINT,), divergences)- compare_state("c5_new_session", ts_frames["chat"]["c5_new_session"], rust_frames["chat"]["c5_new_session"], (NEW_SESSION_TS, NEW_SESSION_RUST), divergences)- if "scope" in selected:- compare_state("b1_cycle_forward", ts_frames["scope"]["b1_cycle_forward"], rust_frames["scope"]["b1_cycle_forward"], ("Model: test-provider/mock-2",), divergences)- compare_state("b2_cycle_backward", ts_frames["scope"]["b2_cycle_backward"], rust_frames["scope"]["b2_cycle_backward"], ("Model: test-provider/mock-1",), divergences)- compare_state(- "b3_picker_scope_row",- ts_frames["scope"]["b3_picker_scope_row"],- rust_frames["scope"]["b3_picker_scope_row"],- (SCOPE_ROW, PICKER_SEARCH, "All models across supported providers"),- divergences,- )- compare_state("b1_single_cycle_refused", ts_frames["scope_single"]["b1_single_cycle_refused"], rust_frames["scope_single"]["b1_single_cycle_refused"], (NO_OTHER_MODELS,), divergences)- if "agents" in selected:- compare_state("a1_ctrl_o_no_code", ts_frames["agents"]["c1_ctrl_o_no_code"], rust_frames["agents"]["c1_ctrl_o_no_code"], ("No program recorded",), divergences)- compare_state("a2_rename_header", ts_frames["agents"]["c2_rename_header"], rust_frames["agents"]["c2_rename_header"], (RENAME_HEADER,), divergences)- compare_state("a3_rename_escape", ts_frames["agents"]["c3_rename_escape"], rust_frames["agents"]["c3_rename_escape"], ("Search sessions",), divergences)- # compare_state appends each divergent state's diff to- # `divergences` (seeded from KNOWN_DIVERGENCES above); a diff- # whose state is not one of the documented expected ones fails- # the run.- unexpected = [- block- for block in divergences[len(KNOWN_DIVERGENCES):]- if block.split(":", 1)[0] not in EXPECTED_DIVERGENT_STATES- ]- print()- print("Expected/known divergences:")- for d in divergences:- print(f"- {d}")- if unexpected:- names = ", ".join(block.split(":", 1)[0] for block in unexpected)- print(f"\nUNEXPECTED divergences: {names}")- return 1- return 0- finally:- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if os.environ.get("KD_KEEP") != "1":- shutil.rmtree(base, ignore_errors=True)---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/latency_trace_probe.py b/scripts/latency_trace_probe.pydeleted file mode 100644index 011f846ded..0000000000--- a/scripts/latency_trace_probe.py+++ /dev/null@@ -1,335 +0,0 @@-#!/usr/bin/env python3-"""prime-agent latency trace probe — the cross-machine comparison protocol.--Drives the LIVE daemon on this machine over its JSONL supervisor socket-and records a per-request timing breakdown for the operator's lag-surfaces (the agents-view request set, the /context request, attach),-plus the live-store shape and the concurrency decomposition (a-lightweight request fired alongside a heavy one: its inflation is the-head-of-line/queueing measure).--Run identically on both machines (the box and the Mac), then compare the-JSON traces: same product, comparable store, wildly different feel — the-difference IS the diagnosis (fleet contention, hardware, or the-request-path defects under fix).--Usage: python3 pa-latency-trace.py [--socket /path] [--out trace.json]- The trace JSON is written to --out and printed.-"""-import argparse-import json-import os-import socket-import subprocess-import threading-import time--PROTOCOL = {"name": "prime-agent.daemon", "version": 7}---class DaemonProbe:- def __init__(self, sock, timeout=90.0):- self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- self.s.settimeout(timeout)- self.s.connect(sock)- self.buf = b""- self.deadline = None-- def read_line(self):- # One deadline spans the whole command: a wedged request (a steady- # stream of non-response event frames) still fails the trace- # instead of waiting a socket-timeout per recv forever.- if self.deadline is not None and time.monotonic() > self.deadline:- raise TimeoutError("trace deadline exceeded for the pending response")- while b"\n" not in self.buf:- remaining = None- if self.deadline is not None:- remaining = self.deadline - time.monotonic()- if remaining <= 0:- raise TimeoutError("trace deadline exceeded for the pending response")- self.s.settimeout(remaining)- chunk = self.s.recv(1 << 20)- if not chunk:- raise EOFError("socket closed")- self.buf += chunk- line, self.buf = self.buf.split(b"\n", 1)- return json.loads(line)-- def command(self, cmd, rid, timeout=90.0):- env = {"type": "command", "id": rid, "protocol": PROTOCOL, "command": cmd}- self.deadline = time.monotonic() + timeout- t0 = time.time()- self.s.sendall((json.dumps(env) + "\n").encode())- try:- while True:- msg = self.read_line()- if msg.get("id") == rid and msg.get("type") == "response":- return {"wall_ms": (time.time() - t0) * 1000.0, "response": msg}- finally:- self.deadline = None-- def close(self):- self.s.close()-- def handshake(self, timeout=90.0):- """Read the daemon_hello with a deadline: a daemon that accepts- the socket but never greets fails the trace instead of blocking- indefinitely."""- self.deadline = time.monotonic() + timeout- try:- return self.read_line()- finally:- self.deadline = None---def kitty_probe_timing(budget_s=2.5):- """The terminal enhanced-key query latency, measured on THIS process's- tty (run the trace from inside the interactive terminal being- compared): the TUI's surface start blocks input-blind on this answer- for up to 2s when the terminal does not answer (an SSH pipe often- does not; a local terminal answers in milliseconds) — the- per-switch, terminal-dependent stall that stacks with the request- chain."""- import select- import sys- if not sys.stdout.isatty():- return {"available": False, "reason": "no tty on this process"}- fd = sys.stdout.fileno()- old = None- try:- import termios- old = termios.tcgetattr(fd)- import tty- tty.setraw(fd)- except Exception:- old = None- t0 = time.time()- answered = False- try:- os.write(fd, b"\x1b[?u") # the kitty keyboard-protocol query- deadline = t0 + budget_s- while time.time() < deadline:- ready, _, _ = select.select([fd], [], [], deadline - time.time())- if ready:- os.read(fd, 65536)- answered = True- break- finally:- if old is not None:- try:- termios.tcsetattr(fd, termios.TCSADRAIN, old)- except Exception:- pass- return {- "available": True,- "answered": answered,- "answer_ms": round((time.time() - t0) * 1000.0, 1),- "note": "answered in answer_ms; unanswered means the TUI's kitty probe waits out its 2s budget per surface start (input-blind) — the terminal-dependent per-switch stall",- }---def command_timing(probe, cmd, rid, label):- r = probe.command(cmd, rid)- return {- "label": label,- "command": cmd.get("type"),- "wall_ms": round(r["wall_ms"], 2),- "success": r["response"].get("success"),- "payload_bytes": len(json.dumps(r["response"].get("data") or {})),- }---def store_shape(agent_dir):- sessions = os.path.join(agent_dir, "sessions")- artifacts = os.path.join(agent_dir, "session-artifacts")- files = 0- total = 0- largest = 0- if os.path.isdir(sessions):- for f in os.listdir(sessions):- if f.endswith(".jsonl"):- p = os.path.join(sessions, f)- try:- size = os.path.getsize(p)- except OSError:- # The live store changes mid-scan: a vanished file is- # skipped, never an aborted trace.- continue- files += 1- total += size- largest = max(largest, size)- subagent_dirs = 0- if os.path.isdir(artifacts):- for dirpath, dirnames, _ in os.walk(artifacts):- subagent_dirs += sum(1 for d in dirnames if d.startswith("sub-"))- return {- "top_level_sessions": files,- "top_level_bytes": total,- "largest_session_bytes": largest,- "subagent_dirs": subagent_dirs,- }---def env_shape():- try:- load1 = os.getloadavg()[0]- except Exception:- load1 = None- nproc = os.cpu_count()- return {"load_1min": load1, "cores": nproc}---def main():- ap = argparse.ArgumentParser()- ap.add_argument("--socket", default=os.environ.get("PA_TRACE_SOCKET", "/tmp/prime-agent-1000/daemon.sock"))- ap.add_argument("--out", default="pa-latency-trace.json")- ap.add_argument("--agent-dir", default=os.path.expanduser("~/.prime/agent"))- args = ap.parse_args()-- trace = {- "protocol_version": 1,- "machine": {"hostname": socket.gethostname()},- "steps": [],- "store": store_shape(args.agent_dir),- "env": env_shape(),- "concurrency": [],- }-- # 1. The connection + handshake.- p = DaemonProbe(args.socket)- hello = p.handshake()- trace["steps"].append({- "label": "daemon_hello handshake",- "command": "connect",- "wall_ms": 0.0,- "success": hello.get("type") == "daemon_hello",- "payload_bytes": len(json.dumps(hello)),- })-- # 2. A live session for the request set: prefer the busiest live- # session (the operator's own), else any live row.- listing = p.command({"type": "list", "all": True}, "trace-list")- rows = (listing["response"].get("data") or {}).get("sessions") or []- active = None- for row in rows:- if row.get("isActive") or row.get("activeSessionId"):- active = row.get("activeSessionId") or row.get("id")- break- if active is None and rows:- active = rows[0].get("id")- trace["live_session"] = active- trace["live_session_rows"] = len(rows)-- if active:- rid = 0-- def run(cmd, label):- nonlocal rid- rid += 1- t = command_timing(p, cmd, f"trace-{rid}", label)- trace["steps"].append(t)- return t-- # The agents-view request set + the operator's named lag surfaces.- run({"type": "roster_subscribe", "activeSessionId": active}, "agents view: roster subscribe")- run({"type": "get_rlm_children", "activeSessionId": active}, "agents view: rlm children")- run({"type": "get_session_stats", "activeSessionId": active}, "tray: session stats")- run({"type": "get_state", "activeSessionId": active}, "state read")- run({"type": "get_context_tree", "activeSessionId": active}, "/context: context tree")- run({"type": "get_messages", "activeSessionId": active}, "messages read")-- # 3. The concurrency decomposition: a lightweight request fired- # only AFTER the heavy request is on the wire (an event- # synchronized on the send), on SEPARATE connections — the- # lightweight one's inflation over its solo baseline is the- # queueing/head-of-line measure of this daemon under its live- # load.- solo = command_timing(p, {"type": "get_session_stats", "activeSessionId": active}, "solo-baseline", "solo baseline")- trace["steps"].append(solo)- heavy = {"type": "get_context_tree", "activeSessionId": active}- p2 = DaemonProbe(args.socket)- p2.handshake()- result_box = {}- sent = threading.Event()-- def fire_heavy():- try:- env = {"type": "command", "id": "concurrent-heavy", "protocol": PROTOCOL, "command": heavy}- p2.deadline = time.monotonic() + 90.0- t0 = time.time()- p2.s.sendall((json.dumps(env) + "\n").encode())- sent.set()- while True:- msg = p2.read_line()- if msg.get("id") == "concurrent-heavy" and msg.get("type") == "response":- result_box["heavy"] = {"wall_ms": (time.time() - t0) * 1000.0}- return- except Exception as exc: # noqa: BLE001 - the heavy leg's failure is recorded, never swallowed- result_box["heavy_error"] = repr(exc)-- th = threading.Thread(target=fire_heavy)- th.start()- sent.wait(timeout=5.0)- light = command_timing(p, {"type": "get_session_stats", "activeSessionId": active}, "concurrent-light", "concurrent light (stats)")- th.join()- trace["concurrency"] = {- "heavy_label": "get_context_tree",- "heavy_wall_ms": round(result_box["heavy"]["wall_ms"], 2) if result_box.get("heavy") else None,- "heavy_error": result_box.get("heavy_error"),- "light_wall_ms": round(light["wall_ms"], 2),- "light_solo_wall_ms": round(solo["wall_ms"], 2),- "light_inflation_ms": round(light["wall_ms"] - solo["wall_ms"], 2),- "sync": "the light request fires after the heavy request is on the wire; a failed heavy leg records heavy_error instead of a silent null",- }- p2.close()-- # 4. The attach round trip (the Esc-handoff surface): a fresh- # client attaches and detaches.- p3 = DaemonProbe(args.socket)- p3.handshake()- attach = command_timing(p3, {"type": "attach", "activeSessionId": active, "clientId": "latency-trace"}, "attach-fresh", "fresh-client attach (the Esc-handoff surface)")- trace["steps"].append(attach)-- # 5. The client-side view-switch CHAIN: the requests the TUI's- # switch awaits SEQUENTIALLY on one connection, summed — the- # felt round trip's request component (each step inflates- # under fleet contention; the sum is the bound the operator- # feels stacked with the terminal probe below).- chain_steps = [- ({"type": "attach", "activeSessionId": active, "clientId": "latency-trace-chain"}, "chain: attach"),- ({"type": "roster_subscribe", "activeSessionId": active}, "chain: roster subscribe"),- ({"type": "get_session_stats", "activeSessionId": active}, "chain: session stats"),- ({"type": "get_state", "activeSessionId": active}, "chain: state read"),- ({"type": "get_rlm_children", "activeSessionId": active}, "chain: rlm children"),- ({"type": "detach", "activeSessionId": active, "clientId": "latency-trace-chain"}, "chain: detach"),- ]- chain = []- chain_t0 = time.time()- for cmd, label in chain_steps:- chain.append(command_timing(p3, cmd, "chain-step", label))- chain_total = (time.time() - chain_t0) * 1000.0- trace["switch_chain"] = {- "note": "the sequential request chain a view switch awaits on one connection (the client-side request component of the felt round trip)",- "steps": chain,- "total_wall_ms": round(chain_total, 2),- }- # The step-4 attach registered this trace client: detach it, so- # the probe leaves no phantom attached client behind.- command_timing(p3, {"type": "detach", "activeSessionId": active, "clientId": "latency-trace"}, "detach-trace", "detach the trace client")- p3.close()-- # 6. The terminal enhanced-key probe timing (run the trace from inside- # the interactive terminal being compared): the surface start- # blocks input-blind on this answer for up to 2s when the terminal- # does not answer — the terminal-dependent per-switch stall that- # stacks with the request chain.- trace["kitty_probe"] = kitty_probe_timing()-- p.close()- with open(args.out, "w") as f:- json.dump(trace, f, indent=2)- print(json.dumps(trace, indent=2))---if __name__ == "__main__":- main()diff --git a/scripts/left_arrow_pty_repro.py b/scripts/left_arrow_pty_repro.pydeleted file mode 100644index 4e369edb88..0000000000--- a/scripts/left_arrow_pty_repro.py+++ /dev/null@@ -1,669 +0,0 @@-#!/usr/bin/env python3-"""Kevin's live repro on a RAW PTY (no tmux): the harness is the terminal.--A kitty-capable terminal in miniature: it watches the client's byte-stream, answers the kitty keyboard-protocol query and the primary-device attributes query (BOTH answers, or crossterm 0.28's probe thread-parks the shared event reader forever and the app freezes), and sends-keys in the encoding the client's pushed flags call for — kitty CSI-u-press/release pairs once `\x1b[>7u` was pushed, legacy sequences before.--Scenarios, per side (`ts` = the deployed TS release, `rust` = this-branch's build, `dogfood` = the box's public Rust build — the behavior-Kevin ran):--- `left-instant`: a bare LEFT ~0.3s after launch (Kevin's "hit it- immediately"). TS parity: the empty editor's agents-back hands the- pane to the agents view — the client stays alive; nobody may print- "shutdown stalled; forced exit."-- `left-frame`: the same key once the chat painted.-- `left-slow-answer`: the kitty answer is delayed past the whole probe- window, so the key lands while the probe is in flight and the chat- teardown races it. TS has no exit deadline on a view switch; the Rust- client must stay alive and complete the handoff.-- `wedge-force-quit`: a JSONL proxy holds `get_session_stats` requests;- the first faux turn completes, the loop parks in the post-turn stats- refresh (its 10s bound), and a double Ctrl+C pair arrives while the- loop is parked — the force-quit watchdog fires. The forced exit MUST- restore the terminal: the stop-set bytes (paste off, kitty pop,- modifyOtherKeys reset, mouse off, leave alt screen, cursor show) on- the stream and a cooked tty (canonical input + echo) after the exit.-- `quit-normal`: the canonical exit — a faux turn completes, then the- Ctrl+C pair (hint, exit). The exit MUST emit the full stop set and- leave the pty cooked; both the TS release and this build own the same- contract (the exit frame flush is TS parity, not a failure).-- `quit-poisoned`: the pty enters raw mode BEFORE the client starts (a- previous run's broken exit), then the same quit. crossterm's saved- "original" is the poisoned raw state, so `disable_raw_mode` restores- raw: only the exit's cooked-tty verification/repair (this port's- hardening — TS restores its own captured `wasRaw`, the poisoned state)- can end cooked. Gates this build; the TS side records the divergence.--Facts per scenario: alive/exited + exit code, the "shutdown stalled"-message, the kitty push/pop balance, the stop-set presence, the pty-termios after a leave, whether the handoff painted the roster surface.--Each scenario runs against its OWN daemon on its OWN sandboxed socket-(the client auto-spawns it; the wedge scenario fronts it with the-stalling proxy). Daemons are reaped by their unique socket path, never-by pattern.-"""--import argparse-import fcntl-import glob-import json-import os-import re-import select-import shutil-import signal-import socket-import struct-import subprocess-import sys-import tempfile-import termios-import threading-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-import visual_parity as vp # noqa: E402--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import ts_identity # noqa: E402--SIZE = (120, 36)--#: The deployed TS release binary (the parity side; the PATH-#: `prime-agent` may be this repo's dogfood build — ts_identity guards-#: against playing that as TS).-_release_glob = os.path.expanduser(- "~/.local/share/prime-agent/releases/0.9.5-linux-x64-*/prime-agent"-)-_release_hits = sorted(glob.glob(_release_glob))-TS_BIN = os.environ.get("TS_BIN") or (_release_hits[-1] if _release_hits else "prime-agent")-RUST_BIN = os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)), "..", "target", "debug", "prime-agent"- ),-)-DOGFOOD_BIN = os.environ.get("PA_DOGFOOD_BINARY", "/usr/local/bin/prime-agent")-# `os.execve` never resolves PATH: a bare command name (the Mac's `prime-agent`-# symlink) must resolve to its absolute path or the forked client dies on-# ENOENT before it ever paints.-if os.path.sep not in TS_BIN:- _resolved = shutil.which(TS_BIN)- if _resolved:- TS_BIN = _resolved--#: The kitty query answer: flags 1|2|4 (what a terminal supporting all-#: three pushed modes answers), then the DA1 answer — crossterm's probe-#: blocks reading the primary device attributes after the flags answer.-KITTY_FLAGS_ANSWER = b"\x1b[?7u"-DA1_ANSWER = b"\x1b[?62;c"-KITTY_QUERY = b"\x1b[?u"--#: Byte markers whose balance proves the terminal modes come back.-KITTY_PUSH = b"\x1b[>7u"-KITTY_POP = b"\x1b[<u"-PASTE_OFF = b"\x1b[?2004l"-MODIFY_RESET = b"\x1b[>4;0m"-MOUSE_OFF = b"\x1b[?1006l"-LEAVE_ALT = b"\x1b[?1049l"-CURSOR_SHOW = b"\x1b[?25h"--#: The needles: the chat settle marker (the same one the tmux harnesses-#: use), the faux reply, and the agents-view roster surface.-CHAT_SETTLE = b"Collapsed mode"-FAUX_REPLY = b"arrow repro"-AGENTS_VIEW_NEEDLE = b" idle, "--#: The worker-role marker in a daemon worker's environment; the wedge-#: scenario SIGSTOPs the sandbox's worker so the next prompt request-#: parks the UI loop in its 10s bound while the reader thread stays-#: alive to observe the Ctrl+C pair (the session traffic rides the-#: direct worker transport, so a supervisor-socket proxy cannot hold it).-WORKER_ROLE_MARKER = b"PRIME_AGENT_INTERNAL_DAEMON_WORKER=1"--FAUX_SCRIPT = {- "engine": "faux",- "modelId": "faux-1",- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 18,- "responses": [{"text": "left arrow repro reply"}],-}---def side_binary(side):- if side == "ts":- return TS_BIN- if side == "dogfood":- return DOGFOOD_BIN- return RUST_BIN---def side_env(side, sandbox):- # This harness may itself run inside a prime-agent daemon worker:- # the inherited PRIME_AGENT_INTERNAL_* role vars would start an- # explicitly spawned daemon in WORKER mode against the box's real- # supervisor (the auto-spawn path strips the same set).- env = {k: v for k, v in os.environ.items() if not k.startswith("PRIME_AGENT_INTERNAL_")}- env.update(- {- "HOME": sandbox["home"],- "TMPDIR": sandbox["tmp"],- "PRIME_AGENT_CODING_AGENT_DIR": sandbox["agent"],- "PRIME_AGENT_FAUX_SCRIPT": sandbox["faux_script"],- "PRIME_AGENT_DISABLE_ANALYTICS": "1",- }- )- env.pop("TMUX", None)- if side in ("rust", "dogfood"):- env["PI_PACKAGE_DIR"] = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- return env---class PtyClient:- """One TUI client on a raw pty: the harness is the terminal."""-- def __init__(self, side, sandbox, answer_policy, poison_raw=False):- self.side = side- self.sandbox = sandbox- self.answer_policy = answer_policy- # `quit-poisoned`: the slave termios enters raw mode before the- # client forks (a previous run's broken exit), so the client's- # saved "original" mode is itself raw.- self.poison_raw = poison_raw- self.master = None- self.pid = None- self.stream = bytearray()- self.exited = False- self.exit_code = None- self.pushes = 0- self.pops = 0- self.queries_scheduled = 0-- def start(self, socket_path):- self.master, slave = pty_open_raw()- if self.poison_raw:- attrs = termios.tcgetattr(slave)- attrs[3] &= ~(termios.ICANON | termios.ECHO | termios.ISIG)- attrs[1] &= ~(termios.ICRNL | termios.IXON)- attrs[3] &= ~termios.IEXTEN- termios.tcsetattr(slave, termios.TCSANOW, attrs)- pid = os.fork()- if pid == 0:- os.setsid()- fcntl.ioctl(slave, termios.TIOCSCTTY, 0)- os.dup2(slave, 0)- os.dup2(slave, 1)- os.dup2(slave, 2)- if slave > 2:- os.close(slave)- os.close(self.master)- os.chdir(self.sandbox["cwd"])- env = side_env(self.side, self.sandbox)- argv = [side_binary(self.side), "--daemon-socket", socket_path,- "--model", vp.TS_SCRIPT_MODEL]- os.execve(argv[0], argv, env)- self.pid = pid- os.close(slave)- fcntl.ioctl(self.master, termios.TIOCSWINSZ, struct.pack("HHHH", SIZE[1], SIZE[0], 0, 0))- return pid-- def send_bytes(self, data):- try:- os.write(self.master, data)- except OSError:- pass-- def send_left(self):- if self.pushes > self.pops:- # Kitty flags pushed: a real terminal sends the CSI-u- # press/release pair for the arrow (codepoint 57417).- self.send_bytes(b"\x1b[57417;1:1u")- time.sleep(0.02)- self.send_bytes(b"\x1b[57417;1:3u")- else:- self.send_bytes(b"\x1b[D")-- def send_text(self, text):- self.send_bytes(text.encode())-- def send_ctrl_c(self):- if self.pushes > self.pops:- self.send_bytes(b"\x1b[99;5:1u")- time.sleep(0.02)- self.send_bytes(b"\x1b[99;5:3u")- else:- self.send_bytes(b"\x03")-- def pump(self, seconds):- deadline = time.time() + seconds- while time.time() < deadline:- self.pump_once(0.05)-- def pump_once(self, timeout):- ready, _, _ = select.select([self.master], [], [], timeout)- if ready:- try:- chunk = os.read(self.master, 65536)- except OSError:- return False- if not chunk:- return False- self.stream.extend(chunk)- self.pushes += chunk.count(KITTY_PUSH)- self.pops += chunk.count(KITTY_POP)- self.schedule_answers()- return True-- def schedule_answers(self):- """Answer every kitty query seen exactly once, on the policy's- delay (measured from when the query appeared in the stream)."""- seen = bytes(self.stream).count(KITTY_QUERY) - self.queries_scheduled- if seen <= 0 or not self.answer_policy.get("answer", True):- return- self.queries_scheduled += seen- delay = self.answer_policy.get("delay_ms", 0) / 1000.0- if delay <= 0:- self._write_answers()- else:- threading.Timer(delay, self._write_answers).start()-- def _write_answers(self):- # Two separate writes: TS's kitty-response handler pattern is- # line-anchored, so the flags answer must arrive as its own chunk.- self.send_bytes(KITTY_FLAGS_ANSWER)- time.sleep(0.02)- self.send_bytes(DA1_ANSWER)-- def alive(self):- if self.exited:- return False- pid, status = os.waitpid(self.pid, os.WNOHANG)- if pid == self.pid:- self.exited = True- self.exit_code = os.waitstatus_to_exitcode(status)- return False- return True-- def wait_exit(self, timeout):- deadline = time.time() + timeout- while time.time() < deadline:- self.pump_once(0.1)- if not self.alive():- return True- return False-- def termios_cooked(self):- try:- attrs = termios.tcgetattr(self.master)- except termios.error:- return {"error": "tcgetattr failed"}- return {- "icanon": bool(attrs[3] & termios.ICANON),- "echo": bool(attrs[3] & termios.ECHO),- }-- def kill(self):- if not self.exited:- try:- os.kill(self.pid, signal.SIGKILL)- except OSError:- pass- try:- os.waitpid(self.pid, 0)- except (ChildProcessError, OSError):- pass- if self.master is not None:- try:- os.close(self.master)- except OSError:- pass---def pty_open_raw():- import pty as pty_mod-- return pty_mod.openpty()---def stream_has(client, needle):- """Match a text needle on the ANSI-stripped stream: styled or wrapped- output interleaves escape sequences inside the raw bytes."""- if isinstance(needle, bytes):- needle = needle.decode()- return needle in visible_text(client.stream)---def wait_for_needle(client, needle, timeout):- deadline = time.time() + timeout- while time.time() < deadline:- client.pump_once(0.2)- if stream_has(client, needle):- return True- if not client.alive():- return stream_has(client, needle)- return stream_has(client, needle)---def visible_text(stream):- text = bytes(stream)- text = re.sub(b"\x1b\\[\\??[0-9;:]*[a-zA-Z]", b"", text)- text = re.sub(b"\x1b\\][^\x07\x1b]*(\x07|\x1b\\\\)", b"", text)- return text.decode(errors="replace")---def daemon_pids_for(socket_path):- """Live `--mode daemon` processes whose argv references this socket."""- found = []- if not os.path.isdir("/proc"):- return found # non-Linux: the pid discovery is VM-only- for entry in os.listdir("/proc"):- if not entry.isdigit():- continue- try:- with open(f"/proc/{entry}/cmdline", "rb") as f:- cmdline = f.read()- except OSError:- continue- if b"--mode" in cmdline and socket_path.encode() in cmdline:- found.append(int(entry))- return found---def kill_daemons(socket_path, sandbox=None):- for pid in daemon_pids_for(socket_path):- try:- os.kill(pid, signal.SIGTERM)- except OSError:- pass- time.sleep(0.5)- for pid in daemon_pids_for(socket_path):- try:- os.kill(pid, signal.SIGKILL)- except OSError:- pass- # The sandbox's detached session workers outlive their supervisor- # (the worker's supervisor-loss timeout is five minutes): reap them- # too, or every scenario leaves a worker behind that the next- # scenario's wedge may SIGSTOP instead of its own. Resume any this- # scenario stopped so the TERM is observable.- if sandbox is not None:- for pid in sandbox_worker_pids(sandbox):- try:- os.kill(pid, signal.SIGCONT)- except OSError:- pass- for pid in sandbox_worker_pids(sandbox):- try:- os.kill(pid, signal.SIGTERM)- except OSError:- pass- time.sleep(0.5)- for pid in sandbox_worker_pids(sandbox):- try:- os.kill(pid, signal.SIGKILL)- except OSError:- pass---def sandbox_worker_pids(sandbox):- """Daemon worker processes belonging to THIS sandbox: the worker-role- env marker plus the sandbox agent dir in the environment (never a- bare pattern; other daemons on the box are untouched)."""- agent_marker = sandbox["agent"].encode()- found = []- if not os.path.isdir("/proc"):- return found # non-Linux: the pid discovery is VM-only- for entry in os.listdir("/proc"):- if not entry.isdigit():- continue- try:- with open(f"/proc/{entry}/environ", "rb") as f:- environ = f.read()- except OSError:- continue- if WORKER_ROLE_MARKER in environ and agent_marker in environ:- found.append(int(entry))- return found---def run_scenario(side, sandbox, label, answer_policy, wedge=False):- socket_path = os.path.join(sandbox["agent"], f"daemon-{label}-{side}.sock")- stopped_workers = []- facts = {"side": side, "scenario": label}- if wedge and not os.path.isdir("/proc"):- # The wedge scenario SIGSTOPs this sandbox's worker by pid:- # without /proc (non-Linux dev runs) there is no worker to stop- # and no daemon reap — skip LOUDLY instead of silently running a- # degenerate scenario that can never fire the force quit.- print(f"[skip] {side} {label}: /proc unavailable (run on the Linux VM)")- facts["skipped"] = True- return facts- client = PtyClient(side, sandbox, answer_policy, poison_raw=label == "quit-poisoned")- try:- client.start(socket_path)- if label == "left-instant":- time.sleep(0.3)- client.send_left()- elif label in ("quit-normal", "quit-poisoned"):- facts["chat_settled"] = wait_for_needle(client, CHAT_SETTLE, timeout=60)- client.send_text("hello\r")- facts["reply_streamed"] = wait_for_needle(client, FAUX_REPLY, timeout=60)- client.pump(1.0)- # The canonical exit gesture: the hint press, then the exit.- client.send_ctrl_c()- client.pump(0.8)- client.send_ctrl_c()- else:- facts["chat_settled"] = wait_for_needle(client, CHAT_SETTLE, timeout=60)- if label == "left-frame":- client.pump(0.6)- client.send_left()- elif label == "left-slow-answer":- client.pump(0.4)- client.send_left()- elif label == "wedge-force-quit":- client.send_text("hello\r")- facts["reply_streamed"] = wait_for_needle(client, FAUX_REPLY, timeout=60)- # Freeze this sandbox's worker, then submit again: the- # prompt request rides the direct worker transport into- # the stopped worker and parks the UI loop in its 10s- # bound. The Ctrl+C pair lands while the loop is parked- # (the reader thread still observes it), so the- # force-quit watchdog fires — the exit_guard's exact- # contract for a wedged daemon request.- client.pump(1.0)- stopped_workers.extend(sandbox_worker_pids(sandbox))- facts["workers_stopped"] = len(stopped_workers)- for pid in stopped_workers:- os.kill(pid, signal.SIGSTOP)- client.send_text("again\r")- client.pump(1.0)- client.send_ctrl_c()- client.pump(0.3)- client.send_ctrl_c()- deadline = time.time() + 12- while time.time() < deadline and client.alive():- client.pump_once(0.2)- facts["alive"] = client.alive()- if not facts["alive"]:- client.wait_exit(3)- facts["exit_code"] = client.exit_code- text = bytes(client.stream)- facts["shutdown_stalled"] = b"shutdown stalled" in text- facts["kitty_pushes"] = client.pushes- facts["kitty_pops"] = client.pops- facts["handoff_painted"] = AGENTS_VIEW_NEEDLE.decode() in visible_text(text)- facts["stop_set"] = {- "paste_off": PASTE_OFF in text,- "kitty_pop": KITTY_POP in text,- "modify_reset": MODIFY_RESET in text,- "mouse_off": MOUSE_OFF in text,- "leave_alt": LEAVE_ALT in text,- "cursor_show": CURSOR_SHOW in text,- }- facts["push_pop_balanced"] = client.pops >= client.pushes- if not facts["alive"]:- facts["termios_after"] = client.termios_cooked()- facts["tail_text"] = visible_text(client.stream)[-400:]- finally:- client.kill()- for pid in stopped_workers:- try:- os.kill(pid, signal.SIGCONT)- except OSError:- pass- kill_daemons(socket_path, sandbox)- return facts---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--sides", default=None, help="comma list: ts,rust,dogfood")- parser.add_argument("--scenarios", default=None, help="comma list of scenario labels")- parser.add_argument("--keep", action="store_true")- args = parser.parse_args()-- sides = args.sides.split(",") if args.sides else ["ts", "rust", "dogfood"]- if "ts" in sides:- ts_identity.assert_ts_side_is_the_ts_product(ts_bin=TS_BIN)-- base = tempfile.mkdtemp(prefix="left-arrow-pty-")- print(f"sandbox root: {base}")- shared_cwd, script_path, sandboxes = vp.prepare_sandbox(base)- with open(script_path, "w") as f:- json.dump(FAUX_SCRIPT, f, indent=2)- for sandbox in sandboxes.values():- sandbox["cwd"] = shared_cwd- sandbox["faux_script"] = script_path- # The Rust settings loader keys onboarding on `onboardingShown`- # (the TS sandbox key is `onboardingCompleted`): write both, or a- # fresh Rust client opens the trace-consent screen and the LEFT- # goes to its selector instead of the chat editor.- with open(os.path.join(sandbox["agent"], "settings.json"), "w") as f:- json.dump({"onboardingCompleted": True, "onboardingShown": True}, f)- dogfood_sandbox = {- "home": os.path.join(base, "dogfood", "home"),- "agent": os.path.join(base, "dogfood", "agent"),- "tmp": os.path.join(base, "dogfood", "tmp"),- "cwd": shared_cwd,- "faux_script": script_path,- }- for key in ("home", "agent", "tmp"):- os.makedirs(dogfood_sandbox[key], exist_ok=True)- os.makedirs(os.path.join(dogfood_sandbox["agent"], "sessions"), exist_ok=True)- with open(os.path.join(dogfood_sandbox["agent"], "settings.json"), "w") as f:- json.dump({"onboardingCompleted": True, "onboardingShown": True}, f)- sandbox_for = {- "ts": sandboxes["ts"],- "rust": sandboxes["rust"],- "dogfood": dogfood_sandbox,- }-- all_scenarios = [- "left-instant",- "left-frame",- "left-slow-answer",- "wedge-force-quit",- "quit-normal",- "quit-poisoned",- ]- scenarios = args.scenarios.split(",") if args.scenarios else all_scenarios-- results = {}- try:- for side in sides:- for label in scenarios:- policy = {"answer": True, "delay_ms": 0}- if label == "left-slow-answer":- policy = {"answer": True, "delay_ms": 2600}- wedge = label == "wedge-force-quit"- facts = run_scenario(side, sandbox_for[side], label, policy, wedge=wedge)- results[f"{side}:{label}"] = facts- print(f"[pty] {side} {label}: {json.dumps(facts)[:900]}", flush=True)- finally:- if not args.keep:- subprocess.run(["rm", "-rf", base], check=False)-- failures = []- for key, facts in results.items():- if facts.get("skipped"):- continue # the loud /proc skip: recorded, never gated- side, label = key.split(":")- if label.startswith("left-"):- if facts.get("shutdown_stalled"):- failures.append(f"{key}:forced-exit-on-left")- if facts.get("alive") is False:- failures.append(f"{key}:client-died")- # The canonical quit owns the same stop-set contract on both the- # TS release and this build (parity: TS `TUI.stop` +- # `ProcessTerminal.stop`); the cooked-tty repair after a poisoned- # start is this port's hardening — TS restores its own captured- # `wasRaw` (the poisoned state), so the TS side records the- # divergence instead of gating.- if label == "quit-normal" and side in ("rust", "ts"):- if facts.get("exit_code") != 0:- failures.append(f"{key}:exit-code={facts.get('exit_code')}")- stop = facts.get("stop_set") or {}- # TS writes the modifyOtherKeys reset only when its fallback- # armed the mode (kitty answered here, so TS never does); this- # port always writes the defensive reset — required on rust,- # optional on ts.- parts = ("paste_off", "kitty_pop", "mouse_off", "leave_alt", "cursor_show")- if side == "rust":- parts = parts + ("modify_reset",)- for part in parts:- if stop.get(part) is not True:- failures.append(f"{key}:missing-{part}")- termios_state = facts.get("termios_after") or {}- if termios_state.get("icanon") is not True or termios_state.get("echo") is not True:- failures.append(f"{key}:tty-not-cooked")- if label == "quit-poisoned" and side == "rust":- if facts.get("exit_code") != 0:- failures.append(f"{key}:exit-code={facts.get('exit_code')}")- termios_state = facts.get("termios_after") or {}- if termios_state.get("icanon") is not True or termios_state.get("echo") is not True:- failures.append(f"{key}:poisoned-start-not-repaired")- if label == "quit-poisoned" and side == "ts":- # TS restores its captured `wasRaw` (the poisoned raw) on- # exit — the divergence is recorded, not gated: it is TS's- # own behavior, not this port's regression.- pass- # The wedge stop-set gate holds only for this branch's build:- # TS has no force-quit watchdog at all (it stays alive), and the- # dogfood side is the recorded "before" — its missing restore- # writes are the bug being fixed, not a regression.- if label == "wedge-force-quit" and side == "rust":- if facts.get("exit_code") is None:- failures.append(f"{key}:no-force-quit")- if facts.get("shutdown_stalled") is not True:- failures.append(f"{key}:no-stall-message")- stop = facts.get("stop_set") or {}- for part in (- "paste_off",- "kitty_pop",- "modify_reset",- "mouse_off",- "leave_alt",- "cursor_show",- ):- if stop.get(part) is not True:- failures.append(f"{key}:missing-{part}")- termios_state = facts.get("termios_after") or {}- if termios_state.get("icanon") is not True or termios_state.get("echo") is not True:- failures.append(f"{key}:tty-not-cooked")- for failure in failures:- print(f"FAIL {failure}")- print("LEFT-ARROW PTY REPRO:", "RED" if failures else "GREEN")- return 1 if failures else 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/mcp_hint_parity.py b/scripts/mcp_hint_parity.pydeleted file mode 100755index 6a6e5b7153..0000000000--- a/scripts/mcp_hint_parity.py+++ /dev/null@@ -1,545 +0,0 @@-#!/usr/bin/env python3-"""`/plugins` vs `/mcp` pinned-definition hint parity verifier.--The MCP catalog-source-unavailable hint (`service-catalog.ts:1081,1102` in-TS, `catalog_plugin_views.rs` in the Rust port) claims a connection record-outlived its catalog entry. The claim is honest only when a validated-remote catalog snapshot is in hand to PROVE the service is gone — TS always-has its catalog (compiled into the deployed release), so it never claims-absence it cannot prove; the Rust port falls silent when it has no snapshot-(the fetch never ran, failed, or the bundled asset is missing).--The gating matrix, driven like a user in tmux on both products with the-SAME seeded fixtures (a pending `linear` record whose service IS in the-catalog, and a pending `vanished-fixture` record whose service is in NO-source):--+---------------------------+--------------------+------------------+-| cell | surface | expected hint |-+---------------------------+--------------------+------------------+-| ts_vanished | /plugins picker | SHOWN, byte- |-| | (compiled catalog) | exact TS string |-| ts_linear | /plugins picker | hidden |-| rust_vanished_cached | /mcp view (the | SHOWN, byte- |-| | snapshot cache) | exact TS string |-| rust_linear_cached | /mcp view | hidden |-| rust_vanished_uncached | /mcp view (no | hidden (the fix: |-| | snapshot at all) | no provable |-| | | absence, no hint)|-| rust_linear_uncached | /mcp view | hidden |-+---------------------------+--------------------+------------------+--Every cell also asserts the row itself: the pinned row keeps its label-("Vanished Fixture") and stays `Not connected`; the resolved linear row-stays `Needs verification` with its catalog description as the detail.-The vanished row's line and the hint line are byte-compared across the-two products (identical wording, placement, and timing is the lane's-parity bar).--Frames land in --out-dir (one .txt per cell) plus report.txt; the exit-code is non-zero when any expectation fails.-"""--import argparse-import glob-import json-import os-import re-import shlex-import shutil-import subprocess-import sys-import tempfile-import time-import uuid--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--WIDTH, HEIGHT = 140, 40--#: The hint under test, byte-exact (TS `service-catalog.ts:1082`); the-#: picker renders its detail line with one leading space.-HINT = "This service's catalog source is unavailable; its connection keeps the pinned definition."-HINT_LINE = " " + HINT--#: TS 0.9.5 compiled-catalog linear description prefix (the resolved row's-#: detail line).-LINEAR_DESCRIPTION_PREFIX = "Search, create and update Linear issues"--#: The two pending connection records, byte-identical on both products:-#: `linear` resolves against the catalog; `vanished-fixture` is in NO source.-RECORDS = {- "version": 1,- "connections": {- "linear": {- "connectionId": "linear",- "serviceId": "linear",- "endpoint": "https://mcp.linear.app/mcp",- "label": "Linear",- "status": "pending",- "createdAt": 1,- "updatedAt": 1,- },- "vanished-fixture": {- "connectionId": "vanished-fixture",- "serviceId": "vanished-fixture",- "endpoint": "https://vanished.example/mcp",- "label": "Vanished Fixture",- "status": "pending",- "createdAt": 1,- "updatedAt": 1,- },- },-}--#: The fetch lane's snapshot envelope (pa-models `SnapshotFile`, the TS-#: `CatalogCache` disk form): this catalog url, public scope, any age.-CATALOG_URL = (- "https://raw.githubusercontent.com/PrimeIntellect-ai/prime-agent-catalog"- "/main/plugins/catalog.v2.json"-)-FETCHED_AT = 1_790_082_036_135--#: The repo-relative fixture the pa-core/e2e parity corpus already pins:-#: the real catalog document, so the cached side's roster byte-matches the-#: deployed TS release's compiled catalog.-FIXTURE = os.path.join(- os.path.dirname(os.path.dirname(os.path.abspath(__file__))),- "crates", "pa-core", "tests", "fixtures", "mcp", "plugins-catalog.v2.json",-)--#: The faux provider contract (visual_parity's TS_SCRIPT_MODEL): both-#: products boot against a scripted provider with zero turns — the /plugins-#: and /mcp surfaces read the service catalog and the records, never the-#: model.-FAUX_MODEL = "faux-1"-FAUX_SCRIPT = {- "engine": "faux",- "modelId": "faux-1",- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "responses": [],-}---def tmux(*args, check=True):- result = subprocess.run(["tmux", *args], capture_output=True, text=True, check=False)- if check and result.returncode != 0:- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")- return result.stdout---def ansi_stripped(text: str) -> str:- text = re.sub(r"\x1b\][^\x07]*(\x07|\x1b\\)", "", text)- text = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", text)- text = re.sub(r"\x1b[()][0-9A-B]", "", text)- return text---def capture(session: str) -> str:- # Plain `-p` (tmux's rendered text): escape sequences are dropped by- # tmux itself. `-p -e` instead splits an escape sequence at a wrapped- # line boundary and strands its tail in the captured text (observed:- # the splash's colorized "prime agent \x1b[38;2;16" line), corrupting- # every byte-level assertion downstream.- raw = tmux("capture-pane", "-t", session, "-p")- lines = [ansi_stripped(line).rstrip() for line in raw.splitlines()]- while lines and not lines[-1]:- lines.pop()- return "\n".join(lines)---def wait_for(session: str, needle: str, timeout: float) -> None:- deadline = time.time() + timeout- while time.time() < deadline:- if needle in capture(session):- return- time.sleep(0.4)- raise TimeoutError(f"session {session} never showed {needle!r}")---def launch(session: str, agent_dir: str, command: str, tmp_dir: str) -> None:- tmux("kill-session", "-t", session, check=False)- tmux("new-session", "-d", "-s", session, "-x", str(WIDTH), "-y", str(HEIGHT))- time.sleep(0.5)- os.makedirs(tmp_dir, exist_ok=True)- # TMPDIR must stay SHORT: the daemon's per-session worker sockets land in- # `<TMPDIR>/prime-agent-<uid>/worker-<id>.sock`, and a unix domain socket- # path caps at 108 bytes (observed: `listen EINVAL` with the deep- # worktree path; the battery sandboxes live under short /tmp paths for- # the same reason). The OS temp root plus the run id keep it shallow- # and private to this invocation (see short_tmp).- socket_probe = os.path.join(tmp_dir, "prime-agent-1000", "worker-xxxxxxxxxxxx-yyyyyyyyyyyy.sock")- if len(socket_probe) >= 108:- raise RuntimeError(- f"TMPDIR {tmp_dir} is too deep for the worker unix sockets ({len(socket_probe)} >= 108)"- )- # The pane runs a shell, so every interpolated value is quoted: an- # out-dir with spaces (or shell metacharacters) must not redirect- # HOME/TMPDIR/the coding-agent dir somewhere wrong or run unintended- # commands instead of starting the agent.- env = (- f"HOME={shlex.quote(os.path.join(agent_dir, 'home'))} "- f"TMPDIR={shlex.quote(tmp_dir)} "- f"PRIME_AGENT_CODING_AGENT_DIR={shlex.quote(agent_dir)} "- f"PRIME_AGENT_DISABLE_ANALYTICS=1 {command}"- )- tmux("send-keys", "-t", session, env, "Enter")---def close(session: str) -> None:- tmux("send-keys", "-t", session, "Escape")- time.sleep(1.0)---def capture_cell(session: str, command: str, query: str, row_label: str, out_dir: str, name: str) -> str:- """Open the picker/view, type the query, wait for the row, capture."""- tmux("send-keys", "-t", session, command, "Enter")- time.sleep(1.5)- tmux("send-keys", "-t", session, query)- wait_for(session, row_label, 20.0)- time.sleep(1.0)- frame = capture(session)- with open(os.path.join(out_dir, f"{name}.txt"), "w") as handle:- handle.write(frame + "\n")- close(session)- return frame---def side_row(frame: str, label: str) -> str:- """The rendered row line for `label` (the picker's MenuRow line)."""- for line in frame.splitlines():- if line.strip().startswith("›") and label in line:- return line.rstrip()- return ""---def hint_line(frame: str) -> str:- """The rendered hint detail line, byte-exact, when present."""- for line in frame.splitlines():- if line.strip() == HINT:- return line- return ""---def lines_below_row(frame: str, row: str) -> list:- """Every rendered line under `row` until the key hint."""- lines = frame.splitlines()- for index, line in enumerate(lines):- if line == row:- below = []- for follow in lines[index + 1 :]:- if "navigate" in follow and "close" in follow:- break- below.append(follow)- return below- return []---def default_ts_binary() -> str:- """The TS side's launch command. The deployed 0.9.5 release binary- predates the service catalog (#2330): it has neither /plugins nor the- pinned-definition hint. The parity ground truth is the TS-main CLI- bundle in the read-only checkout (queue_edit_parity's rule); the- deployed release is the fallback."""- override = os.environ.get("PA_TS_BINARY")- if override:- return override- ts_main_cli = os.path.join(- "/home/ubuntu", "prime-agent", "packages", "coding-agent", "dist", "bundle", "cli.js"- )- if os.path.exists(ts_main_cli):- return f"node {shlex.quote(ts_main_cli)}"- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- candidates = sorted(glob.glob(os.path.join(releases, "0.9.5-linux-x64-*", "prime-agent")))- if not candidates:- raise SystemExit("no TS-main checkout and no deployed 0.9.5 release; set PA_TS_BINARY")- return shlex.quote(candidates[-1])---def runtime_package_dir() -> str:- """The installed TS release that ships prime-agent-runtime (the Rust- kernel's sidecar). No release on this box carries a bundled- mcp-services.bundled.json, so the uncached cell stays provably- uncached."""- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- candidates = sorted(- entry- for entry in glob.glob(os.path.join(releases, "*"))- if os.path.isdir(os.path.join(entry, "prime-agent-runtime"))- )- if not candidates:- raise SystemExit("no release with prime-agent-runtime/ found; set PI_PACKAGE_DIR")- return candidates[-1]---def short_tmp(run_id: str, side: str) -> str:- """A per-invocation but SHALLOW TMPDIR (see launch): deep paths break- the worker unix sockets with EINVAL. The run id keeps concurrent runs- from sharing a pane, a TMPDIR, or a daemon-reap needle; the OS temp- root keeps the socket path under the 108-byte cap on any checkout."""- return os.path.join(tempfile.gettempdir(), f"pa-mcp-hint-{run_id}", side)---def faux_script_path(agent_dir: str) -> str:- """The faux script lives beside the side's agent dir (inside the- harness's out-dir, never in the repo tree)."""- return os.path.join(os.path.dirname(agent_dir), "faux-script.json")---def seed_agent_dir(agent_dir: str, cache: bool, ts_extension: bool) -> None:- os.makedirs(os.path.join(agent_dir, "sessions"), exist_ok=True)- os.makedirs(os.path.join(agent_dir, "home"), exist_ok=True)- os.makedirs(os.path.join(agent_dir, "tmp"), exist_ok=True)- os.makedirs(os.path.join(agent_dir, "extensions"), exist_ok=True)- with open(os.path.join(agent_dir, "mcp-connections.json"), "w") as handle:- json.dump(RECORDS, handle)- if cache:- with open(FIXTURE) as handle:- payload = json.load(handle)- with open(os.path.join(agent_dir, "mcp-service-catalog.v2.json"), "w") as handle:- json.dump(- {"url": CATALOG_URL, "scope": "public", "fetchedAt": FETCHED_AT, "payload": payload},- handle,- )- # Onboarding must never appear: the trace-opt-in prompt (TS's final- # onboarding question) and the telemetry notice would swallow the- # /plugins and /mcp keys. Both products read the same settings keys- # (TS-parity wire identifiers).- with open(os.path.join(agent_dir, "settings.json"), "w") as handle:- json.dump(- {- "onboardingShown": True,- "agentTraces": {"enabled": True},- "telemetry": {"noticeShown": True},- },- handle,- )- # The faux provider keeps the boot deterministic: no provider auth, no- # model-catalog fetch, no kernel rebuild (the visual-parity battery- # contract; the Rust build reads PRIME_AGENT_FAUX_SCRIPT natively, the- # TS checkout through the shared ts_faux_extension.js sandbox driver).- with open(faux_script_path(agent_dir), "w") as handle:- json.dump(FAUX_SCRIPT, handle)- if ts_extension:- with open(- os.path.join(os.path.dirname(os.path.abspath(__file__)), "ts_faux_extension.js"),- encoding="utf-8",- ) as handle:- extension = handle.read()- with open(os.path.join(agent_dir, "extensions", "mcp-hint-faux.js"), "w") as handle:- handle.write(extension)---def run_ts(ts_binary: str, out_dir: str, results: list, run_id: str) -> None:- agent_dir = os.path.join(out_dir, "ts-agent")- os.makedirs(agent_dir, exist_ok=True)- seed_agent_dir(agent_dir, cache=False, ts_extension=True)- session = f"mcp-hint-{run_id}-ts"- # The session is killed on EVERY exit path: a failed launch or a boot- # timeout must not leave the pane alive for a later run to reuse.- try:- launch(- session,- agent_dir,- (- f"PRIME_AGENT_FAUX_SCRIPT={shlex.quote(faux_script_path(agent_dir))} "- f"{ts_binary} --daemon-socket {shlex.quote(os.path.join(agent_dir, 'daemon.sock'))} "- f"--model {FAUX_MODEL}"- ),- short_tmp(run_id, "ts"),- )- # Mode-neutral settled-editor needle (queue_edit_parity's proven boot- # marker): TS-main opens in Details mode, the Rust build in Collapsed- # mode.- wait_for(session, "mode (Ctrl+O to expand)", 120.0)- time.sleep(2.0)- results.append(("ts_vanished", capture_cell(session, "/plugins", "vanished", "Vanished Fixture", out_dir, "ts_vanished")))- results.append(("ts_linear", capture_cell(session, "/plugins", "linear", "Linear", out_dir, "ts_linear")))- finally:- tmux("kill-session", "-t", session, check=False)---def run_rust(rust_binary: str, out_dir: str, results: list, cache: bool, run_id: str) -> None:- suffix = "cached" if cache else "uncached"- agent_dir = os.path.join(out_dir, f"rust-{suffix}-agent")- os.makedirs(agent_dir, exist_ok=True)- seed_agent_dir(agent_dir, cache=cache, ts_extension=False)- session = f"mcp-hint-{run_id}-rs-{suffix}"- package_dir = os.environ.get("PI_PACKAGE_DIR") or runtime_package_dir()- # The session is killed on EVERY exit path: a failed launch or a boot- # timeout must not leave the pane alive for a later run to reuse.- try:- launch(- session,- agent_dir,- (- f"PI_PACKAGE_DIR={shlex.quote(package_dir)} "- f"PI_OFFLINE=1 "- f"PRIME_AGENT_FAUX_SCRIPT={shlex.quote(faux_script_path(agent_dir))} "- f"{shlex.quote(rust_binary)} --daemon-socket {shlex.quote(os.path.join(agent_dir, 'daemon.sock'))} "- f"--model {FAUX_MODEL}"- ),- short_tmp(run_id, suffix),- )- wait_for(session, "mode (Ctrl+O to expand)", 150.0)- time.sleep(2.0)- results.append(- (- f"rust_vanished_{suffix}",- capture_cell(session, "/mcp", "vanished", "Vanished Fixture", out_dir, f"rust_vanished_{suffix}"),- )- )- results.append(- (- f"rust_linear_{suffix}",- capture_cell(session, "/mcp", "linear", "Linear", out_dir, f"rust_linear_{suffix}"),- )- )- finally:- tmux("kill-session", "-t", session, check=False)---def check_cell(name: str, frame: str, report: list) -> bool:- """The matrix expectation for one cell. The row always stays; the hint- only when the cell names it."""- ok = True- row = side_row(frame, "Vanished Fixture") if "vanished" in name else side_row(frame, "Linear")- if not row:- report.append(f"FAIL {name}: the row never rendered")- return False- # The pinned row is deterministic (never one-click connectable -> the- # muted "Not connected"); the linear row's trailing status is- # record/grant-state dependent (a fresh pending record without a- # credential is the stale-connection state -> "Connect"), so it is- # recorded for the frame diff rather than hard-asserted.- expect_status = "Not connected" if "vanished" in name else None- if expect_status and not row.endswith(expect_status):- report.append(f"FAIL {name}: row {row!r} does not end with {expect_status!r}")- ok = False- else:- report.append(f"ok {name}: row {row.strip()!r}")- if "vanished" in name and ("uncached" not in name):- # The hint must sit in the VANISHED row's own detail block (the- # lines under the row, above the footer) — the same text anywhere- # else in the frame is not a pass.- block = lines_below_row(frame, row)- hint = next((line for line in block if line.strip() == HINT), "")- if not hint:- report.append(f"FAIL {name}: the pinned hint is MISSING from the row's detail block")- return False- if hint != HINT_LINE:- report.append(f"FAIL {name}: hint line {hint!r} != {HINT_LINE!r}")- ok = False- else:- report.append(f"ok {name}: hint line byte-exact in the row's detail block")- else:- hint = hint_line(frame)- if hint:- report.append(f"FAIL {name}: the hint must stay hidden, found {hint!r}")- ok = False- else:- report.append(f"ok {name}: hint hidden")- if "linear" in name:- # The resolved row's detail block carries the catalog description- # (the Rust view renders a status-head line above it — the- # sanctioned extension — so search the whole block).- details = " ".join(line.strip() for line in lines_below_row(frame, row))- if LINEAR_DESCRIPTION_PREFIX not in details:- report.append(f"FAIL {name}: linear detail block {details!r} lacks the catalog description")- ok = False- else:- report.append(f"ok {name}: linear detail carries the catalog description")- return ok---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--rust-binary", help="path to the Rust prime-agent build")- parser.add_argument("--ts-binary", help="path to the deployed TS release binary")- parser.add_argument("--out-dir", required=True, help="directory for the captured frames and report")- parser.add_argument("--side", choices=["both", "ts", "rust"], default="both")- args = parser.parse_args()- # The out-dir must resolve absolutely: every derived path (agent dirs,- # daemon sockets, faux scripts) rides it into the products' env, and a- # relative PRIME_AGENT_CODING_AGENT_DIR trips a pre-existing platform- # bug — the settings lock's mtime probe (utimensat(-1) on a relative- # path -> EBADF) turns every settings read into silent defaults, so- # the trace onboarding owns the pane and eats the /mcp keys (proven:- # a relative out-dir fails every rust cell, an absolute one passes).- # Real invocations always carry absolute agent dirs (HOME-derived).- args.out_dir = os.path.abspath(args.out_dir)- # Each product resolves only when this run drives it: a single-side- # capture must not exit before launching when the unselected product is- # unavailable (the identity guard compares the pair, so it needs both).- rust_binary = None- ts_binary = None- if args.side in ("both", "rust"):- rust_binary = args.rust_binary or ts_identity.default_rust_binary()- if args.side in ("both", "ts"):- ts_binary = args.ts_binary or default_ts_binary()- if rust_binary and ts_binary:- ts_identity.assert_ts_side_is_the_ts_product(ts_binary, rust_binary)- os.makedirs(args.out_dir, exist_ok=True)-- # One id for every derived name (tmux sessions, TMPDIRs, the reap- # needles): concurrent verifier runs must not kill each other's panes- # or reap each other's daemons, and a failed run's leftover TMPDIR- # must not be picked up by the next one.- run_id = uuid.uuid4().hex[:8]-- results: list = []- def reap(agent_dir_name: str, tmp_dir: str) -> None:- needle = os.path.join(args.out_dir, agent_dir_name)- batterylib.reap_daemons(- socket_paths=[os.path.join(needle, "daemon.sock")],- # The detached session workers carry no harness path in their- # argv — only their cwd — so a cwd root is what lets the sweep- # reach them. The root is the side's own unique agent dir- # (never the whole out-dir: the sweep kills every process- # whose cwd sits under a root, and an out-dir tree can hold- # unrelated shells, editors, or builds).- cwd_roots=[needle],- needles=[needle, tmp_dir],- )- shutil.rmtree(tmp_dir, ignore_errors=True)- try:- os.rmdir(os.path.dirname(tmp_dir)) # the run root, once empty- except OSError:- pass-- if args.side in ("both", "ts"):- try:- run_ts(ts_binary, args.out_dir, results, run_id)- finally:- reap("ts-agent", short_tmp(run_id, "ts"))- if args.side in ("both", "rust"):- for cache in (True, False):- suffix = "cached" if cache else "uncached"- try:- run_rust(rust_binary, args.out_dir, results, cache=cache, run_id=run_id)- finally:- reap(f"rust-{suffix}-agent", short_tmp(run_id, suffix))- if args.side in ("ts", "rust"):- print(f"captured the {args.side} side to {args.out_dir}")- return 0-- report = [- f"ts binary: {ts_binary}",- f"rust binary: {rust_binary}",- ]- outcomes = [check_cell(name, frame, report) for name, frame in results]- ok = all(outcomes)- report.append("MATRIX: " + ("PASS" if ok else "FAIL"))- text = "\n".join(report)- print(text)- with open(os.path.join(args.out_dir, "report.txt"), "w") as handle:- handle.write(text + "\n")- return 0 if ok else 1---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/mcp_view_parity.py b/scripts/mcp_view_parity.pydeleted file mode 100644index 0919193eb2..0000000000--- a/scripts/mcp_view_parity.py+++ /dev/null@@ -1,316 +0,0 @@-#!/usr/bin/env python3-"""The `/mcp` view's parity harness (TS `ServiceCatalogPickerComponent`).--Drives the REAL TS component (from the read-only TS checkout, through its-own tsx) and the REAL Rust view (the `mcp_view_parity_frames` example)-over identical fixtures, key sequences, and geometry, then diffs the-rendered frames line-for-line — the search field, the rows with their-trailing status, the scroll counter, the one fixed detail line, and the-hint.--Run the TS side on the box (tsx only; no Rust toolchain needed):-- python3 scripts/mcp_view_parity.py --side ts --out /tmp/mcp/ts.json--Run the Rust side where the checkout is built (the gate sandbox):-- python3 scripts/mcp_view_parity.py --side rust \- --rust-dir /work/repo --out /tmp/mcp/rust.json--Diff the two frame sets:-- python3 scripts/mcp_view_parity.py --diff /tmp/mcp/ts.json /tmp/mcp/rust.json--The fixture is the four-card catalog the `pa-tui` unit tests use (a-connected user stdio server, a connected catalog service with a-record-carried tool count, a connectable OAuth service, and a pasteable-token service) plus the empty catalog; the scenarios cover the open-frame, navigation, the pasteable selection, a search query, and the two-empty states.-"""--from __future__ import annotations--import argparse-import json-import re-import shutil-import subprocess-import sys-import tempfile-from pathlib import Path--WIDTH = 110-VIEWPORT_ROWS = 19--# Canonical key ids -> the raw pi-tui key sequences the TS components take-# (the Rust side receives the canonical ids).-TS_KEY = {- "down": "\x1b[B",- "up": "\x1b[A",- "enter": "\r",- "escape": "\x1b",-}--ANSI = re.compile(- r"\x1b\[[0-9;?]*[a-zA-Z]"- r"|\x1b[\]_^X][^\x07\x1b]*(?:\x07|\x1b\\)"- r"|\x1b."-)--CARDS = [- {- "serviceId": "fixture-echo",- "label": "fixture-echo",- "connectionStatus": "connected",- "connectable": False,- "usesOAuth": False,- "source": "user",- "connectionIds": ["fixture-echo"],- "pasteToken": False,- "aliases": [],- },- {- "serviceId": "notion",- "label": "Notion",- "connectionStatus": "connected",- "connectable": False,- "usesOAuth": True,- "source": "catalog",- "connectionIds": ["notion"],- "pasteToken": False,- "aliases": [],- "description": "Notion workflows.",- "toolCount": 12,- },- {- "serviceId": "linear",- "label": "Linear",- "connectionStatus": "not_connected",- "connectable": True,- "usesOAuth": True,- "source": "catalog",- "connectionIds": [],- "pasteToken": False,- "aliases": ["linear-app"],- "description": "Search and update Linear issues.",- },- {- "serviceId": "github",- "label": "GitHub",- "connectionStatus": "setup_required",- "connectable": False,- "usesOAuth": False,- "source": "catalog",- "connectionIds": [],- "pasteToken": True,- "aliases": [],- "description": "Inspect repositories.",- "setupHint": "paste a GitHub personal access token",- },-]--BIG_CARDS = [- {- "serviceId": f"service-{index}",- "label": f"Service {index}",- "connectionStatus": "not_connected",- "connectable": True,- "usesOAuth": True,- "source": "catalog",- "connectionIds": [],- "pasteToken": False,- "aliases": [],- "description": "A catalog service.",- }- for index in range(69)-]--SCENARIOS = [- ("open", CARDS, []),- ("navigate", CARDS, ["down", "down"]),- ("pasteable", CARDS, ["down", "down", "down"]),- ("search", CARDS, list("github")),- ("nomatch", CARDS, list("zzz")),- ("empty", [], []),- ("window", BIG_CARDS, ["down"] * 10),-]--ENTRY = """-import { readFileSync } from "node:fs";-import { ServiceCatalogPickerComponent } from {component_path};-import { initTheme } from {theme_path};--initTheme("prime");--const fixturePath = process.argv[2];-const viewportRows = Number(process.argv[3]);-const width = Number(process.argv[4]);-const keys = process.argv[5]- ? process.argv[5].split(" ").filter((key) => key && key !== "-")- : [];-const views = JSON.parse(readFileSync(fixturePath, "utf8"));-const picker = new ServiceCatalogPickerComponent(- views,- () => {},- () => {},- { getRows: () => viewportRows },-);-picker.focused = true;-for (const key of keys) picker.handleInput(key);-for (const line of picker.render(width)) console.log(line);-"""---def normalize(raw_lines: list[str]) -> list[str]:- """One plain-text trimmed line per rendered row (the diff shape)."""- return [ANSI.sub("", line).rstrip() for line in raw_lines]---def run(command: list[str], cwd: Path | None = None, env: dict | None = None) -> list[str]:- result = subprocess.run(- command,- cwd=cwd,- env=env,- capture_output=True,- text=True,- check=True,- )- return result.stdout.splitlines()---def ts_key(key: str) -> str:- return TS_KEY.get(key, key)---def ts_side(out: Path, ts_checkout: Path) -> None:- tsx = ts_checkout / "node_modules" / ".bin" / "tsx"- if not tsx.exists():- sys.exit(f"no tsx in the checkout: {tsx}")- scratch = Path(tempfile.mkdtemp(prefix="mcp-parity-ts-"))- home = scratch / "home"- home.mkdir()- try:- entry = scratch / "entry.mts"- component_path = json.dumps(- str(- ts_checkout- / "packages/coding-agent/src/modes/interactive/components/service-catalog-picker.ts"- )- )- theme_path = json.dumps(- str(- ts_checkout- / "packages/coding-agent/src/modes/interactive/theme/theme.ts"- )- )- entry.write_text(- ENTRY.replace("{component_path}", component_path).replace(- "{theme_path}", theme_path- )- )- frames: dict[str, list[str]] = {}- for name, cards, keys in SCENARIOS:- fixture = scratch / f"{name}.json"- fixture.write_text(json.dumps(cards))- raw = run(- [- str(tsx),- str(entry),- str(fixture),- str(VIEWPORT_ROWS),- str(WIDTH),- " ".join(ts_key(key) for key in keys) or "-",- ],- cwd=scratch,- env={- **dict(__import__("os").environ),- "HOME": str(home),- },- )- frames[name] = normalize(raw)- out.write_text(json.dumps(frames, indent=2))- print(f"TS frames written to {out}")- finally:- shutil.rmtree(scratch, ignore_errors=True)---def rust_side(out: Path, rust_dir: Path) -> None:- frames: dict[str, list[str]] = {}- with tempfile.TemporaryDirectory(prefix="mcp-parity-rust-") as tmp:- scratch = Path(tmp)- for name, cards, keys in SCENARIOS:- fixture = scratch / f"{name}.json"- fixture.write_text(json.dumps({"connections": [], "services": cards}))- raw = run(- [- "cargo",- "run",- "-q",- "-p",- "pa-tui",- "--example",- "mcp_view_parity_frames",- "--",- str(fixture),- str(VIEWPORT_ROWS),- str(WIDTH),- " ".join(keys) or "-",- ],- cwd=rust_dir,- )- frames[name] = normalize(raw)- out.write_text(json.dumps(frames, indent=2))- print(f"Rust frames written to {out}")---def diff_sides(ts_path: Path, rust_path: Path) -> int:- ts_frames = json.loads(Path(ts_path).read_text())- rust_frames = json.loads(Path(rust_path).read_text())- failures = 0- for name, _cards, _keys in SCENARIOS:- ts_lines = ts_frames.get(name, [])- rust_lines = rust_frames.get(name, [])- if ts_lines == rust_lines:- print(f"PASS {name}")- continue- failures += 1- print(f"FAIL {name}")- for index in range(max(len(ts_lines), len(rust_lines))):- ts_line = ts_lines[index] if index < len(ts_lines) else "<missing>"- rust_line = rust_lines[index] if index < len(rust_lines) else "<missing>"- if ts_line != rust_line:- print(f" line {index}:")- print(f" ts: {ts_line!r}")- print(f" rust: {rust_line!r}")- if failures:- print(f"{failures}/{len(SCENARIOS)} scenarios differ")- return 1- print(f"all {len(SCENARIOS)} scenarios byte-identical")- return 0---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--side", choices=["ts", "rust"])- parser.add_argument("--diff", nargs=2, metavar=("TS", "RUST"))- parser.add_argument("--out", type=Path, default=Path("/tmp/mcp-parity.json"))- parser.add_argument("--ts-checkout", type=Path, default=Path("/home/ubuntu/prime-agent"))- parser.add_argument("--rust-dir", type=Path, default=Path("."))- args = parser.parse_args()- if args.diff:- return diff_sides(args.diff[0], args.diff[1])- if not args.side:- parser.error("one of --side or --diff is required")- # The advertised one-liners write under /tmp/mcp: create the output- # directory so a fresh checkout's first run does not fail on it.- args.out.parent.mkdir(parents=True, exist_ok=True)- if args.side == "ts":- ts_side(args.out, args.ts_checkout)- else:- rust_side(args.out, args.rust_dir)- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/mouse_sgr_parity.py b/scripts/mouse_sgr_parity.pydeleted file mode 100755index 987aafd0c8..0000000000--- a/scripts/mouse_sgr_parity.py+++ /dev/null@@ -1,520 +0,0 @@-#!/usr/bin/env python3-"""Mouse SGR escape-leak parity verifier: drive the Rust interactive TUI-and the installed TS binary through the same mouse-report byte streams-under a raw pty and prove the leak contract (the "random escape-sequences typed into the editor" defect, TS `packages/tui/src/stdin-buffer.ts`):-- - a real terminal emits SGR mouse reports as one write per report; the- reader's OS-read boundary can land anywhere inside them. crossterm's- parser commits a lone trailing `ESC` at every partial-read tail, and- the sequence it opened then arrives as plain `Char` presses — during- a drag that is the report body (`[<32;14;2M`) typed into the editor.- TS never commits that early: `StdinBuffer` holds the `ESC` until the- next chunk completes the sequence (within its 10 ms window) or proves- it stood alone. The Rust side ports that discipline as the reader's- `SequenceGuard` (crates/pa-tui/src/sequence_guard.rs);- - the injection reproduces the boundary: the opening `ESC` is written- alone, the continuation ~4 ms later (inside the hold window, across- two OS reads). The split is a timing bet, so a full run is gated on- a positive control (`--defect-control PRE_FIX_BINARY`): the same- split discipline against a pre-fix build MUST leak — a committed- lone `ESC` is the only path that types a report body, so the- control's leak is per-run proof the read boundary happened (no leak- is a setup failure, never a vacuous pass) — and every recorded gap- must stay under 8 ms (a stretched gap drifts toward the flush- contract). Every report of the drag corpus (press, drags, a- three-way split, wheel, release) must reach the editor as NOTHING —- no report body may render on either binary, and no turn may start- on its own;- - the reader must stay healthy after the drag: typing `hi` + Enter- submits exactly `hi` (the submission is the leak detector — anything- the drag had typed would ride along) and runs the scripted turn once;- - a genuinely lone `ESC` (>hold later, nothing continues it) flushes as- the Esc key press on both binaries, and typing `ok` + Enter right- after still submits exactly `ok` (the flush path must not wedge or- duplicate input);- - startup wire parity: both binaries arm button-event SGR tracking- (`ESC[?1002h` + `ESC[?1006h`) and disarm it on exit.--tmux cannot reproduce the OS-read boundary (it re-shapes the bytes), so-like bracketed_paste_parity.py this verifier drives both binaries through-the scripted faux session under a raw pty.--`--defect-demo BASE_BINARY` runs the drag scenario against a pre-fix Rust-build and prints the leak signals it still emits (expected: the report-bodies render as typed text) — the before/after half of the evidence;-exit code is 0 in demo mode.--Exit code is non-zero when any stage check fails on either binary.-"""--import argparse-import json-import os-import pty-import select-import struct-import subprocess-import sys-import fcntl-import termios-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import visual_parity as vp--WIDTH, HEIGHT = 120, 36--# Unique per-scenario markers: the submission detector (word-level, the-# same span-diff reason as bracketed_paste_parity.py).-SENTINEL_DRAG = "MOUSE SGR PARITY SENTINEL"-SENTINEL_ESC = "LONE ESC PARITY SENTINEL"-SENTINEL_WORDS = ["SENTINEL"]-WORKING_LABEL = b"Waiting"--FAUX_SCRIPT = {- "engine": "faux",- "modelId": vp.TS_SCRIPT_MODEL,- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 18,- "responses": [{"content": [{"type": "text", "text": "{sentinel} ack."}]}],-}--# The wire modes both binaries must arm/disarm (mouse_tracking.rs:44/50 ==-# terminal.ts:580).-SGR_ON = b"\x1b[?1002h\x1b[?1006h"-SGR_OFF = b"\x1b[?1006l\x1b[?1002l"--# The drag corpus: what each report's body renders as when the reader-# leaks it (crossterm commits the `ESC`, the body arrives as Char presses).-# A leak renders the body text verbatim in the editor and in the echo of-# whatever the user submits next.-REPORT_BODIES = [- b"[<0;13;2M", # left press- b"[<32;14;2M", # left drag- b"[<32;15;3M", # left drag (three-way split)- b"[<64;20;5M", # wheel up (three-way split)- b"[<0;15;3m", # left release (injected whole, the control)-]--# The gap between the `ESC` write and its continuation: well inside the-# 10 ms hold (TS StdinBuffer.timeout == SequenceGuard::HOLD) so the-# sequence reassembles, but far enough apart that the reader thread-# (blocked in `read`, woken by the first byte) has scheduled and consumed-# it in its own OS read. The gap alone is still a timing bet — the-# per-run proof that the boundary really happened is the defect control-# (`--defect-control`, below): a pre-fix build MUST leak under the same-# split discipline, because a committed lone `ESC` is the only way its-# parser types a report body.-SPLIT_GAP_S = 0.004-# A gap stretched toward the hold flips the scenario into the-# late-continuation contract (both products flush the `ESC` and type the-# body), so a run whose worst gap passes this line is a setup failure,-# not a divergence.-SPLIT_GAP_LIMIT_S = 0.008---class PtyCapture:- """One binary under a raw pty; output captured stage by stage."""-- def __init__(self, command, env_extra, cwd):- master, slave = pty.openpty()- fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", HEIGHT, WIDTH, 0, 0))- env = dict(os.environ)- env["TERM"] = "xterm-256color"- env.update(env_extra)- self.proc = subprocess.Popen(command, stdin=slave, stdout=slave, stderr=slave, env=env, cwd=cwd)- os.close(slave)- self.master = master- self.stages = []- self.gaps = []-- def pump(self, seconds):- """Read output for `seconds`, recording the stage's bytes."""- stage = bytearray()- deadline = time.time() + seconds- while time.time() < deadline:- readable, _, _ = select.select([self.master], [], [], 0.05)- if self.master in readable:- try:- chunk = os.read(self.master, 65536)- except OSError:- break- if not chunk:- break- stage.extend(chunk)- self.stages.append(bytes(stage))- return bytes(stage)-- def write(self, data):- os.write(self.master, data)-- def wait_session_modes(self, timeout=40):- """Startup stage: read until the session owns the terminal.-- The launcher cold start (bun, daemon attach) is slow and variable- (run 2026-09-22: the TS side reached the alt screen well past a- fixed 6 s window, so a fixed sleep raced the injection into the- tty's echoed canonical buffer). The deterministic signal is the- alt-screen enter plus the SGR-tracking arm: the injection (and- every assertion about tracking modes) starts only once the binary- has both up. The arm can trail the alt screen by seconds (the- daemon attach sits between them on the Rust side), hence the- two-marker wait.- """- stage = bytearray()- deadline = time.time() + timeout- while time.time() < deadline:- if b"\x1b[?1049h" in stage and b"\x1b[?1002h" in stage:- break- readable, _, _ = select.select([self.master], [], [], 0.1)- if self.master in readable:- try:- chunk = os.read(self.master, 65536)- except OSError:- break- if not chunk:- break- stage.extend(chunk)- # A short settle in the same stage: the editor's first frame lands- # before the injection. (Not self.pump — that would append its own- # stage and shift every index-based assertion.)- settle = time.time() + 0.5- while time.time() < settle:- readable, _, _ = select.select([self.master], [], [], 0.05)- if self.master in readable:- try:- chunk = os.read(self.master, 65536)- except OSError:- break- if not chunk:- break- stage.extend(chunk)- self.stages.append(bytes(stage))- return bytes(stage)-- def write_split(self, chunks, gap=SPLIT_GAP_S):- """One sequence whose bytes the OS delivers in separate reads.-- Each chunk is its own pty write; the gap keeps the reads apart- while staying inside the hold window the guard (and TS's- StdinBuffer) reassemble within. The gap is busy-waited to- microsecond precision: a plain sleep stretches under load (run- 2026-09-22: a 2 ms sleep exceeded the 10 ms hold, both products- then correctly flush the `ESC` and type the body — the- late-continuation contract, not a divergence), which would turn- the in-hold reassembly case into the flush case. The gap is a- timing bet, so the run is only trusted when the defect control- confirms it per-run (a pre-fix build must leak under this same- discipline — the committed lone ESC is the only path that types- a report body) and when every recorded gap stayed under- SPLIT_GAP_LIMIT_S; anything else fails the run as a setup error.- """- for index, chunk in enumerate(chunks):- if index:- start = time.perf_counter()- target = start + gap- time.sleep(gap * 0.25)- while time.perf_counter() < target:- pass- self.gaps.append(time.perf_counter() - start)- self.write(chunk)-- def close(self):- try:- self.proc.terminate()- self.proc.wait(5)- except Exception:- self.proc.kill()- try:- os.close(self.master)- except OSError:- pass---def build_command(binary, sandbox, script_path):- common = {- "HOME": sandbox["home"],- "TMPDIR": sandbox["tmp"],- "PRIME_AGENT_CODING_AGENT_DIR": sandbox["agent"],- "PRIME_AGENT_FAUX_SCRIPT": script_path,- "PRIME_AGENT_DISABLE_ANALYTICS": "1",- }- if binary == "ts":- command = [- "prime-agent",- "--daemon-socket",- os.path.join(sandbox["agent"], "daemon.sock"),- "--model",- vp.TS_SCRIPT_MODEL,- ]- else:- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)),- "..",- "target",- "debug",- "prime-agent",- ),- )- common["PI_PACKAGE_DIR"] = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- command = [- rust,- "--daemon-socket",- os.path.join(sandbox["agent"], "daemon.sock"),- "--model",- vp.TS_SCRIPT_MODEL,- ]- return command, common---def run_drag_scenario(command, env_extra, cwd):- """The committed-`ESC` read boundary during a drag (and a wheel tick).-- Stage 1 carries the whole corpus: press and first drag split in two,- second drag and the wheel report split in three, the release whole- (the control — crossterm parses complete reports fine). Stage 2 types- `hi`, stage 3 submits it: the echo must carry exactly `hi`.- """- capture = PtyCapture(command, env_extra, cwd)- try:- capture.wait_session_modes() # stage 0: startup + SGR arm- capture.write(b"\x1b[<0;15;3m") # release, whole — warms the reader- capture.write_split([b"\x1b", b"[<0;13;2M"]) # press- capture.write_split([b"\x1b", b"[<32;14;2M"]) # drag- capture.write_split([b"\x1b", b"[<32;", b"15;3M"]) # drag, 3-way- capture.write_split([b"\x1b", b"[<64;", b"20;5M"]) # wheel, 3-way- capture.pump(1.5) # stage 1- capture.write(b"hi")- capture.pump(0.8) # stage 2- capture.write(b"\r")- capture.pump(18) # stage 3: the scripted turn- capture.write(b"\x03")- capture.pump(1.5) # stage 4: exit hint- capture.write(b"\x03")- capture.pump(10) # stage 5: teardown (session cleanup takes seconds)- return capture.stages, capture.gaps- finally:- capture.close()---def run_lone_esc_scenario(command, env_extra, cwd):- """A genuinely lone `ESC` flushes as the key press; input keeps working.-- The `ESC` stands alone well past the hold window (nothing continues- it), then `ok` + Enter submits exactly `ok` — the flush path must not- wedge the reader or duplicate the keystrokes behind it.- """- capture = PtyCapture(command, env_extra, cwd)- try:- capture.wait_session_modes() # stage 0: startup + SGR arm- capture.write(b"\x1b")- capture.pump(0.25) # stage 1: the hold expires, the Esc flushes- capture.write(b"ok")- capture.pump(0.8) # stage 2- capture.write(b"\r")- capture.pump(18) # stage 3: the scripted turn- capture.write(b"\x03")- capture.pump(1.5) # stage 4- capture.write(b"\x03")- capture.pump(10) # stage 5: teardown (session cleanup takes seconds)- return capture.stages, capture.gaps- finally:- capture.close()---def leak_scan(stages):- """Every signal that report bytes reached the editor as text."""- whole = b"".join(stages)- hits = []- for body in REPORT_BODIES:- if body in whole:- hits.append(f"report body rendered as text: {body!r}")- if b"[<" in whole:- hits.append("a report fragment (b'[<') rendered anywhere")- return hits---def check_stages(name, stages, scenario, binary, out_dir=None, suffix=""):- failures = []- startup, post_input = stages[0], stages[1] + stages[2]- whole = b"".join(stages)- post_enter = b"".join(stages[3:])-- # Wire parity: both binaries arm button-event SGR tracking at startup- # and disarm it at teardown (mouse_tracking.rs:44/50 == terminal.ts:580).- if SGR_ON not in startup:- failures.append(f"startup never arms SGR tracking (no {SGR_ON!r})")- if SGR_OFF not in stages[4] + stages[5]:- failures.append(f"teardown never disarms SGR tracking (no {SGR_OFF!r})")-- # The leak contract: nothing the drag carried may render as text.- failures += leak_scan(stages)-- # No turn may start from the drag (or from the lone ESC).- sentinel = SENTINEL_DRAG if scenario == "drag" else SENTINEL_ESC- if WORKING_LABEL in post_input:- failures.append("a turn started before Enter")- for word in SENTINEL_WORDS:- if word.encode() in post_input:- failures.append(f"the turn ran before Enter ({word} in the pre-Enter stages)")-- # The reader stays healthy: typing + Enter submits exactly the typed- # text (anything leaked into the editor rides along in the echo).- if not all(word.encode() in post_enter for word in SENTINEL_WORDS):- failures.append(f"the scripted turn never ran after Enter ({sentinel} missing)")- typed = b"hi" if scenario == "drag" else b"ok"- if typed not in post_enter:- failures.append(f"the submitted message lost the typed text {typed!r}")- for body in REPORT_BODIES:- if body in post_enter:- failures.append(f"the submitted echo carries a leaked body {body!r}")-- print(- f"{name}: {len(whole)} bytes; SGR_ON={'yes' if SGR_ON in startup else 'NO'}, "- f"SGR_OFF={'yes' if SGR_OFF in stages[4] + stages[5] else 'NO'}, "- f"{len(failures)} failures"- )- if out_dir:- with open(os.path.join(out_dir, f"{binary}{suffix}-raw.bin"), "wb") as f:- f.write(whole)- with open(os.path.join(out_dir, f"{binary}{suffix}-stages.json"), "w") as f:- json.dump([len(s) for s in stages], f)- return failures---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--raw-out", default=None, help="directory for raw captures")- parser.add_argument(- "--binary", choices=("ts", "rust"), default=None, help="run one side only"- )- parser.add_argument(- "--defect-demo",- metavar="BASE_BINARY",- default=None,- help="run the drag scenario against a pre-fix Rust build and print the leak signals it emits (exit 0)",- )- parser.add_argument(- "--defect-control",- metavar="PRE_FIX_BINARY",- default=None,- help="gate the run on a positive control: the drag scenario against this pre-fix Rust build MUST leak (a committed lone ESC is the only path that types a report body), proving this run's split writes really landed the read boundary; no leak fails the run as a setup error instead of a false pass",- )- args = parser.parse_args()-- import tempfile-- # Fail fast before any launch: a non-TS `prime-agent` on PATH plays a- # Rust build as the "ts" side and reports false divergences.- vp.ts_identity.assert_ts_side_is_the_ts_product()-- base = tempfile.mkdtemp(prefix="mouse-sgr-parity-")- out_dir = args.raw_out or tempfile.mkdtemp(prefix="mouse-sgr-raw-")- os.makedirs(out_dir, exist_ok=True)-- import visual_parity as vpm-- shared_cwd, _, sandboxes = vpm.prepare_sandbox(base)-- if args.defect_demo:- script_path = os.path.join(base, "faux-script.json")- with open(script_path, "w") as f:- json.dump(FAUX_SCRIPT, f, indent=2)- command, env = build_command("rust", sandboxes["rust"], script_path)- command[0] = args.defect_demo- stages, _ = run_drag_scenario(command, env, shared_cwd)- hits = leak_scan(stages)- if hits:- print(f"DEFECT CONFIRMED on {args.defect_demo} (pre-fix build leaks):")- for hit in hits:- print(f" - {hit}")- else:- print(f"defect NOT reproduced on {args.defect_demo}: no leak signals fired")- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- return 0-- # The positive control: the split writes are a timing bet, so the- # run is only trustworthy when a pre-fix build leaks under the very- # same discipline in this same run - a committed lone `ESC` is the- # only path that types a report body, so a leak is direct evidence- # the read boundary happened (no leak: report a setup failure, never- # a vacuous pass).- if args.defect_control:- script_path = os.path.join(base, "faux-control.json")- with open(script_path, "w") as f:- json.dump(FAUX_SCRIPT, f, indent=2)- command, env = build_command("rust", sandboxes["rust"], script_path)- command[0] = args.defect_control- print(f"defect control: {args.defect_control}")- stages, _ = run_drag_scenario(command, env, shared_cwd)- hits = leak_scan(stages)- if not hits:- print(- "SETUP FAILURE: the pre-fix control build did NOT leak under this "- "run's split writes - the committed-ESC read boundary did not "- "happen, so a parity pass would say nothing. Rerun the verifier."- )- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- return 1- print(f" control leak confirmed ({len(hits)} signals): the read boundary happened in this run")-- failures = {}- binaries = ("ts", "rust") if not args.binary else (args.binary,)- for binary in binaries:- failures[binary] = []- for scenario, runner in (- ("drag", run_drag_scenario),- ("lone-esc", run_lone_esc_scenario),- ):- script_path = os.path.join(base, f"faux-{scenario}.json")- script = dict(FAUX_SCRIPT)- script["responses"] = [- {- "content": [- {- "type": "text",- "text": f"{SENTINEL_DRAG if scenario == 'drag' else SENTINEL_ESC} ack.",- }- ]- }- ]- with open(script_path, "w") as f:- json.dump(script, f, indent=2)- command, env = build_command(binary, sandboxes[binary], script_path)- stages, gaps = runner(command, env, shared_cwd)- worst = max(gaps, default=0.0)- print(f" ({binary}/{scenario}: {len(gaps)} split gaps, worst {worst*1000:.2f} ms vs 10 ms hold)")- if worst > SPLIT_GAP_LIMIT_S:- failures[binary].append(- f"setup: worst split gap {worst*1000:.2f} ms passed "- f"{SPLIT_GAP_LIMIT_S*1000:.0f} ms (drifting toward the 10 ms "- "hold - this scenario tested the flush contract, not the "- "in-hold reassembly)"- )- failures[binary] += check_stages(- f"{binary}/{scenario}", stages, scenario, binary, out_dir,- "" if scenario == "drag" else "-esc",- )-- batterylib.reap_daemons(needles=[base], cwd_roots=[base])-- failed = {binary: fails for binary, fails in failures.items() if fails}- if failed:- for binary, fails in failed.items():- print(f"{binary} FAILED:")- for fail in fails:- print(f" - {fail}")- return 1- print("PARITY: ts and rust handle the mouse SGR corpus identically (no leak, input intact)")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/osc8_parity.py b/scripts/osc8_parity.pydeleted file mode 100644index bc748ef91b..0000000000--- a/scripts/osc8_parity.py+++ /dev/null@@ -1,441 +0,0 @@-#!/usr/bin/env python3-"""OSC 8 hyperlink parity verifier: byte-capture the raw terminal stream of-the Rust interactive TUI and the deployed TS binary over the same scripted-faux turn and compare the OSC 8 hyperlink sequences each emits.--TS reference (deployed 0.9.5 binary, the parity ground truth):-`markdown.ts` `case "link"` wraps the rendered label in-`\x1b]8;;URL\x1b\\` ... `\x1b]8;;\x1b\\` only when-`getCapabilities().hyperlinks` is true; the legacy branch prints the label-plus ` (href)` when the label differs from the href (mailto stripped). The-capability gate is `terminal-image.ts detectCapabilities`: hyperlinks on-for kitty/ghostty/wezterm/iTerm2/VS Code/Alacritty, forced off under-tmux/screen and in unknown terminals. (TS-main has since started wrapping-the legacy branch too - a documented version gap, not a port divergence.)--Leg A (raw pty, TERM_PROGRAM=vscode so both sides detect hyperlinks): the-OSC 8 opens must appear in the same settled-frame rows with the same URL-and the same visible label on both sides. This is the bare-URL autolink-fix itself: marked's gfm url rule links bare http/https/ftp/www/email-shapes that the Rust used to render as plain body text.--Leg B (tmux pane, no capability env): both sides render the legacy-fallback rows identically and the captured pane contains no OSC 8 at all --tmux 3.2a swallows the sequences, which is exactly why detectCapabilities-forces them off under tmux.--Exit code is non-zero when the sequences or rows differ.-"""--import argparse-import glob-import json-import os-import pty-import re-import select-import signal-import shutil-import struct-import subprocess-import sys-import fcntl-import termios-import tempfile-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)-import visual_parity as vp # noqa: E402 (sandbox + tmux + capture helpers)--WIDTH, HEIGHT = 120, 36--# The scripted faux turn: every link shape Kevin's dogfood reported as-# plain text, one paragraph per row so the rows map 1:1.-URL_TURN = (- "Links live here.\n"- "\n"- "PR: https://github.com/PrimeIntellect-ai/prime-agent/pull/182.\n"- "\n"- "Share: https://x.dev/share/abc123?u=1 now\n"- "\n"- "WWW: www.example.com/path end\n"- "\n"- "Email: [email protected] bye\n"- "\n"- "Angle: <https://angle.dev/x> done\n"- "\n"- "Explicit: [docs](https://example.com/docs) and [https://bare.dev](https://bare.dev)\n"- "\n"- "Parens: (see https://x.dev/page_(p), thanks)\n"- "\n"- "Nested: [pre <https://inner.dev> post](https://outer.dev)\n"-)--PROMPT = "Show me the links."-URL_NEEDLES = [line.split(":")[0] + ": " for line in URL_TURN.splitlines() if ": " in line]--FAUX_SCRIPT = {- "engine": "faux",- "modelId": "faux-1",- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 18,- "responses": [{"content": [{"type": "text", "text": URL_TURN}]}],-}--OSC8_OPEN = re.compile(rb"\x1b\]8;;([^\x1b]*)\x1b\\")-SGR_RE = re.compile(rb"\x1b\[[0-9;?]*[A-Za-z]")---def run_pty(command, env_extra, cwd, turn_seconds):- """Run `command` as its own session owning a fresh pty; return every- output byte plus the byte offset where the harness resized the tty.-- `pty.fork()` makes the client the session leader with the slave as- its controlling terminal, so the TIOCSWINSZ resize below reaches it- as SIGWINCH and forces the full-frame repaint the settled hyperlink- rows are captured from. Timing is driven by quiescence, not fixed- sleeps: the prompt is typed only once the attach chrome is quiet and- echoes back, the turn is awaited until the stream falls silent, and- the capture ends after the post-resize repaint has quiesced.- """- env = dict(os.environ)- # The harness box itself often runs under tmux; the capability probe- # must see the terminal this pty pretends to be, not the box's session.- for key in (- "TMUX",- "TMUX_PANE",- "TERM_PROGRAM",- "TERM_PROGRAM_VERSION",- "KITTY_WINDOW_ID",- "WEZTERM_PANE",- "ITERM_SESSION_ID",- "GHOSTTY_RESOURCES_DIR",- ):- env.pop(key, None)- env["TERM"] = "xterm-256color"- env.update(env_extra)- pid, master = pty.fork()- if pid == 0: # child: session leader on the new controlling terminal- try:- os.chdir(cwd)- os.execve(command[0], command, env)- except Exception:- os._exit(127)- fcntl.ioctl(master, termios.TIOCSWINSZ, struct.pack("HHHH", HEIGHT, WIDTH, 0, 0))- out = bytearray()-- def child_running():- try:- done, _ = os.waitpid(pid, os.WNOHANG)- return done == 0- except ChildProcessError:- return False-- def pump_until(settled, timeout, quiet=2.0):- """Pump until `settled()` holds and the stream has been quiet."""- start = time.time()- last_byte = time.time()- while time.time() - start < timeout:- readable, _, _ = select.select([master], [], [], 0.1)- if master in readable:- try:- chunk = os.read(master, 65536)- except OSError:- return False- if not chunk:- return False- out.extend(chunk)- last_byte = time.time()- if settled() and time.time() - last_byte >= quiet:- return True- return False-- def frame_settled():- # The clients repaint their status row while idle; the splash is- # done once the stream falls silent with the frame up.- return b"Collapsed mode" in out-- def turn_settled():- # The diff painters repaint streamed rows cell-by-cell, so the- # needle rows never appear contiguous in the byte stream; the turn- # is settled once it has begun and the stream falls quiet.- return b"Links live here" in out-- t0 = time.time()- alive = pump_until(frame_settled, 90, quiet=3.0)- # Type only once the editor echoes it back: clients drop keys while- # the attach chrome still repaints (the Rust editor starts reading- # seconds after "Collapsed mode" first paints), so a blind write can- # be lost entirely. Retype until the echo lands, then submit.- echoed = False- for _ in range(12):- os.write(master, PROMPT.encode() + b"\r")- echoed = pump_until(lambda: PROMPT.encode() in out, 10, quiet=0.5)- if echoed:- break- print(f" pty: prompt echoed at {time.time() - t0:.1f}s")- alive = alive and echoed and pump_until(turn_settled, turn_seconds, quiet=4.0)- print(f" pty: turn settle at {time.time() - t0:.1f}s ({len(out)} bytes)")- # Resize to force a full repaint on both sides: the diff painters only- # emit a row's OSC 8 sequences when its cells repaint, so the settled- # hyperlink rows must be observed after a full-frame redraw.- resize_offset = len(out)- fcntl.ioctl(master, termios.TIOCSWINSZ, struct.pack("HHHH", HEIGHT, WIDTH - 4, 0, 0))- alive = alive and pump_until(lambda: True, 20, quiet=3.0)- print(f" pty: resize settle at {time.time() - t0:.1f}s ({len(out)} bytes)")- alive = alive and child_running()- try:- os.kill(pid, signal.SIGTERM)- os.waitpid(pid, 0)- except Exception:- try:- os.kill(pid, signal.SIGKILL)- os.waitpid(pid, 0)- except Exception:- pass- os.close(master)- if not alive:- print("WARN: the client exited early or never settled under the pty")- return bytes(out), resize_offset---def binary_command(binary, sandbox, script_path, ts_bin):- agent = sandbox["agent"]- common_env = {- "HOME": sandbox["home"],- "TMPDIR": sandbox["tmp"],- "PRIME_AGENT_CODING_AGENT_DIR": agent,- "PRIME_AGENT_FAUX_SCRIPT": script_path,- "PRIME_AGENT_DISABLE_ANALYTICS": "1",- }- if binary == "ts":- # The resolved executable path, not a PATH lookup: leg B sends the- # command through the tmux server, whose environment may hold a- # stale PATH (and resolve a different binary than `main` asserted).- command = [ts_bin, "--daemon-socket", os.path.join(agent, "daemon.sock"), "--model", vp.TS_SCRIPT_MODEL]- else:- rust = os.environ.get(- ts_identity.RUST_BINARY_ENV,- os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "target", "debug", "prime-agent"),- )- common_env["PI_PACKAGE_DIR"] = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- command = [rust, "--daemon-socket", os.path.join(agent, "daemon.sock"), "--model", vp.TS_SCRIPT_MODEL]- return command, common_env---def leg_a_events(tail):- """Settled-frame OSC 8 events: {row: (url, visible label)}.-- `tail` is the stream after the resize that forces both painters into a- full-frame redraw, so the events are the settled ones. Rows are- tracked by absolute cursor addressing (both painters emit- `[row;colH` before painting), so an open is attributed to the row the- cursor sits on - not to whichever row was painted next. The last- event per row wins (the frame repaint is the final pass).- """- events = {}- row = 1- pending = None # [row, url, label bytes] while a hyperlink region is open- prev_end = 0- for m in re.finditer(rb"\x1b", tail):- if m.start() < prev_end:- # an ESC inside a sequence already consumed (the ST of an OSC 8- # open/close): not a new sequence start.- continue- between = tail[prev_end : m.start()]- if pending is not None:- pending[2] += between- prev_end = m.start()- rest = tail[m.start() :]- if rest.startswith(b"\x1b]"):- link = re.match(rb"\x1b\]8;;([^\x1b]*)\x1b\\", rest)- if not link:- # another OSC payload (shell prompt markers etc.): skip it- # through its terminator; it neither closes nor breaks the- # active hyperlink region.- skip = re.search(rb"[\x07]|\x1b\\", rest[2:])- prev_end = m.start() + 2 + (skip.end() if skip else 0)- continue- url = link.group(1)- if url:- pending = [row, url.decode("utf-8", "replace"), b""]- elif pending is not None:- label = re.sub(rb"[^\x20-\x7e]", b"", pending[2])- events.setdefault(pending[0], []).append(- (pending[1], label.decode("utf-8", "replace"))- )- pending = None- prev_end = m.start() + len(link.group(0))- elif rest.startswith(b"\x1b["):- move = re.match(rb"\x1b\[(\d+);(\d+)H", rest)- if move:- new_row = int(move.group(1))- if pending is not None and new_row != row:- # the region did not close on the row it opened: the- # label wrapped; keep the first row's part.- label = re.sub(rb"[^\x20-\x7e]", b"", pending[2])- events.setdefault(pending[0], []).append(- (pending[1], label.decode("utf-8", "replace"))- )- pending = None- row = new_row- prev_end = m.start() + len(move.group(0))- else:- skip = re.match(rb"\x1b\[[0-9;?]*[A-Za-z]", rest)- if skip:- prev_end = m.start() + len(skip.group(0))- else:- prev_end = m.start() + 1- return events---def leg_a(ts_bin, rust_bin, base):- """Raw-pty capture with hyperlinks forced on: compare settled events."""- shared_cwd, script_path, sandboxes = base- raw = {}- resize_at = {}- for binary in ("ts", "rust"):- command, env_extra = binary_command(binary, sandboxes[binary], script_path, ts_bin)- env_extra["TERM_PROGRAM"] = "vscode"- raw[binary], resize_at[binary] = run_pty(command, env_extra, shared_cwd, 150)- events = {b: leg_a_events(raw[b][resize_at[b] :]) for b in raw}- for b in ("ts", "rust"):- with open(os.path.join(OUT_DIR, f"leg-a-{b}.bin"), "wb") as f:- f.write(raw[b])- print(f"leg A {b}: {len(raw[b])} bytes, {len(events[b])} settled OSC 8 rows")- if not events["rust"]:- print("FAIL leg A: the Rust side emitted no OSC 8 sequences")- return 1- if not events["ts"]:- print("FAIL leg A: the TS side emitted no OSC 8 sequences")- return 1- if events["ts"] != events["rust"]:- print("FAIL leg A: OSC 8 events differ")- for row in sorted(set(events["ts"]) | set(events["rust"])):- a = events["ts"].get(row)- b = events["rust"].get(row)- if a != b:- print(f" row {row}: ts={a} rust={b}")- return 1- # The lane fix itself: bare urls must be among the wrapped hrefs.- urls = {url for links in events["ts"].values() for url, _ in links}- for expected in (- "https://github.com/PrimeIntellect-ai/prime-agent/pull/182",- "https://x.dev/share/abc123?u=1",- "http://www.example.com/path",- "mailto:[email protected]",- "https://angle.dev/x",- "https://example.com/docs",- "https://bare.dev/",- "https://x.dev/page_(p)",- # Macroscope finding 4, byte-proofed: the angle autolink inside a- # link label runs in marked too (only the url rule is inLink-guarded)- # and the nested hyperlink renders identically on both sides.- "https://outer.dev",- "https://inner.dev",- ):- if expected not in urls:- print(f"FAIL leg A: expected OSC 8 href missing: {expected}")- return 1- print("PASS leg A: OSC 8 rows, hrefs, and labels are identical")- return 0---def leg_b(base, ts_bin):- """tmux panes with no capability env: legacy fallback parity, no OSC 8."""- shared_cwd, script_path, sandboxes = base- panes = {}- for binary in ("ts", "rust"):- session = f"vplane-osc8-{binary}"- vp.tmux("kill-session", "-t", session, check=False)- vp.tmux("new-session", "-d", "-s", session, "-x", str(WIDTH), "-y", str(HEIGHT), "-c", shared_cwd)- command, env_extra = binary_command(binary, sandboxes[binary], script_path, ts_bin)- env = " ".join(f"{k}={v}" for k, v in env_extra.items())- vp.tmux("send-keys", "-t", session, f"{env} {' '.join(command)}", "Enter")- vp.wait_for(session, "Collapsed mode", timeout=40)- time.sleep(1.0)- vp.tmux("send-keys", "-t", session, PROMPT, "Enter")- deadline = time.time() + 40- while time.time() < deadline:- pane = vp.capture(session, escape=False)- if "Parens:" in pane:- break- time.sleep(0.5)- time.sleep(2.0)- panes[binary] = {"plain": vp.capture(session, escape=False), "escapes": vp.capture(session, escape=True)}- vp.tmux("kill-session", "-t", session, check=False)- for b in ("ts", "rust"):- with open(os.path.join(OUT_DIR, f"leg-b-{b}.txt"), "w") as f:- f.write(panes[b]["escapes"])- if "\x1b]8;" in panes[b]["escapes"]:- print(f"FAIL leg B: {b} pane carries OSC 8 sequences under tmux")- return 1- # Every link row must render the same visible legacy text on both sides.- ts_rows = {line.strip() for line in panes["ts"]["plain"].splitlines() if line.strip()}- rust_rows = {line.strip() for line in panes["rust"]["plain"].splitlines() if line.strip()}- failures = []- for needle in URL_NEEDLES:- ts_row = next((r for r in ts_rows if r.startswith(needle)), None)- rust_row = next((r for r in rust_rows if r.startswith(needle)), None)- if ts_row is None or rust_row is None:- failures.append(f"{needle!r}: ts={ts_row!r} rust={rust_row!r}")- elif ts_row != rust_row:- failures.append(f"{needle!r}: ts={ts_row!r} rust={rust_row!r}")- if failures:- print("FAIL leg B: legacy fallback rows differ")- for f_ in failures:- print(f" {f_}")- return 1- print("PASS leg B: legacy rows identical, no OSC 8 under tmux")- return 0---OUT_DIR = None---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--keep", action="store_true", help="keep the sandbox dir")- parser.add_argument("--out", default=None, help="directory for captures")- args = parser.parse_args()-- global OUT_DIR- OUT_DIR = args.out or tempfile.mkdtemp(prefix="osc8-parity-")- os.makedirs(OUT_DIR, exist_ok=True)-- ts_bin = os.environ.get("TS_BIN") or shutil.which("prime-agent")- rust_bin = os.environ.get(ts_identity.RUST_BINARY_ENV) or os.path.join(- os.path.dirname(os.path.abspath(__file__)), "..", "target", "debug", "prime-agent"- )- if not os.path.exists(rust_bin):- print(f"FAIL: rust binary not found at {rust_bin} (set PA_RUST_BINARY)")- return 1- ts_identity.assert_ts_side_is_the_ts_product(ts_bin, rust_bin)-- base_dir = tempfile.mkdtemp(prefix="osc8-parity-sandbox-")- script_path = os.path.join(base_dir, "faux-script.json")- with open(script_path, "w") as f:- json.dump(FAUX_SCRIPT, f, indent=2)- shared_cwd, _, sandboxes = vp.prepare_sandbox(base_dir)- # prepare_sandbox writes vp.FAUX_SCRIPT; overwrite with this harness's.- with open(script_path, "w") as f:- json.dump(FAUX_SCRIPT, f, indent=2)- base = (shared_cwd, script_path, sandboxes)- try:- rc = leg_a(ts_bin, rust_bin, base)- if rc:- return rc- return leg_b(base, ts_bin)- finally:- batterylib.reap_daemons(needles=[base_dir], cwd_roots=[base_dir])- if not args.keep:- shutil.rmtree(base_dir, ignore_errors=True)---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/osc_parity.py b/scripts/osc_parity.pydeleted file mode 100644index 9826cc3e93..0000000000--- a/scripts/osc_parity.py+++ /dev/null@@ -1,189 +0,0 @@-#!/usr/bin/env python3-"""OSC 133 zone-marker parity verifier: byte-capture the raw terminal stream-of the Rust interactive TUI and the installed TS binary and compare the-shell-integration markers they emit (TS `user-message.ts` /-`assistant-message.ts` / `slash-command-message.ts`).--Note on tmux: tmux parses (and, before 3.3, silently swallows) OSC 133, so-`capture-pane -e` cannot show these sequences — the pane never stores them.-This verifier therefore drives both binaries through the scripted faux-session under a raw pty and records every output byte before any terminal-parser sits in between (scripts/visual_parity.py owns the visible-frame-diff; this one owns the zero-width control sequences).--Checks, per binary and across binaries:- - the zone-start (`133;A`) and end/final (`133;B` then `133;C`) sequences- are emitted at the same terminal rows;- - every marked assistant/user message row pair (A row before B/C row)- exists on both sides.--Exit code is non-zero when the marker shapes or rows differ.-"""--import argparse-import os-import pty-import re-import select-import signal-import struct-import subprocess-import sys-import fcntl-import termios-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import visual_parity as vp--WIDTH, HEIGHT = 120, 36-A_ROW = re.compile(rb"\x1b\[(\d+);1H(?:\x1b\[2K)?\x1b\]133;A\x07")-B_ROW = re.compile(rb"\x1b\[(\d+);1H(?:\x1b\[2K)?(?:\x1b\]133;B\x07\x1b\]133;C\x07)")---def run_pty(command, env_extra, cwd, keys_script, total_seconds):- """Run `command` under a raw pty; return every output byte."""- master, slave = pty.openpty()- fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", HEIGHT, WIDTH, 0, 0))- env = dict(os.environ)- env["TERM"] = "xterm-256color"- env.update(env_extra)- proc = subprocess.Popen(- command, stdin=slave, stdout=slave, stderr=slave, env=env, cwd=cwd- )- os.close(slave)- out = bytearray()-- def pump(dur):- deadline = time.time() + dur- while time.time() < deadline:- readable, _, _ = select.select([master], [], [], 0.1)- if master in readable:- try:- chunk = os.read(master, 65536)- except OSError:- return False- if not chunk:- return False- out.extend(chunk)- return True-- keys_script(master, pump)- time.sleep(0.5)- try:- proc.terminate()- proc.wait(5)- except Exception:- proc.kill()- os.close(master)- return bytes(out)---def session_keys(master, pump):- """Drive the scripted faux turn: wait for the splash, submit the prompt."""- pump(6)- os.write(master, vp.PROMPT.encode() + b"\r")- pump(35)---def capture(binary, sandbox, shared_cwd, script_path):- agent = sandbox["agent"]- common = {- "HOME": sandbox["home"],- # Isolated TMPDIR: the TS supervisor's socket (the default- # daemon-socket dir) stays under this run's sandbox, so the- # cleanup reap can sweep by path alone.- "TMPDIR": sandbox["tmp"],- "PRIME_AGENT_CODING_AGENT_DIR": agent,- "PRIME_AGENT_FAUX_SCRIPT": script_path,- "PRIME_AGENT_DISABLE_ANALYTICS": "1",- }- if binary == "ts":- command = [- "prime-agent",- "--daemon-socket",- os.path.join(agent, "daemon.sock"),- "--model",- vp.TS_SCRIPT_MODEL,- ]- else:- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)),- "..",- "target",- "debug",- "prime-agent",- ),- )- common["PI_PACKAGE_DIR"] = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- command = [- rust,- "--daemon-socket",- os.path.join(agent, "daemon.sock"),- "--model",- vp.TS_SCRIPT_MODEL,- ]- return run_pty(command, common, shared_cwd, session_keys, 45)---def marker_rows(raw):- a_rows = sorted({int(m.group(1)) for m in A_ROW.finditer(raw)})- b_rows = sorted({int(m.group(1)) for m in B_ROW.finditer(raw)})- return a_rows, b_rows---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--keep", action="store_true", help="keep the sandbox dir")- parser.add_argument("--raw-out", default=None, help="directory for raw captures")- args = parser.parse_args()-- import tempfile- import shutil-- # Fail fast before any launch: a non-TS `prime-agent` on PATH plays a- # Rust build as the "ts" side and reports false divergences.- vp.ts_identity.assert_ts_side_is_the_ts_product()-- base = tempfile.mkdtemp(prefix="osc-parity-sandbox-")- out_dir = args.raw_out or tempfile.mkdtemp(prefix="osc-parity-raw-")- os.makedirs(out_dir, exist_ok=True)- shared_cwd, script_path, sandboxes = vp.prepare_sandbox(base)- try:- raw = {}- for binary in ("ts", "rust"):- raw[binary] = capture(binary, sandboxes[binary], shared_cwd, script_path)- with open(os.path.join(out_dir, f"{binary}-raw.bin"), "wb") as f:- f.write(raw[binary])- a_rows, b_rows = marker_rows(raw[binary])- print(f"{binary}: {len(raw[binary])} bytes; A rows {a_rows}; B/C rows {b_rows}")- if not a_rows or not b_rows:- print(f"FAIL {binary}: no OSC 133 markers in the raw stream")- return 1-- ts_a, ts_b = marker_rows(raw["ts"])- rust_a, rust_b = marker_rows(raw["rust"])- if ts_a != rust_a or ts_b != rust_b:- print(f"FAIL: marker rows differ (ts A {ts_a} B {ts_b}; rust A {rust_a} B {rust_b})")- return 1- for a in ts_a:- if not any(b > a for b in ts_b):- print(f"FAIL: zone-start row {a} has no matching end row below it")- return 1- print(f"PASS: both binaries mark the same rows (A {ts_a}, B/C {ts_b})")- return 0- finally:- # Rmtree alone leaks the scenario daemons (the pty kill does not- # take the detached daemon/supervisor pair down; #223): sweep- # every daemon this run spawned before deleting the sandbox.- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if not args.keep:- shutil.rmtree(base, ignore_errors=True)---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/paste_stream_parity.py b/scripts/paste_stream_parity.pydeleted file mode 100755index 9c29020432..0000000000--- a/scripts/paste_stream_parity.py+++ /dev/null@@ -1,411 +0,0 @@-#!/usr/bin/env python3-"""Paste-during-streaming verifier: a paste mid-turn must register in the-editor instantly (the input path never blocks on transcript processing).--Resumes the ~40MB drag corpus session (the perf family's heavy transcript),-starts a paced faux streaming turn on top of it, and pastes into the editor-while the stream renders — the flagship input-latency contract:-- * while the turn streams and the view follows the tail, a 12-line- bracketed paste lands as the collapsed `[paste #N +12 lines]`- indicator within one coalesced frame plus capture overhead — never- waiting on a transcript-sized layout pass;- * a marker-less keystroke burst (the tmux 3.2a `paste-buffer` shape)- lands the same way mid-stream;- * the same paste while the view is PAUSED mid-history (wheel up) — the- adversarial case: every streaming delta appends while the window is- pinned far above the tail, exactly the path that used to run a full- geometry resolve per append — still registers instantly;- * the turn keeps streaming through every paste window (the words- advance past the marker the verifier saw before the pause), and the- queued editor text submits whole after the turn: the session file- carries every pasted line and the scripted ack.--The per-paste registration latencies are measured (evidence, not just-asserted) against the STEP_BUDGET_S budget — the same coalesced-frame-budget the drag verifier uses. The Rust side gates the budget; the TS-side runs the identical scenario for parity evidence (behavior must-match: registration, collapse indicator, follow hint, submission-integrity) with its latencies reported for reference.--tmux rules: default socket only (`env -u TMUX`), pastep-* session names,-no kill-server; the session is killed individually and the daemon reaped-at the end (leaked workers starve later suites).-"""--import argparse-import json-import os-import re-import shutil-import subprocess-import sys-import time-from datetime import datetime, timezone-from pathlib import Path--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)-from drag_select_parity import NEEDLE, TURNS, corpus_path, find_runtime_package_dir--REPO = Path(__file__).resolve().parent.parent--CAPTURE_POLL_S = 0.005-STEP_TIMEOUT_S = 5.0-# One coalesced frame (16ms) plus tmux capture overhead, with CI headroom —-# the drag verifier's budget: above this the input lag is visible.-STEP_BUDGET_S = 0.35--# The paced streaming answer: 150 numbered words so the pane shows exactly-# how far the stream advanced at every measurement point. ~640 faux tokens-# at 30 tokens/second ≈ 20s of streaming — a wide mid-stream window for the-# three paste measurements.-STREAM_WORDS = 150-STREAM_TEXT = " ".join(f"streaming-word-{i:03d}" for i in range(STREAM_WORDS))-PASTE_ACK = "PASTE STREAM ACK 7f3d"-PROMPT = "begin the paced paste stream test"--# Paste payloads: the collapsed bracketed block (>10 lines -> the-# `[paste #N +12 lines]` indicator) and the marker-less 3-line burst-# (the tmux 3.2a shape: inline in the editor, unique words so the pane-# capture proves the exact bytes landed).-FOLLOW_PASTE = [f"follow paste line {i:02d} aabb" for i in range(12)]-BURST_PASTE = ["bursthorse-one first", "bursthorse-two second", "bursthorse-three third"]-PAUSED_PASTE = [f"paused paste line {i:02d} ccdd" for i in range(12)]--# A large-context scripted model: the resumed 19MB corpus (~640k tokens)-# would overflow a 128k window and TS fires context-overflow recovery whose-# summarization requests eat the queued scripted responses (the Rust-# engine's marker-matched queues survive it; the shared TS harness-# extension cannot script through TS's recovery). The paste contract is-# mid-stream input latency, not the overflow path — both sides run the-# identical large-context scenario.-FAUX_SCRIPT = {- "engine": "faux",- "modelId": "faux-1",- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 10000000,- "tokensPerSecond": 30,- "responses": [- {"content": [{"type": "text", "text": STREAM_TEXT}]},- {"content": [{"type": "text", "text": PASTE_ACK}]},- ],-}--# The TS extension registers the same paced faux provider from-# PRIME_AGENT_FAUX_SCRIPT (shared harness contract).-TS_FAUX_EXTENSION = open(- os.path.join(os.path.dirname(os.path.abspath(__file__)), "ts_faux_extension.js"),- encoding="utf-8",-).read()--# The working loader row (spinner + activity + elapsed + the token counter)-# is the in-pane proof a turn is still streaming; both products render it.-STREAMING_RE = re.compile(r"(Waiting|tokens)")---def tmux(*args, check=True):- result = subprocess.run(- ["env", "-u", "TMUX", "tmux", *args],- capture_output=True,- text=True,- )- if check and result.returncode != 0:- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")- return result.stdout---def capture(session, escape=True):- flag = "-e" if escape else "-p"- return tmux("capture-pane", flag, "-p", "-t", session)---def sgr_hex(sequence):- return [f"{byte:02x}" for byte in sequence.encode()]---def send_bytes(session, sequence):- tmux("send-keys", "-t", session, "-H", *sgr_hex(sequence))---def wheel_up(row):- return f"\x1b[<64;1;{row}M"---def wait_for(session, needle, timeout, poll=0.05):- deadline = time.time() + timeout- while time.time() < deadline:- pane = capture(session, escape=False)- if needle in pane:- return pane- time.sleep(poll)- raise TimeoutError(f"session {session} never showed {needle!r}")---def wait_gone(session, pattern, timeout, poll=0.1):- deadline = time.time() + timeout- while time.time() < deadline:- pane = capture(session, escape=False)- if not re.search(pattern, pane):- return pane- time.sleep(poll)- raise TimeoutError(f"session {session} never dropped /{pattern}/")---def bracketed_paste(lines):- return "\x1b[200~" + "\r\n".join(lines) + "\x1b[201~"---def measure_registration(session, payload, needle, label, out_dir):- """Send the paste bytes and poll the pane until the paste's visible- marker appears; return the registration latency."""- send_bytes(session, payload)- started = time.monotonic()- raw = None- # The diff renderer may write the row in styled segments, so the pane- # capture is matched by the marker's words, not one contiguous string.- parts = needle.split()- while time.monotonic() - started < STEP_TIMEOUT_S:- raw = capture(session)- if all(part in raw for part in parts):- return time.monotonic() - started- time.sleep(CAPTURE_POLL_S)- (out_dir / f"{label}-stuck.raw").write_text(raw or "")- raise AssertionError(- f"{label}: the editor never registered the paste (no {needle!r})"- )---def side_command(binary, sandbox, script_path, corpus):- """The pane command line for one side (mirrors visual_parity.py)."""- env = (- f"HOME={sandbox['home']} TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"PRIME_AGENT_FAUX_SCRIPT={script_path} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- if binary == "ts":- command = (- f"prime-agent --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model faux-1 --resume {corpus}"- )- else:- rust = os.environ.get(- "PA_RUST_BINARY", str(REPO / "target" / "release" / "prime-agent")- )- package_dir = os.environ.get("PI_PACKAGE_DIR") or find_runtime_package_dir()- command = (- f"PI_PACKAGE_DIR={package_dir} "- f"{rust} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model faux-1 --resume {corpus}"- )- return f"{env} {command}"---def read_tail(path, tail_bytes=2 * 1024 * 1024):- with open(path, "rb") as handle:- handle.seek(0, os.SEEK_END)- size = handle.tell()- handle.seek(max(0, size - tail_bytes))- return handle.read().decode("utf-8", errors="replace")---def read_tail_settled(path, needles, tail_bytes=2 * 1024 * 1024, timeout=15.0):- """The corpus tail once every needle is present (the daemon flushes its- session records slightly after the pane renders them, so the integrity- read retries until the records land instead of racing the flush)."""- deadline = time.time() + timeout- tail = ""- while True:- tail = read_tail(path, tail_bytes)- if all(needle in tail for needle in needles) or time.time() >= deadline:- return tail- time.sleep(0.5)---def run_side(binary, corpus, script_path, out_dir, width, height):- """One binary through the full scenario; returns the evidence dict."""- sandbox_root = out_dir / binary- sandbox = {- "home": sandbox_root / "home",- "agent": sandbox_root / "agent",- "tmp": sandbox_root / "tmp",- }- for path in (sandbox["home"], sandbox["agent"], sandbox["tmp"]):- path.mkdir(parents=True, exist_ok=True)- (sandbox["agent"] / "settings.json").write_text(- json.dumps({"onboardingCompleted": True})- )- if binary == "ts":- # The TS daemon loads the faux-provider driver extension from the- # agent dir (visual_parity.py's shared extension source).- ext_dir = sandbox["agent"] / "extensions"- ext_dir.mkdir(exist_ok=True)- (ext_dir / "paste-stream-faux.js").write_text(TS_FAUX_EXTENSION)- # Each side resumes its own copy of the corpus: a resumed session- # appends its turn records to the file, so a shared corpus would hand- # the second side the first side's transcript (the needle is then no- # longer at the tail and the resume wait can never succeed).- corpus_copy = sandbox_root / "corpus.jsonl"- shutil.copyfile(corpus, corpus_copy)- corpus = corpus_copy-- session = f"pastep-{binary}"- tmux("kill-session", "-t", session, check=False)- tmux("new-session", "-d", "-s", session, "-x", str(width), "-y", str(height), "-c", "/tmp")- tmux(- "send-keys", "-t", session,- side_command(binary, sandbox, script_path, corpus), "Enter",- )- failures = []- try:- # The resumed 40MB transcript: the first frame walks it once.- wait_for(session, NEEDLE, timeout=180)- time.sleep(0.5)- (out_dir / f"{binary}-resumed.txt").write_text(capture(session))-- # Start the paced streaming turn.- tmux("send-keys", "-t", session, PROMPT, "Enter")- wait_for(session, f"streaming-word-{30:03d}", timeout=40)-- # Paste 1: mid-stream, following the tail — the collapsed indicator.- follow_ms = measure_registration(- session,- bracketed_paste(FOLLOW_PASTE),- "[paste #1 +12 lines]",- f"{binary}-follow-paste",- out_dir,- )-- # Paste 2: the marker-less burst, later in the same stream.- wait_for(session, f"streaming-word-{60:03d}", timeout=40)- burst_ms = measure_registration(- session,- "\r\n".join(BURST_PASTE),- "bursthorse-three third",- f"{binary}-burst-paste",- out_dir,- )-- # Paste 3: paused mid-history while the stream appends — the- # adversarial case (per-delta appends far above the window).- wait_for(session, f"streaming-word-{90:03d}", timeout=40)- for _ in range(12):- send_bytes(session, wheel_up(5))- time.sleep(0.6)- if "to follow" not in capture(session, escape=False):- failures.append("the wheel-up never paused into history")- paused_ms = measure_registration(- session,- bracketed_paste(PAUSED_PASTE),- "[paste #2 +12 lines]",- f"{binary}-paused-paste",- out_dir,- )-- # Back to the tail: the stream must have kept advancing through the- # paused paste window (the words past the pre-pause marker prove- # the turn was live while the paste registered).- tmux("send-keys", "-t", session, "C-S-Down")- wait_for(session, f"streaming-word-{STREAM_WORDS - 1:03d}", timeout=40)- # The turn completes: the loader row drops.- wait_gone(session, STREAMING_RE, timeout=40)- (out_dir / f"{binary}-stream-done.txt").write_text(capture(session))-- # The queued editor text submits whole after the turn. The second- # turn rebuilds the full resumed context, so the TS worker can take- # minutes on the 19MB corpus — the ack wait is not a latency- # assertion and gets a generous budget.- tmux("send-keys", "-t", session, "Enter")- wait_for(session, PASTE_ACK, timeout=300)- (out_dir / f"{binary}-submitted.txt").write_text(capture(session))-- # Submission integrity from the session file (ground truth, both- # products append JSONL): every pasted line verbatim.- tail = read_tail_settled(- corpus, [PASTE_ACK] + FOLLOW_PASTE + BURST_PASTE + PAUSED_PASTE- )- for line in FOLLOW_PASTE + BURST_PASTE + PAUSED_PASTE:- if line not in tail:- failures.append(f"the submitted message lost {line!r}")- if PASTE_ACK not in tail:- failures.append("the scripted ack never reached the session file")-- return {- "binary": binary,- "follow_paste_ms": round(follow_ms * 1000, 1),- "burst_paste_ms": round(burst_ms * 1000, 1),- "paused_paste_ms": round(paused_ms * 1000, 1),- "failures": failures,- }- finally:- tmux("kill-session", "-t", session, check=False)- batterylib.reap_daemons(- socket_paths=[Path(sandbox["agent"]) / "daemon.sock"],- cwd_roots=[Path(sandbox["agent"])],- )---def main():- parser = argparse.ArgumentParser()- parser.add_argument("--width", type=int, default=120)- parser.add_argument("--height", type=int, default=36)- parser.add_argument(- "--binary", choices=["rust", "ts", "both"], default="both",- help="which side to drive (the rust side gates the latency budget)",- )- args = parser.parse_args()-- ts_identity.assert_ts_side_is_the_ts_product()-- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")- out_dir = Path(__file__).resolve().parent / "paste-stream-runs" / stamp- out_dir.mkdir(parents=True)- # Reuse the drag family's 40MB corpus (shared cache location).- corpus_root = Path(__file__).resolve().parent / "drag-select-runs"- corpus_root.mkdir(exist_ok=True)- corpus = corpus_path(corpus_root)- script_path = out_dir / "faux-script.json"- script_path.write_text(json.dumps(FAUX_SCRIPT))- print(f"corpus: {corpus} ({corpus.stat().st_size / 1024 / 1024:.0f}MB)")-- sides = ["rust", "ts"] if args.binary == "both" else [args.binary]- evidence = {- "corpus": {"turns": TURNS, "size_mb": round(corpus.stat().st_size / 1024 / 1024, 1)}- }- failed = False- for side in sides:- result = run_side(side, corpus, script_path, out_dir, args.width, args.height)- evidence[side] = result- print(- f"{side}: follow {result['follow_paste_ms']}ms burst "- f"{result['burst_paste_ms']}ms paused {result['paused_paste_ms']}ms"- + (f" failures={result['failures']}" if result["failures"] else "")- )- if result["failures"]:- failed = True- if side == "rust":- worst = max(- result["follow_paste_ms"], result["burst_paste_ms"], result["paused_paste_ms"]- )- if worst > STEP_BUDGET_S * 1000:- print(- f"FAIL ({side}): a paste registration took {worst}ms "- f"(budget {STEP_BUDGET_S * 1000:.0f}ms) — the input path "- "blocked on transcript processing"- )- failed = True- else:- print(- f"PASS ({side}): every paste registered within "- f"{worst}ms (budget {STEP_BUDGET_S * 1000:.0f}ms) mid-stream"- )- (out_dir / "evidence.json").write_text(json.dumps(evidence, indent=2))- return 1 if failed else 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/print_json_parity.py b/scripts/print_json_parity.pydeleted file mode 100644index 644fbc19ca..0000000000--- a/scripts/print_json_parity.py+++ /dev/null@@ -1,987 +0,0 @@-#!/usr/bin/env python3-"""Print-mode json event-stream parity verifier: run the installed TS-prime-agent binary and the Rust rewrite in `--mode json` print runs over the-same scripted faux provider, normalize the volatile event fields, and diff-the full event sequences (the #211 parity-evidence pattern, headless: no-tmux, stdout json lines only).--Scenarios (each a fresh isolated HOME + agent dir per side; a scenario is-one or more sequential runs over the same shared session store):-- - stream: one prompt, one streamed text answer. Covers the session- header row, the harness digest's message pair (TS commit-time- injection, between turn_start and the user message pair), the- message_update deltas with the slim assistantMessageEvent (no nested- partial on the wire), and the run lifecycle order.- - threshold: a small seed turn then a ~12k-token crossing turn over a- 16k context window with reserveTokens=1. Covers the threshold- compaction arm's compaction_start/compaction_end pair (reason, result,- willRetry=false) at the settled turn boundary. The compact-trigger- auto-refine the compaction schedules stays off the stream on both- sides: the disposal drain runs after the client's subscription is torn- down (only the durable rows persist).- - resume: two runs over one session. Run one ends above the reserve- headroom with compaction disabled (nothing fires, either boundary);- run two resumes with compaction enabled (`--continue`, its own daemon- socket so the first run's worker never pins the session), and the- pre-turn boundary (TS `_runPreTurnCompaction`) fires the threshold- arm before the admitted prompt: the compaction_start/compaction_end- pair precedes the prompt's turn events on both sides.- - compact-refine: the overflow compact-and-retry arm whose retried turn- settles, then the serialized checkpoint's compact-trigger auto-refine:- the review gate approves and the refinement runs mid-run, streaming- the refinement rows' message pairs and refine_complete (the #214- residue: TS print mode auto-refines after compactions; probed against- the TS binary).- - compact-refine-decline: the same overflow shape with a declining- review - no refinement rows, no refine events, identical streams.- - goal-budget: `--goal <objective> --goal-token-budget 5` drives the- print-mode goal continuation surface the TS session hosts inside the- one print run: the seeded goal's continuation context rides the first- turn ahead of the user row, the settled turn's usage crossing publishes- the budget_limited goal_update and queues the `[goal: budget-limit]`- wrap-up steer (the queued session_action_update), the run ends, and- the steer drains as its own run (preparing/committing/running phase- frames) before the process exits. Compaction stays off (the goal- frames are the diff target).- - goal-natural: the same seed with an unbounded-budget goal loops the- natural continuation mints INSIDE the one run (turn_end -> mint- goal_update -> turn_start, no run boundary between continuation turns)- until the faux queue exhausts and the terminal error fails the goal- (the error goal_update after the run's agent_end).--The Rust run rides the harness digest row through the loop's prompt input-(the same TS design), so `agent_end.messages` includes it on both sides and-the comparison is full parity: any event difference fails.--Both sides run with RLM_DEPTH unset (root sessions are depth 0; the TS-daemon strips the env for its workers, the Rust print run is in-process).-The compaction scenarios that stay about the compaction arms (`threshold`,-`resume`) pin `autoRefine: {enabled: false}` in the sandbox settings so-the review rounds never enter their streams; the compact-refine scenarios-leave the gate at its enabled default - the compact-trigger review IS the-surface under test there (the threshold scenario scripts the drain's-decline, so its disposal round stays silent on both sides at the enabled-default). The settings gate is the product's own switch, so nothing else-differs.-- - goal-status: `/goal status` with no goal: the session-command surface- the print path dropped before this lane — the `session_action_update`- phase frames (kind `session_command`) around the durable echo row, the- `goal_update` publish, the `No active goal.` result row, the settled- idle frame. No model turn.- - goal-start: `/goal ship the feature`: the same frames, then the- goal_update, the queued continuation's preview frame, the result row,- and the continuation admitted as the queued turn (its `running` frame- at the turn's turn_start) — the in-run goal loop continues to the faux- queue's exhaustion, the terminal error fails the goal (the error- goal_update after the settled boundary), and the drained frame closes.- - compact-skip: a short session's `/compact`: the echo row, the- `compaction_start`, the skip's `compaction_end` (warning), no result- row (TS `CompactionSkippedError` records nothing).- - compact-manual: a compactable session's- `/compact focus on the essentials`: the compaction runs (start event- with the instructions, the settled end with the result), the next- prompt's turn runs on the compacted context.- - model-passthrough: `/model` (a client command, not a session command):- the print path never parses it — it runs to the model as a plain- prompt turn (the parse-but-drop regression guard).- - autonomous-status: `/autonomous status`: the echo row plus the durable- `autonomous_status` row pair.- - refine-command: `/refine <instructions>` after a work turn: the- scripted review approves, the refinement rows stream- (`refinement_outcome` pair plus `refine_complete`), and the- display-only result row lands on the wire ahead of the idle frame.--The Rust build cannot run on the parity host (sandbox glibc), so the-harness supports split runs: `--only ts` on the TS host and `--only-rust` with PA_RUST_BINARY pointing at the sandbox build (PI_PACKAGE_DIR-set to the sidecar) each persist their normalized captures plus a-sandbox-root meta into --out; when one side's captures already exist-there, the run diffs them and reports (the same diff the one-process-flow produces).--Exit code is non-zero when any event sequence differs. Use --keep to keep-the sandbox trees, --out to pin captures.-"""--import argparse-import difflib-import json-import os-import re-import shutil-import subprocess-import sys-import tempfile--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--TS_FAUX_EXTENSION = open(- os.path.join(os.path.dirname(os.path.abspath(__file__)), "ts_faux_extension.js"),- encoding="utf-8",-).read()---def find_runtime_package_dir():- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- if not os.path.isdir(releases):- raise SystemExit("cannot find the prime-agent-runtime sidecar; set PI_PACKAGE_DIR")- candidates = [- entry- for entry in sorted(os.listdir(releases))- if os.path.isdir(os.path.join(releases, entry, "prime-agent-runtime"))- ]- if not candidates:- raise SystemExit("no release with prime-agent-runtime/ under " + releases)- return os.path.join(releases, candidates[-1])---def prepare_sandbox(base, binary, settings):- home = os.path.join(base, binary, "home")- agent = os.path.join(base, binary, "agent")- tmp = os.path.join(base, binary, "tmp")- os.makedirs(home, exist_ok=True)- os.makedirs(tmp, exist_ok=True)- os.makedirs(os.path.join(agent, "sessions"), exist_ok=True)- os.makedirs(os.path.join(agent, "extensions"), exist_ok=True)- write_settings(agent, settings)- if binary == "ts":- # The TS binary runs its session in a daemon worker; the faux- # provider is a sandbox extension.- with open(os.path.join(agent, "extensions", "print-faux.js"), "w") as handle:- handle.write(TS_FAUX_EXTENSION)- # The isolated TMPDIR keeps the TS supervisor's socket (the default- # daemon-socket dir) under this run's sandbox, so the cleanup reap- # can sweep the side's daemons by path alone.- return {"home": home, "agent": agent, "tmp": tmp}---def write_settings(agent, settings):- with open(os.path.join(agent, "settings.json"), "w") as handle:- json.dump(settings, handle)---def run_scenario(binary, sandbox, script_path, prompts, cwd, extra_args, socket_path):- """Run the binary in print json mode; return (exit, stdout, stderr)."""- env = {key: value for key, value in os.environ.items()}- # Root sessions are depth 0 on both sides; ambient harness env stays out.- for leaked in ("RLM_DEPTH", "HOME", "PRIME_AGENT_CODING_AGENT_DIR", "PRIME_AGENT_FAUX_SCRIPT"):- env.pop(leaked, None)- env.update(- {- "HOME": sandbox["home"],- "TMPDIR": sandbox["tmp"],- "PRIME_AGENT_CODING_AGENT_DIR": sandbox["agent"],- "PRIME_AGENT_FAUX_SCRIPT": script_path,- "PRIME_AGENT_DISABLE_ANALYTICS": "1",- "PRIME_DISABLE_VERSION_CHECK": "1",- }- )- if binary == "ts":- command = ["prime-agent", "--daemon-socket", socket_path, "--model", "faux-1", "--mode", "json"]- else:- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "target", "debug", "prime-agent"),- )- env["PI_PACKAGE_DIR"] = os.environ.get("PI_PACKAGE_DIR") or find_runtime_package_dir()- # The Rust print harness takes the faux script inline (the env var- # is the JSON, not a path).- with open(script_path) as handle:- env["PRIME_AGENT_FAUX_SCRIPT"] = handle.read()- command = [rust, "--daemon-socket", socket_path, "--model", "faux-1", "--mode", "json"]- # The resume flags ride ahead of the prompts (both parsers accept- # positionals only last).- result = subprocess.run(- command + extra_args + ["-p"] + prompts,- capture_output=True,- text=True,- env=env,- cwd=cwd,- timeout=300,- )- return result.returncode, result.stdout, result.stderr---UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")---def normalize(value, sandbox_root):- """Normalize one parsed event (volatile fields -> placeholders)."""- if isinstance(value, list):- return [normalize(item, sandbox_root) for item in value]- if not isinstance(value, dict):- return value- out = {}- for key, item in value.items():- out[key] = normalize_value(key, item, sandbox_root)- return out---def normalize_value(key, item, sandbox_root):- if isinstance(item, (int, float)) and not isinstance(item, bool):- if key in (- "timestamp",- "tokensBefore",- "tokens",- "totalTokens",- "input",- "output",- "cacheRead",- "cacheWrite",- # The goal accounting's per-side token estimates (the #182- # normalization class: each side estimates its own context).- "tokensUsed",- "timeUsedSeconds",- "createdAt",- "updatedAt",- # The autonomous status snapshot's wall-clock start (the /autonomous- # on row's details): volatile per run.- "startedAt",- ):- return "<N>"- return item- if isinstance(item, str):- if key == "cwd" or sandbox_root in item:- return "<SANDBOX>"- if UUID_RE.match(item):- return "<ID>"- if key == "timestamp":- return "<TS>"- if key in ("created_at", "updated_at"):- # Harness-entry timestamps (the refinement result's before/after- # snapshots): volatile, normalized to a placeholder.- return "<TS>"- if key in ("firstKeptEntryId", "id", "refinementId"):- return "<ID>"- # The goal context texts (message contents, queue previews, action- # labels) carry the same per-side token estimates inline.- item = re.sub(r"- tokens used: -?\d+", "- tokens used: <n>", item)- item = re.sub(r"- remaining tokens: -?\d+", "- remaining tokens: <n>", item)- item = re.sub(r"- time used seconds: -?\d+", "- time used seconds: <n>", item)- return item- if isinstance(item, list):- return [normalize_value(key, entry, sandbox_root) for entry in item]- if isinstance(item, dict):- return normalize(item, sandbox_root)- return item---def normalize_events(stdout, sandbox_root):- """Parse, normalize, and collapse the json event lines (consecutive- message_update deltas of one type collapse to a single run marker -- the chunk boundaries are a faux-provider artifact, not a wire- contract)."""- events = []- for line in stdout.splitlines():- line = line.strip()- if not line:- continue- event = normalize_event(json.loads(line), sandbox_root)- previous = events[-1] if events else None- if (- isinstance(previous, dict)- and previous.get("type") == "message_update"- and event.get("type") == "message_update"- and previous.get("assistantMessageEvent") == event.get("assistantMessageEvent")- ):- continue- events.append(event)- return float_checkpoint_agent_end(events)---def is_refinement_event(event):- """One serialized-checkpoint refinement event (the compact-trigger- auto-refine surface): the durable rows' message pairs or the- refine_complete/refine_failed terminal events."""- if event.get("type") in ("refine_complete", "refine_failed"):- return True- message = event.get("message", {})- return event.get("type") in ("message_start", "message_end") and message.get(- "customType"- ) in ("refinement_outcome", "refinement_notice")---def float_checkpoint_agent_end(events):- """Hoist the overflow-retry continuation run's trailing agent_end across- the serialized checkpoint's refinement events (one narrow reordering):- the TS checkpoint runs inside the agent loop's stop decision - refine- events first, then the run's agent_end - while the Rust print boundary- runs post-idle, after the run's agent_end. An agent_end that directly- follows a turn_end and is followed ONLY by refinement events moves to- the tail; every other position is untouched."""- for index, event in enumerate(events):- if (- event.get("type") == "agent_end"- and index > 0- and events[index - 1].get("type") == "turn_end"- and events[index + 1 :]- and all(is_refinement_event(item) for item in events[index + 1 :])- ):- return events[:index] + events[index + 1 :] + [event]- return events---def normalize_event(event, sandbox_root):- event = normalize(event, sandbox_root)- kind = event.get("type")- if kind == "session":- # Keep the identity row's shape only.- return {"type": "session", "version": event.get("version")}- if kind in ("message_start", "message_end", "message_update", "turn_end"):- message = event.get("message", {})- normalized = {- "type": kind,- "message": normalize_message(message, sandbox_root),- }- if kind == "message_update":- # The delta chunking is a faux-provider artifact (token size- # bounds differ per implementation); the wire contract is the- # delta type and its content index - the accumulated partial- # at an intermediate chunk boundary is not. The terminal- # message_start/message_end events carry the content claim.- delta = event.get("assistantMessageEvent", {})- normalized["assistantMessageEvent"] = {- "type": delta.get("type"),- "contentIndex": delta.get("contentIndex"),- }- normalized["message"] = {"role": normalized["message"].get("role")}- if kind == "turn_end":- normalized["toolResults"] = event.get("toolResults", [])- return normalized- if kind == "agent_end":- # Role-level comparison of the run's message list; content is- # covered by the per-message events above.- return {- "type": "agent_end",- "messages": [- {"role": message.get("role"), "customType": message.get("customType")}- for message in event.get("messages", [])- ],- }- if kind == "compaction_end" and isinstance(event.get("result"), dict):- result = dict(event["result"])- result["tokensBefore"] = "<N>"- result["firstKeptEntryId"] = "<ID>"- # The derived file-operations block is extractor bookkeeping; the- # parity claim is the summary fields.- result.pop("details", None)- event = dict(event)- event["result"] = result- return event---def normalize_message(message, sandbox_root):- """One message's wire shape, volatile fields normalized."""- if not isinstance(message, dict):- return message- out = dict(message)- if out.get("role") == "custom" and out.get("customType") == "harness_digest":- # The digest body: the composed harness state (same framing on both- # sides; the ranked entries differ with wording, so compare the- # frame shape only).- content = out.get("content")- out["content"] = (- content[: content.index("\n")] + "\n<DIGEST>" if isinstance(content, str) and "\n" in content else "<DIGEST>"- )- details = out.get("details")- if isinstance(details, dict):- out["details"] = {"digest": "<DIGEST>"}- return out- # The assistant wire: drop the Rust-only diagnostics array, normalize- # the provider registration id and the usage estimate.- out.pop("diagnostics", None)- if isinstance(out.get("api"), str):- out["api"] = "<API>"- if isinstance(out.get("usage"), dict):- out["usage"] = "<USAGE>"- return out---def diff_events(ts_events, rust_events):- """Compare the normalized event sequences; returns the failure text."""- if len(ts_events) != len(rust_events):- return (- f"event count differs: ts={len(ts_events)} rust={len(rust_events)}\n"- + "\n".join(- difflib.unified_diff(- [json.dumps(event, sort_keys=True) for event in ts_events],- [json.dumps(event, sort_keys=True) for event in rust_events],- fromfile="ts",- tofile="rust",- lineterm="",- n=1,- )- )- )- failures = []- for index, (ts_event, rust_event) in enumerate(zip(ts_events, rust_events)):- if ts_event == rust_event:- continue- failures.append(- f"event {index} differs:\n ts: {json.dumps(ts_event, sort_keys=True)}\n"- f" rust: {json.dumps(rust_event, sort_keys=True)}\n"- )- return "".join(failures)---def faux_script(responses, context_window):- return {- "engine": "faux",- "modelId": "faux-1",- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": context_window,- "responses": responses,- }---# One run of a scenario: its own settings (written into the shared agent-# dir), faux script (written to its own script file), prompt list, and-# extra CLI args (the resume run passes --continue). Every run gets its-# own daemon socket so a previous run's worker never pins the session.-SCENARIOS = {- "stream": {- "runs": [- {- "settings": {"onboardingCompleted": True},- "script": faux_script(["a streamed parity answer"], 128000),- "prompts": ["hello parity"],- "args": [],- }- ]- },- "threshold": {- "runs": [- {- # Both sides' small-prompt context estimates sit under the 13k- # headroom (ts ~11.4k, rust ~8.3k - each side estimates its- # own prompt) and the ~6k-token crossing turn pushes both- # past it without overflowing the 20k window: the seed turn- # must stay below, the crossing turn must cross, on both- # sides.- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": True, "reserveTokens": 7000, "keepRecentTokens": 10},- },- # The fourth response serves the disposal drain's auto-refine- # review (the compaction scheduled the trigger; no further- # turn consumed it): a decline, so the drain's surface is- # silence on both sides - the compact-trigger round itself- # stays off the stream (TS dispose runs it after the- # subscription teardown).- "script": faux_script(- [- "seed reply",- "crossing reply",- "the compaction summary",- '{"shouldRefine": false, "rationale": "one-off tool output"}',- ],- 20000,- ),- "prompts": ["seed turn", "crossing turn " + "x" * 24000],- "args": [],- }- ]- },- "resume": {- "runs": [- {- # Run one: a big seed turn pushes the settled usage past the- # 18k headroom on both sides (each side estimates its own- # context: ts ~2x its serialized input via cacheWrite, rust- # ~23k), the small trailing turns keep the cut tail small,- # and compaction is disabled - neither boundary fires, so- # the session persists above the headroom.- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": False, "reserveTokens": 7000, "keepRecentTokens": 10},- "autoRefine": {"enabled": False},- },- "script": faux_script(["seed reply", "reply two padded", "k3", "k4"], 25000),- # The trailing turn texts are sized so the keep-recent walk- # (10 tokens) absorbs its budget at the ASSISTANT reply of- # "turn two" (its 16 chars push the trailing accumulation- # over the budget; the replies around it do not), not a- # user message: the resumed run's pre-turn compaction cuts- # INSIDE a turn — a split-turn compaction. TS backs it with- # TWO summarizer calls (the history checkpoint + the- # turn-prefix call) and a "**Turn Context (split turn):**"- # suffix; the merged summary rides the compaction_end- # result, so this scenario diffs the split shape- # byte-for-byte. The replies stay small: the TS print- # client rides the daemon wire, whose delta stream cannot- # be compared under a ~1000-delta burst (observed TS-side- # event loss; the Rust print run is in-process).- "prompts": [- "big seed turn " + "x" * 60000,- "turn two",- "turn three",- "turn four",- ],- "args": [],- },- {- # Run two: resume (`--continue`, fresh daemon socket) with- # compaction enabled - the pre-turn boundary fires the- # threshold arm before the admitted prompt, and the- # compacted context (summary + the small kept tail) sits- # back under the headroom, so the resumed turn's settled- # boundary stays quiet on both sides.- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": True, "reserveTokens": 7000, "keepRecentTokens": 10},- "autoRefine": {"enabled": False},- },- # Two summarizer responses for the split-turn compaction- # (history, then turn prefix - both sides pop the scripted- # queue at call time, history first), then the resumed- # turn's reply.- "script": faux_script(- [- "the history summary",- "the turn prefix summary",- "recovered after the resume",- ],- 25000,- ),- "prompts": ["next prompt"],- "args": ["--continue"],- },- ]- },- "compact-refine": {- "runs": [- {- # The overflow compact-and-retry (willRetry=true) whose- # retried turn settles, then the serialized checkpoint's- # compact-trigger auto-refine: the scripted review approves,- # the scripted refinement plan applies one memory edit, and- # the refine events stream mid-run on both sides. The- # overflow response is scripted (the classifier reads the- # error text), the way the #211/#214 unit harnesses do.- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": True, "reserveTokens": 1, "keepRecentTokens": 10},- },- "script": faux_script(- [- "seed reply",- {"text": "", "stopReason": "error", "errorMessage": "prompt is too long: 213462 tokens > 200000 maximum"},- "the compaction summary",- "recovered reply",- '{"shouldRefine": true, "rationale": "the overflow recovery tactic is reusable", "instructions": "record the tactic"}',- '{"summary":"note it","rationale":"repeated","expectedOutcome":"recall","edits":[{"action":"create","kind":"memory","id":"m1","title":"Tactic","content":"Use tactic A"}]}',- ],- 200000,- ),- "prompts": ["seed turn " + "x" * 48000, "overflow probe " + "x" * 48000],- "args": [],- }- ]- },- "goal-budget": {- "runs": [- {- # The budget-bounded goal loop: the seeded continuation- # context rides turn one, the crossing flips the goal to- # budget_limited (goal_update + the queued steering- # preview), the run ends, and the wrap-up steer drains as- # its own run (preparing/committing/running frames) before- # the empty-queue frame settles the stream. Compaction- # stays off; the goal frames are the diff target.- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": False},- },- "script": faux_script(- [- {"text": "goal turn reply"},- {"text": "wrap-up reply"},- ],- 128000,- ),- "prompts": ["work"],- "args": ["--goal", "finish the work", "--goal-token-budget", "5"],- }- ]- },- "goal-natural": {- "runs": [- {- # The natural continuation loop inside the one run: each- # settled turn mints the next continuation context (the- # continuationsUsed bump goal_update between turn_end and- # turn_start, no run boundary), until the faux queue- # exhausts and the terminal error fails the goal (the- # error goal_update after the run's agent_end - both- # providers raise the same "No more faux responses- # queued"). No token budget, so no wrap-up steer.- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": False},- },- "script": faux_script(- [- {"text": "turn one reply"},- {"text": "turn two reply"},- ],- 128000,- ),- "prompts": ["work"],- "args": ["--goal", "finish the work"],- }- ]- },- "goal-status": {- "runs": [- {- # The no-goal status command: frames, echo, goal_update,- # result row, idle frame — then a plain prompt whose turn- # runs on the context that carries the command rows (TS- # pushes them onto the live agent state).- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": False},- },- "script": faux_script([{"text": "hello reply"}], 128000),- "prompts": ["/goal status", "hello"],- "args": [],- }- ]- },- "goal-start": {- "runs": [- {- # The goal start command: the continuation schedules as- # queued session input and drains inside the same prompt- # wait; the in-run loop continues to the queue's- # exhaustion, the terminal error fails the goal.- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": False},- },- "script": faux_script(- [- {"text": "goal turn reply"},- {"text": "second turn reply"},- {"text": "third turn reply"},- ],- 128000,- ),- "prompts": ["/goal ship the feature"],- "args": [],- }- ]- },- "compact-skip": {- "runs": [- {- # A short session's /compact: the skip's warning- # compaction_end, no result row.- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": True, "reserveTokens": 1, "keepRecentTokens": 10},- },- "script": faux_script([{"text": "seed reply"}], 128000),- "prompts": ["hello", "/compact"],- "args": [],- }- ]- },- "compact-manual": {- "runs": [- {- # A compactable session's /compact with instructions: the- # compaction runs, the next prompt's turn continues on the- # compacted context.- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": True, "reserveTokens": 1, "keepRecentTokens": 10},- "autoRefine": {"enabled": False},- },- "script": faux_script(- [- {"text": "seed reply one"},- {"text": "seed reply two"},- {"text": "the compaction summary"},- {"text": "after compact reply"},- ],- 200000,- ),- "prompts": [- "seed turn one " + "x" * 15000,- "seed turn two " + "x" * 15000,- "/compact focus on the essentials",- "after prompt",- ],- "args": [],- }- ]- },- "model-passthrough": {- "runs": [- {- # A client command (/model) is not a session command: it- # runs to the model as a plain prompt (the parse-but-drop- # regression guard).- "settings": {"onboardingCompleted": True},- "script": faux_script([{"text": "a reply about the model command"}], 128000),- "prompts": ["/model"],- "args": [],- }- ]- },- "autonomous-status": {- "runs": [- {- # The autonomous status command: the echo row plus the- # durable autonomous_status row pair.- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": False},- },- "script": faux_script([], 128000),- "prompts": ["/autonomous status"],- "args": [],- }- ]- },- "autonomous-on": {- "runs": [- {- # The /autonomous on flip plus the in-run continuation- # (the #254 ambiguity, resolved against the binary): the- # command's action frames and rows (the #254 surface),- # then the "task" prompt's ONE run churning both- # continuations IN-RUN (turn_end -> turn_start, the- # continuation user row pair between them, no- # agent_start/agent_end between continuation turns), and- # the max-continuations budget ending the loop with no- # stop row or frame (the stderr exit contract carries it).- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": False},- },- "script": faux_script(- [- {"text": "work turn reply"},- {"text": "task turn reply"},- {"text": "continuation reply one"},- {"text": "continuation reply two"},- ],- 128000,- ),- "prompts": ["work", "/autonomous on --max-continuations 2", "task"],- "args": [],- }- ]- },- "autonomous-cli": {- "runs": [- {- # The CLI-flag autonomous run: the same in-run shape (the- # flags enable the loop from the first turn; one run, the- # continuation churns inside the prompt wait, the budget- # ends it silently).- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": False},- },- "script": faux_script(- [- {"text": "task turn reply"},- {"text": "continuation reply one"},- ],- 128000,- ),- "prompts": ["task"],- "args": ["--autonomous-max-continuations", "1"],- }- ]- },- "refine-command": {- "runs": [- {- # The manual /refine after a work turn: the scripted review- # approves, the refinement runs (rows plus refine_complete- # on the wire), the display-only result row follows.- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": False},- },- "script": faux_script(- [- {"text": "work reply"},- '{"shouldRefine": true, "rationale": "the pattern is reusable", "instructions": "record it"}',- '{"summary":"note","rationale":"repeated","expectedOutcome":"recall","edits":[{"action":"create","kind":"memory","id":"m1","title":"Tactic","content":"Use tactic A"}]}',- ],- 128000,- ),- "prompts": ["do some work", "/refine record the pattern"],- "args": [],- }- ]- },- "compact-refine-decline": {- "runs": [- {- # The same overflow shape with a declining review: the- # cooldown stamps, no refinement rows, no refine events -- # identical streams.- "settings": {- "onboardingCompleted": True,- "compaction": {"enabled": True, "reserveTokens": 1, "keepRecentTokens": 10},- },- "script": faux_script(- [- "seed reply",- {"text": "", "stopReason": "error", "errorMessage": "prompt is too long: 213462 tokens > 200000 maximum"},- "the compaction summary",- "recovered reply",- '{"shouldRefine": false, "rationale": "one-off tool output"}',- ],- 200000,- ),- "prompts": ["seed turn " + "x" * 48000, "overflow probe " + "x" * 48000],- "args": [],- }- ]- },-}---def capture_paths(out_dir, binary, name, index):- """The persisted normalized-capture and meta paths for one run."""- suffix = "" if index == 0 else f"-run{index}"- return (- os.path.join(out_dir, f"{binary}-{name}{suffix}.norm.json"),- os.path.join(out_dir, f"{binary}-{name}{suffix}.meta.json"),- )---def save_captures(out_dir, binary, name, normalized_list, sandbox_root):- """Persist one side's normalized captures plus the sandbox root (the- split-run compare loads them back)."""- for index, events in enumerate(normalized_list):- norm_path, meta_path = capture_paths(out_dir, binary, name, index)- with open(norm_path, "w") as handle:- json.dump(events, handle)- with open(meta_path, "w") as handle:- json.dump({"sandbox_root": sandbox_root}, handle)---def load_captures(out_dir, binary, name, run_count):- """The other side's persisted normalized captures, or None when any- run is missing."""- loaded = []- for index in range(run_count):- norm_path, _ = capture_paths(out_dir, binary, name, index)- if not os.path.exists(norm_path):- return None- with open(norm_path) as handle:- loaded.append(json.load(handle))- return loaded---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--keep", action="store_true")- parser.add_argument("--out", default=None)- parser.add_argument("--only", default=None, choices=["ts", "rust"])- parser.add_argument("--scenario", default=None, choices=sorted(SCENARIOS))- args = parser.parse_args()-- # Fail fast before any launch: a non-TS `prime-agent` on PATH plays a- # Rust build as the "ts" side and reports false divergences.- if args.only in (None, "ts"):- ts_identity.assert_ts_side_is_the_ts_product()-- base = tempfile.mkdtemp(prefix="print-json-parity-")- out_dir = args.out or tempfile.mkdtemp(prefix="print-json-captures-")- os.makedirs(out_dir, exist_ok=True)- failures = []- try:- for name, scenario in SCENARIOS.items():- if args.scenario and name != args.scenario:- continue- print(f"== scenario {name}")- shared_cwd = os.path.join(base, f"{name}-cwd")- os.makedirs(shared_cwd, exist_ok=True)- # captures[binary][run_index] = the normalized events of that run.- captures = {"ts": [], "rust": []}- for binary in ("ts", "rust"):- if args.only and binary != args.only:- continue- sandbox = prepare_sandbox(os.path.join(base, name), binary, scenario["runs"][0]["settings"])- for index, run in enumerate(scenario["runs"]):- # A later run may change the settings (the resume scenario- # enables compaction for run two); the agent dir - and its- # session store - stays shared across the runs.- if index > 0:- write_settings(sandbox["agent"], run["settings"])- script_path = os.path.join(base, f"{name}-run{index}-faux-script.json")- with open(script_path, "w") as handle:- json.dump(run["script"], handle)- # One daemon socket per run: a previous run's worker must- # not pin the session the next run resumes.- socket_path = os.path.join(sandbox["agent"], f"daemon-run{index}.sock")- code, stdout, stderr = run_scenario(- binary, sandbox, script_path, run["prompts"], shared_cwd, run["args"], socket_path- )- # The TS print run spawns a daemon (plus its supervisor) on- # this run's socket; reap it right away so a multi-run- # scenario never stacks daemons, and an exit never leaks- # one onto a deleted socket (#223).- batterylib.reap_daemons(needles=[os.path.join(base, name)], cwd_roots=[os.path.join(base, name)])- suffix = "" if index == 0 else f"-run{index}"- with open(os.path.join(out_dir, f"{binary}-{name}{suffix}.jsonl"), "w") as handle:- handle.write(stdout)- with open(os.path.join(out_dir, f"{binary}-{name}{suffix}.stderr"), "w") as handle:- handle.write(stderr)- captures[binary].append(normalize_events(stdout, os.path.join(base, name)))- # Persist each in-process side's normalized captures (the- # split-run compare: one side runs on the TS host, the other in- # the rust build sandbox, both against the same --out).- for binary in ("ts", "rust"):- if captures[binary]:- save_captures(out_dir, binary, name, captures[binary], os.path.join(base, name))- if args.only:- other = "rust" if args.only == "ts" else "ts"- if not captures[other]:- loaded = load_captures(out_dir, other, name, len(scenario["runs"]))- if loaded is not None:- captures[other] = loaded- if not (captures["ts"] and captures["rust"]):- print(f"SKIP {name} (only one side captured; run the other side with the same --out)")- continue- for index in range(len(scenario["runs"])):- label = name if index == 0 else f"{name}/run{index}"- diff = diff_events(captures["ts"][index], captures["rust"][index])- if diff:- failures.append(label)- print(diff)- with open(os.path.join(out_dir, f"{label.replace('/', '-')}-diff.txt"), "w") as handle:- handle.write(diff)- print(f"FAIL {label} (captures in {out_dir})")- else:- print(f"PASS {label} ({len(captures['ts'][index])} events, both sides)")- finally:- # Sweep anything a failed run left behind (an exception mid-run- # skips the per-run reap above), so the sandbox never dies with a- # live daemon still pointing at it.- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if not args.keep:- shutil.rmtree(base, ignore_errors=True)- if failures:- print(f"parity failures: {', '.join(failures)}")- return 1- print("print json event parity: PASS")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/prompt_menu_parity.py b/scripts/prompt_menu_parity.pydeleted file mode 100644index bdf4a3f6d6..0000000000--- a/scripts/prompt_menu_parity.py+++ /dev/null@@ -1,510 +0,0 @@-#!/usr/bin/env python3-"""Prompt-menu behavior harness: drive the BASE and BRANCH Rust builds-through the prompt-menu states and verify the prompt-menu-unification-behaviors (the family's deliberate divergences, verified on the branch).--Both sides are driven like a user in tmux with the faux provider engine-(`PRIME_AGENT_FAUX_SCRIPT`, the same harness seam visual_parity uses):-tmux launches the binary against an isolated HOME/agent dir, keys are sent-at the editor, and the rendered pane is captured after each state settles.--The states:--- a_empty_tab: Tab on the empty prompt. BEFORE (base): the forced file- completion lists the whole cwd (junk like a `.claude` directory). AFTER- (branch): nothing happens - no menu.-- b_slash_menu: `/m` opens the slash-command dropdown. AFTER: the dropdown- renders through the unified menu grammar (the `›` marker on the selected- row, the shared status rows).-- c_model_picker / d_mcp_menu: bare `/model` and `/mcp` open their menus.-- e_esc_menu_streaming: a slow faux turn streams; `./` + Tab opens the cwd- completion menu; Esc closes it. AFTER: the menu closes AND the rollout- CONTINUES (the loader still streams, no aborted row). BEFORE (base): Esc- also interrupts the turn.-- f_model_arg_rejection: `/model <arg>` + Enter. AFTER: the usage error row- with the text kept in the editor. BEFORE (base): the picker opens with the- search prefilled.-- g_model_tab_filtered: `/model <partial>` + Tab. AFTER: the model picker- opens with the partial as its filter. BEFORE: no picker (the Tab is file- completion of the partial).-- h_mcp_tab_filtered: `/mcp <partial>` + Tab. AFTER: the connections view- opens with the partial as its filter. BEFORE: no view.--Exit code is non-zero when any branch assertion fails. The report and the-per-state frames go to stdout and --out.-"""--import argparse-import json-import os-import re-import shlex-import subprocess-import sys-import time--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)--# Per-invocation suffix: concurrent runs must not reuse (and kill) each-# other's sessions.-SESSION_BASE = f"pmenu-base-{os.getpid()}"-SESSION_BRANCH = f"pmenu-branch-{os.getpid()}"-WIDTH, HEIGHT = 110, 34-SETTLE = 1.0-TS_SCRIPT_MODEL = "faux-1"--# The slow streaming turn for the Esc state: a long thinking block at 4-# tokens/second keeps the loader alive while the menu interaction runs.-STREAM_FAUX_SCRIPT = {- "engine": "faux",- "modelId": TS_SCRIPT_MODEL,- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 4,- "responses": [- {- "content": [- {- "type": "thinking",- "thinking": (- "A long slow thinking pass so the streaming loader stays up while the "- "completion menu opens and Escape closes it: the turn must still be "- "streaming after the key lands, proving the menu consumed the Escape "- "instead of the abort. This block is long on purpose so the faux "- "provider keeps streaming it for a good while before any visible "- "text appears in the transcript."- ),- },- {"type": "text", "text": "the final answer streams after the menu check"},- ]- },- {"content": [{"type": "text", "text": "second turn"}]},- ],-}--SPINNERS = "".join(- "\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f"- "\u25f4\u25f7\u25f6\u25f5\u25cb\u25f8\u25fb\u25fc"-)-SPINNER_CLASS = "[" + SPINNERS + "]"---def tmux(*args, check=True):- result = subprocess.run(- ["env", "-u", "TMUX", "tmux", *args], capture_output=True, text=True- )- if check and result.returncode != 0:- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")- return result.stdout---def ansi_stripped(text):- text = re.sub("\x1b\\][^\x07]*(\x07|\x1b\\\\)", "", text)- text = re.sub("\x1b\\[[0-?]*[ -/]*[@-~]", "", text)- return text---def capture(session):- raw = tmux("capture-pane", "-t", session, "-p", "-e")- lines = [ansi_stripped(line).rstrip() for line in raw.splitlines()]- while lines and not lines[-1]:- lines.pop()- return "\n".join(lines)---def wait_for(session, needle, timeout):- deadline = time.time() + timeout- while time.time() < deadline:- pane = capture(session)- if needle in pane:- return pane- time.sleep(0.3)- raise TimeoutError(f"session {session} never showed {needle!r}")---def wait_or_none(session, needle, timeout):- try:- return wait_for(session, needle, timeout)- except TimeoutError:- return None---def find_runtime_package_dir():- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- if not os.path.isdir(releases):- raise SystemExit("no TS release sidecar; set PI_PACKAGE_DIR")- candidates = [- entry- for entry in sorted(os.listdir(releases))- if os.path.isdir(os.path.join(releases, entry, "prime-agent-runtime"))- ]- if not candidates:- raise SystemExit("no release with prime-agent-runtime/")- return os.path.join(releases, candidates[-1])---def make_sandbox(base):- home = os.path.join(base, "home")- agent = os.path.join(base, "agent")- tmp = os.path.join(base, "tmp")- for path in (home, tmp, os.path.join(agent, "sessions")):- os.makedirs(path, exist_ok=True)- with open(os.path.join(agent, "settings.json"), "w") as handle:- json.dump({"onboardingCompleted": True}, handle)- return home, agent, tmp---def launch(session, binary, sandbox, script_path, shared_cwd):- home, agent, tmp = sandbox- tmux("kill-session", "-t", session, check=False)- tmux(- "new-session", "-d", "-s", session, "-x", str(WIDTH), "-y", str(HEIGHT),- "-c", shared_cwd,- )- time.sleep(0.5)- # The pane's shell parses the typed command: every path is- # shell-quoted (an --out with spaces must not split the environment- # assignment) and the binary resolves to an absolute path first (a- # relative one would be looked up under shared_cwd, the new- # session's cwd, not the checkout the harness ran from).- package_dir = os.environ.get("PI_PACKAGE_DIR") or find_runtime_package_dir()- # The pane shell inherits the harness process environment, so any- # inherited `RLM_*` variable (e.g. RLM_DEPTH=debug) leaks into the- # launched agent and can panic its env parsing: scrub them first.- rlm_unset = " ".join(- f"-u {shlex.quote(name)}" for name in os.environ if name.startswith("RLM_")- )- env = " ".join(- f"{name}={shlex.quote(value)}"- for name, value in (- ("HOME", home),- ("TMPDIR", tmp),- ("PRIME_AGENT_CODING_AGENT_DIR", agent),- ("PRIME_AGENT_FAUX_SCRIPT", script_path),- ("PRIME_AGENT_DISABLE_ANALYTICS", "1"),- ("PI_PACKAGE_DIR", package_dir),- )- )- command = (- f"env {rlm_unset} {env} {shlex.quote(os.path.abspath(binary))} "- f"--daemon-socket {shlex.quote(os.path.join(agent, 'daemon.sock'))} "- f"--model {TS_SCRIPT_MODEL}"- )- tmux("send-keys", "-t", session, command, "Enter")- wait_for(session, "Collapsed mode", timeout=60)---def send(session, *keys):- for key in keys:- tmux("send-keys", "-t", session, key)- time.sleep(0.12)---def run_states(session, out_dir, label, verify_branch):- """Drive every state; return the assertion results."""- frames = {}- results = []-- def check(name, ok, detail):- results.append((name, ok, detail))-- def clear_editor():- send(session, "C-u")-- # (a) empty Tab- send(session, "Tab")- time.sleep(SETTLE)- frames[f"{label}_a_empty_tab"] = capture(session)- menu_open = "alpha.txt" in frames[f"{label}_a_empty_tab"]- if verify_branch:- check("empty_tab_is_a_noop", not menu_open, f"cwd_menu_open={menu_open}")- else:- check("BASE_empty_tab_opens_cwd_menu", menu_open, f"cwd_menu_open={menu_open}")-- # (b) slash dropdown grammar- send(session, "/", "m")- time.sleep(SETTLE + 0.6)- frames[f"{label}_b_slash_menu"] = capture(session)- pane = frames[f"{label}_b_slash_menu"]- marker_rows = re.findall(r"^\s*› \S+", pane, re.M)- if verify_branch:- check(- "slash_menu_uses_menu_grammar",- len(marker_rows) == 1 and "model" in pane and "(" in pane,- f"marker_rows={marker_rows}",- )- send(session, "Escape")- time.sleep(0.4)- clear_editor()-- # (c) bare /model opens the picker. The trailing space completes the- # command token BEFORE Enter (the base's takes_argument completion- # would otherwise consume Enter to append its separator; the branch's- # menu-only /mcp//model complete without the separator).- send(session, "/model ")- send(session, "Enter")- frames[f"{label}_c_model_picker"] = wait_for(session, "Search models", timeout=15)- if verify_branch:- check(- "bare_model_opens_picker",- "Search models" in frames[f"{label}_c_model_picker"],- "picker search field",- )- send(session, "Escape")- time.sleep(SETTLE)-- # (d) bare /mcp opens the connections view (the daemon may serve the- # builtin catalog's service rows, so the frame needle is the view's- # search field, not the empty-roster row).- send(session, "/mcp ")- send(session, "Enter")- frames[f"{label}_d_mcp_menu"] = wait_for(- session, "Search MCP connections", timeout=15- )- if verify_branch:- check(- "bare_mcp_opens_menu",- "Search MCP connections" in frames[f"{label}_d_mcp_menu"],- "connections view frame",- )- send(session, "Escape")- time.sleep(SETTLE)-- # (e) Esc closes the open menu while a turn streams- send(session, "Run the check.")- send(session, "Enter")- wait_for(session, "Thinking", timeout=30)- send(session, ".", "/")- send(session, "Tab")- frames[f"{label}_e_menu_open_streaming"] = wait_for(- session, "alpha.txt", timeout=10- )- menu_open = "alpha.txt" in frames[f"{label}_e_menu_open_streaming"]- check(- f"{'BRANCH' if verify_branch else 'BASE'}_stream_menu_opens",- menu_open,- "the cwd menu lists the sandbox files",- )- send(session, "Escape")- time.sleep(1.2)- frames[f"{label}_e_after_escape"] = capture(session)- after = frames[f"{label}_e_after_escape"]- menu_closed = "alpha.txt" not in after- if verify_branch:- still_streaming = bool(re.search(SPINNER_CLASS, after))- aborted = "aborted" in after- check(- "esc_closes_menu_not_the_rollout",- menu_closed and still_streaming and not aborted,- f"menu_closed={menu_closed} streaming={still_streaming} "- f"aborted={aborted}",- )- else:- base_interrupted = "aborted" in after and not re.search(SPINNER_CLASS, after)- check(- "BASE_esc_also_interrupts",- menu_closed and base_interrupted,- f"menu_closed={menu_closed} interrupted={base_interrupted}",- )- # Drain the turn so the later command states dispatch.- send(session, "Escape")- wait_or_none(session, "aborted", 20)- time.sleep(1.0)- clear_editor()-- # (f) /model <arg> + Enter- send(session, "/model gpt-5. ")- send(session, "Enter")- time.sleep(SETTLE + 0.6)- frames[f"{label}_f_model_arg"] = capture(session)- pane = frames[f"{label}_f_model_arg"]- if verify_branch:- rejected = "Usage: /model" in pane- kept = "/model gpt-5" in pane- check(- "model_arg_rejected",- rejected and kept and "Search models" not in pane,- f"rejected={rejected} kept={kept}",- )- else:- opened = "Enter select" in pane- check(- "BASE_model_arg_opens_filtered_picker",- opened,- "base: the arg prefills the picker search",- )- send(session, "Escape")- time.sleep(SETTLE)- clear_editor()-- # (g) /model <partial> + Tab- send(session, "/model gp")- send(session, "Tab")- frame = wait_or_none(session, "Enter select", timeout=8)- frames[f"{label}_g_model_tab"] = frame or capture(session)- if verify_branch:- opened = frame is not None and re.search(- r"> gp\b", frames[f"{label}_g_model_tab"]- )- check(- "model_tab_opens_filtered_picker",- opened,- "picker open with the partial as its filter",- )- else:- check(- "BASE_model_tab_is_file_completion",- frame is None,- "base: no picker on Tab in the argument context",- )- if frame is not None:- send(session, "Escape")- time.sleep(SETTLE)- clear_editor()-- # (h) /mcp <partial> + Tab- send(session, "/mcp lin")- send(session, "Tab")- frame = wait_or_none(session, "navigate", timeout=8)- frames[f"{label}_h_mcp_tab"] = frame or capture(session)- if verify_branch:- opened = frame is not None and re.search(- r"> lin\b", frames[f"{label}_h_mcp_tab"]- )- check(- "mcp_tab_opens_filtered_menu",- opened,- "connections view open with the partial as its filter",- )- else:- check(- "BASE_mcp_tab_is_file_completion",- frame is None,- "base: no view on Tab in the argument context",- )- if frame is not None:- send(session, "Escape")-- for name, frame in frames.items():- with open(os.path.join(out_dir, f"{name}.txt"), "w") as handle:- handle.write(frame + "\n")- return results---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--out", default="/tmp/prompt-menu-parity")- parser.add_argument(- "--base-binary",- default=os.environ.get("PA_BASE_BINARY", ""),- help="the pre-change binary (the origin/rust build)",- )- parser.add_argument(- "--branch-binary",- default=os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)),- "..",- "target",- "debug",- "prime-agent",- ),- ),- help="the with-change binary (the worktree build)",- )- parser.add_argument(- "--skip-base", action="store_true", help="verify only the branch build"- )- args = parser.parse_args()- # The sandbox paths (the faux script, the daemon sockets) leak into the- # child environment and resolve against the tmux pane's cwd, not this- # process's — a relative --out would point the launched binary at- # ./sandbox/cwd/sandbox/... Normalize once, here.- args.out = os.path.abspath(args.out)- os.makedirs(args.out, exist_ok=True)-- base = os.path.join(args.out, "sandbox")- shared_cwd = os.path.join(base, "cwd")- os.makedirs(shared_cwd, exist_ok=True)- with open(os.path.join(shared_cwd, "alpha.txt"), "w") as handle:- handle.write("alpha\n")- with open(os.path.join(shared_cwd, "beta.md"), "w") as handle:- handle.write("# beta\n")- os.makedirs(os.path.join(shared_cwd, "gamma"), exist_ok=True)-- script_path = os.path.join(base, "faux-script.json")- with open(script_path, "w") as handle:- json.dump(STREAM_FAUX_SCRIPT, handle, indent=2)-- all_results = []- sockets = []- # Reap any daemons a previous (possibly crashed) run leaked on this- # harness's sockets before launching fresh sides.- stale_sandbox = os.path.join(args.out, "sandbox")- stale_sockets = []- for side in ("base", "branch"):- socket = os.path.join(stale_sandbox, side, "agent", "daemon.sock")- if os.path.exists(socket):- stale_sockets.append(socket)- if stale_sockets:- # cwd_roots scopes the detached-worker sweep, which kills ANY- # process working under the roots: only the harness-owned sandbox- # dir belongs there (`--out .` or `--out /tmp` must not sweep- # unrelated processes).- batterylib.reap_daemons(- socket_paths=stale_sockets,- needles=(args.out,),- cwd_roots=(stale_sandbox,),- )- # Each side tears down in a finally: a wait_for timeout or a tmux- # error mid-run must not leak the session or its daemon, and the- # final reap must run even when a side raises.- try:- if not args.skip_base:- if not args.base_binary:- raise SystemExit("set --base-binary (or PA_BASE_BINARY)")- sandbox = make_sandbox(os.path.join(base, "base"))- sockets.append(os.path.join(sandbox[1], "daemon.sock"))- try:- launch(- SESSION_BASE, args.base_binary, sandbox, script_path, shared_cwd- )- all_results += run_states(- SESSION_BASE, args.out, "base", verify_branch=False- )- finally:- tmux("kill-session", "-t", SESSION_BASE, check=False)-- sandbox = make_sandbox(os.path.join(base, "branch"))- sockets.append(os.path.join(sandbox[1], "daemon.sock"))- try:- launch(- SESSION_BRANCH, args.branch_binary, sandbox, script_path, shared_cwd- )- all_results += run_states(- SESSION_BRANCH, args.out, "branch", verify_branch=True- )- finally:- tmux("kill-session", "-t", SESSION_BRANCH, check=False)- finally:- batterylib.reap_daemons(- socket_paths=sockets, needles=(args.out,), cwd_roots=(base,)- )-- failed = 0- print("\n== prompt-menu harness ==")- for name, ok, detail in all_results:- status = "PASS" if ok else "FAIL"- if not ok:- failed += 1- print(f"[{status}] {name}: {detail}")- print(f"\n{len(all_results) - failed}/{len(all_results)} checks passed")- print(f"frames under {args.out}")- return 1 if failed else 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/protocol_breadth_parity.py b/scripts/protocol_breadth_parity.pydeleted file mode 100644index c43fbc0bbd..0000000000--- a/scripts/protocol_breadth_parity.py+++ /dev/null@@ -1,407 +0,0 @@-#!/usr/bin/env python3-"""Daemon protocol-breadth wire parity (roadmap item 7, wave-1 verifier).--Runs the installed TS `prime-agent` supervisor and the Rust `pa-daemon`-side by side on isolated temp HOME/TMPDIR state, sends the same command-envelopes to both, and byte-compares the response shapes (dynamic fields-normalized away). The lane contract:-- - an unknown command type fails with the exact TS error string and the- offending type echoed in the response `command` field;- - a previously-rejected TS command type (resume_queue,- mutate_queued_message, get_connection_state, ...) routes exactly like- TS: same `Unknown active session: <id>` refusal for a bogus selector;- - the waves b10-b11 selector-less arms (cron_list, heartbeats_list,- cron_cancel, rename/delete_saved_session, list_agent_peers) match,- and the close-out batch covers every remaining TS command type with a- deterministic fresh-supervisor error path (a bogus selector refuses- with the exact TS error before any worker sees the command).--Usage: python3 scripts/protocol_breadth_parity.py [path-to-pa-daemon]-(the default is target/debug/pa-daemon relative to the repo root).-"""-import json, os, socket, subprocess, sys, tempfile, time, uuid--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))-TS = "prime-agent"-RS = sys.argv[1] if len(sys.argv) > 1 else os.path.join(REPO, "target", "debug", "pa-daemon")-SCRUB = [- "PRIME_AGENT_INTERNAL_DAEMON_WORKER",- "PRIME_AGENT_INTERNAL_DAEMON_WORKER_TOKEN",- "PRIME_AGENT_INTERNAL_DAEMON_WORKER_ACTIVE_SESSION_ID",- "PRIME_AGENT_INTERNAL_DAEMON_WORKER_INSTANCE_ID",- "PRIME_AGENT_INTERNAL_DAEMON_WORKER_RECOVERY_JOURNAL",- "PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_SOCKET",- "PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL",- "PRIME_AGENT_INTERNAL_SESSION_LEASES",- "PRIME_AGENT_INTERNAL_SESSION_LEASE_OWNER_ID",-]--def _start(binary, sock, agent_dir):- env = {k: v for k, v in os.environ.items() if k not in SCRUB}- # Fresh HOME keeps the daemon off shared box state (supervisor-owner- # registry, daemon sockets), like the parity-battery sandboxes.- env["HOME"] = agent_dir + "-home"- os.makedirs(env["HOME"], exist_ok=True)- env["PRIME_AGENT_CODING_AGENT_DIR"] = agent_dir- env["PRIME_AGENT_DISABLE_ANALYTICS"] = "1"- # Isolated TMPDIR keeps the default daemon-socket dir (and the legacy- # supervisor registry under it) away from other lanes' daemons on the- # shared box; the ownership check refuses to start otherwise.- env["TMPDIR"] = agent_dir + "-tmp"- os.makedirs(env["TMPDIR"], exist_ok=True)- # Per-user global supervisor registry: point it at the temp home so- # the ownership check cannot see other lanes' daemons on this box.- env["PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_REGISTRY_DIR"] = (- env["HOME"] + "/.prime/supervisor-owners"- )- child = subprocess.Popen(- [binary, "supervisor", "--socket", sock, "--agent-dir", agent_dir],- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env,- )- # The TS supervisor's default socket dir is per-user- # (prime-agent-<uid>); root runs (sandboxes) land in prime-agent-0.- ts_default_socket = os.path.join(- env.get("TMPDIR", ""), f"prime-agent-{os.getuid()}", "daemon.sock")- deadline = time.time() + 15- while time.time() < deadline:- if os.path.exists(sock) or os.path.exists(ts_default_socket):- return child- if child.poll() is not None:- raise SystemExit(f"{binary} exited with {child.returncode}")- time.sleep(0.05)- raise SystemExit(f"{binary} socket never appeared")--def start(binary, sock, agent_dir):- """Start one supervisor; returns (child, socket_path).-- The TS supervisor binds its default socket under $TMPDIR- (prime-agent-1000/daemon.sock) even with --socket given; the Rust- supervisor honors --socket. Both get an isolated TMPDIR so no two- daemons in this run (or on the box) collide.- """- child = _start(binary, sock, agent_dir)- ts_default = os.path.join(- agent_dir + "-tmp", f"prime-agent-{os.getuid()}", "daemon.sock")- return child, (ts_default if binary == TS else sock)--def connect(sock):- s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- s.settimeout(10)- s.connect(sock)- f = s.makefile("rw")- hello = json.loads(f.readline())- return s, f, hello--def send(f, cid, command):- if command.get("id") == "bare":- # A bare command (no envelope): the TS supervisor rejects it with- # the protocol error under command:"parse".- env = command- else:- env = {"type": "command", "id": cid,- "protocol": {"name": "prime-agent.daemon", "version": 7},- "command": command}- f.write(json.dumps(env) + "\n")- f.flush()- while True:- line = f.readline()- if not line:- raise SystemExit("connection closed")- value = json.loads(line)- if value.get("type") == "response" and value.get("id") == cid:- return value- # A bare command's failure still carries the client's own id.--def norm(response):- """Normalize dynamic fields; compare the wire shape."""- data = response.pop("data", None)- out = {- "id": response.get("id"),- "command": response.get("command"),- "success": response.get("success"),- "error": response.get("error"),- }- if response.get("errorInfo") is not None:- out["errorInfo"] = response["errorInfo"]- return out, data--CASES = [- ("unknown type keeps the TS error",- {"type": "bogus_command"}),- ("bare command answers the TS parse failure",- {"type": "list", "id": "bare"}),- ("previously-rejected type now routes (resume_queue)",- {"type": "resume_queue", "activeSessionId": "bogus-1"}),- ("previously-rejected type now routes (mutate_queued_message)",- {"type": "mutate_queued_message", "activeSessionId": "bogus-1",- "lane": "steering", "index": 0, "expectedText": "x",- "mutation": {"type": "delete"}}),- ("previously-rejected type now routes (get_connection_state)",- {"type": "get_connection_state", "activeSessionId": "bogus-1"}),- ("no-selector command now matches TS (agent_messages_status)",- {"type": "agent_messages_status"}),- ("no-selector command now matches TS (agent_messages_pause)",- {"type": "agent_messages_pause"}),- ("no-selector command now matches TS (agent_messages_resume)",- {"type": "agent_messages_resume"}),- # Waves b10-b11: the scheduling catalog and the saved-session/peer- # surface. The selector-less forms are the TS supervisor arms; bogus- # selectors resolve through the generic route with the TS refusal.- ("b10 scheduling selector-less matches TS (cron_list)",- {"type": "cron_list"}),- ("b10 scheduling selector-less matches TS (heartbeats_list)",- {"type": "heartbeats_list"}),- ("b10 scheduling selector-less unknown job (cron_cancel)",- {"type": "cron_cancel", "jobId": "ghost-job"}),- ("b10 scheduling bogus selector routes (cron_add)",- {"type": "cron_add", "activeSessionId": "bogus-1",- "schedule": "every 10m", "prompt": "hi"}),- ("b10 scheduling bogus selector routes (heartbeat_get)",- {"type": "heartbeat_get", "activeSessionId": "bogus-1"}),- ("b10 scheduling bogus selector routes (heartbeat_set)",- {"type": "heartbeat_set", "activeSessionId": "bogus-1",- "schedule": "every 5m", "prompt": "hi"}),- ("b10 scheduling bogus selector routes (heartbeat_update)",- {"type": "heartbeat_update", "activeSessionId": "bogus-1",- "action": "pause"}),- ("b10 scheduling bogus selector routes (heartbeat_manage)",- {"type": "heartbeat_manage", "activeSessionId": "bogus-1",- "jobId": "j", "action": "pause"}),- ("b11 saved-session rename unknown path (rename_saved_session)",- {"type": "rename_saved_session",- "sessionPath": "/tmp/does-not-exist-xyz.jsonl", "name": "renamed"}),- ("b11 saved-session delete unknown path (delete_saved_session)",- {"type": "delete_saved_session",- "sessionPath": "/tmp/does-not-exist-xyz.jsonl"}),- ("b11 peer roster requires worker auth (list_agent_peers)",- {"type": "list_agent_peers"}),- # Waves b2-b5 (worker commands): a bogus selector routes identically- # on both supervisors - the exact TS refusal before any worker sees- # the command.- ("b2 getter routes (get_connection_state)",- {"type": "get_connection_state", "activeSessionId": "bogus-1"}),- ("b2 getter routes (get_rlm_children)",- {"type": "get_rlm_children", "activeSessionId": "bogus-1"}),- ("b2 getter routes (get_context_tree)",- {"type": "get_context_tree", "activeSessionId": "bogus-1"}),- ("b2 getter routes (get_commands)",- {"type": "get_commands", "activeSessionId": "bogus-1"}),- ("b2 getter routes (get_resource_snapshot)",- {"type": "get_resource_snapshot", "activeSessionId": "bogus-1"}),- ("b2 getter routes (get_session_context)",- {"type": "get_session_context", "activeSessionId": "bogus-1"}),- ("b2 getter routes (get_system_prompt)",- {"type": "get_system_prompt", "activeSessionId": "bogus-1"}),- ("b2 getter routes (get_tool_definition)",- {"type": "get_tool_definition", "activeSessionId": "bogus-1", "name": "bash"}),- ("b2 getter routes (get_rlm_max_depth_status)",- {"type": "get_rlm_max_depth_status", "activeSessionId": "bogus-1"}),- ("b2 getter routes (get_model_catalog)",- {"type": "get_model_catalog", "activeSessionId": "bogus-1"}),- ("b2 getter routes (get_available_models)",- {"type": "get_available_models", "activeSessionId": "bogus-1"}),- ("b3 switch routes (cycle_model)",- {"type": "cycle_model", "activeSessionId": "bogus-1"}),- ("b3 switch routes (set_scoped_models)",- {"type": "set_scoped_models", "activeSessionId": "bogus-1", "scopedModels": []}),- ("b3 switch routes (cycle_thinking_level)",- {"type": "cycle_thinking_level", "activeSessionId": "bogus-1"}),- ("b3 switch routes (set_service_tier)",- {"type": "set_service_tier", "activeSessionId": "bogus-1", "serviceTier": "priority"}),- ("b3 switch routes (set_transport)",- {"type": "set_transport", "activeSessionId": "bogus-1", "transport": "auto"}),- ("b3 switch routes (set_steering_mode)",- {"type": "set_steering_mode", "activeSessionId": "bogus-1", "mode": "all"}),- ("b3 switch routes (set_follow_up_mode)",- {"type": "set_follow_up_mode", "activeSessionId": "bogus-1", "mode": "all"}),- ("b3 switch routes (set_auto_retry)",- {"type": "set_auto_retry", "activeSessionId": "bogus-1", "enabled": True}),- ("b3 switch routes (abort_retry)",- {"type": "abort_retry", "activeSessionId": "bogus-1"}),- ("b4 command routes (append_custom_message)",- {"type": "append_custom_message", "activeSessionId": "bogus-1",- "message": {"customType": "x", "content": "y", "display": True}}),- ("b4 command routes (restore_next_turn)",- {"type": "restore_next_turn", "activeSessionId": "bogus-1", "messages": []}),- ("b4 command routes (restore_actions)",- {"type": "restore_actions", "activeSessionId": "bogus-1",- "snapshot": {"formatVersion": 1, "actions": []}}),- ("b4 command routes (refine)",- {"type": "refine", "activeSessionId": "bogus-1", "instructions": "tidy"}),- ("b4 command routes (reload)",- {"type": "reload", "activeSessionId": "bogus-1"}),- ("b5 bash routes (execute_bash)",- {"type": "execute_bash", "activeSessionId": "bogus-1", "command": "echo hi"}),- ("b5 bash routes (execute_bash_and_wait)",- {"type": "execute_bash_and_wait", "activeSessionId": "bogus-1", "command": "echo hi"}),- ("b5 bash routes (abort_bash)",- {"type": "abort_bash", "activeSessionId": "bogus-1"}),- # Waves b6-b9: every new command routes; a bogus selector refuses with- # the exact TS error before any worker sees the command. The- # selector-less agent_messages_* forms match the TS supervisor arms- # (wave b7); the ownership/lifecycle commands (b9) answer the TS- # unknown-session error, and retry_worker resolves before its arm.- ("b6 rlm routes (cancel_rlm_child)",- {"type": "cancel_rlm_child", "activeSessionId": "bogus-1", "childId": "c"}),- ("b6 rlm routes (delete_rlm_subagent)",- {"type": "delete_rlm_subagent", "activeSessionId": "bogus-1", "childId": "c"}),- ("b6 rlm routes (set_rlm_max_depth)",- {"type": "set_rlm_max_depth", "activeSessionId": "bogus-1", "maxDepth": 3}),- ("b6 rlm routes (get_rlm_max_depth_status)",- {"type": "get_rlm_max_depth_status", "activeSessionId": "bogus-1"}),- ("b7 clear routes (agent_messages_clear)",- {"type": "agent_messages_clear", "activeSessionId": "bogus-1"}),- ("b8 pause routes (acquire_session_input_pause)",- {"type": "acquire_session_input_pause", "activeSessionId": "bogus-1", "leaseKey": "k"}),- ("b8 pause routes (release_session_input_pause)",- {"type": "release_session_input_pause", "activeSessionId": "bogus-1", "pauseId": "p"}),- ("b9 ownership routes (complete_owned_session)",- {"type": "complete_owned_session", "activeSessionId": "bogus-1"}),- ("b9 ownership routes (promote_owned_session)",- {"type": "promote_owned_session", "activeSessionId": "bogus-1"}),- ("b9 navigation routes (new_session)",- {"type": "new_session", "activeSessionId": "bogus-1"}),- ("b9 navigation routes (switch_session)",- {"type": "switch_session", "activeSessionId": "bogus-1", "sessionPath": "/tmp/x.jsonl"}),- ("b9 navigation routes (import_jsonl)",- {"type": "import_jsonl", "activeSessionId": "bogus-1", "inputPath": "/tmp/in.jsonl"}),- ("b9 navigation routes (export_html)",- {"type": "export_html", "activeSessionId": "bogus-1", "outputPath": "/tmp/out.html"}),- ("b9 navigation routes (export_jsonl)",- {"type": "export_jsonl", "activeSessionId": "bogus-1", "outputPath": "/tmp/out.jsonl"}),- ("b9 admission routes (cancel_prompt_admission)",- {"type": "cancel_prompt_admission", "activeSessionId": "bogus-1", "admissionId": "a1"}),- ("b9 recovery routes (retry_worker)",- {"type": "retry_worker", "activeSessionId": "bogus-1"}),- # Audit close-out: every remaining TS command type rides the same- # fresh-supervisor comparison with a deterministic envelope (the- # empty-catalog reads, and the bogus-selector refusal). Types with- # real side effects (create, ack_result, restart, shutdown,- # prepare_update_restart) are covered by the e2e suites instead.- ("close-out: list answers the empty catalog",- {"type": "list"}),- ("close-out: list_saved_sessions answers the empty catalog",- {"type": "list_saved_sessions"}),- ("close-out: roster_subscribe answers the empty roster",- {"type": "roster_subscribe"}),- ("close-out: roster_unsubscribe answers success",- {"type": "roster_unsubscribe"}),- ("close-out: transport ticket for a bogus session (get_direct_worker_transport)",- {"type": "get_direct_worker_transport", "activeSessionId": "bogus-1"}),- ("close-out: attach bogus selector",- {"type": "attach", "activeSessionId": "bogus-1"}),- # NOTE: `reattach` has no close-out case: the TS supervisor arm- # crashes on a minimal reattach ("undefined is not an object (evaluating- # 'e.replaceAll')" - a TS bug, fixed-shape reattach is covered by the- # direct-attach e2e suite), so the Rust parse refusal is the correct- # divergence to keep.- ("close-out: detach bogus selector",- {"type": "detach", "activeSessionId": "bogus-1"}),- ("close-out: kill bogus selector",- {"type": "kill", "activeSessionId": "bogus-1"}),- ("close-out: rename bogus selector",- {"type": "rename", "activeSessionId": "bogus-1", "name": "x"}),- ("close-out: set_session_name bogus selector",- {"type": "set_session_name", "activeSessionId": "bogus-1", "name": "x"}),- ("close-out: prompt bogus selector",- {"type": "prompt", "activeSessionId": "bogus-1", "message": "hi"}),- ("close-out: prompt_and_wait bogus selector",- {"type": "prompt_and_wait", "activeSessionId": "bogus-1", "message": "hi"}),- ("close-out: steer bogus selector",- {"type": "steer", "activeSessionId": "bogus-1", "message": "hi"}),- ("close-out: follow_up bogus selector",- {"type": "follow_up", "activeSessionId": "bogus-1", "message": "hi"}),- ("close-out: abort bogus selector",- {"type": "abort", "activeSessionId": "bogus-1"}),- ("close-out: start_side_question bogus selector",- {"type": "start_side_question", "activeSessionId": "bogus-1"}),- ("close-out: abort_side_question bogus selector",- {"type": "abort_side_question", "activeSessionId": "bogus-1"}),- ("close-out: send_message bogus target",- {"type": "send_message", "targetActiveSessionId": "bogus-1", "message": "hi"}),- ("close-out: wait_for_idle bogus selector",- {"type": "wait_for_idle", "activeSessionId": "bogus-1"}),- ("close-out: wait_for_headless_completion bogus selector",- {"type": "wait_for_headless_completion", "activeSessionId": "bogus-1"}),- ("close-out: get_session_header bogus selector",- {"type": "get_session_header", "activeSessionId": "bogus-1"}),- ("close-out: get_state bogus selector",- {"type": "get_state", "activeSessionId": "bogus-1"}),- ("close-out: get_messages bogus selector",- {"type": "get_messages", "activeSessionId": "bogus-1"}),- ("close-out: get_session_stats bogus selector",- {"type": "get_session_stats", "activeSessionId": "bogus-1"}),- ("close-out: get_queue bogus selector",- {"type": "get_queue", "activeSessionId": "bogus-1"}),- ("close-out: clear_queue bogus selector",- {"type": "clear_queue", "activeSessionId": "bogus-1"}),- ("close-out: abort_and_clear_queue bogus selector",- {"type": "abort_and_clear_queue", "activeSessionId": "bogus-1"}),- ("close-out: get_last_assistant_text bogus selector",- {"type": "get_last_assistant_text", "activeSessionId": "bogus-1"}),- ("close-out: replace_acp_mcp_servers bogus selector",- {"type": "replace_acp_mcp_servers", "activeSessionId": "bogus-1",- "ownerId": "o", "servers": []}),- ("close-out: set_model bogus selector",- {"type": "set_model", "activeSessionId": "bogus-1",- "provider": "p", "modelId": "m"}),- ("close-out: set_thinking_level bogus selector",- {"type": "set_thinking_level", "activeSessionId": "bogus-1",- "level": "medium"}),- ("close-out: set_auto_compaction bogus selector",- {"type": "set_auto_compaction", "activeSessionId": "bogus-1",- "enabled": True}),- ("close-out: compact bogus selector",- {"type": "compact", "activeSessionId": "bogus-1"}),- ("close-out: abort_compaction bogus selector",- {"type": "abort_compaction", "activeSessionId": "bogus-1"}),-]--# Fail fast before any launch: a non-TS `prime-agent` on PATH plays a-# Rust build as the "ts" side and reports false protocol diffs.-ts_identity.assert_ts_side_is_the_ts_product(TS)--tmp = tempfile.mkdtemp(prefix="pa-parity-")-ts_sock = os.path.join(tmp, "ts.sock")-rs_sock = os.path.join(tmp, "rs.sock")-ts_child, ts_path = start(TS, ts_sock, os.path.join(tmp, "ts-agent"))-rs_child, rs_path = start(RS, rs_sock, os.path.join(tmp, "rs-agent"))-try:- ts_f = connect(ts_path)[1]- rs_f = connect(rs_path)[1]- failures = 0- for label, command in CASES:- cid = "bare" if command.get("id") == "bare" else "c-" + uuid.uuid4().hex[:8]- ts_resp = send(ts_f, cid, command)- rs_resp = send(rs_f, cid, command)- ts_norm, ts_data = norm(ts_resp)- rs_norm, rs_data = norm(rs_resp)- ok = ts_norm == rs_norm- expected = "later wave" in label- status = ("MATCH " if ok else ("EXPECTED-DIFF " if expected else "UNEXPECTED-DIFF "))- print(f"{status} {label}")- print(f" TS: {json.dumps(ts_norm)}")- print(f" RS: {json.dumps(rs_norm)}")- # An expected diff is the staged remainder (the TS supervisor arm- # for the selector-less form lands with its breadth wave); it- # must not fail the verifier, but it is always printed.- if ts_norm != rs_norm and not expected:- failures += 1- print(f"\n{'ALL MATCH' if failures == 0 else f'{failures} UNEXPECTED DIFFS'}")- sys.exit(1 if failures else 0)-finally:- for child in (ts_child, rs_child):- child.terminate()- try:- child.wait(timeout=5)- except subprocess.TimeoutExpired:- child.kill()- # The TS supervisor can have been replaced mid-run (the respawn- # surfaces a fresh `--mode daemon` the terminate above never saw);- # sweep this run's tmp root so no daemon outlives the verifier (#223).- batterylib.reap_daemons(needles=[tmp], cwd_roots=[tmp])diff --git a/scripts/queue_edit_parity.py b/scripts/queue_edit_parity.pydeleted file mode 100644index 60fa4a943e..0000000000--- a/scripts/queue_edit_parity.py+++ /dev/null@@ -1,414 +0,0 @@-#!/usr/bin/env python3-"""Queue-edit parity (TS vs Rust), tmux frame-diff, both key byte forms.--The queue-edit flow under test (TS keybindings.ts + custom-editor.ts):-alt+up selects a parked steer/follow-up message - its text loads into the-editor with the dim browse header; alt+down walks back to the draft;-Enter re-queues the edit onto the steering lane (the daemon-side-`mutate_queued_message` replace, TS `enter steers`); an empty submit-deletes; Escape cancels back to the draft.--Two byte forms drive the same "alt+up" identity:--- the xterm parameter form `\x1b[1;3A` (tmux M-Up) — both products- handle it natively, so the TS and Rust captures diff byte-exact per- state (strip rows, browse header, editor text row);-- the meta-wrapped form `\x1b\x1b[A` (macOS Terminal "use option as- meta key") — TS-main's keys.test.ts pins the wrapped identity- (matchesKey("\x1b\x1b[1;5A", "ctrl+alt+up") et al.), but the live TS- pipeline splits the bytes first (StdinBuffer extractCompleteSequences- emits `\x1b\x1b`, then `[`, `A`; observed: the escape-repeat arms, the- session tree opens, the turn aborts and the queue drains). The Rust- reader repairs the wrapped identity instead (merge_legacy_meta_escapes),- so the Rust wrapped capture must equal the Rust parameter capture- byte-exact — the same "alt+up" identity reaching the same states.--Exit code is non-zero when any state differs.--Reuses the visual_parity faux-provider harness (tmux rules: default-socket, vplane-* session names, sessions killed individually) and the-#226 shared daemon reap.-"""--import argparse-import difflib-import glob-import json-import os-import shutil-import sys-import tempfile-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-import visual_parity as vp-import queue_parity as qp--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--STEERING_PROMPT = "steering prompt text"-FOLLOW_UP_PROMPT = "follow-up prompt text"-EDITED_PROMPT = f"{FOLLOW_UP_PROMPT} edited"-DRAFT = "draft text"-FIRST_PROMPT = "tell me something slowly"--STEERING_ROW = f"Steering: {STEERING_PROMPT}"-FOLLOW_UP_ROW = f"Follow-up: {FOLLOW_UP_PROMPT}"-EDITED_ROW = f"Steering: {EDITED_PROMPT}"-HINT_ROW = "to browse and edit queued messages"-# The browse header is the only surface that quotes the affordances ("enter-# steers"); the strip hint row only says "browse and edit".-HEADER_MARK = "enter steers"--# Turn 1 streams long enough (600 tokens at 6 tokens/s) to cover the whole-# edit flow; the remaining queue delivers at the boundary afterwards.-QUEUE_EDIT_FAUX_SCRIPT = {- "engine": "faux",- "modelId": vp.TS_SCRIPT_MODEL,- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 6,- "responses": [- {- "content": [- {- "type": "text",- "text": "The first turn streams slowly for a very long time so the parked queue has plenty of time to be browsed and edited before this turn settles and the queue drains. " * 8,- }- ]- },- {"content": [{"type": "text", "text": "steering delivered"}]},- {"content": [{"type": "text", "text": "follow-up delivered"}]},- ],-}--# The meta-wrapped byte forms macOS Terminal sends with "use option as-# meta key" (TS matchesKey's double-ESC branch): Option+Up/Down wrap the-# whole arrow sequence in an extra ESC.-WRAPPED_UP = "\x1b\x1b[A"-WRAPPED_DOWN = "\x1b\x1b[B"---def default_ts_binary():- """The ts side's launch command: the TS-main CLI from the parity- ground-truth checkout, resolved absolutely. Two rules drive this:-- - the box PATH `prime-agent` may itself be the Rust dogfood install- (and the tmux SERVER resolves pane commands through its own PATH),- so the harness never launches a bare `prime-agent`;- - the DEPLOYED 0.9.5 release binary predates TS matchesKey's- double-ESC branch (observed: the wrapped form opens the session- tree via the escape-repeat and types the `[A` tail literally), so- the wrapped-byte flow must be compared against TS-main.-- PA_TS_BINARY overrides (an absolute path or a full command string).- """- override = os.environ.get("PA_TS_BINARY")- if override:- return override- ts_main_cli = os.path.join(- "/home/ubuntu/prime-agent", "packages", "coding-agent", "dist", "bundle", "cli.js"- )- if os.path.exists(ts_main_cli):- return f"node {ts_main_cli}"- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- candidates = sorted(glob.glob(os.path.join(releases, "0.9.5-linux-x64-*", "prime-agent")))- if not candidates:- raise SystemExit("neither the TS-main checkout nor a deployed TS release found; set PA_TS_BINARY")- return candidates[-1]---def send_wrapped(session, sequence):- """One literal write of the wrapped byte form (one terminal write, so- the app's reader folds it exactly like macOS Terminal sends it)."""- vp.tmux("send-keys", "-t", session, "-l", sequence)---def prepare_edit_sandbox(base):- """The visual_parity fixture with the queue-edit faux script (a long- slow first turn so the parked queue survives the whole edit flow)."""- shared_cwd, _, sandboxes = vp.prepare_sandbox(base)- script_path = os.path.join(base, "queue-edit-faux-script.json")- with open(script_path, "w") as f:- json.dump(QUEUE_EDIT_FAUX_SCRIPT, f, indent=2)- return shared_cwd, script_path, sandboxes---def settle(session, samples=2, gap=0.4):- """Wait until two captures agree (the attach chrome settles before any- typed key dispatches on a transcript the attach rebuilds)."""- last = vp.capture(session)- stable = 0- for _ in range(120):- time.sleep(gap)- current = vp.capture(session)- if current == last:- stable += 1- if stable >= samples:- return- else:- stable = 0- last = current- raise RuntimeError("the pane never settled after attach")---def send_up(session, key_form):- """One Option+Up press in the given byte form."""- if key_form == "wrapped":- send_wrapped(session, WRAPPED_UP)- else:- vp.tmux("send-keys", "-t", session, "M-Up")---def send_down(session, key_form):- """One Option+Down press in the given byte form."""- if key_form == "wrapped":- send_wrapped(session, WRAPPED_DOWN)- else:- vp.tmux("send-keys", "-t", session, "M-Down")---def run_edit_session(binary, sandbox, shared_cwd, script_path, size, out_dir, prefix, key_form):- """Drive one binary through the queue-edit states with one key byte- form; the capture names carry the form so the two Rust runs compare."""- width, height = size- session = f"vplane-{binary}-qedit-{width}x{height}"- vp.tmux("kill-session", "-t", session, check=False)- vp.tmux("new-session", "-d", "-s", session, "-x", str(width), "-y", str(height), "-c", shared_cwd)- env = (- f"HOME={sandbox['home']} "- f"TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"PRIME_AGENT_FAUX_SCRIPT={script_path} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- if binary == "ts":- command = (- f"{default_ts_binary()} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {vp.TS_SCRIPT_MODEL}"- )- else:- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)), "..", "target", "debug", "prime-agent"- ),- )- package_dir = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- command = (- f"PI_PACKAGE_DIR={package_dir} "- f"{rust} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {vp.TS_SCRIPT_MODEL}"- )- vp.tmux("send-keys", "-t", session, f"{env} {command}", "Enter")- # Mode-neutral boot marker: TS-main opens in Details mode, the Rust- # build (and the deployed 0.9.5 release) in Collapsed mode.- try:- vp.wait_for(session, "mode (Ctrl+O to expand)", timeout=90)- except TimeoutError:- print(f"[{binary}] boot timeout; pane contents:")- print(vp.capture(session))- vp.tmux("kill-session", "-t", session, check=False)- raise- settle(session)-- # The slow turn streams; park one steering prompt and one follow-up.- vp.tmux("send-keys", "-t", session, FIRST_PROMPT)- vp.tmux("send-keys", "-t", session, "Enter")- vp.wait_for(session, "streams slowly", timeout=60)- vp.tmux("send-keys", "-t", session, STEERING_PROMPT)- vp.tmux("send-keys", "-t", session, "Enter")- vp.tmux("send-keys", "-t", session, FOLLOW_UP_PROMPT)- vp.tmux("send-keys", "-t", session, "M-Enter")- qp_wait_plain(session, FOLLOW_UP_ROW, timeout=30)- qp_wait_plain(session, STEERING_ROW, timeout=15)-- # A visible draft: the stash/restore shows through every state.- vp.tmux("send-keys", "-t", session, "-l", DRAFT)- time.sleep(0.5)-- frames = {}-- # (b1) select: alt+up picks the newest parked message (the follow-up);- # its text loads into the editor, the header appears.- send_up(session, key_form)- qp_wait_plain(session, "follow-up 1", timeout=15)- time.sleep(0.5)- frames[f"b1_select_{key_form}"] = vp.capture(session)-- # (b2) edit + re-queue: append " edited" and Enter - the replace moves- # the item onto the steering lane (TS `enter steers`), the header- # clears and the stashed draft restores.- vp.tmux("send-keys", "-t", session, "-l", " edited")- vp.tmux("send-keys", "-t", session, "Enter")- qp_wait_plain(session, EDITED_ROW, timeout=15)- qp_wait_plain(session, HEADER_MARK, gone=True, timeout=15)- time.sleep(0.5)- frames[f"b2_requeued_{key_form}"] = vp.capture(session)-- # (b3) cancel: alt+up selects the newest (the edited item, "steering- # 2"), alt+down walks past it back to the draft.- send_up(session, key_form)- qp_wait_plain(session, "steering 2", timeout=15)- send_down(session, key_form)- qp_wait_plain(session, HEADER_MARK, gone=True, timeout=15)- time.sleep(0.5)- frames[f"b3_cancel_{key_form}"] = vp.capture(session)-- # (b4) empty deletes: select the edited item, backspace it empty, Enter- # - the delete mutation drops the row and the draft restores.- send_up(session, key_form)- qp_wait_plain(session, "steering 2", timeout=15)- for _ in range(len(EDITED_PROMPT)):- vp.tmux("send-keys", "-t", session, "Bspace")- vp.tmux("send-keys", "-t", session, "Enter")- qp_wait_plain(session, EDITED_ROW, gone=True, timeout=15)- qp_wait_plain(session, HEADER_MARK, gone=True, timeout=15)- time.sleep(0.5)- frames[f"b4_delete_{key_form}"] = vp.capture(session)-- # Exit: ctrl+c aborts the settled run, a second press exits.- vp.tmux("send-keys", "-t", session, "C-c")- time.sleep(0.5)- vp.tmux("send-keys", "-t", session, "C-c")- time.sleep(1.0)- vp.tmux("kill-session", "-t", session, check=False)-- os.makedirs(out_dir, exist_ok=True)- for state, frame in frames.items():- with open(os.path.join(out_dir, f"{binary}-{state}-{width}x{height}.txt"), "w") as f:- f.write(frame)- return frames---def qp_wait_plain(session, needle, timeout=30, gone=False):- qp.wait_plain(session, needle, timeout=timeout, gone=gone)---def state_rows(frame, markers):- """The rows of one frame containing any marker, ANSI bytes intact."""- return qp.styled_rows(frame, markers)---def require_absent(frame, text, state):- if text in qp.strip_ansi(frame):- raise RuntimeError(f"scenario drift in {state}: {text!r} still on screen")---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--size", default="120x36")- parser.add_argument("--keep", action="store_true")- parser.add_argument("--out", default=None)- parser.add_argument("--only", default=None, choices=("ts", "rust"))- parser.add_argument("--key-form", default="param", choices=("param", "wrapped"))- parser.add_argument("--session-prefix", default="vp")- args = parser.parse_args()- width, height = args.size.split("x")- size = (str(width), str(height))-- if args.only in (None, "ts"):- # The TS-main CLI prints `--version` on stderr; merge it so the- # guard's stdout probe sees it (the pane command stays clean).- ts_identity.assert_ts_side_is_the_ts_product(ts_bin=f"{default_ts_binary()} 2>&1")-- # Short base path: the daemon's worker socket lives under- # `$TMPDIR/prime-agent-1000/worker-<id>.sock` and AF_UNIX paths cap at- # 108 bytes — the default descriptive prefix pushed the worker path- # past it (the worker dies with `listen EINVAL`).- base = tempfile.mkdtemp(prefix="qe-", dir="/tmp")- out_dir = args.out or tempfile.mkdtemp(prefix="queue-edit-captures-")- shared_cwd, script_path, sandboxes = prepare_edit_sandbox(base)- STATES = ("b1_select", "b2_requeued", "b3_cancel", "b4_delete")- try:- if args.only:- run_edit_session(- args.only, sandboxes[args.only], shared_cwd, script_path, size, out_dir,- args.session_prefix, args.key_form,- )- print(f"captures for {args.only} in {out_dir}")- return 0- # The flow parity: both products driven with the parameter form.- ts_frames = run_edit_session(- "ts", sandboxes["ts"], shared_cwd, script_path, size, out_dir, args.session_prefix, "param"- )- rust_frames = run_edit_session(- "rust", sandboxes["rust"], shared_cwd, script_path, size, out_dir, args.session_prefix, "param"- )- # The wrapped repair: the Rust build driven with the meta-wrapped- # bytes must reach the same states (TS-main pins the identity in- # keys.test.ts; its live pipeline splits the bytes first — see the- # module docstring).- rust_wrapped = run_edit_session(- "rust", sandboxes["rust"], shared_cwd, script_path, size, out_dir, args.session_prefix, "wrapped"- )- # Scenario guards: the TS captures must show the state under test- # (a too-late capture after delivery would compare empty rows).- qp.require_markers(- ts_frames["b1_select_param"],- ["follow-up 1", FOLLOW_UP_ROW, STEERING_ROW],- "b1_select_param (ts)",- )- qp.require_markers(- ts_frames["b2_requeued_param"], [EDITED_ROW, STEERING_ROW, DRAFT], "b2_requeued_param (ts)"- )- qp.require_markers(ts_frames["b3_cancel_param"], [DRAFT, STEERING_ROW], "b3_cancel_param (ts)")- require_absent(ts_frames["b4_delete_param"], EDITED_PROMPT, "b4_delete_param (ts)")- require_absent(rust_frames["b4_delete_param"], EDITED_PROMPT, "b4_delete_param (rust)")- require_absent(rust_wrapped["b4_delete_wrapped"], EDITED_PROMPT, "b4_delete_wrapped (rust)")-- failures = []- strip_markers = ("Steering: ", "Follow-up: ", HINT_ROW, HEADER_MARK, DRAFT, FOLLOW_UP_PROMPT)- for state in STATES:- name = f"{state}-{args.size}"- ts_rows = state_rows(ts_frames[f"{state}_param"], strip_markers)- rust_rows = state_rows(rust_frames[f"{state}_param"], strip_markers)- if ts_rows == rust_rows:- print(f"PASS {name}: {len(ts_rows)} row(s) match (ts vs rust)")- for row in ts_rows:- print(f" | {qp.strip_ansi(row)}")- else:- print(f"FAIL {name} (ts vs rust)")- print(- "\n".join(- difflib.unified_diff(- [qp.strip_ansi(r) for r in ts_rows],- [qp.strip_ansi(r) for r in rust_rows],- fromfile="ts", tofile="rust", lineterm="", n=1,- )- )- )- failures.append(name)- # The wrapped form reaches the same states as the parameter form.- wrapped_rows = state_rows(rust_wrapped[f"{state}_wrapped"], strip_markers)- if wrapped_rows == rust_rows:- print(f"PASS {name}: wrapped == parameter form ({len(rust_rows)} row(s))")- else:- print(f"FAIL {name} (rust wrapped vs parameter)")- print(- "\n".join(- difflib.unified_diff(- [qp.strip_ansi(r) for r in rust_rows],- [qp.strip_ansi(r) for r in wrapped_rows],- fromfile="rust-param", tofile="rust-wrapped", lineterm="", n=1,- )- )- )- failures.append(f"{name} wrapped")- if any(failures):- failed = [f for f in failures if f]- print(f"{len(failed)} state(s) differ; captures in {out_dir}")- return 1- print(f"all queue-edit states match; captures in {out_dir}")- return 0- finally:- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if not args.keep:- shutil.rmtree(base, ignore_errors=True)---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/queue_parity.py b/scripts/queue_parity.pydeleted file mode 100644index f02c23d0be..0000000000--- a/scripts/queue_parity.py+++ /dev/null@@ -1,700 +0,0 @@-#!/usr/bin/env python3-"""Prompt-surface parity: frame-diff the queued-prompt strip and the live-editor highlight against the installed TS prime-agent binary in tmux.--Drives both binaries to the same defined states and compares what the user-sees:--- the queued strip behind a slow running turn — one steering prompt (Enter)- and one follow-up prompt (alt+enter), drained after delivery — with the- strip rows compared ANSI byte-exact (the TS prompt-highlight styling: dim- previews, accent on a leading slash command's `/name` segment,- success/mdLink on @path/--flag tokens);-- a second parked lane with slash-command and token-bearing prompts, so the- accent styling itself is compared byte-exact (captured before delivery,- aborted away after);-- the streaming follow-up hint (TS `getTrayOverrideLabel`'s streaming- arm): while the slow turn streams and a draft sits in the editor, the- tray row reads `<followUp> to queue message` — compared ANSI- byte-exact, and its departure with the cleared draft is asserted;-- the live editor with a slash command and argument tokens typed but not- submitted — cursor at the end (command segment accented, tokens colored)- and cursor moved inside the command token (accent suppressed), the- editor's text row compared byte-exact;-- the transcript prompt-highlight surfaces (TS `PromptTokenMask` +- `SlashCommandMessageComponent`): a token-bearing user-message row (the- `success`/`mdLink` token colors inside the `userMessageText` body on the- `userMessageBg` block), a session-command echo row (accent `/name`,- default-fg rest, same block), and a command-bearing user row (`/hotkeys`- echoed as a user message with its whole command segment in accent).--The command-bearing user row runs in its own tmux session at 120x130: the-`/hotkeys` guide rendered under it (markdown tables, one border row per-table row) is taller than the 120x36 viewport, so the user block would-scroll off a 36-row capture (the row bytes are width-bound, and the width-stays 120). Everything else runs at the default size.--Exit code is non-zero when any state's visible rows differ.--Reuses the visual_parity faux-provider harness (tmux rules: default socket,-vplane-* session names, sessions killed individually).-"""--import argparse-import difflib-import json-import os-import re-import shutil-import sys-import tempfile-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-import visual_parity as vp--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--# Turn 1/4 stream slowly (6 tokens/s) so the window stays open for the-# parked submissions; turns 2/3 answer the queued prompts.-QUEUE_FAUX_SCRIPT = {- "engine": "faux",- "modelId": vp.TS_SCRIPT_MODEL,- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 3,- "responses": [- # The token-user-row turn answers quickly so the transcript state- # settles; the queue turns follow (the first of them streams- # slowly).- {"content": [{"type": "text", "text": "token user row delivered"}]},- {- "content": [- {- "type": "text",- # Long enough that the streaming-hint state AND the- # parked strip both fit inside the turn at the faux's- # 3 tokens/second (the hint capture + clear, then the- # two parked prompts, all before the settle).- "text": "The first turn streams slowly and keeps going for a good long while, "- "certainly long enough that the streaming follow-up hint can be captured over "- "a draft while the turn is still live, and then the parked preview strip has "- "plenty of time to render with both of its rows before this turn finally "- "settles and the queue drains the parked prompts as their own turns.",- }- ]- },- {"content": [{"type": "text", "text": "steering delivered"}]},- {"content": [{"type": "text", "text": "follow-up delivered"}]},- {- "content": [- {- "type": "text",- "text": "The second turn streams even more slowly and keeps going for a while so the parked slash command strip has plenty of time to render before the turn settles and the queue drains.",- }- ]- },- ],-}--FIRST_PROMPT = "tell me something slowly"-STEERING_PROMPT = "steering prompt text"-FOLLOW_UP_PROMPT = "follow-up prompt text"-SECOND_PROMPT = "tell me something slowly again"--# The editor states type a recognized argument-taking command with both-# argument-token forms. The parked slash prompts are session commands-# (`/compact`, `/goal`): client commands execute immediately instead of-# parking, while session commands queue behind the running turn and render-# in the accent-styled strip — captured before delivery and aborted away.-EDITOR_COMMAND = "/new @docs/plan.md --draft"-SLASH_STEERING_PROMPTS = [- "/compact focus the summary on tests",- "/goal finish the port @docs/plan.md --verbose",- "fix @Cargo.toml --quiet now",-]--# Transcript prompt-highlight states (TS `PromptTokenMask` on user rows,-# `SlashCommandMessageComponent` for the echo): a plain prompt carrying-# @path/--flag tokens (user row, byte-exact), the same session command the-# parked lane types (durable echo row, byte-exact — the fresh session skips-# compaction with the TS warning row), and the /hotkeys client command-# (command-bearing user row, byte-exact, own 120x80 session).-USER_TOKEN_PROMPT = "fix @Cargo.toml --quiet now"-TOKEN_TURN_RESPONSE = "token user row delivered"-ECHO_COMMAND = "/compact focus the summary on tests"-HOTKEYS_COMMAND = "/hotkeys"-HOTKEYS_SIZE = (120, 130)--# Strip rows both binaries must render (the visible queue surface).-STEERING_ROW = f"Steering: {STEERING_PROMPT}"-FOLLOW_UP_ROW = f"Follow-up: {FOLLOW_UP_PROMPT}"-HINT_ROW = "to browse and edit queued messages"--# The streaming follow-up hint (TS `getTrayOverrideLabel`): while a turn-# streams and a draft sits in the editor, the tray's location label is-# replaced by `<followUp> to queue message` (the default binding on this-# platform is alt+enter on both binaries).-HINT_DRAFT = "draft not sent yet"-STREAMING_HINT_ROW = "Alt+Enter to queue message"--ANSI_PATTERN = re.compile("\x1b\\[[0-9;]*[A-Za-z]")---def strip_ansi(text):- return ANSI_PATTERN.sub("", text)---def normalize_sgr_boundaries(frame):- """Canonicalize tmux's row-boundary reset placement (the same rules- visual_parity applies before its byte-diffs): the trailing fg/bg reset- attaches to the end of the styled row or the start of the next one- depending on timing, and both describe identical cells."""- frame = re.sub("\x1b\\[39m\n", "\n", frame)- frame = re.sub("\n\x1b\\[39m(?= )", "\n", frame)- frame = re.sub("\x1b\\[49m\n", "\n", frame)- frame = re.sub("\n\x1b\\[49m(?= )", "\n", frame)- return frame---def strip_rows(frame):- """The queue-strip rows of one frame, ANSI-stripped, in render order."""- return [- line.strip()- for line in strip_ansi(frame).split("\n")- if any(marker in line for marker in ("Steering: ", "Follow-up: ", HINT_ROW))- ]---def styled_rows(frame, markers):- """The rows of one frame containing any marker, ANSI bytes intact."""- frame = normalize_sgr_boundaries(frame)- return [- line- for line in frame.split("\n")- if any(marker in strip_ansi(line) for marker in markers)- ]---def strip_rows_styled(frame):- """The queue-strip rows with their ANSI styling, for byte-exact compare."""- return styled_rows(- frame, ("Steering: ", "Follow-up: ", HINT_ROW)- )---def editor_rows_styled(frame):- """The editor's typed-text row with its ANSI styling, for byte-exact- compare (the prompt dock row holding the command)."""- return styled_rows(frame, ("@docs/plan.md",))---def exact_rows_styled(frame, text):- """The transcript rows whose ANSI-stripped text equals `text`, ANSI- bytes intact, for byte-exact compare (the user block's content row and- the session-command echo row)."""- frame = normalize_sgr_boundaries(frame)- return [- line- for line in frame.split("\n")- if strip_ansi(line).strip() == text- ]---def styled_segment(line, text):- """The ANSI bytes of `line` that render exactly `text` (the styled- segment), so a row that carries side-varying content past the segment- (the tray row's context label: token counts differ per side) still- compares byte-exact over the segment under test."""- import re as _re-- plain = strip_ansi(line)- start = plain.find(text)- if start < 0:- return None- end = start + len(text)- out = []- plain_pos = 0- i = 0- while i < len(line):- if line[i] == "\x1b":- match = _re.match(r"\x1b\[[0-9;]*[A-Za-z]", line[i:])- sequence = match.group(0) if match else line[i]- # An escape strictly inside the segment (a color change mid-- # segment) belongs to it — the WHOLE sequence, so the byte-- # exact compare sees real styling; the one AT the segment's- # end starts the next span (the context label) and stays out.- if start <= plain_pos < end:- out.append(sequence)- i += len(sequence)- continue- if start <= plain_pos < end:- out.append(line[i])- plain_pos += 1- i += 1- return "".join(out)---def tray_segment_rows(frame, text):- """The styled tray segments (rows containing `text`) for byte-exact- compare: the hint row's own bytes, never the context label beside it."""- frame = normalize_sgr_boundaries(frame)- segments = []- for line in frame.split("\n"):- if text in strip_ansi(line):- segment = styled_segment(line, text)- if segment is not None:- segments.append(segment)- return segments---def prepare_queue_sandbox(base):- """The visual_parity fixture with the queue-specific faux script."""- shared_cwd, script_path, sandboxes = vp.prepare_sandbox(base)- script_path = os.path.join(base, "queue-faux-script.json")- with open(script_path, "w") as f:- json.dump(QUEUE_FAUX_SCRIPT, f, indent=2)- return shared_cwd, script_path, sandboxes---def wait_plain(session, needle, timeout=30, gone=False):- """Poll the pane's ANSI-stripped text until `needle` appears (or is gone)."""- deadline = time.time() + timeout- while time.time() < deadline:- plain = strip_ansi(vp.capture(session))- if (needle not in plain) == gone:- return- time.sleep(0.3)- raise RuntimeError(- f"timed out waiting for {needle!r} to {'vanish' if gone else 'appear'}"- )---def run_queue_session(binary, sandbox, shared_cwd, script_path, size, out_dir, prefix):- """Drive one binary through the queue/editor states, capturing each frame."""- width, height = size- session = f"vplane-{prefix}-queue-{binary}-{width}x{height}"- vp.tmux("kill-session", "-t", session, check=False)- vp.tmux("new-session", "-d", "-s", session, "-x", width, "-y", height, "-c", shared_cwd)- env = (- f"HOME={sandbox['home']} "- f"TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"PRIME_AGENT_FAUX_SCRIPT={script_path} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- if binary == "ts":- # The tmux server's inherited PATH may sit a Rust build at- # `prime-agent` (the box's release install): resolve the binary- # in THIS process's PATH (the operator points it at the TS- # release for the run) and launch the absolute path.- ts_bin = shutil.which("prime-agent") or "prime-agent"- command = (- f"{ts_bin} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {vp.TS_SCRIPT_MODEL}"- )- else:- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)), "..", "target", "debug", "prime-agent"- ),- )- package_dir = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- command = (- f"PI_PACKAGE_DIR={package_dir} "- f"{rust} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {vp.TS_SCRIPT_MODEL}"- )- vp.tmux("send-keys", "-t", session, f"{env} {command}", "Enter")-- frames = {}- # (a) fresh start.- vp.wait_for(session, "Collapsed mode", timeout=60)- # (u) the token-bearing user row: a plain prompt with @path/--flag- # tokens submitted while idle renders the TS `PromptTokenMask` colors- # inside the user block; the faux turn settles so the frame is stable.- vp.tmux("send-keys", "-t", session, USER_TOKEN_PROMPT)- vp.tmux("send-keys", "-t", session, "Enter")- vp.wait_for(session, TOKEN_TURN_RESPONSE, timeout=60)- time.sleep(0.5)- frames["u_token_user_row"] = vp.capture(session)- # (s) the session-command echo row: the same command the parked lane- # types, submitted while idle. The fresh session skips compaction (the- # durable TS warning row), and the durable echo row stays on screen —- # accent `/compact`, default-fg rest, on the user-message block.- vp.tmux("send-keys", "-t", session, ECHO_COMMAND)- vp.tmux("send-keys", "-t", session, "Enter")- wait_plain(session, "too short to compact", timeout=60)- time.sleep(0.5)- frames["s_slash_echo_row"] = vp.capture(session)- # (e1) the editor highlight: type a slash command with argument tokens- # without submitting, close the autocomplete, capture the editor row.- vp.tmux("send-keys", "-t", session, EDITOR_COMMAND)- wait_plain(session, "@docs/plan.md")- vp.tmux("send-keys", "-t", session, "Escape")- time.sleep(1.0)- frames["e_editor_slash"] = vp.capture(session)- # (e2) the cursor inside the command token suppresses its accent; the- # argument tokens stay colored.- for _ in range(len(EDITOR_COMMAND) - 2):- vp.tmux("send-keys", "-t", session, "Left")- time.sleep(1.0)- frames["e_editor_cursor_in_command"] = vp.capture(session)- # Clear the editor (TS escape-repeat: two presses clear the input).- vp.tmux("send-keys", "-t", session, "Escape")- time.sleep(0.4)- vp.tmux("send-keys", "-t", session, "Escape")- wait_plain(session, "@docs/plan.md", gone=True, timeout=15)-- # (q) the queue strip: submit the slow first turn, wait until it streams,- # then park one steering prompt (Enter) and one follow-up prompt- # (alt+enter) behind it.- vp.tmux("send-keys", "-t", session, FIRST_PROMPT)- vp.tmux("send-keys", "-t", session, "Enter")- vp.wait_for(session, "streams slowly", timeout=60)-- # (h) the streaming follow-up hint (TS `getTrayOverrideLabel`): early- # in the slow turn, type a draft without submitting — the tray row- # becomes `<followUp> to queue message`. Captured before the parking- # below (the parked prompts ride the same turn; the cleared draft- # leaves the editor exactly as the parking expects).- vp.tmux("send-keys", "-t", session, HINT_DRAFT)- try:- vp.wait_for(session, STREAMING_HINT_ROW, timeout=15)- except TimeoutError:- # Failure evidence: the pane at the miss, so the diff between the- # rendered tray and the expected row is visible post-run.- dump = vp.capture(session, escape=False)- os.makedirs(out_dir, exist_ok=True)- with open(os.path.join(out_dir, f"{binary}-h-miss-plain.txt"), "w") as f:- f.write(dump)- raise- time.sleep(0.3)- frames["h_streaming_hint"] = vp.capture(session)- # Clear the draft with backspaces: the escape-repeat pair is the TS- # streaming-turn surface (the double press aborts the turn and opens- # the session tree mid-run), never a plain input clear.- for _ in range(len(HINT_DRAFT) + 2):- vp.tmux("send-keys", "-t", session, "BSpace")- wait_plain(session, HINT_DRAFT, gone=True, timeout=15)- wait_plain(session, STREAMING_HINT_ROW, gone=True, timeout=15)-- vp.tmux("send-keys", "-t", session, STEERING_PROMPT)- vp.tmux("send-keys", "-t", session, "Enter")- vp.tmux("send-keys", "-t", session, FOLLOW_UP_PROMPT)- vp.tmux("send-keys", "-t", session, "M-Enter")- try:- vp.wait_for(session, HINT_ROW, timeout=30)- vp.wait_for(session, STEERING_ROW, timeout=15)- except TimeoutError:- os.makedirs(out_dir, exist_ok=True)- with open(os.path.join(out_dir, f"{binary}-strip-miss-plain.txt"), "w") as f:- f.write(vp.capture(session, escape=False))- raise- vp.wait_for(session, FOLLOW_UP_ROW, timeout=15)- time.sleep(0.3)- frames["q_queue_strip"] = vp.capture(session)-- # (b) the browse state: alt+up selects the newest parked message (the- # follow-up) and shows the dim browse header.- vp.tmux("send-keys", "-t", session, "M-Up")- vp.wait_for(session, "browse", timeout=15)- frames["q_browse_header"] = vp.capture(session)- vp.tmux("send-keys", "-t", session, "M-Down")- time.sleep(1.0)-- # (c) drained: both queued prompts delivered, strip cleared.- vp.wait_for(session, "steering delivered", timeout=120)- vp.wait_for(session, "follow-up delivered", timeout=120)- for _ in range(200):- pane = vp.capture(session, escape=False)- if HINT_ROW not in pane:- break- time.sleep(0.3)- frames["q_drained"] = vp.capture(session)-- # (s) the slash-command strip: a second slow turn, with slash-command and- # token-bearing prompts parked behind it; captured before delivery.- vp.tmux("send-keys", "-t", session, SECOND_PROMPT)- vp.tmux("send-keys", "-t", session, "Enter")- vp.wait_for(session, "even more slowly", timeout=60)- for prompt in SLASH_STEERING_PROMPTS:- vp.tmux("send-keys", "-t", session, prompt)- vp.tmux("send-keys", "-t", session, "Enter")- # The accent styling splits the row mid-text, so wait on the- # ANSI-stripped pane.- for prompt in SLASH_STEERING_PROMPTS:- wait_plain(session, f"Steering: {prompt}")- time.sleep(0.3)- frames["q_slash_strip"] = vp.capture(session)-- # Exit: ctrl+c aborts the settled run, a second press exits.- vp.tmux("send-keys", "-t", session, "C-c")- time.sleep(0.5)- vp.tmux("send-keys", "-t", session, "C-c")- time.sleep(1.0)- vp.tmux("kill-session", "-t", session, check=False)-- os.makedirs(out_dir, exist_ok=True)- for state, frame in frames.items():- with open(os.path.join(out_dir, f"{binary}-{state}-{width}x{height}.txt"), "w") as f:- f.write(frame)- return frames---def run_hotkeys_session(binary, sandbox, shared_cwd, script_path, out_dir, prefix):- """The command-bearing user row (`/hotkeys` echoed as a user message- block, TS `echoLocalCommand` + `PromptTokenMask`): its own session at- 120x80 — the guide rendered under the row is taller than the 36-row- viewport, and the row's bytes are width-bound (width stays 120)."""- width, height = HOTKEYS_SIZE- session = f"vplane-{prefix}-hotkeys-{binary}-{width}x{height}"- vp.tmux("kill-session", "-t", session, check=False)- vp.tmux(- "new-session", "-d", "-s", session, "-x", str(width), "-y", str(height), "-c", shared_cwd- )- env = (- f"HOME={sandbox['home']} "- f"TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"PRIME_AGENT_FAUX_SCRIPT={script_path} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- if binary == "ts":- # (See the queue session above: resolve the TS binary in this- # process's PATH — the tmux server's inherited PATH may sit a- # Rust build at `prime-agent`.)- ts_bin = shutil.which("prime-agent") or "prime-agent"- command = (- f"{ts_bin} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {vp.TS_SCRIPT_MODEL}"- )- else:- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)), "..", "target", "debug", "prime-agent"- ),- )- package_dir = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- command = (- f"PI_PACKAGE_DIR={package_dir} "- f"{rust} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {vp.TS_SCRIPT_MODEL}"- )- vp.tmux("send-keys", "-t", session, f"{env} {command}", "Enter")- vp.wait_for(session, "Collapsed mode", timeout=60)- vp.tmux("send-keys", "-t", session, HOTKEYS_COMMAND)- vp.tmux("send-keys", "-t", session, "Enter")- # The guide under the row proves the user block settled.- wait_plain(session, "Navigation", timeout=30)- time.sleep(0.5)- frame = vp.capture(session)- vp.tmux("send-keys", "-t", session, "C-c")- time.sleep(0.5)- vp.tmux("send-keys", "-t", session, "C-c")- time.sleep(1.0)- vp.tmux("kill-session", "-t", session, check=False)- os.makedirs(out_dir, exist_ok=True)- with open(- os.path.join(out_dir, f"{binary}-u_command_user_row-{width}x{height}.txt"), "w"- ) as f:- f.write(frame)- return {"u_command_user_row": frame}---def require_markers(frame, markers, state):- """Scenario guard: every expected row must be on screen when captured,- so a too-late capture (delivered before the frame) cannot false-pass."""- plain = strip_ansi(frame)- missing = [marker for marker in markers if marker not in plain]- if missing:- raise RuntimeError(- f"scenario drift in {state}: expected rows not on screen: {missing}"- )---def compare(name, ts_rows, rust_rows):- if ts_rows == rust_rows:- print(f"PASS {name}: {len(ts_rows)} row(s) match")- for row in ts_rows:- print(f" | {row}")- return None- print(f"FAIL {name}")- print(- "\n".join(- difflib.unified_diff(- [str(r) for r in ts_rows], [str(r) for r in rust_rows],- fromfile="ts", tofile="rust", lineterm="", n=1,- )- )- )- return name---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--size", default="120x36")- parser.add_argument("--keep", action="store_true")- parser.add_argument("--out", default=None)- parser.add_argument("--only", default=None, choices=("ts", "rust"))- parser.add_argument("--session-prefix", default="vp")- args = parser.parse_args()- width, height = args.size.split("x")- size = (width, height)-- # Fail fast before any launch: a non-TS `prime-agent` on PATH plays a- # Rust build as the "ts" side and reports false divergences.- if args.only in (None, "ts"):- ts_identity.assert_ts_side_is_the_ts_product()-- base = tempfile.mkdtemp(prefix="queue-parity-sandbox-")- out_dir = args.out or tempfile.mkdtemp(prefix="queue-parity-captures-")- shared_cwd, script_path, sandboxes = prepare_queue_sandbox(base)- try:- if args.only:- run_queue_session(- args.only, sandboxes[args.only], shared_cwd, script_path, size, out_dir, args.session_prefix- )- print(f"captures for {args.only} in {out_dir}")- return 0- ts_frames = run_queue_session(- "ts", sandboxes["ts"], shared_cwd, script_path, size, out_dir, args.session_prefix- )- rust_frames = run_queue_session(- "rust", sandboxes["rust"], shared_cwd, script_path, size, out_dir, args.session_prefix- )- ts_hotkeys = run_hotkeys_session(- "ts", sandboxes["ts"], shared_cwd, script_path, out_dir, args.session_prefix- )- rust_hotkeys = run_hotkeys_session(- "rust", sandboxes["rust"], shared_cwd, script_path, out_dir, args.session_prefix- )- ts_frames.update(ts_hotkeys)- rust_frames.update(rust_hotkeys)- # Scenario guards: the strip states must show every parked row when- # captured (a frame after delivery would compare empty rows).- require_markers(- ts_frames["q_queue_strip"],- [STEERING_ROW, FOLLOW_UP_ROW, HINT_ROW],- "q_queue_strip (ts)",- )- require_markers(- ts_frames["q_slash_strip"],- [f"Steering: {prompt}" for prompt in SLASH_STEERING_PROMPTS] + [HINT_ROW],- "q_slash_strip (ts)",- )- require_markers(- ts_frames["h_streaming_hint"],- [STREAMING_HINT_ROW, HINT_DRAFT],- "h_streaming_hint (ts)",- )- require_markers(- rust_frames["h_streaming_hint"],- [STREAMING_HINT_ROW, HINT_DRAFT],- "h_streaming_hint (rust)",- )- # The transcript states must show their rows (an early capture or a- # scrolled-off block would compare empty rows).- for state, text in (- ("u_token_user_row", USER_TOKEN_PROMPT),- ("s_slash_echo_row", ECHO_COMMAND),- ("u_command_user_row", HOTKEYS_COMMAND),- ):- require_markers(ts_frames[state], [text], f"{state} (ts)")- require_markers(rust_frames[state], [text], f"{state} (rust)")- failures = []- # Strip rows compare ANSI byte-exact: the prompt-highlight styling- # (dim base, accent command segment, colored tokens) is the surface- # under test.- failures.append(- compare(- f"q_queue_strip-{args.size}",- strip_rows_styled(ts_frames["q_queue_strip"]),- strip_rows_styled(rust_frames["q_queue_strip"]),- )- )- failures.append(- compare(- f"q_slash_strip-{args.size}",- strip_rows_styled(ts_frames["q_slash_strip"]),- strip_rows_styled(rust_frames["q_slash_strip"]),- )- )- # The transcript rows compare ANSI byte-exact: the TS PromptTokenMask- # styling (accent command segment, success/mdLink tokens inside the- # userMessageText body) and the echo row's accent command segment- # are the surfaces under test.- for state, text in (- ("u_token_user_row", USER_TOKEN_PROMPT),- ("s_slash_echo_row", ECHO_COMMAND),- ("u_command_user_row", HOTKEYS_COMMAND),- ):- failures.append(- compare(- f"{state}-{args.size}",- exact_rows_styled(ts_frames[state], text),- exact_rows_styled(rust_frames[state], text),- )- )- # The editor's typed-text row compares byte-exact in both cursor- # positions.- for state in ("e_editor_slash", "e_editor_cursor_in_command"):- failures.append(- compare(- f"{state}-{args.size}",- editor_rows_styled(ts_frames[state]),- editor_rows_styled(rust_frames[state]),- )- )- # The streaming follow-up hint row compares ANSI byte-exact over- # the hint segment (the tray override label — muted key +- # description, TS `getTrayOverrideLabel` -> `renderInfoLine`);- # the row's right side (the context label) carries per-side token- # counts and is not the surface under test.- failures.append(- compare(- f"h_streaming_hint-{args.size}",- tray_segment_rows(ts_frames["h_streaming_hint"], STREAMING_HINT_ROW),- tray_segment_rows(rust_frames["h_streaming_hint"], STREAMING_HINT_ROW),- )- )- # The browse header and drained strip keep the plain-row compare.- for state in ("q_browse_header", "q_drained"):- name = f"{state}-{args.size}"- ts_rows = strip_rows(ts_frames[state])- rust_rows = strip_rows(rust_frames[state])- if ts_rows == rust_rows:- print(f"PASS {name}: {len(ts_rows)} strip row(s) match")- else:- print(f"FAIL {name}")- print(- "\n".join(- difflib.unified_diff(- [str(r) for r in ts_rows], [str(r) for r in rust_rows],- fromfile="ts", tofile="rust", lineterm="", n=1,- )- )- )- failures.append(name)- if any(failures):- failed = [f for f in failures if f]- print(f"{len(failed)} state(s) differ; captures in {out_dir}")- return 1- print(f"all queue/editor states match; captures in {out_dir}")- return 0- finally:- # Rmtree alone leaks the scenario daemons (a killed TUI pane does- # not take its detached daemon/supervisor pair down; #223): sweep- # every daemon this run spawned before deleting the sandbox.- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if not args.keep:- shutil.rmtree(base, ignore_errors=True)---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/readoption_wake_repro.py b/scripts/readoption_wake_repro.pydeleted file mode 100644index 5fc82d8a42..0000000000--- a/scripts/readoption_wake_repro.py+++ /dev/null@@ -1,334 +0,0 @@-#!/usr/bin/env python3-"""Deterministic re-adoption wake repro (lane readoption-wake-path).--An ISOLATED daemon (agent dir + socket + kernel venv) hosts one session.-The session starts a detached background bash() watcher (a real kernel-cell), its turn settles (idle), the SUPERVISOR is killed -9 and relaunched-(adopting the still-live worker), and when the watcher process exits the-bash-completion notice must WAKE the session.--Usage: repro_readoption_wake.py <path-to-pa-daemon> <work-dir>-Prints WAKE_OK on the green path; on the red path prints the frozen-evidence (no bash-done row, kernel stderr's rejection) and exits 1.-"""-import json-import os-import signal-import socket-import subprocess-import sys-import threading-import time-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer-from pathlib import Path--DAEMON = sys.argv[1]-ROOT = Path(sys.argv[2])-AGENT_DIR = ROOT / "agent"-SOCK = ROOT / "daemon.sock"-SESSIONS = AGENT_DIR / "sessions"-KILL_MS = str(120 * 1000) # workers outlive the supervisor-lost window--MOCK_PORT = [None]-MOCK_REQUESTS = []-MOCK_LOCK = threading.Lock()---def sse(chunks):- payload = "".join(f"data: {c}\n\n" for c in chunks) + "data: [DONE]\n\n"- return (- "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n"- f"Connection: close\r\nContent-Length: {len(payload)}\r\n\r\n{payload}"- ).encode()---def chunk(delta, finish=None):- return json.dumps(- {- "id": "chatcmpl-wake",- "object": "chat.completion.chunk",- "created": 1750000000,- "model": "mock-1",- "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],- }- )---WATCHER_CODE = 'bash("sleep 12; echo RW_WAKE_DONE")\nprint("watcher armed")'-TOOL_CALL = json.dumps({"code": WATCHER_CODE})---class Mock(BaseHTTPRequestHandler):- def do_POST(self):- length = int(self.headers.get("content-length", 0))- body = self.rfile.read(length)- with MOCK_LOCK:- MOCK_REQUESTS.append(body.decode("utf-8", "replace"))- index = len(MOCK_REQUESTS) - 1- if index == 0:- data = sse(- [- chunk(- {- "role": "assistant",- "content": "",- "tool_calls": [- {- "index": 0,- "id": "call-wake-1",- "type": "function",- "function": {"name": "ipython", "arguments": TOOL_CALL},- }- ],- },- None,- ),- chunk({}, "tool_calls"),- ]- )- elif index == 1:- data = sse(- [- chunk({"role": "assistant", "content": "watcher started"}, None),- chunk({}, "stop"),- ]- )- else:- data = sse(- [- chunk({"role": "assistant", "content": "woken by the bash-done notice"}, None),- chunk({}, "stop"),- ]- )- self.wfile.write(data)-- def log_message(self, *args):- pass---def start_mock():- server = ThreadingHTTPServer(("127.0.0.1", 0), Mock)- threading.Thread(target=server.serve_forever, daemon=True).start()- return server.server_address[1]---class Wire:- def __init__(self, path):- self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- self.sock.connect(str(path))- self.buf = b""- hello = self.readline()- assert hello.get("type") == "daemon_hello", hello-- def readline(self):- while b"\n" not in self.buf:- data = self.sock.recv(65536)- if not data:- raise RuntimeError("daemon closed")- self.buf += data- line, self.buf = self.buf.split(b"\n", 1)- return json.loads(line)-- def request(self, command, rid, timeout=180.0):- envelope = {- "type": "command",- "id": rid,- "protocol": {"name": "prime-agent.daemon", "version": 7},- "command": command,- }- self.sock.sendall((json.dumps(envelope) + "\n").encode())- deadline = time.time() + timeout- while time.time() < deadline:- self.sock.settimeout(1.0)- try:- line = self.readline()- except (TimeoutError, socket.timeout):- continue- if line.get("id") == rid:- return line- raise TimeoutError(f"no response for {rid}")---def spawn_daemon():- env = dict(os.environ)- env.pop("PRIME_API_KEY", None)- env["PRIME_AGENT_CODING_AGENT_DIR"] = str(AGENT_DIR)- env["PRIME_AGENT_KERNEL_PYTHON"] = os.environ.get(- "RWP_KERNEL_PYTHON", str(ROOT.parent / "rwp-kernel-venv/bin/python")- )- env["PRIME_AGENT_INTERNAL_WORKER_SUPERVISOR_LOST_EXIT_MS"] = KILL_MS- proc = subprocess.Popen(- [DAEMON, "supervisor", "--socket", str(SOCK), "--agent-dir", str(AGENT_DIR)],- stdout=(ROOT / "supervisor.out").open("ab"),- stderr=(ROOT / "supervisor.err").open("ab"),- env=env,- start_new_session=True,- )- deadline = time.time() + 20- while time.time() < deadline:- if SOCK.exists():- return proc- if proc.poll() is not None:- raise RuntimeError(f"supervisor died at boot: rc={proc.returncode}")- time.sleep(0.05)- raise RuntimeError("supervisor socket never appeared")---def wait_for(predicate, timeout, what):- deadline = time.time() + timeout- while time.time() < deadline:- value = predicate()- if value:- return value- time.sleep(0.25)- raise TimeoutError(f"condition never became true: {what}")---def main():- # The work-dir must be disposable AND fresh: refuse an existing path- # (a caller pointing this at a real directory must never lose it).- if ROOT.exists():- raise RuntimeError(f"work-dir already exists: {ROOT} (use a fresh disposable path)")- ROOT.mkdir(parents=True)- for d in (AGENT_DIR, SESSIONS):- d.mkdir(parents=True)- port = start_mock()- (AGENT_DIR / "models.json").write_text(- json.dumps(- {- "providers": {- "prime-inference": {- "api": "openai-completions",- "baseUrl": f"http://127.0.0.1:{port}/v1",- "apiKey": "sk-wake",- "models": [- {- "id": "mock-1",- "name": "Mock 1",- "api": "openai-completions",- "contextWindow": 128000,- "maxTokens": 4096,- }- ],- }- }- }- )- )- supervisor = spawn_daemon()- client = Wire(SOCK)- created = client.request(- {- "type": "create",- "name": "wake-lane",- "config": {- "cwd": str(ROOT),- "sessionDir": str(SESSIONS),- "provider": "prime-inference",- "model": "mock-1",- },- },- "c1",- )- assert created["success"], created- active_id = created["data"].get("id") or created["data"]["activeSessionId"]- session_id = created["data"]["sessionId"]- session_file = SESSIONS / f"{session_id}.jsonl"- print(f"session: {session_id} active: {active_id}")-- started = client.request(- {"type": "prompt_and_wait", "activeSessionId": active_id, "message": "start the watcher and stop"},- "p1",- timeout=240,- )- assert started["success"], started- first = client.request({"type": "get_messages", "activeSessionId": active_id}, "gm0")- assert first["success"], first- assert "watcher started" in json.dumps(first["data"]), first- print("turn 1 settled; the detached watcher runs (sleep 12)")-- # The false-green guard: the watcher must still be RUNNING at the- # kill — a completion that already landed means the wake was not- # exercised across re-adoption (fail loudly instead of matching a- # pre-restart reply later).- prekill = client.request(- {"type": "get_messages", "activeSessionId": active_id}, "gm0b"- )- assert prekill.get("success"), prekill- assert "bash-done" not in json.dumps(prekill["data"]), (- "the watcher completed BEFORE the restart - the repro did not "- "exercise the re-adoption wake"- )-- # The supervisor dies hard; the worker survives, orphaned.- os.kill(supervisor.pid, signal.SIGKILL)- supervisor.wait()- client.sock.close()- SOCK.unlink(missing_ok=True)- print(f"supervisor killed -9 at t+0; relaunching")- supervisor = spawn_daemon()- client = Wire(SOCK)-- def listed():- response = client.request({"type": "list"}, "l")- return response["data"]["sessions"] if response.get("success") else []-- wait_for(- lambda: any(s.get("sessionId") == session_id or s.get("id") == active_id for s in listed()),- 30,- "adoption",- )- print("worker re-adopted by the second supervisor generation")-- # The watcher exits ~12s after its cell; the notice must wake the session.- def woken():- response = client.request(- {"type": "get_messages", "activeSessionId": active_id}, "gm"- )- if not response.get("success"):- return False- return "woken by the bash-done notice" in json.dumps(response["data"])-- try:- wait_for(woken, 90, "the bash-done wake")- except TimeoutError:- file_rows = session_file.read_text() if session_file.exists() else ""- kernel_stderr = ""- stderr_path = AGENT_DIR / "session-artifacts" / session_id / "kernel-stderr.log"- if stderr_path.exists():- kernel_stderr = stderr_path.read_text()- print("WAKE_MISSING: the session stayed asleep across re-adoption")- print(f" async_bash_completion row persisted: {'async_bash_completion' in file_rows}")- rejection = [l for l in kernel_stderr.splitlines() if "not accepted" in l or "bash.completed" in l]- print(f" kernel stderr rejection lines: {rejection[:3]}")- print(f" provider requests seen: {len(MOCK_REQUESTS)}")- for i, body in enumerate(MOCK_REQUESTS):- print(f" --- request {i} (last 400 chars):")- print(" " + body[-400:].replace("\n", " ")[:400])- # The red path cleans up like the green one: a leaked supervisor- # (and its adopted workers) would poison later runs.- try:- client.request({"type": "kill", "activeSessionId": active_id}, "k1")- except Exception:- pass- os.kill(supervisor.pid, signal.SIGTERM)- try:- supervisor.wait(timeout=10)- except subprocess.TimeoutExpired:- os.kill(supervisor.pid, signal.SIGKILL)- sys.exit(1)-- file_rows = session_file.read_text()- assert "async_bash_completion" in file_rows, "no durable notice row"- assert "[bash-done pid:" in file_rows, "no bash-done content row"- print("WAKE_OK: the bash-done notice woke the re-adopted session")- client.request({"type": "kill", "activeSessionId": active_id}, "k1")- os.kill(supervisor.pid, signal.SIGTERM)- try:- supervisor.wait(timeout=10)- except subprocess.TimeoutExpired:- os.kill(supervisor.pid, signal.SIGKILL)---if __name__ == "__main__":- main()diff --git a/scripts/session_stop_lifecycle_parity.py b/scripts/session_stop_lifecycle_parity.pydeleted file mode 100755index 3bcee3ce7b..0000000000--- a/scripts/session_stop_lifecycle_parity.py+++ /dev/null@@ -1,313 +0,0 @@-#!/usr/bin/env python3-"""Stop-lifecycle verifier (lane: deletion-lifecycle; the zombie fix).--Wire-level user test proving the stop/delete lifecycle on both products-(TS parity diff): stopping a session must cancel its goals' continuation-paths AND its scheduled jobs (heartbeats), and no wake pass may revive-the stopped session. The TS contract under test (daemon-mode-`closeSessionOnce("killed")` -> `cancelScheduledJobsForSession`, the-supervisor's `finalizeArchivedWorkerStop`, `isPersistedCronJobRunnable`,-`collectPassiveScheduledJobs`):-- 1. a session with an active goal + an active heartbeat is KILLED through- the wire `kill` (the stop path);- 2. the kill cancels the heartbeat durably (`scheduled-jobs.json` flips- the job to `cancelled`, `nextRunAt` clears) and archives the session- file (state `archived`);- 3. after a daemon restart, the session never revives (no boot re-arm- wake, no schedule delivery) — the daemon's `list` never shows it- again, the goal record freezes (no continuation rows), and the- store's cancel + archived state held.--Runs one side at a time (`--side rust` or `--side ts`); both sides must-pass every step. Timing information (nextRunAt/lastRunAt) is recorded for-the diff but never asserted equal to the second.--Usage:- python3 scripts/session_stop_lifecycle_parity.py --side rust --binary <path> \- --repo <checkout> [--out <dir>]-"""--from __future__ import annotations--import argparse-import json-import shutil-import sys-import time-from datetime import datetime, timezone-from pathlib import Path--REPO = Path(__file__).resolve().parents[1]-sys.path.insert(0, str(REPO / "scripts" / "battery"))-import batterylib as B # noqa: E402--OBJECTIVE = "keep the lane alive until merged"-HEARTBEAT_PROMPT = "liveness ping"-HEARTBEAT_SCHEDULE = "every 10s"-NO_REVIVAL_WINDOW_S = 12.0---class Verifier:- def __init__(self, side_name: str, binary: str, out: Path, repo: Path):- self.name = side_name- self.out = out- self.repo = repo- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")- self.runid = "stop" + stamp- root = out / self.name- root.mkdir(parents=True, exist_ok=True)- agent = root / "agent"- work = root / "work"- work.mkdir(parents=True, exist_ok=True)- if agent.exists():- shutil.rmtree(agent)- agent.mkdir(parents=True)- mock = B.MockProvider(root, [])- mock.set_responses([{"text": "the lane works on"} for _ in range(8)])- mock.start()- tmpdir = Path("/tmp") / f"{self.runid}-{self.name}"- if tmpdir.exists():- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- self.side = B.Side(- name=side_name,- binary=binary,- root=root,- agent_dir=agent,- work_dir=work,- daemon_socket=root / "daemon.sock",- mock=mock,- )- self.side.env = B.scrubbed_env(agent, tmpdir)- if side_name == "rust":- self.side.env["PI_PACKAGE_DIR"] = str(self.repo)- self.side.env["PRIME_API_KEY"] = "sk-battery"- self.side.write_models_json()- settings_path = agent / "settings.json"- settings = json.loads(settings_path.read_text()) if settings_path.exists() else {}- settings["onboardingShown"] = True- settings["telemetry"] = {**(settings.get("telemetry") or {}), "noticeShown": True}- settings_path.write_text(json.dumps(settings))- self.findings: list[dict] = []-- def record(self, summary: str, ok: bool, evidence: str = "") -> None:- self.findings.append(- {"side": self.name, "ok": ok, "summary": summary, "evidence": evidence}- )- print(f"[{'ok ' if ok else 'FAIL'}] {self.name}: {summary}")-- def evidence_json(self, name: str, obj) -> Path:- path = self.out / self.name- path.mkdir(parents=True, exist_ok=True)- target = path / name- target.write_text(json.dumps(obj, indent=2))- return target-- def request(self, command_id: str, command: dict, timeout: float = 120) -> dict:- wire = B.Wire(self.side.daemon_socket)- try:- return wire.request(command_id, command, timeout=timeout)- finally:- wire.close()-- def create_session(self) -> dict:- return self.request(- "stop-create",- {- "type": "create",- "name": "stop-lifecycle",- "config": {- "cwd": str(self.side.work_dir),- "sessionDir": str(self.side.agent_dir / "sessions"),- "provider": "prime-inference",- "model": "mock-1",- "executionMode": "print",- },- },- timeout=120,- )-- def session_file(self, session_id: str) -> Path:- return self.side.agent_dir / "sessions" / f"{session_id}.jsonl"-- def scheduled_jobs(self, session_id: str) -> dict:- path = (- self.side.agent_dir- / "session-artifacts"- / session_id- / "scheduled-jobs.json"- )- if not path.exists():- return {}- return json.loads(path.read_text())-- def latest_state(self, session_id: str) -> str:- state = ""- for line in self.session_file(session_id).read_text().splitlines():- try:- entry = json.loads(line)- except json.JSONDecodeError:- continue- if entry.get("type") == "session_state":- status = entry.get("state", {}).get("status")- if status:- state = status- return state-- def goal_rows(self, session_id: str) -> list[dict]:- rows = []- for line in self.session_file(session_id).read_text().splitlines():- try:- entry = json.loads(line)- except json.JSONDecodeError:- continue- if entry.get("type") == "custom" and entry.get("customType") == "thread_goal_state":- rows.append(entry)- return rows-- def file_row_count(self, session_id: str) -> int:- return len(- [line for line in self.session_file(session_id).read_text().splitlines() if line.strip()]- )-- def listed_ids(self) -> list[str]:- response = self.request("stop-list", {"type": "list"}, timeout=30)- sessions = (response.get("data") or {}).get("sessions") or []- return [- (row.get("sessionId") or row.get("id") or "") for row in sessions- ]-- def run(self) -> bool:- self.side.start_daemon()- created = self.create_session()- if created.get("success") is not True:- self.record("daemon create failed: " + json.dumps(created)[:200], ok=False)- return False- session_id = (- (created.get("data") or {}).get("sessionId")- or (created.get("data") or {}).get("activeSessionId")- or (created.get("data") or {}).get("id")- or ""- )- self.record("daemon created the session", bool(session_id))-- # The zombie-orchestrator shape: an active goal + a heartbeat.- started = self.request(- "stop-goal",- {- "type": "prompt_and_wait",- "activeSessionId": session_id,- "message": f"/goal {OBJECTIVE}",- },- timeout=240,- )- self.record("the goal start turn ran", started.get("success") is True)- heartbeat = self.request(- "stop-hb",- {- "type": "heartbeat_set",- "activeSessionId": session_id,- "schedule": HEARTBEAT_SCHEDULE,- "prompt": HEARTBEAT_PROMPT,- },- timeout=60,- )- self.record("heartbeat_set registered the heartbeat", heartbeat.get("success") is True)- jobs = (self.scheduled_jobs(session_id).get("jobs") or [])- self.record(- "the heartbeat job is active in the durable store",- any(job.get("status") == "active" for job in jobs),- )-- # THE STOP: the wire kill.- killed = self.request(- "stop-kill", {"type": "kill", "activeSessionId": session_id}, timeout=120- )- self.record("the wire kill succeeded", killed.get("success") is True)- self.evidence_json("01-kill-response.json", killed)-- # The kill cancelled the heartbeat durably and archived the file.- deadline = time.time() + 10- job_status = None- while time.time() < deadline:- jobs = (self.scheduled_jobs(session_id).get("jobs") or [])- if jobs and jobs[0].get("status") == "cancelled":- job_status = jobs[0].get("status")- break- time.sleep(0.2)- jobs = (self.scheduled_jobs(session_id).get("jobs") or [])- job_status = jobs[0].get("status") if jobs else None- self.evidence_json("02-post-kill-jobs.json", self.scheduled_jobs(session_id))- self.record(- "the killed session's heartbeat cancelled in the durable store",- job_status == "cancelled",- )- state = self.latest_state(session_id)- self.record("the killed session's file archived", state == "archived")- # The frozen-record baselines: captured after the kill settles (the- # kill appends its own `session_state: archived` row and an- # in-flight continuation may land rows before the archive- # settles), so the post-restart comparisons measure only what a- # revival would have written.- goal_rows_at_kill = self.goal_rows(session_id)- file_rows_at_kill = self.file_row_count(session_id)-- # The restart: the wake passes (boot re-arm, adoption) get their- # shot at reviving the stopped session.- self.side.stop_daemon()- time.sleep(1)- self.side.start_daemon()-- # THE ACCEPTANCE: no revival across the window (an active- # `every 10s` heartbeat would have woken the session within it).- revived = False- deadline = time.time() + NO_REVIVAL_WINDOW_S- while time.time() < deadline:- if session_id in self.listed_ids():- revived = True- break- time.sleep(0.5)- self.record("the killed session never revived after the restart", not revived)-- # No continuation: the goal record and the file froze at the kill.- self.record(- "the stopped session's goal record froze",- len(self.goal_rows(session_id)) == len(goal_rows_at_kill),- )- self.record(- "the stopped session's file froze",- self.file_row_count(session_id) == file_rows_at_kill,- )- self.record(- "the durable cancel held across the restart",- ((self.scheduled_jobs(session_id).get("jobs") or [{}])[0].get("status") == "cancelled"),- )- self.record(- "the archived state held across the restart",- self.latest_state(session_id) == "archived",- )- self.evidence_json("03-final-jobs.json", self.scheduled_jobs(session_id))- self.side.stop_daemon()- return all(finding["ok"] for finding in self.findings)---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--side", required=True, choices=["rust", "ts"])- parser.add_argument("--binary", required=True)- parser.add_argument("--repo", required=True)- parser.add_argument("--out", default="scripts/stop-lifecycle-runs")- args = parser.parse_args()- out = Path(args.out)- verifier = Verifier(args.side, args.binary, out, Path(args.repo))- ok = verifier.run()- out_dir = out / args.side- out_dir.mkdir(parents=True, exist_ok=True)- (out_dir / "findings.json").write_text(json.dumps(verifier.findings, indent=2))- print(f"[{'PASS' if ok else 'FAIL'}] {args.side}: stop lifecycle")- return 0 if ok else 1---if __name__ == "__main__":- raise SystemExit(main())diff --git a/scripts/skill_invocation_parity.py b/scripts/skill_invocation_parity.pydeleted file mode 100644index e12ed5c177..0000000000--- a/scripts/skill_invocation_parity.py+++ /dev/null@@ -1,282 +0,0 @@-#!/usr/bin/env python3-"""Skill-invocation parity verifier: drive the user-typed `/skill:<name>`-submission through a LIVE daemon session on both binaries and frame-diff-the result.--The bug this lane fixes (Kevin dogfood): invoking a skill dumped the full-SKILL.md content into the transcript. TS expands the submission into a-`<skill ...>` block inside the user message (TS `_expandSkillCommand`) and-the TUI renders the compact expandable card (`[skill] <name>` collapsed,-`**<name>**` + the content expanded), with the invocation arguments as-their own user block. The Rust side now expands and renders the same way.--This harness is the live end of the verifier: `custom_message_parity.py`-frame-diffs the PERSISTED block shape (resume/replay); this one proves the-submission path produces it on both binaries. Each side runs the real-daemon with a scripted faux provider (`{"engine": "faux"}` rides the-session-create script on the Rust side; the shared extension registers the-same provider in the TS daemon), a sandboxed agent dir carrying ONE-fixture skill (`web-search`), and types the same-`/skill:web-search find parity tuis` submission. States compared:-- a_collapsed: the settled transcript after the turn — the `[skill]`- web-search card and the `find parity tuis` user block, never the raw- block text;- b_expanded: Ctrl+O twice — the card opens the markdown body.--The collapsed/expanded reach contract is asserted on BOTH sides before the-frame diff; the raw `<skill` block text must never surface in either state.--tmux rules: default socket only (`env -u TMUX`), skillp-* session names,-no kill-server; sessions are killed individually at the end.-"""--import argparse-import difflib-import json-import os-import re-import shutil-import subprocess-import sys-import tempfile-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-import visual_parity as vp # the shared faux-provider + normalize harness--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--SIZES = [("120", "90")]-SESSION_PREFIX = "skillp"--# The fixture skill both sides load from their sandbox agent dir.-SKILL_NAME = "web-search"-SKILL_BODY = "Run one web search and report the titles.\n\nKeep the query short."-SKILL_MARKDOWN = (- "---\n"- 'name: web-search\n'- "description: Search the web and report results.\n"- "---\n"- f"{SKILL_BODY}"-)--# The submission under test and the reply the scripted provider serves.-SUBMISSION = f"/skill:{SKILL_NAME} find parity tuis"-SKILL_ARGS = "find parity tuis"-REPLY = "Skill invocation recorded."-FAUX_SCRIPT = {- "engine": "faux",- "modelId": vp.TS_SCRIPT_MODEL,- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 40,- "responses": [{"content": [{"type": "text", "text": REPLY}]}],-}--SPINNER_CLASS = "[" + "\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f" + "]"---def tmux(*args, check=True):- result = subprocess.run(["env", "-u", "TMUX", "tmux", *args], capture_output=True, text=True)- if check and result.returncode != 0:- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")- return result.stdout---def capture(session):- return tmux("capture-pane", "-e", "-p", "-t", session)---def capture_plain(session):- return tmux("capture-pane", "-p", "-t", session)---def wait_for(session, needle, timeout):- deadline = time.time() + timeout- while time.time() < deadline:- if needle in capture_plain(session):- return- time.sleep(0.3)- raise TimeoutError(f"session {session} never showed {needle!r}")---def prepare_sandbox(base):- """Per-binary sandboxes + the shared fixture skill + faux script."""- script_path = os.path.join(base, "faux-script.json")- with open(script_path, "w") as f:- json.dump(FAUX_SCRIPT, f, indent=2)- sandboxes = {}- for binary in ("ts", "rust"):- home = os.path.join(base, binary, "home")- agent = os.path.join(base, binary, "agent")- tmp = os.path.join(base, binary, "tmp")- os.makedirs(home, exist_ok=True)- os.makedirs(tmp, exist_ok=True)- os.makedirs(os.path.join(agent, "sessions"), exist_ok=True)- os.makedirs(os.path.join(agent, "extensions"), exist_ok=True)- with open(os.path.join(agent, "settings.json"), "w") as f:- json.dump({"onboardingCompleted": True}, f)- # The fixture skill both resource loaders discover from- # `<agentDir>/skills` (user scope on both sides).- skill_dir = os.path.join(agent, "skills", SKILL_NAME)- os.makedirs(skill_dir, exist_ok=True)- with open(os.path.join(skill_dir, "SKILL.md"), "w") as f:- f.write(SKILL_MARKDOWN)- sandboxes[binary] = {"home": home, "agent": agent, "tmp": tmp, "cwd": base}- with open(os.path.join(sandboxes["ts"]["agent"], "extensions", "visual-faux.js"), "w") as f:- f.write(vp.TS_FAUX_EXTENSION)- return script_path, sandboxes---def run_side(binary, sandbox, script_path, size, out_dir):- """Type the submission, capture the collapsed and expanded frames."""- width, height = size- session = f"{SESSION_PREFIX}-{binary}-{width}x{height}"- tmux("kill-session", "-t", session, check=False)- tmux("new-session", "-d", "-s", session, "-x", width, "-y", height, "-c", sandbox["cwd"])- env = (- f"HOME={sandbox['home']} "- f"TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"PRIME_AGENT_FAUX_SCRIPT={script_path} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- if binary == "ts":- command = (- f"{env} prime-agent --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {vp.TS_SCRIPT_MODEL}"- )- else:- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "target", "debug", "prime-agent"),- )- package_dir = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- command = (- f"{env} PI_PACKAGE_DIR={package_dir} "- f"{rust} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {vp.TS_SCRIPT_MODEL}"- )- tmux("send-keys", "-t", session, command, "Enter")- wait_for(session, "Collapsed mode", timeout=60)- time.sleep(1.0)- tmux("send-keys", "-t", session, SUBMISSION)- tmux("send-keys", "-t", session, "Enter")- # Settled: the scripted reply rendered and no loader row remains.- deadline = time.time() + 60- while time.time() < deadline:- pane = capture_plain(session)- if REPLY in pane and not re.search(SPINNER_CLASS, pane):- break- time.sleep(0.3)- else:- raise TimeoutError(f"{binary}: the turn never settled on the scripted reply")- time.sleep(1.0)- frames = {"a_collapsed": capture(session)}- tmux("send-keys", "-t", session, "C-o")- tmux("send-keys", "-t", session, "C-o")- time.sleep(1.5)- frames["b_expanded"] = capture(session)- tmux("kill-session", "-t", session, check=False)- for state, frame in frames.items():- with open(os.path.join(out_dir, f"{binary}-{state}-{width}x{height}.txt"), "w") as f:- f.write(frame)- return frames---def capture_plain_text(frame):- """Strip ANSI codes so content assertions match the visible text."""- return re.sub(r"\x1b\[[0-9;]*[A-Za-z]", "", frame)---def assert_reach(side, frames):- """The card contract: the compact card + args, the body only expanded,- never the raw block text."""- collapsed = capture_plain_text(frames["a_collapsed"])- expanded = capture_plain_text(frames["b_expanded"])- assert f"[skill] {SKILL_NAME}" in collapsed, (- f"{side}: the one-line skill card is missing collapsed"- )- assert SKILL_ARGS in collapsed, f"{side}: the args user block is missing collapsed"- assert "Run one web search" not in collapsed, (- f"{side}: the skill body leaked while collapsed"- )- assert "<skill" not in collapsed, f"{side}: the raw skill block leaked collapsed"- assert "Run one web search" in expanded, f"{side}: Ctrl+O did not open the skill body"- assert "<skill" not in expanded, f"{side}: the raw skill block leaked expanded"- assert SKILL_ARGS in expanded, f"{side}: the args user block is missing expanded"---def normalize(frame, root, agent_dir):- """The shared volatile scrub plus the sandbox agent-dir scrub: the- expanded skill card prints the fixture skill's `References are- relative to <agentDir>/skills/web-search.` line, and each side's- sandbox agent dir differs by design (`ts/agent` vs `rust/agent`), so- both collapse to the same placeholder."""- return vp.normalize(frame.replace(agent_dir, "<AGENT-DIR>"), root)---def diff_lines(left, right):- return "\n".join(- difflib.unified_diff(left.split("\n"), right.split("\n"), fromfile="ts", tofile="rust", lineterm="", n=1)- )---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--sizes", default=",".join(f"{w}x{h}" for w, h in SIZES))- parser.add_argument("--keep", action="store_true")- parser.add_argument("--out", default=None)- parser.add_argument("--only", default=None, choices=["ts", "rust"])- args = parser.parse_args()- sizes = [tuple(entry.split("x")) for entry in args.sizes.split(",")]-- if args.only in (None, "ts"):- ts_identity.assert_ts_side_is_the_ts_product()-- base = tempfile.mkdtemp(prefix="skill-invocation-parity-")- out_dir = args.out or tempfile.mkdtemp(prefix="skill-invocation-captures-")- os.makedirs(out_dir, exist_ok=True)- script_path, sandboxes = prepare_sandbox(base)- failures = []- try:- if args.only:- frames = run_side(args.only, sandboxes[args.only], script_path, sizes[0], out_dir)- assert_reach(args.only, frames)- print(f"captures for {args.only} in {out_dir}: {sorted(frames)}")- return 0- for size in sizes:- ts_frames = run_side("ts", sandboxes["ts"], script_path, size, out_dir)- rust_frames = run_side("rust", sandboxes["rust"], script_path, size, out_dir)- for side, frames in (("ts", ts_frames), ("rust", rust_frames)):- assert_reach(side, frames)- for state in ("a_collapsed", "b_expanded"):- ts_norm = normalize(ts_frames[state], base, sandboxes["ts"]["agent"])- rust_norm = normalize(rust_frames[state], base, sandboxes["rust"]["agent"])- name = f"{state}-{size[0]}x{size[1]}"- if ts_norm == rust_norm:- print(f"PASS {name}")- else:- print(f"FAIL {name}")- report = os.path.join(out_dir, f"diff-{name}.txt")- with open(report, "w") as f:- f.write(diff_lines(ts_norm, rust_norm))- print(f" diff: {report}")- failures.append(name)- finally:- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if not args.keep:- shutil.rmtree(base, ignore_errors=True)- if failures:- print(f"{len(failures)} state(s) differ; captures in {out_dir}")- return 1- print(f"all states match; captures in {out_dir}")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/steer_queue_parity.py b/scripts/steer_queue_parity.pydeleted file mode 100644index cd0c239e45..0000000000--- a/scripts/steer_queue_parity.py+++ /dev/null@@ -1,854 +0,0 @@-#!/usr/bin/env python3-"""Steer/queue/abort wire parity (TS binary vs Rust build).--Drives both products side by side over the daemon wire with the same mock-provider script and byte-compares the normalized event traces of the-three flows that define the queue/abort UX:--- steer/follow-up boundary delivery: a queued steer and a queued- follow-up both deliver as a NEW run at the agent-idle boundary (the- TS-verified daemon semantic; the agent-level mid-run injection lives in- the agent library and is not on the daemon wire), steering lane first,- and the delivery projects the TS active-action phases (`preparing` at- pickup, `committing` before the dispatch, `running` after the delivered- run's `agent_start`, cleared at the settle, the compactRlmText label).-- multi-steer batch delivery (queue mode "all", seeded via- `<agentDir>/settings.json` `steeringMode`): three steers parked behind- a running wedge turn co-deliver as ONE batched turn at the boundary- (TS `_pumpSessionInputs`'s mode-gated gathering +- `turnExecutionPoliciesEqual`) - one delivery `agent_start`, three user- rows, one reply - on both binaries byte-compareably.-- one-at-a-time multi-steer (mode seeded explicitly): three parked steers- deliver one per boundary on both binaries - the mode surface stays- byte-compareable under the rust port's new batched default.-- default multi-steer (NO seed): THE DELIBERATE DIVERGENCE. The TS product- defaults `steeringMode: "one-at-a-time"` (one steer per boundary);- the rust port's product default is "all" - Kevin 2026-09-23: "if we- have many messages in the steer queue, then ALL of them should be sent- after the next tool call [co-delivered as one batch at the next- tool-call boundary]". The two traces differ BY DESIGN here, so this- flow records per-side shape findings and is EXCLUDED from the byte- diff; the seeded flows above keep the mode surface parity-exact.-- abort settle: an abort during a running kernel cell settles the turn- at once - tool_execution_end(isError) + the aborted toolResult row pair- + turn_end + agent_end broadcast (and the toolResult row persists),- the cell dies (no finish marker), the queue suspends (the TS- `requestAbort` suspension) and a steer resumes it.-- abort ownership: the abort of a busy session A (with a parked steer)- neither kills nor corrupts a concurrent session B - B's own turn runs- to completion, A's queued steer survives parked and delivers after the- resume.--Each side runs alone (`--side rust` / `--side ts`); after both, `--diff`-byte-compares the normalized traces and the projection sequences. The-normalization keeps frame shapes and ordering (ids, timestamps, meta,-usage, and the racy aborted-tool text are scrubbed) so a semantic drift-fails the diff even when every assertion passes.-"""--from __future__ import annotations--import argparse-import json-import shutil-import subprocess-import sys-import time-from datetime import datetime, timezone-from pathlib import Path--REPO = Path(__file__).resolve().parents[1]-sys.path.insert(0, str(REPO / "scripts" / "battery"))-import batterylib as B # noqa: E402 (the shared daemon-reap sweep)--PROMPT = "three tools prompt the queue drives"-STEER_MSG = "steer now use plan b"-FOLLOWUP_MSG = "follow up now do more"-BATCH_STEERS = [- "steer batch one",- "steer batch two",- "steer batch three",-]-# Each tool cell sleeps so the parked inputs land deterministically-# mid-run: the steer arrives during tool 2's cell, so the run stops at-# the next boundary (TS `_steeringStopPending`) and never runs tool 3.-THREE_TOOLS = [- {"toolCall": {"name": "ipython", "arguments": {"code": "import time\nprint('tool one done')\ntime.sleep(3)"}}},- {"toolCall": {"name": "ipython", "arguments": {"code": "import time\nprint('tool two done')\ntime.sleep(3)"}}},- {"toolCall": {"name": "ipython", "arguments": {"code": "import time\nprint('tool three done')\ntime.sleep(3)"}}},- {"text": "all three tools done"},-]-WEDGE_CELL = (- "import time\n"- "open('wedge-started','w').write('1')\n"- "time.sleep(300)\n"- "open('wedge-finished','w').write('1')\n"- "print('cell done')"-)-# The compared frame family (everything else - dashboards, heartbeats,-# goal recaps - is side-internal noise and is filtered before the diff).-COMPARED_TYPES = {- "agent_start",- "agent_end",- "turn_start",- "turn_end",- "message_start",- "message_end",- "message_update",- "tool_execution_start",- "tool_execution_end",- "session_action_update",-}---def normalize_event(event: dict) -> dict:- """One normalized frame: type + the stable shape fields only."""- kind = event.get("type")- out = {"type": kind}- if kind in ("message_start", "message_end"):- message = event.get("message") or {}- role = message.get("role")- out["role"] = role- if kind == "message_start" and role == "assistant":- # The start frame's partial content is stream-chunk dependent- # (TS carries the first block, Rust starts empty): only the- # END frame's content shape is compared.- return out- if role == "user":- out["text"] = message.get("content")- elif role == "assistant":- content = message.get("content") or []- kinds = [part.get("type") for part in content if isinstance(part, dict)]- out["content"] = kinds- out["stop"] = message.get("stopReason")- elif role == "toolResult":- is_error = bool(message.get("isError"))- out["isError"] = is_error- if is_error:- out["text"] = "<ABORT-RESULT>"- else:- texts = [- part.get("text", "")- for part in (message.get("content") or [])- if isinstance(part, dict)- ]- out["text"] = "\n".join(texts)- elif role == "custom":- out["customType"] = message.get("customType")- elif kind == "tool_execution_end":- out["isError"] = bool(event.get("isError"))- if out["isError"]:- out["text"] = "<ABORT-RESULT>"- else:- result = event.get("result") or {}- texts = [- part.get("text", "")- for part in (result.get("content") or [])- if isinstance(part, dict)- ]- out["text"] = "\n".join(texts)- elif kind == "turn_end":- message = event.get("message") or {}- content = message.get("content") or []- kinds = [part.get("type") for part in content if isinstance(part, dict)]- out["content"] = kinds- out["stop"] = message.get("stopReason")- results = event.get("toolResults") or []- out["toolResults"] = [- {"isError": bool(result.get("isError")), "text": "<ABORT-RESULT>" if result.get("isError") else (result.get("content") or [{}])[0].get("text", "")}- for result in results- ]- elif kind == "agent_end":- messages = event.get("messages") or []- # The harness-digest custom row is session-content (present when- # the side's session has harness state), not the queue/abort- # surface: it drops from the compared roles.- out["roles"] = [- (message.get("role"), (message.get("content") or [{}])[0].get("type", None) if isinstance(message.get("content"), list) else None)- for message in messages- if message.get("role") != "custom"- ]- elif kind == "session_action_update":- out["actions"] = event.get("actions")- elif kind == "message_update":- out["type"] = "message_update"- return out---class Side:- def __init__(self, name: str, binary: str, out: Path, steering_mode: str | None = None):- self.name = name- self.out = out / name- self.out.mkdir(parents=True, exist_ok=True)- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")- self.runid = "sqp" + stamp- self.root = out / f"{name}-{stamp}"- self.agent = self.root / "agent"- self.agent.mkdir(parents=True)- self.work = self.root / "work"- self.work.mkdir()- # The queue delivery modes (TS `steeringMode`/`followUpMode`, the- # global `<agentDir>/settings.json`): `all` batches the parked- # steering prefix into ONE co-delivered turn at the boundary.- if steering_mode is not None:- (self.agent / "settings.json").write_text(- json.dumps({"steeringMode": steering_mode, "followUpMode": "one-at-a-time"})- )- self.mock = B.MockProvider(self.root, [0])- self.mock.set_responses([{"text": "idle filler"}])- self.mock.start()- self.binary = binary- # Findings accumulate ACROSS the run's Side instances (each flow- # builds its own Side; a per-instance list loses the earlier- # flows' FAILs from the summary).- self.findings: list[dict] = []- self.all_findings: list[dict] = []- prior = out / "all-findings.json"- if prior.exists():- try:- self.all_findings = json.loads(prior.read_text())- except Exception:- self.all_findings = []- self.env = B.scrubbed_env(self.agent, self.root / "tmp")- # The kernel python: reuse the machine's installed kernel venv when- # present. A fresh HOME would otherwise bootstrap a fresh venv per- # run (a full `uv sync`), which exceeds the supervisor's 30s- # worker-boot deadline (the TS `WORKER_CONNECT_TIMEOUT_MS`) on a- # loaded box - the kernel itself stays real, only the venv- # bootstrap is reused.- import os as _os- kernel_python = Path.home() / ".prime/agent/kernel-venv/bin/python"- if kernel_python.exists():- self.env["PRIME_AGENT_KERNEL_PYTHON"] = str(kernel_python)- if name == "rust":- self.env["PI_PACKAGE_DIR"] = str(REPO)- self.write_models_json()- self.daemon_proc = None- self.sock = None-- # -- daemon lifecycle ----------------------------------------------------- def write_models_json(self) -> None:- models = {- "providers": {- "prime-inference": {- "api": "openai-completions",- "baseUrl": self.mock.url(),- "apiKey": "sk-battery",- "models": [- {- "id": "mock-1",- "name": "Mock 1",- "api": "openai-completions",- "baseUrl": self.mock.url(),- "contextWindow": 128000,- "maxTokens": 4096,- }- ],- }- }- }- (self.agent / "models.json").write_text(json.dumps(models))-- def start_daemon(self) -> None:- argv = [self.binary, "supervisor", "--socket", str(self.root / "daemon.sock"), "--agent-dir", str(self.agent)]- self.daemon_proc = subprocess.Popen(- argv,- stdout=subprocess.DEVNULL,- stderr=open(self.root / "daemon.log", "w"),- env=self.env,- )- deadline = time.time() + 30- candidates = [self.root / "daemon.sock", self.root / "tmp" / f"prime-agent-{B.os.getuid()}" / "daemon.sock"]- while time.time() < deadline:- for cand in candidates:- if cand.exists():- self.sock = cand- return- if self.daemon_proc.poll() is not None:- raise SystemExit(f"{self.name} daemon exited early")- time.sleep(0.1)- raise SystemExit(f"{self.name} daemon socket never appeared")-- def stop_daemon(self) -> None:- needles = [str(self.root / "daemon.sock"), str(self.root)]- B.reap_daemons(socket_paths=[self.sock] if self.sock else [], needles=needles, proc=self.daemon_proc)-- # -- helpers -------------------------------------------------------------- def record(self, summary: str, ok: bool, evidence: str = "") -> None:- finding = {"side": self.name, "ok": ok, "summary": summary, "evidence": evidence}- self.findings.append(finding)- self.all_findings.append(finding)- (self.out / "all-findings.json").write_text(json.dumps(self.all_findings, indent=1))- suffix = f" :: {evidence[:240]}" if (not ok and evidence) else ""- print(f"[{'ok ' if ok else 'FAIL'}] {self.name}: {summary}{suffix}")-- def evidence(self, name: str, text: str) -> None:- (self.out / name).write_text(text)-- def queue_script(self, responses: list, extra_queues: list | None = None) -> None:- """Session-scoped mock queues, first-match-wins per request. The- dashboard catch-all must come first: the daemon's status-line- recap requests embed the conversation (so they carry every flow- prompt's marker text) and their own `<agent-state>` wrapper; the- wrapper routes them here before they can steal a flow response."""- queues = [- {"name": "dashboard", "match": ["<agent-state>"], "responses": [{"text": "ok"}]},- {"name": "flow", "match": [PROMPT], "responses": responses},- ]- queues.extend(extra_queues or [])- self.mock.set_responses([{"text": "idle filler"}], queues=queues)-- def wait_marker(self, path: Path, timeout: float = 240.0, wire=None) -> bool:- deadline = time.time() + timeout- while time.time() < deadline:- if wire:- wire.drain(0.3)- if path.exists():- return True- time.sleep(0.2)- return False-- def wait_event(self, wire, predicate, timeout: float = 120.0):- """Drain until a matching session event arrives; returns it."""- deadline = time.time() + timeout- while time.time() < deadline:- wire.drain(0.4)- for e in wire.events:- if e.get("type") == "session_event":- if predicate(e["event"]):- return e["event"]- return None-- def session_event_types(self, wire) -> list:- return [- e["event"].get("type")- for e in wire.events- if e.get("type") == "session_event"- ]-- def raw_trace(self, wire) -> list:- """The raw session events; the diff-time normalizer filters and- shapes them so a normalization tweak never needs a side re-run."""- return [e["event"] for e in wire.events if e.get("type") == "session_event"]-- # -- flows ---------------------------------------------------------------- def flow_queue_delivery(self) -> list:- """The steer + follow-up boundary delivery and its projections."""- work = self.root / "work-q"- work.mkdir()- self.queue_script(THREE_TOOLS + [- {"text": f"acknowledged {STEER_MSG}"},- {"text": f"acknowledged {FOLLOWUP_MSG}"},- ])- wire = B.Wire(self.sock)- try:- created = wire.request("q-create", {"type": "create", "config": {"cwd": str(work), "model": "mock-1", "sessionDir": str(self.agent / "sessions")}})- assert created.get("success") is True, created- sid = created["data"]["id"]- wire.request("q-attach", {"type": "attach", "activeSessionId": sid})- prompt = wire.request("q-prompt", {"type": "prompt", "activeSessionId": sid, "message": PROMPT})- assert prompt.get("success") is True, prompt- # Park both inputs mid-run (after tool one's tool_execution_end).- first_end = self.wait_event(wire, lambda ev: ev.get("type") == "tool_execution_end")- self.record("the 3-tool run started", first_end is not None)- steer = wire.request("q-steer", {"type": "steer", "activeSessionId": sid, "message": STEER_MSG})- follow = wire.request("q-follow", {"type": "follow_up", "activeSessionId": sid, "message": FOLLOWUP_MSG})- self.record("steer + follow_up parked behind the busy turn", steer.get("success") is True and follow.get("success") is True)- # Both deliver as new runs at the idle boundary, steer first.- steered = self.wait_event(wire, lambda ev: ev.get("type") == "message_start" and STEER_MSG in json.dumps(ev.get("message") or {}), timeout=180)- self.record("the steer delivered as a new run at the idle boundary", steered is not None)- followed = self.wait_event(wire, lambda ev: ev.get("type") == "message_start" and FOLLOWUP_MSG in json.dumps(ev.get("message") or {}), timeout=180)- self.record("the follow-up delivered after the steer's run", followed is not None)- # Drain past the follow-up run's settle: the cleared queue- # projection arrives after the delivered run's agent_end.- if followed is not None:- self.wait_event(wire, lambda ev: ev.get("type") == "agent_end", timeout=180)- wire.drain(2.0)- types = self.session_event_types(wire)- if steered is not None and followed is not None:- steer_idx = types.index("message_start", types.index("agent_start", 0)) if False else None- # The projection phases: preparing/committing before the- # delivered run's agent_start, running after it, with labels.- trace = [- normalize_event(ev)- for ev in self.raw_trace(wire)- if ev.get("type") in COMPARED_TYPES- ]- phase_seq = [t["actions"].get("active", {}).get("phase") if t["type"] == "session_action_update" else None for t in trace]- phases = [p for p in phase_seq if p]- self.record("the delivery projected preparing/committing/running with labels", phases[:3] == ["preparing", "committing", "running"], json.dumps(phases))- labels = [t["actions"].get("active", {}).get("label") for t in trace if t["type"] == "session_action_update" and t["actions"].get("active")]- self.record("the active labels are the compacted messages", labels and all(l in (STEER_MSG, FOLLOWUP_MSG) for l in labels if l), json.dumps(labels))- return self.raw_trace(wire)- finally:- wire.close()-- def flow_batch_delivery(self) -> list:- """The multi-steer batch under queue mode "all" (TS- `_pumpSessionInputs`'s mode gate): the same-lane parked prefix- co-delivers as ONE batched turn at the boundary."""- work = self.root / "work-b"- work.mkdir()- # The parked-lane parking must be deterministic: tool one's cell- # holds the turn long enough for every steer to park mid-run (the- # established three-tools pattern), so the steering stop ends the- # run at tool one's boundary with the whole prefix queued.- # The mock serves its responses in request order: the wedge's- # two tool calls consume the first two; the steering stop ends the- # run at tool two's boundary, so the batched turn is request- # three — the batch reply.- self.queue_script(- [- {"toolCall": {"name": "ipython", "arguments": {"code": "import time\nprint('batch tool one done')\ntime.sleep(5)"}}},- {"toolCall": {"name": "ipython", "arguments": {"code": "import time\nprint('batch tool two done')\ntime.sleep(12)"}}},- ]- + [{"text": "batch reply"}, {"text": "all batch tools done"}]- )- wire = B.Wire(self.sock)- try:- created = wire.request("b-create", {"type": "create", "config": {"cwd": str(work), "model": "mock-1", "sessionDir": str(self.agent / "sessions")}})- assert created.get("success") is True, created- sid = created["data"]["id"]- wire.request("b-attach", {"type": "attach", "activeSessionId": sid})- prompt = wire.request("b-prompt", {"type": "prompt", "activeSessionId": sid, "message": PROMPT})- assert prompt.get("success") is True, prompt- first_end = self.wait_event(wire, lambda ev: ev.get("type") == "tool_execution_end")- self.record("the batch wedge run started", first_end is not None)- park_t0 = time.time()- for msg in BATCH_STEERS:- parked = wire.request(f"b-steer-{msg}", {"type": "steer", "activeSessionId": sid, "message": msg})- assert parked.get("success") is True, parked- print(f"[timing] {self.name}: parked {msg!r} at +{time.time() - park_t0:.2f}s")- # The parked rows project before the boundary: every steer is- # visible in the queue projection before the run stops (the- # parking is part of the assertion surface, and it makes the- # pickup race-free: all three rows are queued when the- # boundary hits).- for msg in BATCH_STEERS:- proj = self.wait_event(- wire,- lambda ev, m=msg: ev.get("type") == "session_action_update"- and m in json.dumps(ev.get("actions") or {}),- timeout=60,- )- print(f"[timing] {self.name}: projected {msg!r} at +{time.time() - park_t0:.2f}s")- assert proj is not None, "the parking projection never arrived"- self.record("three steers parked behind the busy turn", True)- # The run stops at the wedge's boundary and the parked prefix- # co-delivers as ONE batched turn: one delivery agent_start,- # three user rows, one reply.- delivered = self.wait_event(- wire,- lambda ev: ev.get("type") == "message_start"- and BATCH_STEERS[0] in json.dumps(ev.get("message") or {}),- timeout=180,- )- self.record("the batched turn's first steer row delivered", delivered is not None)- replied = self.wait_event(- wire,- lambda ev: ev.get("type") == "message_end"- and "batch reply" in json.dumps(ev.get("message") or {}),- timeout=180,- )- self.record("the batched turn settled with one reply", replied is not None)- if replied is not None:- self.wait_event(wire, lambda ev: ev.get("type") == "agent_end", timeout=180)- wire.drain(2.0)- types = self.session_event_types(wire)- if delivered is not None and replied is not None:- # The delivery window: everything after the wedge run's- # agent_end (the batched turn is the next — and, under- # mode "all", the only — run).- wedge_end = types.index("agent_end")- delivery = types[wedge_end + 1 :]- self.record(- "the delivery ran as ONE agent_start",- delivery.count("agent_start") == 1,- json.dumps(delivery[:40]),- )- # The three steers + the batched reply ride the one run:- # three user message_starts plus the reply's.- self.record(- "the three steers co-delivered in the one batched turn",- delivery.count("message_start") >= 4,- json.dumps(delivery[:40]),- )- return self.raw_trace(wire)- finally:- wire.close()-- def flow_multi_steer(self, seed: str | None) -> list:- """Three parked steers under the given queue-mode seed: the- one-at-a-time mode (seeded, or the TS default) delivers one steer- per boundary on both binaries; the rust port's default ("all",- Kevin's batch spec) co-delivers the prefix as ONE batched turn —- the deliberate divergence this flow records per side."""- work = self.root / ("work-m" if seed is None else f"work-m-{seed}")- work.mkdir()- # The wedge: tool one's cell holds the turn while the steers park,- # so the steering stop ends the run at tool one's boundary with- # the whole prefix queued. Replies cover both shapes: the batch- # consumes one, the drip-feed three.- self.queue_script(- [- {"toolCall": {"name": "ipython", "arguments": {"code": "import time\nprint('multi steer tool one done')\ntime.sleep(5)"}}},- {"toolCall": {"name": "ipython", "arguments": {"code": "import time\nprint('multi steer tool two done')\ntime.sleep(12)"}}},- ]- + [- {"text": f"multi steer reply {index}"}- for index in range(1, 5)- ]- )- wire = B.Wire(self.sock)- try:- created = wire.request("m-create", {"type": "create", "config": {"cwd": str(work), "model": "mock-1", "sessionDir": str(self.agent / "sessions")}})- assert created.get("success") is True, created- sid = created["data"]["id"]- wire.request("m-attach", {"type": "attach", "activeSessionId": sid})- prompt = wire.request("m-prompt", {"type": "prompt", "activeSessionId": sid, "message": PROMPT})- assert prompt.get("success") is True, prompt- first_end = self.wait_event(wire, lambda ev: ev.get("type") == "tool_execution_end")- self.record("the multi-steer wedge run started", first_end is not None)- for msg in BATCH_STEERS:- parked = wire.request(f"m-steer-{msg}", {"type": "steer", "activeSessionId": sid, "message": msg})- assert parked.get("success") is True, parked- for msg in BATCH_STEERS:- proj = self.wait_event(- wire,- lambda ev, m=msg: ev.get("type") == "session_action_update"- and m in json.dumps(ev.get("actions") or {}),- timeout=60,- )- assert proj is not None, "the parking projection never arrived"- self.record("three steers parked behind the busy turn", True)- # Wait out the wedge run's settle, then the delivery window.- last_reply = self.wait_event(- wire,- lambda ev: ev.get("type") == "message_end"- and any(- f"multi steer reply {index}" in json.dumps(ev.get("message") or {})- for index in range(1, 5)- ),- timeout=180,- )- self.record("the queued steers were delivered and answered", last_reply is not None)- if last_reply is not None:- self.wait_event(wire, lambda ev: ev.get("type") == "agent_end", timeout=180)- wire.drain(3.0)- types = self.session_event_types(wire)- # The delivery window: everything after the wedge run's- # agent_end (the FIRST agent_end — the fresh session's only- # earlier run; the drip shape's delivery turns each carry- # their own agent_end inside the window).- wedge_end = types.index("agent_end")- delivery = types[wedge_end + 1:]- starts = delivery.count("agent_start")- if seed is None:- # The default divergence: the rust port batches, the TS- # product drips. Record the shape each side must show.- if self.name == "rust":- self.record(- "the DEFAULT co-delivers the parked prefix as ONE batched turn (Kevin's batch spec)",- starts == 1 and delivery.count("message_start") >= 4,- json.dumps(delivery[:40]),- )- else:- self.record(- "the TS DEFAULT delivers one steer per boundary (one-at-a-time)",- starts == 3,- json.dumps(delivery[:40]),- )- else:- self.record(- "queue mode one-at-a-time delivers one steer per boundary",- starts == 3,- json.dumps(delivery[:40]),- )- return self.raw_trace(wire)- finally:- wire.close()-- def flow_abort_settle(self) -> list:- """The abort during a running kernel cell."""- work = self.root / "work-a"- work.mkdir()- self.queue_script([- {"toolCall": {"name": "ipython", "arguments": {"code": WEDGE_CELL}}},- {"text": "the cell completed"},- {"text": "resumed after the abort"},- ])- wire = B.Wire(self.sock)- try:- created = wire.request("a-create", {"type": "create", "config": {"cwd": str(work), "model": "mock-1", "sessionDir": str(self.agent / "sessions")}})- assert created.get("success") is True, created- sid = created["data"]["id"]- wire.request("a-attach", {"type": "attach", "activeSessionId": sid})- prompt = wire.request("a-prompt", {"type": "prompt", "activeSessionId": sid, "message": PROMPT})- assert prompt.get("success") is True, prompt- started = self.wait_marker(work / "wedge-started", wire=wire)- self.record("the wedge cell started (real kernel)", started)- abort = wire.request("a-abort", {"type": "abort", "activeSessionId": sid})- self.record("the abort command succeeded", abort.get("success") is True)- settled = self.wait_event(wire, lambda ev: ev.get("type") == "agent_end", timeout=60)- self.record("the aborted turn settled (agent_end within the budget)", settled is not None)- # The settle frames: tool_execution_end(isError) + toolResult- # pair + turn_end before the agent_end.- types = self.session_event_types(wire)- if settled is not None:- idx = len(types) - 1 - types[::-1].index("agent_end")- tail = types[: idx + 1]- ok = (- "tool_execution_end" in tail- and tail.count("message_end") >= 2- and "turn_end" in tail- )- self.record("the settle frames: tool_execution_end + toolResult pair + turn_end + agent_end", ok, json.dumps(tail[-8:]))- time.sleep(3)- self.record("the interrupted cell died (no finish marker)", not (work / "wedge-finished").exists())- # The toolResult row persisted.- persisted = False- for path in (self.agent / "sessions").glob("*.jsonl"):- for line in path.read_text().splitlines():- row = json.loads(line)- message = row.get("message") or {}- if message.get("role") == "toolResult" and message.get("isError") is True:- persisted = True- self.record("the aborted toolResult row persisted to the session file", persisted)- # The queue suspension: a plain prompt is refused, a steer resumes.- refused = wire.request("a-susp", {"type": "prompt", "activeSessionId": sid, "message": "plain prompt after abort"})- self.record("a plain prompt is refused while the queue is suspended", refused.get("success") is False, json.dumps(refused.get("error"))[:120])- resume = wire.request("a-resume", {"type": "steer", "activeSessionId": sid, "message": "resume the session please"})- self.record("a steer resumed the suspended queue", resume.get("success") is True)- resumed = self.wait_event(wire, lambda ev: ev.get("type") == "message_start" and "resume the session please" in json.dumps(ev.get("message") or {}), timeout=180)- self.record("the resume steer delivered", resumed is not None)- if resumed is not None:- self.wait_event(wire, lambda ev: ev.get("type") == "agent_end", timeout=180)- wire.drain(2.0)- return self.raw_trace(wire)- finally:- wire.close()-- def flow_abort_ownership(self) -> list:- """The abort of session A does not kill or corrupt session B."""- work = self.root / "work-o"- work.mkdir()- self.queue_script(- [- {"toolCall": {"name": "ipython", "arguments": {"code": "import time\ntime.sleep(120)\nprint('ownership cell')"}}},- {"text": "A recovered"},- ],- extra_queues=[- {- "name": "session-b",- "match": ["session b own task"],- "responses": [{"text": "B completed its own turn"}],- }- ],- )- wire = B.Wire(self.sock)- try:- created_a = wire.request("o-create-a", {"type": "create", "config": {"cwd": str(work), "model": "mock-1", "sessionDir": str(self.agent / "sessions")}})- created_b = wire.request("o-create-b", {"type": "create", "config": {"cwd": str(work), "model": "mock-1", "sessionDir": str(self.agent / "sessions")}})- assert created_a.get("success") is True and created_b.get("success") is True- sid_a = created_a["data"]["id"]- sid_b = created_b["data"]["id"]- wire.request("o-attach-a", {"type": "attach", "activeSessionId": sid_a})- # A second client attached to B: session events are per-session.- wire_b = B.Wire(self.sock)- try:- wire_b.request("o-attach-b", {"type": "attach", "activeSessionId": sid_b})- prompt_a = wire.request("o-prompt-a", {"type": "prompt", "activeSessionId": sid_a, "message": PROMPT})- assert prompt_a.get("success") is True- # A's kernel cell is live before the steer parks and the- # abort lands (the abort must interrupt the running cell,- # not a provider wait).- a_cell = self.wait_event(wire, lambda ev: ev.get("type") == "tool_execution_start", timeout=240)- self.record("session A's kernel cell started", a_cell is not None)- # A parks a steer; B starts its own turn.- parked = wire.request("o-steer-a", {"type": "steer", "activeSessionId": sid_a, "message": "steer for session a"})- self.record("session A parked a steer behind its busy turn", parked.get("success") is True)- prompt_b = wire_b.request("o-prompt-b", {"type": "prompt", "activeSessionId": sid_b, "message": "session b own task"})- self.record("session B admitted its own prompt", prompt_b.get("success") is True)- # Abort A mid-cell: B is unaffected, A's parked steer survives.- abort_a = wire.request("o-abort-a", {"type": "abort", "activeSessionId": sid_a})- self.record("session A aborted mid-cell", abort_a.get("success") is True)- b_done = self.wait_event(wire_b, lambda ev: ev.get("type") == "message_end" and "B completed its own turn" in json.dumps(ev.get("message") or {}), timeout=240)- self.record("session B's own turn ran to completion despite A's abort", b_done is not None)- a_settled = self.wait_event(wire, lambda ev: ev.get("type") == "agent_end", timeout=60)- self.record("session A's aborted turn settled", a_settled is not None)- finally:- wire_b.close()- # A's queued steer survived the abort: a resume delivers it.- resume = wire.request("o-resume-a", {"type": "steer", "activeSessionId": sid_a, "message": "resume session a"})- self.record("the resume steer admitted on A", resume.get("success") is True)- a_steered = self.wait_event(wire, lambda ev: ev.get("type") == "message_start" and "steer for session a" in json.dumps(ev.get("message") or {}), timeout=180)- self.record("A's parked steer survived the abort and delivered after the resume", a_steered is not None)- # Drain past the delivery's settle (the cleared projection and- # the run's terminal frames arrive after the agent_end).- if a_steered is not None:- self.wait_event(wire, lambda ev: ev.get("type") == "agent_end", timeout=180)- wire.drain(2.0)- return self.raw_trace(wire)- finally:- wire.close()---def run_side(name: str, binary: str, out: Path) -> int:- side = Side(name, binary, out)- traces = {}- try:- side.start_daemon()- traces["queue-delivery"] = side.flow_queue_delivery()- side.evidence("trace-queue-delivery.json", json.dumps(traces["queue-delivery"], indent=1))- side.stop_daemon()- side = Side(name, binary, out, steering_mode="all")- side.start_daemon()- traces["batch-delivery"] = side.flow_batch_delivery()- side.evidence("trace-batch-delivery.json", json.dumps(traces["batch-delivery"], indent=1))- side.stop_daemon()- # The one-at-a-time multi-steer mode stays byte-diffable on both- # binaries; the unseeded default flow records the deliberate- # divergence (the rust port batches, TS drips) and is excluded- # from the diff set.- side = Side(name, binary, out, steering_mode="one-at-a-time")- side.start_daemon()- traces["one-at-a-time-multi-steer"] = side.flow_multi_steer("one-at-a-time")- side.evidence(- "trace-one-at-a-time-multi-steer.json",- json.dumps(traces["one-at-a-time-multi-steer"], indent=1),- )- side.stop_daemon()- side = Side(name, binary, out)- side.start_daemon()- traces["default-multi-steer"] = side.flow_multi_steer(None)- side.evidence(- "trace-default-multi-steer.json",- json.dumps(traces["default-multi-steer"], indent=1),- )- side.stop_daemon()- side = Side(name, binary, out)- side.start_daemon()- traces["abort-settle"] = side.flow_abort_settle()- side.evidence("trace-abort-settle.json", json.dumps(traces["abort-settle"], indent=1))- side.stop_daemon()- side = Side(name, binary, out)- side.start_daemon()- traces["abort-ownership"] = side.flow_abort_ownership()- side.evidence("trace-abort-ownership.json", json.dumps(traces["abort-ownership"], indent=1))- finally:- try:- side.stop_daemon()- except Exception:- pass- side.evidence("summary.json", json.dumps(side.all_findings, indent=1))- total = side.all_findings- failed = [f for f in total if not f["ok"]]- print(f"{name}: {len(total) - len(failed)}/{len(total)} steps ok (all flows)")- return 1 if failed else 0---def run_diff(out: Path) -> int:- failed = 0- # "default-multi-steer" is excluded BY DESIGN: the unseeded default is- # the deliberate divergence (Kevin's batch spec — the rust port- # co-delivers the parked prefix; the TS product's default- # one-at-a-time drips one steer per boundary). Its per-side shape- # findings live in summary.json.- for flow in (- "queue-delivery",- "batch-delivery",- "one-at-a-time-multi-steer",- "abort-settle",- "abort-ownership",- ):- ts_path = out / "ts" / f"trace-{flow}.json"- rust_path = out / "rust" / f"trace-{flow}.json"- if not ts_path.exists() or not rust_path.exists():- print(f"diff {flow}: missing side traces (run both --side invocations first)")- failed += 1- continue- def norm(raw):- out = []- for ev in raw:- if ev.get("type") not in COMPARED_TYPES:- continue- frame = normalize_event(ev)- # Streaming pacing (message_update deltas) and the- # session-start harness digest are content noise, not the- # queue/abort surface: they drop from the compared trace.- if frame["type"] == "message_update":- continue- if frame.get("role") == "custom" or frame.get("customType"):- continue- out.append(frame)- # Collapse consecutive identical frames (repeat updates).- collapsed = []- for frame in out:- if collapsed and collapsed[-1] == frame:- continue- collapsed.append(frame)- return collapsed-- ts = norm(json.loads(ts_path.read_text()))- rust = norm(json.loads(rust_path.read_text()))- # The interleaving of queue projections and run frames is a TS- # event-queue race (a mid-run admission projects after the run's- # queued frames on one TS run, mid-run on another), so the byte- # compare splits the trace into the queue-projection sequence and- # the run-frame sequence and compares each in order; the phase- # assertions in the side runs pin the pickup-before-agent_start- # ordering that is deterministic.- def split(frames):- projections = [f for f in frames if f["type"] == "session_action_update"]- runs = [f for f in frames if f["type"] != "session_action_update"]- return projections, runs-- ts_proj, ts_runs = split(ts)- rust_proj, rust_runs = split(rust)- if ts_proj == rust_proj and ts_runs == rust_runs:- print(f"diff {flow}: MATCHES ({len(ts_runs)} run frames, {len(ts_proj)} projections)")- else:- failed += 1- if ts_proj != rust_proj:- print(f"diff {flow}: PROJECTIONS DIFFER (ts {len(ts_proj)}, rust {len(rust_proj)})")- if ts_runs != rust_runs:- print(f"diff {flow}: RUN FRAMES DIFFER (ts {len(ts_runs)}, rust {len(rust_runs)})")- import difflib- for label, a, b in (- ("projections", ts_proj, rust_proj),- ("run-frames", ts_runs, rust_runs),- ):- if a == b:- continue- a_lines = json.dumps(a, indent=1).splitlines()- b_lines = json.dumps(b, indent=1).splitlines()- diff_lines = list(difflib.unified_diff(a_lines, b_lines, f"ts-{label}", f"rust-{label}", lineterm=""))- for line in diff_lines[:50]:- print(line)- (out / f"diff-{flow}-{label}.txt").write_text("\n".join(diff_lines))- return 1 if failed else 0---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--side", choices=["rust", "ts"], default=None)- parser.add_argument("--diff", action="store_true", help="byte-compare both sides' normalized traces")- parser.add_argument("--binary", default=None)- parser.add_argument("--out", default=str(REPO / "scripts" / "steer-queue-runs"))- args = parser.parse_args()- out = Path(args.out)- if args.diff:- return run_diff(out)- if not args.side:- parser.error("choose --side rust|ts or --diff")- binary = args.binary or (- str(REPO / "target" / "debug" / "pa-daemon") if args.side == "rust" else "prime-agent"- )- return run_side(args.side, binary, out)---if __name__ == "__main__":- raise SystemExit(main())diff --git a/scripts/stop-lifecycle-runs/README.md b/scripts/stop-lifecycle-runs/README.mddeleted file mode 100644index 678918fcc4..0000000000--- a/scripts/stop-lifecycle-runs/README.md+++ /dev/null@@ -1,25 +0,0 @@-# Stop-lifecycle parity run (2026-09-23, lane deletion-lifecycle)--Both sides driven by `scripts/session_stop_lifecycle_parity.py` (the same-wire steps on each product): create a persisted session, start a goal,-set an `every 10s` heartbeat, wire-`kill` it, then restart the daemon and-watch for revival.--| step | rust | ts |-|---|---|---|-| daemon created the session | PASS | PASS |-| the goal start turn ran | PASS | PASS |-| heartbeat_set registered the heartbeat | PASS | PASS |-| the heartbeat job is active in the durable store | PASS | PASS |-| the wire kill succeeded | PASS | PASS |-| the killed session's heartbeat cancelled in the durable store (`status: cancelled`, `nextRunAt` cleared) | PASS | PASS |-| the killed session's file archived (`session_state: archived`) | PASS | PASS |-| the killed session never revived after the restart | PASS | PASS |-| the stopped session's goal record froze | PASS | PASS |-| the stopped session's file froze | PASS | PASS |-| the durable cancel held across the restart | PASS | PASS |-| the archived state held across the restart | PASS | PASS |--The durable-store evidence (`02-post-kill-jobs.json` per side) is-shape-identical across the products (ids/timestamps excepted): the killed-session's job flips to `cancelled` with `nextRunAt` cleared on both.diff --git a/scripts/stop-lifecycle-runs/rust/01-kill-response.json b/scripts/stop-lifecycle-runs/rust/01-kill-response.jsondeleted file mode 100644index 07083596dd..0000000000--- a/scripts/stop-lifecycle-runs/rust/01-kill-response.json+++ /dev/null@@ -1,6 +0,0 @@-{- "id": "stop-kill",- "type": "response",- "command": "kill",- "success": true-}\ No newline at end of filediff --git a/scripts/stop-lifecycle-runs/rust/02-post-kill-jobs.json b/scripts/stop-lifecycle-runs/rust/02-post-kill-jobs.jsondeleted file mode 100644index bcf849fc8e..0000000000--- a/scripts/stop-lifecycle-runs/rust/02-post-kill-jobs.json+++ /dev/null@@ -1,25 +0,0 @@-{- "jobs": [- {- "id": "691bfe66-54ce-4641-9bbd-beae27ba32e5",- "status": "cancelled",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "44501de88487",- "sessionId": "01a0cd97-7e52-7402-96f7-578933c6e36a",- "sessionFile": "/root/stop-lifecycle-runs/rust/agent/sessions/01a0cd97-7e52-7402-96f7-578933c6e36a.jsonl",- "cwd": "/root/stop-lifecycle-runs/rust/work",- "prompt": "liveness ping",- "schedule": {- "kind": "interval",- "expression": "every 10s",- "intervalMs": 10000- },- "createdAt": "2026-09-23T09:27:33.460Z",- "updatedAt": "2026-09-23T09:27:33.634Z",- "runCount": 0- }- ],- "dispatches": []-}\ No newline at end of filediff --git a/scripts/stop-lifecycle-runs/rust/03-final-jobs.json b/scripts/stop-lifecycle-runs/rust/03-final-jobs.jsondeleted file mode 100644index bcf849fc8e..0000000000--- a/scripts/stop-lifecycle-runs/rust/03-final-jobs.json+++ /dev/null@@ -1,25 +0,0 @@-{- "jobs": [- {- "id": "691bfe66-54ce-4641-9bbd-beae27ba32e5",- "status": "cancelled",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "44501de88487",- "sessionId": "01a0cd97-7e52-7402-96f7-578933c6e36a",- "sessionFile": "/root/stop-lifecycle-runs/rust/agent/sessions/01a0cd97-7e52-7402-96f7-578933c6e36a.jsonl",- "cwd": "/root/stop-lifecycle-runs/rust/work",- "prompt": "liveness ping",- "schedule": {- "kind": "interval",- "expression": "every 10s",- "intervalMs": 10000- },- "createdAt": "2026-09-23T09:27:33.460Z",- "updatedAt": "2026-09-23T09:27:33.634Z",- "runCount": 0- }- ],- "dispatches": []-}\ No newline at end of filediff --git a/scripts/stop-lifecycle-runs/rust/findings.json b/scripts/stop-lifecycle-runs/rust/findings.jsondeleted file mode 100644index eea0951c42..0000000000--- a/scripts/stop-lifecycle-runs/rust/findings.json+++ /dev/null@@ -1,74 +0,0 @@-[- {- "side": "rust",- "ok": true,- "summary": "daemon created the session",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "the goal start turn ran",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "heartbeat_set registered the heartbeat",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "the heartbeat job is active in the durable store",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "the wire kill succeeded",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "the killed session's heartbeat cancelled in the durable store",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "the killed session's file archived",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "the killed session never revived after the restart",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "the stopped session's goal record froze",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "the stopped session's file froze",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "the durable cancel held across the restart",- "evidence": ""- },- {- "side": "rust",- "ok": true,- "summary": "the archived state held across the restart",- "evidence": ""- }-]\ No newline at end of filediff --git a/scripts/stop-lifecycle-runs/ts/01-kill-response.json b/scripts/stop-lifecycle-runs/ts/01-kill-response.jsondeleted file mode 100644index 07083596dd..0000000000--- a/scripts/stop-lifecycle-runs/ts/01-kill-response.json+++ /dev/null@@ -1,6 +0,0 @@-{- "id": "stop-kill",- "type": "response",- "command": "kill",- "success": true-}\ No newline at end of filediff --git a/scripts/stop-lifecycle-runs/ts/02-post-kill-jobs.json b/scripts/stop-lifecycle-runs/ts/02-post-kill-jobs.jsondeleted file mode 100644index 858ea55222..0000000000--- a/scripts/stop-lifecycle-runs/ts/02-post-kill-jobs.json+++ /dev/null@@ -1,25 +0,0 @@-{- "jobs": [- {- "id": "74ae6093-5b26-476d-bd66-a83ce95fe07c",- "status": "cancelled",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "31201d1f3c9e",- "sessionId": "01a0cd97-d5cb-72bc-9177-5035f7acc9f4",- "sessionFile": "/root/stop-lifecycle-runs/ts/agent/sessions/01a0cd97-d5cb-72bc-9177-5035f7acc9f4.jsonl",- "cwd": "/root/stop-lifecycle-runs/ts/work",- "prompt": "liveness ping",- "schedule": {- "kind": "interval",- "expression": "every 10s",- "intervalMs": 10000- },- "createdAt": "2026-09-23T09:27:56.119Z",- "updatedAt": "2026-09-23T09:27:56.544Z",- "runCount": 0- }- ],- "dispatches": []-}\ No newline at end of filediff --git a/scripts/stop-lifecycle-runs/ts/03-final-jobs.json b/scripts/stop-lifecycle-runs/ts/03-final-jobs.jsondeleted file mode 100644index 858ea55222..0000000000--- a/scripts/stop-lifecycle-runs/ts/03-final-jobs.json+++ /dev/null@@ -1,25 +0,0 @@-{- "jobs": [- {- "id": "74ae6093-5b26-476d-bd66-a83ce95fe07c",- "status": "cancelled",- "source": "heartbeat",- "runtimeKind": "top-level",- "deliveryMode": "steer",- "activeSessionId": "31201d1f3c9e",- "sessionId": "01a0cd97-d5cb-72bc-9177-5035f7acc9f4",- "sessionFile": "/root/stop-lifecycle-runs/ts/agent/sessions/01a0cd97-d5cb-72bc-9177-5035f7acc9f4.jsonl",- "cwd": "/root/stop-lifecycle-runs/ts/work",- "prompt": "liveness ping",- "schedule": {- "kind": "interval",- "expression": "every 10s",- "intervalMs": 10000- },- "createdAt": "2026-09-23T09:27:56.119Z",- "updatedAt": "2026-09-23T09:27:56.544Z",- "runCount": 0- }- ],- "dispatches": []-}\ No newline at end of filediff --git a/scripts/stop-lifecycle-runs/ts/findings.json b/scripts/stop-lifecycle-runs/ts/findings.jsondeleted file mode 100644index 4f10e31eef..0000000000--- a/scripts/stop-lifecycle-runs/ts/findings.json+++ /dev/null@@ -1,74 +0,0 @@-[- {- "side": "ts",- "ok": true,- "summary": "daemon created the session",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "the goal start turn ran",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "heartbeat_set registered the heartbeat",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "the heartbeat job is active in the durable store",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "the wire kill succeeded",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "the killed session's heartbeat cancelled in the durable store",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "the killed session's file archived",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "the killed session never revived after the restart",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "the stopped session's goal record froze",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "the stopped session's file froze",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "the durable cancel held across the restart",- "evidence": ""- },- {- "side": "ts",- "ok": true,- "summary": "the archived state held across the restart",- "evidence": ""- }-]\ No newline at end of filediff --git a/scripts/thinking_parity.py b/scripts/thinking_parity.pydeleted file mode 100755index 1be4301405..0000000000--- a/scripts/thinking_parity.py+++ /dev/null@@ -1,682 +0,0 @@-#!/usr/bin/env python3-"""Thinking-block display parity verifier: frame-diff the Rust TUI against-the installed TS prime-agent binary rendering the SAME thinking traces in-every path that reaches the display:-- - REPLAYED: a session JSONL with TS-shaped thinking blocks (the- `{"type":"thinking","thinking":...,"thinkingSignature":"reasoning_content"}`- wire form TS-written sessions carry) resumed in the TS binary- (`prime-agent -r <path>`) and replayed in the Rust TUI- (`pa-tui-replay <path>`).- - LIVE: a scripted OpenAI-completions mock streaming `reasoning_content`- deltas (the prime-inference/GLM thinking wire) drives both binaries- interactively.- - RESUMED: the same TS-shaped fixture resumed through the Rust- interactive binary's daemon attach (the resume Kevin dogfooded).--States per side: collapsed (overview: thinking hidden), details (Ctrl+O-once: thinking visible, dim), all (Ctrl+O twice). Frames are normalized-for volatile content and diffed; the reach asserts check the detail-level-gating on BOTH sides (absent collapsed, present dim expanded).--Wire parity is checked too: the Rust-written session file must persist the-`thinkingSignature` key on its thinking blocks — the same key TS-written-sessions carry (a snake_case serde rename once dropped the signature at the-pa-ai -> pa-agent boundary, degrading the block to plain text on the next-provider request).--tmux rules: default socket only (`env -u TMUX`), thinkparity-* session-names, no kill-server; sessions are killed individually at the end.-"""--import argparse-import difflib-import glob-import json-import os-import re-import shutil-import subprocess-import sys-import tempfile-import threading-import time-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--SIZES = [("120", "90")]--MARKER_TEXT = "FINAL thinking parity marker reached."-LIVE_BODY = "Live body text after thinking."-LIVE_THINK = "LIVE-THINK-A first reasoning fragment."-THINK_A = "The user probes thinking rendering."-THINK_B = "Second trace marks THINKPROBE-B"---# ----------------------------------------------------------------------------# Fixture: a TS-shaped session with thinking blocks in every message form.-# -----------------------------------------------------------------------------def session_paths():- return sorted(- glob.glob(os.path.expanduser("~/.prime/agent/sessions/**/*.jsonl"), recursive=True),- key=os.path.getmtime,- )---def newest_assistant_envelope():- """A real assistant message envelope (api/provider/usage fields) so the- synthetic replies deserialize in BOTH loaders (same contract as- custom_message_parity.py; the smallest captured envelope wins)."""- best = None- for path in reversed(session_paths()):- try:- with open(path, encoding="utf-8") as f:- for line in f:- if '"thinking"' in line:- continue- try:- row = json.loads(line)- except ValueError:- continue- message = row.get("message") if row.get("type") == "message" else None- if (- isinstance(message, dict)- and message.get("role") == "assistant"- and isinstance(message.get("content"), list)- and any(- isinstance(block, dict)- and block.get("type") == "text"- and len(block.get("text", "")) < 200- for block in message["content"]- )- and (best is None or len(line) < best[0])- ):- best = (len(line), message)- except OSError:- continue- if best is None:- raise SystemExit("no assistant message found in captured sessions")- return json.loads(json.dumps(best[1]))---def newest_session_header():- for path in reversed(session_paths()):- try:- with open(path, encoding="utf-8") as f:- first = f.readline()- except OSError:- continue- try:- header = json.loads(first)- except ValueError:- continue- if header.get("type") == "session":- return header- raise SystemExit("no captured session header found under ~/.prime/agent/sessions")---def build_session(path, envelope, cwd):- """The parity session: user turn, thinking+text reply, thinking+toolcall- turn with its result, closing text marker. The thinking blocks carry the- TS wire form (`thinkingSignature`), so the fixture is byte-shape- identical to a TS-written session."""- header = {- "type": "session",- "version": 3,- "id": "thinkparity-session",- "cwd": cwd,- "timestamp": "2026-09-21T00:00:00.000Z",- }- entries = [header]- base_ms = 1_700_000_000_000-- def entry(type_, fields, ms):- row = {"type": type_}- row.update(fields)- row["id"] = f"e{ms - 1_700_000_000_000:04d}"- row["parentId"] = entries[-1]["id"]- row["timestamp"] = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(ms / 1000))- return row-- def assistant_with(content, ms, stop="stop"):- message = json.loads(json.dumps(envelope))- message["content"] = content- message["provider"] = "prime-inference"- message["model"] = "z-ai/glm-5.3"- message["timestamp"] = ms- if stop != "stop":- message["stopReason"] = stop- return message-- entries.append(entry("message", {- "message": {"role": "user", "content": "Thinking parity probe.", "timestamp": base_ms},- }, base_ms))- base_ms += 1- entries.append(entry("message", {"message": assistant_with([- {"type": "thinking", "thinking": THINK_A- + " I should mark the THINKPROBE-A token in the reasoning trace so the parity check can find it.",- "thinkingSignature": "reasoning_content"},- {"type": "text", "text": "Replied with body text."},- ], base_ms)}, base_ms))- base_ms += 1- entries.append(entry("message", {"message": assistant_with([- {"type": "thinking", "thinking": THINK_B + " before the tool call.",- "thinkingSignature": "reasoning_content"},- {"type": "toolCall", "name": "ipython", "id": "toolu_think01",- "arguments": {"code": "print('tool ran')"}},- ], base_ms, stop="toolUse")}, base_ms))- base_ms += 1- entries.append(entry("message", {"message": {- "role": "toolResult", "toolCallId": "toolu_think01", "toolName": "ipython",- "content": [{"type": "text", "text": "tool ran"}],- "details": {"status": "ok", "durationMs": 2, "stdout": "tool ran\n"},- "isError": False, "timestamp": base_ms,- }}, base_ms))- base_ms += 1- entries.append(entry("message", {"message": assistant_with(- [{"type": "text", "text": MARKER_TEXT}], base_ms)}, base_ms))- with open(path, "w") as f:- for row in entries:- f.write(json.dumps(row) + "\n")- return path---# ----------------------------------------------------------------------------# The live mock: OpenAI-completions SSE with reasoning_content deltas.-# -----------------------------------------------------------------------------MOCK_CHUNKS = [- {"delta": {"reasoning_content": LIVE_THINK + " "}},- {"delta": {"reasoning_content": "LIVE-THINK-B second fragment."}},- {"delta": {"content": LIVE_BODY}},- {"delta": {}, "finish_reason": "stop"},-]---class MockState:- def __init__(self):- self.requests = []---def start_mock(log_path):- """One mock per side (request logs never interleave). Returns the port."""- state = MockState()- chunks = MOCK_CHUNKS-- class Handler(BaseHTTPRequestHandler):- def log_message(self, *args):- pass-- def do_GET(self):- self.send_response(200)- self.send_header("Content-Type", "application/json")- self.end_headers()- self.wfile.write(json.dumps(- {"data": [{"id": "mock-1", "object": "model"}]}).encode())-- def do_POST(self):- body = self.rfile.read(int(self.headers.get("Content-Length", 0)))- state.requests.append(body)- self.send_response(200)- self.send_header("Content-Type", "text/event-stream")- self.end_headers()- for index, chunk in enumerate(chunks):- wire = {- "id": "chatcmpl-mock",- "model": "mock-1",- "choices": [{"delta": chunk["delta"], "index": 0}],- }- if "finish_reason" in chunk:- wire["choices"][0]["finish_reason"] = chunk["finish_reason"]- self.wfile.write(f"data: {json.dumps(wire)}\n\n".encode())- self.wfile.write(b"data: [DONE]\n\n")- self.wfile.flush()-- server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)- thread = threading.Thread(target=server.serve_forever, daemon=True)- thread.start()- return server.server_address[1], state, server---def write_models_json(agent_dir, base_url):- os.makedirs(agent_dir, exist_ok=True)- models = {"providers": {"prime-inference": {- "api": "openai-completions", "baseUrl": base_url, "apiKey": "sk-battery",- "models": [{"id": "mock-1", "name": "Mock 1", "api": "openai-completions",- "baseUrl": base_url, "contextWindow": 128000, "maxTokens": 4096,- "reasoning": True}]}}}- with open(os.path.join(agent_dir, "models.json"), "w") as f:- json.dump(models, f, indent=1)---# ----------------------------------------------------------------------------# tmux machinery (same rules as custom_message_parity.py).-# -----------------------------------------------------------------------------def tmux(*args, check=True):- result = subprocess.run(["env", "-u", "TMUX", "tmux", *args], capture_output=True, text=True)- if check and result.returncode != 0:- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")- return result.stdout---def capture(session):- return tmux("capture-pane", "-e", "-p", "-t", session)---def capture_plain(session):- return tmux("capture-pane", "-p", "-t", session)---def wait_for(session, needle, timeout):- deadline = time.time() + timeout- while time.time() < deadline:- if needle in capture_plain(session):- return- time.sleep(0.3)- raise TimeoutError(f"session {session} never showed {needle!r}")---def normalize(frame, root):- """The custom_message_parity.py normalizer: volatile rows and values out,- transcript rows in (see that harness for the provenance of each rule)."""- frame = frame.replace(root, "<SANDBOX>")-- def chrome_row(line):- plain = re.sub(r"\x1b\[[0-9;]*m", "", line)- return (- "prime agent" in plain- or "cwd" in plain- or plain.strip().startswith("model ")- or re.search("[\u2580-\u259f]", plain) is not None- )-- frame = re.sub(r"v\d+\.\d+\.\d+", "vX.X.X", frame)- frame = re.sub(r"\b[0-9a-f]{12}\b", "<SID>", frame)- frame = re.sub(r"\b\d+(\.\d+)?(ms|s)\b", "<T>", frame)- frame = re.sub(r"\d+(\.\d+)?[kM]? \(\d+%\)", "<TOK> (<PCT>)", frame)- frame = re.sub(r"[\u2193\u2191] [\d.kM]+ tokens", "<DIR> <TOK> tokens", frame)- spinners = "".join("\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f")- frame = re.sub("[" + spinners + "]", "<SPIN>", frame)- pulses = "".join("\u25f4\u25f7\u25f6\u25f5\u25cb\u25f8\u25fb\u25fc")- frame = re.sub("[" + pulses + "]", "<PULSE>", frame)- frame = re.sub("\x1b\[39m\n", "\n", frame)- frame = re.sub("\n\x1b\[39m(?= )", "\n", frame)- frame = re.sub("\x1b\[49m\n", "\n", frame)- frame = re.sub("\n\x1b\[49m(?= )", "\n", frame)- kept = []- for line in frame.split("\n"):- plain = re.sub(r"\x1b\[[0-9;]*m", "", line)- if "cwd" in plain and "$0.00" in plain:- continue- if "\u2190" in line and "manage" in line:- continue- if chrome_row(line):- continue- kept.append(line)- while kept and not kept[0].strip():- kept.pop(0)- while kept and not kept[-1].strip():- kept.pop()- return "\n".join(kept)---def strip_ansi(frame):- return re.sub(r"\x1b\[[0-9;]*[A-Za-z]", "", frame)---def diff_lines(left, right):- return "\n".join(- difflib.unified_diff(left.split("\n"), right.split("\n"),- fromfile="ts", tofile="rust", lineterm="", n=1)- )---# ----------------------------------------------------------------------------# Sides.-# -----------------------------------------------------------------------------def prepare_sandbox(base, mock_urls):- cwd = os.path.join(base, "cwd")- os.makedirs(cwd, exist_ok=True)- sides = {}- for name, url in mock_urls.items():- home = os.path.join(base, name, "home")- agent = os.path.join(base, name, "agent")- tmp = os.path.join(base, name, "tmp")- os.makedirs(home, exist_ok=True)- os.makedirs(tmp, exist_ok=True)- os.makedirs(os.path.join(agent, "sessions"), exist_ok=True)- with open(os.path.join(agent, "settings.json"), "w") as f:- json.dump({"onboardingCompleted": True}, f)- if url:- write_models_json(agent, url)- sides[name] = {"home": home, "agent": agent, "cwd": cwd, "tmp": tmp}- return sides---def capture_states(session, marker, sizes_note):- """collapsed -> details -> all; returns the three frames."""- wait_for(session, marker, timeout=90)- time.sleep(1.5)- frames = {"a_collapsed": capture(session)}- tmux("send-keys", "-t", session, "C-o")- time.sleep(1.5)- frames["b_details"] = capture(session)- tmux("send-keys", "-t", session, "C-o")- time.sleep(1.5)- frames["c_all"] = capture(session)- return frames---def run_ts_replay(session_path, sandbox, size, out_dir):- session = f"thinkparity-ts-{size[0]}x{size[1]}"- tmux("kill-session", "-t", session, check=False)- tmux("new-session", "-d", "-s", session, "-x", size[0], "-y", size[1], "-c", sandbox["cwd"])- env = (- f"HOME={sandbox['home']} TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} PRIME_AGENT_DISABLE_ANALYTICS=1"- )- command = f"{env} prime-agent --offline -r {session_path}"- tmux("send-keys", "-t", session, command, "Enter")- frames = capture_states(session, MARKER_TEXT, "ts replay")- tmux("kill-session", "-t", session, check=False)- for state, frame in frames.items():- with open(os.path.join(out_dir, f"ts-{state}-{size[0]}x{size[1]}.txt"), "w") as f:- f.write(frame)- return frames---def run_rust_replay(session_path, sandbox, size, out_dir, binary):- session = f"thinkparity-rust-{size[0]}x{size[1]}"- tmux("kill-session", "-t", session, check=False)- tmux("new-session", "-d", "-s", session, "-x", size[0], "-y", size[1], "-c", sandbox["cwd"])- command = f"HOME={sandbox['home']} {binary} {session_path}"- tmux("send-keys", "-t", session, command, "Enter")- frames = capture_states(session, MARKER_TEXT, "rust replay")- tmux("kill-session", "-t", session, check=False)- for state, frame in frames.items():- with open(os.path.join(out_dir, f"rust-{state}-{size[0]}x{size[1]}.txt"), "w") as f:- f.write(frame)- return frames---def run_rust_interactive_resume(session_path, sandbox, size, out_dir, binary, name):- """The daemon-attach resume path (what `prime-agent -r` dogfoods)."""- session = f"thinkparity-rust-resume-{size[0]}x{size[1]}"- tmux("kill-session", "-t", session, check=False)- tmux("new-session", "-d", "-s", session, "-x", size[0], "-y", size[1], "-c", sandbox["cwd"])- env = (- f"HOME={sandbox['home']} TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']}"- )- package_dir = os.path.abspath(- os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")- )- command = (- f"{env} PI_PACKAGE_DIR={package_dir}"- f" {binary} --daemon-socket {sandbox['agent']}/daemon.sock --offline -r {session_path}"- )- tmux("send-keys", "-t", session, command, "Enter")- frames = capture_states(session, MARKER_TEXT, "rust resume")- tmux("send-keys", "-t", session, "C-c")- time.sleep(0.5)- tmux("send-keys", "-t", session, "C-c")- time.sleep(1.0)- tmux("kill-session", "-t", session, check=False)- for state, frame in frames.items():- with open(os.path.join(out_dir, f"rust-resume-{state}-{size[0]}x{size[1]}.txt"), "w") as f:- f.write(frame)- return frames---def run_live(binary, sandbox, size, out_dir, name, prompt):- """One live interactive turn against the reasoning mock."""- session = f"thinkparity-{name}-{size[0]}x{size[1]}"- tmux("kill-session", "-t", session, check=False)- tmux("new-session", "-d", "-s", session, "-x", size[0], "-y", size[1], "-c", sandbox["cwd"])- env = (- f"HOME={sandbox['home']} TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} PRIME_AGENT_DISABLE_ANALYTICS=1"- )- package_dir = os.path.abspath(- os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")- )- extra = f"PI_PACKAGE_DIR={package_dir}" if name == "rust" else ""- command = (- f"{env} {extra} {binary} --provider prime-inference --model mock-1 --offline "- f"--daemon-socket {sandbox['agent']}/daemon.sock"- )- tmux("send-keys", "-t", session, command, "Enter")- time.sleep(8)- tmux("send-keys", "-t", session, prompt, "Enter")- wait_for(session, LIVE_BODY, timeout=90)- time.sleep(1.5)- frames = {"a_collapsed": capture(session)}- tmux("send-keys", "-t", session, "C-o")- time.sleep(1.5)- frames["b_details"] = capture(session)- for state, frame in frames.items():- with open(os.path.join(out_dir, f"live-{name}-{state}-{size[0]}x{size[1]}.txt"), "w") as f:- f.write(frame)- return frames, session---def rust_session_thinking_block(sandbox):- """The thinking block the Rust daemon persisted for the live turn: must- carry the TS wire signature key."""- for path in sorted(- glob.glob(os.path.join(sandbox["agent"], "sessions", "*.jsonl")),- key=os.path.getmtime,- ):- with open(path, encoding="utf-8") as f:- text = f.read()- if '"thinking"' not in text:- continue- for line in text.splitlines():- if '"thinking"' not in line:- continue- try:- row = json.loads(line)- except ValueError:- continue- message = row.get("message")- if not (isinstance(message, dict) and message.get("role") == "assistant"):- continue- for block in message.get("content", []):- if isinstance(block, dict) and block.get("type") == "thinking":- return block- return None---# ----------------------------------------------------------------------------# Reach assertions.-# -----------------------------------------------------------------------------def assert_replay_reach(side, frames):- collapsed = strip_ansi(frames["a_collapsed"])- details = strip_ansi(frames["b_details"])- all_frame = strip_ansi(frames["c_all"])- assert THINK_A not in collapsed, f"{side}: thinking visible collapsed"- assert THINK_B not in collapsed, f"{side}: thinking visible collapsed"- assert THINK_A in details, f"{side}: thinking missing at details level"- assert THINK_B in details, f"{side}: thinking missing at details level"- assert THINK_A in all_frame, f"{side}: thinking missing at all level"---def assert_live_reach(side, frames):- collapsed = strip_ansi(frames["a_collapsed"])- details = strip_ansi(frames["b_details"])- assert LIVE_THINK not in collapsed, f"{side}: live thinking visible collapsed"- assert LIVE_THINK in details, f"{side}: live thinking missing at details level"---def assert_dim(frame, needle):- """The quiet TS treatment: the thinking row renders in the dim color."""- for line in frame.split("\n"):- plain = strip_ansi(line)- if needle in plain:- assert "\x1b[38;2;113;113;122m" in line, (- f"thinking row not dim: {line!r}"- )- return- raise AssertionError(f"needle {needle!r} not in frame")---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--sizes", default=",".join(f"{w}x{h}" for w, h in SIZES))- parser.add_argument("--keep", action="store_true")- parser.add_argument("--out", default=None)- parser.add_argument("--only", default=None, choices=["ts", "rust"])- args = parser.parse_args()- sizes = [tuple(entry.split("x")) for entry in args.sizes.split(",")]-- if args.only in (None, "ts"):- ts_identity.assert_ts_side_is_the_ts_product()-- rust_dir = os.environ.get(- "PA_RUST_DIR",- os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")),- )- rust_bin = os.path.join(rust_dir, "target", "debug", "prime-agent")- rust_replay = os.path.join(rust_dir, "target", "debug", "pa-tui-replay")- for path in (rust_bin, rust_replay):- if not os.path.exists(path):- raise SystemExit(f"missing {path}; build first (cargo build --bin prime-agent --bin pa-tui-replay)")-- base = tempfile.mkdtemp(prefix="thinking-parity-")- out_dir = args.out or tempfile.mkdtemp(prefix="thinking-captures-")-- # One mock per live side.- ts_mock = start_mock(base)- rust_mock = start_mock(base)- sandboxes = prepare_sandbox(base, {- "ts": f"http://127.0.0.1:{ts_mock[0]}/v1",- "rust": f"http://127.0.0.1:{rust_mock[0]}/v1",- "ts-replay": None,- "rust-replay": None,- "rust-resume": None,- })- session_path = build_session(- os.path.join(base, "thinking-session.jsonl"),- newest_assistant_envelope(),- os.path.join(base, "cwd"),- )- print(f"session: {session_path}")-- failures = []- ts_mock_server, rust_mock_server = ts_mock[2], rust_mock[2]- try:- for size in sizes:- if args.only in (None, "ts"):- ts_replay = run_ts_replay(session_path, sandboxes["ts-replay"], size, out_dir)- if args.only in (None, "rust"):- rust_replay = run_rust_replay(- session_path, sandboxes["rust-replay"], size, out_dir, rust_replay- )- if args.only is None:- assert_replay_reach("ts", ts_replay)- assert_replay_reach("rust", rust_replay)- for state in ("a_collapsed", "b_details", "c_all"):- name = f"replay-{state}-{size[0]}x{size[1]}"- ts_norm = normalize(ts_replay[state], base)- rust_norm = normalize(rust_replay[state], base)- if ts_norm == rust_norm:- print(f"PASS {name}")- else:- print(f"FAIL {name}")- report = os.path.join(out_dir, f"diff-{name}.txt")- with open(report, "w") as f:- f.write(diff_lines(ts_norm, rust_norm))- print(f" diff: {report}")- failures.append(name)-- # The daemon-attach resume path: TS-shaped fixture through the- # Rust interactive binary (the dogfood surface).- if args.only in (None, "rust"):- resume_frames = run_rust_interactive_resume(- session_path, sandboxes["rust-resume"], size, out_dir, rust_bin, "resume"- )- assert_replay_reach("rust-resume", resume_frames)- assert_dim(resume_frames["b_details"], THINK_A)- if args.only is None:- ts_norm = normalize(ts_replay["b_details"], base)- rust_norm = normalize(resume_frames["b_details"], base)- name = f"resume-vs-ts-{size[0]}x{size[1]}"- if ts_norm == rust_norm:- print(f"PASS {name}")- else:- print(f"FAIL {name}")- report = os.path.join(out_dir, f"diff-{name}.txt")- with open(report, "w") as f:- f.write(diff_lines(ts_norm, rust_norm))- print(f" diff: {report}")- failures.append(name)-- # The live turn: both binaries against the reasoning mock.- if args.only in (None, "ts"):- ts_live, ts_sess = run_live(- "prime-agent", sandboxes["ts"], size, out_dir, "ts-live",- "say the live thinking probe",- )- tmux("kill-session", "-t", ts_sess, check=False)- if args.only in (None, "rust"):- rust_live, rust_sess = run_live(- rust_bin, sandboxes["rust"], size, out_dir, "rust-live",- "say the live thinking probe",- )- if args.only is None:- assert_live_reach("ts", ts_live)- assert_live_reach("rust", rust_live)- assert_dim(ts_live["b_details"], LIVE_THINK)- assert_dim(rust_live["b_details"], LIVE_THINK)- for state in ("a_collapsed", "b_details"):- name = f"live-{state}-{size[0]}x{size[1]}"- ts_norm = normalize(ts_live[state], base)- rust_norm = normalize(rust_live[state], base)- if ts_norm == rust_norm:- print(f"PASS {name}")- else:- print(f"FAIL {name}")- report = os.path.join(out_dir, f"diff-{name}.txt")- with open(report, "w") as f:- f.write(diff_lines(ts_norm, rust_norm))- print(f" diff: {report}")- failures.append(name)- # Wire parity: the Rust-written session carries the TS wire- # signature key on its thinking block.- block = rust_session_thinking_block(sandboxes["rust"])- assert block is not None, "no thinking block persisted by the rust live turn"- assert block.get("thinkingSignature") == "reasoning_content", (- f"rust-written thinking block lost the TS wire signature: {block}"- )- print("PASS rust-written thinkingSignature wire parity")- finally:- # Sweep this harness's tmux sessions (some arms return early under- # --only, so kill by the thinkparity- prefix, not by stored handles).- listing = tmux("list-sessions", "-F", "#{session_name}", check=False)- for name in listing.split():- if name.startswith("thinkparity-"):- tmux("kill-session", "-t", name, check=False)- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- ts_mock_server.shutdown()- ts_mock_server.server_close()- rust_mock_server.shutdown()- rust_mock_server.server_close()- if not args.keep:- shutil.rmtree(base, ignore_errors=True)-- if failures:- print(f"{len(failures)} state(s) differ; captures in {out_dir}")- return 1- print(f"all states match; captures in {out_dir}")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/tl_verify_agents_view.py b/scripts/tl_verify_agents_view.pydeleted file mode 100644index 8171683b5c..0000000000--- a/scripts/tl_verify_agents_view.py+++ /dev/null@@ -1,111 +0,0 @@--"""Interactive verifier (tmux): the Rust agents view renders the thinking-level on a TOP-LEVEL row in every universe:- 1. live session row (unregressed): "mock-1:high"- 2. after a daemon restart (saved-catalog row): "mock-1:high" (was bare "mock-1")- 3. a stopped subagent (ledger-seeded row): "mock-1:high"-The TS binary runs the same flow for the cross-side record.-"""-import json, os, sys, time, shutil-from pathlib import Path--sys.path.insert(0, "/home/ubuntu/prime-agent-rs/scripts/battery")-import batterylib as B--RUN = Path("/tmp/thinking-level-verify")-BINARY = sys.argv[1] if len(sys.argv) > 1 else "/tmp/prime-agent-tl-musl"-TAG = Path(BINARY).name--def make_side(name, binary):- root = RUN / name- if root.exists():- shutil.rmtree(root)- root.mkdir(parents=True)- agent = root / "agent"; work = root / "work"- work.mkdir(parents=True); agent.mkdir(parents=True)- mock = B.MockProvider(root, [0])- mock.set_responses([{"text": "verify reply"}])- mock.start()- tmpdir = Path("/tmp") / f"tl-verify-{name}"- if tmpdir.exists(): shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- side = B.Side(name=name, binary=binary, root=root, agent_dir=agent,- work_dir=work, daemon_socket=root / "daemon.sock", mock=mock)- side.env = B.scrubbed_env(agent, tmpdir, {})- models = {"providers": {"prime-inference": {- "api": "openai-completions", "baseUrl": mock.url(), "apiKey": "sk-battery",- "models": [{"id": "mock-1", "name": "Mock 1", "api": "openai-completions",- "baseUrl": mock.url(), "reasoning": True,- "contextWindow": 128000, "maxTokens": 4096}]}}}- (agent / "models.json").write_text(json.dumps(models, indent=1))- sp = agent / "settings.json"- sp.write_text(json.dumps({"onboardingShown": True}))- return side--def capture_rows(side, tag, expect_text="Model", expand=False):- sess = f"tlv-{tag}-{side.name}"- argv = [BINARY, "agents", "--daemon-socket", str(side.daemon_socket)]- B.tmux_launch(sess, argv, side.env, side.work_dir)- B.tmux_wait_text(sess, expect_text, timeout=60)- time.sleep(2.0)- frame = B.tmux_capture(sess)- side.evidence(tag, f"{tag}-{side.name}.txt", frame)- rows = [ln for ln in frame.splitlines() if "mock-1" in ln or "subagent" in ln]- for ln in rows:- print(f"[{TAG}] {tag}/{side.name} ROW:", ln)- if expand:- # Move to the subagent-summary row and toggle it open.- for key in ("down", "down", "Right"):- B.tmux_send(sess, key, enter=False)- time.sleep(0.6)- time.sleep(1.0)- frame = B.tmux_capture(sess)- side.evidence(tag, f"{tag}-expanded-{side.name}.txt", frame)- for ln in frame.splitlines():- if "mock-1" in ln or "subagent" in ln:- print(f"[{TAG}] {tag}-expanded/{side.name} ROW:", ln)- B.tmux_kill(sess)- return frame--side = make_side(Path(BINARY).name, BINARY)-side.mock.set_responses([{"text": "verify reply"}])-side.start_daemon()-wire = B.Wire(side.daemon_socket)-create = wire.request("c1", {"type": "create", "name": "verify-top", "config": {- "cwd": str(side.work_dir), "sessionDir": str(side.agent_dir / "sessions"),- "provider": "prime-inference", "model": "mock-1", "thinking": "high",- "executionMode": "print"}}, timeout=120)-assert create.get("success") is True, create-top = create["data"].get("activeSessionId") or create["data"].get("id")-pw = wire.request("p1", {"type": "prompt_and_wait", "activeSessionId": top,- "message": "verify prompt"}, timeout=180)-print(f"[{TAG}] prompt ok:", pw.get("success"))-# A subagent child (spawn task context: model + thinking high), then stop it.-child_dir = side.agent_dir / "subagents"-child_dir.mkdir(parents=True, exist_ok=True)-parent_file = create["data"].get("sessionFile")-parent_session = create["data"].get("sessionId")-cc = wire.request("c2", {"type": "create", "name": "verify-child", "config": {- "cwd": str(side.work_dir), "sessionDir": str(child_dir),- "provider": "prime-inference", "model": "mock-1", "thinking": "high",- "rlmDepth": 1, "parentSessionPath": parent_file, "executionMode": "print"},- "runtimeMetadata": {"kind": "subagent", "rlmChildId": "child-1", "rlmDepth": 1,- "parentSessionFile": parent_file, "parentSessionId": parent_session,- "parentActiveSessionId": top}}, timeout=120)-print(f"[{TAG}] child create ok:", cc.get("success"), "thinkingLevel:", (cc.get("data") or {}).get("thinkingLevel"))-child = (cc.get("data") or {}).get("activeSessionId")-# Stop the child worker without deleting it (a plain kill).-if cc.get("success"):- k = wire.request("k1", {"type": "kill", "activeSessionId": child}, timeout=120)- print(f"[{TAG}] child kill ok:", k.get("success"))-wire.close()-capture_rows(side, "live")--# Restart the daemon: every live row is gone; the agents view rows come from-# the saved catalog (the post-restart universe).-side.stop_daemon()-time.sleep(1.0)-side.start_daemon()-capture_rows(side, "after-restart", expand=True)-side.stop_daemon()-print("DONE")diff --git a/scripts/tool_card_parity.py b/scripts/tool_card_parity.pydeleted file mode 100644index e5b2692f3a..0000000000--- a/scripts/tool_card_parity.py+++ /dev/null@@ -1,373 +0,0 @@-#!/usr/bin/env python3-"""Tool-call card parity verifier: frame-diff the Rust interactive UI-against the installed TS prime-agent binary across all THREE conversation-detail modes, over a scripted session that exercises the tool-card states:-- - a bash call with enough output to trigger the collapsed preview- truncation (`... N earlier lines`) and the expanded full output,- - an ipython cell with multi-line stdout (collapsed summary line, expanded- code + output rows),- - an ipython error cell (error marker, ename, traceback treatment).--Both binaries run the same faux provider script (TS via the sandbox-extension, Rust via PRIME_AGENT_FAUX_SCRIPT) under isolated HOME/agent-dir-sandboxes in tmux at 120x36. States captured per binary:- a_fresh_start, b_collapsed (overview after the turn),- c_details (Ctrl+O x1), d_all (Ctrl+O x2), plus e_running (the first bash- card while the spinner is live). Frames are normalized for volatile- content (versions, session ids, durations, spinners) and diffed; the exit- code is non-zero when any state differs.--tmux rules: default socket only (`env -u TMUX`), tcparity-* session names,-no kill-server; sessions are killed individually at the end.-"""--import argparse-import difflib-import json-import os-import re-import shutil-import subprocess-import sys-import tempfile-import time--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--SIZES = [("120", "36")]--# One turn: text, a bash call with 12-line output (preview truncation), an-# ipython python cell with 4-line stdout, an ipython error cell, done.-# Content is identical on both sides so frames compare content-for-content.-FAUX_SCRIPT = {- "engine": "faux",- "modelId": "faux-1",- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 18,- "responses": [- {- "content": [- {- "type": "thinking",- "thinking": "I will run the scripted checks: a bash call, a python cell, then an error cell.",- },- {"type": "text", "text": "Running the card checks now."},- {- "type": "toolCall",- "name": "bash",- "id": "toolu_bash01",- # Two seconds of sleep hold the running state long- # enough to capture e_running on both sides, then the- # 12 lines drive the collapsed-preview truncation.- "arguments": {"command": "sleep 2 && seq 1 12"},- },- ]- },- {- "content": [- {"type": "text", "text": "Now the python cell."},- {- "type": "toolCall",- "name": "ipython",- "id": "toolu_py001",- "arguments": {- "code": "for i in range(3):\n print(f'line {i}')\nprint('cell done')"- },- },- ]- },- {- "content": [- {"type": "text", "text": "Now the error cell."},- {- "type": "toolCall",- "name": "ipython",- "id": "toolu_err001",- "arguments": {"code": "raise ValueError('boom')"},- },- ]- },- {"content": [{"type": "text", "text": "All card states shown."}]},- ],-}--# Shared with visual_parity.py: one extension source for every harness.-TS_FAUX_EXTENSION = open(- os.path.join(os.path.dirname(os.path.abspath(__file__)), "ts_faux_extension.js"),- encoding="utf-8",-).read()--PROMPT = "Run the card checks."--SPINNER_CHARS = "\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f\u25f4\u25f7\u25f6\u25f5\u25cb\u25f8\u25fb\u25fc"-# A character class over the spinner glyphs: `re.search(SPINNER_CHARS, ...)`-# would match the literal sequence instead of any single glyph.-SPINNER_CLASS = "[" + SPINNER_CHARS + "]"--STATES = [- ("a_fresh_start", "fresh splash"),- ("b_collapsed", "overview after the scripted turn"),- ("c_details", "details mode (Ctrl+O once)"),- ("d_all", "all mode (Ctrl+O twice)"),- # The running state is momentary on both sides (the harness captures- # it opportunistically); compared only when both frames exist.- ("e_running", "the first bash card while the turn is live"),-]---def tmux(*args, check=True):- result = subprocess.run(["env", "-u", "TMUX", "tmux", *args], capture_output=True, text=True)- if check and result.returncode != 0:- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")- return result.stdout---def capture(session):- return tmux("capture-pane", "-e", "-p", "-t", session)---def capture_plain(session):- return tmux("capture-pane", "-p", "-t", session)---def normalize(frame, root):- frame = frame.replace(root, "<SANDBOX>")- frame = re.sub(r"v\d+\.\d+\.\d+", "vX.X.X", frame)- frame = re.sub(r"\b[0-9a-f]{12}\b", "<SID>", frame)- frame = re.sub(r"\b\d+(\.\d+)?(ms|s)\b", "<T>", frame)- frame = re.sub(r"\d+(\.\d+)?[kM]? \(\d+%\)", "<TOK> (<PCT>)", frame)- frame = re.sub(r"[\u2193\u2191] [\d.kM]+ tokens", "<DIR> <TOK> tokens", frame)- frame = re.sub(r"\b\d+s\b", "<S>", frame)- spinners = "".join("\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f")- frame = re.sub("[" + spinners + "]", "<SPIN>", frame)- pulses = "".join("\u25f4\u25f7\u25f6\u25f5\u25cb\u25f8\u25fb\u25fc")- frame = re.sub("[" + pulses + "]", "<PULSE>", frame)- # tmux places trailing resets (foreground 39m, background 49m) at either- # the end of the row whose styled text just ended or before the next- # row's default margin; both describe default cells, so drop them.- frame = re.sub("\x1b\[39m\n", "\n", frame)- frame = re.sub("\n\x1b\[39m(?= )", "\n", frame)- frame = re.sub("\x1b\[49m\n", "\n", frame)- frame = re.sub("\n\x1b\[49m(?= )", "\n", frame)- # The tray right side is right-aligned against differing token counts;- # collapse the alignment padding so the row compares by content.- frame = re.sub(- r" +((?:\x1b\[[0-9;]*m)*(?:faux-1 \u00b7 )?<TOK> \(<PCT>\)\s*)$",- r" <TRAY-RIGHT>\1",- frame,- flags=re.MULTILINE,- )- return frame---def diff_lines(left, right):- return "\n".join(- difflib.unified_diff(left.split("\n"), right.split("\n"), fromfile="ts", tofile="rust", lineterm="", n=1)- )---def find_runtime_package_dir():- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- if not os.path.isdir(releases):- raise SystemExit("cannot find the prime-agent-runtime sidecar; set PI_PACKAGE_DIR")- candidates = [- entry- for entry in sorted(os.listdir(releases))- if os.path.isdir(os.path.join(releases, entry, "prime-agent-runtime"))- ]- if not candidates:- raise SystemExit("no release with prime-agent-runtime/ under " + releases)- return os.path.join(releases, candidates[-1])---def prepare_sandbox(base):- shared_cwd = os.path.join(base, "shared-cwd")- os.makedirs(shared_cwd, exist_ok=True)- script_path = os.path.join(base, "faux-script.json")- with open(script_path, "w") as f:- json.dump(FAUX_SCRIPT, f, indent=2)- sandboxes = {}- for binary in ("ts", "rust"):- home = os.path.join(base, binary, "home")- agent = os.path.join(base, binary, "agent")- tmp = os.path.join(base, binary, "tmp")- os.makedirs(home, exist_ok=True)- os.makedirs(tmp, exist_ok=True)- os.makedirs(os.path.join(agent, "extensions"), exist_ok=True)- os.makedirs(os.path.join(agent, "sessions"), exist_ok=True)- with open(os.path.join(agent, "settings.json"), "w") as f:- json.dump({"onboardingCompleted": True}, f)- # The isolated TMPDIR keeps the TS supervisor's socket (the- # default daemon-socket dir) off the shared box root, so the- # cleanup reap can sweep this side's daemons by path alone.- sandboxes[binary] = {"home": home, "agent": agent, "tmp": tmp}- with open(os.path.join(sandboxes["ts"]["agent"], "extensions", "tool-card-faux.js"), "w") as f:- f.write(TS_FAUX_EXTENSION)- return shared_cwd, script_path, sandboxes---def wait_for(session, needle, timeout):- deadline = time.time() + timeout- while time.time() < deadline:- if needle in capture_plain(session):- return- time.sleep(0.3)- raise TimeoutError(f"session {session} never showed {needle!r}")---def run_session(binary, sandbox, shared_cwd, script_path, size, out_dir):- width, height = size- session = f"tcparity-{binary}-{width}x{height}"- tmux("kill-session", "-t", session, check=False)- tmux("new-session", "-d", "-s", session, "-x", width, "-y", height, "-c", shared_cwd)- env = (- f"HOME={sandbox['home']} "- f"TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"PRIME_AGENT_FAUX_SCRIPT={script_path} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- if binary == "ts":- command = (- f"prime-agent --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model faux-1"- )- else:- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "target", "debug", "prime-agent"),- )- package_dir = os.environ.get("PI_PACKAGE_DIR") or find_runtime_package_dir()- command = (- f"PI_PACKAGE_DIR={package_dir} "- f"{rust} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model faux-1"- )- tmux("send-keys", "-t", session, f"{env} {command}", "Enter")-- frames = {}- wait_for(session, "Collapsed mode", timeout=40)- time.sleep(1.0)- frames["a_fresh_start"] = capture(session)-- tmux("send-keys", "-t", session, PROMPT)- tmux("send-keys", "-t", session, "Enter")-- # First bash card runs while the turn is live (running marker).- deadline = time.time() + 60- while time.time() < deadline:- pane = capture_plain(session)- if "card checks now" in pane and "running" in pane:- frames["e_running"] = capture(session)- break- time.sleep(0.1)-- # The Rust kernel bootstrap (cold uv cache in the sandbox) can hold a- # turn open for over a minute, so the settle window is generous.- deadline = time.time() + 300- while time.time() < deadline:- pane = capture_plain(session)- if "All card states shown." in pane and not re.search(SPINNER_CLASS, pane):- break- time.sleep(0.5)- time.sleep(1.0)- # The settle poll can race a spinner frame: re-check before capturing.- for _ in range(20):- if not re.search(SPINNER_CLASS, capture_plain(session)):- break- time.sleep(0.5)- frames["b_collapsed"] = capture(session)-- # Ctrl+O once: details mode.- tmux("send-keys", "-t", session, "C-o")- try:- wait_for(session, "Details mode", timeout=10)- except TimeoutError:- pass- time.sleep(1.0)- frames["c_details"] = capture(session)-- # Ctrl+O twice: all mode (expanded).- tmux("send-keys", "-t", session, "C-o")- try:- wait_for(session, "Expanded mode", timeout=10)- except TimeoutError:- pass- time.sleep(1.0)- frames["d_all"] = capture(session)-- tmux("send-keys", "-t", session, "C-c")- time.sleep(0.5)- tmux("send-keys", "-t", session, "C-c")- time.sleep(1.0)- tmux("kill-session", "-t", session, check=False)-- os.makedirs(out_dir, exist_ok=True)- for state, frame in frames.items():- with open(os.path.join(out_dir, f"{binary}-{state}-{width}x{height}.txt"), "w") as f:- f.write(frame)- return frames---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--sizes", default=",".join(f"{w}x{h}" for w, h in SIZES))- parser.add_argument("--keep", action="store_true")- parser.add_argument("--out", default=None)- parser.add_argument("--only", default=None, choices=["ts", "rust"])- args = parser.parse_args()- sizes = [tuple(entry.split("x")) for entry in args.sizes.split(",")]-- # Fail fast before any launch: a non-TS `prime-agent` on PATH plays a- # Rust build as the "ts" side and reports false divergences.- if args.only in (None, "ts"):- ts_identity.assert_ts_side_is_the_ts_product()-- base = tempfile.mkdtemp(prefix="tool-card-parity-")- out_dir = args.out or tempfile.mkdtemp(prefix="tool-card-captures-")- shared_cwd, script_path, sandboxes = prepare_sandbox(base)- failures = []- try:- if args.only:- run_session(args.only, sandboxes[args.only], shared_cwd, script_path, sizes[0], out_dir)- print(f"captures for {args.only} in {out_dir}")- return 0- for size in sizes:- ts_frames = run_session("ts", sandboxes["ts"], shared_cwd, script_path, size, out_dir)- rust_frames = run_session("rust", sandboxes["rust"], shared_cwd, script_path, size, out_dir)- for state, _ in STATES:- if state not in ts_frames or state not in rust_frames:- continue- ts_norm = normalize(ts_frames[state], base)- rust_norm = normalize(rust_frames[state], base)- name = f"{state}-{size[0]}x{size[1]}"- if ts_norm == rust_norm:- print(f"PASS {name}")- else:- print(f"FAIL {name}")- report = os.path.join(out_dir, f"diff-{name}.txt")- with open(report, "w") as f:- f.write(diff_lines(ts_norm, rust_norm))- print(f" diff: {report}")- failures.append(name)- finally:- # Rmtree alone leaks the scenario daemons (a killed TUI pane does- # not take its detached daemon/supervisor pair down; #223): sweep- # every daemon this run spawned before deleting the sandbox.- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if not args.keep:- shutil.rmtree(base, ignore_errors=True)- if failures:- print(f"{len(failures)} state(s) differ; captures in {out_dir}")- return 1- print(f"all states match; captures in {out_dir}")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/ts_faux_extension.js b/scripts/ts_faux_extension.jsindex 6719362751..d69808f111 100644--- a/scripts/ts_faux_extension.js+++ b/scripts/ts_faux_extension.js@@ -1,5 +1,5 @@-// Shared faux-provider driver extension for the parity harnesses-// (visual_parity.py, tool_card_parity.py, compact_parity.py): registers the+// Shared faux-provider driver extension for the perf-wave dimensions+// (scripts/battery/sustained_cpu.py, stream_throughput.py): registers the// faux provider with scripted responses read from PRIME_AGENT_FAUX_SCRIPT// (same harness contract the Rust rewrite uses). Verification harness only;// never installed for real users.diff --git a/scripts/tui-polish-runs/2026-09-22-tui-polish/README.md b/scripts/tui-polish-runs/2026-09-22-tui-polish/README.mddeleted file mode 100644index 38a7bc8dd8..0000000000--- a/scripts/tui-polish-runs/2026-09-22-tui-polish/README.md+++ /dev/null@@ -1,42 +0,0 @@-# tui-polish parity evidence (2026-09-22)--Verifier: `scripts/tui_polish_parity.py` (lane tui-polish). Both sides run on-this box under tmux (120x90); the ts side is the deployed TS release-`0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent`-(the box PATH `prime-agent` is currently a Rust dogfood install of this repo,-so the harness takes TS_BIN explicitly; `ts_identity.assert_ts_side_is_the_ts_product`-guards the binary used). The rust side is the worktree's-`target/debug/{prime-agent,pa-tui-replay}` at this branch's HEAD.--Result (both PASS; captures regenerated from the final tree at HEAD):-- PASS replay-a_collapsed-120x90 (byte-identical)- PASS replay-b_details-120x90 (byte-identical)- PASS replay-c_all-120x90 (byte-identical)- PASS loader-row (byte-identical rows, ESC[39m gap reset)--A second fix landed before the final rerun: the markdown block-cache key now-carries the fence lang (TS keys on `token.raw`, which includes the info-string) - without it a cached ```python final block could serve its token-colors to a same-content ```json block during streaming (adopted from-tui-polish-v2's review; regression test-`block_cache_does_not_carry_token_colors_across_langs`).--Files:--- `ts-*-120x90.txt` / `rust-*-120x90.txt`: the three detail states per side,- captured with `tmux capture-pane -e` (ANSI retained).-- `loader-probe-frames.txt`: dense mid-stream captures while the working- loader was up on both sides (slow reasoning mock).-- `loader-rows.txt`: the normalized loader rows (spinner/elapsed/token- count normalized; SGR placement retained) — byte-identical sets.--The replay fixture's assistant text carries a ```python fence (keywords,-built-ins, numbers, f-strings, def header, comment, literal), a bare fence-(uniform fallback), and a ```python title=x fence (marked passes the whole-info string as the lang, hljs has no such language -> uniform).--Found by the frame-diff on the first post-fix run: `header_mode` consumed the-`(` of a def/class params group without emitting it (text loss on the-expanded-ipynb surface too) - fixed together with the token-color wiring;-see the `def_header_line_text_is_lossless` test in `tool_card/highlight.rs`.diff --git a/scripts/tui-polish-runs/2026-09-22-tui-polish/loader-probe-frames.txt b/scripts/tui-polish-runs/2026-09-22-tui-polish/loader-probe-frames.txtdeleted file mode 100644index 89a7223a0b..0000000000--- a/scripts/tui-polish-runs/2026-09-22-tui-polish/loader-probe-frames.txt+++ /dev/null@@ -1,4416 +0,0 @@-===== ts-00- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== ts-01- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠙[39m [38;2;161;161;170mThinking · 0s · ↓ 15 tokens[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 15 (0%)--===== ts-02- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠼[39m [38;2;161;161;170mThinking · 0s · ↓ 15 tokens[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 15 (0%)--===== ts-03- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠦[39m [38;2;161;161;170mThinking · 0s · ↓ 15 tokens[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 15 (0%)--===== ts-04- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠏[39m [38;2;161;161;170mThinking · 0s · ↓ 28 tokens[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 28 (0%)--===== ts-05- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠹[39m [38;2;161;161;170mThinking · 0s · ↓ 28 tokens[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 28 (0%)--===== ts-06- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠼[39m [38;2;161;161;170mThinking · 1s · ↓ 28 tokens[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 28 (0%)--===== ts-07- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠧[39m [38;2;161;161;170mThinking · 1s · ↓ 28 tokens[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 28 (0%)--===== ts-08- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠏[39m [38;2;161;161;170mThinking · 1s · ↓ 41 tokens[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 41 (0%)--===== ts-09- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠹[39m [38;2;161;161;170mThinking · 1s · ↓ 41 tokens[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 41 (0%)--===== ts-10- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠴[39m [38;2;161;161;170mThinking · 2s · ↓ 41 tokens[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 41 (0%)--===== ts-11- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m-- [38;2;124;111;175m⠧[39m [38;2;161;161;170mWriting · 2s · ↓ 49 tokens[39m--------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 49 (0%)--===== ts-12- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m-- [38;2;124;111;175m⠋[39m [38;2;161;161;170mWriting · 2s · ↓ 49 tokens[39m--------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 49 (0%)--===== ts-13- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m-- [38;2;124;111;175m⠸[39m [38;2;161;161;170mWriting · 2s · ↓ 49 tokens[39m--------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 49 (0%)--===== ts-14- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m-- [38;2;124;111;175m⠦[39m [38;2;161;161;170mWriting · 2s · ↓ 49 tokens[39m--------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 49 (0%)--===== ts-15- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m-- [38;2;124;111;175m⠇[39m [38;2;161;161;170mWriting · 3s · ↓ 49 tokens[39m--------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 49 (0%)--===== ts-16- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m-- [38;2;124;111;175m⠙[39m [38;2;161;161;170mWriting · 3s · ↓ 49 tokens[39m--------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 49 (0%)--===== ts-17- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m-- [38;2;124;111;175m⠼[39m [38;2;161;161;170mWriting · 3s · ↓ 49 tokens[39m--------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 49 (0%)--===== ts-18- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== ts-19- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== ts-20- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== ts-21- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== ts-22- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== ts-23- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== rust-00- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > s[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-01- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-02- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the l[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-03- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader p[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-04- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parity pro[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-05- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--- [38;2;124;111;175m⠋[39m [38;2;161;161;170mWaiting · 0s[39m-------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-06- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠹[39m [38;2;161;161;170mWaiting · 0s[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-07- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠴[39m [38;2;161;161;170mThinking · 0s · ↓ 15 tokens-----------------------------------------------------------------------[39m [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-08- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠇[39m [38;2;161;161;170mThinking · 0s · ↓ 15 tokens-----------------------------------------------------------------------[39m [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-09- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠙[39m [38;2;161;161;170mThinking · 0s · ↓ 15 tokens-----------------------------------------------------------------------[39m [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-10- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠼[39m [38;2;161;161;170mThinking · 1s · ↓ 28 tokens-----------------------------------------------------------------------[39m [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-11- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠦[39m [38;2;161;161;170mThinking · 1s · ↓ 28 tokens-----------------------------------------------------------------------[39m [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-12- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠏[39m [38;2;161;161;170mThinking · 1s · ↓ 28 tokens-----------------------------------------------------------------------[39m [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-13- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠸[39m [38;2;161;161;170mThinking · 1s · ↓ 41 tokens-----------------------------------------------------------------------[39m [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-14- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠦[39m [38;2;161;161;170mThinking · 2s · ↓ 41 tokens-----------------------------------------------------------------------[39m [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-15- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠇[39m [38;2;161;161;170mThinking · 2s · ↓ 41 tokens-----------------------------------------------------------------------[39m [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-16- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m-- [38;2;124;111;175m⠙[39m [38;2;161;161;170mWriting · 2s · ↓ 49 tokens[39m--------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-17- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m-- [38;2;124;111;175m⠼[39m [38;2;161;161;170mWriting · 2s · ↓ 49 tokens[39m--------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-18- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m-- [38;2;124;111;175m⠦[39m [38;2;161;161;170mWriting · 2s · ↓ 49 tokens[39m--------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-19- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m-- [38;2;124;111;175m⠋[39m [38;2;161;161;170mWriting · 3s · ↓ 49 tokens[39m--------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-20- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m-- [38;2;124;111;175m⠹[39m [38;2;161;161;170mWriting · 3s · ↓ 49 tokens[39m--------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-21- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m-- [38;2;124;111;175m⠸[39m [38;2;161;161;170mWriting · 3s · ↓ 49 tokens[39m--------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-22- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m-- [38;2;124;111;175m⠇[39m [38;2;161;161;170mWriting · 3s · ↓ 49 tokens[39m--------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-23- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;216;216;220mLive body text after thinking.[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)-diff --git a/scripts/tui-polish-runs/2026-09-22-tui-polish/loader-rows.txt b/scripts/tui-polish-runs/2026-09-22-tui-polish/loader-rows.txtdeleted file mode 100644index 5f8ed5c192..0000000000--- a/scripts/tui-polish-runs/2026-09-22-tui-polish/loader-rows.txt+++ /dev/null@@ -1,4 +0,0 @@-===== ts normalized loader rows-'\x1b[49m \x1b[38;2;124;111;175m<SPIN>\x1b[39m \x1b[38;2;161;161;170mThinking · <T> · <DIR> <TOK> tokens'-===== rust normalized loader rows-'\x1b[49m \x1b[38;2;124;111;175m<SPIN>\x1b[39m \x1b[38;2;161;161;170mThinking · <T> · <DIR> <TOK> tokens'diff --git a/scripts/tui-polish-runs/2026-09-22-tui-polish/rust-a_collapsed-120x90.txt b/scripts/tui-polish-runs/2026-09-22-tui-polish/rust-a_collapsed-120x90.txtdeleted file mode 100644index a771114357..0000000000--- a/scripts/tui-polish-runs/2026-09-22-tui-polish/rust-a_collapsed-120x90.txt+++ /dev/null@@ -1,90 +0,0 @@--- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mcwd-[39m ▗▟▌ ▐███▛▘▗▄█▖- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- TUI polish parity probe.---[49m [38;2;216;216;220mThe parity code block:[39m-- [38;2;56;189;248mdef[39m [38;2;56;189;248mgutter_probe[39m([38;2;212;212;216mcount=[38;2;245;158;11m7[39m):- [38;2;161;161;170m# probe comment[39m- total = [38;2;245;158;11m0[39m- [38;2;56;189;248mfor[39m i [38;2;56;189;248min[39m [38;2;245;158;11mrange[39m(count):- [38;2;245;158;11mprint[39m([38;2;139;168;136mf"line {i}"[39m)- total += i- [38;2;56;189;248mif[39m total [38;2;56;189;248mis[39m [38;2;56;189;248mnot[39m [38;2;245;158;11mNone[39m:- [38;2;56;189;248mreturn[39m total-- gutter_probe([38;2;245;158;11m3[39m)-- [38;2;216;216;220mA bare fence stays uniform:[39m-- [38;2;139;168;136mplain code line[39m-- [38;2;216;216;220mAn attribute fence stays uniform:[39m-- [38;2;139;168;136mattribute code line[39m-- [38;2;216;216;220mFINAL thinking parity marker reached.[39m-------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--diff --git a/scripts/tui-polish-runs/2026-09-22-tui-polish/rust-b_details-120x90.txt b/scripts/tui-polish-runs/2026-09-22-tui-polish/rust-b_details-120x90.txtdeleted file mode 100644index 88defdb7f5..0000000000--- a/scripts/tui-polish-runs/2026-09-22-tui-polish/rust-b_details-120x90.txt+++ /dev/null@@ -1,90 +0,0 @@--- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mcwd-[39m ▗▟▌ ▐███▛▘▗▄█▖- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- TUI polish parity probe.---[49m [38;2;216;216;220mThe parity code block:[39m-- [38;2;56;189;248mdef[39m [38;2;56;189;248mgutter_probe[39m([38;2;212;212;216mcount=[38;2;245;158;11m7[39m):- [38;2;161;161;170m# probe comment[39m- total = [38;2;245;158;11m0[39m- [38;2;56;189;248mfor[39m i [38;2;56;189;248min[39m [38;2;245;158;11mrange[39m(count):- [38;2;245;158;11mprint[39m([38;2;139;168;136mf"line {i}"[39m)- total += i- [38;2;56;189;248mif[39m total [38;2;56;189;248mis[39m [38;2;56;189;248mnot[39m [38;2;245;158;11mNone[39m:- [38;2;56;189;248mreturn[39m total-- gutter_probe([38;2;245;158;11m3[39m)-- [38;2;216;216;220mA bare fence stays uniform:[39m-- [38;2;139;168;136mplain code line[39m-- [38;2;216;216;220mAn attribute fence stays uniform:[39m-- [38;2;139;168;136mattribute code line[39m-- [38;2;216;216;220mFINAL thinking parity marker reached.[39m-------------------------------------------------- [38;2;113;113;122mDetails mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--diff --git a/scripts/tui-polish-runs/2026-09-22-tui-polish/rust-c_all-120x90.txt b/scripts/tui-polish-runs/2026-09-22-tui-polish/rust-c_all-120x90.txtdeleted file mode 100644index 1725ab8b9f..0000000000--- a/scripts/tui-polish-runs/2026-09-22-tui-polish/rust-c_all-120x90.txt+++ /dev/null@@ -1,90 +0,0 @@--- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mcwd-[39m ▗▟▌ ▐███▛▘▗▄█▖- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- TUI polish parity probe.---[49m [38;2;216;216;220mThe parity code block:[39m-- [38;2;56;189;248mdef[39m [38;2;56;189;248mgutter_probe[39m([38;2;212;212;216mcount=[38;2;245;158;11m7[39m):- [38;2;161;161;170m# probe comment[39m- total = [38;2;245;158;11m0[39m- [38;2;56;189;248mfor[39m i [38;2;56;189;248min[39m [38;2;245;158;11mrange[39m(count):- [38;2;245;158;11mprint[39m([38;2;139;168;136mf"line {i}"[39m)- total += i- [38;2;56;189;248mif[39m total [38;2;56;189;248mis[39m [38;2;56;189;248mnot[39m [38;2;245;158;11mNone[39m:- [38;2;56;189;248mreturn[39m total-- gutter_probe([38;2;245;158;11m3[39m)-- [38;2;216;216;220mA bare fence stays uniform:[39m-- [38;2;139;168;136mplain code line[39m-- [38;2;216;216;220mAn attribute fence stays uniform:[39m-- [38;2;139;168;136mattribute code line[39m-- [38;2;216;216;220mFINAL thinking parity marker reached.[39m-------------------------------------------------- [38;2;113;113;122mExpanded mode (Ctrl+O to collapse)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--diff --git a/scripts/tui-polish-runs/2026-09-22-tui-polish/ts-a_collapsed-120x90.txt b/scripts/tui-polish-runs/2026-09-22-tui-polish/ts-a_collapsed-120x90.txtdeleted file mode 100644index 65941c4c0b..0000000000--- a/scripts/tui-polish-runs/2026-09-22-tui-polish/ts-a_collapsed-120x90.txt+++ /dev/null@@ -1,90 +0,0 @@- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mz-ai/glm-5.3[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- TUI polish parity probe.---[49m [38;2;216;216;220mThe parity code block:[39m-- [38;2;56;189;248mdef[39m [38;2;56;189;248mgutter_probe[39m([38;2;212;212;216mcount=[38;2;245;158;11m7[39m):- [38;2;161;161;170m# probe comment[39m- total = [38;2;245;158;11m0[39m- [38;2;56;189;248mfor[39m i [38;2;56;189;248min[39m [38;2;245;158;11mrange[39m(count):- [38;2;245;158;11mprint[39m([38;2;139;168;136mf"line {i}"[39m)- total += i- [38;2;56;189;248mif[39m total [38;2;56;189;248mis[39m [38;2;56;189;248mnot[39m [38;2;245;158;11mNone[39m:- [38;2;56;189;248mreturn[39m total-- gutter_probe([38;2;245;158;11m3[39m)-- [38;2;216;216;220mA bare fence stays uniform:[39m-- [38;2;139;168;136mplain code line[39m-- [38;2;216;216;220mAn attribute fence stays uniform:[39m-- [38;2;139;168;136mattribute code line[39m-- [38;2;216;216;220mFINAL thinking parity marker reached.[39m-------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mz-ai/glm-5.3:high · 8.8k (1%)diff --git a/scripts/tui-polish-runs/2026-09-22-tui-polish/ts-b_details-120x90.txt b/scripts/tui-polish-runs/2026-09-22-tui-polish/ts-b_details-120x90.txtdeleted file mode 100644index 4c403fc781..0000000000--- a/scripts/tui-polish-runs/2026-09-22-tui-polish/ts-b_details-120x90.txt+++ /dev/null@@ -1,90 +0,0 @@- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mz-ai/glm-5.3[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- TUI polish parity probe.---[49m [38;2;216;216;220mThe parity code block:[39m-- [38;2;56;189;248mdef[39m [38;2;56;189;248mgutter_probe[39m([38;2;212;212;216mcount=[38;2;245;158;11m7[39m):- [38;2;161;161;170m# probe comment[39m- total = [38;2;245;158;11m0[39m- [38;2;56;189;248mfor[39m i [38;2;56;189;248min[39m [38;2;245;158;11mrange[39m(count):- [38;2;245;158;11mprint[39m([38;2;139;168;136mf"line {i}"[39m)- total += i- [38;2;56;189;248mif[39m total [38;2;56;189;248mis[39m [38;2;56;189;248mnot[39m [38;2;245;158;11mNone[39m:- [38;2;56;189;248mreturn[39m total-- gutter_probe([38;2;245;158;11m3[39m)-- [38;2;216;216;220mA bare fence stays uniform:[39m-- [38;2;139;168;136mplain code line[39m-- [38;2;216;216;220mAn attribute fence stays uniform:[39m-- [38;2;139;168;136mattribute code line[39m-- [38;2;216;216;220mFINAL thinking parity marker reached.[39m-------------------------------------------------- [38;2;113;113;122mDetails mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mz-ai/glm-5.3:high · 8.8k (1%)diff --git a/scripts/tui-polish-runs/2026-09-22-tui-polish/ts-c_all-120x90.txt b/scripts/tui-polish-runs/2026-09-22-tui-polish/ts-c_all-120x90.txtdeleted file mode 100644index 342b3f853f..0000000000--- a/scripts/tui-polish-runs/2026-09-22-tui-polish/ts-c_all-120x90.txt+++ /dev/null@@ -1,90 +0,0 @@- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mz-ai/glm-5.3[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-pywg9nph/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- TUI polish parity probe.---[49m [38;2;216;216;220mThe parity code block:[39m-- [38;2;56;189;248mdef[39m [38;2;56;189;248mgutter_probe[39m([38;2;212;212;216mcount=[38;2;245;158;11m7[39m):- [38;2;161;161;170m# probe comment[39m- total = [38;2;245;158;11m0[39m- [38;2;56;189;248mfor[39m i [38;2;56;189;248min[39m [38;2;245;158;11mrange[39m(count):- [38;2;245;158;11mprint[39m([38;2;139;168;136mf"line {i}"[39m)- total += i- [38;2;56;189;248mif[39m total [38;2;56;189;248mis[39m [38;2;56;189;248mnot[39m [38;2;245;158;11mNone[39m:- [38;2;56;189;248mreturn[39m total-- gutter_probe([38;2;245;158;11m3[39m)-- [38;2;216;216;220mA bare fence stays uniform:[39m-- [38;2;139;168;136mplain code line[39m-- [38;2;216;216;220mAn attribute fence stays uniform:[39m-- [38;2;139;168;136mattribute code line[39m-- [38;2;216;216;220mFINAL thinking parity marker reached.[39m-------------------------------------------------- [38;2;113;113;122mExpanded mode (Ctrl+O to collapse)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mz-ai/glm-5.3:high · 8.8k (1%)diff --git a/scripts/tui-polish-runs/2026-09-23-tui-polish/loader-probe-frames.txt b/scripts/tui-polish-runs/2026-09-23-tui-polish/loader-probe-frames.txtdeleted file mode 100644index 3a264c3897..0000000000--- a/scripts/tui-polish-runs/2026-09-23-tui-polish/loader-probe-frames.txt+++ /dev/null@@ -1,4416 +0,0 @@-===== ts-00-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-01-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-02-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-03-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-04-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-05-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-06-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-07-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-08-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-09-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-10-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-11-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-12-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-13-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-14-HOME=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/home TMPDIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/tmp PRIME_AGENT_CODING_-AGENT_DIR=/tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent PRIME_AGENT_DISABLE_ANALYTICS=1 /home/ubuntu/.local/share/prime--agent/releases/0.9.5-linux-x64-bc4b0ed791d1e8b3b5d6a95249a60306d9579fc0d6038e5d7d82f068d81f008d/prime-agent --provider-prime-inference --model mock-1 --offline --daemon-socket /tmp/mission-tmp/tui-polish-63lo7ujb/ts/agent/daemon.sock-- ____ _ ____ __ ____ __- / __ \_____(_)___ ___ ___ / _/___ / /____ / / /__ _____/ /_- / /_/ / ___/ / __ `__ \/ _ \ / // __ \/ __/ _ \/ / / _ \/ ___/ __/- / ____/ / / / / / / / / __// // / / / /_/ __/ / / __/ /__/ /_-/_/ /_/ /_/_/ /_/ /_/\___/___/_/ /_/\__/\___/_/_/\___/\___/\__/--$ say the loader parity probe--------------------------------------------------------------------------------===== ts-15--------------------------------------------------------------------------------------------===== ts-16- cwd-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘---------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parity probe- [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== ts-17- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘---------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parity probe- [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== ts-18- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘---------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parity probe- [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== ts-19- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘---------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parity probe- [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== ts-20- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘---------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parity probe- [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== ts-21- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘---------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parity probe- [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== ts-22- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘---------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parity probe- [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== ts-23- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘---------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parity probe- [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1:medium · 0 (0%)--===== rust-00- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > s[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-01- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > sa[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-02- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-03- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say t[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-04- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say th[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-05- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-06- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-07- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the l[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-08- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loa[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-09- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the load[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-10- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loade[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-11- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-12- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader p[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-13- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader pa[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-14- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader pari[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-15- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parit[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-16- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parity[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-17- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parity [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-18- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parity pr[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-19- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parity pro[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-20- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘----------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > say the loader parity probe[7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-21- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--- [38;2;124;111;175m⠋[39m [38;2;161;161;170mWaiting · 0s[39m-------------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-22- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠹[39m [38;2;161;161;170mWaiting · 0s[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)--===== rust-23- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.1.0[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mmock-1[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- say the loader parity probe---[49m [38;2;124;111;175m⠼[39m [38;2;161;161;170mWaiting · 0s[39m----------------------------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mmock-1 · 0 (0%)-diff --git a/scripts/tui-polish-runs/2026-09-23-tui-polish/loader-rows.txt b/scripts/tui-polish-runs/2026-09-23-tui-polish/loader-rows.txtdeleted file mode 100644index 6db04a1c8c..0000000000--- a/scripts/tui-polish-runs/2026-09-23-tui-polish/loader-rows.txt+++ /dev/null@@ -1,2 +0,0 @@-===== ts normalized loader rows-===== rust normalized loader rowsdiff --git a/scripts/tui-polish-runs/2026-09-23-tui-polish/rust-a_collapsed-120x90.txt b/scripts/tui-polish-runs/2026-09-23-tui-polish/rust-a_collapsed-120x90.txtdeleted file mode 100644index a771114357..0000000000--- a/scripts/tui-polish-runs/2026-09-23-tui-polish/rust-a_collapsed-120x90.txt+++ /dev/null@@ -1,90 +0,0 @@--- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mcwd-[39m ▗▟▌ ▐███▛▘▗▄█▖- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- TUI polish parity probe.---[49m [38;2;216;216;220mThe parity code block:[39m-- [38;2;56;189;248mdef[39m [38;2;56;189;248mgutter_probe[39m([38;2;212;212;216mcount=[38;2;245;158;11m7[39m):- [38;2;161;161;170m# probe comment[39m- total = [38;2;245;158;11m0[39m- [38;2;56;189;248mfor[39m i [38;2;56;189;248min[39m [38;2;245;158;11mrange[39m(count):- [38;2;245;158;11mprint[39m([38;2;139;168;136mf"line {i}"[39m)- total += i- [38;2;56;189;248mif[39m total [38;2;56;189;248mis[39m [38;2;56;189;248mnot[39m [38;2;245;158;11mNone[39m:- [38;2;56;189;248mreturn[39m total-- gutter_probe([38;2;245;158;11m3[39m)-- [38;2;216;216;220mA bare fence stays uniform:[39m-- [38;2;139;168;136mplain code line[39m-- [38;2;216;216;220mAn attribute fence stays uniform:[39m-- [38;2;139;168;136mattribute code line[39m-- [38;2;216;216;220mFINAL thinking parity marker reached.[39m-------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--diff --git a/scripts/tui-polish-runs/2026-09-23-tui-polish/rust-b_details-120x90.txt b/scripts/tui-polish-runs/2026-09-23-tui-polish/rust-b_details-120x90.txtdeleted file mode 100644index 88defdb7f5..0000000000--- a/scripts/tui-polish-runs/2026-09-23-tui-polish/rust-b_details-120x90.txt+++ /dev/null@@ -1,90 +0,0 @@--- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mcwd-[39m ▗▟▌ ▐███▛▘▗▄█▖- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- TUI polish parity probe.---[49m [38;2;216;216;220mThe parity code block:[39m-- [38;2;56;189;248mdef[39m [38;2;56;189;248mgutter_probe[39m([38;2;212;212;216mcount=[38;2;245;158;11m7[39m):- [38;2;161;161;170m# probe comment[39m- total = [38;2;245;158;11m0[39m- [38;2;56;189;248mfor[39m i [38;2;56;189;248min[39m [38;2;245;158;11mrange[39m(count):- [38;2;245;158;11mprint[39m([38;2;139;168;136mf"line {i}"[39m)- total += i- [38;2;56;189;248mif[39m total [38;2;56;189;248mis[39m [38;2;56;189;248mnot[39m [38;2;245;158;11mNone[39m:- [38;2;56;189;248mreturn[39m total-- gutter_probe([38;2;245;158;11m3[39m)-- [38;2;216;216;220mA bare fence stays uniform:[39m-- [38;2;139;168;136mplain code line[39m-- [38;2;216;216;220mAn attribute fence stays uniform:[39m-- [38;2;139;168;136mattribute code line[39m-- [38;2;216;216;220mFINAL thinking parity marker reached.[39m-------------------------------------------------- [38;2;113;113;122mDetails mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--diff --git a/scripts/tui-polish-runs/2026-09-23-tui-polish/rust-c_all-120x90.txt b/scripts/tui-polish-runs/2026-09-23-tui-polish/rust-c_all-120x90.txtdeleted file mode 100644index 1725ab8b9f..0000000000--- a/scripts/tui-polish-runs/2026-09-23-tui-polish/rust-c_all-120x90.txt+++ /dev/null@@ -1,90 +0,0 @@--- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mcwd-[39m ▗▟▌ ▐███▛▘▗▄█▖- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- TUI polish parity probe.---[49m [38;2;216;216;220mThe parity code block:[39m-- [38;2;56;189;248mdef[39m [38;2;56;189;248mgutter_probe[39m([38;2;212;212;216mcount=[38;2;245;158;11m7[39m):- [38;2;161;161;170m# probe comment[39m- total = [38;2;245;158;11m0[39m- [38;2;56;189;248mfor[39m i [38;2;56;189;248min[39m [38;2;245;158;11mrange[39m(count):- [38;2;245;158;11mprint[39m([38;2;139;168;136mf"line {i}"[39m)- total += i- [38;2;56;189;248mif[39m total [38;2;56;189;248mis[39m [38;2;56;189;248mnot[39m [38;2;245;158;11mNone[39m:- [38;2;56;189;248mreturn[39m total-- gutter_probe([38;2;245;158;11m3[39m)-- [38;2;216;216;220mA bare fence stays uniform:[39m-- [38;2;139;168;136mplain code line[39m-- [38;2;216;216;220mAn attribute fence stays uniform:[39m-- [38;2;139;168;136mattribute code line[39m-- [38;2;216;216;220mFINAL thinking parity marker reached.[39m-------------------------------------------------- [38;2;113;113;122mExpanded mode (Ctrl+O to collapse)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--diff --git a/scripts/tui-polish-runs/2026-09-23-tui-polish/ts-a_collapsed-120x90.txt b/scripts/tui-polish-runs/2026-09-23-tui-polish/ts-a_collapsed-120x90.txtdeleted file mode 100644index f648b3f75e..0000000000--- a/scripts/tui-polish-runs/2026-09-23-tui-polish/ts-a_collapsed-120x90.txt+++ /dev/null@@ -1,90 +0,0 @@- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mz-ai/glm-5.3[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- TUI polish parity probe.---[49m [38;2;216;216;220mThe parity code block:[39m-- [38;2;56;189;248mdef[39m [38;2;56;189;248mgutter_probe[39m([38;2;212;212;216mcount=[38;2;245;158;11m7[39m):- [38;2;161;161;170m# probe comment[39m- total = [38;2;245;158;11m0[39m- [38;2;56;189;248mfor[39m i [38;2;56;189;248min[39m [38;2;245;158;11mrange[39m(count):- [38;2;245;158;11mprint[39m([38;2;139;168;136mf"line {i}"[39m)- total += i- [38;2;56;189;248mif[39m total [38;2;56;189;248mis[39m [38;2;56;189;248mnot[39m [38;2;245;158;11mNone[39m:- [38;2;56;189;248mreturn[39m total-- gutter_probe([38;2;245;158;11m3[39m)-- [38;2;216;216;220mA bare fence stays uniform:[39m-- [38;2;139;168;136mplain code line[39m-- [38;2;216;216;220mAn attribute fence stays uniform:[39m-- [38;2;139;168;136mattribute code line[39m-- [38;2;216;216;220mFINAL thinking parity marker reached.[39m-------------------------------------------------- [38;2;113;113;122mCollapsed mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mz-ai/glm-5.3:high · 10k (1%)diff --git a/scripts/tui-polish-runs/2026-09-23-tui-polish/ts-b_details-120x90.txt b/scripts/tui-polish-runs/2026-09-23-tui-polish/ts-b_details-120x90.txtdeleted file mode 100644index d1a2fe4b9e..0000000000--- a/scripts/tui-polish-runs/2026-09-23-tui-polish/ts-b_details-120x90.txt+++ /dev/null@@ -1,90 +0,0 @@- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mz-ai/glm-5.3[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- TUI polish parity probe.---[49m [38;2;216;216;220mThe parity code block:[39m-- [38;2;56;189;248mdef[39m [38;2;56;189;248mgutter_probe[39m([38;2;212;212;216mcount=[38;2;245;158;11m7[39m):- [38;2;161;161;170m# probe comment[39m- total = [38;2;245;158;11m0[39m- [38;2;56;189;248mfor[39m i [38;2;56;189;248min[39m [38;2;245;158;11mrange[39m(count):- [38;2;245;158;11mprint[39m([38;2;139;168;136mf"line {i}"[39m)- total += i- [38;2;56;189;248mif[39m total [38;2;56;189;248mis[39m [38;2;56;189;248mnot[39m [38;2;245;158;11mNone[39m:- [38;2;56;189;248mreturn[39m total-- gutter_probe([38;2;245;158;11m3[39m)-- [38;2;216;216;220mA bare fence stays uniform:[39m-- [38;2;139;168;136mplain code line[39m-- [38;2;216;216;220mAn attribute fence stays uniform:[39m-- [38;2;139;168;136mattribute code line[39m-- [38;2;216;216;220mFINAL thinking parity marker reached.[39m-------------------------------------------------- [38;2;113;113;122mDetails mode (Ctrl+O to expand)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mz-ai/glm-5.3:high · 10k (1%)diff --git a/scripts/tui-polish-runs/2026-09-23-tui-polish/ts-c_all-120x90.txt b/scripts/tui-polish-runs/2026-09-23-tui-polish/ts-c_all-120x90.txtdeleted file mode 100644index 3d2377ea69..0000000000--- a/scripts/tui-polish-runs/2026-09-23-tui-polish/ts-c_all-120x90.txt+++ /dev/null@@ -1,90 +0,0 @@- cwd [38;2;113;113;122m$0.00[39m-- ▗▄▄█▀- ███▄ ▗▄███▀- ▗█▛▐█▙ ▗▄█▀▗█▀ prime agent [38;2;161;161;170mv0.9.5[39m- ▗█▛ ▟██▙▄██▛ ▟▛ [38;2;113;113;122mmodel [38;2;161;161;170mz-ai/glm-5.3[39m- ▗▟▌ ▐███▛▘▗▄█▖ [38;2;113;113;122mcwd [38;2;161;161;170m/tmp/mission-tmp/tui-polish-63lo7ujb/cwd[39m- ▟███▄ ▄▄▟███▀- ▜█▛▀▘ ▜█▛▀▘--[48;2;26;26;31m- TUI polish parity probe.---[49m [38;2;216;216;220mThe parity code block:[39m-- [38;2;56;189;248mdef[39m [38;2;56;189;248mgutter_probe[39m([38;2;212;212;216mcount=[38;2;245;158;11m7[39m):- [38;2;161;161;170m# probe comment[39m- total = [38;2;245;158;11m0[39m- [38;2;56;189;248mfor[39m i [38;2;56;189;248min[39m [38;2;245;158;11mrange[39m(count):- [38;2;245;158;11mprint[39m([38;2;139;168;136mf"line {i}"[39m)- total += i- [38;2;56;189;248mif[39m total [38;2;56;189;248mis[39m [38;2;56;189;248mnot[39m [38;2;245;158;11mNone[39m:- [38;2;56;189;248mreturn[39m total-- gutter_probe([38;2;245;158;11m3[39m)-- [38;2;216;216;220mA bare fence stays uniform:[39m-- [38;2;139;168;136mplain code line[39m-- [38;2;216;216;220mAn attribute fence stays uniform:[39m-- [38;2;139;168;136mattribute code line[39m-- [38;2;216;216;220mFINAL thinking parity marker reached.[39m-------------------------------------------------- [38;2;113;113;122mExpanded mode (Ctrl+O to collapse)[39m-[48;2;26;26;31m- > [7m [0m[39m[48;2;26;26;31m--[38;2;113;113;122m[49m←[38;2;161;161;170m manage[39m [38;2;113;113;122mz-ai/glm-5.3:high · 10k (1%)diff --git a/scripts/tui_exit_restore_parity.py b/scripts/tui_exit_restore_parity.pydeleted file mode 100644index 80c280ccb1..0000000000--- a/scripts/tui_exit_restore_parity.py+++ /dev/null@@ -1,684 +0,0 @@-#!/usr/bin/env python3-"""The TUI exit-path terminal restoration battery (tmux e2e).--Kevin's live report (the paper-cut family): exiting the TUI can leave the-terminal broken three ways — the alternate screen still on (the shell-prompt renders inside the dead TUI frame, "the old TUI above it"), the tty-raw ("escape codes while typing"), and enhancement modes left armed-(kitty CSI-u / SGR mouse reports leaking into the shell). This battery-kills the TUI through every exit path on a REAL terminal (an isolated tmux-server, plain bash in the pane) and asserts the three invariants of a-whole terminal:-- (i) the alternate screen is left — `#{alternate_on}` is 0 after the- process exits (and 1 while the TUI runs, the vacuity gate);- (ii) the tty is cooked — the pane shell's `stty -g` after the exit- matches the pre-launch capture (for the poisoned-start scenario,- the sane baseline captured before anything ran);- (iii) no escape bytes leak — typing `echo <literal>` into the shell- after the exit echoes the literal line (no CSI/kitty/mouse- sequences interleaved, `capture-pane -e`).--Scenarios (each runs against its own daemon socket + sandbox + tmux-server):--- `quit`: the canonical exit — Ctrl+C pair (hint, then exit) on a settled- chat. The flushed inline transcript above the prompt is TS parity- (`TUI.stop`'s exitFullscreen flush), not a failure.-- `quit-slash`: `/quit`.-- `agents-exit`: the agents view (`--resume` bare) exits via its own- Ctrl+C pair — the view's teardown owns the same restore.-- `error-exit`: the worker is SIGSTOPped mid-session, then a prompt is- submitted into it — the parked request's bound is the fatal error the- loop propagates; the exit must still hand the terminal back whole.-- `wedge`: the worker stays stopped and the parked double Ctrl+C fires- the force-quit watchdog — the exit-within-2s contract.-- `poisoned`: the shell enters `stty raw -echo` (a previous run's broken- exit) BEFORE the launch; a normal quit must still end cooked — the- crossterm saved-original is poisoned, so only the exit's cooked-tty- verification/repair can fix it.-- `panic` (rust sides only): `pa-tui-replay --panic-exit` panics mid-loop- — the unwind restore must still fire and the process must die 101.--Sides: `ts` (the deployed TS release binary), `rust` (the branch build),-`before` (the recorded pre-fix build, failures recorded not gated). The-rust-only mechanical paths (error-exit / wedge / panic) run rust sides;-the TS side runs the visible-shell-state paths it owns the same contract-for (its exits must leave the shell whole too). The force-quit watchdog-itself is a rust-only port surface (TS has no watchdog — its own loop-exit handles the pair).--Usage:- scripts/tui_exit_restore_parity.py --sides ts,rust \- --rust-bin target/release/prime-agent --out runs/exits- scripts/tui_exit_restore_parity.py --sides rust --scenarios quit,poisoned--Requires tmux + a POSIX shell; the worker-pid discovery reads /proc-(Linux). On non-Linux the worker scenarios are skipped (the VM runs them).-"""--import argparse-import glob-import json-import os-import re-import signal-import subprocess-import sys-import tempfile-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-import visual_parity as vp # noqa: E402--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import ts_identity # noqa: E402--SIZE = (120, 36)--#: The deployed TS release binary (parity side).-_release_glob = os.path.expanduser(- "~/.local/share/prime-agent/releases/0.9.5-linux-x64-*/prime-agent"-)-_release_hits = sorted(glob.glob(_release_glob))-TS_BIN = os.environ.get("TS_BIN") or (_release_hits[-1] if _release_hits else "prime-agent")-RUST_BIN = os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)), "..", "target", "release", "prime-agent"- ),-)-REPLAY_BIN = os.environ.get("PA_REPLAY_BINARY")--#: The chat-settle needle (side-agnostic: the TS detail hint reads-#: "Details mode", the rust port "Collapsed mode", both carry the key-#: hint) and the agents-view roster surface needle.-CHAT_SETTLE = "Ctrl+O to expand"-AGENTS_VIEW_NEEDLE = " idle, "-RESUME_HINT_NEEDLE = "Resume this session with"--#: The worker-role marker in a daemon worker's environment (this sandbox's-#: own processes only — matched with the sandbox agent dir, never a bare-#: pattern; other daemons on the box are untouched).-WORKER_ROLE_MARKER = b"PRIME_AGENT_INTERNAL_DAEMON_WORKER=1"--#: How long a parked UI request takes to hit its bound and exit fatally-#: (the error-exit scenario waits for the shell prompt on this budget).-ERROR_EXIT_WAIT_S = 90--FAUX_SCRIPT = {- "engine": "faux",- "modelId": "faux-1",- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 18,- "responses": [{"text": "exit restore reply"}],-}---def side_binary(side):- if side == "ts":- return TS_BIN- if side == "before":- return os.environ.get("PA_BEFORE_BINARY", RUST_BIN)- return RUST_BIN---class TmuxServer:- """One isolated tmux server (`-L` socket): the shell pane host.-- An isolated server (never the shared/default one) keeps the exit- battery off any ambient tmux configuration (a global default-shell- wrapper, session hooks) and lets the harness kill the whole server- per scenario.- """-- def __init__(self, tag):- self.socket = f"exitrestore-{os.getpid()}-{tag}"- self.session = "s"- subprocess.run(["tmux", "-L", self.socket, "kill-server"], capture_output=True)-- def run(self, *args, timeout=60, check=False):- proc = subprocess.run(- ["tmux", "-L", self.socket, *args],- capture_output=True,- text=True,- timeout=timeout,- )- if check and proc.returncode != 0:- raise RuntimeError(- f"tmux {' '.join(args[:4])} failed: {proc.returncode} {proc.stderr.strip()}"- )- return proc-- def new_session(self, cwd):- self.run(- "new-session",- "-d",- "-s",- self.session,- "-x",- str(SIZE[0]),- "-y",- str(SIZE[1]),- "-c",- cwd,- "bash",- "--noprofile",- "--norc",- check=True,- )-- def send(self, text):- """Type one line into the pane and submit it with Enter (the- established harness pattern: a literal string then the Enter- key)."""- self.run("send-keys", "-t", self.session, text, "Enter", check=True)-- def send_key(self, key):- self.run("send-keys", "-t", self.session, key, check=True)-- def capture(self, escapes=False, history=None):- args = ["capture-pane", "-p", "-t", self.session]- if escapes:- args.append("-e")- if history:- # tmux `-S` counts from the screen top: negative reaches into- # the scrollback history above it.- args.extend(["-S", str(history)])- return self.run(*args).stdout-- def alternate_on(self):- return self.run(- "display-message", "-p", "-t", self.session, "#{alternate_on}"- ).stdout.strip()-- def kill(self):- self.run("kill-server")---def shell_prompt_back(server, timeout=20):- """The client exited: the pane's last non-empty line is the plain- bash prompt again (bash --noprofile --norc: `bash-<version>$ ` on a- user shell, `bash-<version># ` when the pane shell runs as root —- the VM harnesses do; the flushed exit frame may sit above it and- trailing blank rows below — the exit frame flush is TS parity, not- a failure)."""- deadline = time.time() + timeout- while time.time() < deadline:- text = server.capture()- lines = [line.strip() for line in text.splitlines()]- while lines and not lines[-1]:- lines.pop()- if lines and re.match(r"^bash-[\d.]+[#$] ?$", lines[-1]):- return True- time.sleep(0.2)- return False---def stty_state(server, marker, timeout=15):- """The pane shell's tty state as one comparable token: the POSIX- `cksum` of `stty -g`'s output (macOS prints the `gfmt1:` key=value- form and wraps; Linux a colon-hex blob — the cksum compares either).- """- server.send(f"echo {marker} && stty -g | cksum")- deadline = time.time() + timeout- seen_marker = False- while time.time() < deadline:- text = server.capture()- if marker in text:- seen_marker = True- if seen_marker:- for line in text.splitlines():- match = re.search(r"\b(\d+ \d+)$", line.strip())- if match:- return match.group(1)- time.sleep(0.2)- return None---def typed_clean(server, timeout=15):- """(iii) the leak check: type a literal line into the shell; the echo- must contain the literal text with no escape bytes."""- server.send("echo LITCHECK_OK_7f3a")- deadline = time.time() + timeout- while time.time() < deadline:- text = server.capture(escapes=True)- if "LITCHECK_OK_7f3a" in text:- return text- time.sleep(0.2)- return None---def typed_line_clean(capture_text):- """The echoed command line must be literal: after stripping tmux's- OSC 8 hyperlink wrappers (the pane's own rendering, not a leak), the- line must contain no escape bytes at all — a kitty CSI-u report, an- SGR mouse report, or a paste marker inside the echoed input is the- leak the scenario exists to catch (stripping CSI classes before the- check would hide exactly those)."""- for line in capture_text.splitlines():- if "echo LITCHECK_OK_7f3a" not in line:- continue- stripped = re.sub(r"\x1b\]8;;[^\x07\x1b]*(\x07|\x1b\\)", "", line)- return "\x1b" not in stripped- return False---def launch_command(side, sandbox, socket_path, extra_args):- env = (- f"HOME={sandbox['home']} "- f"TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"PRIME_AGENT_FAUX_SCRIPT={sandbox['faux_script']} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- if side in ("rust", "before"):- package_dir = os.environ.get("PI_PACKAGE_DIR") or vp.find_runtime_package_dir()- env += f" PI_PACKAGE_DIR={package_dir}"- command = (- f"{env} {side_binary(side)} --daemon-socket {socket_path} "- f"--model {vp.TS_SCRIPT_MODEL}"- )- if extra_args:- command += " " + " ".join(extra_args)- return command---def wait_settle(server, needle=CHAT_SETTLE, timeout=60):- deadline = time.time() + timeout- while time.time() < deadline:- if needle in server.capture():- return True- time.sleep(0.3)- return False---def sandbox_worker_pids(sandbox):- """This sandbox's daemon worker processes (Linux /proc; the VM runs- the worker scenarios)."""- if not os.path.isdir("/proc"):- return []- agent_marker = sandbox["agent"].encode()- found = []- for entry in os.listdir("/proc"):- if not entry.isdigit():- continue- try:- with open(f"/proc/{entry}/environ", "rb") as f:- environ = f.read()- except OSError:- continue- if WORKER_ROLE_MARKER in environ and agent_marker in environ:- found.append(int(entry))- return found---def daemon_pids_for(socket_path):- if not os.path.isdir("/proc"):- return []- found = []- for entry in os.listdir("/proc"):- if not entry.isdigit():- continue- try:- with open(f"/proc/{entry}/cmdline", "rb") as f:- cmdline = f.read()- except OSError:- continue- if b"--mode" in cmdline and socket_path.encode() in cmdline:- found.append(int(entry))- return found---def kill_daemons(socket_path):- for pid in daemon_pids_for(socket_path):- try:- os.kill(pid, signal.SIGTERM)- except OSError:- pass- time.sleep(0.5)- for pid in daemon_pids_for(socket_path):- try:- os.kill(pid, signal.SIGKILL)- except OSError:- pass---def ensure_replay_fixture(sandbox):- """A session jsonl for the replay binary: reuse one produced by the- earlier scenarios (each run leaves a session in the sandbox agent- dir), else a minimal fixture in the HOME the binary reads."""- home_sessions = os.path.join(sandbox["home"], ".prime", "agent", "sessions")- os.makedirs(home_sessions, exist_ok=True)- sessions = sorted(glob.glob(os.path.join(sandbox["agent"], "sessions", "*.jsonl")))- if sessions:- target = os.path.join(home_sessions, "replay-fixture.jsonl")- with open(sessions[-1], "rb") as src, open(target, "wb") as dst:- dst.write(src.read())- return target- fixture = os.path.join(home_sessions, "replay-fixture.jsonl")- if os.path.exists(fixture):- return fixture- header = {- "type": "session",- "sessionId": "fixture-1",- "createdAt": "2026-09-23T00:00:00.000Z",- "version": 1,- "title": "fixture",- }- user = {- "type": "message",- "message": {"role": "user", "content": "hello replay"},- "timestamp": "2026-09-23T00:00:01.000Z",- }- assistant = {- "type": "message",- "message": {"role": "assistant", "content": "replay reply"},- "timestamp": "2026-09-23T00:00:02.000Z",- }- with open(fixture, "w") as f:- for entry in (header, user, assistant):- f.write(json.dumps(entry) + "\n")- return fixture---def run_scenario(side, sandbox, label, out_dir):- """One side x scenario: fresh socket + tmux server + pane.-- The launch is ONE shell line ending in the exit probes (`echo- EXITCODE` + `stty -g > file` + its cksum): the probes run the moment- the client exits, BEFORE the shell's line editor touches the tty- again — so the captured state is exactly what the exit restore left,- not what readline healed. (A standalone post-exit `stty` probe would- read the shell's healed state and mask a raw leak.)- """- socket_path = os.path.join(sandbox["agent"], f"daemon-{label}-{side}.sock")- if os.path.exists(socket_path):- os.unlink(socket_path)- server = TmuxServer(f"{label}-{side}")- facts = {"side": side, "scenario": label}- stopped_workers = []- try:- server.new_session(sandbox["cwd"])- time.sleep(0.5)- baseline = stty_state(server, "BASELINE_MARKER")- facts["stty_baseline"] = baseline- # The probe state file lives under the scenario's own sandbox tmp- # (a per-scenario name): concurrent invocations of the harness must- # never checksum another scenario's terminal state.- probe_path = os.path.join(sandbox["tmp"], f"tty_after_exit-{label}-{side}")- probe = (- " ; printf 'EXITCODE:%s\\r\\n' \"$?\""- f" ; stty -g > {probe_path}"- " ; printf 'TTYCK:%s\\r\\n' \"$(cksum < " + probe_path + ")\""- # The canonical-mode marker: a poisoned start ends in the- # cooked-tty REPAIR, whose `stty sane` reconstruction is cooked- # but not byte-identical to the pre-poison baseline — the mode- # is the invariant there, the exact state everywhere else.- " ; if stty -a | grep -q ' -icanon'; then printf 'TTYMODE:raw\\r\\n';"- " else printf 'TTYMODE:cooked\\r\\n'; fi"- )- if label == "panic":- # The replay surface panics mid-loop (rust sides only).- session_fixture = ensure_replay_fixture(sandbox)- replay = REPLAY_BIN or os.path.join(- os.path.dirname(os.path.abspath(side_binary(side))), "pa-tui-replay"- )- server.send(f"{replay} --panic-exit {session_fixture}{probe}")- facts["panic_exited"] = shell_prompt_back(server, timeout=25)- else:- extra_args = ["--resume"] if label == "agents-exit" else []- poison = "stty raw -echo ; " if label == "poisoned" else ""- command = launch_command(side, sandbox, socket_path, extra_args)- server.send(f"{poison}{command}{probe}")- needle = AGENTS_VIEW_NEEDLE if label == "agents-exit" else CHAT_SETTLE- facts["settled"] = wait_settle(server, needle=needle)- if not facts["settled"]:- facts["pane_at_timeout"] = server.capture()- return facts- facts["alt_on_while_running"] = server.alternate_on()- if label in ("quit", "agents-exit", "poisoned"):- server.send_key("C-c")- time.sleep(0.8)- server.send_key("C-c")- elif label == "quit-slash":- server.send("/quit")- elif label in ("error-exit", "wedge"):- workers = sandbox_worker_pids(sandbox)- facts["workers_found"] = len(workers)- for pid in workers:- os.kill(pid, signal.SIGSTOP)- stopped_workers.extend(workers)- server.send("second turn please")- time.sleep(1.5)- if label == "wedge":- server.send_key("C-c")- time.sleep(0.4)- server.send_key("C-c")- facts["force_exited"] = shell_prompt_back(server, timeout=12)- else:- # The parked request's bound is the fatal exit.- facts["error_exited"] = shell_prompt_back(- server, timeout=ERROR_EXIT_WAIT_S- )- # The probes and the prompt: parse from the pane once the shell- # is back (or the timeout passed).- facts["prompt_back"] = shell_prompt_back(server, timeout=25)- exit_probe = parse_exit_probe(server.capture(history=-100))- facts["exit_code"] = exit_probe.get("exit_code")- facts["tty_cksum"] = exit_probe.get("tty_cksum")- facts["tty_mode"] = exit_probe.get("tty_mode")- # (i) the alternate screen is left.- facts["alternate_on_after"] = server.alternate_on()- # (ii) the tty is cooked: the exit probe's state matches the sane- # baseline — except a poisoned start, where the exit's cooked-tty- # repair rebuilds a `stty sane`-equivalent mode that is cooked but- # not byte-identical to the pre-poison baseline; the mode is the- # invariant there.- if label == "poisoned":- facts["stty_matches_sane"] = facts["tty_mode"] == "cooked"- else:- facts["stty_matches_sane"] = (- facts["tty_cksum"] is not None and facts["tty_cksum"] == baseline- )- # (iii) no escape bytes leak into the typed line.- leak_text = typed_clean(server)- facts["typed_visible"] = leak_text is not None- facts["leak_free"] = typed_line_clean(leak_text) if leak_text is not None else None- # Evidence: the pane as the user sees it (with history).- history_text = server.capture(history=-400)- evidence_path = os.path.join(out_dir, f"{side}-{label}-pane.txt")- with open(evidence_path, "w") as f:- f.write(history_text)- facts["evidence_pane"] = evidence_path- facts["resume_hint_visible"] = RESUME_HINT_NEEDLE in history_text- return facts- finally:- try:- server.kill()- except Exception:- pass- for pid in stopped_workers:- try:- os.kill(pid, signal.SIGCONT)- except OSError:- pass- kill_daemons(socket_path)---def parse_exit_probe(capture_text):- """The EXITCODE/TTYCK lines the probe printed (either form survives a- raw-tty staircase: printf emits explicit CR)."""- probe = {}- for line in capture_text.splitlines():- m = re.search(r"EXITCODE:(-?\d+)", line)- if m:- probe["exit_code"] = int(m.group(1))- m = re.search(r"TTYCK:(\d+ \d+)", line)- if m:- probe["tty_cksum"] = m.group(1)- m = re.search(r"TTYMODE:(raw|cooked)", line)- if m:- probe["tty_mode"] = m.group(1)- return probe---def scenario_runs(side, label):- """Which scenarios a side runs at all."""- if label in ("error-exit", "wedge", "panic"):- return side in ("rust", "before")- return True---def true_count(facts):- """A nonzero `workers_found` read: the count arrives as a JSON int or- a string depending on the capture path; `None` reads as zero."""- try:- return int(facts.get("workers_found") or 0) > 0- except (TypeError, ValueError):- return False---def gate_facts(key, facts):- """The failure list for one scenario run (the `before` side records- its failures as the pre-fix evidence; only ts/rust gate the exit)."""- failures = []- label = facts.get("scenario")- if label != "panic" and facts.get("settled") is not True:- failures.append(f"{key}:no-settle")- return failures- expected_exit = 101 if label == "panic" else (1 if label == "error-exit" else 0)- if facts.get("exit_code") != expected_exit:- failures.append(f"{key}:exit-code={facts.get('exit_code')}")- if label == "panic":- if facts.get("panic_exited") is not True:- failures.append(f"{key}:panic-did-not-exit")- else:- if facts.get("prompt_back") is not True:- failures.append(f"{key}:prompt-not-back")- if str(facts.get("alt_on_while_running")) != "1":- failures.append(f"{key}:alt-not-on-while-running")- if label == "wedge":- # The watchdog contract is the scenario's point: the loop was- # parked (workers were found and stopped) and the force quit- # fired — an ordinary quit path or a missed deadline must not- # pass for it.- if not true_count(facts):- failures.append(f"{key}:no-workers-to-wedge")- if facts.get("force_exited") is not True:- failures.append(f"{key}:force-quit-did-not-fire")- if facts.get("alternate_on_after") != "0":- failures.append(f"{key}:alt-on={facts.get('alternate_on_after')}")- if facts.get("stty_matches_sane") is not True:- # TS parity note: on the poisoned start, the TS product restores- # its own captured `wasRaw` (the poisoned raw state) — no- # cooked-tty verification exists there — so the ts side records- # the divergence instead of gating (this port's repair is the- # hardening the scenario drives).- if facts.get("side") == "ts" and facts.get("scenario") == "poisoned":- pass- else:- failures.append(f"{key}:tty-state={facts.get('tty_cksum')}")- if facts.get("leak_free") is not True:- # The TS product restores its captured `wasRaw` on a poisoned- # start, so the shell's first typed line lands in the broken mode- # (the recorded "characters eaten / escape leak" divergence —- # Kevin's live symptom, reproduced on the TS side); the ts side- # records it, this port's repair owns the fix.- if facts.get("side") == "ts" and facts.get("scenario") == "poisoned":- pass- else:- failures.append(f"{key}:escape-leak")- return failures---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--sides", default=None, help="comma list: ts,rust,before")- parser.add_argument("--scenarios", default=None, help="comma list of scenario labels")- parser.add_argument("--out", default=None, help="evidence output dir")- args = parser.parse_args()-- sides = args.sides.split(",") if args.sides else ["ts", "rust"]- if "ts" in sides:- # The identity guard gets the binaries THIS run executes: the ts- # side must be the deployed TS product, checked against the rust- # build the harness actually drives (not the module default).- ts_identity.assert_ts_side_is_the_ts_product(ts_bin=TS_BIN, rust_bin=RUST_BIN)- all_scenarios = [- "quit",- "quit-slash",- "agents-exit",- "error-exit",- "wedge",- "poisoned",- "panic",- ]- scenarios = args.scenarios.split(",") if args.scenarios else all_scenarios-- base = tempfile.mkdtemp(prefix="exit-restore-")- out_dir = args.out or os.path.join(base, "evidence")- os.makedirs(out_dir, exist_ok=True)- print(f"run root: {base}; evidence: {out_dir}", flush=True)-- shared_cwd, script_path, sandboxes = vp.prepare_sandbox(base)- with open(script_path, "w") as f:- json.dump(FAUX_SCRIPT, f, indent=2)- side_sandboxes = {}- for side in sides:- if side in sandboxes:- sandbox = dict(sandboxes[side])- else:- sandbox = {- "home": os.path.join(base, side, "home"),- "agent": os.path.join(base, side, "agent"),- "tmp": os.path.join(base, side, "tmp"),- }- for key in ("home", "agent", "tmp"):- os.makedirs(sandbox[key], exist_ok=True)- os.makedirs(os.path.join(sandbox["agent"], "sessions"), exist_ok=True)- sandbox["cwd"] = shared_cwd- sandbox["faux_script"] = script_path- # Both onboarding keys: the Rust loader keys onboarding on- # `onboardingShown`, the TS loader on `onboardingCompleted`.- with open(os.path.join(sandbox["agent"], "settings.json"), "w") as f:- json.dump({"onboardingCompleted": True, "onboardingShown": True}, f)- side_sandboxes[side] = sandbox-- results = {}- try:- for side in sides:- for label in scenarios:- if not scenario_runs(side, label):- continue- if label in ("error-exit", "wedge") and not os.path.isdir("/proc"):- print(f"[skip] {side} {label}: /proc unavailable (non-Linux)", flush=True)- continue- facts = run_scenario(side, side_sandboxes[side], label, out_dir)- results[f"{side}:{label}"] = facts- print(f"[exit-restore] {side} {label}: {json.dumps(facts)[:900]}", flush=True)- finally:- with open(os.path.join(out_dir, "results.json"), "w") as f:- json.dump(results, f, indent=2)-- gated_failures = []- recorded = []- for key, facts in results.items():- failures = gate_facts(key, facts)- for failure in failures:- if facts.get("side") == "before":- recorded.append(f"RECORDED-BEFORE-FAIL {failure}")- else:- gated_failures.append(failure)- for failure in recorded:- print(failure)- for failure in gated_failures:- print(f"FAIL {failure}")- print("EXIT-RESTORE TMUX E2E:", "RED" if gated_failures else "GREEN")- return 1 if gated_failures else 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/tui_perf_bench.py b/scripts/tui_perf_bench.pydeleted file mode 100644index 59e5c0c877..0000000000--- a/scripts/tui_perf_bench.py+++ /dev/null@@ -1,280 +0,0 @@-#!/usr/bin/env python3-"""Large-session TUI perf regression bench (lane tui-large-session-perf).--Generates a synthetic large session (a big transcript with a bounded-post-compaction window, many passivated subagent transcripts, and a spawn-ledger), then drives a REAL pa-cli daemon + TUI in tmux and measures:-- - open_cold: fresh daemon -> resume the target -> session view painted- - switch_to_agents / switch_to_session: the agents-back round trip- - switch_*_2: the second round trip (warm)--Budgets (default, on the synthetic fixture): open_cold <= 6s,-switch_to_session_2 <= 2s. Exits nonzero when a budget is breached - a-regression in the open/switch paths (ledger re-seeding, re-parsing,-blocking hydration) shows up as a budget blowup.--Usage:- python3 scripts/tui_perf_bench.py --bin <prime-agent> [--keep-fixture]-The fixture + daemon live under /tmp/pa-tui-perf-bench-* (never the real-agent dir). Requires tmux; TERM must not be set to a dumb value.-"""-import argparse-import hashlib-import json-import os-import shutil-import signal-import subprocess-import sys-import tempfile-import time-import uuid--TMUX_SOCK = "pabench" + uuid.uuid4().hex[:6]---def tmux(*args, check=True):- cmd = ["tmux", "-L", TMUX_SOCK] + list(args)- r = subprocess.run(cmd, capture_output=True, text=True)- if check and r.returncode != 0:- raise RuntimeError(f"tmux {args}: {r.stderr}")- return r.stdout---def env(agent_dir, kernel_venv=None):- e = {- "PATH": os.environ.get("PATH", "/usr/local/bin:/usr/bin:/bin"),- "HOME": os.environ.get("HOME", "/root"),- "TERM": "xterm-256color",- "PRIME_AGENT_CODING_AGENT_DIR": agent_dir,- "PRIME_AGENT_TELEMETRY": "0",- }- if kernel_venv:- e["PRIME_AGENT_KERNEL_VENV"] = kernel_venv- for stale in ("PRIME_AGENT_SESSION_DIR",):- e.pop(stale, None)- return e---def write_line(path, value):- with open(path, "ab") as f:- f.write(json.dumps(value).encode() + b"\n")---def make_fixture(root, transcript_mb, children, child_mb):- """A synthetic saved session family: one big parent transcript with a- bounded post-compaction window, `children` passivated subagent- transcripts, and a spawn ledger pointing at them."""- agent_dir = os.path.join(root, "agent")- sessions = os.path.join(agent_dir, "sessions")- artifacts = os.path.join(agent_dir, "session-artifacts")- parent_id = "01bench0000-0000-7000-8000-%012d" % children- os.makedirs(sessions, exist_ok=True)- parent_file = os.path.join(sessions, parent_id + ".jsonl")- parent = {- "type": "session",- "version": 3,- "id": parent_id,- "timestamp": "2026-01-01T00:00:00.000Z",- "cwd": root,- "rlmDepth": 0,- }- write_line(parent_file, parent)- # Pre-compaction bulk: enough message entries to reach ~transcript_mb.- target_bytes = transcript_mb * 1024 * 1024- filler = "x" * 1024- written = 0- index = 0- while written < target_bytes:- for role in ("user", "assistant"):- entry = {- "type": "message",- "id": "m%d" % index,- "parentId": "m%d" % (index - 1) if index else None,- "timestamp": "2026-01-01T00:00:00.000Z",- "message": {- "role": role,- "content": [{"type": "text", "text": filler}],- },- }- write_line(parent_file, entry)- written += 1100- index += 1- # The compaction boundary: everything above collapses; the window below- # is what the attach snapshot carries.- write_line(parent_file, {- "type": "compaction",- "id": "cmp1",- "parentId": "m%d" % (index - 1),- "timestamp": "2026-01-01T00:00:00.000Z",- "summary": "synthetic compaction boundary",- "tokensBefore": 200000,- })- # The visible window: what the session view must paint on open.- marker = "BENCH-FIXTURE-MARKER final tail"- for i in range(40):- write_line(parent_file, {- "type": "message",- "id": "w%d" % i,- "parentId": "cmp1" if i == 0 else "w%d" % (i - 1),- "timestamp": "2026-01-01T00:00:00.000Z",- "message": {- "role": "assistant" if i == 39 else "user",- "content": [{"type": "text", "text": marker if i == 39 else "window entry %d" % i}],- },- })- # The passivated children: one transcript each under the parent's- # artifacts dir, wired by spawn-ledger edges. Each child transcript is- # `child_mb` MB - the ledger-seed walk re-reads every one of them on- # every roster subscribe in the regressed shape, so the fixture must- # carry realistic (multi-MB) children to catch that class.- parent_artifacts = os.path.join(artifacts, parent_id)- edges = [{- "v": 1,- "op": "meta",- "at": "2026-01-01T00:00:00.000Z",- "sessionsDir": sessions,- }]- for c in range(children):- child_id = "01benchchild%04d-0000-7000-8000-%012d" % (c, c)- sub_dir = os.path.join(parent_artifacts, "sub-%06d" % c)- os.makedirs(sub_dir, exist_ok=True)- child_file = os.path.join(sub_dir, child_id + ".jsonl")- write_line(child_file, {- "type": "session", "version": 3, "id": child_id,- "timestamp": "2026-01-01T00:00:00.000Z",- "cwd": root, "parentSession": parent_file,- "rlmDepth": 1,- })- child_target = child_mb * 1024 * 1024- child_written = 0- m = 0- while child_written < child_target:- write_line(child_file, {- "type": "message",- "id": "c%d" % m,- "parentId": "c%d" % (m - 1) if m else None,- "timestamp": "2026-01-01T00:00:00.000Z",- "message": {- "role": "user" if m == 0 else "assistant",- "content": [{"type": "text", "text": filler}],- },- })- child_written += 1100- m += 1- edges.append({- "v": 1, "op": "spawn", "at": "2026-01-01T00:00:00.000Z",- "childId": "sub-%06d" % c,- "parent": parent_file,- "child": child_file,- "name": "bench-worker-%d" % c,- "depth": 1,- })- ledger_hash = hashlib.sha256(os.path.realpath(sessions).encode()).hexdigest()[:16]- ledger_dir = os.path.join(agent_dir, "rlm-ledger")- os.makedirs(ledger_dir, exist_ok=True)- ledger_file = os.path.join(ledger_dir, ledger_hash + ".jsonl")- with open(ledger_file, "wb") as f:- for edge in edges:- f.write(json.dumps(edge).encode() + b"\n")- return agent_dir, parent_file, marker---def wait_for(marker_fn, timeout, desc, t0):- while True:- # The visible pane only: history would carry a prior view's- # marker and answer a switch before its repaint landed.- pane = tmux("capture-pane", "-p", "-t", "bench:0.0")- if marker_fn(pane):- return time.monotonic() - t0- if time.monotonic() - t0 > timeout:- raise TimeoutError("%s not visible in %ss; pane tail:\n%s" % (desc, timeout, pane[-1200:]))- time.sleep(0.02)---SESSION_MARKER = "BENCH-FIXTURE-MARKER"-AGENTS_MARKER = "Search sessions"---def main():- ap = argparse.ArgumentParser()- ap.add_argument("--bin", required=True, help="path to the prime-agent binary to bench")- ap.add_argument("--transcript-mb", type=int, default=30)- ap.add_argument("--children", type=int, default=200)- ap.add_argument("--child-mb", type=float, default=2.0)- ap.add_argument("--open-budget", type=float, default=6.0)- ap.add_argument("--switch-budget", type=float, default=2.0)- ap.add_argument("--keep-fixture", action="store_true")- args = ap.parse_args()-- root = tempfile.mkdtemp(prefix="pa-tui-perf-bench-")- daemon = None- results = {"fixture": {"transcript_mb": args.transcript_mb,- "children": args.children, "child_mb": args.child_mb}}- try:- agent_dir, target, marker = make_fixture(root, args.transcript_mb, args.children, args.child_mb)- socket = os.path.join(root, "daemon.sock")- daemon_log = open(os.path.join(root, "daemon.log"), "wb")- # open_cold covers the whole cold path: daemon startup and- # socket initialization included, on one monotonic clock - a- # regression before the socket appears must fail the budget- # too.- t0 = time.monotonic()- daemon = subprocess.Popen(- [args.bin, "--mode", "daemon", "--daemon-socket", socket],- stdout=daemon_log, stderr=daemon_log, stdin=subprocess.DEVNULL,- env=env(agent_dir), start_new_session=True,- )- while not os.path.exists(socket):- if time.monotonic() - t0 > 60:- raise RuntimeError("daemon socket never appeared")- time.sleep(0.05)- tmux("new-session", "-d", "-s", "bench", "-x", "200", "-y", "45", "-c", root,- "env", "-u", "PRIME_AGENT_SESSION_DIR",- "PRIME_AGENT_CODING_AGENT_DIR=" + agent_dir, "PRIME_AGENT_TELEMETRY=0",- "TERM=xterm-256color",- args.bin, "--daemon-socket", socket, "--resume", target)- results["open_cold_s"] = round(wait_for(- lambda pane: SESSION_MARKER in pane, 90, "cold open session view", t0), 3)- time.sleep(1.0)- def switch(keys, desc, timeout=60):- tmux("send-keys", "-t", "bench:0.0", keys)- t = time.monotonic()- return round(wait_for(- lambda pane: AGENTS_MARKER in pane if desc.startswith("agents") else SESSION_MARKER in pane,- timeout, desc, t), 3)- results["switch_to_agents_s"] = switch("Left", "agents view")- time.sleep(1.0)- results["switch_to_session_s"] = switch("Enter", "session view")- time.sleep(0.5)- results["switch_to_agents_2_s"] = switch("Left", "agents view 2")- results["switch_to_session_2_s"] = switch("Enter", "session view 2")- tmux("send-keys", "-t", "bench:0.0", "C-c")- time.sleep(0.2)- tmux("send-keys", "-t", "bench:0.0", "C-c")- finally:- tmux("kill-server", check=False)- if daemon is not None:- daemon.terminate()- try:- daemon.wait(timeout=5)- except subprocess.TimeoutExpired:- daemon.kill()- if not args.keep_fixture:- shutil.rmtree(root, ignore_errors=True)- else:- print("fixture kept at", root)- print(json.dumps(results, indent=2))- failed = False- if results["open_cold_s"] > args.open_budget:- print("FAIL: open_cold %.2fs > budget %.2fs" % (results["open_cold_s"], args.open_budget))- failed = True- if results["switch_to_session_2_s"] > args.switch_budget:- print("FAIL: warm switch %.2fs > budget %.2fs" % (results["switch_to_session_2_s"], args.switch_budget))- failed = True- return 1 if failed else 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/tui_polish_parity.py b/scripts/tui_polish_parity.pydeleted file mode 100644index 5fbb82daa4..0000000000--- a/scripts/tui_polish_parity.py+++ /dev/null@@ -1,398 +0,0 @@-#!/usr/bin/env python3-"""TUI styling-parity verifier (tui-polish lane): the two known color-layer-divergences from the gutter-verify audit, byte-compared against the TS-binary on PATH.-- 1. Fenced-code syntax colors. The TS markdown theme's `highlightCode`- (cli-highlight over the highlight.js 10.7.3 grammar, the same pass the- expanded ipython cell uses) renders ```python fences multicolor; the- Rust TUI rendered them uniform. This harness replays a session whose- assistant text carries a python fence (keywords, built-ins, numbers,- f-strings, a def header, literals), a bare fence (the uniform- fallback), and an attribute fence (```python title=x: marked passes- the whole trimmed info string, so hljs has no such language and the- block stays uniform) through BOTH binaries and byte-compares the- normalized frames (volatile values out, in-line ANSI in). A- multicolor guard asserts the TS code rows actually carry >=2 distinct- colors so a both-sides-uniform false pass cannot hold.-- 2. The loader row's SGR boundary. TS's `Loader` renders- `${spinnerColorFn(frame)} ${messageColorFn(msg)}`: chalk resets to- default fg on the spinner->label gap; the Rust carried the label- color over the space. This harness streams a slow reasoning mock- into BOTH binaries, densely captures the mid-stream frames while the- working loader is up, extracts every loader row, normalizes the- volatile spinner/elapsed/token-count values, and byte-compares the- row sets. The gap's `ESC[39m ` reset must sit between the spinner- and the label on both sides.--Frames and diffs land in --out as the parity-diff evidence.-"""--import json-import os-import re-import sys-import tempfile-import threading-import time-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import thinking_parity as tp # noqa: E402 (the shared capture machinery)-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--SPINNERS = "\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f"--#: The deployed TS product this harness diffs against. The box's PATH-#: `prime-agent` may be a Rust dogfood install (the ts-identity guard-#: refuses that); point TS_BIN at the installed TS release when it is.-TS_BIN = os.environ.get("TS_BIN", "prime-agent")--# The corpus python block: keywords, built-ins, numbers, f-strings, a def-# header (title + params), a comment, and a literal - every scope the-# token-class mapping carries.-PY_BLOCK = "def gutter_probe(count=7):\n # probe comment\n total = 0\n for i in range(count):\n print(f\"line {i}\")\n total += i\n if total is not None:\n return total\n\ngutter_probe(3)"--ASSISTANT_TEXT = (- "The parity code block:\n"- "```python\n" + PY_BLOCK + "\n```\n"- "\n"- "A bare fence stays uniform:\n"- "```\nplain code line\n```\n"- "\n"- "An attribute fence stays uniform:\n"- "```python title=x\nattribute code line\n```\n"- "\n"- "FINAL thinking parity marker reached."-)--LIVE_PROMPT = "say the loader parity probe"---def start_slow_mock():- """The reasoning mock, slowed so the loader row stays up for the dense- capture window."""-- class Handler(BaseHTTPRequestHandler):- def log_message(self, *args):- pass-- def do_GET(self):- self.send_response(200)- self.send_header("Content-Type", "application/json")- self.end_headers()- self.wfile.write(json.dumps({"data": [{"id": "mock-1", "object": "model"}]}).encode())-- def do_POST(self):- self.rfile.read(int(self.headers.get("Content-Length", 0)))- self.send_response(200)- self.send_header("Content-Type", "text/event-stream")- self.end_headers()- chunks = [- {"delta": {"reasoning_content": "LOADERPARITY-A first reasoning fragment that streams slowly."}},- {"delta": {"reasoning_content": "LOADERPARITY-B second fragment streams slowly too."}},- {"delta": {"reasoning_content": "LOADERPARITY-C third fragment wraps up the slow trace."}},- {"delta": {"content": "Live body text after thinking."}},- {"delta": {}, "finish_reason": "stop"},- ]- for chunk in chunks:- wire = {"id": "chatcmpl-mock", "model": "mock-1",- "choices": [{"delta": chunk["delta"], "index": 0}]}- if "finish_reason" in chunk:- wire["choices"][0]["finish_reason"] = chunk["finish_reason"]- self.wfile.write(f"data: {json.dumps(wire)}\n\n".encode())- self.wfile.flush()- time.sleep(0.7)- self.wfile.write(b"data: [DONE]\n\n")-- server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)- threading.Thread(target=server.serve_forever, daemon=True).start()- return server.server_address[1], server---def build_session(path, envelope, cwd):- """The replay fixture: an assistant text block with the three fences,- byte-shaped like a TS-written session (the shared envelope machinery)."""- header = {- "type": "session",- "version": 3,- "id": "tuipolish-session",- "cwd": cwd,- "timestamp": "2026-09-22T00:00:00.000Z",- }- entries = [header]- base_ms = 1_700_000_000_000-- def entry(type_, fields, ms):- row = {"type": type_}- row.update(fields)- row["id"] = f"e{ms - 1_700_000_000_000:04d}"- row["parentId"] = entries[-1]["id"]- row["timestamp"] = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(ms / 1000))- return row-- def assistant_with(content, ms):- message = json.loads(json.dumps(envelope))- message["content"] = content- message["provider"] = "prime-inference"- message["model"] = "z-ai/glm-5.3"- message["timestamp"] = ms- return message-- entries.append(entry("message", {- "message": {"role": "user", "content": "TUI polish parity probe.", "timestamp": base_ms},- }, base_ms))- base_ms += 1- entries.append(entry("message", {"message": assistant_with([- {"type": "text", "text": ASSISTANT_TEXT},- ], base_ms)}, base_ms))- base_ms += 1- with open(path, "w", encoding="utf-8") as f:- for row in entries:- f.write(json.dumps(row) + "\n")- return path---def env_noise(frame):- """The gutter-verify environment-row filter: sandbox startup notices- (ripgrep-missing, tmux extended-keys) are environment rows, not- transcript rows; drop them (with wrapped continuations) and collapse- blank runs so only content rows participate."""- out = []- lines = frame.split("\n")- i = 0- while i < len(lines):- plain = tp.strip_ansi(lines[i])- if "ripgrep" in plain:- i += 5- continue- if "extended-keys" in plain:- i += 2- continue- out.append(lines[i])- i += 1- collapsed = []- prev_blank = False- for line in out:- blank = not line.strip()- if blank and prev_blank:- continue- collapsed.append(line)- prev_blank = blank- return "\n".join(collapsed)---def code_color_rows(frame):- """The python-fence rows that must carry the syntax colors: rows whose- plain text is the corpus code lines."""- rows = []- for line in frame.split("\n"):- plain = tp.strip_ansi(line)- stripped = plain.lstrip()- if stripped.startswith(("def gutter_probe", "for i in range", "print(f\"line")):- rows.append(line)- return rows---def run_ts_replay(session_path, sandbox, size, out_dir):- """tp.run_ts_replay with the explicit TS_BIN (the PATH binary may be a- Rust dogfood install; the identity guard checks the binary used)."""- session = f"tuipolish-ts-{size[0]}x{size[1]}"- tp.tmux("kill-session", "-t", session, check=False)- tp.tmux("new-session", "-d", "-s", session, "-x", size[0], "-y", size[1], "-c", sandbox["cwd"])- env = (- f"HOME={sandbox['home']} TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} PRIME_AGENT_DISABLE_ANALYTICS=1"- )- command = f"{env} {TS_BIN} --offline -r {session_path}"- tp.tmux("send-keys", "-t", session, command, "Enter")- frames = tp.capture_states(session, tp.MARKER_TEXT, "ts replay")- tp.tmux("kill-session", "-t", session, check=False)- for state, frame in frames.items():- with open(os.path.join(out_dir, f"ts-{state}-{size[0]}x{size[1]}.txt"), "w") as f:- f.write(frame)- return frames---def replay_compare(session_path, sandboxes, out_dir, failures):- """REPLAY: both binaries render the same session; the normalized- frames (in-line ANSI kept) must be byte-identical."""- size = ("120", "90")- ts_frames = run_ts_replay(session_path, sandboxes["ts-replay"], size, out_dir)- rust_frames = tp.run_rust_replay(- session_path, sandboxes["rust-replay"], size, out_dir, RUST_REPLAY_BIN- )- for state in ("a_collapsed", "b_details", "c_all"):- name = f"replay-{state}-{size[0]}x{size[1]}"- ts_norm = env_noise(tp.normalize(ts_frames[state], sandboxes["ts-replay"]["cwd"]))- rust_norm = env_noise(tp.normalize(rust_frames[state], sandboxes["rust-replay"]["cwd"]))- if ts_norm == rust_norm:- print(f"PASS {name} (byte-identical)")- else:- report = os.path.join(out_dir, f"diff-{name}.txt")- with open(report, "w") as f:- f.write(tp.diff_lines(ts_norm, rust_norm))- print(f"FAIL {name}: diff at {report}")- failures.append(name)- # The multicolor guard: the TS python-fence rows carry the token- # colors (>=2 distinct fg colors per code row), so the- # byte-identical pass cannot be a both-sides-uniform false pass.- ts_code = code_color_rows(ts_norm)- if not ts_code:- print(f"FAIL {name}: no python-fence rows found in the TS frame")- failures.append(f"{name}-code-rows")- continue- for row in ts_code:- colors = set(re.findall(r"\x1b\[38;2;[0-9;]+m", row))- if len(colors) < 2:- print(f"FAIL {name}: TS code row is uniform: {row!r}")- failures.append(f"{name}-multicolor")- # The two uniform fences must stay uniform on both sides.- bare = [line for line in ts_norm.split("\n")- if tp.strip_ansi(line).strip() == "plain code line"]- if not bare or "\x1b[" not in bare[0]:- print("FAIL bare fence: not styled uniformly on the TS side")- failures.append("bare-fence")---def loader_rows(session, report_frames, label, root):- """Dense mid-stream capture; every working-loader row, normalized- (spinner/elapsed/token-count out, ANSI placement in)."""- rows = set()- for step in range(24):- frame = tp.capture(session)- report_frames.append((f"{label}-{step:02d}", frame))- for line in frame.split("\n"):- plain = tp.strip_ansi(line)- if re.match(f"^ [{SPINNERS}] Thinking", plain):- rows.add(tp.normalize(line + "\n", root).strip("\n"))- time.sleep(0.2)- return rows---def loader_compare(base, out_dir, failures):- """LIVE: stream the slow mock into both binaries and compare the- normalized loader rows (the SGR boundary on the spinner->label gap)."""- port, server = start_slow_mock()- sandboxes = tp.prepare_sandbox(base, {- "ts": f"http://127.0.0.1:{port}/v1",- "rust": f"http://127.0.0.1:{port}/v1",- })- sides = {}- report_frames = []- try:- for side, binary in (("ts", TS_BIN), ("rust", RUST_BIN)):- sandbox = sandboxes[side]- session = f"tuipolish-{side}"- tp.tmux("kill-session", "-t", session, check=False)- tp.tmux("new-session", "-d", "-s", session, "-x", "120", "-y", "90",- "-c", sandbox["cwd"])- env = (f"HOME={sandbox['home']} TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"PRIME_AGENT_DISABLE_ANALYTICS=1")- package_dir = os.path.abspath(- os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")- )- extra = f"PI_PACKAGE_DIR={package_dir}" if side == "rust" else ""- command = (f"{env} {extra} {binary} --provider prime-inference "- f"--model mock-1 --offline --daemon-socket {sandbox['agent']}/daemon.sock")- tp.tmux("send-keys", "-t", session, command, "Enter")- time.sleep(10)- tp.tmux("send-keys", "-t", session, LIVE_PROMPT, "Enter")- sides[side] = loader_rows(session, report_frames, side, base)- tp.tmux("kill-session", "-t", session, check=False)- finally:- listing = tp.tmux("list-sessions", "-F", "#{session_name}", check=False)- for name in listing.split():- if name.startswith("tuipolish-"):- tp.tmux("kill-session", "-t", name, check=False)- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- server.shutdown()- server.server_close()-- with open(os.path.join(out_dir, "loader-probe-frames.txt"), "w") as f:- for label, frame in report_frames:- f.write(f"===== {label}\n{frame}\n")- with open(os.path.join(out_dir, "loader-rows.txt"), "w") as f:- for side in ("ts", "rust"):- f.write(f"===== {side} normalized loader rows\n")- for row in sorted(sides[side]):- f.write(repr(row) + "\n")-- for side in ("ts", "rust"):- if not sides[side]:- print(f"FAIL loader-{side}: no loader row captured while streaming")- failures.append(f"loader-{side}-absent")- if sides["ts"] == sides["rust"] and sides["ts"]:- # The pen reset must sit on the gap: the spinner's color run is- # closed by ESC[39m before the plain space and the label.- row = sorted(sides["ts"])[0]- if re.search(f"\x1b\[39m \x1b\[38;2;[0-9;]+mThinking", row):- print("PASS loader-row (byte-identical rows, ESC[39m gap reset)")- else:- print(f"FAIL loader-row: gap reset missing: {row!r}")- failures.append("loader-row-reset")- else:- print("FAIL loader-row: normalized row sets differ (see loader-rows.txt)")- failures.append("loader-row-set")---def main():- global RUST_BIN, RUST_REPLAY_BIN- rust_dir = os.environ.get(- "PA_RUST_DIR", os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))- )- RUST_BIN = os.path.join(rust_dir, "target", "debug", "prime-agent")- RUST_REPLAY_BIN = os.path.join(rust_dir, "target", "debug", "pa-tui-replay")- for path in (RUST_BIN, RUST_REPLAY_BIN):- if not os.path.exists(path):- raise SystemExit(f"missing {path}; build first")-- ts_identity.assert_ts_side_is_the_ts_product(ts_bin=TS_BIN)-- default_out = os.path.join(- os.path.dirname(os.path.abspath(__file__)),- "tui-polish-runs", time.strftime("%Y-%m-%d-tui-polish"),- )- out_dir = os.environ.get("OUT_DIR", default_out)- os.makedirs(out_dir, exist_ok=True)-- base = tempfile.mkdtemp(prefix="tui-polish-")- failures = []- # Two independent mocks (the shared machinery runs one per side set).- ts_mock = tp.start_mock(base)- rust_mock = tp.start_mock(base)- try:- sandboxes = tp.prepare_sandbox(base, {- "ts": f"http://127.0.0.1:{ts_mock[0]}/v1",- "rust": f"http://127.0.0.1:{rust_mock[0]}/v1",- "ts-replay": None,- "rust-replay": None,- })- session_path = build_session(- os.path.join(base, "tui-polish-session.jsonl"),- tp.newest_assistant_envelope(),- os.path.join(base, "cwd"),- )- replay_compare(session_path, sandboxes, out_dir, failures)- ts_mock[2].shutdown()- ts_mock[2].server_close()- rust_mock[2].shutdown()- rust_mock[2].server_close()- loader_compare(base, out_dir, failures)- finally:- batterylib.reap_daemons(needles=[base], cwd_roots=[base])-- print(f"evidence in {out_dir}")- if failures:- print(f"FAILURES: {failures}")- return 1- print("ALL TUI-POLISH PARITY CHECKS PASSED")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/utility_command_parity.py b/scripts/utility_command_parity.pydeleted file mode 100755index 42125a86d7..0000000000--- a/scripts/utility_command_parity.py+++ /dev/null@@ -1,278 +0,0 @@-#!/usr/bin/env python3-"""Per-command live A/B parity captures for the utility-commands lane-(`/btw`, `/side`, `/fast`, `/fullscreen`, `/reload`, `/rlm-max-depth`,-`/scoped-models`, `/settings`, `/name`+`/rename`, `/thinking`).--Both binaries run in tmux against their own mock provider and daemon (the-battery's isolation rules): each command drives one scripted interaction,-the frame lands under scripts/battery/runs/<stamp>/utility-commands/<side>/,-and the normalized frames byte-diff per command.--One-command re-run (from the repo root):-- python3 scripts/utility_command_parity.py [--ts-bin PATH] [--rust-bin PATH]--The Rust binary defaults to target/release/prime-agent.-"""--from __future__ import annotations--import argparse-import datetime-import difflib-import json-import re-import shutil-import sys-import time-from pathlib import Path--sys.path.insert(0, str(Path(__file__).parent / "battery"))-import batterylib as B # noqa: E402-import perf as P # noqa: E402--FLOW = "utility-commands"---def normalize_frame(frame: str, side: B.Side) -> str:- """Strip the volatile frame contents: versions, paths, ids, timestamps,- and the usage/cost label (the Rust debug build reports 0.0.0)."""- text = frame- # Version labels (the TS release vs the Rust 0.0.0 build), paths, ids,- # and cost figures are the volatile frame contents.- text = re.sub(r"v\d+\.\d+\.\d+", "v<version>", text)- home = str(Path.home())- text = text.replace(str(side.work_dir), "<work>")- # The TS product abbreviates the home prefix as `~`.- text = text.replace("~/" + str(side.work_dir.relative_to(home)), "<work>")- text = text.replace(str(side.agent_dir), "<agent>")- text = text.replace(str(side.root), "<run>")- text = re.sub(r"\$[0-9]+\.[0-9]+", "$<cost>", text)- # Session ids and the elapsed clock digits on loaders.- text = re.sub(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", "<uuid>", text)- # Layout noise: the TS inline surface appends rows into native- # scrollback while the Rust surface repaints a fixed fullscreen frame,- # so blank padding differs. The content sequence (non-blank rows) is- # the comparable artifact.- return "\n".join(- line.rstrip() for line in text.splitlines() if line.strip()- )---class UtilityParity:- def __init__(self, ts_bin: str, rust_bin: str):- self.stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")- self.run_dir = Path(__file__).resolve().parents[1] / "scripts" / "battery" / "runs" / self.stamp- self.run_dir.mkdir(parents=True)- self.ts_bin = ts_bin- self.rust_bin = rust_bin- self.runid = "util" + self.stamp- self.sides: dict[str, B.Side] = {}- self.findings: list[dict] = []-- def make_side(self, name: str, binary: str) -> B.Side:- root = self.run_dir / name- root.mkdir(parents=True, exist_ok=True)- agent = root / "agent"- work = root / "work"- work.mkdir(parents=True, exist_ok=True)- if agent.exists():- shutil.rmtree(agent)- agent.mkdir(parents=True)- mock = B.MockProvider(root, [])- mock.set_responses([{"text": "the mock side answer"}])- mock.start()- tmpdir = Path("/tmp") / f"{self.runid}-{name}"- if tmpdir.exists():- shutil.rmtree(tmpdir)- tmpdir.mkdir(parents=True)- side = B.Side(- name=name,- binary=binary,- root=root,- agent_dir=agent,- work_dir=work,- daemon_socket=root / "daemon.sock",- mock=mock,- )- side.env = B.scrubbed_env(agent, tmpdir)- if name == "rust":- side.env["PI_PACKAGE_DIR"] = str(Path(__file__).resolve().parents[1])- side.env["PRIME_API_KEY"] = "sk-battery"- side.write_models_json()- self.sides[name] = side- return side-- def evidence(self, side: B.Side, name: str, frame: str) -> None:- (side.root / FLOW).mkdir(parents=True, exist_ok=True)- (side.root / FLOW / name).write_text(frame)-- def record(self, summary: str, command: str, gap: bool) -> None:- self.findings.append({"command": command, "summary": summary, "gap": gap})-- def launch(self, side: B.Side) -> str:- """One settled interactive pane per side; every command drives it."""- session = f"{self.runid}-{side.name}"- argv = P.launch_argv(side, side.daemon_socket)- B.tmux_launch(session, argv, side.env, side.work_dir)- # A fresh install shows the trace-sharing notice on the TS side: press- # through like the battery's f1 (Down + Enter = Not now).- frame = B.tmux_wait_text(session, "Share agent traces|>|manage", timeout=30)- if "Share agent traces" in frame:- B.tmux_send(session, "Down")- time.sleep(0.5)- B.tmux_send(session, "Enter")- time.sleep(2.0)- # Wait for the settled main screen (two identical frames).- deadline = time.time() + 30- stable = False- while time.time() < deadline and not stable:- first = B.tmux_capture(session)- time.sleep(1.5)- second = B.tmux_capture(session)- stable = first == second and (">" in first or "manage" in first)- if not stable:- self.record(f"{side.name}: TUI never reached a stable main screen", "launch", gap=True)- return session-- def run_command(self, side: B.Side, session: str, steps: list[tuple[str, str]], name: str) -> str:- """Send one command's keys, waiting for `settle` between them; the- final frame is the capture."""- for keys, settle in steps:- B.tmux_send(session, keys, enter=keys != "Escape")- time.sleep(settle)- return B.tmux_capture(session)-- def run(self) -> int:- for name, binary in (("ts", self.ts_bin), ("rust", self.rust_bin)):- self.make_side(name, binary)- frames: dict[str, dict[str, str]] = {"ts": {}, "rust": {}}- for side_name in ("ts", "rust"):- side = self.sides[side_name]- session = self.launch(side)- # /name + /rename: set through the alias, then report.- frames[side_name]["name-set"] = self.run_command(- side,- session,- [("/rename parity session", 1.5), ("/name", 2.0)],- "name",- )- # /rlm-max-depth: view, then set.- frames[side_name]["rlm-max-depth-view"] = self.run_command(- side, session, [("/rlm-max-depth", 2.0)], "rlm-max-depth"- )- frames[side_name]["rlm-max-depth-set"] = self.run_command(- side, session, [("/rlm-max-depth 3", 2.0)], "rlm-max-depth"- )- # /fast: the mock model is not fast-mode eligible, so the TS- # unavailable status row shows on both sides.- frames[side_name]["fast"] = self.run_command(- side, session, [("/fast", 2.0)], "fast"- )- # /fullscreen: off then on — the persisted-preference status rows.- frames[side_name]["fullscreen-off"] = self.run_command(- side, session, [("/fullscreen off", 2.0)], "fullscreen"- )- frames[side_name]["fullscreen-on"] = self.run_command(- side, session, [("/fullscreen on", 2.0)], "fullscreen"- )- # /reload: the guarded reload + outcome status.- frames[side_name]["reload"] = self.run_command(- side, session, [("/reload", 3.0)], "reload"- )- # /btw: the side-question pane, a follow-up, the notice, and esc.- frames[side_name]["btw"] = self.run_command(- side,- session,- [- ("/btw what is the mock answer", 4.0),- ("and follow up please", 4.0),- ("/model", 1.5),- ("Escape", 1.5),- ],- "btw",- )- # /settings: the menu frame, one row change, then esc.- frames[side_name]["settings"] = self.run_command(- side,- session,- [("/settings", 2.0), ("Enter", 1.5), ("Escape", 1.5)],- "settings",- )- # /scoped-models: the selector frame, a toggle, then esc.- frames[side_name]["scoped-models"] = self.run_command(- side,- session,- [- ("/scoped-models", 2.0),- ("Enter", 1.5),- ("Escape", 1.5),- ],- "scoped-models",- )- # /thinking: the alias opens the effort surface.- frames[side_name]["thinking"] = self.run_command(- side,- session,- [("/thinking", 2.0), ("Escape", 1.5)],- "thinking",- )- for capture_name, frame in frames[side_name].items():- self.evidence(side, f"{capture_name}.txt", frame)- B.tmux_kill(session)- side.mock.stop()-- # Compare: normalized frames per command.- report = [f"# Utility-command parity run {self.stamp}", ""]- gaps = 0- for capture_name in frames["ts"]:- ts_text = normalize_frame(frames["ts"][capture_name], self.sides["ts"])- rust_text = normalize_frame(frames["rust"][capture_name], self.sides["rust"])- diff = list(- difflib.unified_diff(- ts_text.splitlines(), rust_text.splitlines(), "ts", "rust", lineterm="", n=1- )- )- match = not diff- if not match:- gaps += 1- self.record(- f"{capture_name}: {'identical (normalized)' if match else 'frames differ'}",- capture_name,- gap=not match,- )- report.append(f"## {capture_name}")- report.append("")- report.append(f"- ts: `{FLOW}/{capture_name}.txt`")- report.append(f"- rust: `{FLOW}/{capture_name}.txt`")- report.append(f"- verdict: {'match' if match else 'DIFF'}")- if not match:- report.append("")- report.append("```diff")- report.extend(diff[:40])- report.append("```")- report.append("")- (self.run_dir / "utility-commands-report.md").write_text("\n".join(report) + "\n")- (self.run_dir / "utility-commands-findings.json").write_text(- json.dumps({"stamp": self.stamp, "findings": self.findings}, indent=2) + "\n"- )- print(f"frames: {self.run_dir}")- for finding in self.findings:- mark = "GAP " if finding["gap"] else "PASS"- print(f"[{mark}] {finding['command']}: {finding['summary']}")- print(f"report: {self.run_dir / 'utility-commands-report.md'}")- return 1 if gaps else 0---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--ts-bin", default="prime-agent")- parser.add_argument(- "--rust-bin", default=str(Path(__file__).resolve().parents[1] / "target" / "release" / "prime-agent")- )- args = parser.parse_args()- return UtilityParity(args.ts_bin, args.rust_bin).run()---if __name__ == "__main__":- raise SystemExit(main())diff --git a/scripts/visual_parity.py b/scripts/visual_parity.pydeleted file mode 100755index 4342a4ad3a..0000000000--- a/scripts/visual_parity.py+++ /dev/null@@ -1,690 +0,0 @@-#!/usr/bin/env python3-"""Interactive TUI visual-parity verifier: frame-diff the Rust interactive-UI against the installed TS prime-agent binary in tmux.--Drives both binaries to the same defined states (fresh start, one turn with a-tool call, a second turn rendering a markdown table and links, thinking-visible via Ctrl+O, the working spinner mid-turn, the mouse-wheel-scroll/follow cycle driven by byte-identical SGR wheel reports, and the-in-app mouse selection: a press-drag-release over rendered transcript-text whose OSC 52 clipboard copy is byte-compared from the pane's raw-output) at 120x36 and 220x50, captures the rendered-panes with escape sequences, normalizes volatile content, and reports-per-state frame diffs. Exit code is non-zero when any state differs.--The TS side is driven through the faux provider registered by a sandbox-extension (the harness equivalent of the test suite's registerFauxProvider-fixtures); the Rust side runs the real agent engine over the same scripted-faux provider through `PRIME_AGENT_FAUX_SCRIPT` ({"engine": "faux", ...}).--tmux rules: default socket only (`env -u TMUX`), vplane-* session names,-no kill-server; sessions are killed individually at the end.-"""--import argparse-import base64-import difflib-import json-import os-import re-import shutil-import subprocess-import sys-import tempfile-import time--sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery"))-import batterylib # noqa: E402 (the shared daemon-reap sweep)-import ts_identity # noqa: E402 (the shared PATH-binary identity guard)--TS_SCRIPT_MODEL = "faux-1"-SIZES = [("120", "36"), ("220", "50")]--# The scripted queue both binaries consume, in request order. Turn 1 makes-# two model requests — the response below (thinking, a text block, an ipython-# tool call), then a continuation after the tool result — and turn 2 makes-# one. A toolUse response always consumes the next queued response too, so-# turn 1 takes two scripted responses. Content is identical on both sides so-# the frames compare content-for-content.-# The table/link-bearing turn: exercises the GFM table block (header,-# delimiter row, body rows) and both link forms, including a mixed-width-# CJK cell so column measurement shows up in the frame diff.-TABLE_AND_LINKS_TURN = (- "Here is the status board:\n"- "\n"- "| Task | State | Notes |\n"- "| --- | --- | --- |\n"- "| alpha | done | shipped in v1.0 |\n"- "| beta \u6570\u636e | running | wraps when narrow |\n"- "| gamma | pending | blocked on upstream |\n"- "\n"- "See the [docs](https://example.com/docs) and the [changelog](https://example.com/log)."-)--SECOND_PROMPT = "Show me the status table."--# Turn 1's final answer, served to the post-tool continuation request (the-# daemon re-requests the model after a toolUse response) so state b settles-# on the tool-call card plus this answer.-TURN1_FINAL_ANSWER = "The check printed the expected marker. Anything else?"--FAUX_SCRIPT = {- "engine": "faux",- "modelId": "faux-1",- "modelName": "Faux Model",- "reasoning": False,- "contextWindow": 128000,- "tokensPerSecond": 18,- "responses": [- {- "content": [- {- "type": "thinking",- "thinking": "The user wants a quick check. I will run a short Python cell in the persistent kernel and report the result.",- },- {"type": "text", "text": "Let me run a quick check."},- {- "type": "toolCall",- "name": "ipython",- "id": "toolu_visual01",- "arguments": {"code": "print('visual parity ok')"},- },- ]- },- # Turn 1 continuation after the ipython tool result (state b).- {"content": [{"type": "text", "text": TURN1_FINAL_ANSWER}]},- # Turn 2: markdown table + links (state e_table_and_links).- {"content": [{"type": "text", "text": TABLE_AND_LINKS_TURN}]},- ],-}--# The TS extension registers the faux provider and scripts its responses from-# PRIME_AGENT_FAUX_SCRIPT (mirrors the test-suite registerFauxProvider fixture).-# It also serves the daemon's post-turn dashboard status-line request from a-# canned empty verdict, so a daemon whose status line falls back to the session-# model cannot consume a scripted response and desync the queue.-# Shared with tool_card_parity.py and compact_parity.py: one extension source-# for every harness.-TS_FAUX_EXTENSION = open(- os.path.join(os.path.dirname(os.path.abspath(__file__)), "ts_faux_extension.js"),- encoding="utf-8",-).read()--PROMPT = "Run a quick check."--# Spinner + working-icon frames (chat.rs LOADER_FRAMES / WORKING_ICON_FRAMES).-SPINNER_CHARS = "\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f\u25f4\u25f7\u25f6\u25f5\u25cb\u25f8\u25fb\u25fc"-# A character class over the spinner glyphs: `re.search(SPINNER_CHARS, ...)`-# would match the literal sequence instead of any single glyph.-SPINNER_CLASS = "[" + SPINNER_CHARS + "]"---def find_runtime_package_dir():- """Locate the installed TS release directory (ships prime-agent-runtime)."""- releases = os.path.expanduser("~/.local/share/prime-agent/releases")- if not os.path.isdir(releases):- raise SystemExit(- "cannot find the prime-agent-runtime sidecar; set PI_PACKAGE_DIR "- "to a directory containing prime-agent-runtime/"- )- candidates = [- entry- for entry in sorted(os.listdir(releases))- if os.path.isdir(- os.path.join(releases, entry, "prime-agent-runtime")- )- ]- if not candidates:- raise SystemExit(- "no release with prime-agent-runtime/ under " + releases- )- return os.path.join(releases, candidates[-1])---STATES = [- ("a_fresh_start", "fresh splash with model and cwd lines"),- ("b_turn_with_tool", "idle after a turn containing a tool-call card"),- ("e_table_and_links", "idle after a turn rendering a markdown table and links"),- ("c_thinking_visible", "conversation detail (Ctrl+O): thinking block visible"),- ("d_spinner", "working loader mid-turn"),- ("f_tree_pane", "the /tree selector pane over the settled session"),- ("g_fork_pane", "the /fork user-message selector over the settled session"),- ("f_kernel_boot", "python-kernel boot: the tool-owned loader note mid-turn"),- ("h_mouse_scrolled", "mouse wheel-up: SGR reports scroll the transcript off the tail"),- ("i_mouse_follow", "mouse wheel-down: back at the tail, following resumed"),- ("j_mouse_selected", "mouse press-drag: the spanned transcript row renders selected"),- ("k_mouse_copied", "mouse release: the selection cleared, the spanned text copied out"),- ("l_mouse_copy", "the OSC 52 clipboard sequence the release emitted"),-]--# SGR wheel press reports, the bytes a real terminal emits with ?1002+?1006-# tracking active: ESC [ < 64;10;10 M (wheel up) / 65 (wheel down). tmux-# `send-keys -H` writes the raw bytes into the pane's stdin, so both-# binaries parse the same report stream a terminal mouse would send.-WHEEL_UP_HEX = "1b 5b 3c 36 34 3b 31 30 3b 31 30 4d".split()-WHEEL_DOWN_HEX = "1b 5b 3c 36 35 3b 31 30 3b 31 30 4d".split()--# Wheel turns per scroll state: six ups lift the view eighteen lines off the-# tail (well past one screen of transcript); eight downs over-scroll back so-# the clamp at the bottom is the settled state both sides reach.-MOUSE_WHEEL_UP_TURNS = 6-MOUSE_WHEEL_DOWN_TURNS = 8--# The transcript text the selection states drag across (the second turn's-# answer): located per binary in the rendered pane, dragged from its first-# cell to its last, so the OSC 52 copy is exactly this string.-SELECTION_NEEDLE = "Here is the status board:"---def send_wheel_report(session, report_hex, turns):- """Send `turns` SGR wheel reports, spaced so each arrives as its own- read (a merged chunk would coalesce into one input delivery)."""- for _ in range(turns):- tmux("send-keys", "-t", session, "-H", *report_hex)- time.sleep(0.1)---def sgr_hex(sequence):- """The `send-keys -H` hex form of one raw byte sequence."""- return [f"{byte:02x}" for byte in sequence.encode("latin1")]---def send_mouse_report(session, sequence):- """Send one raw SGR mouse report into the pane's stdin."""- tmux("send-keys", "-t", session, "-H", *sgr_hex(sequence))---def mouse_press(col, row):- """SGR left-button press at a one-based terminal cell."""- return f"\x1b[<0;{col};{row}M"---def mouse_drag(col, row):- """SGR left-button motion (button 0 + the motion bit) — a held drag."""- return f"\x1b[<32;{col};{row}M"---def mouse_release(col, row):- """SGR left-button release at a one-based terminal cell."""- return f"\x1b[<0;{col};{row}m"---def locate_plain(pane_text, needle):- """The needle's (row, column) in a plain (escape-free) pane capture."""- for row, line in enumerate(pane_text.split("\n")):- col = line.find(needle)- if col >= 0:- return row, col- return None---def osc52_copies(raw):- """The OSC 52 clipboard sequences (ESC ] 52 ; c ; <base64> BEL) a pane's- raw output stream carried, in order."""- return re.findall("\x1b\]52;c;([A-Za-z0-9+/=]+)\x07", raw)---def tmux(*args, check=True):- """Run a tmux command on the default socket (never inside TMUX)."""- result = subprocess.run(- ["env", "-u", "TMUX", "tmux", *args],- capture_output=True,- text=True,- )- if check and result.returncode != 0:- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")- return result.stdout---def capture(session, escape=True):- flag = "-e" if escape else "-p"- return tmux("capture-pane", flag, "-p", "-t", session)---def normalize(frame, root):- """Normalize volatile content so stable chrome compares equal."""- frame = frame.replace(root, "<SANDBOX>")- # Product versions differ between the binaries.- frame = re.sub(r"v\d+\.\d+\.\d+", "vX.X.X", frame)- # Session ids (12-hex display ids).- frame = re.sub(r"\b[0-9a-f]{12}\b", "<SID>", frame)- # Durations ("2ms", "1.2s", "0.0s").- frame = re.sub(r"\b\d+(\.\d+)?(ms|s)\b", "<T>", frame)- # Context usage in the tray: "6.1k (5%)", "72 (0%)".- frame = re.sub(r"\d+(\.\d+)?[kM]? \(\d+%\)", "<TOK> (<PCT>)", frame)- # Loader token counts and elapsed seconds.- frame = re.sub(r"[\u2193\u2191] [\d.kM]+ tokens", "<DIR> <TOK> tokens", frame)- frame = re.sub(r"\b\d+s\b", "<S>", frame)- # Spinner and working-icon animation frames.- spinners = "".join("\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f")- frame = re.sub("[" + spinners + "]", "<SPIN>", frame)- # TS `WORKING_ICON_FRAMES` (◇◈◆◈) and the pre-parity Rust set.- pulses = "".join("\u25c7\u25c8\u25c6\u25f4\u25f7\u25f6\u25f5\u25cb\u25f8\u25fb\u25fc")- frame = re.sub("[" + pulses + "]", "<PULSE>", frame)- # tmux places the trailing foreground-reset (\x1b[39m) differently for- # identical screens: at the end of the row whose styled text just ended,- # or before the next row's default margin. Both describe default-colored- # cells, so drop boundary resets before comparing. The same applies to- # the background-reset (\x1b[49m) the editor line leaves on the blank- # rows above a message: tmux attaches it to the end of the last blank- # row or to the message row's leading space.- frame = re.sub("\x1b\[39m\n", "\n", frame)- frame = re.sub("\n\x1b\[39m(?= )", "\n", frame)- frame = re.sub("\x1b\[49m\n", "\n", frame)- frame = re.sub("\n\x1b\[49m(?= )", "\n", frame)- # The loader row's spinner-to-label gap: TS resets the spinner color and- # leaves the separator space default-colored; Rust carries the label- # color across the space. A space's foreground is invisible either way,- # so canonicalize both to the TS shape (space before the label color).- frame = re.sub(r"(?<=<SPIN>)\x1b\[39m (?=\x1b\[38;2;161;161;170m)", " ", frame)- frame = re.sub(- r"(?<=<SPIN>)\x1b\[38;2;161;161;170m (?=\S)", " \x1b[38;2;161;161;170m", frame- )- # The right-aligned tray: its padding shifts when the volatile context- # usage strings (already normalized above) had different widths, so- # collapse the padding run before the tray's model segment.- frame = re.sub(r" +(\x1b\[38;2;113;113;122mfaux-1 \u00b7 )", r" \1", frame)- # The selection-background row: the pi-tui writer's escape placement- # inside the selection wrap varies between runs of the same binary- # (bold-on for the role label, fg resets mid-row, the trailing reset- # bundle), so the tree pane's selected row compares by visible text.- frame = re.sub(- "(\x1b\[38;2;[0-9;]+m)?\x1b\[48;2;34;34;38m[^\n]*",- lambda m: re.sub("\x1b\[[0-9;]*m", "", m.group(0)),- frame,- )- # Reverse-video rows (the in-app mouse-selection highlight, the follow- # hint): the TS writer strips the span's styling and resets before and- # after it while ratatui's diff places its reset bundle at the row end,- # so identical reversed rows differ in escape placement alone. Those- # rows compare by visible text.- frame = re.sub(- "^[^\n]*\x1b\[7m[^\n]*$",- lambda m: re.sub("\x1b\[[0-9;]*m", "", m.group(0)),- frame,- flags=re.MULTILINE,- )- # Selector list rows (the `› ` cursor prefix): same writer variance for- # the accent cursor and the bold selected row.- frame = re.sub(- "^.*› .*$",- lambda m: re.sub("\x1b\[[0-9;]*m", "", m.group(0)),- frame,- flags=re.MULTILINE,- )- return frame---def diff_lines(left, right):- return "\n".join(- difflib.unified_diff(- left.split("\n"), right.split("\n"),- fromfile="ts", tofile="rust", lineterm="", n=1,- )- )---def prepare_sandbox(base):- """Create the per-binary sandboxes and the shared cwd fixture."""- shared_cwd = os.path.join(base, "shared-cwd")- os.makedirs(shared_cwd, exist_ok=True)- with open(os.path.join(shared_cwd, "alpha.txt"), "w") as f:- f.write("alpha\n")- with open(os.path.join(shared_cwd, "beta.md"), "w") as f:- f.write("# beta\n")-- script_path = os.path.join(base, "faux-script.json")- with open(script_path, "w") as f:- json.dump(FAUX_SCRIPT, f, indent=2)-- sandboxes = {}- for binary in ("ts", "rust"):- home = os.path.join(base, binary, "home")- agent = os.path.join(base, binary, "agent")- tmp = os.path.join(base, binary, "tmp")- os.makedirs(home, exist_ok=True)- os.makedirs(tmp, exist_ok=True)- os.makedirs(os.path.join(agent, "extensions"), exist_ok=True)- os.makedirs(os.path.join(agent, "sessions"), exist_ok=True)- with open(os.path.join(agent, "settings.json"), "w") as f:- json.dump({"onboardingCompleted": True}, f)- # The isolated TMPDIR keeps the TS supervisor's socket (the- # default daemon-socket dir) off the shared box root, so the- # cleanup reap can sweep this side's daemons by path alone.- sandboxes[binary] = {"home": home, "agent": agent, "tmp": tmp}- with open(- os.path.join(sandboxes["ts"]["agent"], "extensions", "visual-faux.js"), "w"- ) as f:- f.write(TS_FAUX_EXTENSION)- return shared_cwd, script_path, sandboxes---def wait_for(session, needle, timeout):- deadline = time.time() + timeout- while time.time() < deadline:- pane = capture(session, escape=False)- if needle in pane:- return- time.sleep(0.3)- raise TimeoutError(f"session {session} never showed {needle!r}")---def run_session(binary, sandbox, shared_cwd, script_path, size, out_dir, session_prefix):- """Drive one binary through the defined states, capturing each frame."""- width, height = size- session = f"vplane-{session_prefix}-{binary}-{width}x{height}"- tmux("kill-session", "-t", session, check=False)- tmux("new-session", "-d", "-s", session, "-x", width, "-y", height, "-c", shared_cwd)- env = (- f"HOME={sandbox['home']} "- f"TMPDIR={sandbox['tmp']} "- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "- f"PRIME_AGENT_FAUX_SCRIPT={script_path} "- "PRIME_AGENT_DISABLE_ANALYTICS=1"- )- if binary == "ts":- command = (- f"prime-agent --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {TS_SCRIPT_MODEL}"- )- else:- rust = os.environ.get(- "PA_RUST_BINARY",- os.path.join(- os.path.dirname(os.path.abspath(__file__)), "..", "target", "debug", "prime-agent"- ),- )- # The Rust kernel needs the prime-agent-runtime sidecar (the TS- # release ships it next to its binary; the Rust build tree does not).- package_dir = os.environ.get("PI_PACKAGE_DIR") or find_runtime_package_dir()- command = (- f"PI_PACKAGE_DIR={package_dir} "- f"{rust} --daemon-socket {sandbox['agent']}/daemon.sock "- f"--model {TS_SCRIPT_MODEL}"- )- tmux("send-keys", "-t", session, f"{env} {command}", "Enter")-- frames = {}- # (a) fresh start: wait for the splash + editor to settle.- wait_for(session, "Collapsed mode", timeout=40)- time.sleep(1.0)- frames["a_fresh_start"] = capture(session)-- # Submit the turn.- tmux("send-keys", "-t", session, PROMPT)- tmux("send-keys", "-t", session, "Enter")-- # (d) spinner: the working loader mid-turn. The loader's Thinking phase- # renders identically on both binaries (a spinner glyph, the activity- # label, elapsed seconds, and the streaming token count) and lasts ~1s- # at the scripted 18 tokens/second, so poll for the loader row and- # capture immediately, still inside the phase. The Thinking-phase- # needle must match the row as rendered ("Thinking ·"), not the- # activity name alone.- deadline = time.time() + 60- while time.time() < deadline:- pane = capture(session, escape=False)- if re.search(r"Thinking \u00b7", pane):- break- time.sleep(0.1)- else:- raise TimeoutError(- f"session {session} never showed the Thinking loader row"- )- frames["d_spinner"] = capture(session)-- # (f) kernel boot: the first ipython call boots the python kernel- # (one-time, ~30s in a fresh sandbox HOME). While it runs, the tool- # owns the loader note and both binaries render the same row- # ("⠹ › setting up python kernel (one-time, ~30s)…" plus elapsed): TS- # via the extension-UI setWorkingMessage request, Rust from the same- # stage text carried by the tool's `starting` partials. The session-create- # prewarm moved the boot ahead of the prompt on a warm box (the- # runtime sidecar's venv is already installed), so the note is- # best-effort: poll for a bounded window and capture inside it; a- # warm boot has no note to show and the state is skipped on both- # sides (spinner frames and elapsed seconds normalize).- deadline = time.time() + 20- while time.time() < deadline:- pane = capture(session, escape=False)- if "setting up python kernel" in pane:- frames["f_kernel_boot"] = capture(session)- break- time.sleep(0.5)-- # (b) idle after the turn: the final answer rendered AND the loader row- # is gone (the spinner line disappears once the turn ends).- deadline = time.time() + 120- while time.time() < deadline:- pane = capture(session, escape=False)- if "Anything else?" in pane and not re.search(SPINNER_CLASS, pane):- break- time.sleep(0.3)- time.sleep(1.0)- frames["b_turn_with_tool"] = capture(session)-- # (f) the /tree selector pane: opens over the settled session right- # after the first turn (the double-Escape shortcut would need two- # presses within 500ms; the command path is the stable one). Captured- # before the table turn, whose scripted-response exhaustion leaves a- # failed turn in the transcript. Esc closes it before the next state.- tmux("send-keys", "-t", session, "/tree")- tmux("send-keys", "-t", session, "Enter")- wait_for(session, "Session Tree", timeout=15)- time.sleep(1.0)- frames["f_tree_pane"] = capture(session)- tmux("send-keys", "-t", session, "Escape")- time.sleep(0.5)-- # (g) the /fork user-message selector: same mount, same escape-close.- tmux("send-keys", "-t", session, "/fork")- tmux("send-keys", "-t", session, "Enter")- wait_for(session, "Fork from Message", timeout=15)- time.sleep(1.0)- frames["g_fork_pane"] = capture(session)- tmux("send-keys", "-t", session, "Escape")- time.sleep(0.5)-- # (e) table + links: submit a second turn whose response carries a- # markdown table and links; capture the settled frame. The faux queue- # holds two responses (the first turn's post-tool continuation consumes- # the table), so the second turn settles on its provider error — wait- # for that row, not the table text (it already rendered in turn 1).- tmux("send-keys", "-t", session, SECOND_PROMPT)- tmux("send-keys", "-t", session, "Enter")- deadline = time.time() + 120- while time.time() < deadline:- pane = capture(session, escape=False)- if "No more faux responses queued" in pane and not re.search(SPINNER_CLASS, pane):- break- time.sleep(0.3)- time.sleep(1.0)- frames["e_table_and_links"] = capture(session)-- # (c) thinking visible: Ctrl+O toggles conversation detail.- tmux("send-keys", "-t", session, "C-o")- try:- wait_for(session, "Details mode", timeout=10)- except TimeoutError:- pass- time.sleep(1.0)- frames["c_thinking_visible"] = capture(session)-- # (h) mouse wheel-up: byte-identical SGR wheel reports scroll the- # transcript window three lines per turn; MOUSE_WHEEL_UP_TURNS turns- # lift the view off the tail (the follow hint appears over the last- # transcript row).- send_wheel_report(session, WHEEL_UP_HEX, MOUSE_WHEEL_UP_TURNS)- time.sleep(1.0)- frames["h_mouse_scrolled"] = capture(session)-- # (i) mouse wheel-down: scroll back; the clamp at the bottom settles- # both binaries at the tail with following resumed.- send_wheel_report(session, WHEEL_DOWN_HEX, MOUSE_WHEEL_DOWN_TURNS)- time.sleep(1.0)- frames["i_mouse_follow"] = capture(session)-- # (j-k-l) in-app mouse selection: byte-identical SGR press/drag/release- # reports drag across the second turn's answer text; the pane's raw- # output stream (pipe-pane) records the OSC 52 clipboard copy the- # release emits. The needle's rendered cell is located per binary so- # both drag the same rendered text (the frames already compare equal- # at this point, so the cells match).- plain = capture(session, escape=False)- located = locate_plain(plain, SELECTION_NEEDLE)- if located is None:- raise TimeoutError(- f"session {session} never showed the selection needle {SELECTION_NEEDLE!r}"- )- needle_row, needle_col = located- pane_raw = os.path.join(sandbox["tmp"], "pane-osc52.raw")- if os.path.exists(pane_raw):- os.remove(pane_raw)- tmux("pipe-pane", "-t", session, f"cat > {pane_raw}")- send_mouse_report(session, mouse_press(needle_col + 1, needle_row + 1))- time.sleep(0.3)- send_mouse_report(session, mouse_drag(needle_col + 1 + len(SELECTION_NEEDLE), needle_row + 1))- time.sleep(0.5)- frames["j_mouse_selected"] = capture(session)- selected = capture(session)- needle_prefix = selected.split("\n")[needle_row] if needle_row < len(- selected.split("\n")- ) else ""- if "\x1b[7m" + SELECTION_NEEDLE not in needle_prefix:- raise AssertionError(- f"session {session} did not render the dragged text reversed mid-drag"- )- send_mouse_report(session, mouse_release(needle_col + 1 + len(SELECTION_NEEDLE), needle_row + 1))- time.sleep(0.5)- tmux("pipe-pane", "-t", session)- frames["k_mouse_copied"] = capture(session)- released = frames["k_mouse_copied"]- needle_prefix = released.split("\n")[needle_row] if needle_row < len(- released.split("\n")- ) else ""- if "\x1b[7m" + SELECTION_NEEDLE in needle_prefix:- raise AssertionError(- f"session {session} kept the selection highlighted after the release"- )- with open(pane_raw, "rb") as f:- raw = f.read().decode("latin1")- copies = osc52_copies(raw)- if not copies:- raise AssertionError(- f"session {session} never emitted an OSC 52 copy for the release"- )- decoded = base64.b64decode(copies[-1]).decode("utf-8")- if decoded != SELECTION_NEEDLE:- raise AssertionError(- f"session {session} copied {decoded!r} for the release, expected "- f"{SELECTION_NEEDLE!r}"- )- frames["l_mouse_copy"] = f"\x1b]52;c;{copies[-1]}\x07"-- # Exit: ctrl+c aborts a running turn, a second press exits when idle.- tmux("send-keys", "-t", session, "C-c")- time.sleep(0.5)- tmux("send-keys", "-t", session, "C-c")- time.sleep(1.0)- tmux("kill-session", "-t", session, check=False)-- os.makedirs(out_dir, exist_ok=True)- for state, frame in frames.items():- with open(os.path.join(out_dir, f"{binary}-{state}-{width}x{height}.txt"), "w") as f:- f.write(frame)- return frames---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--sizes", default=",".join(f"{w}x{h}" for w, h in SIZES))- parser.add_argument("--keep", action="store_true", help="keep the sandbox dir")- parser.add_argument(- "--out", default=None, help="captures directory (default: a fresh temp dir)"- )- parser.add_argument(- "--only", default=None, help="run a single binary (ts|rust) for capture shakedown"- )- parser.add_argument(- "--session-prefix",- default="vp",- help="tmux session-name prefix (vplane-<prefix>-<binary>-WxH); distinct "- "prefixes keep concurrent harness runs on the same box from killing "- "each other's sessions",- )- args = parser.parse_args()- sizes = []- for entry in args.sizes.split(","):- width, height = entry.split("x")- sizes.append((width, height))-- # Fail fast before any launch: a non-TS `prime-agent` on PATH (e.g. a- # Rust build symlinked there) plays a Rust build as the "ts" side and- # reports false divergences (see the guard's docstring).- if args.only in (None, "ts"):- ts_identity.assert_ts_side_is_the_ts_product()-- base = tempfile.mkdtemp(prefix="visual-parity-sandbox-")- out_dir = args.out or tempfile.mkdtemp(prefix="visual-parity-captures-")- shared_cwd, script_path, sandboxes = prepare_sandbox(base)- failures = []- try:- if args.only:- run_session(- args.only,- sandboxes[args.only],- shared_cwd,- script_path,- sizes[0],- out_dir,- args.session_prefix,- )- print(f"captures for {args.only} in {out_dir}")- return 0- for size in sizes:- ts_frames = run_session(- "ts", sandboxes["ts"], shared_cwd, script_path, size, out_dir, args.session_prefix- )- rust_frames = run_session(- "rust", sandboxes["rust"], shared_cwd, script_path, size, out_dir, args.session_prefix- )- for state, _ in STATES:- # A best-effort state (the kernel-boot note) skips only- # when BOTH sides skipped it; one side showing what the- # other lacks is a divergence like any other.- if state not in ts_frames or state not in rust_frames:- if state not in ts_frames and state not in rust_frames:- print(f"SKIP {state}-{size[0]}x{size[1]} (absent on both sides)")- continue- missing = "ts" if state not in ts_frames else "rust"- failures.append(f"{state}-{size[0]}x{size[1]}")- print(f"FAIL {state}-{size[0]}x{size[1]} (absent on {missing})")- continue- ts_norm = normalize(ts_frames[state], base)- rust_norm = normalize(rust_frames[state], base)- name = f"{state}-{size[0]}x{size[1]}"- if ts_norm == rust_norm:- print(f"PASS {name}")- else:- print(f"FAIL {name}")- report = os.path.join(out_dir, f"diff-{name}.txt")- with open(report, "w") as f:- f.write(diff_lines(ts_norm, rust_norm))- print(f" diff: {report}")- failures.append(name)- finally:- # Rmtree alone leaks the scenario daemons (a killed TUI pane does- # not take its detached daemon/supervisor pair down; #223): sweep- # every daemon this run spawned before deleting the sandbox.- batterylib.reap_daemons(needles=[base], cwd_roots=[base])- if not args.keep:- shutil.rmtree(base, ignore_errors=True)- if failures:- print(f"{len(failures)} state(s) differ; captures in {out_dir}")- return 1- print(f"all states match; captures in {out_dir}")- return 0---if __name__ == "__main__":- sys.exit(main())