|
| 1 | +import asyncio |
| 2 | +import contextlib |
| 3 | +import json |
| 4 | +import os |
| 5 | +import signal |
| 6 | +import sys |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | + |
| 10 | +async def _relay(reader: asyncio.StreamReader, writer: asyncio.StreamWriter, tag: str): |
| 11 | + try: |
| 12 | + while True: |
| 13 | + line = await reader.readline() |
| 14 | + if not line: |
| 15 | + break |
| 16 | + # Mirror to the other end unchanged |
| 17 | + writer.write(line) |
| 18 | + try: |
| 19 | + await writer.drain() |
| 20 | + except ConnectionError: |
| 21 | + break |
| 22 | + # Try to pretty-print the JSON-RPC message for visibility |
| 23 | + try: |
| 24 | + obj = json.loads(line.decode("utf-8", errors="replace")) |
| 25 | + pretty = json.dumps(obj, ensure_ascii=False, indent=2) |
| 26 | + print(f"[{tag}] {pretty}", file=sys.stderr) |
| 27 | + except Exception: |
| 28 | + # Non-JSON (shouldn't happen on the protocol stream) |
| 29 | + print(f"[{tag}] {line!r}", file=sys.stderr) |
| 30 | + finally: |
| 31 | + try: |
| 32 | + writer.close() |
| 33 | + await writer.wait_closed() |
| 34 | + except Exception: |
| 35 | + pass |
| 36 | + |
| 37 | + |
| 38 | +async def main() -> None: |
| 39 | + root = Path(__file__).resolve().parent |
| 40 | + agent_path = str(root / "agent.py") |
| 41 | + client_path = str(root / "client.py") |
| 42 | + |
| 43 | + # Ensure PYTHONPATH includes project src for `from acp import ...` |
| 44 | + env = os.environ.copy() |
| 45 | + src_dir = str((root.parent / "src").resolve()) |
| 46 | + env["PYTHONPATH"] = src_dir + os.pathsep + env.get("PYTHONPATH", "") |
| 47 | + |
| 48 | + agent = await asyncio.create_subprocess_exec( |
| 49 | + sys.executable, |
| 50 | + agent_path, |
| 51 | + stdin=asyncio.subprocess.PIPE, |
| 52 | + stdout=asyncio.subprocess.PIPE, |
| 53 | + stderr=sys.stderr, |
| 54 | + env=env, |
| 55 | + ) |
| 56 | + client = await asyncio.create_subprocess_exec( |
| 57 | + sys.executable, |
| 58 | + client_path, |
| 59 | + stdin=asyncio.subprocess.PIPE, |
| 60 | + stdout=asyncio.subprocess.PIPE, |
| 61 | + stderr=sys.stderr, |
| 62 | + env=env, |
| 63 | + ) |
| 64 | + |
| 65 | + assert agent.stdout and agent.stdin and client.stdout and client.stdin |
| 66 | + |
| 67 | + # Wire: agent.stdout -> client.stdin, client.stdout -> agent.stdin |
| 68 | + t1 = asyncio.create_task(_relay(agent.stdout, client.stdin, "agent→client")) |
| 69 | + t2 = asyncio.create_task(_relay(client.stdout, agent.stdin, "client→agent")) |
| 70 | + |
| 71 | + # Handle shutdown |
| 72 | + stop = asyncio.Event() |
| 73 | + |
| 74 | + def _on_sigint(*_): |
| 75 | + stop.set() |
| 76 | + |
| 77 | + loop = asyncio.get_running_loop() |
| 78 | + try: |
| 79 | + loop.add_signal_handler(signal.SIGINT, _on_sigint) |
| 80 | + loop.add_signal_handler(signal.SIGTERM, _on_sigint) |
| 81 | + except NotImplementedError: |
| 82 | + pass |
| 83 | + |
| 84 | + done, _ = await asyncio.wait( |
| 85 | + { |
| 86 | + t1, |
| 87 | + t2, |
| 88 | + asyncio.create_task(agent.wait()), |
| 89 | + asyncio.create_task(client.wait()), |
| 90 | + asyncio.create_task(stop.wait()), |
| 91 | + }, |
| 92 | + return_when=asyncio.FIRST_COMPLETED, |
| 93 | + ) |
| 94 | + |
| 95 | + # Teardown |
| 96 | + for proc in (agent, client): |
| 97 | + if proc.returncode is None: |
| 98 | + with contextlib.suppress(ProcessLookupError): |
| 99 | + proc.terminate() |
| 100 | + try: |
| 101 | + await asyncio.wait_for(proc.wait(), 2) |
| 102 | + except asyncio.TimeoutError: |
| 103 | + with contextlib.suppress(ProcessLookupError): |
| 104 | + proc.kill() |
| 105 | + for task in (t1, t2): |
| 106 | + task.cancel() |
| 107 | + with contextlib.suppress(asyncio.CancelledError): |
| 108 | + await task |
| 109 | + |
| 110 | + |
| 111 | +if __name__ == "__main__": |
| 112 | + asyncio.run(main()) |
0 commit comments