Repository navigation
Expand file tree
/
Copy pathfx-goal
More file actions
executable file
·386 lines (343 loc) · 15.4 KB
/
Copy pathfx-goal
File metadata and controls
executable file
·386 lines (343 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
#!/usr/bin/env python3
"""Continue an explicitly marked fx goal in its Ghostty terminal."""
import argparse
import fcntl
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
import time
ROOT = Path(os.environ.get("FX_GOAL_HOME", Path.home() / ".local/state/ghostty-fx-goal"))
MARKER = "[[FX_GOAL_CONTINUE]]"
FOLLOWUP = ("Continue the active goal. Read its current status with fx-goal status. "
"If further work can proceed without user input, end with [[FX_GOAL_CONTINUE]]. "
"If the goal is complete, call fx-goal complete. If blocked or awaiting the user, "
"call fx-goal pause and explain why.")
TERMINALS = r'''function run(argv) {
const app = Application('Ghostty'), tty = argv[0], result = [];
for (const w of app.windows()) for (const tab of w.tabs()) {
const ts = tab.terminals();
for (const t of ts) if (t.tty() === tty)
result.push({id:t.id(), tty:t.tty(), title:w.name(), window:w.id(),
selected:tab.selected(), pane_count:ts.length});
}
return JSON.stringify(result);
}'''
PASTE = '''on run argv
tell application id "com.mitchellh.ghostty"
set t to terminal id (item 1 of argv)
input text (item 2 of argv) to t
end tell
end run'''
ENTER = '''on run argv
tell application id "com.mitchellh.ghostty" to send key "enter" to terminal id (item 1 of argv)
end run'''
def run(args, timeout=8):
p = subprocess.run(args, text=True, capture_output=True, timeout=timeout)
if p.returncode:
raise RuntimeError(f"{args[0]} failed: {p.stderr.strip()[:300]}")
return p.stdout.strip()
def live():
return json.loads(run(["fx", "sessions", "--live", "--all", "--json"]))["sessions"]
def ancestors(pid):
seen = set()
while pid > 1 and pid not in seen:
seen.add(pid)
yield pid
try:
pid = int(run(["ps", "-p", str(pid), "-o", "ppid="]).strip())
except (ValueError, RuntimeError):
return
def choose_session(requested=None):
sessions = live()
if requested:
matches = [s for s in sessions if s["id"] == requested]
else:
chain = set(ancestors(os.getppid()))
matches = [s for s in sessions if s.get("pid") in chain]
if len(matches) != 1:
raise RuntimeError("Could not identify exactly one live fx session. Supply --session ID.")
return matches[0]
def tty_of(pid):
tty = run(["ps", "-p", str(pid), "-o", "tty="])
if not re.fullmatch(r"ttys\d+", tty):
raise RuntimeError("The fx process has no local macOS terminal.")
return "/dev/" + tty
def is_foreground(pid):
fields = run(["ps", "-p", str(pid), "-o", "stat=,pgid=,tpgid="]).split()
return len(fields) == 3 and not fields[0].startswith("T") and fields[1] == fields[2]
def terminal_for(tty):
values = json.loads(run(["osascript", "-l", "JavaScript", "-e", TERMINALS, "--", tty]))
if len(values) != 1:
raise RuntimeError("Could not match exactly one Ghostty terminal to the fx TTY.")
return values[0]
def screen(terminal):
candidates = []
expected_id = terminal["id"]
for _ in range(3):
terminal = terminal_for(terminal["tty"])
if terminal["id"] != expected_id:
raise RuntimeError("Terminal identity changed.")
if not terminal["selected"] or terminal["pane_count"] != 1:
raise RuntimeError("Select the target tab; split panes are not supported.")
listing = json.loads(run(["agent-desktop", "list-windows", "--app", "Ghostty"]))
candidates = [w for w in listing["data"] if w.get("title") == terminal["title"]]
if len(candidates) == 1:
break
time.sleep(0.2)
result = None
if not candidates:
matches = []
for window in listing["data"]:
if not window.get("visible") or window.get("minimized"):
continue
snapshot = json.loads(run(["agent-desktop", "snapshot", "--app", "Ghostty", "--window-id", window["id"], "--compact"]))
if not snapshot.get("ok") or not snapshot["data"].get("complete"):
raise RuntimeError("Could not identify all visible Ghostty windows.")
if snapshot["data"]["tree"].get("name") == terminal["title"]:
matches.append((window, snapshot))
if len(matches) == 1:
candidates, result = [matches[0][0]], matches[0][1]
if len(candidates) != 1 or candidates[0].get("minimized") or not candidates[0].get("visible"):
raise RuntimeError("The target window is hidden, minimized, or ambiguous.")
if result is None:
result = json.loads(run(["agent-desktop", "snapshot", "--app", "Ghostty", "--window-id", candidates[0]["id"], "--compact"]))
if not result.get("ok") or not result["data"].get("complete"):
raise RuntimeError("Could not read the complete Ghostty accessibility tree.")
values = []
def walk(node):
if node.get("role") == "textfield" and "value" in node:
values.append(node["value"])
for child in node.get("children", []):
walk(child)
walk(result["data"]["tree"])
if len(values) != 1:
raise RuntimeError("Could not identify one terminal screen.")
current = terminal_for(terminal["tty"])
if current != terminal or result["data"]["tree"].get("name") != terminal["title"]:
raise RuntimeError("Terminal changed while its screen was read.")
return values[0]
def prompt_is_empty(text):
# shortcut: matches fx 0.0.18's English footer, update after fx changes its layout.
return bool(re.search(r"(?:^|\n)┃[ \t]*\n[ \t]*\n(?:ask|auto|full access) ·[^\n]*\s*$", text))
def prompt_matches(text, expected):
footer = re.search(r"\n(?:ask|auto|full access) ·[^\n]*\s*$", text)
if not footer:
return False
lines = text[:footer.start()].splitlines()
while lines and not lines[-1].strip():
lines.pop()
parts = []
while lines and lines[-1].startswith("┃"):
parts.append(lines.pop()[1:].strip())
return " ".join(" ".join(reversed(parts)).split()) == " ".join(expected.split())
def latest(session):
data = json.loads(run(["fx", "session", session, "--tail", "1", "--json"]))
history = data.get("history", [])
if not history or history[-1].get("kind") != "assistant":
return None
text = history[-1].get("assistant") or ""
if not text.rstrip().endswith(MARKER):
return None
return hashlib.sha256(json.dumps(history[-1], sort_keys=True, ensure_ascii=False).encode()).hexdigest()
def delivery_observed(session, pid):
for _ in range(12):
time.sleep(0.5)
matches = [s for s in live() if s["id"] == session and s.get("pid") == pid]
if len(matches) != 1:
return False
if matches[0]["state"] == "working":
return True
history = json.loads(run(["fx", "session", session, "--tail", "1", "--json"])).get("history", [])
if history and (history[-1].get("user") or {}).get("text") == FOLLOWUP:
return True
return False
def state_path(session):
if not re.fullmatch(r"[A-Za-z0-9_-]{1,100}", session):
raise RuntimeError("Invalid fx session ID.")
return ROOT / (session + ".json")
def lock(session):
ROOT.mkdir(parents=True, exist_ok=True, mode=0o700)
path = ROOT / (session + ".lock")
f = open(path, "a+")
os.chmod(path, 0o600)
fcntl.flock(f, fcntl.LOCK_EX)
return f
def read_state(session):
try:
return json.loads(state_path(session).read_text())
except FileNotFoundError:
raise RuntimeError("No goal is set for this session.") from None
def write_state(data):
path = state_path(data["session"])
fd, name = tempfile.mkstemp(prefix=".goal-", dir=ROOT)
try:
with os.fdopen(fd, "w") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
f.write("\n")
f.flush()
os.fsync(f.fileno())
os.replace(name, path)
finally:
if os.path.exists(name):
os.unlink(name)
def worker(session):
state_path(session)
ROOT.mkdir(parents=True, exist_ok=True, mode=0o700)
with open(ROOT / (session + ".worker.lock"), "a+") as held:
try:
fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return
stable = None
while True:
time.sleep(2)
try:
with lock(session):
data = read_state(session)
if data["status"] in ("complete", "cleared"):
return
if data["status"] != "active":
stable = None
continue
sessions = [s for s in live() if s["id"] == session and s.get("pid") == data["fx_pid"]]
if len(sessions) != 1:
raise RuntimeError("The original fx session is no longer live; resume manually.")
if sessions[0]["state"] != "idle":
stable = None
continue
digest = latest(session)
if not digest or digest == data.get("last_sent"):
stable = None
continue
if digest != stable:
stable = digest
continue
with lock(session):
data = read_state(session)
if data["status"] != "active" or data.get("last_sent") == digest:
continue
current = [s for s in live() if s["id"] == session and s.get("pid") == data["fx_pid"]]
if len(current) != 1 or current[0]["state"] != "idle" or latest(session) != digest:
stable = None
continue
if not is_foreground(data["fx_pid"]):
raise RuntimeError("The fx process is not the foreground terminal job.")
terminal = terminal_for(tty_of(data["fx_pid"]))
if terminal["id"] != data["terminal_id"] or not prompt_is_empty(screen(terminal)):
raise RuntimeError("Target terminal changed or its prompt is not empty.")
# Record before delivery: an uncertain write must never be retried blindly.
data["last_sent"] = digest
data["deliveries"] += 1
write_state(data)
run(["osascript", "-e", PASTE, terminal["id"], FOLLOWUP])
if not prompt_matches(screen(terminal), FOLLOWUP):
raise RuntimeError("Pasted input differs from expected; Enter was not sent.")
current = [s for s in live() if s["id"] == session and s.get("pid") == data["fx_pid"]]
if len(current) != 1 or current[0]["state"] != "idle":
raise RuntimeError("Session changed after paste; Enter was not sent.")
run(["osascript", "-e", ENTER, terminal["id"]])
if not delivery_observed(session, data["fx_pid"]):
raise RuntimeError("Input delivery could not be confirmed; inspect the terminal before resuming.")
stable = None
except Exception as exc:
try:
with lock(session):
data = read_state(session)
if data["status"] == "active":
data["status"] = "paused"
data["reason"] = str(exc)[:300]
write_state(data)
except Exception:
return
stable = None
def spawn(session):
subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "_watch", session],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True, close_fds=True)
def watcher_running(session):
path = ROOT / (session + ".worker.lock")
if not path.exists():
return False
with open(path) as f:
try:
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return True
fcntl.flock(f, fcntl.LOCK_UN)
return False
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--session", help="Exact live fx session ID; otherwise identify the calling fx process")
commands = parser.add_subparsers(dest="action", required=True)
start = commands.add_parser("start")
start.add_argument("objective")
for name in ("status", "pause", "resume", "clear", "complete"):
commands.add_parser(name)
watch = commands.add_parser("_watch", help=argparse.SUPPRESS)
watch.add_argument("watch_session")
args = parser.parse_args()
if args.action == "_watch":
return worker(args.watch_session)
session = None
if args.session and args.action in ("status", "pause", "clear"):
sid = args.session
else:
session = choose_session(args.session)
sid = session["id"]
state_path(sid)
with lock(sid):
if args.action == "start":
objective = args.objective.strip()
if not objective:
raise RuntimeError("Objective cannot be empty.")
try:
previous = read_state(sid)
except RuntimeError:
previous = None
if previous and previous["status"] not in ("complete", "cleared"):
raise RuntimeError("This session already has a goal; clear it first.")
tty = tty_of(session["pid"])
terminal = terminal_for(tty)
data = {"session": sid, "fx_pid": session["pid"], "terminal_id": terminal["id"],
"objective": objective, "status": "active", "reason": "", "deliveries": 0,
"last_sent": latest(sid)}
else:
data = read_state(sid)
if args.action == "pause":
if data["status"] != "active":
raise RuntimeError("Only an active goal can be paused.")
data.update(status="paused", reason="Paused by user or agent.")
elif args.action == "resume":
if data["status"] != "paused":
raise RuntimeError("Only a paused goal can be resumed.")
if data["fx_pid"] != session["pid"]:
data["fx_pid"] = session["pid"]
data["terminal_id"] = terminal_for(tty_of(session["pid"]))["id"]
data.update(status="active", reason="")
elif args.action == "clear":
data.update(status="cleared", reason="")
elif args.action == "complete":
if data["status"] not in ("active", "paused"):
raise RuntimeError("Only an active or paused goal can be completed.")
data.update(status="complete", reason="")
if args.action == "clear":
state_path(sid).unlink()
elif args.action != "status":
write_state(data)
if args.action in ("start", "resume"):
spawn(sid)
if args.action == "status":
data["watcher_running"] = watcher_running(sid)
print(json.dumps(data, ensure_ascii=False))
if __name__ == "__main__":
try:
main()
except (RuntimeError, OSError, ValueError, KeyError, subprocess.TimeoutExpired) as exc:
print(f"fx-goal: {exc}", file=sys.stderr)
sys.exit(1)