|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +gstack-codex-jsonl-parser: parse Codex CLI --json streaming output to human-readable form. |
| 4 | +
|
| 5 | +Usage: gstack-codex-jsonl-parser [--mode challenge|consult] |
| 6 | + Reads JSONL from stdin (codex exec --json output), prints formatted lines to stdout. |
| 7 | +
|
| 8 | +Modes: |
| 9 | + challenge Track turn.completed count; warn on disconnect (no events received). |
| 10 | + consult Extract SESSION_ID from thread.started for follow-up sessions. |
| 11 | +""" |
| 12 | +import sys |
| 13 | +import json |
| 14 | + |
| 15 | +mode = "consult" |
| 16 | +args = sys.argv[1:] |
| 17 | +i = 0 |
| 18 | +while i < len(args): |
| 19 | + if args[i] == "--mode" and i + 1 < len(args): |
| 20 | + mode = args[i + 1] |
| 21 | + i += 2 |
| 22 | + else: |
| 23 | + i += 1 |
| 24 | + |
| 25 | +turn_completed_count = 0 |
| 26 | +for line in sys.stdin: |
| 27 | + line = line.strip() |
| 28 | + if not line: |
| 29 | + continue |
| 30 | + try: |
| 31 | + obj = json.loads(line) |
| 32 | + t = obj.get("type", "") |
| 33 | + if t == "thread.started" and mode == "consult": |
| 34 | + tid = obj.get("thread_id", "") |
| 35 | + if tid: |
| 36 | + print(f"SESSION_ID:{tid}", flush=True) |
| 37 | + elif t == "item.completed" and "item" in obj: |
| 38 | + item = obj["item"] |
| 39 | + itype = item.get("type", "") |
| 40 | + text = item.get("text", "") |
| 41 | + if itype == "reasoning" and text: |
| 42 | + print(f"[codex thinking] {text}", flush=True) |
| 43 | + print(flush=True) |
| 44 | + elif itype == "agent_message" and text: |
| 45 | + print(text, flush=True) |
| 46 | + elif itype == "command_execution": |
| 47 | + cmd = item.get("command", "") |
| 48 | + if cmd: |
| 49 | + print(f"[codex ran] {cmd}", flush=True) |
| 50 | + elif t == "turn.completed": |
| 51 | + turn_completed_count += 1 |
| 52 | + usage = obj.get("usage", {}) |
| 53 | + tokens = usage.get("input_tokens", 0) + usage.get("output_tokens", 0) |
| 54 | + if tokens: |
| 55 | + print(f"\ntokens used: {tokens}", flush=True) |
| 56 | + except Exception: |
| 57 | + pass |
| 58 | + |
| 59 | +if mode == "challenge" and turn_completed_count == 0: |
| 60 | + print( |
| 61 | + "[codex warning] No turn.completed event received — possible mid-stream disconnect.", |
| 62 | + flush=True, |
| 63 | + file=sys.stderr, |
| 64 | + ) |
0 commit comments