Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat(repl): add colored mode badges and PTY debugger

Rach Pradhanfc8fe5cc7c23
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 63e9e75e..a1ce6c82 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -51,6 +51,9 @@ jobs:
- name: PTY spinner anti-stealth test
run: python3 scripts/test-pty-spinner.py zig-out/bin/graff
+ - name: PTY REPL interaction test
+ run: python3 scripts/test-pty-repl.py zig-out/bin/graff
+
- name: SDK generation drift
run: |
python3 sdk/generate.py --harness ./zig-out/bin/graff
diff --git a/README.md b/README.md
index 91705dbb..1c66f72f 100644
--- a/README.md
+++ b/README.md
@@ -401,7 +401,9 @@ click-to-fold.
/plan toggle plan mode: read-only explore + propose; writes/edits denied
/key [p k] show API-key status; /key <provider> <key> adds one live (+ Keychain)
/keepcontext toggle keeping the conversation when /model switches wire format (default on)
-/reasoning codex/gpt-5 reasoning depth: low|medium|high (default high)
+/reasoning reasoning picker: low|medium|high|xhigh|max|ultra (persists)
+/fast toggle Codex priority service tier for lower latency
+/ultracode toggle persistent multi-agent workflow mode
/rewind [n] list past prompts; /rewind <n> drops prompt n+after & reverts its file edits
/image <path> attach an image to your next message (vision models only)
/paste attach the clipboard image (macOS); also Ctrl-V (⌘V can't be captured)
@@ -425,10 +427,14 @@ editing (Ctrl-A/E/W/U/K, Option+Delete, word moves). The selected model is
remembered in `~/.simple-harness-model` and resumed next launch
(`--model <name>` overrides; a remembered model that's no longer in the table is
ignored with a note). The prompt is a small statusline:
-`[model · 12345/800k tok (1%) · ⚡cached · $0.0042]`: context used vs the
-compaction budget, last cache hit, and session spend. Errors aim to be
-actionable: `/resume nope` says the session file wasn't found and points at
-`/sessions`; an unknown `/foo` points at `/help`.
+`[model · Extra high · Fast · Plan · cwd /repo · 12345/800k tok (1%) · ⚡cached]`.
+Active modes are visible at a glance: Low is green, Medium cyan, High yellow,
+Extra high/Ultra/Ultracode magenta, Max/Strict/YOLO red, and Plan yellow.
+Badges for unsupported settings are hidden instead of implying they apply. The
+tail shows context used vs the compaction budget, last cache hit, and (for
+metered providers) session spend.
+Errors aim to be actionable: `/resume nope` says the session file wasn't found
+and points at `/sessions`; an unknown `/foo` points at `/help`.
---
@@ -461,7 +467,7 @@ the REPL:
| mode | turn on | what it does |
| ---------- | -------------------- | ------------ |
| **yolo** | `--yolo` · `/yolo` | Skip **every** prompt: bash, edits, and MCP all run without asking. For sandboxes, CI, and `-p`/`--json` runs where there's no human to answer. `--yolo` starts the session in it; `/yolo` toggles mid-session. |
-| **plan** | `/plan` | Read-only: the model explores and *proposes* a plan; the gate hard-denies writes, edits, MCP, and any bash beyond the read-only seed (even your saved allow-list) until you `/plan` again to execute. The prompt shows a ` plan` badge. |
+| **plan** | `/plan` | Read-only: the model explores and *proposes* a plan; the gate hard-denies writes, edits, MCP, and any bash beyond the read-only seed (even your saved allow-list) until you `/plan` again to execute. The prompt shows a yellow `Plan` badge. |
| **strict** | `/strict` | "Every message is a tool": the model must call exactly one tool per message and finish with `attempt_completion`. Useful for deterministic, scriptable agent loops. |
**One-shot mode** (`graff -p "…"` or `--json`) has no human to answer the
diff --git a/docs/debugging-the-harness.md b/docs/debugging-the-harness.md
index c89760ec..07cda391 100644
--- a/docs/debugging-the-harness.md
+++ b/docs/debugging-the-harness.md
@@ -13,11 +13,48 @@ path. Find it, move it off the path, apply the result somewhere free.
## 1. Measure the RIGHT path
- **Interactive ≠ oneshot.** `graff -p` skips the TUI header/card, so it misses the
session-title call, the card render, etc. For anything the user feels *interactively*,
- drive a real PTY (`pty.fork`) — see `scripts/test-pty-spinner.py`. Oneshot benchmarks
- hid the entire title-gen call in #117.
+ drive a real PTY. `scripts/pty-debug.py` provides ordered command/key/expect actions
+ over the shared `scripts/pty_harness.py`; `test-pty-spinner.py` and
+ `test-pty-repl.py` exercise the same driver in CI. Oneshot benchmarks hid the entire
+ title-gen call in #117.
- **Split the phases.** `time-to-prompt` (startup) and `time-to-first-response` (the turn)
have completely different culprits. Profile them separately or you'll fix the wrong one.
+### Agent-friendly PTY debugger
+
+Build once, then describe the terminal interaction in command-line order:
+
+```bash
+zig build
+scripts/pty-debug.py --bin zig-out/bin/graff --cwd /tmp \
+ --arg --model --arg gpt-5.6-sol \
+ --cmd '/effort xhigh' \
+ --expect 'reasoning effort: Extra high' \
+ --expect-prompt
+```
+
+Full-screen pickers can be driven with real key sequences:
+
+```bash
+scripts/pty-debug.py --bin zig-out/bin/graff \
+ --cmd /effort --expect 'Reasoning level for' \
+ --key down --key enter --expect 'reasoning effort:'
+```
+
+Useful debugging options:
+
+- `--raw-out /tmp/graff.pty` preserves exact ANSI, alternate-screen, and cursor bytes.
+- `--text-out /tmp/graff.txt` writes the cleaned transcript agents normally want to inspect.
+- `--rows 24 --cols 80` reproduces wrapping, clipping, and picker-layout bugs at an exact
+ terminal size (the deterministic default is 40×120).
+- `--env KEY=VALUE` / `--unset KEY` isolate feature flags, auth, and inherited shell state.
+- `--no-color` intentionally tests the promptless line-oriented fallback and implies
+ `--no-ready`; normal runs force a real `TERM` and unset `NO_COLOR` so a CI/agent shell
+ cannot silently disable the TUI.
+- Every expectation has a timeout and only matches output produced after the most recent
+ input action, so stale startup text cannot create a false pass while several assertions
+ can still inspect one terminal redraw.
+
## 2. Isolate with toggles
Bisect by flipping one thing at a time and re-timing:
- `GRAFF_FLEET=off` — drops the fleet `pullElites` GET.
diff --git a/scripts/pty-debug.py b/scripts/pty-debug.py
new file mode 100755
index 00000000..f5a031a3
--- /dev/null
+++ b/scripts/pty-debug.py
@@ -0,0 +1,245 @@
+#!/usr/bin/env python3
+"""Drive a real Graff REPL from an ordered list of terminal actions.
+
+Examples:
+ scripts/pty-debug.py --bin zig-out/bin/graff --cwd /tmp \\
+ --arg --model --arg gpt-5.6-sol \\
+ --cmd '/effort xhigh' --expect 'reasoning effort: Extra high' \\
+ --expect-prompt
+
+ scripts/pty-debug.py --bin zig-out/bin/graff \\
+ --cmd /effort --expect 'Reasoning level for' \\
+ --key down --key enter --expect 'reasoning effort:'
+
+Actions execute in command-line order. Assertions inspect output produced since
+the most recent input action, which prevents stale startup text from passing.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import sys
+from pathlib import Path
+
+from pty_harness import PtyFailure, PtySession
+
+
+USAGE = __doc__ + """
+Options:
+ --bin PATH Graff binary (default: zig-out/bin/graff, then graff)
+ --cwd PATH child working directory (default: current directory)
+ --arg VALUE append one Graff launch argument; repeat as needed
+ --env KEY=VALUE set a child environment variable
+ --unset KEY remove a child environment variable
+ --timeout SECONDS timeout for each expectation (default: 10)
+ --rows N terminal height (default: 40)
+ --cols N terminal width (default: 120)
+ --raw-out PATH save exact PTY bytes, including ANSI/control sequences
+ --text-out PATH save the cleaned readable transcript
+ --no-ready do not wait for the initial `] ›` prompt
+ --no-color set NO_COLOR=1 and skip the interactive-prompt wait
+ --quiet print only failures and the final transcript
+
+Ordered actions:
+ --cmd TEXT type TEXT followed by Enter
+ --text TEXT type without Enter
+ --key NAME enter/up/down/left/right/esc/tab/backspace/ctrl-c/ctrl-d
+ --expect TEXT wait for literal cleaned terminal text
+ --expect-re REGEX wait for a regular expression
+ --expect-prompt wait for the next `] ›` prompt
+ --sleep SECONDS keep capturing output for a fixed interval
+"""
+
+
+VALUE_OPTIONS = {
+ "--bin",
+ "--cwd",
+ "--arg",
+ "--env",
+ "--unset",
+ "--timeout",
+ "--rows",
+ "--cols",
+ "--raw-out",
+ "--text-out",
+}
+ACTION_VALUES = {"--cmd", "--text", "--key", "--expect", "--expect-re", "--sleep"}
+ACTION_FLAGS = {"--expect-prompt"}
+BOOL_OPTIONS = {"--no-ready", "--no-color", "--quiet"}
+
+
+def die(message: str) -> None:
+ print(f"pty-debug: {message}", file=sys.stderr)
+ raise SystemExit(2)
+
+
+def parse(argv: list[str]) -> tuple[dict[str, object], list[tuple[str, str]]]:
+ default_bin = "zig-out/bin/graff" if os.path.exists("zig-out/bin/graff") else "graff"
+ config: dict[str, object] = {
+ "bin": default_bin,
+ "cwd": os.getcwd(),
+ "args": [],
+ "env": {},
+ "unset": [],
+ "timeout": 10.0,
+ "rows": 40,
+ "cols": 120,
+ "raw_out": None,
+ "text_out": None,
+ "ready": True,
+ "color": True,
+ "quiet": False,
+ }
+ actions: list[tuple[str, str]] = []
+ i = 0
+ positional_bin = False
+ while i < len(argv):
+ token = argv[i]
+ if token in ("-h", "--help"):
+ print(USAGE.strip())
+ raise SystemExit(0)
+ if not token.startswith("-") and not positional_bin:
+ config["bin"] = token
+ positional_bin = True
+ i += 1
+ continue
+ if token in ACTION_FLAGS:
+ actions.append((token, ""))
+ i += 1
+ continue
+ if token in BOOL_OPTIONS:
+ if token == "--no-ready":
+ config["ready"] = False
+ elif token == "--no-color":
+ config["color"] = False
+ config["ready"] = False
+ else:
+ config["quiet"] = True
+ i += 1
+ continue
+ if token in VALUE_OPTIONS or token in ACTION_VALUES:
+ if i + 1 >= len(argv):
+ die(f"{token} needs a value")
+ value = argv[i + 1]
+ if token in ACTION_VALUES:
+ actions.append((token, value))
+ elif token == "--bin":
+ config["bin"] = value
+ elif token == "--cwd":
+ config["cwd"] = value
+ elif token == "--arg":
+ config["args"].append(value) # type: ignore[union-attr]
+ elif token == "--env":
+ if "=" not in value:
+ die("--env expects KEY=VALUE")
+ key, env_value = value.split("=", 1)
+ config["env"][key] = env_value # type: ignore[index]
+ elif token == "--unset":
+ config["unset"].append(value) # type: ignore[union-attr]
+ elif token == "--timeout":
+ try:
+ config["timeout"] = float(value)
+ except ValueError:
+ die("--timeout expects a number")
+ elif token == "--rows":
+ try:
+ config["rows"] = int(value)
+ except ValueError:
+ die("--rows expects an integer")
+ elif token == "--cols":
+ try:
+ config["cols"] = int(value)
+ except ValueError:
+ die("--cols expects an integer")
+ elif token == "--raw-out":
+ config["raw_out"] = value
+ elif token == "--text-out":
+ config["text_out"] = value
+ i += 2
+ continue
+ die(f"unknown option {token!r}; use --help")
+ if not actions:
+ die("no actions supplied; add --cmd/--key/--expect (see --help)")
+ if float(config["timeout"]) <= 0:
+ die("--timeout must be positive")
+ if int(config["rows"]) <= 0 or int(config["cols"]) <= 0:
+ die("--rows and --cols must be positive")
+ return config, actions
+
+
+def note(quiet: bool, message: str) -> None:
+ if not quiet:
+ print(message, file=sys.stderr)
+
+
+def main() -> int:
+ config, actions = parse(sys.argv[1:])
+ quiet = bool(config["quiet"])
+ session = PtySession(
+ str(config["bin"]),
+ config["args"], # type: ignore[arg-type]
+ cwd=str(config["cwd"]),
+ env=config["env"], # type: ignore[arg-type]
+ unset_env=config["unset"], # type: ignore[arg-type]
+ color=bool(config["color"]),
+ timeout=float(config["timeout"]),
+ rows=int(config["rows"]),
+ cols=int(config["cols"]),
+ )
+ cursor = 0
+ failed: Exception | None = None
+ try:
+ if config["ready"]:
+ cursor = session.wait_for_literal("] ›", start=cursor)
+ note(quiet, "✓ initial REPL prompt")
+ for action, value in actions:
+ if action == "--cmd":
+ cursor = len(session.raw)
+ session.send_line(value)
+ note(quiet, f"→ cmd {value}")
+ elif action == "--text":
+ cursor = len(session.raw)
+ session.send_text(value)
+ note(quiet, f"→ text {value!r}")
+ elif action == "--key":
+ cursor = len(session.raw)
+ session.send_key(value)
+ note(quiet, f"→ key {value}")
+ elif action == "--expect":
+ session.wait_for_literal(value, start=cursor)
+ note(quiet, f"✓ expect {value!r}")
+ elif action == "--expect-re":
+ session.wait_for(re.compile(value), start=cursor)
+ note(quiet, f"✓ expect-re {value!r}")
+ elif action == "--expect-prompt":
+ session.wait_for_literal("] ›", start=cursor)
+ note(quiet, "✓ next REPL prompt")
+ elif action == "--sleep":
+ session.pump_for(float(value))
+ note(quiet, f"✓ captured {value}s")
+ session.pump_for(0.15)
+ except (PtyFailure, ValueError, re.error) as exc:
+ failed = exc
+ finally:
+ session.close()
+
+ raw = bytes(session.raw)
+ text = session.text
+ if config["raw_out"]:
+ Path(str(config["raw_out"])).write_bytes(raw)
+ note(quiet, f"saved raw PTY bytes → {config['raw_out']}")
+ if config["text_out"]:
+ Path(str(config["text_out"])).write_text(text, encoding="utf-8")
+ note(quiet, f"saved cleaned transcript → {config['text_out']}")
+
+ print(text, end="" if text.endswith("\n") else "\n")
+ if failed:
+ print(f"\nPTY DEBUG FAILED: {failed}", file=sys.stderr)
+ return 1
+ note(quiet, f"✓ {len(actions)} action(s) completed")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/pty_harness.py b/scripts/pty_harness.py
new file mode 100755
index 00000000..1caedb34
--- /dev/null
+++ b/scripts/pty_harness.py
@@ -0,0 +1,364 @@
+#!/usr/bin/env python3
+"""Small, dependency-free PTY driver shared by Graff debug/test scripts."""
+
+from __future__ import annotations
+
+import fcntl
+import os
+import pty
+import re
+import select
+import signal
+import struct
+import termios
+import time
+from dataclasses import dataclass
+from typing import Iterable, Mapping, Pattern, Sequence
+
+
+OSC_RE = re.compile(rb"\x1b\].*?(?:\x07|\x1b\\)", re.DOTALL)
+CSI_TEXT_RE = re.compile(r"\x1b\[([0-?]*)([ -/]*)([@-~])")
+
+KEYS = {
+ "enter": b"\r",
+ "return": b"\r",
+ "up": b"\x1b[A",
+ "down": b"\x1b[B",
+ "right": b"\x1b[C",
+ "left": b"\x1b[D",
+ "esc": b"\x1b",
+ "escape": b"\x1b",
+ "tab": b"\t",
+ "backspace": b"\x7f",
+ "ctrl-c": b"\x03",
+ "ctrl-d": b"\x04",
+ "ctrl-g": b"\x07",
+}
+
+
+def terminal_text(raw: bytes) -> str:
+ """Render a readable scrollback transcript from terminal output.
+
+ This intentionally implements only the horizontal cursor/erase operations
+ used by Graff's line editor. Merely deleting ANSI bytes turns typed input
+ into `/e/ef/eff/...`; applying the redraws leaves the final visible line.
+ Full-screen picker repaints remain as sequential snapshots, which is more
+ useful for debugging than pretending this is a complete terminal emulator.
+ """
+ source = OSC_RE.sub(b"", raw).decode("utf-8", errors="replace")
+ lines: list[str] = []
+ line: list[str] = []
+ col = 0
+ i = 0
+
+ def count(params: str, default: int = 1) -> int:
+ head = params.lstrip("?").split(";", 1)[0]
+ try:
+ return int(head) if head else default
+ except ValueError:
+ return default
+
+ while i < len(source):
+ if source[i] == "\x1b":
+ match = CSI_TEXT_RE.match(source, i)
+ if match:
+ params, _, final = match.groups()
+ amount = count(params)
+ if final == "D":
+ col = max(0, col - amount)
+ elif final == "C":
+ col += amount
+ elif final == "G":
+ col = max(0, amount - 1)
+ elif final == "K":
+ mode = count(params, 0)
+ if mode == 2:
+ line.clear()
+ col = 0
+ elif mode == 1:
+ for j in range(min(col + 1, len(line))):
+ line[j] = " "
+ else:
+ del line[min(col, len(line)) :]
+ elif final == "J" and count(params, 0) == 2:
+ if line:
+ lines.append("".join(line).rstrip())
+ line = []
+ col = 0
+ elif final in ("H", "f"):
+ col = 0
+ i = match.end()
+ continue
+ single = re.match(r"\x1b[()][0-2A-Z]", source[i:])
+ if single:
+ i += single.end()
+ continue
+ # Unknown escape: discard ESC but keep following printable bytes.
+ i += 1
+ continue
+ ch = source[i]
+ i += 1
+ if ch == "\r":
+ col = 0
+ elif ch == "\n":
+ lines.append("".join(line).rstrip())
+ line = []
+ col = 0
+ elif ch == "\b":
+ col = max(0, col - 1)
+ elif ch >= " ":
+ if col > len(line):
+ line.extend(" " for _ in range(col - len(line)))
+ if col == len(line):
+ line.append(ch)
+ else:
+ line[col] = ch
+ col += 1
+ if line:
+ lines.append("".join(line).rstrip())
+ return "\n".join(lines)
+
+
+class PtyFailure(RuntimeError):
+ pass
+
+
+class PtyTimeout(PtyFailure):
+ pass
+
+
+@dataclass
+class PtyResult:
+ raw: bytes
+ exit_code: int | None
+ timed_out: bool
+
+ @property
+ def text(self) -> str:
+ return terminal_text(self.raw)
+
+
+class PtySession:
+ """A real terminal session with incremental send/wait/capture operations."""
+
+ def __init__(
+ self,
+ binary: str,
+ args: Sequence[str] = (),
+ *,
+ cwd: str | None = None,
+ env: Mapping[str, str] | None = None,
+ unset_env: Iterable[str] = (),
+ color: bool = True,
+ timeout: float = 10.0,
+ rows: int = 40,
+ cols: int = 120,
+ ) -> None:
+ self.binary = os.path.abspath(binary) if os.sep in binary else binary
+ self.args = list(args)
+ self.cwd = os.path.abspath(cwd or os.getcwd())
+ self.timeout = timeout
+ self.rows = rows
+ self.cols = cols
+ self.raw = bytearray()
+ self.exit_code: int | None = None
+ self._closed = False
+
+ child_env = os.environ.copy()
+ if env:
+ child_env.update(env)
+ for name in unset_env:
+ child_env.pop(name, None)
+ child_env["PWD"] = self.cwd
+ if color:
+ child_env.pop("NO_COLOR", None)
+ child_env.setdefault("TERM", "xterm-256color")
+ else:
+ child_env["NO_COLOR"] = "1"
+
+ self.pid, self.fd = pty.fork()
+ if self.pid == 0:
+ try:
+ os.chdir(self.cwd)
+ fcntl.ioctl(0, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))
+ os.execvpe(self.binary, [self.binary, *self.args], child_env)
+ except BaseException:
+ os._exit(127)
+
+ @property
+ def text(self) -> str:
+ return terminal_text(bytes(self.raw))
+
+ def _record_exit(self, status: int) -> None:
+ self.exit_code = os.waitstatus_to_exitcode(status)
+
+ def poll(self) -> int | None:
+ if self.exit_code is not None:
+ return self.exit_code
+ try:
+ pid, status = os.waitpid(self.pid, os.WNOHANG)
+ except ChildProcessError:
+ return self.exit_code
+ if pid:
+ self._record_exit(status)
+ return self.exit_code
+
+ def pump(self, wait: float = 0.05) -> bool:
+ """Read one available chunk. Returns true when bytes were captured."""
+ if self._closed:
+ return False
+ ready, _, _ = select.select([self.fd], [], [], max(0.0, wait))
+ if not ready:
+ self.poll()
+ return False
+ try:
+ chunk = os.read(self.fd, 65536)
+ except OSError:
+ self.poll()
+ return False
+ if not chunk:
+ self.poll()
+ return False
+ self.raw.extend(chunk)
+ return True
+
+ def pump_for(self, seconds: float) -> None:
+ deadline = time.monotonic() + max(0.0, seconds)
+ while time.monotonic() < deadline and self.poll() is None:
+ self.pump(min(0.05, deadline - time.monotonic()))
+
+ def send(self, data: bytes) -> None:
+ if self.poll() is not None:
+ raise PtyFailure(f"child already exited with {self.exit_code}")
+ os.write(self.fd, data)
+
+ def send_text(self, text: str) -> None:
+ self.send(text.encode("utf-8"))
+
+ def send_line(self, text: str) -> None:
+ self.send(text.encode("utf-8") + b"\r")
+
+ def send_key(self, name: str) -> None:
+ key = KEYS.get(name.lower())
+ if key is None:
+ raise PtyFailure(f"unknown key {name!r}; choose from {', '.join(sorted(KEYS))}")
+ self.send(key)
+
+ def wait_for(
+ self,
+ expected: str | Pattern[str],
+ *,
+ start: int = 0,
+ timeout: float | None = None,
+ ) -> int:
+ """Wait for cleaned text emitted after raw-byte offset ``start``.
+
+ The returned cursor is the current raw length. Callers should reset
+ their cursor immediately before an input action, then keep that same
+ cursor for every assertion about the resulting redraw. Cleaned text
+ offsets are not stable because terminal erase/cursor commands can
+ rewrite an earlier visible line.
+ """
+ deadline = time.monotonic() + (self.timeout if timeout is None else timeout)
+ pattern = re.compile(expected) if isinstance(expected, str) else expected
+ while True:
+ raw_start = min(start, len(self.raw))
+ text = terminal_text(bytes(self.raw[raw_start:]))
+ match = pattern.search(text)
+ if match:
+ return len(self.raw)
+ if self.poll() is not None:
+ raise PtyFailure(
+ f"child exited with {self.exit_code} before matching {pattern.pattern!r}"
+ )
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ tail = self.text[-2000:]
+ raise PtyTimeout(
+ f"timed out after {timeout or self.timeout:.1f}s waiting for "
+ f"{pattern.pattern!r}\n--- transcript tail ---\n{tail}"
+ )
+ self.pump(min(0.05, remaining))
+
+ def wait_for_literal(
+ self, expected: str, *, start: int = 0, timeout: float | None = None
+ ) -> int:
+ return self.wait_for(re.compile(re.escape(expected)), start=start, timeout=timeout)
+
+ def read_until_exit(self, timeout: float | None = None) -> PtyResult:
+ deadline = time.monotonic() + (self.timeout if timeout is None else timeout)
+ timed_out = False
+ while self.poll() is None:
+ if time.monotonic() >= deadline:
+ timed_out = True
+ break
+ self.pump(min(0.05, deadline - time.monotonic()))
+ if timed_out:
+ self.terminate()
+ else:
+ # Drain bytes already queued after waitpid observed the exit.
+ while self.pump(0):
+ pass
+ return PtyResult(bytes(self.raw), self.exit_code, timed_out)
+
+ def terminate(self) -> None:
+ if self.poll() is None:
+ try:
+ os.kill(self.pid, signal.SIGTERM)
+ except ProcessLookupError:
+ pass
+ end = time.monotonic() + 0.5
+ while self.poll() is None and time.monotonic() < end:
+ self.pump(0.05)
+ if self.poll() is None:
+ try:
+ os.kill(self.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ try:
+ _, status = os.waitpid(self.pid, 0)
+ self._record_exit(status)
+ except ChildProcessError:
+ pass
+
+ def close(self) -> None:
+ if self._closed:
+ return
+ self.terminate()
+ try:
+ os.close(self.fd)
+ except OSError:
+ pass
+ self._closed = True
+
+ def __enter__(self) -> "PtySession":
+ return self
+
+ def __exit__(self, *_: object) -> None:
+ self.close()
+
+
+def run_to_exit(
+ binary: str,
+ args: Sequence[str] = (),
+ *,
+ cwd: str | None = None,
+ env: Mapping[str, str] | None = None,
+ unset_env: Iterable[str] = (),
+ color: bool = True,
+ timeout: float = 15.0,
+ rows: int = 40,
+ cols: int = 120,
+) -> PtyResult:
+ with PtySession(
+ binary,
+ args,
+ cwd=cwd,
+ env=env,
+ unset_env=unset_env,
+ color=color,
+ timeout=timeout,
+ rows=rows,
+ cols=cols,
+ ) as session:
+ return session.read_until_exit(timeout)
diff --git a/scripts/test-pty-repl.py b/scripts/test-pty-repl.py
new file mode 100755
index 00000000..eacaa506
--- /dev/null
+++ b/scripts/test-pty-repl.py
@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+"""Deterministic real-PTY smoke test for interactive REPL state/redraws."""
+
+import os
+import sys
+import tempfile
+
+from pty_harness import PtySession, terminal_text
+
+
+_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
+
+
+def main() -> None:
+ assert terminal_text(b"prompt\r\x1b[2Kdone") == "done"
+ assert terminal_text(b"abc\x1b[2DXY") == "aXY"
+ with tempfile.TemporaryDirectory(prefix="graff-pty-") as tmp:
+ env = {
+ "HOME": tmp,
+ "CODEGRAFF_API_KEY": "local-pty-test",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ }
+ with PtySession(
+ GRAFF,
+ ["--model", "deepseek-v4-pro", "--no-telemetry"],
+ cwd=tmp,
+ env=env,
+ unset_env=("CODEX_HOME", "NO_COLOR"),
+ timeout=15.0,
+ ) as session:
+ session.wait_for_literal("] ›")
+
+ def command(line: str, output: str, prompt: str, color_bytes: bytes) -> None:
+ cursor = len(session.raw)
+ session.send_line(line)
+ session.wait_for_literal(output, start=cursor)
+ session.wait_for_literal(prompt, start=cursor)
+ if color_bytes not in bytes(session.raw[cursor:]):
+ raise AssertionError(f"missing colored badge {color_bytes!r} after {line}")
+
+ base = "deepseek-v4-pro · Extra high"
+ command(
+ "/effort xhigh",
+ "reasoning effort: Extra high",
+ f"[{base} · cwd {tmp}]",
+ b"\x1b[35mExtra high\x1b[0m",
+ )
+ command(
+ "/plan",
+ "plan mode on",
+ f"[{base} · Plan · cwd {tmp}]",
+ b"\x1b[33mPlan\x1b[0m",
+ )
+ command(
+ "/strict",
+ "strict mode ON",
+ f"[{base} · Plan · Strict · cwd {tmp}]",
+ b"\x1b[31mStrict\x1b[0m",
+ )
+ command(
+ "/ultracode on",
+ "ultracode mode: on",
+ f"[{base} · Plan · Strict · Ultracode · cwd {tmp}]",
+ b"\x1b[35mUltracode\x1b[0m",
+ )
+ command(
+ "/yolo",
+ "yolo mode ON",
+ f"[{base} · Plan · Strict · Ultracode · YOLO · cwd {tmp}]",
+ b"\x1b[31mYOLO\x1b[0m",
+ )
+ session.send_key("ctrl-d")
+ result = session.read_until_exit(5.0)
+ if result.timed_out or result.exit_code != 0:
+ raise SystemExit(
+ f"REPL did not exit cleanly: exit={result.exit_code} timed_out={result.timed_out}"
+ )
+ print("ok PTY REPL commands, colored mode badges, redraws, and clean exit")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test-pty-spinner.py b/scripts/test-pty-spinner.py
index 7c22158c..071a0ff7 100644
--- a/scripts/test-pty-spinner.py
+++ b/scripts/test-pty-spinner.py
@@ -15,7 +15,9 @@ by running there or by code review — this raises the bar as far as a test can.
Usage: python3 scripts/test-pty-spinner.py [path-to-graff]
Exit 0 = clean, 1 = a forbidden glyph (or a broken render) was found.
"""
-import os, sys, pty, select
+import os, sys
+
+from pty_harness import run_to_exit
_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
# absolute, so the child's chdir() to another cwd can't break the exec lookup
@@ -28,31 +30,14 @@ THRESHOLD = 0x10000 # supplementary plane: no legit spinner glyph lives here;
def render_in_pty(cwd):
- """Run `graff --selftest-spinner` in a PTY rooted at cwd; return captured bytes."""
- pid, fd = pty.fork()
- if pid == 0: # child: real TTY on the slave end
- try:
- os.chdir(cwd)
- os.execvp(GRAFF, [GRAFF, "--selftest-spinner"])
- except Exception:
- os._exit(127)
- out = bytearray()
- while True:
- try:
- r, _, _ = select.select([fd], [], [], 15.0)
- if not r:
- break
- chunk = os.read(fd, 65536)
- if not chunk:
- break
- out += chunk
- except OSError:
- break
- try:
- os.waitpid(pid, 0)
- except OSError:
- pass
- return bytes(out)
+ """Run the spinner hook in the shared real-PTY harness."""
+ return run_to_exit(
+ GRAFF,
+ ["--selftest-spinner"],
+ cwd=cwd,
+ env={"LMSTUDIO_API_KEY": os.environ["LMSTUDIO_API_KEY"]},
+ timeout=15.0,
+ )
def scan(raw):
@@ -72,9 +57,15 @@ def main():
cwds.append(c)
failures = 0
for cwd in cwds:
- raw = render_in_pty(cwd)
- bad, lines, ok = scan(raw)
- if bad:
+ result = render_in_pty(cwd)
+ bad, lines, ok = scan(result.raw)
+ if result.timed_out:
+ print(f"FAIL cwd={cwd}: PTY render timed out")
+ failures += 1
+ elif result.exit_code != 0:
+ print(f"FAIL cwd={cwd}: spinner exited {result.exit_code}")
+ failures += 1
+ elif bad:
glyphs = ", ".join(f"U+{c:X}" for c in bad)
print(f"FAIL cwd={cwd}: {len(bad)} supplementary-plane glyph(s) rendered: {glyphs}")
failures += 1
diff --git a/src/agent.zig b/src/agent.zig
index b0a0349b..c59839f1 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -38,6 +38,32 @@ const pricing = @import("pricing.zig");
const ansi = @import("ansi.zig");
const style = &ansi.style;
+fn reasoningPromptLabel(effort: ReasoningEffort) []const u8 {
+ return switch (effort) {
+ .low => "Low",
+ .medium => "Medium",
+ .high => "High",
+ .xhigh => "Extra high",
+ .max => "Max",
+ .ultra => "Ultra",
+ };
+}
+
+fn reasoningPromptColor(effort: ReasoningEffort) []const u8 {
+ return switch (effort) {
+ .low => style.green,
+ .medium => style.cyan,
+ .high => style.yellow,
+ .xhigh => style.magenta,
+ .max => style.red,
+ .ultra => style.magenta,
+ };
+}
+
+fn writePromptBadge(w: *Io.Writer, color: []const u8, label: []const u8) !void {
+ try w.print("{s} · {s}{s}{s}{s}", .{ style.dim, style.reset, color, label, style.reset });
+}
+
pub const TodoItem = struct {
content: []const u8,
status: []const u8,
@@ -129,7 +155,6 @@ pub const Agent = struct {
pub fn prompt(self: *Agent) !void {
if (main_mod.json_mode) return; // SDK drives turns; no human prompt
const w = self.out orelse return;
- const flag: []const u8 = if (self.strict and main_mod.plan_mode) " strict·plan" else if (self.strict) " strict" else if (main_mod.plan_mode) " plan" else "";
var cbuf: [40]u8 = undefined;
const cost: []const u8 = if (!main_mod.show_cost) "" else blk: {
if (std.mem.eql(u8, self.provider.id, "codex"))
@@ -143,21 +168,23 @@ pub const Agent = struct {
(std.fmt.bufPrint(&kbuf, " · ⚡{d} cached", .{self.last_cache_read}) catch "")
else
"";
+ try w.print("\n{s}[{s}{s}{s}{s}", .{ style.dim, style.reset, style.cyan, self.provider.model, style.reset });
+ if (self.effortApplies()) try writePromptBadge(w, reasoningPromptColor(self.reasoning), reasoningPromptLabel(self.reasoning));
+ if (self.fast and self.provider.kind == .responses) try writePromptBadge(w, style.green, "Fast");
+ if (main_mod.plan_mode) try writePromptBadge(w, style.yellow, "Plan");
+ if (self.strict) try writePromptBadge(w, style.red, "Strict");
+ if (self.ultracode_mode) try writePromptBadge(w, style.magenta, "Ultracode");
+ if (self.approvals) |approvals| if (approvals.yoloEnabled(self.io)) try writePromptBadge(w, style.red, "YOLO");
+ try w.print("{s} · cwd {s}{s}{s}", .{ style.dim, style.reset, main_mod.g_cwd_display, style.dim });
if (self.last_context_tokens > 0) {
const threshold = self.provider.compactAt();
// % of the compaction budget already used — glanceable headroom.
const pct = if (threshold > 0) self.last_context_tokens * 100 / threshold else 0;
- try w.print("\n{s}[{s}{s}{s}{s}{s} · cwd {s}{s}{s} · {d}/{d}k tok ({d}%){s}{s}]{s} {s}›{s} ", .{
- style.dim, style.reset, style.cyan, self.provider.model, flag, style.dim,
- style.reset, main_mod.g_cwd_display, style.dim, self.last_context_tokens, threshold / 1000, pct,
- cached, cost, style.reset, style.bold, style.reset,
+ try w.print(" · {d}/{d}k tok ({d}%){s}{s}]{s} {s}›{s} ", .{
+ self.last_context_tokens, threshold / 1000, pct, cached, cost, style.reset, style.bold, style.reset,
});
} else {
- try w.print("\n{s}[{s}{s}{s}{s}{s} · cwd {s}{s}{s}{s}]{s} {s}›{s} ", .{
- style.dim, style.reset, style.cyan, self.provider.model, flag, style.dim,
- style.reset, main_mod.g_cwd_display, style.dim, cost, style.reset, style.bold,
- style.reset,
- });
+ try w.print("{s}]{s} {s}›{s} ", .{ cost, style.reset, style.bold, style.reset });
}
try w.flush();
}
@@ -407,3 +434,12 @@ pub const Agent = struct {
pub const wrapCell = @import("agent_table.zig").wrapCell;
pub const isTableSeparator = @import("agent_table.zig").isTableSeparator;
};
+
+test "reasoning prompt label uses picker wording" {
+ try std.testing.expectEqualStrings("Low", reasoningPromptLabel(.low));
+ try std.testing.expectEqualStrings("Medium", reasoningPromptLabel(.medium));
+ try std.testing.expectEqualStrings("High", reasoningPromptLabel(.high));
+ try std.testing.expectEqualStrings("Extra high", reasoningPromptLabel(.xhigh));
+ try std.testing.expectEqualStrings("Max", reasoningPromptLabel(.max));
+ try std.testing.expectEqualStrings("Ultra", reasoningPromptLabel(.ultra));
+}
diff --git a/src/ansi.zig b/src/ansi.zig
index 53340b23..ba292aae 100644
--- a/src/ansi.zig
+++ b/src/ansi.zig
@@ -15,6 +15,7 @@ pub const Style = struct {
red: []const u8 = "",
green: []const u8 = "",
yellow: []const u8 = "",
+ magenta: []const u8 = "",
cyan: []const u8 = "",
pub const ansi: Style = .{
@@ -24,6 +25,7 @@ pub const Style = struct {
.red = "\x1b[31m",
.green = "\x1b[32m",
.yellow = "\x1b[33m",
+ .magenta = "\x1b[35m",
.cyan = "\x1b[36m",
};
};
@@ -39,6 +41,7 @@ test "Style: blank by default, ansi has escape codes" {
try std.testing.expectEqualStrings("", blank.bold);
try std.testing.expectEqualStrings("\x1b[0m", Style.ansi.reset);
try std.testing.expectEqualStrings("\x1b[1m", Style.ansi.bold);
+ try std.testing.expectEqualStrings("\x1b[35m", Style.ansi.magenta);
try std.testing.expectEqualStrings("\x1b[36m", Style.ansi.cyan);
}
diff --git a/src/approvals.zig b/src/approvals.zig
index 577c01f0..64006c9c 100644
--- a/src/approvals.zig
+++ b/src/approvals.zig
@@ -137,6 +137,12 @@ pub const Approvals = struct {
return self.yolo;
}
+ pub fn yoloEnabled(self: *Approvals, io: Io) bool {
+ self.mutex.lockUncancelable(io);
+ defer self.mutex.unlock(io);
+ return self.yolo;
+ }
+
/// No chaining, piping, redirection, or substitution — those can smuggle
/// a second command past a prefix match.
fn isSimple(cmd: []const u8) bool {
diff --git a/src/cli.zig b/src/cli.zig
index dad9bfa0..41b67056 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -21,10 +21,10 @@ const harness_version = root.harness_version;
pub const changelog_text =
\\What's new
\\──────────
- \\0.0.191
- \\ • `/effort` now opens Codex's six-level reasoning picker in the REPL
- \\ • Extra high, Max, and Ultra work through slash commands and JSON controls
- \\ • Ultra combines maximum server reasoning with automatic task delegation
+ \\0.0.192
+ \\ • The REPL prompt now shows color-coded reasoning and active mode badges
+ \\ • PTY debugging can script commands, keys, assertions, and terminal dimensions
+ \\ • Interactive prompt redraws and ANSI colors now have a real-PTY CI regression
\\
;