Files
hx/tests/fake_claude.py
T

35 lines
2.2 KiB
Python
Executable File

#!/usr/bin/env python3
"""Fake `claude -p --output-format stream-json`: logs argv to $FAKE_CLAUDE_LOG, streams one reply."""
import json, os, sys
open(os.environ["FAKE_CLAUDE_LOG"], "a").write(json.dumps(sys.argv[1:]) + "\n")
if "--version" in sys.argv:
print("fake"); sys.exit(0)
def out(o): print(json.dumps(o), flush=True)
reply = "hello from claude"
if "--permission-prompt-tool" in sys.argv: # act like claude: ask hx whether `rm -rf x` may run
import subprocess
cfg = json.loads(sys.argv[sys.argv.index("--mcp-config") + 1])["mcpServers"]["hx"]
p = subprocess.Popen([cfg["command"], *cfg["args"]], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
text=True, env={**os.environ, **cfg["env"]})
call = {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "approve", "arguments":
{"tool_name": "Bash", "input": {"command": "rm -rf x"}}}}
p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}) + "\n" + json.dumps(call) + "\n")
p.stdin.flush()
cm = {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "codemode", "arguments":
{"script": "return await tools.bash({command: 'echo cm-' + 'ok > cm.txt; cat cm.txt'})"}}}
if "HX_CODEMODE" in cfg["env"]:
p.stdin.write(json.dumps(cm) + "\n"); p.stdin.flush()
lines = [json.loads(p.stdout.readline()) for _ in range(2 + ("HX_CODEMODE" in cfg["env"]))]
p.stdin.close()
reply = "approve: " + json.loads(lines[1]["result"]["content"][0]["text"])["behavior"]
if len(lines) == 3:
reply += " " + lines[2]["result"]["content"][0]["text"]
out({"type": "system", "subtype": "init", "session_id": "S1"})
ev = lambda e: out({"type": "stream_event", "session_id": "S1", "event": e})
out({"type": "assistant", "session_id": "S1", "message": {"content": [
{"type": "tool_use", "name": "Bash", "input": {"command": "echo hi-from-tool"}}]}})
ev({"type": "content_block_delta", "delta": {"type": "text_delta", "text": reply + " "}})
ev({"type": "content_block_delta", "delta": {"type": "text_delta", "text": "from claude"}})
out({"type": "result", "session_id": "S1", "is_error": False, "result": "hello from claude",
"usage": {"input_tokens": 3, "output_tokens": 4}})