Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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 |
| --- | --- | --- |
Expand Down
6 changes: 6 additions & 0 deletions SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
62 changes: 62 additions & 0 deletions one_conv/live/claude.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import os
import re
import socket
import time
import uuid
from pathlib import Path

Expand Down Expand Up @@ -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?)")
Expand Down
16 changes: 15 additions & 1 deletion one_conv/live/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)")
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
26 changes: 26 additions & 0 deletions one_conv/live/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
24 changes: 24 additions & 0 deletions one_conv/live/spawn.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
51 changes: 51 additions & 0 deletions tests/test_live_spawn.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Loading
Loading