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
fleetdeck/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """FleetDeck: mission control for Claude Code and Codex agents."""
2
+
3
+ __version__ = "0.3.0"
fleetdeck/__main__.py ADDED
@@ -0,0 +1,232 @@
1
+ """`fleetdeck` entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import os
8
+ import shutil
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ from . import __version__, paths
13
+ from .config import Settings, load_settings, save_settings
14
+
15
+
16
+ def _parser() -> argparse.ArgumentParser:
17
+ p = argparse.ArgumentParser(
18
+ prog="fleetdeck",
19
+ description="Multi-project terminal command center for Claude Code agents.",
20
+ )
21
+ p.add_argument("--demo", action="store_true",
22
+ help="run with simulated agents (no Claude Code calls)")
23
+ p.add_argument("--config", type=Path, help="path to config.yaml")
24
+ p.add_argument("--version", action="version", version=f"fleetdeck {__version__}")
25
+ sub = p.add_subparsers(dest="cmd")
26
+ sub.add_parser("doctor", help="check the environment and Claude Code CLI")
27
+ sub.add_parser("init-config", help="write a default config.yaml if none exists")
28
+ acc = sub.add_parser("accounts", help="list Claude / Codex accounts and their login state")
29
+ acc.add_argument("--discover", action="store_true",
30
+ help="also look for ~/.claude-* and ~/.codex-* folders")
31
+ acc.add_argument("--save", action="store_true",
32
+ help="with --discover: add signed-in accounts to config.yaml")
33
+ ap = sub.add_parser("add-project", help="register a project directory")
34
+ ap.add_argument("path")
35
+ ap.add_argument("--name")
36
+ ap.add_argument("--group", choices=["office", "personal"], default="personal")
37
+ ap.add_argument("--test-command", default="")
38
+ return p
39
+
40
+
41
+ def _doctor(config: Path) -> int:
42
+ from .adapters.base import BackendError
43
+ from .adapters.claude_cli import ClaudeCLIBackend
44
+
45
+ settings = load_settings(config)
46
+ ok = True
47
+
48
+ def line(good: bool, label: str, detail: str = "") -> None:
49
+ nonlocal ok
50
+ ok &= good
51
+ print(f" {'✓' if good else '✗'} {label}" + (f" — {detail}" if detail else ""))
52
+
53
+ print(f"fleetdeck {__version__}")
54
+ line(sys.version_info >= (3, 12), "Python ≥ 3.12", sys.version.split()[0])
55
+ line(True, "config", str(config) + ("" if config.exists()
56
+ else " (not created; defaults)"))
57
+ for err in settings.load_errors:
58
+ line(False, "config error", err)
59
+ line(shutil.which("git") is not None, "git on PATH", shutil.which("git") or "missing")
60
+ binary = shutil.which(settings.claude_binary)
61
+ line(binary is not None, "Claude Code CLI", binary or f"{settings.claude_binary!r} not found")
62
+ if binary:
63
+ be = ClaudeCLIBackend(settings.claude_binary, settings.command_timeout)
64
+
65
+ async def probe() -> None:
66
+ v = await be.version()
67
+ line(v is not None, "claude --version", v or "failed")
68
+ for name in sorted(settings.environments):
69
+ env = settings.env_for(name)
70
+ try:
71
+ sessions = await be.list_sessions(env)
72
+ bg = sum(1 for s in sessions if s.get("kind") == "background")
73
+ line(True, f"claude agents --json --all [{name}]",
74
+ f"{len(sessions)} sessions ({bg} background)")
75
+ except BackendError as exc:
76
+ line(False, f"claude agents --json --all [{name}]", str(exc))
77
+
78
+ asyncio.run(probe())
79
+ from .db import Store
80
+ try:
81
+ store = Store(paths.db_path())
82
+ line(True, "database", f"{paths.db_path()} ({len(store.list_projects())} projects)")
83
+ store.close()
84
+ except Exception as exc: # noqa: BLE001 — report any DB failure
85
+ line(False, "database", str(exc))
86
+ print("\nAll good." if ok else "\nSome checks failed — see docs/TROUBLESHOOTING.md.")
87
+ return 0 if ok else 1
88
+
89
+
90
+ def _accounts(config: Path, *, discover: bool, save: bool) -> int:
91
+ from .accounts import discover as discover_accounts, probe, resolve_env
92
+
93
+ settings = load_settings(config)
94
+
95
+ async def go():
96
+ kw = dict(claude_binary=settings.claude_binary, codex_binary=settings.codex_binary)
97
+ configured = settings.effective_accounts()
98
+ statuses = [await probe(a, env=await resolve_env(a), **kw) for a in configured]
99
+ found = await discover_accounts(**kw) if discover else []
100
+ return statuses, found
101
+
102
+ statuses, found = asyncio.run(go())
103
+ active = settings.active(settings.effective_accounts())
104
+ print("Configured accounts" + ("" if settings.accounts else " (automatic)") + ":")
105
+ for s in statuses:
106
+ mark = "●" if s.logged_in else ("○" if s.logged_in is False else "?")
107
+ star = " ← active" if s.account.name == active.name else ""
108
+ where = s.account.home or "default location"
109
+ print(f" {mark} {s.account.icon} {s.account.name:14} {s.account.provider:6} "
110
+ f"{s.label or s.error or '':32} {where}{star}")
111
+ if s.detail and not s.logged_in:
112
+ print(f" {s.detail}")
113
+ if discover:
114
+ known = {(a.provider, a.home) for a in settings.effective_accounts()}
115
+ new = [s for s in found if (s.account.provider, s.account.home) not in known]
116
+ print("\nDiscovered:" if new else "\nNo new accounts found.")
117
+ for s in new:
118
+ mark = "●" if s.logged_in else "○"
119
+ print(f" {mark} {s.account.icon} {s.account.name:14} {s.account.provider:6} "
120
+ f"{s.label or s.detail or ''} {s.account.home or 'default location'}")
121
+ if save and new:
122
+ settings.accounts = settings.effective_accounts() + [s.account for s in new]
123
+ save_settings(settings, config)
124
+ print(f"\nSaved {len(new)} account(s) to {config}")
125
+ return 0
126
+
127
+
128
+ def _demo_store():
129
+ from .adapters.demo import demo_fleet, ensure_demo_workspace, seed_demo_tasks
130
+ from .db import Store
131
+
132
+ home = paths.ensure_private_dir(paths.home_dir())
133
+ workspace = ensure_demo_workspace(home / "demo-workspace")
134
+ db = paths.db_path(demo=True)
135
+ for suffix in ("", "-wal", "-shm"):
136
+ try:
137
+ os.remove(str(db) + suffix)
138
+ except FileNotFoundError:
139
+ pass
140
+ store = Store(db)
141
+ for i, (name, group, path) in enumerate(workspace):
142
+ p = store.add_project(name, path, group, pinned=i in (0, 3),
143
+ test_command="python3 -c \"print('3 passed')\"")
144
+ if i == 0:
145
+ store.add_task(p.id, "Add idempotency keys", "Add idempotency keys to POST /invoices",
146
+ priority=2)
147
+ store.add_task(p.id, "Rate limiting", "Add per-tenant rate limiting middleware",
148
+ priority=3)
149
+ if i == 2:
150
+ store.add_task(p.id, "Speed up nightly job", "Profile and speed up the nightly ETL",
151
+ priority=1)
152
+ seed_demo_tasks(store, workspace)
153
+ store.log("info", "Demo mode: agents, logs and timings are simulated.")
154
+ return store, demo_fleet(workspace)
155
+
156
+
157
+ def main(argv: list[str] | None = None) -> int:
158
+ args = _parser().parse_args(argv)
159
+ migrated = paths.migrate_legacy_home()
160
+ if migrated is not None:
161
+ print(f"fleetdeck: copied your settings and history from {migrated} "
162
+ f"to {paths.home_dir()} (the old folder is kept as a backup).", file=sys.stderr)
163
+ config = (args.config or paths.config_path()).expanduser()
164
+ if args.cmd == "doctor":
165
+ return _doctor(config)
166
+ if args.cmd == "accounts":
167
+ return _accounts(config, discover=args.discover, save=args.save)
168
+ if args.cmd == "init-config":
169
+ if config.exists():
170
+ print(f"{config} already exists")
171
+ return 0
172
+ save_settings(Settings(), config)
173
+ print(f"wrote {config}")
174
+ return 0
175
+ if args.cmd == "add-project":
176
+ from .db import Store
177
+ path = os.path.realpath(os.path.expanduser(args.path))
178
+ if not os.path.isdir(path):
179
+ print(f"not a directory: {args.path}", file=sys.stderr)
180
+ return 2
181
+ paths.ensure_private_dir(paths.home_dir())
182
+ store = Store(paths.db_path())
183
+ try:
184
+ p = store.add_project(args.name or os.path.basename(path), path, args.group,
185
+ test_command=args.test_command)
186
+ except Exception as exc: # noqa: BLE001 — e.g. already registered
187
+ print(f"could not add project: {exc}", file=sys.stderr)
188
+ return 1
189
+ print(f"added {p.name} ({p.group}) → {p.path}")
190
+ return 0
191
+
192
+ settings = load_settings(config)
193
+ paths.ensure_private_dir(paths.home_dir())
194
+
195
+ from .ui.app import CommandCenterApp
196
+
197
+ if args.demo:
198
+ store, backend = _demo_store()
199
+ settings.dispatch_paused = False
200
+ else:
201
+ from .adapters.claude_cli import ClaudeCLIBackend
202
+ from .adapters.codex_cli import CodexBackend
203
+ from .db import Store
204
+ from .services.fleet import Fleet, Member
205
+
206
+ have = {"claude": shutil.which(settings.claude_binary) is not None,
207
+ "codex": shutil.which(settings.codex_binary) is not None}
208
+ accounts = [a for a in settings.effective_accounts(have["codex"]) if have[a.provider]]
209
+ if not accounts:
210
+ print(f"Neither Claude Code ({settings.claude_binary!r}) nor Codex "
211
+ f"({settings.codex_binary!r}) was found on PATH.\n"
212
+ "Install one, set claude_binary / codex_binary in config.yaml, or try "
213
+ "`fleetdeck --demo`.", file=sys.stderr)
214
+ return 2
215
+ store = Store(paths.db_path())
216
+ claude = ClaudeCLIBackend(settings.claude_binary, settings.command_timeout)
217
+ runs_dir = paths.home_dir() / "runs"
218
+ backend = Fleet([
219
+ Member(a, claude if a.provider == "claude" else
220
+ CodexBackend(store, a.name, runs_dir, settings.codex_binary), dict(a.env))
221
+ for a in accounts
222
+ ], active=settings.active_account)
223
+ app = CommandCenterApp(settings, store, backend, config_path=config, demo=args.demo)
224
+ try:
225
+ app.run()
226
+ finally:
227
+ store.close()
228
+ return app.return_code or 0
229
+
230
+
231
+ if __name__ == "__main__":
232
+ sys.exit(main())
fleetdeck/accounts.py ADDED
@@ -0,0 +1,115 @@
1
+ """Find and inspect signed-in Claude Code / Codex accounts.
2
+
3
+ Read-only by design: discovery only looks at directories that already contain
4
+ a config marker, and only runs `claude auth status --json` / `codex login
5
+ status`. It never logs in, logs out, or edits anything.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import json
12
+ import os
13
+ import sys
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+
17
+ from .config import Account
18
+ from .proc import CommandNotFound, run
19
+
20
+ CLAUDE_MARKERS = (".claude.json",)
21
+ CODEX_MARKERS = ("auth.json", "config.toml")
22
+
23
+
24
+ @dataclass(slots=True)
25
+ class AccountStatus:
26
+ account: Account
27
+ logged_in: bool | None # None = couldn't tell
28
+ label: str = "" # email for Claude, "ChatGPT" / "API key" for Codex
29
+ detail: str = "" # plan / org
30
+ error: str | None = None
31
+
32
+
33
+ async def probe(account: Account, *, claude_binary: str = "claude",
34
+ codex_binary: str = "codex", timeout: float = 15.0,
35
+ env: dict[str, str] | None = None) -> AccountStatus:
36
+ env = account.env if env is None else env
37
+ try:
38
+ if account.provider == "claude":
39
+ code, out, err = await run([claude_binary, "auth", "status", "--json"], env=env,
40
+ timeout=timeout)
41
+ try:
42
+ data = json.loads(out)
43
+ except json.JSONDecodeError:
44
+ return AccountStatus(account, None, error=(err or out).strip()[:200] or
45
+ f"exit {code}")
46
+ plan = data.get("subscriptionType") or data.get("planTier") or ""
47
+ org = data.get("orgName") or ""
48
+ detail = " · ".join(x for x in (str(plan).capitalize() if plan else "", org) if x)
49
+ logged = bool(data.get("loggedIn"))
50
+ label = data.get("email") or ""
51
+ if not logged and account.home and not account.token_keychain:
52
+ detail = "not signed in; if it uses `claude setup-token`, set token_keychain"
53
+ return AccountStatus(account, logged, label=label or
54
+ ("" if not logged else data.get("authMethod") or ""),
55
+ detail=detail)
56
+ code, out, err = await run([codex_binary, "login", "status"], env=env, timeout=timeout)
57
+ text = (out + err).strip()
58
+ low = text.lower()
59
+ logged = "logged in" in low and "not logged in" not in low
60
+ label = "ChatGPT" if "chatgpt" in low else ("API key" if "api key" in low else "")
61
+ return AccountStatus(account, logged, label=label,
62
+ detail=text.splitlines()[0][:80] if text else "")
63
+ except CommandNotFound as exc:
64
+ return AccountStatus(account, None, error=f"{exc} not installed")
65
+
66
+
67
+ # --------------------------------------------------------------- runtime env
68
+ _TOKEN_CACHE: dict[str, str] = {}
69
+
70
+
71
+ async def read_keychain(service: str) -> str | None:
72
+ """Read a generic password from the macOS Keychain (None if unavailable)."""
73
+ if sys.platform != "darwin":
74
+ return None
75
+ try:
76
+ code, out, _ = await run(["security", "find-generic-password", "-s", service, "-w"],
77
+ timeout=10)
78
+ except CommandNotFound:
79
+ return None
80
+ token = out.strip()
81
+ return token if code == 0 and token else None
82
+
83
+
84
+ async def resolve_env(account: Account, *, reader=read_keychain) -> dict[str, str]:
85
+ """Full environment for this account's processes, including a token from
86
+ the Keychain when configured. Cached in memory only; never persisted."""
87
+ env = account.env
88
+ if account.provider == "claude" and account.token_keychain:
89
+ token = _TOKEN_CACHE.get(account.token_keychain)
90
+ if token is None:
91
+ token = await reader(account.token_keychain)
92
+ if token:
93
+ _TOKEN_CACHE[account.token_keychain] = token
94
+ if token:
95
+ env["CLAUDE_CODE_OAUTH_TOKEN"] = token
96
+ return env
97
+
98
+
99
+ def _candidates(home: Path) -> list[Account]:
100
+ out: list[Account] = [Account("claude", "claude", None)]
101
+ for d in sorted(home.glob(".claude-*")):
102
+ if d.is_dir() and any((d / m).exists() for m in CLAUDE_MARKERS):
103
+ out.append(Account(d.name.removeprefix(".claude-") or d.name, "claude", str(d)))
104
+ if any((home / ".codex" / m).exists() for m in CODEX_MARKERS):
105
+ out.append(Account("chatgpt", "codex", None))
106
+ for d in sorted(home.glob(".codex-*")):
107
+ if d.is_dir() and any((d / m).exists() for m in CODEX_MARKERS):
108
+ out.append(Account("chatgpt-" + d.name.removeprefix(".codex-"), "codex", str(d)))
109
+ return out
110
+
111
+
112
+ async def discover(home: Path | None = None, **kw) -> list[AccountStatus]:
113
+ """Probe the default locations plus ~/.claude-* and ~/.codex-* folders."""
114
+ cands = _candidates(home or Path(os.path.expanduser("~")))
115
+ return list(await asyncio.gather(*(probe(a, **kw) for a in cands)))
File without changes
@@ -0,0 +1,71 @@
1
+ """Backend contract between the UI/services and whatever runs the agents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Protocol, runtime_checkable
7
+
8
+
9
+ @dataclass(slots=True)
10
+ class LaunchSpec:
11
+ cwd: str
12
+ prompt: str
13
+ name: str
14
+ model: str | None = None
15
+ permission_mode: str | None = None
16
+ worktree: str | None = None
17
+ append_system_prompt: str | None = None
18
+ env: dict[str, str] = field(default_factory=dict)
19
+
20
+
21
+ @dataclass(slots=True)
22
+ class CommandResult:
23
+ ok: bool
24
+ output: str = ""
25
+ agent_id: str | None = None # set by launch when the id could be read
26
+
27
+ @property
28
+ def message(self) -> str:
29
+ text = self.output.strip()
30
+ return text.splitlines()[0] if text else ("ok" if self.ok else "failed")
31
+
32
+
33
+ @runtime_checkable
34
+ class Backend(Protocol):
35
+ """Every method is async and must never raise for expected CLI failures;
36
+ it returns a CommandResult with ok=False instead."""
37
+
38
+ name: str
39
+ is_demo: bool
40
+
41
+ async def version(self) -> str | None: ...
42
+
43
+ async def list_sessions(self, env: dict[str, str]) -> list[dict[str, Any]]:
44
+ """Raw records exactly as `claude agents --json --all` returns them."""
45
+ ...
46
+
47
+ async def launch(self, spec: LaunchSpec) -> CommandResult: ...
48
+
49
+ async def follow_up(self, session_id: str, prompt: str, *, cwd: str,
50
+ env: dict[str, str]) -> CommandResult:
51
+ """Continue an existing session with a new prompt in the background.
52
+ The session's process must not be running (stop it first), otherwise
53
+ Claude Code starts a copy under a new id instead of resuming in place."""
54
+ ...
55
+
56
+ async def logs(self, agent_id: str, env: dict[str, str]) -> CommandResult: ...
57
+
58
+ async def stop(self, agent_id: str, env: dict[str, str]) -> CommandResult: ...
59
+
60
+ async def respawn(self, agent_id: str, env: dict[str, str]) -> CommandResult: ...
61
+
62
+ async def remove(self, agent_id: str, env: dict[str, str]) -> CommandResult: ...
63
+
64
+ def attach_argv(self, agent_id: str) -> list[str] | None:
65
+ """Command to run in the foreground (TUI suspended) to attach, or None
66
+ if attaching is not possible for this backend."""
67
+ ...
68
+
69
+
70
+ class BackendError(RuntimeError):
71
+ """The backend itself is unusable (binary missing, unparsable output)."""
@@ -0,0 +1,187 @@
1
+ """Adapter over the public Claude Code CLI.
2
+
3
+ Only commands verified against Claude Code 2.1.x help output and docs are used:
4
+
5
+ claude --version
6
+ claude agents --json --all
7
+ claude --bg [--name N] [--model M] [--permission-mode P] [--worktree W]
8
+ [--append-system-prompt S] <prompt>
9
+ claude logs <id> | stop <id> | respawn <id> | rm <id> | attach <id>
10
+
11
+ Never passed, by design: --dangerously-skip-permissions,
12
+ --allow-dangerously-skip-permissions, --permission-mode bypassPermissions/dontAsk.
13
+ Claude Code's private storage (~/.claude/jobs, sockets, credentials) is never
14
+ read.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import re
21
+ import shutil
22
+ from typing import Any
23
+
24
+ from ..models import SAFE_PERMISSION_MODES
25
+ from ..proc import CommandNotFound, run
26
+ from .base import BackendError, CommandResult, LaunchSpec
27
+
28
+ # "backgrounded · 676a41e3 · fleet-probe"
29
+ _BG_ID = re.compile(r"backgrounded\s*[·:\-]\s*([0-9a-f]{6,})", re.IGNORECASE)
30
+ _ID_SAFE = re.compile(r"^[A-Za-z0-9._\- ]{1,128}$")
31
+ _UUID = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
32
+ # "note: session d391e7d6 is already running in the background, so this started a copy as d58a75ed"
33
+ _COPY_NOTE = re.compile(r"started a copy as ([0-9a-f]{6,})", re.IGNORECASE)
34
+
35
+ FORBIDDEN_FLAGS = (
36
+ "--dangerously-skip-permissions",
37
+ "--allow-dangerously-skip-permissions",
38
+ )
39
+
40
+
41
+ def build_launch_argv(binary: str, spec: LaunchSpec) -> list[str]:
42
+ argv = [binary, "--bg", "--name", spec.name]
43
+ if spec.model:
44
+ argv += ["--model", spec.model]
45
+ if spec.permission_mode and spec.permission_mode != "default":
46
+ if spec.permission_mode not in SAFE_PERMISSION_MODES:
47
+ raise ValueError(f"permission mode {spec.permission_mode!r} is not allowed")
48
+ argv += ["--permission-mode", spec.permission_mode]
49
+ if spec.worktree:
50
+ argv += ["--worktree", spec.worktree]
51
+ if spec.append_system_prompt:
52
+ argv += ["--append-system-prompt", spec.append_system_prompt]
53
+ argv.append(safe_prompt(spec.prompt))
54
+ if any(f in argv[:-1] for f in FORBIDDEN_FLAGS):
55
+ raise ValueError("permission-bypass flags are never passed by fleetdeck")
56
+ return argv
57
+
58
+
59
+ def safe_prompt(prompt: str) -> str:
60
+ prompt = prompt.strip()
61
+ # A leading dash would be parsed as an option by the CLI.
62
+ return "Task: " + prompt if prompt.startswith("-") else prompt
63
+
64
+
65
+ def build_follow_up_argv(binary: str, session_id: str, prompt: str) -> list[str]:
66
+ """`claude --bg --resume <uuid> <prompt>`: verified on 2.1.332 to wake a
67
+ stopped session in place ("woke session … with its saved options")."""
68
+ if not _UUID.match(session_id):
69
+ raise ValueError(f"not a session UUID: {session_id!r}")
70
+ return [binary, "--bg", "--resume", session_id, safe_prompt(prompt)]
71
+
72
+
73
+ def parse_copy_id(output: str) -> str | None:
74
+ m = _COPY_NOTE.search(output)
75
+ return m.group(1) if m else None
76
+
77
+
78
+ def parse_sessions(stdout: str) -> list[dict[str, Any]]:
79
+ text = stdout.strip()
80
+ if not text:
81
+ return []
82
+ start = text.find("[")
83
+ if start > 0: # tolerate a banner line before the JSON array
84
+ text = text[start:]
85
+ try:
86
+ data = json.loads(text)
87
+ except json.JSONDecodeError as exc:
88
+ raise BackendError(f"`claude agents --json` returned invalid JSON: {exc}") from exc
89
+ if not isinstance(data, list):
90
+ raise BackendError("`claude agents --json` did not return a list")
91
+ return [d for d in data if isinstance(d, dict)]
92
+
93
+
94
+ def parse_launch_id(output: str) -> str | None:
95
+ m = _BG_ID.search(output)
96
+ return m.group(1) if m else None
97
+
98
+
99
+ class ClaudeCLIBackend:
100
+ name = "claude-cli"
101
+ is_demo = False
102
+
103
+ def __init__(self, binary: str = "claude", timeout: float = 15.0) -> None:
104
+ self.binary = binary
105
+ self.timeout = timeout
106
+ self._version: str | None = None
107
+
108
+ def available(self) -> bool:
109
+ return shutil.which(self.binary) is not None
110
+
111
+ async def _run(
112
+ self, *args: str, env: dict[str, str] | None = None, cwd: str | None = None,
113
+ timeout: float | None = None,
114
+ ) -> tuple[int, str, str]:
115
+ try:
116
+ return await run([self.binary, *args], env=env, cwd=cwd,
117
+ timeout=timeout or self.timeout)
118
+ except CommandNotFound as exc:
119
+ raise BackendError(
120
+ f"Claude Code CLI not found ({self.binary!r}). Install it or set "
121
+ "claude_binary in config.yaml."
122
+ ) from exc
123
+
124
+ async def version(self) -> str | None:
125
+ if self._version is None:
126
+ code, out, _ = await self._run("--version", timeout=10)
127
+ self._version = out.strip().split()[0] if code == 0 and out.strip() else None
128
+ return self._version
129
+
130
+ async def list_sessions(self, env: dict[str, str]) -> list[dict[str, Any]]:
131
+ code, out, err = await self._run("agents", "--json", "--all", env=env)
132
+ if code != 0:
133
+ raise BackendError((err or out).strip() or f"claude agents exited {code}")
134
+ return parse_sessions(out)
135
+
136
+ async def launch(self, spec: LaunchSpec) -> CommandResult:
137
+ try:
138
+ argv = build_launch_argv(self.binary, spec)
139
+ except ValueError as exc:
140
+ return CommandResult(False, str(exc))
141
+ try:
142
+ code, out, err = await run(argv, cwd=spec.cwd, env=spec.env, timeout=60,
143
+ track=False)
144
+ except CommandNotFound:
145
+ return CommandResult(False, f"Claude Code CLI not found ({self.binary!r})")
146
+ text = "\n".join(t for t in (out.strip(), err.strip()) if t)
147
+ return CommandResult(code == 0, text, parse_launch_id(text) if code == 0 else None)
148
+
149
+ async def follow_up(self, session_id: str, prompt: str, *, cwd: str,
150
+ env: dict[str, str]) -> CommandResult:
151
+ try:
152
+ argv = build_follow_up_argv(self.binary, session_id, prompt)
153
+ except ValueError as exc:
154
+ return CommandResult(False, str(exc))
155
+ try:
156
+ code, out, err = await run(argv, cwd=cwd, env=env, timeout=60, track=False)
157
+ except CommandNotFound:
158
+ return CommandResult(False, f"Claude Code CLI not found ({self.binary!r})")
159
+ text = "\n".join(t for t in (out.strip(), err.strip()) if t)
160
+ return CommandResult(code == 0, text, parse_launch_id(text) if code == 0 else None)
161
+
162
+ async def _simple(self, verb: str, agent_id: str, env: dict[str, str]) -> CommandResult:
163
+ if not _ID_SAFE.match(agent_id):
164
+ return CommandResult(False, f"refusing unsafe session id {agent_id!r}")
165
+ try:
166
+ code, out, err = await self._run(verb, agent_id, env=env)
167
+ except BackendError as exc:
168
+ return CommandResult(False, str(exc))
169
+ text = "\n".join(t for t in (out.rstrip(), err.rstrip()) if t)
170
+ return CommandResult(code == 0, text)
171
+
172
+ async def logs(self, agent_id: str, env: dict[str, str]) -> CommandResult:
173
+ return await self._simple("logs", agent_id, env)
174
+
175
+ async def stop(self, agent_id: str, env: dict[str, str]) -> CommandResult:
176
+ return await self._simple("stop", agent_id, env)
177
+
178
+ async def respawn(self, agent_id: str, env: dict[str, str]) -> CommandResult:
179
+ return await self._simple("respawn", agent_id, env)
180
+
181
+ async def remove(self, agent_id: str, env: dict[str, str]) -> CommandResult:
182
+ return await self._simple("rm", agent_id, env)
183
+
184
+ def attach_argv(self, agent_id: str) -> list[str] | None:
185
+ if not _ID_SAFE.match(agent_id):
186
+ return None
187
+ return [self.binary, "attach", agent_id]