claude-command-center 0.1.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 (38) hide show
  1. claude_center/__init__.py +3 -0
  2. claude_center/__main__.py +171 -0
  3. claude_center/adapters/__init__.py +0 -0
  4. claude_center/adapters/base.py +64 -0
  5. claude_center/adapters/claude_cli.py +156 -0
  6. claude_center/adapters/demo.py +276 -0
  7. claude_center/config.py +213 -0
  8. claude_center/db.py +406 -0
  9. claude_center/gitinfo.py +169 -0
  10. claude_center/models.py +166 -0
  11. claude_center/paths.py +33 -0
  12. claude_center/proc.py +92 -0
  13. claude_center/redact.py +51 -0
  14. claude_center/services/__init__.py +0 -0
  15. claude_center/services/dispatcher.py +261 -0
  16. claude_center/services/monitor.py +226 -0
  17. claude_center/services/notifier.py +71 -0
  18. claude_center/status.py +97 -0
  19. claude_center/termrender.py +124 -0
  20. claude_center/ui/__init__.py +0 -0
  21. claude_center/ui/app.py +859 -0
  22. claude_center/ui/app.tcss +213 -0
  23. claude_center/ui/commands.py +61 -0
  24. claude_center/ui/screens/__init__.py +0 -0
  25. claude_center/ui/screens/modals.py +446 -0
  26. claude_center/ui/style.py +120 -0
  27. claude_center/ui/views.py +220 -0
  28. claude_center/ui/widgets/__init__.py +0 -0
  29. claude_center/ui/widgets/agent_table.py +117 -0
  30. claude_center/ui/widgets/bottom.py +27 -0
  31. claude_center/ui/widgets/details.py +205 -0
  32. claude_center/ui/widgets/header.py +64 -0
  33. claude_center/ui/widgets/sidebar.py +187 -0
  34. claude_command_center-0.1.0.dist-info/METADATA +204 -0
  35. claude_command_center-0.1.0.dist-info/RECORD +38 -0
  36. claude_command_center-0.1.0.dist-info/WHEEL +4 -0
  37. claude_command_center-0.1.0.dist-info/entry_points.txt +2 -0
  38. claude_command_center-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,3 @@
1
+ """Claude Command Center — a multi-project TUI for Claude Code background agents."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,171 @@
1
+ """`claude-center` 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="claude-center",
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"claude-center {__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
+ ap = sub.add_parser("add-project", help="register a project directory")
29
+ ap.add_argument("path")
30
+ ap.add_argument("--name")
31
+ ap.add_argument("--group", choices=["office", "personal"], default="personal")
32
+ ap.add_argument("--test-command", default="")
33
+ return p
34
+
35
+
36
+ def _doctor(config: Path) -> int:
37
+ from .adapters.base import BackendError
38
+ from .adapters.claude_cli import ClaudeCLIBackend
39
+
40
+ settings = load_settings(config)
41
+ ok = True
42
+
43
+ def line(good: bool, label: str, detail: str = "") -> None:
44
+ nonlocal ok
45
+ ok &= good
46
+ print(f" {'✓' if good else '✗'} {label}" + (f" — {detail}" if detail else ""))
47
+
48
+ print(f"claude-center {__version__}")
49
+ line(sys.version_info >= (3, 12), "Python ≥ 3.12", sys.version.split()[0])
50
+ line(True, "config", str(config) + ("" if config.exists()
51
+ else " (not created; defaults)"))
52
+ for err in settings.load_errors:
53
+ line(False, "config error", err)
54
+ line(shutil.which("git") is not None, "git on PATH", shutil.which("git") or "missing")
55
+ binary = shutil.which(settings.claude_binary)
56
+ line(binary is not None, "Claude Code CLI", binary or f"{settings.claude_binary!r} not found")
57
+ if binary:
58
+ be = ClaudeCLIBackend(settings.claude_binary, settings.command_timeout)
59
+
60
+ async def probe() -> None:
61
+ v = await be.version()
62
+ line(v is not None, "claude --version", v or "failed")
63
+ for name in sorted(settings.environments):
64
+ env = settings.env_for(name)
65
+ try:
66
+ sessions = await be.list_sessions(env)
67
+ bg = sum(1 for s in sessions if s.get("kind") == "background")
68
+ line(True, f"claude agents --json --all [{name}]",
69
+ f"{len(sessions)} sessions ({bg} background)")
70
+ except BackendError as exc:
71
+ line(False, f"claude agents --json --all [{name}]", str(exc))
72
+
73
+ asyncio.run(probe())
74
+ from .db import Store
75
+ try:
76
+ store = Store(paths.db_path())
77
+ line(True, "database", f"{paths.db_path()} ({len(store.list_projects())} projects)")
78
+ store.close()
79
+ except Exception as exc: # noqa: BLE001 — report any DB failure
80
+ line(False, "database", str(exc))
81
+ print("\nAll good." if ok else "\nSome checks failed — see docs/TROUBLESHOOTING.md.")
82
+ return 0 if ok else 1
83
+
84
+
85
+ def _demo_store():
86
+ from .adapters.demo import DemoBackend, ensure_demo_workspace, seed_demo_tasks
87
+ from .db import Store
88
+
89
+ home = paths.ensure_private_dir(paths.home_dir())
90
+ workspace = ensure_demo_workspace(home / "demo-workspace")
91
+ db = paths.db_path(demo=True)
92
+ for suffix in ("", "-wal", "-shm"):
93
+ try:
94
+ os.remove(str(db) + suffix)
95
+ except FileNotFoundError:
96
+ pass
97
+ store = Store(db)
98
+ for i, (name, group, path) in enumerate(workspace):
99
+ p = store.add_project(name, path, group, pinned=i in (0, 3),
100
+ test_command="python3 -c \"print('3 passed')\"")
101
+ if i == 0:
102
+ store.add_task(p.id, "Add idempotency keys", "Add idempotency keys to POST /invoices",
103
+ priority=2)
104
+ store.add_task(p.id, "Rate limiting", "Add per-tenant rate limiting middleware",
105
+ priority=3)
106
+ if i == 2:
107
+ store.add_task(p.id, "Speed up nightly job", "Profile and speed up the nightly ETL",
108
+ priority=1)
109
+ seed_demo_tasks(store, workspace)
110
+ store.log("info", "Demo mode: agents, logs and timings are simulated.")
111
+ return store, DemoBackend(workspace)
112
+
113
+
114
+ def main(argv: list[str] | None = None) -> int:
115
+ args = _parser().parse_args(argv)
116
+ config = (args.config or paths.config_path()).expanduser()
117
+ if args.cmd == "doctor":
118
+ return _doctor(config)
119
+ if args.cmd == "init-config":
120
+ if config.exists():
121
+ print(f"{config} already exists")
122
+ return 0
123
+ save_settings(Settings(), config)
124
+ print(f"wrote {config}")
125
+ return 0
126
+ if args.cmd == "add-project":
127
+ from .db import Store
128
+ path = os.path.realpath(os.path.expanduser(args.path))
129
+ if not os.path.isdir(path):
130
+ print(f"not a directory: {args.path}", file=sys.stderr)
131
+ return 2
132
+ paths.ensure_private_dir(paths.home_dir())
133
+ store = Store(paths.db_path())
134
+ try:
135
+ p = store.add_project(args.name or os.path.basename(path), path, args.group,
136
+ test_command=args.test_command)
137
+ except Exception as exc: # noqa: BLE001 — e.g. already registered
138
+ print(f"could not add project: {exc}", file=sys.stderr)
139
+ return 1
140
+ print(f"added {p.name} ({p.group}) → {p.path}")
141
+ return 0
142
+
143
+ settings = load_settings(config)
144
+ paths.ensure_private_dir(paths.home_dir())
145
+
146
+ from .ui.app import CommandCenterApp
147
+
148
+ if args.demo:
149
+ store, backend = _demo_store()
150
+ settings.dispatch_paused = False
151
+ else:
152
+ from .adapters.claude_cli import ClaudeCLIBackend
153
+ from .db import Store
154
+
155
+ if shutil.which(settings.claude_binary) is None:
156
+ print(f"Claude Code CLI {settings.claude_binary!r} not found on PATH.\n"
157
+ "Install Claude Code, set claude_binary in config.yaml, or try "
158
+ "`claude-center --demo`.", file=sys.stderr)
159
+ return 2
160
+ store = Store(paths.db_path())
161
+ backend = ClaudeCLIBackend(settings.claude_binary, settings.command_timeout)
162
+ app = CommandCenterApp(settings, store, backend, config_path=config, demo=args.demo)
163
+ try:
164
+ app.run()
165
+ finally:
166
+ store.close()
167
+ return app.return_code or 0
168
+
169
+
170
+ if __name__ == "__main__":
171
+ sys.exit(main())
File without changes
@@ -0,0 +1,64 @@
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 logs(self, agent_id: str, env: dict[str, str]) -> CommandResult: ...
50
+
51
+ async def stop(self, agent_id: str, env: dict[str, str]) -> CommandResult: ...
52
+
53
+ async def respawn(self, agent_id: str, env: dict[str, str]) -> CommandResult: ...
54
+
55
+ async def remove(self, agent_id: str, env: dict[str, str]) -> CommandResult: ...
56
+
57
+ def attach_argv(self, agent_id: str) -> list[str] | None:
58
+ """Command to run in the foreground (TUI suspended) to attach, or None
59
+ if attaching is not possible for this backend."""
60
+ ...
61
+
62
+
63
+ class BackendError(RuntimeError):
64
+ """The backend itself is unusable (binary missing, unparsable output)."""
@@ -0,0 +1,156 @@
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 · ccc-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
+
32
+ FORBIDDEN_FLAGS = (
33
+ "--dangerously-skip-permissions",
34
+ "--allow-dangerously-skip-permissions",
35
+ )
36
+
37
+
38
+ def build_launch_argv(binary: str, spec: LaunchSpec) -> list[str]:
39
+ argv = [binary, "--bg", "--name", spec.name]
40
+ if spec.model:
41
+ argv += ["--model", spec.model]
42
+ if spec.permission_mode and spec.permission_mode != "default":
43
+ if spec.permission_mode not in SAFE_PERMISSION_MODES:
44
+ raise ValueError(f"permission mode {spec.permission_mode!r} is not allowed")
45
+ argv += ["--permission-mode", spec.permission_mode]
46
+ if spec.worktree:
47
+ argv += ["--worktree", spec.worktree]
48
+ if spec.append_system_prompt:
49
+ argv += ["--append-system-prompt", spec.append_system_prompt]
50
+ prompt = spec.prompt.strip()
51
+ # A leading dash would be parsed as an option by the CLI.
52
+ if prompt.startswith("-"):
53
+ prompt = "Task: " + prompt
54
+ argv.append(prompt)
55
+ if any(f in argv[:-1] for f in FORBIDDEN_FLAGS):
56
+ raise ValueError("permission-bypass flags are never passed by claude-center")
57
+ return argv
58
+
59
+
60
+ def parse_sessions(stdout: str) -> list[dict[str, Any]]:
61
+ text = stdout.strip()
62
+ if not text:
63
+ return []
64
+ start = text.find("[")
65
+ if start > 0: # tolerate a banner line before the JSON array
66
+ text = text[start:]
67
+ try:
68
+ data = json.loads(text)
69
+ except json.JSONDecodeError as exc:
70
+ raise BackendError(f"`claude agents --json` returned invalid JSON: {exc}") from exc
71
+ if not isinstance(data, list):
72
+ raise BackendError("`claude agents --json` did not return a list")
73
+ return [d for d in data if isinstance(d, dict)]
74
+
75
+
76
+ def parse_launch_id(output: str) -> str | None:
77
+ m = _BG_ID.search(output)
78
+ return m.group(1) if m else None
79
+
80
+
81
+ class ClaudeCLIBackend:
82
+ name = "claude-cli"
83
+ is_demo = False
84
+
85
+ def __init__(self, binary: str = "claude", timeout: float = 15.0) -> None:
86
+ self.binary = binary
87
+ self.timeout = timeout
88
+ self._version: str | None = None
89
+
90
+ def available(self) -> bool:
91
+ return shutil.which(self.binary) is not None
92
+
93
+ async def _run(
94
+ self, *args: str, env: dict[str, str] | None = None, cwd: str | None = None,
95
+ timeout: float | None = None,
96
+ ) -> tuple[int, str, str]:
97
+ try:
98
+ return await run([self.binary, *args], env=env, cwd=cwd,
99
+ timeout=timeout or self.timeout)
100
+ except CommandNotFound as exc:
101
+ raise BackendError(
102
+ f"Claude Code CLI not found ({self.binary!r}). Install it or set "
103
+ "claude_binary in config.yaml."
104
+ ) from exc
105
+
106
+ async def version(self) -> str | None:
107
+ if self._version is None:
108
+ code, out, _ = await self._run("--version", timeout=10)
109
+ self._version = out.strip().split()[0] if code == 0 and out.strip() else None
110
+ return self._version
111
+
112
+ async def list_sessions(self, env: dict[str, str]) -> list[dict[str, Any]]:
113
+ code, out, err = await self._run("agents", "--json", "--all", env=env)
114
+ if code != 0:
115
+ raise BackendError((err or out).strip() or f"claude agents exited {code}")
116
+ return parse_sessions(out)
117
+
118
+ async def launch(self, spec: LaunchSpec) -> CommandResult:
119
+ try:
120
+ argv = build_launch_argv(self.binary, spec)
121
+ except ValueError as exc:
122
+ return CommandResult(False, str(exc))
123
+ try:
124
+ code, out, err = await run(argv, cwd=spec.cwd, env=spec.env, timeout=60,
125
+ track=False)
126
+ except CommandNotFound:
127
+ return CommandResult(False, f"Claude Code CLI not found ({self.binary!r})")
128
+ text = "\n".join(t for t in (out.strip(), err.strip()) if t)
129
+ return CommandResult(code == 0, text, parse_launch_id(text) if code == 0 else None)
130
+
131
+ async def _simple(self, verb: str, agent_id: str, env: dict[str, str]) -> CommandResult:
132
+ if not _ID_SAFE.match(agent_id):
133
+ return CommandResult(False, f"refusing unsafe session id {agent_id!r}")
134
+ try:
135
+ code, out, err = await self._run(verb, agent_id, env=env)
136
+ except BackendError as exc:
137
+ return CommandResult(False, str(exc))
138
+ text = "\n".join(t for t in (out.rstrip(), err.rstrip()) if t)
139
+ return CommandResult(code == 0, text)
140
+
141
+ async def logs(self, agent_id: str, env: dict[str, str]) -> CommandResult:
142
+ return await self._simple("logs", agent_id, env)
143
+
144
+ async def stop(self, agent_id: str, env: dict[str, str]) -> CommandResult:
145
+ return await self._simple("stop", agent_id, env)
146
+
147
+ async def respawn(self, agent_id: str, env: dict[str, str]) -> CommandResult:
148
+ return await self._simple("respawn", agent_id, env)
149
+
150
+ async def remove(self, agent_id: str, env: dict[str, str]) -> CommandResult:
151
+ return await self._simple("rm", agent_id, env)
152
+
153
+ def attach_argv(self, agent_id: str) -> list[str] | None:
154
+ if not _ID_SAFE.match(agent_id):
155
+ return None
156
+ return [self.binary, "attach", agent_id]
@@ -0,0 +1,276 @@
1
+ """Simulated backend for `claude-center --demo`.
2
+
3
+ Produces records in the same documented shape as `claude agents --json --all`
4
+ so the whole pipeline (status mapping, project matching, dispatcher, UI) runs
5
+ unchanged. Nothing here talks to Claude Code.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import random
12
+ import subprocess
13
+ import time
14
+ import uuid
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from .base import CommandResult, LaunchSpec
20
+
21
+ DEMO_PROJECTS: list[tuple[str, str]] = [
22
+ ("acme-billing-api", "office"),
23
+ ("acme-web-console", "office"),
24
+ ("data-pipeline", "office"),
25
+ ("personal-blog", "personal"),
26
+ ("rust-raytracer", "personal"),
27
+ ]
28
+
29
+ _LOG_SCRIPT = [
30
+ "⏺ Reading CLAUDE.md and project structure",
31
+ "⏺ Read(src/{mod}/service.ts)",
32
+ "⏺ Grep(\"{sym}\") — 7 matches in 4 files",
33
+ "⏺ Planning: 1) add validation 2) update callers 3) extend tests",
34
+ "⏺ Edit(src/{mod}/service.ts) +24 −6",
35
+ "⏺ Edit(src/{mod}/controller.ts) +9 −2",
36
+ "⏺ Bash(npm run build) — exit 0",
37
+ "⏺ Bash(npm test -- {mod}) — 42 passed",
38
+ "⏺ Write(src/{mod}/__tests__/{mod}.spec.ts)",
39
+ "⏺ Bash(npm test) — 118 passed, 0 failed",
40
+ "⏺ Summary: implemented change, build and tests green",
41
+ ]
42
+
43
+ _SCENARIOS = ("ok", "ok", "ok", "permission", "input", "fail")
44
+
45
+ # (project index, scenario, session name, age seconds, task title, task prompt)
46
+ INITIAL_SESSIONS = [
47
+ (0, "ok", "refactor-invoice-service", 1240, "Refactor invoice service",
48
+ "Split InvoiceService into pricing and persistence; keep the public API stable."),
49
+ (0, "permission", "add-stripe-webhooks", 410, "Stripe webhooks",
50
+ "Add verified Stripe webhook handling for invoice.paid and invoice.failed."),
51
+ (1, "ok", "dark-mode-settings", 95, "Dark mode settings",
52
+ "Add a dark-mode toggle to the settings page, persisted per user."),
53
+ (2, "fail", "backfill-partitions", 1800, "Backfill partitions",
54
+ "Backfill monthly event partitions for 2024 and verify row counts."),
55
+ (3, "input", "draft-release-notes", 300, "Draft release notes",
56
+ "Draft release notes for v2.3 from merged PRs since the last tag."),
57
+ (4, "ok", "bvh-acceleration", 2600, "BVH acceleration",
58
+ "Implement a BVH for triangle meshes and benchmark against the naive path."),
59
+ ]
60
+
61
+
62
+ def seed_demo_tasks(store, workspace: list[tuple[str, str, str]]) -> None:
63
+ """Give the pre-running demo sessions real task rows + launch records, so
64
+ the Task column and task queue go through the same code path as live use."""
65
+ import time as _time
66
+ from ..models import TaskStatus
67
+
68
+ import os
69
+ projects = {p.path: p for p in store.list_projects()} # stored as realpath
70
+ now = _time.time()
71
+ for pidx, scenario, name, age, title, prompt in INITIAL_SESSIONS:
72
+ project = projects.get(os.path.realpath(workspace[pidx][2]))
73
+ if project is None:
74
+ continue
75
+ task = store.add_task(project.id, title, prompt, priority=2)
76
+ store.update_task(task.id, status=TaskStatus.RUNNING, agent_name=name,
77
+ started_at=now - age - 1, attempts=1)
78
+ store.record_launch(name, project_id=project.id, task_id=task.id,
79
+ model="opus" if pidx % 2 == 0 else "sonnet",
80
+ permission_mode="plan" if scenario == "input" else "default",
81
+ prompt=prompt)
82
+
83
+
84
+ @dataclass
85
+ class _Sim:
86
+ id: str
87
+ name: str
88
+ cwd: str
89
+ started: float
90
+ scenario: str
91
+ kind: str = "background"
92
+ state: str = "working"
93
+ status: str | None = "busy"
94
+ waiting_for: str | None = None
95
+ step: int = 0
96
+ log: list[str] = field(default_factory=list)
97
+ next_at: float = 0.0
98
+ mod: str = "billing"
99
+ session_id: str = field(default_factory=lambda: str(uuid.uuid4()))
100
+ pid: int = field(default_factory=lambda: random.randint(20_000, 90_000))
101
+
102
+
103
+ def ensure_demo_workspace(root: Path) -> list[tuple[str, str, str]]:
104
+ """Create small real git repos with uncommitted changes (idempotent).
105
+
106
+ Returns (name, group, path) per demo project.
107
+ """
108
+ out = []
109
+ root.mkdir(parents=True, exist_ok=True)
110
+ for name, group in DEMO_PROJECTS:
111
+ repo = root / name
112
+ if not (repo / ".git").exists():
113
+ (repo / "src").mkdir(parents=True, exist_ok=True)
114
+ (repo / "README.md").write_text(f"# {name}\n\nDemo project for claude-center.\n")
115
+ (repo / "src" / "app.py").write_text("def main():\n return 'hello'\n")
116
+ git = ["git", "-C", str(repo), "-c", "user.name=demo",
117
+ "-c", "user.email=demo@example.invalid"]
118
+ try:
119
+ subprocess.run([*git[:3], "init", "-q", "-b", "main"], check=True,
120
+ capture_output=True)
121
+ subprocess.run([*git, "add", "."], check=True, capture_output=True)
122
+ subprocess.run([*git, "commit", "-qm", "initial"], check=True,
123
+ capture_output=True)
124
+ except (OSError, subprocess.CalledProcessError):
125
+ pass
126
+ (repo / "src" / "app.py").write_text(
127
+ "def main():\n return greet('world')\n\n\n"
128
+ "def greet(who: str) -> str:\n return f'hello {who}'\n"
129
+ )
130
+ (repo / "src" / "new_feature.py").write_text("FEATURE_FLAG = True\n")
131
+ out.append((name, group, str(repo)))
132
+ return out
133
+
134
+
135
+ class DemoBackend:
136
+ name = "demo"
137
+ is_demo = True
138
+
139
+ def __init__(self, workspace: list[tuple[str, str, str]], *, speed: float = 1.0,
140
+ seed: int | None = None) -> None:
141
+ self._rng = random.Random(seed)
142
+ self._speed = speed
143
+ self._sims: dict[str, _Sim] = {}
144
+ now = time.time()
145
+ mods = ["billing", "auth", "ingest", "posts", "render"]
146
+ for i, (pidx, scenario, name, age, _title, _prompt) in enumerate(INITIAL_SESSIONS):
147
+ _, _, path = workspace[pidx]
148
+ sim = self._new_sim(name, path, scenario, now - age, mods[pidx])
149
+ # fast-forward pre-existing sessions
150
+ for _ in range(self._rng.randint(2, 6)):
151
+ self._advance(sim, now)
152
+ self._sims[sim.id] = sim
153
+ # one interactive session, like a terminal the user has open
154
+ _, _, path = workspace[1]
155
+ inter = _Sim(id="", name=f"{Path(path).name}-a1", cwd=path, started=now - 3600,
156
+ scenario="ok", kind="interactive", state="", status="idle")
157
+ self._sims["interactive-1"] = inter
158
+ self._last_tick = now
159
+
160
+ # ------------------------------------------------------------ helpers
161
+ def _new_sim(self, name: str, cwd: str, scenario: str, started: float, mod: str) -> _Sim:
162
+ sid = uuid.uuid4().hex[:8]
163
+ return _Sim(id=sid, name=name, cwd=cwd, started=started, scenario=scenario,
164
+ mod=mod, next_at=time.time() + self._delay())
165
+
166
+ def _delay(self) -> float:
167
+ return self._rng.uniform(1.5, 4.0) / self._speed
168
+
169
+ def _advance(self, sim: _Sim, now: float) -> None:
170
+ if sim.kind != "background" or sim.state in ("done", "failed", "stopped"):
171
+ return
172
+ if sim.state == "blocked":
173
+ return # waits for the user (attach is simulated by respawn)
174
+ line = _LOG_SCRIPT[min(sim.step, len(_LOG_SCRIPT) - 1)]
175
+ sim.log.append(line.format(mod=sim.mod, sym=f"{sim.mod.capitalize()}Service"))
176
+ sim.step += 1
177
+ if sim.scenario == "permission" and sim.step == 4:
178
+ sim.state, sim.status, sim.waiting_for = "blocked", "waiting", "permission prompt"
179
+ sim.log.append("⏺ Bash(rm -rf build && npm run migrate) — awaiting permission")
180
+ elif sim.scenario == "input" and sim.step == 3:
181
+ sim.state, sim.status, sim.waiting_for = "blocked", "waiting", "input needed"
182
+ sim.log.append("⏺ Question: should the changelog include internal refactors?")
183
+ elif sim.scenario == "fail" and sim.step == 5:
184
+ sim.state, sim.status = "failed", None
185
+ sim.log.append("✗ Error: migration 0042 failed: relation \"events_2024\" exists")
186
+ sim.log.append(" DATABASE_URL=postgres://app:hunter2secret@db:5432/app")
187
+ elif sim.step >= len(_LOG_SCRIPT):
188
+ sim.state, sim.status = "done", "idle"
189
+ sim.next_at = now + self._delay()
190
+
191
+ def _tick(self) -> None:
192
+ now = time.time()
193
+ for sim in self._sims.values():
194
+ if sim.next_at and now >= sim.next_at:
195
+ self._advance(sim, now)
196
+
197
+ def _record(self, s: _Sim) -> dict[str, Any]:
198
+ rec: dict[str, Any] = {
199
+ "cwd": s.cwd,
200
+ "kind": s.kind,
201
+ "startedAt": int(s.started * 1000),
202
+ "sessionId": s.session_id,
203
+ "name": s.name,
204
+ }
205
+ if s.kind == "background":
206
+ rec["id"] = s.id
207
+ rec["state"] = s.state
208
+ alive = s.kind == "interactive" or s.state in ("working", "blocked", "done")
209
+ if alive and s.status:
210
+ rec["pid"] = s.pid
211
+ rec["status"] = s.status
212
+ if s.status == "waiting" and s.waiting_for:
213
+ rec["waitingFor"] = s.waiting_for
214
+ return rec
215
+
216
+ # ------------------------------------------------------------ backend
217
+ async def version(self) -> str | None:
218
+ return "demo"
219
+
220
+ async def list_sessions(self, env: dict[str, str]) -> list[dict[str, Any]]:
221
+ await asyncio.sleep(0.02)
222
+ self._tick()
223
+ return [self._record(s) for s in self._sims.values()]
224
+
225
+ async def launch(self, spec: LaunchSpec) -> CommandResult:
226
+ await asyncio.sleep(0.1)
227
+ scenario = self._rng.choice(_SCENARIOS)
228
+ sim = self._new_sim(spec.name, spec.cwd, scenario, time.time(),
229
+ Path(spec.cwd).name.split("-")[0])
230
+ sim.log.append(f"⏺ Task: {spec.prompt[:120]}")
231
+ if spec.permission_mode == "plan":
232
+ sim.log.append("⏺ Plan mode: exploring before proposing changes")
233
+ self._sims[sim.id] = sim
234
+ return CommandResult(True, f"backgrounded · {sim.id} · {spec.name}", sim.id)
235
+
236
+ def _find(self, agent_id: str) -> _Sim | None:
237
+ for s in self._sims.values():
238
+ if s.id == agent_id or s.name == agent_id:
239
+ return s
240
+ return None
241
+
242
+ async def logs(self, agent_id: str, env: dict[str, str]) -> CommandResult:
243
+ s = self._find(agent_id)
244
+ if not s:
245
+ return CommandResult(False, f"No session matching '{agent_id}'.")
246
+ header = f"Session {s.id} · {s.name} [DEMO — simulated output]"
247
+ return CommandResult(True, "\n".join([header, *s.log]))
248
+
249
+ async def stop(self, agent_id: str, env: dict[str, str]) -> CommandResult:
250
+ s = self._find(agent_id)
251
+ if not s:
252
+ return CommandResult(False, f"No session matching '{agent_id}'.")
253
+ s.state, s.status, s.waiting_for = "stopped", None, None
254
+ s.log.append("■ Stopped by user")
255
+ return CommandResult(True, f"stopped {s.id}")
256
+
257
+ async def respawn(self, agent_id: str, env: dict[str, str]) -> CommandResult:
258
+ s = self._find(agent_id)
259
+ if not s:
260
+ return CommandResult(False, f"No session matching '{agent_id}'.")
261
+ s.state, s.status, s.waiting_for = "working", "busy", None
262
+ s.scenario = "ok"
263
+ s.step = max(0, s.step - 2)
264
+ s.next_at = time.time() + self._delay()
265
+ s.log.append("↻ Respawned")
266
+ return CommandResult(True, f"respawned {s.id}")
267
+
268
+ async def remove(self, agent_id: str, env: dict[str, str]) -> CommandResult:
269
+ s = self._find(agent_id)
270
+ if not s:
271
+ return CommandResult(False, f"No session matching '{agent_id}'.")
272
+ self._sims = {k: v for k, v in self._sims.items() if v is not s}
273
+ return CommandResult(True, f"removed {s.id}")
274
+
275
+ def attach_argv(self, agent_id: str) -> list[str] | None:
276
+ return None