fleetdeck 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. fleetdeck/__init__.py +3 -0
  2. fleetdeck/__main__.py +232 -0
  3. fleetdeck/accounts.py +115 -0
  4. fleetdeck/adapters/__init__.py +0 -0
  5. fleetdeck/adapters/base.py +71 -0
  6. fleetdeck/adapters/claude_cli.py +187 -0
  7. fleetdeck/adapters/codex_cli.py +362 -0
  8. fleetdeck/adapters/demo.py +331 -0
  9. fleetdeck/config.py +323 -0
  10. fleetdeck/db.py +511 -0
  11. fleetdeck/gitinfo.py +169 -0
  12. fleetdeck/models.py +178 -0
  13. fleetdeck/paths.py +64 -0
  14. fleetdeck/proc.py +92 -0
  15. fleetdeck/redact.py +51 -0
  16. fleetdeck/services/__init__.py +0 -0
  17. fleetdeck/services/dispatcher.py +382 -0
  18. fleetdeck/services/fleet.py +65 -0
  19. fleetdeck/services/monitor.py +253 -0
  20. fleetdeck/services/notifier.py +71 -0
  21. fleetdeck/status.py +97 -0
  22. fleetdeck/terminal.py +235 -0
  23. fleetdeck/termrender.py +129 -0
  24. fleetdeck/ui/__init__.py +0 -0
  25. fleetdeck/ui/app.py +1295 -0
  26. fleetdeck/ui/app.tcss +263 -0
  27. fleetdeck/ui/commands.py +63 -0
  28. fleetdeck/ui/screens/__init__.py +0 -0
  29. fleetdeck/ui/screens/modals.py +623 -0
  30. fleetdeck/ui/style.py +150 -0
  31. fleetdeck/ui/views.py +230 -0
  32. fleetdeck/ui/widgets/__init__.py +0 -0
  33. fleetdeck/ui/widgets/agent_table.py +185 -0
  34. fleetdeck/ui/widgets/bottom.py +27 -0
  35. fleetdeck/ui/widgets/details.py +295 -0
  36. fleetdeck/ui/widgets/header.py +87 -0
  37. fleetdeck/ui/widgets/sidebar.py +227 -0
  38. fleetdeck/ui/widgets/splitter.py +66 -0
  39. fleetdeck/ui/widgets/terminal.py +119 -0
  40. fleetdeck-0.3.0.dist-info/METADATA +245 -0
  41. fleetdeck-0.3.0.dist-info/RECORD +44 -0
  42. fleetdeck-0.3.0.dist-info/WHEEL +4 -0
  43. fleetdeck-0.3.0.dist-info/entry_points.txt +2 -0
  44. fleetdeck-0.3.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,362 @@
1
+ """Adapter for OpenAI Codex CLI (ChatGPT sign-in), verified on codex-cli 0.155.
2
+
3
+ Codex has no machine-readable session list (`codex agents` is interactive), so
4
+ FleetDeck manages the runs it starts itself:
5
+
6
+ launch codex exec --json --skip-git-repo-check -s <sandbox> [-m M] <prompt>
7
+ follow-up codex exec --json --skip-git-repo-check -s <sandbox> resume <thread> <prompt>
8
+ attach codex resume <thread> (interactive, TUI suspended)
9
+ stop SIGTERM to the run's process group
10
+
11
+ Each run is a detached process (own session, stdin = /dev/null; with an open
12
+ stdin `codex exec` waits to read it) whose JSONL events go to a log file, so
13
+ runs survive the dashboard exiting. Status comes only from the observed events:
14
+ thread.started{thread_id}, turn.started, item.started/completed{item},
15
+ turn.completed{usage}, turn.failed / error.
16
+
17
+ Never passed: --dangerously-bypass-approvals-and-sandbox, --approve-for-me,
18
+ -s danger-full-access. Non-interactive Codex cannot ask for approval, so the
19
+ sandbox (read-only / workspace-write) is what bounds it.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import os
26
+ import re
27
+ import secrets
28
+ import signal
29
+ import subprocess
30
+ import time
31
+ from dataclasses import dataclass, field
32
+ from pathlib import Path
33
+ from typing import Any
34
+
35
+ from ..db import Store
36
+ from ..proc import CommandNotFound, run
37
+ from .base import CommandResult, LaunchSpec
38
+
39
+ FORBIDDEN = ("--dangerously-bypass-approvals-and-sandbox", "--approve-for-me",
40
+ "danger-full-access", "--dangerously-bypass-hook-trust")
41
+ _THREAD = re.compile(r"^[0-9a-fA-F-]{8,64}$")
42
+
43
+
44
+ def sandbox_for(permission_mode: str | None) -> str:
45
+ """Plan mode → read-only; everything else → workspace-write (never full access)."""
46
+ return "read-only" if permission_mode == "plan" else "workspace-write"
47
+
48
+
49
+ def _safe_prompt(prompt: str) -> str:
50
+ prompt = prompt.strip()
51
+ return "Task: " + prompt if prompt.startswith("-") else prompt
52
+
53
+
54
+ def build_exec_argv(binary: str, prompt: str, *, sandbox: str, model: str | None = None,
55
+ resume_thread: str | None = None) -> list[str]:
56
+ if sandbox not in ("read-only", "workspace-write"):
57
+ raise ValueError(f"sandbox {sandbox!r} is not allowed")
58
+ argv = [binary, "exec", "--json", "--skip-git-repo-check", "-s", sandbox]
59
+ if model:
60
+ argv += ["-m", model]
61
+ if resume_thread:
62
+ if not _THREAD.match(resume_thread):
63
+ raise ValueError(f"not a Codex session id: {resume_thread!r}")
64
+ argv += ["resume", resume_thread]
65
+ argv.append(_safe_prompt(prompt))
66
+ if any(f in argv[:-1] for f in FORBIDDEN):
67
+ raise ValueError("approval/sandbox bypass flags are never passed by FleetDeck")
68
+ return argv
69
+
70
+
71
+ # ------------------------------------------------------------------ events
72
+ @dataclass
73
+ class RunState:
74
+ """What a run's event log says so far (parsed incrementally)."""
75
+
76
+ offset: int = 0
77
+ thread_id: str | None = None
78
+ turns_started: int = 0
79
+ turns_completed: int = 0
80
+ failed: bool = False
81
+ last_error: str | None = None
82
+ usage: dict[str, int] | None = None
83
+ last_event_at: float | None = None
84
+ running_command: str | None = None
85
+
86
+
87
+ def parse_events(path: Path, st: RunState) -> RunState:
88
+ try:
89
+ with open(path, "rb") as f:
90
+ f.seek(st.offset)
91
+ chunk = f.read()
92
+ except FileNotFoundError:
93
+ return st
94
+ end = chunk.rfind(b"\n")
95
+ if end < 0:
96
+ return st # only a partially written line so far: read it next time
97
+ complete = chunk[:end]
98
+ st.offset += end + 1
99
+ for line in complete.splitlines():
100
+ try:
101
+ ev = json.loads(line)
102
+ except (json.JSONDecodeError, UnicodeDecodeError):
103
+ continue
104
+ st.last_event_at = time.time()
105
+ t = ev.get("type")
106
+ if t == "thread.started":
107
+ st.thread_id = ev.get("thread_id") or st.thread_id
108
+ elif t == "turn.started":
109
+ st.turns_started += 1
110
+ st.failed = False
111
+ elif t == "turn.completed":
112
+ st.turns_completed += 1
113
+ if isinstance(ev.get("usage"), dict):
114
+ st.usage = {k: v for k, v in ev["usage"].items() if isinstance(v, int)}
115
+ elif t in ("turn.failed", "error"):
116
+ st.failed = True
117
+ err = ev.get("error") or ev.get("message")
118
+ st.last_error = (err.get("message") if isinstance(err, dict) else err) or t
119
+ elif t in ("item.started", "item.completed"):
120
+ item = ev.get("item") or {}
121
+ if item.get("type") == "command_execution":
122
+ st.running_command = item.get("command") if t == "item.started" else None
123
+ return st
124
+
125
+
126
+ def render_log(path: Path, prompt: str | None) -> str:
127
+ """Human-readable transcript of one run's JSONL events."""
128
+ out: list[str] = []
129
+ if prompt:
130
+ out.append(f"❯ {prompt}")
131
+ try:
132
+ lines = path.read_bytes().splitlines()
133
+ except FileNotFoundError:
134
+ return "\n".join(out + ["(no output yet)"])
135
+ for raw in lines:
136
+ try:
137
+ ev = json.loads(raw)
138
+ except (json.JSONDecodeError, UnicodeDecodeError):
139
+ continue
140
+ t = ev.get("type")
141
+ if t == "thread.started":
142
+ out.append(f"· session {ev.get('thread_id', '')}")
143
+ elif t == "item.completed":
144
+ item = ev.get("item") or {}
145
+ kind = item.get("type")
146
+ if kind == "agent_message":
147
+ out.append(f"⏺ {item.get('text', '')}")
148
+ elif kind == "command_execution":
149
+ code = item.get("exit_code")
150
+ out.append(f"$ {item.get('command', '')}" + (f" (exit {code})" if code else ""))
151
+ body = (item.get("aggregated_output") or "").rstrip()
152
+ if body:
153
+ tail = body.splitlines()[-12:]
154
+ out.extend(" " + ln for ln in tail)
155
+ elif kind == "error":
156
+ out.append(f"⚠ {item.get('message', '')}")
157
+ elif kind == "reasoning":
158
+ continue
159
+ else:
160
+ summary = item.get("path") or item.get("text") or ""
161
+ out.append(f"· {kind} {summary}".rstrip())
162
+ elif t == "turn.completed":
163
+ u = ev.get("usage") or {}
164
+ out.append(f"✓ turn done · {u.get('input_tokens', 0):,} in / "
165
+ f"{u.get('output_tokens', 0):,} out tokens")
166
+ elif t in ("turn.failed", "error"):
167
+ err = ev.get("error") or ev.get("message") or t
168
+ out.append(f"✗ {err.get('message') if isinstance(err, dict) else err}")
169
+ return "\n".join(out)
170
+
171
+
172
+ # ------------------------------------------------------------------ backend
173
+ @dataclass
174
+ class _Live:
175
+ proc: subprocess.Popen
176
+ started: float = field(default_factory=time.time)
177
+
178
+
179
+ class CodexBackend:
180
+ """One instance per Codex account (CODEX_HOME)."""
181
+
182
+ name = "codex"
183
+ is_demo = False
184
+ provider = "codex"
185
+
186
+ def __init__(self, store: Store, account: str, runs_dir: Path,
187
+ binary: str = "codex") -> None:
188
+ self.store = store
189
+ self.account = account
190
+ self.runs_dir = runs_dir
191
+ self.binary = binary
192
+ self._live: dict[str, _Live] = {} # runs started by this process (we reap them)
193
+ self._states: dict[str, RunState] = {}
194
+ self._version: str | None = None
195
+
196
+ # ---------------------------------------------------------- helpers
197
+ def _alive(self, run_id: str, pid: int | None) -> bool:
198
+ live = self._live.get(run_id)
199
+ if live is not None:
200
+ return live.proc.poll() is None # also reaps
201
+ if not pid:
202
+ return False
203
+ try:
204
+ os.kill(pid, 0)
205
+ except ProcessLookupError:
206
+ return False
207
+ except PermissionError:
208
+ return True
209
+ return True
210
+
211
+ def _state(self, row) -> RunState:
212
+ st = self._states.setdefault(row["id"], RunState(thread_id=row["thread_id"]))
213
+ parse_events(Path(row["log_path"]), st)
214
+ if st.thread_id and st.thread_id != row["thread_id"]:
215
+ self.store.update_codex_run(row["id"], thread_id=st.thread_id)
216
+ return st
217
+
218
+ def _spawn(self, argv: list[str], cwd: str, env: dict[str, str],
219
+ run_id: str) -> subprocess.Popen:
220
+ self.runs_dir.mkdir(parents=True, exist_ok=True)
221
+ log = self.runs_dir / f"{run_id}.jsonl"
222
+ err = self.runs_dir / f"{run_id}.err"
223
+ with open(log, "ab") as out, open(err, "ab") as errf:
224
+ proc = subprocess.Popen(
225
+ argv, cwd=cwd, env={**os.environ, **env},
226
+ stdin=subprocess.DEVNULL, # an open stdin makes `codex exec` wait for it
227
+ stdout=out, stderr=errf,
228
+ start_new_session=True, # survives the dashboard; own process group
229
+ )
230
+ for p in (log, err):
231
+ try:
232
+ os.chmod(p, 0o600)
233
+ except OSError:
234
+ pass
235
+ self._live[run_id] = _Live(proc)
236
+ return proc
237
+
238
+ # ---------------------------------------------------------- backend
239
+ async def version(self) -> str | None:
240
+ if self._version is None:
241
+ try:
242
+ code, out, _ = await run([self.binary, "--version"], timeout=10)
243
+ except CommandNotFound:
244
+ return None
245
+ self._version = out.strip().split()[-1] if code == 0 and out.strip() else None
246
+ return self._version
247
+
248
+ async def list_sessions(self, env: dict[str, str]) -> list[dict[str, Any]]:
249
+ records = []
250
+ for row in self.store.codex_runs(self.account):
251
+ st = self._state(row)
252
+ alive = self._alive(row["id"], row["pid"])
253
+ if row["stopped"]:
254
+ state = "stopped"
255
+ elif alive:
256
+ state = "working"
257
+ elif st.turns_completed and st.turns_completed >= st.turns_started and not st.failed:
258
+ state = "done"
259
+ else:
260
+ state = "failed"
261
+ rec: dict[str, Any] = {
262
+ "id": row["id"], "kind": "background", "cwd": row["cwd"],
263
+ "startedAt": int(row["started_at"] * 1000),
264
+ "sessionId": st.thread_id, "name": row["name"] or row["id"],
265
+ "state": state, "provider": "codex", "usage": st.usage,
266
+ }
267
+ if alive:
268
+ rec["pid"] = row["pid"]
269
+ rec["status"] = "busy"
270
+ records.append(rec)
271
+ return records
272
+
273
+ async def launch(self, spec: LaunchSpec) -> CommandResult:
274
+ prompt = spec.prompt
275
+ if spec.append_system_prompt: # Codex has no flag for this: prepend, visibly
276
+ prompt = f"Project instructions:\n{spec.append_system_prompt}\n\nTask:\n{prompt}"
277
+ sandbox = sandbox_for(spec.permission_mode)
278
+ try:
279
+ argv = build_exec_argv(self.binary, prompt, sandbox=sandbox, model=spec.model)
280
+ except ValueError as exc:
281
+ return CommandResult(False, str(exc))
282
+ run_id = secrets.token_hex(4)
283
+ try:
284
+ proc = self._spawn(argv, spec.cwd, spec.env, run_id)
285
+ except FileNotFoundError:
286
+ return CommandResult(False, f"Codex CLI not found ({self.binary!r})")
287
+ except OSError as exc:
288
+ return CommandResult(False, f"could not start codex: {exc}")
289
+ self.store.add_codex_run(run_id, account=self.account, name=spec.name, cwd=spec.cwd,
290
+ log_path=str(self.runs_dir / f"{run_id}.jsonl"),
291
+ pid=proc.pid, prompt=spec.prompt, model=spec.model,
292
+ sandbox=sandbox)
293
+ return CommandResult(True, f"started codex run {run_id} (sandbox {sandbox})", run_id)
294
+
295
+ async def follow_up(self, session_id: str, prompt: str, *, cwd: str,
296
+ env: dict[str, str]) -> CommandResult:
297
+ runs = self.store.codex_runs(self.account, include_hidden=True, thread_id=session_id)
298
+ if not runs:
299
+ return CommandResult(False, f"no FleetDeck run for Codex session {session_id}")
300
+ last = runs[-1]
301
+ if self._alive(last["id"], last["pid"]):
302
+ return CommandResult(False, "that Codex run is still working")
303
+ try:
304
+ argv = build_exec_argv(self.binary, prompt, sandbox=last["sandbox"],
305
+ model=last["model"], resume_thread=session_id)
306
+ except ValueError as exc:
307
+ return CommandResult(False, str(exc))
308
+ run_id = secrets.token_hex(4)
309
+ try:
310
+ proc = self._spawn(argv, cwd or last["cwd"], env, run_id)
311
+ except OSError as exc:
312
+ return CommandResult(False, f"could not start codex: {exc}")
313
+ self.store.add_codex_run(run_id, account=self.account, name=last["name"],
314
+ cwd=cwd or last["cwd"],
315
+ log_path=str(self.runs_dir / f"{run_id}.jsonl"),
316
+ pid=proc.pid, prompt=prompt, model=last["model"],
317
+ sandbox=last["sandbox"], thread_id=session_id)
318
+ for r in runs: # one row per conversation: the newest run represents it
319
+ self.store.update_codex_run(r["id"], hidden=1)
320
+ return CommandResult(True, f"resumed Codex session in run {run_id}", run_id)
321
+
322
+ async def logs(self, agent_id: str, env: dict[str, str]) -> CommandResult:
323
+ row = self.store.get_codex_run(agent_id)
324
+ if row is None:
325
+ return CommandResult(False, f"No Codex run {agent_id!r}")
326
+ thread = row["thread_id"] or self._state(row).thread_id
327
+ rows = (self.store.codex_runs(self.account, include_hidden=True, thread_id=thread)
328
+ if thread else [row])
329
+ parts = [render_log(Path(r["log_path"]), r["prompt"]) for r in rows]
330
+ return CommandResult(True, "\n\n".join(parts))
331
+
332
+ async def stop(self, agent_id: str, env: dict[str, str]) -> CommandResult:
333
+ row = self.store.get_codex_run(agent_id)
334
+ if row is None:
335
+ return CommandResult(False, f"No Codex run {agent_id!r}")
336
+ if self._alive(agent_id, row["pid"]) and row["pid"]:
337
+ try:
338
+ os.killpg(row["pid"], signal.SIGTERM)
339
+ except (ProcessLookupError, PermissionError):
340
+ pass
341
+ self.store.update_codex_run(agent_id, stopped=1)
342
+ return CommandResult(True, f"stopped codex run {agent_id}")
343
+
344
+ async def respawn(self, agent_id: str, env: dict[str, str]) -> CommandResult:
345
+ return CommandResult(False, "Codex runs can't be respawned; send a follow-up (m) "
346
+ "to continue the conversation")
347
+
348
+ async def remove(self, agent_id: str, env: dict[str, str]) -> CommandResult:
349
+ row = self.store.get_codex_run(agent_id)
350
+ if row is None:
351
+ return CommandResult(False, f"No Codex run {agent_id!r}")
352
+ if self._alive(agent_id, row["pid"]):
353
+ return CommandResult(False, "stop the run first (s)")
354
+ self.store.update_codex_run(agent_id, hidden=1) # Codex's own session files stay
355
+ return CommandResult(True, f"removed codex run {agent_id} from the list")
356
+
357
+ def attach_argv(self, agent_id: str) -> list[str] | None:
358
+ row = self.store.get_codex_run(agent_id)
359
+ thread = row["thread_id"] if row is not None else None
360
+ if not thread or not _THREAD.match(thread):
361
+ return None
362
+ return [self.binary, "resume", thread]