|
| 1 | +"""Periodic watch loop for long-running Codex work. |
| 2 | +
|
| 3 | +watch keeps a single Codex thread alive and periodically "ticks" it with the |
| 4 | +current time and a reminder of the original instructions. Each tick expects a |
| 5 | +small JSON status payload so the loop can decide whether to continue. |
| 6 | +""" |
| 7 | + |
| 8 | +import json |
| 9 | +import time |
| 10 | +from datetime import datetime |
| 11 | + |
| 12 | +from .agent import Agent |
| 13 | + |
| 14 | +_JSON_INSTRUCTIONS = ( |
| 15 | + "Respond with JSON only (no markdown/backticks/extra text).\n" |
| 16 | + "Return a single JSON object with keys:\n" |
| 17 | + " status: string (one line)\n" |
| 18 | + " continue: boolean\n" |
| 19 | + " comments: string\n" |
| 20 | + "To stop this watch loop, set continue to false." |
| 21 | +) |
| 22 | + |
| 23 | + |
| 24 | +def watch(minutes, prompt, cwd=None, yolo=True, flags=None): |
| 25 | + """Run a periodic watch loop. |
| 26 | +
|
| 27 | + Args: |
| 28 | + minutes: Tick interval in whole minutes (>= 1). |
| 29 | + prompt: The original instruction prompt. |
| 30 | + cwd: Optional working directory for the Codex session. |
| 31 | + yolo: Whether to pass --yolo to Codex. |
| 32 | + flags: Additional raw CLI flags to pass to Codex. |
| 33 | +
|
| 34 | + Returns: |
| 35 | + The last parsed JSON status object. |
| 36 | + """ |
| 37 | + if not isinstance(minutes, int): |
| 38 | + raise TypeError("minutes must be an integer") |
| 39 | + if minutes < 1: |
| 40 | + raise ValueError("minutes must be >= 1") |
| 41 | + if not isinstance(prompt, str) or not prompt.strip(): |
| 42 | + raise ValueError("prompt must be a non-empty string") |
| 43 | + |
| 44 | + interval = minutes * 60 |
| 45 | + session = Agent(cwd, yolo, None, flags) |
| 46 | + |
| 47 | + last_sent = None |
| 48 | + last_result = None |
| 49 | + tick = 0 |
| 50 | + |
| 51 | + while True: |
| 52 | + tick += 1 |
| 53 | + sent_at = time.monotonic() |
| 54 | + elapsed = None if last_sent is None else sent_at - last_sent |
| 55 | + last_sent = sent_at |
| 56 | + |
| 57 | + now = datetime.now().astimezone().isoformat(timespec="seconds") |
| 58 | + message = _build_tick_prompt(prompt, now, elapsed, tick) |
| 59 | + output = session(message) |
| 60 | + result = _parse_status(output) |
| 61 | + last_result = result |
| 62 | + _print_status(now, elapsed, tick, result) |
| 63 | + |
| 64 | + if not result["continue"]: |
| 65 | + return last_result |
| 66 | + |
| 67 | + next_tick = sent_at + interval |
| 68 | + sleep_seconds = next_tick - time.monotonic() |
| 69 | + if sleep_seconds > 0: |
| 70 | + time.sleep(sleep_seconds) |
| 71 | + |
| 72 | + |
| 73 | +def _build_tick_prompt(prompt, now, elapsed, tick): |
| 74 | + lines = [ |
| 75 | + f"Tick {tick}.", |
| 76 | + f"Local time now: {now}", |
| 77 | + ] |
| 78 | + if elapsed is not None: |
| 79 | + lines.append( |
| 80 | + "Time since last tick: " |
| 81 | + f"{_format_minutes_seconds(elapsed)} ({int(round(elapsed))}s)" |
| 82 | + ) |
| 83 | + lines.extend( |
| 84 | + [ |
| 85 | + "", |
| 86 | + "A reminder: your instructions are:", |
| 87 | + prompt.strip(), |
| 88 | + "", |
| 89 | + _JSON_INSTRUCTIONS, |
| 90 | + ] |
| 91 | + ) |
| 92 | + return "\n".join(lines).strip() |
| 93 | + |
| 94 | + |
| 95 | +def _format_minutes_seconds(seconds): |
| 96 | + if seconds is None: |
| 97 | + return "" |
| 98 | + seconds = int(round(seconds)) |
| 99 | + if seconds < 0: |
| 100 | + seconds = 0 |
| 101 | + minutes, seconds = divmod(seconds, 60) |
| 102 | + return f"{minutes}m{seconds:02d}s" |
| 103 | + |
| 104 | + |
| 105 | +def _parse_status(output): |
| 106 | + text = _maybe_strip_code_fence(str(output or "").strip()) |
| 107 | + data = _try_parse_json(text) |
| 108 | + if data is None: |
| 109 | + snippet = text[:200].replace("\n", "\\n") |
| 110 | + raise ValueError(f"Invalid JSON response. Snippet: {snippet}") |
| 111 | + if not isinstance(data, dict): |
| 112 | + raise ValueError("Status JSON must be an object.") |
| 113 | + |
| 114 | + status = data.get("status") |
| 115 | + cont = data.get("continue") |
| 116 | + comments = data.get("comments") |
| 117 | + |
| 118 | + if not isinstance(status, str): |
| 119 | + raise ValueError("Status JSON missing string 'status'.") |
| 120 | + if not isinstance(cont, bool): |
| 121 | + raise ValueError("Status JSON missing boolean 'continue'.") |
| 122 | + if comments is None: |
| 123 | + comments = "" |
| 124 | + if not isinstance(comments, str): |
| 125 | + raise ValueError("Status JSON missing string 'comments'.") |
| 126 | + |
| 127 | + return { |
| 128 | + "status": _single_line(status), |
| 129 | + "continue": cont, |
| 130 | + "comments": comments, |
| 131 | + } |
| 132 | + |
| 133 | + |
| 134 | +def _maybe_strip_code_fence(text): |
| 135 | + if not text.startswith("```"): |
| 136 | + return text |
| 137 | + lines = text.splitlines() |
| 138 | + if not lines: |
| 139 | + return text |
| 140 | + if lines[0].startswith("```"): |
| 141 | + lines = lines[1:] |
| 142 | + if lines and lines[-1].strip() == "```": |
| 143 | + lines = lines[:-1] |
| 144 | + return "\n".join(lines).strip() |
| 145 | + |
| 146 | + |
| 147 | +def _try_parse_json(text): |
| 148 | + if not text: |
| 149 | + return None |
| 150 | + try: |
| 151 | + return json.loads(text) |
| 152 | + except json.JSONDecodeError: |
| 153 | + pass |
| 154 | + |
| 155 | + start = text.find("{") |
| 156 | + end = text.rfind("}") |
| 157 | + if start == -1 or end == -1 or end <= start: |
| 158 | + return None |
| 159 | + try: |
| 160 | + return json.loads(text[start : end + 1]) |
| 161 | + except json.JSONDecodeError: |
| 162 | + return None |
| 163 | + |
| 164 | + |
| 165 | +def _single_line(text): |
| 166 | + return " ".join(text.replace("\r", " ").split()) |
| 167 | + |
| 168 | + |
| 169 | +def _print_status(now, elapsed, tick, result): |
| 170 | + delta = "" |
| 171 | + if elapsed is not None: |
| 172 | + delta = f" +{_format_minutes_seconds(elapsed)}" |
| 173 | + status = result.get("status", "") |
| 174 | + cont = result.get("continue") |
| 175 | + line = f"[watch {tick} {now}{delta}] {status} (continue={cont})".rstrip() |
| 176 | + print(line) |
| 177 | + comments = result.get("comments") or "" |
| 178 | + if comments.strip(): |
| 179 | + print(comments.rstrip()) |
| 180 | + |
0 commit comments