Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion docs/guides/agent-mode-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ These conventions extend the core principle ("the sandbox is the constraint") wi
LLM calls must never use direct `httpx.post()` or Anthropic SDK calls. Two approaches are supported:

- **In-sandbox code** (e.g., `egg-health-inspect`, `sandbox/llm/`): use `egg_agent.client.run_agent()`, which wraps `claude-agent-sdk` for in-process execution.
- **Orchestrator/gateway code spawning containers**: use `egg_agent.build_agent_command()` to build the `claude --print` command passed to `spawn_agent_container()`.
- **Orchestrator/gateway code spawning containers**: use `egg_agent.build_agent_command()` to build the `python3 -m egg_agent` command passed to `spawn_agent_container()`.

Both approaches ensure:
- Consistent tool access across all agent invocations
Expand Down
38 changes: 18 additions & 20 deletions orchestrator/consensus_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

When agents run in concurrent mode, they must stay alive after completing
their work to participate in BRC (Broadcast-Review-Converge) consensus.
This module provides a shell wrapper that detects early Claude exits and
This module provides a shell wrapper that detects early agent exits and
restarts the agent with a recovery prompt instead of blindly marking
consensus as approved.

If the agent exits without reaching CONFIRMED state in the BRC protocol,
the wrapper restarts Claude with a prompt that explains what happened and
the wrapper restarts the agent with a prompt that explains what happened and
instructs it to assess state, then continue the BRC protocol. Restarts
are capped at ``MAX_CONSENSUS_RESTARTS`` (default 2). After exhausting
restarts the wrapper exits with code 1 so the orchestrator's failure path
Expand All @@ -16,7 +16,7 @@

import shlex

# Default maximum number of times the wrapper will restart Claude after a
# Default maximum number of times the wrapper will restart the agent after a
# clean exit without consensus being reached.
MAX_CONSENSUS_RESTARTS = 2

Expand All @@ -25,7 +25,7 @@
# 10 * 30 = 300 seconds (5 minutes) for other agents to finish.
MAX_READY_POLL_CYCLES = 10

# Recovery prompt given to Claude when it is restarted by the wrapper.
# Recovery prompt given to the agent when it is restarted by the wrapper.
# Placeholders: {restart_number}, {max_restarts}, {brc_state}, {nack_feedback}
_RECOVERY_PROMPT = (
"## BRC CONSENSUS RECOVERY — You were restarted by the consensus wrapper\n\n"
Expand Down Expand Up @@ -53,10 +53,10 @@
"(up to the maximum).**\n"
)

# Shell script that wraps the Claude CLI invocation. After Claude exits:
# Shell script that wraps the agent invocation. After the agent exits:
# - Non-concurrent mode: exit normally.
# - Non-zero exit: treat as failure, no restart.
# - Clean exit (code 0): restart Claude with a recovery prompt (up to
# - Clean exit (code 0): restart the agent with a recovery prompt (up to
# MAX_RESTARTS times). After max restarts, exit 1 to trigger the
# orchestrator's agent failure path (HITL decision).
_CONSENSUS_WRAPPER_TEMPLATE = r"""
Expand All @@ -66,9 +66,9 @@
MAX_RESTARTS={max_restarts}
RESTART_COUNT=0

run_claude() {{
run_agent() {{
local prompt="$1"
{claude_command_prefix} "$prompt"
{agent_command_prefix} "$prompt"
return $?
}}

Expand Down Expand Up @@ -109,7 +109,7 @@
}}

# --- Initial run ---
run_claude {initial_prompt}
run_agent {initial_prompt}
CLAUDE_EXIT=$?

# If not in concurrent mode, exit normally
Expand Down Expand Up @@ -191,7 +191,7 @@
template = template.replace(old, os.environ[key])
sys.stdout.write(template)' <<< "$RECOVERY_PROMPT")

run_claude "$RECOVERY_PROMPT"
run_agent "$RECOVERY_PROMPT"
CLAUDE_EXIT=$?

if [ "$CLAUDE_EXIT" -ne 0 ]; then
Expand Down Expand Up @@ -242,24 +242,22 @@ def build_consensus_wrapped_command(
Returns:
Command list suitable for container spawning (bash -c "...").
"""
# Build the claude command prefix (everything except the prompt argument)
claude_prefix_parts = [
"claude",
"--dangerously-skip-permissions",
"--print",
"--verbose",
"--output-format",
"stream-json",
# Build the agent command prefix (everything except the prompt argument).
# Uses the Agent SDK entry point instead of the claude CLI.
agent_prefix_parts = [
"python3",
"-m",
"egg_agent",
"--model",
model,
"--max-turns",
str(max_turns),
]
claude_command_prefix = " ".join(shlex.quote(p) for p in claude_prefix_parts)
agent_command_prefix = " ".join(shlex.quote(p) for p in agent_prefix_parts)
initial_prompt = shlex.quote(prompt_text)

script = _CONSENSUS_WRAPPER_TEMPLATE.format(
claude_command_prefix=claude_command_prefix,
agent_command_prefix=agent_command_prefix,
initial_prompt=initial_prompt,
max_restarts=max_restarts,
max_ready_polls=max_ready_polls,
Expand Down
72 changes: 43 additions & 29 deletions orchestrator/tests/test_consensus_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os
import shlex
import subprocess
import sys
import tempfile

from consensus_wrapper import (
Expand All @@ -23,13 +24,12 @@ def test_returns_bash_command(self):
assert cmd[1] == "-c"
assert len(cmd) == 3

def test_contains_claude_invocation(self):
"""The wrapper script should contain the full claude command."""
def test_contains_agent_invocation(self):
"""The wrapper script should contain the Agent SDK command."""
cmd = build_consensus_wrapped_command("Test prompt")
script = cmd[2]
assert "claude" in script
assert "--dangerously-skip-permissions" in script
assert "--print" in script
assert "python3" in script
assert "egg_agent" in script
assert "--max-turns" in script
assert "200" in script

Expand Down Expand Up @@ -151,26 +151,35 @@ def test_default_max_ready_polls(self):
assert f"MAX_READY_POLLS={MAX_READY_POLL_CYCLES}" in script


def _make_mock_claude(tmpdir: str, claude_log_file: str | None = None, exit_code: int = 0) -> None:
"""Create a mock claude script.
def _make_mock_agent(tmpdir: str, agent_log_file: str | None = None, exit_code: int = 0) -> None:
"""Create a mock python3 script that intercepts ``-m egg_agent`` calls.

Non-egg_agent ``python3`` invocations (used by the wrapper for JSON
parsing) fall through to the real ``python3``.

Args:
tmpdir: Directory to create the mock in (must be on PATH).
claude_log_file: File to log calls to. If None, logs to tmpdir/claude.log.
agent_log_file: File to log calls to. If None, logs to tmpdir/claude.log.
exit_code: Exit code for the mock. When 0, logs call details;
when non-zero, exits immediately with that code.
"""
mock_claude = os.path.join(tmpdir, "claude")
claude_log = claude_log_file or os.path.join(tmpdir, "claude.log")
with open(mock_claude, "w") as f:
mock_python = os.path.join(tmpdir, "python3")
agent_log = agent_log_file or os.path.join(tmpdir, "claude.log")
real_python = sys.executable
with open(mock_python, "w") as f:
f.write("#!/bin/bash\n")
# Intercept only -m egg_agent calls; pass everything else to real python3
f.write('if [ "$1" = "-m" ] && [ "$2" = "egg_agent" ]; then\n')
if exit_code != 0:
f.write(f"exit {exit_code}\n")
f.write(f" exit {exit_code}\n")
else:
f.write(f'echo "---CLAUDE_CALL_START---" >> {shlex.quote(claude_log)}\n')
f.write(f'echo "${{@: -1}}" >> {shlex.quote(claude_log)}\n')
f.write(f'echo "---CLAUDE_CALL_END---" >> {shlex.quote(claude_log)}\n')
os.chmod(mock_claude, 0o755) # nosec B103
f.write(f' echo "---CLAUDE_CALL_START---" >> {shlex.quote(agent_log)}\n')
f.write(f' echo "${{@: -1}}" >> {shlex.quote(agent_log)}\n')
f.write(f' echo "---CLAUDE_CALL_END---" >> {shlex.quote(agent_log)}\n')
f.write("else\n")
f.write(f' exec {shlex.quote(real_python)} "$@"\n')
f.write("fi\n")
os.chmod(mock_python, 0o755) # nosec B103


class TestConsensusWrapperBehavior:
Expand All @@ -196,12 +205,12 @@ def _make_mock_tools(tmpdir: str, log_file: str, claude_log_file: str | None = N
f.write('echo \'{"data": {"concurrent": {"consensus": {"is_complete": true}}}}\'\n')
os.chmod(mock_orch, 0o755) # nosec B103

_make_mock_claude(tmpdir, claude_log_file)
_make_mock_agent(tmpdir, claude_log_file)

@staticmethod
def _make_failing_claude(tmpdir: str, exit_code: int = 1) -> None:
"""Create a mock claude that exits with a non-zero code."""
_make_mock_claude(tmpdir, exit_code=exit_code)
def _make_failing_agent(tmpdir: str, exit_code: int = 1) -> None:
"""Create a mock agent that exits with a non-zero code."""
_make_mock_agent(tmpdir, exit_code=exit_code)

@staticmethod
def _run_wrapper_command(
Expand Down Expand Up @@ -237,7 +246,7 @@ def test_nonzero_exit_does_not_restart(self):
with tempfile.TemporaryDirectory() as tmpdir:
log_file = os.path.join(tmpdir, "egg-orch.log")
self._make_mock_tools(tmpdir, log_file)
self._make_failing_claude(tmpdir, exit_code=1)
self._make_failing_agent(tmpdir, exit_code=1)

cmd = build_consensus_wrapped_command("Do the work", max_restarts=2)
result = self._run_wrapper_command(cmd, tmpdir)
Expand Down Expand Up @@ -283,7 +292,7 @@ def _make_mock_tools_with_delayed_consensus(
f.write("fi\n")
os.chmod(mock_orch, 0o755) # nosec B103

_make_mock_claude(tmpdir, claude_log_file)
_make_mock_agent(tmpdir, claude_log_file)

def test_clean_exit_triggers_restart(self):
"""A zero Claude exit should trigger a restart, not auto-signal READY."""
Expand Down Expand Up @@ -316,7 +325,7 @@ def test_nonzero_exit_propagates_exit_code(self):
with tempfile.TemporaryDirectory() as tmpdir:
log_file = os.path.join(tmpdir, "egg-orch.log")
self._make_mock_tools(tmpdir, log_file)
self._make_failing_claude(tmpdir, exit_code=42)
self._make_failing_agent(tmpdir, exit_code=42)

cmd = build_consensus_wrapped_command("Prompt", max_restarts=2)
result = self._run_wrapper_command(cmd, tmpdir)
Expand Down Expand Up @@ -357,12 +366,17 @@ def test_max_restarts_respected(self):
)
os.chmod(mock_orch, 0o755) # nosec B103

# Mock claude that always exits cleanly — uses a delimiter to count calls
mock_claude = os.path.join(tmpdir, "claude")
with open(mock_claude, "w") as f:
# Mock python3 that intercepts egg_agent calls and exits cleanly
real_python = sys.executable
mock_python = os.path.join(tmpdir, "python3")
with open(mock_python, "w") as f:
f.write("#!/bin/bash\n")
f.write(f'echo "---CLAUDE_CALL---" >> {shlex.quote(claude_log)}\n')
os.chmod(mock_claude, 0o755) # nosec B103
f.write('if [ "$1" = "-m" ] && [ "$2" = "egg_agent" ]; then\n')
f.write(f' echo "---CLAUDE_CALL---" >> {shlex.quote(claude_log)}\n')
f.write("else\n")
f.write(f' exec {shlex.quote(real_python)} "$@"\n')
f.write("fi\n")
os.chmod(mock_python, 0o755) # nosec B103

cmd = build_consensus_wrapped_command("Do the work", max_restarts=2)
result = self._run_wrapper_command(cmd, tmpdir, timeout=30)
Expand Down Expand Up @@ -423,7 +437,7 @@ def _make_mock_tools_with_agent_confirmed_state(
f.write("fi\n")
os.chmod(mock_orch, 0o755) # nosec B103

_make_mock_claude(tmpdir, claude_log_file)
_make_mock_agent(tmpdir, claude_log_file)

def test_confirmed_agent_skips_restart_and_polls(self):
"""Agent already CONFIRMED should skip restart and poll for consensus."""
Expand Down
2 changes: 1 addition & 1 deletion shared/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Reusable Python libraries shared between the gateway sidecar and sandbox contain
Claude Agent SDK wrapper for in-sandbox agent execution and orchestrator command building.

- `run_agent()` / `run_agent_async()` — run a Claude agent in-process via `claude-agent-sdk`
- `build_agent_command()` — build the `claude --print` command list for orchestrator-spawned containers
- `build_agent_command()` — build the `python3 -m egg_agent` command list for orchestrator-spawned containers
- `AgentResult` — dataclass with response text, success flag, and SDK metadata (cost, turns, duration)

```python
Expand Down
21 changes: 10 additions & 11 deletions shared/egg_agent/command.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Build agent commands for container execution.

The orchestrator spawns containers that run the ``claude`` CLI. This module
provides :func:`build_agent_command` which returns the command list passed to
:func:`spawn_agent_container`.
The orchestrator spawns containers that run the Agent SDK via
``python3 -m egg_agent``. This module provides :func:`build_agent_command`
which returns the command list passed to :func:`spawn_agent_container`.
"""

from __future__ import annotations
Expand All @@ -17,8 +17,10 @@ def build_agent_command(
) -> list[str]:
"""Build a container command list for running a Claude agent.

Returns the ``claude`` CLI command that the orchestrator passes to
``spawn_agent_container()``.
Returns the ``python3 -m egg_agent`` command that the orchestrator
passes to ``spawn_agent_container()``. The entry point wraps the
Agent SDK (``claude_agent_sdk.query()``), so CLI-specific flags like
``--print`` and ``--dangerously-skip-permissions`` are not needed.

Args:
prompt: The prompt text (passed as the last positional argument).
Expand All @@ -30,12 +32,9 @@ def build_agent_command(
Command list suitable for container execution.
"""
cmd: list[str] = [
"claude",
"--dangerously-skip-permissions",
"--print",
"--verbose",
"--output-format",
"stream-json",
"python3",
"-m",
"egg_agent",
"--model",
model,
"--max-turns",
Expand Down
9 changes: 3 additions & 6 deletions tests/shared/egg_agent/test_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,9 @@ def test_default_args(self):
"""Test command with default arguments."""
cmd = build_agent_command("Hello world")
assert cmd == [
"claude",
"--dangerously-skip-permissions",
"--print",
"--verbose",
"--output-format",
"stream-json",
"python3",
"-m",
"egg_agent",
"--model",
"opus",
"--max-turns",
Expand Down
Loading