#!/usr/bin/env python3
r"""
ask_hermes.py — Calypso->Hermes bridge, Mac side (the "Malin-hub" first mission).

Lets Calypso dispatch a single task to the on-box Hermes agent (gpt-5.5 on the
5090) WITHOUT Jun relaying. It POSTs the task to malin.py's :1237 broker on the
5090, which shells out to `hermes chat -q "<task>"` and returns Hermes's stdout.

Direction note: this is the REVERSE of calypso_poller.py. That one is Mac->5090
because the 5090 can't reach the Mac; this is ALSO Mac->5090 (Calypso initiates),
so a plain synchronous POST works — the request just blocks until Hermes finishes.

Guardrail: single-shot dispatch only. Hermes's result comes back as a string and
does NOT auto-trigger anything — no autonomous Calypso<->Hermes loop.

Usage:
    python3 ask_hermes.py "the task text for Hermes"
    echo "task text" | python3 ask_hermes.py
"""
import sys
import requests

HARNESS = "http://100.123.118.101:1237"      # malin.py broker on the 5090 (same host as the poller)
HERMES  = HARNESS + "/bridge/hermes"
TIMEOUT = 320                                 # a hair beyond the 5090-side HERMES_TIMEOUT (300s)


def ask_hermes(task):
    """Send one task to Hermes via the Malin-hub broker; return (output, ok)."""
    try:
        r = requests.post(HERMES, json={"task": task}, timeout=TIMEOUT)
        data = r.json()
        return data.get("output", "(no output)"), bool(data.get("ok", False))
    except requests.exceptions.RequestException as e:
        return (f"(couldn't reach the Malin broker on the 5090: {type(e).__name__} "
                f"— is malin.py running?)"), False


def main():
    task = " ".join(sys.argv[1:]).strip()
    if not task and not sys.stdin.isatty():
        task = sys.stdin.read().strip()
    if not task:
        print('usage: ask_hermes.py "<task for Hermes>"', file=sys.stderr)
        sys.exit(2)
    out, ok = ask_hermes(task)
    print(out)
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()
