diff --git a/README.md b/README.md index 5e45978..a903552 100644 --- a/README.md +++ b/README.md @@ -456,6 +456,12 @@ caller's address so the agent reports back with `send_message`. It returns once the new session shows in `live ls`; otherwise it prints the agent's screen and exits non-zero. Arguments after `--` go to the harness. +A Claude Code subagent cannot lead peers: it shares its parent's process and +environment, so its replies would reach the parent's conversation. `live whoami`, +`live send` and `live spawn` find the in-flight Bash call in the subagent's +transcript and refuse; start the lead with `live spawn claude` instead. A +subagent calling the MCP tools has no shell to match and is not detected. + The one-conv tools are pre-approved (`send_message`, `set_name`, `list_live_sessions`, `read_conversation`, `search_conversations`, `pack_conversations`, `find_conversations`). `--mode` sets the shell and edit approvals: @@ -477,6 +483,8 @@ one-conv live stop --all --yes `live stop` kills the agent's tmux session and forgets it; its conversation stays readable with `one-conv local`. It only stops agents `live spawn` started on this machine, recorded in `spawned.json` in the live folder, and refuses any other session. +An agent that registers after `live spawn` gave up, once someone answers its prompt, +gets its address there at the next `live stop`. | Harness | One-conv tools approved by | Working folder | | --- | --- | --- | diff --git a/SKILL.md b/SKILL.md index 329e4cf..1f6a50c 100644 --- a/SKILL.md +++ b/SKILL.md @@ -302,6 +302,12 @@ a tmux pane can be attached, and on another machine only a box (`NODE/address` o When a spawned agent's work is done and reported, end it with `one-conv live stop ADDRESS --yes`; `one-conv live stop` lists the agents you can stop. +A Claude Code subagent (started with the Agent tool) cannot be a live peer: it has no +address, and every reply to its parent's address lands in the parent's conversation. +`live whoami`, `live send` and `live spawn` refuse to run from a subagent's Bash tool. To +lead peers, start the lead as its own session with `one-conv live spawn claude`, or share +notes through `one-conv board`. + When the user asks you to continue on another machine of the relay, teleport yourself: the MCP `teleport` tool (`node`, `check_only`, `force`, `cwd`, `mode`), or `one-conv live teleport NODE` from your shell. diff --git a/one_conv/live/claude.py b/one_conv/live/claude.py index 3bbac9d..95a3e80 100644 --- a/one_conv/live/claude.py +++ b/one_conv/live/claude.py @@ -8,6 +8,7 @@ import os import re import socket +import time import uuid from pathlib import Path @@ -105,6 +106,67 @@ def session_for_pid(pid: int) -> LiveSession | None: data.get("status", ""), pid, "socket", data.get("messagingSocketPath") or "") +# A Bash call's transcript line is written just before its shell starts: older files hold none in flight. +RECENT_SECONDS = 600 +TAIL_BYTES = 1 << 20 + + +def _squash(text: str) -> str: + """`text` without quoting, escapes and whitespace, so a command matches the shell line that evals it.""" + return re.sub(r"[\s'\"\\]", "", text.replace("\\012", "")) + + +def pending_commands(lines: list[bytes]) -> list[str]: + """Commands of the Bash tool calls in `lines` that have no result yet.""" + calls: dict[str, str] = {} + for line in lines: + try: + content = json.loads(line).get("message", {}).get("content") + except (ValueError, AttributeError): + continue + for block in content if isinstance(content, list) else []: + if not isinstance(block, dict): + continue + if block.get("type") == "tool_use" and block.get("name") == "Bash": + command = (block.get("input") or {}).get("command") + if isinstance(command, str): + calls[block.get("id")] = command + elif block.get("type") == "tool_result": + calls.pop(block.get("tool_use_id"), None) + return list(calls.values()) + + +def _tail(path: Path) -> list[bytes]: + with path.open("rb") as handle: + handle.seek(max(0, handle.seek(0, os.SEEK_END) - TAIL_BYTES)) + return handle.read().splitlines() + + +def subagent_running(session: LiveSession, shell_line: str, now: float | None = None) -> str | None: + """The subagent id whose in-flight Bash call is `shell_line`; None when it is the main conversation's. + + Subagents share their parent's process and environment; only the transcript holding + the pending call tells them apart. The longest matching command wins, the main + conversation on a tie, and no match counts as the main conversation. + """ + main = transcript(session.id, session.cwd) + shell = _squash(shell_line) + cutoff = (time.time() if now is None else now) - RECENT_SECONDS + best, owner = 0, None + for path in [main, *sorted((main.parent / session.id / "subagents").glob("agent-*.jsonl"))]: + try: + if path.stat().st_mtime < cutoff: + continue + commands = pending_commands(_tail(path)) + except OSError: + continue + for command in commands: + squashed = _squash(command) + if len(squashed) > best and squashed in shell: + best, owner = len(squashed), None if path == main else path.stem.removeprefix("agent-") + return owner + + def deliver(session: LiveSession, text: str) -> str: if not session.endpoint: raise RuntimeError(f"{session.address} has no messaging socket (Claude Code too old?)") diff --git a/one_conv/live/cli.py b/one_conv/live/cli.py index 4a7a30f..788103d 100644 --- a/one_conv/live/cli.py +++ b/one_conv/live/cli.py @@ -24,6 +24,16 @@ BOX_PROBE_ATTEMPTS = 4 +def refuse_subagent() -> None: + """Stop a Claude Code subagent from passing its parent's address off as its own.""" + agent = router.subagent_caller() + if agent: + raise click.ClickException( + f"This runs inside Claude Code subagent {agent}, which has no live address: its parent session " + "would get every reply. Run the agent as its own session with `one-conv live spawn claude " + "--brief-file BRIEF --yes`, or share notes through `one-conv board`.") + + def examples(*lines: str) -> str: """A help epilog click prints as written: its leading \\b keeps the line breaks.""" return "\b\nExamples:\n" + "\n".join(f" {line}" for line in lines) @@ -181,6 +191,7 @@ def send_command(target, message, from_stdin, sender, fyi, no_reply, images, tag message = sys.stdin.read() if not message: raise click.UsageError("Give MESSAGE or --stdin.") + refuse_subagent() try: me = router.whoami(sender) origin = router.origin(sys.stdin.isatty() and not from_stdin) @@ -363,6 +374,7 @@ def status_command(message_id, as_json): @live.command("whoami", context_settings=HELP, epilog=examples('one-conv live whoami')) def whoami_command(): """Show which session this process is running inside, as other sessions see it.""" + refuse_subagent() me = router.whoami() if me is None: click.echo("user (not inside an agent session)") @@ -464,6 +476,7 @@ def spawn_command(harness, harness_args, cwd, brief, brief_file, mode, tmux_sess text = brief if brief is not None else (brief_file.read() if brief_file else "") if not text.strip(): raise click.UsageError("Give the agent a brief with --brief or --brief-file: it starts working on it.") + refuse_subagent() sender = router.whoami() text = spawn.with_reply_path(text, sender) try: @@ -482,7 +495,7 @@ def spawn_command(harness, harness_args, cwd, brief, brief_file, mode, tmux_sess except (RuntimeError, OSError) as error: raise click.ClickException(str(error)) from None # Recorded before registering, so an agent stuck on a prompt can still be stopped by its tmux name. - row = spawn.Spawned(name, harness, cwd, "", sender.address if sender else "", time.time()) + row = spawn.Spawned(name, harness, cwd, "", sender.address if sender else "", time.time(), sorted(before)) spawn.record(row) session = spawn.wait_for(adapter.list_sessions, before, cwd, timeout, lambda: spawn.tmux_taken(name)) if session is None: @@ -514,6 +527,7 @@ def stop_command(targets, stop_all, as_json, yes): are refused: stop those yourself. """ registry = spawn.load_registry() + spawn.claim_addresses(registry, router.list_all) if not targets and not stop_all: rows = [{**vars(row), "running": spawn.tmux_taken(row.tmux)} for row in registry.values()] if as_json: diff --git a/one_conv/live/router.py b/one_conv/live/router.py index 70d52d8..1075ee8 100644 --- a/one_conv/live/router.py +++ b/one_conv/live/router.py @@ -154,6 +154,32 @@ def whoami(explicit: str | None = None, meta: dict | None = None, pid: int | Non return None +def _command_line(pid: int) -> str: + return subprocess.run(["ps", "-ww", "-o", "args=", "-p", str(pid)], check=False, capture_output=True, + text=True).stdout.strip() + + +def subagent_caller(pid: int | None = None) -> str | None: + """The Claude Code subagent whose Bash tool started this process, else None. + + A subagent has no live address: whoami names its parent session, which receives every + reply. The shell Claude Code started is matched against the in-flight Bash calls of its + transcripts. MCP tool calls carry no shell, so a subagent calling them is not detected. + """ + current, shell = pid or os.getpid(), None + for _ in range(32): + session = claude.session_for_pid(current) + if session: + return claude.subagent_running(session, _command_line(shell)) if shell else None + if omp.session_for_pid(current) or agy.session_for_pid(current): + return None + step = _process(current) + if step is None or step[0] <= 1 or step[1] in ("codex", "cursor-agent", "agy"): + return None + shell, current = current, step[0] + return None + + def resolve(target: str, sessions: list[LiveSession] | None = None, exclude: LiveSession | None = None) -> LiveSession: """Match an address, id prefix, then title/cwd substring; `exclude` drops the sender first.""" diff --git a/one_conv/live/spawn.py b/one_conv/live/spawn.py index 65be989..6786dd8 100644 --- a/one_conv/live/spawn.py +++ b/one_conv/live/spawn.py @@ -176,6 +176,8 @@ class Spawned: address: str = "" by: str = "" started: float = 0.0 + # Session ids of the harness running before the start; None in rows from older spawners. + before: list[str] | None = None def registry_path() -> Path: @@ -207,6 +209,28 @@ def record(row: Spawned) -> None: save_registry(registry) +def claim_addresses(registry: dict[str, Spawned], sessions: Callable[[str], list[LiveSession]]) -> None: + """Give each running agent recorded without an address the session it registered after spawn gave up. + + An agent held on a prompt past the timeout registers once someone answers it; it is the + session spawn did not see before the start, working in its folder and not yet claimed. + """ + claimed = {row.address for row in registry.values() if row.address} + changed = False + for row in sorted(registry.values(), key=lambda row: row.started): + if row.address or row.before is None or not tmux_taken(row.tmux): + continue + seen = set(row.before) + session = next((session for session in sessions(row.harness) if session.id not in seen + and session.address not in claimed and _same_dir(session.cwd, row.cwd)), None) + if session: + row.address = session.address + claimed.add(session.address) + changed = True + if changed: + save_registry(registry) + + def find(target: str, registry: dict[str, Spawned], resolved: str | None) -> list[Spawned]: """Spawned agents matching a tmux session name, an address (resolved from @name or id prefix), or an id prefix.""" if target in registry: diff --git a/tests/test_live_spawn.py b/tests/test_live_spawn.py index d67e4e8..50299ab 100644 --- a/tests/test_live_spawn.py +++ b/tests/test_live_spawn.py @@ -331,3 +331,54 @@ def test_starting_codex_leaves_claude_config_alone(monkeypatch, tmp_path): monkeypatch.setattr(spawn, "_tmux", lambda *args: subprocess.CompletedProcess(args, 0, "", "")) spawn.start("s", str(tmp_path), spawn.Launch(["codex", "brief"], {})) assert not spawn.claude_config_path().exists() + + +def test_spawn_records_the_sessions_running_before_it(started, monkeypatch, tmp_path): + _sessions(monkeypatch, "codex", lambda: [LiveSession("codex", "old", str(tmp_path))]) + monkeypatch.setattr(spawn, "screen", lambda name: "Review hooks") + CliRunner().invoke(build_live_group(["one-conv"]), + ["spawn", "codex", "--cwd", str(tmp_path), "--brief", "b", "--timeout", "0", "--yes"]) + assert spawn.load_registry()[f"codex-{tmp_path.name}"].before == ["old"] + + +@pytest.fixture +def held_on_a_prompt(monkeypatch): + """A codex spawn that timed out on a prompt; once answered, it registered next to an older session.""" + spawn.record(spawn.Spawned("lstdocs-codex", "codex", "/w/docs", "", "claude:c1", 1.0, ["old"])) + monkeypatch.setattr(spawn, "tmux_taken", lambda name: True) + monkeypatch.setattr(router, "list_all", lambda harness=None: [ + LiveSession("codex", "old", "/w/docs"), LiveSession("codex", "new", "/w/docs")]) + + +def test_stop_lists_the_address_an_agent_registered_after_spawn_gave_up(held_on_a_prompt): + result = CliRunner().invoke(build_live_group(["one-conv"]), ["stop", "--json"]) + assert json.loads(result.output)[0]["address"] == "codex:new" + + +def test_stop_finds_by_address_an_agent_registered_after_spawn_gave_up(held_on_a_prompt, killed): + CliRunner().invoke(build_live_group(["one-conv"]), ["stop", "codex:new", "--yes"]) + assert killed == ["lstdocs-codex"] + + +def _unregistered(before): + return spawn.Spawned("codex-docs", "codex", "/w/docs", "", "", 1.0, before) + + +@pytest.mark.parametrize(("registry", "sessions"), [ + ({"codex-docs": _unregistered([])}, [LiveSession("codex", "new", "/w/other")]), + ({"codex-docs": _unregistered(None)}, [LiveSession("codex", "new", "/w/docs")]), + ({"codex-docs": _unregistered(["new"])}, [LiveSession("codex", "new", "/w/docs")]), + ({"codex-docs": _unregistered([]), + "codex-other": spawn.Spawned("codex-other", "codex", "/w/docs", "codex:new", "", 0.5)}, + [LiveSession("codex", "new", "/w/docs")]), +], ids=["other-folder", "older-spawner-row", "running-before", "already-claimed"]) +def test_claim_leaves_the_address_empty(monkeypatch, registry, sessions): + monkeypatch.setattr(spawn, "tmux_taken", lambda name: True) + spawn.claim_addresses(registry, lambda harness: sessions) + assert registry["codex-docs"].address == "" + + +def test_claim_saves_the_claimed_address(monkeypatch): + monkeypatch.setattr(spawn, "tmux_taken", lambda name: True) + spawn.claim_addresses({"codex-docs": _unregistered([])}, lambda harness: [LiveSession("codex", "new", "/w/docs")]) + assert spawn.load_registry()["codex-docs"].address == "codex:new" diff --git a/tests/test_live_subagent.py b/tests/test_live_subagent.py new file mode 100644 index 0000000..d9c62c5 --- /dev/null +++ b/tests/test_live_subagent.py @@ -0,0 +1,128 @@ +"""A Claude Code subagent has no live address: one-conv finds it from its transcript and refuses to act for it.""" + +import json +import os +import time + +import pytest +from click.testing import CliRunner + +from one_conv.live import claude, router, spawn +from one_conv.live.cli import build_live_group +from one_conv.live.model import LiveSession + +SESSION = LiveSession("claude", "c1", "/work/app") +# The shell Claude Code's Bash tool starts: it evals the command, quotes escaped. +SHELL = ("/bin/zsh -c source /tmp/snapshot.sh 2>/dev/null || true && eval 'one-conv live send @lead '\"'\"'done'\"'\"'" + " --yes' < /dev/null && pwd -P >| /tmp/claude-1-cwd") +COMMAND = "one-conv live send @lead 'done' --yes" + + +def _call(tool_id, command, name="Bash"): + return {"type": "assistant", "message": {"content": [ + {"type": "tool_use", "id": tool_id, "name": name, "input": {"command": command}}]}} + + +def _result(tool_id): + return {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": tool_id, "content": ""}]}} + + +def _lines(*entries): + return [json.dumps(entry).encode() for entry in entries] + + +def _write(path, *entries): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("".join(json.dumps(entry) + "\n" for entry in entries)) + return path + + +@pytest.fixture +def main_transcript(): + return claude.transcript(SESSION.id, SESSION.cwd) + + +@pytest.fixture +def subagent_transcript(main_transcript): + return main_transcript.parent / SESSION.id / "subagents" / "agent-a5fc55.jsonl" + + +def test_a_bash_call_without_result_is_pending(): + assert claude.pending_commands(_lines(_call("t1", "ls"))) == ["ls"] + + +def test_a_bash_call_with_its_result_is_done(): + assert claude.pending_commands(_lines(_call("t1", "ls"), _result("t1"))) == [] + + +def test_other_tools_are_not_pending_commands(): + assert claude.pending_commands(_lines(_call("t1", "ls", name="Read"))) == [] + + +def test_pending_call_in_a_subagent_transcript_names_the_subagent(main_transcript, subagent_transcript): + _write(main_transcript, _call("t0", "git status"), _result("t0")) + _write(subagent_transcript, _call("t1", COMMAND)) + assert claude.subagent_running(SESSION, SHELL) == "a5fc55" + + +def test_pending_call_in_the_main_transcript_is_no_subagent(main_transcript, subagent_transcript): + _write(main_transcript, _call("t0", COMMAND)) + _write(subagent_transcript, _call("t1", "pytest")) + assert claude.subagent_running(SESSION, SHELL) is None + + +def test_the_same_pending_command_in_both_counts_as_the_main_conversation(main_transcript, subagent_transcript): + _write(main_transcript, _call("t0", COMMAND)) + _write(subagent_transcript, _call("t1", COMMAND)) + assert claude.subagent_running(SESSION, SHELL) is None + + +def test_the_longest_matching_command_wins(main_transcript, subagent_transcript): + _write(main_transcript, _call("t0", "one-conv live send")) + _write(subagent_transcript, _call("t1", COMMAND)) + assert claude.subagent_running(SESSION, SHELL) == "a5fc55" + + +def test_a_subagent_transcript_untouched_for_long_is_ignored(main_transcript, subagent_transcript): + _write(main_transcript) + stale = time.time() - claude.RECENT_SECONDS - 60 + os.utime(_write(subagent_transcript, _call("t1", COMMAND)), (stale, stale)) + assert claude.subagent_running(SESSION, SHELL) is None + + +def test_no_transcript_counts_as_the_main_conversation(): + assert claude.subagent_running(SESSION, SHELL) is None + + +def test_subagent_caller_matches_the_shell_claude_started(monkeypatch): + chain = {100: (200, "python3"), 200: (4242, "zsh")} + monkeypatch.setattr(router, "_process", lambda pid: chain.get(pid, (1, "claude"))) + monkeypatch.setattr(claude, "session_for_pid", lambda pid: SESSION if pid == 4242 else None) + monkeypatch.setattr(router, "_command_line", lambda pid: f"shell of {pid}") + monkeypatch.setattr(claude, "subagent_running", lambda session, line: line) + assert router.subagent_caller(pid=100) == "shell of 200" + + +def test_subagent_caller_stops_at_a_nearer_harness(monkeypatch): + chain = {100: (200, "python3"), 200: (4242, "codex")} + monkeypatch.setattr(router, "_process", lambda pid: chain.get(pid, (1, "claude"))) + monkeypatch.setattr(claude, "session_for_pid", lambda pid: SESSION if pid == 4242 else None) + assert router.subagent_caller(pid=100) is None + + +@pytest.mark.parametrize("args", [ + ["whoami"], + ["send", "@lead", "done", "--yes"], + ["spawn", "codex", "--brief", "review", "--yes"], +]) +def test_live_commands_refuse_a_subagent(monkeypatch, args): + monkeypatch.setattr(router, "subagent_caller", lambda: "a5fc55") + monkeypatch.setattr(spawn, "start", lambda *a: pytest.fail("a subagent must not spawn")) + result = CliRunner().invoke(build_live_group(["one-conv"]), args) + assert "Claude Code subagent a5fc55" in result.output + + +def test_the_refusal_names_the_fix(monkeypatch): + monkeypatch.setattr(router, "subagent_caller", lambda: "a5fc55") + result = CliRunner().invoke(build_live_group(["one-conv"]), ["whoami"]) + assert "one-conv live spawn claude --brief-file BRIEF --yes" in result.output