Files
orch/tests/fake_claude.py
T

69 lines
3.3 KiB
Python

#!/usr/bin/env python3
"""Fake `claude -p` for the claude_cli provider (orch tests). It is the process that "executes tools": it reads the
file named in $FAKE_CLAUDE_READ the way the real claude would (directly, no hx involved) and writes what it saw to
./claude-read.txt, then answers. Logs argv to $FAKE_CLAUDE_LOG."""
import json, os, sys
if "--version" in sys.argv:
print("fake")
sys.exit(0)
open(os.environ.get("FAKE_CLAUDE_LOG", "/dev/null"), "a").write(json.dumps(sys.argv[1:]) + "\n")
out = lambda o: print(json.dumps(o), flush=True)
out({"type": "system", "subtype": "init", "session_id": "S1"})
import subprocess
_bridge = {}
def ask(tool, inp, tid):
"""Ask hx whether `tool` may run (like claude with --permission-prompt-tool); returns the answer dict."""
if "--permission-prompt-tool" not in sys.argv or os.environ.get("FAKE_CLAUDE_NOASK"):
return {"behavior": "allow"}
if not _bridge:
cfg = json.loads(sys.argv[sys.argv.index("--mcp-config") + 1])["mcpServers"]["hx"]
_bridge["p"] = subprocess.Popen([cfg["command"], *cfg["args"]], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
text=True, env={**os.environ, **cfg["env"]})
_bridge["n"] = 0
send("initialize", {})
_bridge["p"].stdout.readline()
send("tools/call", {"name": "approve", "arguments": {"tool_name": tool, "input": inp, "tool_use_id": tid}})
return json.loads(json.loads(_bridge["p"].stdout.readline())["result"]["content"][0]["text"])
def send(method, params):
_bridge["n"] = _bridge.get("n", 0) + 1
_bridge["p"].stdin.write(json.dumps({"jsonrpc": "2.0", "id": _bridge["n"], "method": method, "params": params}) + "\n")
_bridge["p"].stdin.flush() # (a lambda `write(..) or flush()` never reaches flush: write returns a truthy count)
def tool(tid, name, inp, run):
"""One tool use: ask, announce, run only when allowed, report the result."""
answer = ask(name, inp, tid)
out({"type": "assistant", "session_id": "S1", "message": {"content": [{"type": "tool_use", "id": tid, "name": name, "input": inp}]}})
if answer["behavior"] == "allow":
res, err = run(), False
else:
res, err = "deny: " + answer.get("message", ""), True
out({"type": "user", "session_id": "S1", "message": {"content": [
{"type": "tool_result", "tool_use_id": tid, "content": res, "is_error": err}]}})
return not err
if os.environ.get("FAKE_CLAUDE_BASH"): # first a Bash call (may be denied softly), then a Read of $FAKE_CLAUDE_READ
cmd = os.environ["FAKE_CLAUDE_BASH"]
tool("b1", "Bash", {"command": cmd}, lambda: subprocess.run(cmd, shell=True, capture_output=True, text=True).stdout)
elif os.environ.get("FAKE_CLAUDE_READ"):
target = os.environ["FAKE_CLAUDE_READ"]
def read():
try:
seen = open(target).read()
except OSError as e:
seen = "ERR " + str(e)
open("claude-read.txt", "w").write(seen)
return seen
tool("t1", "Read", {"file_path": target}, read)
out({"type": "stream_event", "session_id": "S1", "event": {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "done"}}})
out({"type": "result", "session_id": "S1", "is_error": False, "result": "done", "usage": {"input_tokens": 3, "output_tokens": 4}})