|
| 1 | +"""ACP handler for the sync Claude Code tutorial. |
| 2 | +
|
| 3 | +Spawns ``claude -p --output-format stream-json --verbose`` as a LOCAL |
| 4 | +asyncio subprocess (no Scale sandbox -- that is the golden agent's |
| 5 | +production concern). Stdout lines are fed into ``ClaudeCodeTurn``, which |
| 6 | +wraps ``convert_claude_code_to_agentex_events``. Events are delivered via |
| 7 | +``UnifiedEmitter.yield_turn``, the sync HTTP yield path. |
| 8 | +
|
| 9 | +Live runs require the ``claude`` CLI to be installed and an |
| 10 | +ANTHROPIC_API_KEY (or equivalent credential) to be in the environment. |
| 11 | +For offline testing, see ``tests/test_agent_offline.py``, which injects a |
| 12 | +fake subprocess. |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import os |
| 18 | +import asyncio |
| 19 | +from typing import AsyncIterator, AsyncGenerator |
| 20 | + |
| 21 | +from dotenv import load_dotenv |
| 22 | + |
| 23 | +load_dotenv() |
| 24 | + |
| 25 | +import agentex.lib.adk as adk |
| 26 | +from agentex.lib.adk import ClaudeCodeTurn |
| 27 | +from agentex.lib.types.acp import SendMessageParams |
| 28 | +from agentex.lib.core.harness import UnifiedEmitter |
| 29 | +from agentex.lib.types.tracing import SGPTracingProcessorConfig |
| 30 | +from agentex.lib.utils.logging import make_logger |
| 31 | +from agentex.lib.sdk.fastacp.fastacp import FastACP |
| 32 | +from agentex.types.task_message_update import TaskMessageUpdate |
| 33 | +from agentex.types.task_message_content import TaskMessageContent |
| 34 | +from agentex.lib.core.tracing.tracing_processor_manager import add_tracing_processor_config |
| 35 | + |
| 36 | +logger = make_logger(__name__) |
| 37 | + |
| 38 | +add_tracing_processor_config( |
| 39 | + SGPTracingProcessorConfig( |
| 40 | + sgp_api_key=os.environ.get("SGP_API_KEY", ""), |
| 41 | + sgp_account_id=os.environ.get("SGP_ACCOUNT_ID", ""), |
| 42 | + sgp_base_url=os.environ.get("SGP_CLIENT_BASE_URL", ""), |
| 43 | + ) |
| 44 | +) |
| 45 | + |
| 46 | +acp = FastACP.create(acp_type="sync") |
| 47 | + |
| 48 | + |
| 49 | +async def _spawn_claude(prompt: str) -> AsyncIterator[str]: |
| 50 | + """Spawn ``claude -p --output-format stream-json`` locally and yield stdout lines. |
| 51 | +
|
| 52 | + This is a seam: tests replace it with a fake async iterator of |
| 53 | + pre-recorded lines so no real CLI invocation is needed offline. |
| 54 | + """ |
| 55 | + proc = await asyncio.create_subprocess_exec( |
| 56 | + "claude", |
| 57 | + "-p", |
| 58 | + "--output-format", |
| 59 | + "stream-json", |
| 60 | + "--verbose", |
| 61 | + stdin=asyncio.subprocess.PIPE, |
| 62 | + stdout=asyncio.subprocess.PIPE, |
| 63 | + stderr=asyncio.subprocess.PIPE, |
| 64 | + ) |
| 65 | + assert proc.stdout is not None |
| 66 | + assert proc.stdin is not None |
| 67 | + |
| 68 | + proc.stdin.write(prompt.encode()) |
| 69 | + proc.stdin.close() |
| 70 | + |
| 71 | + # Drain stderr concurrently. With --verbose, Claude Code can write enough to |
| 72 | + # stderr to fill the OS pipe buffer; if we only read stdout, the CLI blocks |
| 73 | + # on its stderr write while we block reading stdout — a deadlock. A |
| 74 | + # background task keeps stderr flowing so stdout never stalls. |
| 75 | + async def _drain_stderr() -> None: |
| 76 | + assert proc.stderr is not None |
| 77 | + async for _ in proc.stderr: |
| 78 | + pass |
| 79 | + |
| 80 | + stderr_task = asyncio.create_task(_drain_stderr()) |
| 81 | + |
| 82 | + try: |
| 83 | + buffer = "" |
| 84 | + async for chunk in proc.stdout: |
| 85 | + buffer += chunk.decode("utf-8", errors="replace") |
| 86 | + while "\n" in buffer: |
| 87 | + line, buffer = buffer.split("\n", 1) |
| 88 | + line = line.strip() |
| 89 | + if line: |
| 90 | + yield line |
| 91 | + |
| 92 | + if buffer.strip(): |
| 93 | + yield buffer.strip() |
| 94 | + |
| 95 | + await proc.wait() |
| 96 | + finally: |
| 97 | + # Release the subprocess and stderr drain task even if the consumer |
| 98 | + # abandons the generator early (task cancellation / client disconnect): |
| 99 | + # cancel the drain task and terminate+reap the process if it is still |
| 100 | + # running, so neither is leaked. |
| 101 | + stderr_task.cancel() |
| 102 | + try: |
| 103 | + await stderr_task |
| 104 | + except asyncio.CancelledError: |
| 105 | + pass |
| 106 | + if proc.returncode is None: |
| 107 | + try: |
| 108 | + proc.terminate() |
| 109 | + except ProcessLookupError: |
| 110 | + pass |
| 111 | + await proc.wait() |
| 112 | + |
| 113 | + |
| 114 | +@acp.on_message_send |
| 115 | +async def handle_message_send( |
| 116 | + params: SendMessageParams, |
| 117 | +) -> TaskMessageContent | list[TaskMessageContent] | AsyncGenerator[TaskMessageUpdate, None]: |
| 118 | + """Handle an incoming message: run Claude Code locally and stream events.""" |
| 119 | + task_id = params.task.id |
| 120 | + prompt = params.content.content |
| 121 | + logger.info("Processing message for task %s", task_id) |
| 122 | + |
| 123 | + async with adk.tracing.span( |
| 124 | + trace_id=task_id, |
| 125 | + task_id=task_id, |
| 126 | + name="message", |
| 127 | + input={"message": prompt}, |
| 128 | + data={"__span_type__": "AGENT_WORKFLOW"}, |
| 129 | + ) as turn_span: |
| 130 | + emitter = UnifiedEmitter( |
| 131 | + task_id=task_id, |
| 132 | + trace_id=task_id, |
| 133 | + parent_span_id=turn_span.id if turn_span else None, |
| 134 | + ) |
| 135 | + turn = ClaudeCodeTurn(_spawn_claude(prompt)) |
| 136 | + async for event in emitter.yield_turn(turn): |
| 137 | + yield event |
0 commit comments