#!/usr/bin/env python3 """Render one bridge exchange: answer to stdout, receipt to stderr, log to disk. Kept as a file rather than inlined in the shell script - an f-string full of escaped quotes inside a heredoc inside a shell script is how the first version broke.""" import json, os, sys, pathlib here = pathlib.Path(os.environ["HERE"]) stamp = os.environ["STAMP"] cwd = os.environ["CWD"] prompt = os.environ["PROMPT"] who = os.environ.get("WHO", "grok") errlog = os.environ.get("ERRLOG", "") raw = sys.stdin.read() # !! The agent can exit 0 and still hand back something that is not JSON - it # got killed mid-stream, it rate-limited, it printed a banner. Before this # was caught, that surfaced as a 20-line Python traceback, which tells the # caller nothing about what actually went wrong. try: d = json.loads(raw) except (json.JSONDecodeError, ValueError): print("{}: did not return JSON. Raw output was:".format(who), file=sys.stderr) print((raw[:800] or "(nothing at all - killed, or timed out)"), file=sys.stderr) if errlog and os.path.exists(errlog) and os.path.getsize(errlog): print("--- its stderr ---", file=sys.stderr) with open(errlog) as f: print(f.read()[:800], file=sys.stderr) sys.exit(4) text = d.get("text") or d.get("result") or "" cost = d.get("total_cost_usd", 0.0) or 0.0 sid = d.get("sessionId") or d.get("session_id") or "?" model = ", ".join(d.get("modelUsage", {})) or d.get("model", "?") print(text) print("\n--- {} {} | ${:.4f} | session {}".format(who, model, cost, sid), file=sys.stderr) if who == "grok": print(" resume with: --resume {}".format(sid), file=sys.stderr) out = here / "exchanges" / "{}-{}.md".format(stamp, who) out.write_text( "# {} consult {}\n\n".format(who, stamp) + "- **cwd:** `{}`\n".format(cwd) + "- **session:** `{}`\n".format(sid) + "- **model:** {}\n".format(model) + "- **cost:** ${:.4f}\n\n".format(cost) + "## Asked\n\n{}\n\n## Answered\n\n{}\n".format(prompt, text))