39 lines
1.4 KiB
Python
39 lines
1.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Minimal client for `hx --mode rpc`: sends a prompt, prints streamed text, then session state.
|
|
Usage: python3 examples/rpc_client.py [hx-binary] "prompt"
|
|
"""
|
|
import json, subprocess, sys
|
|
|
|
hx = sys.argv[1] if len(sys.argv) > 2 else "hx"
|
|
p = subprocess.Popen([hx, "--mode", "rpc"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
|
|
nid = 0
|
|
|
|
|
|
def call(method, params=None):
|
|
global nid
|
|
nid += 1
|
|
p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": nid, "method": method, "params": params or {}}) + "\n")
|
|
p.stdin.flush()
|
|
while True:
|
|
m = json.loads(p.stdout.readline())
|
|
if m.get("method") == "event":
|
|
e = m["params"]
|
|
if e["type"] == "stream" and e["event"]["type"] == "text_delta":
|
|
print(e["event"]["text"], end="", flush=True)
|
|
elif e["type"] == "tool_call":
|
|
print(f"\n> {e['name']} {json.dumps(e['args'])[:80]}", flush=True)
|
|
continue
|
|
if m.get("id") == nid:
|
|
if "error" in m:
|
|
raise SystemExit(f"{method}: {m['error']['message']}")
|
|
return m["result"]
|
|
|
|
|
|
r = call("prompt", {"text": sys.argv[-1]})
|
|
print()
|
|
s = call("state")
|
|
print(f"STATE messages={s['messages']} model={s['model']} tools={len(s['tools'])}")
|
|
print(f"BUSY_CHECK {call('set_model', {'model': 'claude-x'})['model']}")
|
|
p.stdin.close()
|
|
p.wait(timeout=30)
|