Skip to content

Commit a974463

Browse files
oleg-kovalclaude
andcommitted
Codex CLI support: session-log adapter and tmux output
No agent CLI other than Claude Code lets you supply the status line as a command. Verified rather than assumed: Codex 0.146's tui.status_line takes a fixed list of built-in item ids (openai/codex#20244, #17827), opencode 1.17 has no statusLine anywhere in its shipped config schema or its 130MB bundle (the proposal is anomalyco/opencode#30295, and a search summary claiming it shipped is wrong), Hermes documents its bar as fixed, and the installed Cursor CLI binary contains no statusline strings at all. Codex does not need a hook. It already writes what matters to ~/.codex/sessions/<date>/rollout-*.jsonl: token_count records carrying last_token_usage, cached_input_tokens and model_context_window, plus rate_limits with used_percent, window_minutes and resets_at. codex_payload() translates those into the same shape Claude Code pipes in, so nothing downstream changes, and --tmux renders it into the tmux status bar instead of Codex's own. main() split into argument handling plus build_line(payload), which is what makes a second harness possible at all. The cache segment now prefers numbers an adapter supplies, since only Claude Code has a transcript to derive them from. to_tmux() rewrites SGR colours as tmux formats, doubles literal '#' (tmux reads it as the start of a format) and strips hyperlinks. Cost and lines changed are omitted for Codex because Codex does not record them; better a missing segment than an invented number. Two bugs the installer only revealed when run: --print fetched and overwrote glint.py before previewing (it clobbered a working copy once), and the tmux value nested double quotes inside a double-quoted string, which ended it mid-path. --print is now a true dry run and the inner path is single-quoted. 88 tests. Co-Authored-By: Claude Code <[email protected]>
1 parent a79a0cd commit a974463

5 files changed

Lines changed: 498 additions & 13 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,19 @@ curl -fsSL https://raw.githubusercontent.com/oleg-koval/glint/main/install.sh |
2424
drink at your desk. Interval is `GLINT_WATER_EVERY`, off with `GLINT_WATER=0`.
2525
- `--rest-status` now reports both clocks, and `--rested` resets both.
2626

27+
- **Codex CLI support** (`install-codex.sh`). Codex has no status-line hook, so
28+
glint reads the rollout log Codex already writes to
29+
`~/.codex/sessions/<date>/rollout-*.jsonl` and renders into the tmux status
30+
bar instead: `--harness codex --tmux`. The adapter translates Codex's session
31+
records into the same payload shape Claude Code pipes in, so every segment
32+
downstream is unchanged. Context comes from `model_context_window`, the cache
33+
ratio from the cached share of the last turn, and quota is bucketed by the
34+
`window_minutes` Codex reports. Cost and lines changed stay hidden because
35+
Codex does not record them. `to_tmux()` rewrites our ANSI colours as tmux
36+
format strings, doubles literal `#`, and drops hyperlinks, which a tmux status
37+
cannot render.
38+
- `--tmux` and `--width N` output flags, and `--harness claude|codex`.
39+
2740
### Changed
2841

2942
- **Long branch names are elided in the middle** instead of running off the

‎README.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,42 @@ Treat them as defaults, not doctrine: `GLINT_REST_NUDGE=40` moves the whole ladd
188188
- **Python 3.8+** (standard library only: no `pip install`)
189189
- **git** (optional; the branch segment simply hides without it)
190190

191+
## Other harnesses (Codex CLI)
192+
193+
Claude Code is currently the only agent CLI that lets you supply the status line as a command. Verified in August 2026:
194+
195+
| Harness | Status line | External command hook |
196+
|---------|-------------|-----------------------|
197+
| Claude Code | `statusLine.command`, session JSON on stdin | **yes** |
198+
| Codex CLI 0.146 | built-in `tui.status_line`, a fixed set of item ids | no ([#20244](https://github.com/openai/codex/issues/20244), [#17827](https://github.com/openai/codex/issues/17827)) |
199+
| opencode 1.17 | built-in TUI bar | no ([#30295](https://github.com/anomalyco/opencode/issues/30295) is a proposal; `statusLine` appears nowhere in the shipped config schema) |
200+
| Hermes Agent | built-in bar, width-adaptive | no |
201+
| Cursor CLI | - | no |
202+
203+
Codex does not need a hook, though, because it already writes everything worth showing to `~/.codex/sessions/<date>/rollout-*.jsonl`. glint reads that and renders into your **tmux status bar** instead of Codex's own:
204+
205+
```bash
206+
curl -fsSL https://raw.githubusercontent.com/oleg-koval/glint/main/install-codex.sh | bash
207+
```
208+
209+
```
210+
✻ G5.6-sol M │ 📁 glint 🌿 dubo-175-retir…kill-gic ●3 │ 🧠 8% 20k/258k ♻️ 50% 📅7d 100% ↻4.1d ⚡240% │ ☕ 52m break 💧 47m
211+
```
212+
213+
Use `--print` first to see the tmux block and a live preview without changing anything. The installer keeps a marked, idempotent block in `~/.tmux.conf`, so re-running refreshes it rather than stacking copies, and it leaves the rest of your config alone.
214+
215+
What you get and what you do not:
216+
217+
- **Works**: model with reasoning effort, context against the real `model_context_window`, cached share of the last turn, quota windows with reset ETAs and the pace marker, plus everything that never needed the harness (directory, git, break, hydration).
218+
- **Missing**: session cost and lines changed. Codex does not record them, and glint would rather omit a segment than invent one.
219+
- Quota is bucketed by the window length Codex reports (`window_minutes`), so a 300 minute window shows as `⏱5h` and 10080 as `📅7d`.
220+
221+
For any other tool, the harness-independent half still works next to it, including in a plain shell:
222+
223+
```bash
224+
python3 ~/.claude/glint.py --harness codex --tmux # or drop --harness for stdin JSON
225+
```
226+
191227
## Upgrading
192228

193229
Re-run the installer: it overwrites `~/.claude/glint.py` and leaves your settings alone:

‎glint.py‎

Lines changed: 190 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,10 @@ def model_short(name: str) -> str:
431431
if fam in low:
432432
m = re.search(r"(\d+(?:[.\-]\d+)?)", n[low.index(fam) + len(fam):])
433433
return f"{initial}{m.group(1).replace('-', '.')}" if m else initial
434+
# Codex model ids look like "gpt-5.6-sol": keep the codename, since that is
435+
# the part that distinguishes them, and drop the vendor prefix.
436+
if low.startswith("gpt-"):
437+
return "G" + n[4:]
434438
return n or name
435439

436440

@@ -768,6 +772,150 @@ def bar(pct: float, color: int, width: int = 8) -> str:
768772
return " " + c(gauge(pct, width), color) if opt_in("BARS") else ""
769773

770774

775+
USAGE = (
776+
"usage: glint.py [--harness claude|codex] [--tmux] [--width N]\n"
777+
" glint.py --rested | --drank | --rest-status | --version\n"
778+
" (no arguments: reads Claude Code status JSON on stdin)"
779+
)
780+
781+
782+
def codex_home() -> str:
783+
return os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex")
784+
785+
786+
def _tail_text(path: str, max_bytes: int = 256 * 1024) -> str:
787+
"""The last `max_bytes` of a file, starting at a line boundary.
788+
789+
A long Codex session runs to megabytes and we want the newest records, so
790+
reading it whole on every repaint would be the slow thing in the render.
791+
"""
792+
with open(path, "rb") as fh:
793+
fh.seek(0, os.SEEK_END)
794+
size = fh.tell()
795+
fh.seek(max(0, size - max_bytes))
796+
chunk = fh.read()
797+
if size > max_bytes:
798+
chunk = chunk.split(b"\n", 1)[-1] # drop the partial first line
799+
return chunk.decode("utf-8", "replace")
800+
801+
802+
def _records(text: str):
803+
for line in text.splitlines():
804+
line = line.strip()
805+
if line.startswith("{"):
806+
try:
807+
yield json.loads(line)
808+
except Exception:
809+
continue
810+
811+
812+
def _codex_sessions(limit: int = 8) -> list[str]:
813+
"""Rollout logs, newest first. Only the few newest can matter."""
814+
root = os.path.join(codex_home(), "sessions")
815+
found = []
816+
for dirpath, _dirs, files in os.walk(root):
817+
for name in files:
818+
if name.startswith("rollout-") and name.endswith(".jsonl"):
819+
path = os.path.join(dirpath, name)
820+
try:
821+
found.append((os.path.getmtime(path), path))
822+
except OSError:
823+
continue
824+
found.sort(reverse=True)
825+
return [p for _mtime, p in found[:limit]]
826+
827+
828+
def codex_payload(cwd: str | None = None) -> dict:
829+
"""Newest Codex session, translated into Claude Code's payload shape.
830+
831+
Codex has no status-line hook (its own bar takes a fixed list of built-in
832+
items), but it writes everything worth showing to
833+
`~/.codex/sessions/<date>/rollout-*.jsonl`: token counts against the model
834+
window, the cached share of them, and quota windows with reset times. So the
835+
adapter reads that and every segment downstream stays unchanged.
836+
"""
837+
cwd = cwd or os.getcwd()
838+
payload: dict = {"cwd": cwd}
839+
840+
chosen = None
841+
for path in _codex_sessions():
842+
try:
843+
head = list(_records(open(path, encoding="utf-8", errors="replace").read(65536)))
844+
except OSError:
845+
continue
846+
meta = next((r.get("payload", {}) for r in head
847+
if r.get("type") == "session_meta"), {})
848+
session_cwd = meta.get("cwd") or ""
849+
if chosen is None:
850+
chosen = (path, head) # newest, as the fallback
851+
if session_cwd and (cwd == session_cwd or cwd.startswith(session_cwd.rstrip("/") + "/")):
852+
chosen = (path, head) # a session rooted at this tree wins
853+
break
854+
if chosen is None:
855+
return payload
856+
857+
path, head = chosen
858+
records = head + list(_records(_tail_text(path)))
859+
860+
model = effort = ""
861+
usage: dict = {}
862+
limits: dict = {}
863+
for rec in records: # last write wins: newest state
864+
body = rec.get("payload") or {}
865+
if body.get("type") == "turn_context" or rec.get("type") == "turn_context":
866+
model = body.get("model") or model
867+
effort = body.get("effort") or effort
868+
if body.get("type") == "token_count":
869+
info = body.get("info") or {}
870+
usage = info or usage
871+
limits = body.get("rate_limits") or limits
872+
873+
if model:
874+
payload["model"] = {"display_name": model, "id": model}
875+
if effort:
876+
payload["effort"] = {"level": effort}
877+
878+
last = (usage.get("last_token_usage") or {}) if usage else {}
879+
window = usage.get("model_context_window") if usage else None
880+
if isinstance(window, (int, float)) and window > 0 and last:
881+
payload["context_window"] = {
882+
"total_input_tokens": last.get("total_tokens") or 0,
883+
"context_window_size": window,
884+
}
885+
if last.get("input_tokens"):
886+
payload["cache"] = {"total": last["input_tokens"],
887+
"read": last.get("cached_input_tokens") or 0}
888+
889+
# Codex reports quota as primary/secondary with the window length attached,
890+
# rather than named five_hour/seven_day slots, so bucket by that length.
891+
rl = {}
892+
for key in ("primary", "secondary"):
893+
entry = (limits or {}).get(key)
894+
if not isinstance(entry, dict) or not isinstance(entry.get("used_percent"), (int, float)):
895+
continue
896+
minutes = entry.get("window_minutes") or 0
897+
slot = "five_hour" if 0 < minutes <= 720 else "seven_day"
898+
rl[slot] = {"used_percentage": entry["used_percent"], "resets_at": entry.get("resets_at")}
899+
if rl:
900+
payload["rate_limits"] = rl
901+
return payload
902+
903+
904+
_SGR = re.compile(r"\033\[(?:(1);)?38;5;(\d+)m")
905+
906+
907+
def to_tmux(line: str) -> str:
908+
"""Rewrite our ANSI colours as tmux format strings.
909+
910+
tmux status strings take `#[fg=colour114]`, not SGR escapes, and treat a bare
911+
`#` as the start of a format, so literal ones have to be doubled first.
912+
Hyperlinks go: OSC 8 does not survive a status line.
913+
"""
914+
line = _OSC8.sub("", line).replace("#", "##")
915+
line = _SGR.sub(lambda m: "#[fg=colour" + m.group(2) + (",bold]" if m.group(1) else "]"), line)
916+
return line.replace("\033[0m", "#[default]")
917+
918+
771919
def main() -> None:
772920
# Detached background refresh spawned by pr_for_branch; not a status-line render.
773921
if len(sys.argv) == 5 and sys.argv[1] == "--refresh-pr":
@@ -800,21 +948,45 @@ def main() -> None:
800948
f"(nudge at {int(env_minutes('WATER_EVERY', WATER_EVERY))})")
801949
return
802950

803-
# Anything else flag-shaped is a typo. Without this it falls through to
804-
# reading stdin and hangs with no output until Ctrl-D.
805-
if len(sys.argv) > 1 and sys.argv[1].startswith("-"):
806-
print(f"glint: unknown option {sys.argv[1]!r}\n"
807-
"usage: glint.py [--rested | --drank | --rest-status | --version]\n"
808-
" (no arguments: reads Claude Code status JSON on stdin)",
809-
file=sys.stderr)
951+
harness, tmux, width = "claude", False, None
952+
args = sys.argv[1:]
953+
while args:
954+
a = args.pop(0)
955+
if a == "--harness" and args:
956+
harness = args.pop(0)
957+
elif a == "--tmux":
958+
tmux = True
959+
elif a == "--width" and args:
960+
try:
961+
width = int(args.pop(0))
962+
except ValueError:
963+
print("glint: --width wants a number", file=sys.stderr)
964+
sys.exit(2)
965+
else:
966+
print(f"glint: unknown option {a!r}\n{USAGE}", file=sys.stderr)
967+
sys.exit(2)
968+
969+
if harness in ("claude", "claude-code"):
970+
try:
971+
d = json.loads(sys.stdin.read())
972+
except Exception:
973+
d = {}
974+
elif harness == "codex":
975+
d = codex_payload() # no hook to pipe us anything: read its session log
976+
else:
977+
print(f"glint: unknown harness {harness!r} (try: claude, codex)", file=sys.stderr)
810978
sys.exit(2)
811979

812-
raw = sys.stdin.read()
813-
try:
814-
d = json.loads(raw)
815-
except Exception:
816-
d = {}
980+
if width is None:
981+
# A tmux status has no tty to measure, so assume it is not the constraint
982+
# and let tmux itself truncate; a real terminal gets the honest width.
983+
width = 400 if tmux else term_width() - 2
984+
line = build_line(d, width)
985+
sys.stdout.write(to_tmux(line) if tmux else line)
986+
817987

988+
def build_line(d: dict, width: int) -> str:
989+
"""The status line itself, from a payload in Claude Code's shape."""
818990
segments: list[tuple[float, int, str]] = [] # (priority, group, text); see fit()
819991

820992
# ── Model badge, with reasoning effort and fast mode ──
@@ -925,6 +1097,11 @@ def main() -> None:
9251097
segments.append((PRIO_CONTEXT, GRP_BUDGET, seg))
9261098

9271099
# ── Prompt-cache efficiency (cache reads are ~10x cheaper than fresh input) ──
1100+
# An adapter can hand us the numbers directly; only Claude Code has a
1101+
# transcript file to derive them from.
1102+
supplied = d.get("cache") or {}
1103+
if isinstance(supplied.get("total"), (int, float)) and supplied["total"] > 0:
1104+
tx_tokens, tx_cached = supplied["total"], supplied.get("read") or 0
9281105
if enabled("CACHE") and tx_tokens > 0:
9291106
ratio = tx_cached / tx_tokens
9301107
rc = GREEN if ratio >= 0.8 else YELLOW if ratio >= 0.5 else RED
@@ -966,7 +1143,7 @@ def main() -> None:
9661143
if wseg:
9671144
segments.append((PRIO_WATER, GRP_REST, wseg))
9681145

969-
sys.stdout.write(fit(segments, term_width() - 2))
1146+
return fit(segments, width)
9701147

9711148

9721149
if __name__ == "__main__":

0 commit comments

Comments
 (0)