aiui-code 0.1.1__tar.gz → 0.1.2__tar.gz

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 (31) hide show
  1. {aiui_code-0.1.1 → aiui_code-0.1.2}/PKG-INFO +34 -1
  2. {aiui_code-0.1.1 → aiui_code-0.1.2}/README.md +33 -0
  3. {aiui_code-0.1.1 → aiui_code-0.1.2}/pyproject.toml +1 -1
  4. {aiui_code-0.1.1 → aiui_code-0.1.2}/src/aiui_code/__init__.py +1 -1
  5. aiui_code-0.1.2/src/aiui_code/cli_control.py +486 -0
  6. aiui_code-0.1.2/src/aiui_code/client.py +269 -0
  7. aiui_code-0.1.2/src/aiui_code/mcp_server.py +743 -0
  8. {aiui_code-0.1.1 → aiui_code-0.1.2}/src/aiui_code/routes.py +44 -0
  9. {aiui_code-0.1.1 → aiui_code-0.1.2}/src/aiui_code/server.py +3 -0
  10. aiui_code-0.1.2/src/aiui_code/static/code.css +1 -0
  11. {aiui_code-0.1.1 → aiui_code-0.1.2}/src/aiui_code/static/code.js +507 -488
  12. {aiui_code-0.1.1 → aiui_code-0.1.2}/src/aiui_code/workspaces.py +35 -4
  13. aiui_code-0.1.2/tests/test_cli_and_mcp.py +246 -0
  14. aiui_code-0.1.1/src/aiui_code/static/code.css +0 -1
  15. {aiui_code-0.1.1 → aiui_code-0.1.2}/.gitignore +0 -0
  16. {aiui_code-0.1.1 → aiui_code-0.1.2}/LICENSE +0 -0
  17. {aiui_code-0.1.1 → aiui_code-0.1.2}/src/aiui_code/approvals.py +0 -0
  18. {aiui_code-0.1.1 → aiui_code-0.1.2}/src/aiui_code/checkpoints.py +0 -0
  19. {aiui_code-0.1.1 → aiui_code-0.1.2}/src/aiui_code/events.py +0 -0
  20. {aiui_code-0.1.1 → aiui_code-0.1.2}/src/aiui_code/git_diff.py +0 -0
  21. {aiui_code-0.1.1 → aiui_code-0.1.2}/src/aiui_code/plugin.py +0 -0
  22. {aiui_code-0.1.1 → aiui_code-0.1.2}/src/aiui_code/pty_service.py +0 -0
  23. {aiui_code-0.1.1 → aiui_code-0.1.2}/src/aiui_code/runner.py +0 -0
  24. {aiui_code-0.1.1 → aiui_code-0.1.2}/src/aiui_code/security.py +0 -0
  25. {aiui_code-0.1.1 → aiui_code-0.1.2}/src/aiui_code/worktrees.py +0 -0
  26. {aiui_code-0.1.1 → aiui_code-0.1.2}/tests/conftest.py +0 -0
  27. {aiui_code-0.1.1 → aiui_code-0.1.2}/tests/test_browser_e2e.py +0 -0
  28. {aiui_code-0.1.1 → aiui_code-0.1.2}/tests/test_plugin_contract.py +0 -0
  29. {aiui_code-0.1.1 → aiui_code-0.1.2}/tests/test_runner_and_approvals.py +0 -0
  30. {aiui_code-0.1.1 → aiui_code-0.1.2}/tests/test_security.py +0 -0
  31. {aiui_code-0.1.1 → aiui_code-0.1.2}/tests/test_workspaces_and_diff.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aiui-code
3
- Version: 0.1.1
3
+ Version: 0.1.2
4
4
  Summary: Multi-agent coding workspace Web UI plugin for PraisonAIUI (aiui)
5
5
  Project-URL: Homepage, https://github.com/MervinPraison/aiui-code
6
6
  Project-URL: Repository, https://github.com/MervinPraison/aiui-code
@@ -67,6 +67,39 @@ List detected engines:
67
67
  aiui code engines
68
68
  ```
69
69
 
70
+ ## Full CLI Parity (Control the Live Dashboard)
71
+
72
+ Every dashboard action is available via `aiui code ...` or `aiui-code ...` (supports `--url`, `--token`, and `--json`):
73
+
74
+ ```bash
75
+ aiui code status
76
+ aiui code workspaces list
77
+ aiui code workspaces add /path/to/another/repo
78
+ aiui code runs start <ws_id> "Add unit tests for auth" --engine praisonai --mode safe --focus
79
+ aiui code runs watch <run_id>
80
+ aiui code runs steer <run_id> "Use pytest fixtures instead"
81
+ aiui code runs message <run_id> "Address review" --comment "app.py:12:Handle None input"
82
+ aiui code diff <run_id> --patch
83
+ aiui code commit <run_id> -m "feat: add auth tests"
84
+ aiui code merge <run_id>
85
+ aiui code approvals list --status pending
86
+ aiui code approvals approve <approval_id>
87
+ aiui code ui --run <run_id> --tab diff # Live-control the open browser dashboard
88
+ ```
89
+
90
+ ## MCP Server (Let Any Agent Control the Dashboard)
91
+
92
+ `aiui-code` exposes **23 MCP tools** and **4 live resources** (`code://status`, `code://workspaces`, `code://runs`, `code://approvals`) over **both** transports:
93
+
94
+ 1. **Stdio MCP** (`aiui code mcp` / `aiui-code mcp`) — for Antigravity, Claude Desktop, Claude Code, Cursor, Codex:
95
+ ```bash
96
+ aiui code mcp-config --transport stdio
97
+ ```
98
+ 2. **Embedded HTTP MCP** (`POST http://127.0.0.1:8766/api/plugins/code/mcp`) — mounted directly on the running dashboard behind PraisonAIUI's auth/origin guards:
99
+ ```bash
100
+ aiui code mcp-config --transport http
101
+ ```
102
+
70
103
  ## Development
71
104
 
72
105
  ```bash
@@ -34,6 +34,39 @@ List detected engines:
34
34
  aiui code engines
35
35
  ```
36
36
 
37
+ ## Full CLI Parity (Control the Live Dashboard)
38
+
39
+ Every dashboard action is available via `aiui code ...` or `aiui-code ...` (supports `--url`, `--token`, and `--json`):
40
+
41
+ ```bash
42
+ aiui code status
43
+ aiui code workspaces list
44
+ aiui code workspaces add /path/to/another/repo
45
+ aiui code runs start <ws_id> "Add unit tests for auth" --engine praisonai --mode safe --focus
46
+ aiui code runs watch <run_id>
47
+ aiui code runs steer <run_id> "Use pytest fixtures instead"
48
+ aiui code runs message <run_id> "Address review" --comment "app.py:12:Handle None input"
49
+ aiui code diff <run_id> --patch
50
+ aiui code commit <run_id> -m "feat: add auth tests"
51
+ aiui code merge <run_id>
52
+ aiui code approvals list --status pending
53
+ aiui code approvals approve <approval_id>
54
+ aiui code ui --run <run_id> --tab diff # Live-control the open browser dashboard
55
+ ```
56
+
57
+ ## MCP Server (Let Any Agent Control the Dashboard)
58
+
59
+ `aiui-code` exposes **23 MCP tools** and **4 live resources** (`code://status`, `code://workspaces`, `code://runs`, `code://approvals`) over **both** transports:
60
+
61
+ 1. **Stdio MCP** (`aiui code mcp` / `aiui-code mcp`) — for Antigravity, Claude Desktop, Claude Code, Cursor, Codex:
62
+ ```bash
63
+ aiui code mcp-config --transport stdio
64
+ ```
65
+ 2. **Embedded HTTP MCP** (`POST http://127.0.0.1:8766/api/plugins/code/mcp`) — mounted directly on the running dashboard behind PraisonAIUI's auth/origin guards:
66
+ ```bash
67
+ aiui code mcp-config --transport http
68
+ ```
69
+
37
70
  ## Development
38
71
 
39
72
  ```bash
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "aiui-code"
7
- version = "0.1.1"
7
+ version = "0.1.2"
8
8
  description = "Multi-agent coding workspace Web UI plugin for PraisonAIUI (aiui)"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- __version__ = "0.1.1"
5
+ __version__ = "0.1.2"
6
6
  __all__ = ["CodePlugin", "__version__", "plugin"]
7
7
 
8
8
 
@@ -0,0 +1,486 @@
1
+ """Full CLI parity commands for controlling a running aiui-code dashboard and MCP server."""
2
+
3
+ # ruff: noqa: UP045 — Optional[...] is required for Typer 0.9-0.12 runtime type inspection.
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import time
9
+ from typing import Any, Optional
10
+
11
+ import typer
12
+
13
+ from aiui_code.client import CodeClient, CodeClientError
14
+
15
+
16
+ def _make_client(url: Optional[str], token: Optional[str]) -> CodeClient:
17
+ try:
18
+ return CodeClient(base_url=url, token=token)
19
+ except ValueError as exc:
20
+ typer.echo(f"Error: {exc}", err=True)
21
+ raise typer.Exit(1) from exc
22
+
23
+
24
+ def _emit(data: Any, as_json: bool, summary: str | None = None) -> None:
25
+ if as_json or summary is None:
26
+ typer.echo(json.dumps(data, indent=2))
27
+ else:
28
+ typer.echo(summary)
29
+
30
+
31
+ def _run_or_exit(fn):
32
+ try:
33
+ return fn()
34
+ except CodeClientError as exc:
35
+ typer.echo(f"Error: {exc}", err=True)
36
+ raise typer.Exit(1) from exc
37
+
38
+
39
+ def _parse_comment(spec: str) -> dict[str, Any]:
40
+ """Parse ``path:line:body`` or ``path:body`` into an inline diff comment dict."""
41
+ parts = spec.split(":", 2)
42
+ if len(parts) == 3 and parts[1].isdigit():
43
+ return {"path": parts[0].strip(), "line": int(parts[1]), "side": "new", "body": parts[2].strip()}
44
+ if len(parts) >= 2:
45
+ return {"path": parts[0].strip(), "side": "new", "body": ":".join(parts[1:]).strip()}
46
+ raise typer.BadParameter(f"Invalid --comment {spec!r}; expected 'path:line:comment'")
47
+
48
+
49
+ def attach_control_commands(cli: typer.Typer) -> None:
50
+ """Register full dashboard control + MCP subcommands on the `aiui code` / `aiui-code` CLI."""
51
+
52
+ url_opt = typer.Option(None, "--url", envvar="AIUI_CODE_URL", help="Dashboard URL (default: http://127.0.0.1:8766).")
53
+ token_opt = typer.Option(None, "--token", envvar="AIUI_CODE_TOKEN", help="Bearer auth token if server requires auth.")
54
+ json_opt = typer.Option(False, "--json", help="Emit raw JSON output.")
55
+
56
+ @cli.command()
57
+ def status(url: Optional[str] = url_opt, token: Optional[str] = token_opt, as_json: bool = json_opt) -> None:
58
+ """Show live dashboard status (workspaces, runs, pending approvals, terminal)."""
59
+ client = _make_client(url, token)
60
+ data = _run_or_exit(client.health)
61
+ summary = (
62
+ f"status={data.get('status')} workspaces={data.get('workspaces')} "
63
+ f"runs={data.get('runs')} pending_approvals={data.get('pending_approvals')} "
64
+ f"terminal={'on' if data.get('terminal_enabled') else 'off'}"
65
+ )
66
+ _emit(data, as_json, summary)
67
+
68
+ # --- Workspaces ---
69
+ ws_app = typer.Typer(help="Manage workspaces registered in the live dashboard.", add_completion=False)
70
+ cli.add_typer(ws_app, name="workspaces")
71
+
72
+ @ws_app.command("list")
73
+ def ws_list(url: Optional[str] = url_opt, token: Optional[str] = token_opt, as_json: bool = json_opt) -> None:
74
+ """List registered workspaces."""
75
+ client = _make_client(url, token)
76
+ data = _run_or_exit(client.list_workspaces)
77
+ lines = [
78
+ f"{w['id']} {w['name']} ({w.get('branch') or 'no-git'}) {w['path']}"
79
+ for w in data.get("workspaces", [])
80
+ ]
81
+ _emit(data, as_json, "\n".join(lines) or "(no workspaces)")
82
+
83
+ @ws_app.command("add")
84
+ def ws_add(
85
+ path: str = typer.Argument(..., help="Directory path to register."),
86
+ name: Optional[str] = typer.Option(None, "--name", help="Optional display name."),
87
+ url: Optional[str] = url_opt,
88
+ token: Optional[str] = token_opt,
89
+ as_json: bool = json_opt,
90
+ ) -> None:
91
+ """Add a local workspace folder to the dashboard."""
92
+ client = _make_client(url, token)
93
+ data = _run_or_exit(lambda: client.add_workspace(path, name=name))
94
+ _emit(data, as_json, f"Added workspace {data['id']} ({data['name']} → {data['path']})")
95
+
96
+ @ws_app.command("remove")
97
+ def ws_remove(
98
+ workspace_id: str = typer.Argument(..., help="Workspace ID to remove."),
99
+ url: Optional[str] = url_opt,
100
+ token: Optional[str] = token_opt,
101
+ as_json: bool = json_opt,
102
+ ) -> None:
103
+ """Remove a workspace from the dashboard."""
104
+ client = _make_client(url, token)
105
+ data = _run_or_exit(lambda: client.remove_workspace(workspace_id))
106
+ _emit(data, as_json, f"Removed workspace {workspace_id}")
107
+
108
+ @ws_app.command("files")
109
+ def ws_files(
110
+ workspace_id: str = typer.Argument(..., help="Workspace ID."),
111
+ rel_dir: str = typer.Option(".", "--dir", help="Relative subdirectory."),
112
+ url: Optional[str] = url_opt,
113
+ token: Optional[str] = token_opt,
114
+ as_json: bool = json_opt,
115
+ ) -> None:
116
+ """List non-ignored files in a workspace."""
117
+ client = _make_client(url, token)
118
+ data = _run_or_exit(lambda: client.list_files(workspace_id, rel_dir=rel_dir))
119
+ lines = [f["path"] for f in data.get("files", [])]
120
+ _emit(data, as_json, "\n".join(lines) or "(no files)")
121
+
122
+ # --- Runs ---
123
+ runs_app = typer.Typer(help="Start, inspect, message, steer, stop, and watch coding runs.", add_completion=False)
124
+ cli.add_typer(runs_app, name="runs")
125
+
126
+ @runs_app.command("list")
127
+ def runs_list(
128
+ workspace_id: Optional[str] = typer.Option(None, "--workspace", "-w", help="Filter by workspace ID."),
129
+ url: Optional[str] = url_opt,
130
+ token: Optional[str] = token_opt,
131
+ as_json: bool = json_opt,
132
+ ) -> None:
133
+ """List active and past runs."""
134
+ client = _make_client(url, token)
135
+ data = _run_or_exit(lambda: client.list_runs(workspace_id=workspace_id))
136
+ lines = [
137
+ f"{r['id']} [{r['status']}] {r['engine']}/{r['mode']} "
138
+ f"+{r.get('additions', 0)}/-{r.get('deletions', 0)} {r['title']}"
139
+ for r in data.get("runs", [])
140
+ ]
141
+ _emit(data, as_json, "\n".join(lines) or "(no runs)")
142
+
143
+ @runs_app.command("start")
144
+ def runs_start(
145
+ workspace_id: str = typer.Argument(..., help="Workspace ID."),
146
+ prompt: str = typer.Argument(..., help="Task prompt for the coding agent."),
147
+ engine: str = typer.Option("praisonai", "--engine", "-e", help="Engine (praisonai, claude-code, codex-cli, gemini-cli, grok-cli, mock)."),
148
+ model: str = typer.Option("", "--model", "-m", help="Optional model override."),
149
+ mode: str = typer.Option("safe", "--mode", help="Execution mode: safe, plan, or auto."),
150
+ worktree: bool = typer.Option(True, "--worktree/--no-worktree", help="Isolate run in a git worktree."),
151
+ title: str = typer.Option("", "--title", help="Optional run title."),
152
+ focus: bool = typer.Option(False, "--focus", help="Focus the newly started run in the open browser dashboard."),
153
+ url: Optional[str] = url_opt,
154
+ token: Optional[str] = token_opt,
155
+ as_json: bool = json_opt,
156
+ ) -> None:
157
+ """Start a new coding agent run in the dashboard."""
158
+ client = _make_client(url, token)
159
+ data = _run_or_exit(
160
+ lambda: client.start_run(
161
+ workspace_id=workspace_id,
162
+ prompt=prompt,
163
+ engine=engine,
164
+ model=model,
165
+ mode=mode,
166
+ worktree=worktree,
167
+ title=title,
168
+ )
169
+ )
170
+ if focus and data.get("id"):
171
+ _run_or_exit(lambda: client.ui_control(run_id=data["id"]))
172
+ _emit(data, as_json, f"Started {data['id']} ({data['engine']}/{data['mode']}, branch={data.get('branch') or '-'})")
173
+
174
+ @runs_app.command("show")
175
+ def runs_show(
176
+ run_id: str = typer.Argument(..., help="Run ID."),
177
+ url: Optional[str] = url_opt,
178
+ token: Optional[str] = token_opt,
179
+ as_json: bool = json_opt,
180
+ ) -> None:
181
+ """Show run details and event history."""
182
+ client = _make_client(url, token)
183
+ data = _run_or_exit(lambda: client.get_run(run_id))
184
+ run = data.get("run", {})
185
+ events = data.get("events", [])
186
+ lines = [
187
+ f"{run.get('id')} [{run.get('status')}] {run.get('engine')}/{run.get('mode')} branch={run.get('branch') or '-'}",
188
+ f"cwd: {run.get('cwd')}",
189
+ f"diff: {run.get('changed_files', 0)} files (+{run.get('additions', 0)}/-{run.get('deletions', 0)})",
190
+ f"events: {len(events)}",
191
+ ]
192
+ for ev in events[-10:]:
193
+ lines.append(f" #{ev.get('seq')} {ev.get('type')}: {json.dumps(ev.get('payload', {}))[:140]}")
194
+ _emit(data, as_json, "\n".join(lines))
195
+
196
+ @runs_app.command("message")
197
+ def runs_message(
198
+ run_id: str = typer.Argument(..., help="Run ID."),
199
+ text: str = typer.Argument("", help="Follow-up message text."),
200
+ mode: Optional[str] = typer.Option(None, "--mode", help="Optionally switch run mode (e.g. safe to execute a plan)."),
201
+ comment: Optional[list[str]] = typer.Option(
202
+ None,
203
+ "--comment",
204
+ "-c",
205
+ help="Inline diff comment as 'path:line:body' (repeatable).",
206
+ ),
207
+ url: Optional[str] = url_opt,
208
+ token: Optional[str] = token_opt,
209
+ as_json: bool = json_opt,
210
+ ) -> None:
211
+ """Send a follow-up message or inline diff review comments to a run."""
212
+ client = _make_client(url, token)
213
+ parsed = [_parse_comment(c) for c in (comment or [])]
214
+ data = _run_or_exit(lambda: client.send_message(run_id, text, line_comments=parsed or None, mode=mode))
215
+ _emit(data, as_json, f"Sent message to {data['id']} (status={data['status']}, mode={data['mode']})")
216
+
217
+ @runs_app.command("steer")
218
+ def runs_steer(
219
+ run_id: str = typer.Argument(..., help="Run ID."),
220
+ instruction: str = typer.Argument(..., help="Mid-flight steering instruction."),
221
+ url: Optional[str] = url_opt,
222
+ token: Optional[str] = token_opt,
223
+ as_json: bool = json_opt,
224
+ ) -> None:
225
+ """Queue a mid-flight steering instruction on a running agent."""
226
+ client = _make_client(url, token)
227
+ data = _run_or_exit(lambda: client.steer(run_id, instruction))
228
+ _emit(data, as_json, f"Steered {run_id} (queued={data.get('queued')})")
229
+
230
+ @runs_app.command("stop")
231
+ def runs_stop(
232
+ run_id: str = typer.Argument(..., help="Run ID."),
233
+ url: Optional[str] = url_opt,
234
+ token: Optional[str] = token_opt,
235
+ as_json: bool = json_opt,
236
+ ) -> None:
237
+ """Interrupt/stop a running agent."""
238
+ client = _make_client(url, token)
239
+ data = _run_or_exit(lambda: client.interrupt(run_id))
240
+ _emit(data, as_json, f"Interrupted {run_id}")
241
+
242
+ @runs_app.command("watch")
243
+ def runs_watch(
244
+ run_id: str = typer.Argument(..., help="Run ID to tail until terminal state."),
245
+ poll_interval: float = typer.Option(0.5, "--interval", help="Polling interval in seconds."),
246
+ timeout: float = typer.Option(300.0, "--timeout", help="Max seconds to wait."),
247
+ url: Optional[str] = url_opt,
248
+ token: Optional[str] = token_opt,
249
+ ) -> None:
250
+ """Stream run events to the terminal until the run finishes."""
251
+ client = _make_client(url, token)
252
+ seen_seq = 0
253
+ deadline = time.monotonic() + timeout
254
+ while time.monotonic() < deadline:
255
+ data = _run_or_exit(lambda: client.get_run(run_id))
256
+ for ev in data.get("events", []):
257
+ seq = int(ev.get("seq", 0))
258
+ if seq > seen_seq:
259
+ seen_seq = seq
260
+ typer.echo(f"[#{seq} {ev.get('type')}] {json.dumps(ev.get('payload', {}))}")
261
+ run_status = str(data.get("run", {}).get("status") or "")
262
+ if run_status in {"completed", "failed", "interrupted"}:
263
+ if run_status == "failed":
264
+ raise typer.Exit(1)
265
+ return
266
+ time.sleep(max(0.1, poll_interval))
267
+ typer.echo(f"Timed out waiting for {run_id}", err=True)
268
+ raise typer.Exit(1)
269
+
270
+ # --- Diff, Git & OpenShip ---
271
+ @cli.command()
272
+ def diff(
273
+ run_id: str = typer.Argument(..., help="Run ID."),
274
+ patch: bool = typer.Option(False, "--patch", "-p", help="Print full unified patch text."),
275
+ url: Optional[str] = url_opt,
276
+ token: Optional[str] = token_opt,
277
+ as_json: bool = json_opt,
278
+ ) -> None:
279
+ """Show changed files and unified diffs for a run."""
280
+ client = _make_client(url, token)
281
+ data = _run_or_exit(lambda: client.diff(run_id))
282
+ if as_json:
283
+ _emit(data, True)
284
+ return
285
+ lines = [f"branch={data.get('branch') or '-'} +{data.get('additions', 0)}/-{data.get('deletions', 0)}"]
286
+ for f in data.get("files", []):
287
+ lines.append(f" {f['path']} (+{f.get('additions', 0)}/-{f.get('deletions', 0)})")
288
+ if patch and f.get("patch"):
289
+ lines.append(f["patch"])
290
+ typer.echo("\n".join(lines))
291
+
292
+ @cli.command()
293
+ def commit(
294
+ run_id: str = typer.Argument(..., help="Run ID."),
295
+ message: str = typer.Option(..., "--message", "-m", help="Commit message."),
296
+ url: Optional[str] = url_opt,
297
+ token: Optional[str] = token_opt,
298
+ as_json: bool = json_opt,
299
+ ) -> None:
300
+ """Commit changes in a run's workspace/worktree."""
301
+ client = _make_client(url, token)
302
+ data = _run_or_exit(lambda: client.commit(run_id, message))
303
+ _emit(data, as_json, f"Committed {data.get('sha')} in {run_id}")
304
+
305
+ @cli.command()
306
+ def merge(
307
+ run_id: str = typer.Argument(..., help="Run ID."),
308
+ target: Optional[str] = typer.Option(None, "--target", help="Optional target branch."),
309
+ url: Optional[str] = url_opt,
310
+ token: Optional[str] = token_opt,
311
+ as_json: bool = json_opt,
312
+ ) -> None:
313
+ """Merge a run's isolated worktree branch back into its repo."""
314
+ client = _make_client(url, token)
315
+ data = _run_or_exit(lambda: client.merge_worktree(run_id, target_branch=target))
316
+ _emit(data, as_json, f"Merged worktree branch {data.get('branch')}")
317
+
318
+ @cli.command()
319
+ def discard(
320
+ run_id: str = typer.Argument(..., help="Run ID."),
321
+ url: Optional[str] = url_opt,
322
+ token: Optional[str] = token_opt,
323
+ as_json: bool = json_opt,
324
+ ) -> None:
325
+ """Discard a run's isolated worktree."""
326
+ client = _make_client(url, token)
327
+ data = _run_or_exit(lambda: client.discard_worktree(run_id))
328
+ _emit(data, as_json, f"Discarded worktree for {run_id}")
329
+
330
+ @cli.command()
331
+ def review(
332
+ run_id: str = typer.Argument(..., help="Run ID."),
333
+ url: Optional[str] = url_opt,
334
+ token: Optional[str] = token_opt,
335
+ as_json: bool = json_opt,
336
+ ) -> None:
337
+ """Run OpenShip self-review for a run."""
338
+ client = _make_client(url, token)
339
+ data = _run_or_exit(lambda: client.openship_review(run_id))
340
+ _emit(data, True if as_json else False, json.dumps(data, indent=2))
341
+
342
+ @cli.command("draft-pr")
343
+ def draft_pr(
344
+ run_id: str = typer.Argument(..., help="Run ID."),
345
+ title: str = typer.Option("", "--title", help="PR title."),
346
+ body: str = typer.Option("", "--body", help="PR body."),
347
+ url: Optional[str] = url_opt,
348
+ token: Optional[str] = token_opt,
349
+ as_json: bool = json_opt,
350
+ ) -> None:
351
+ """Create an OpenShip Draft PR for a run (never auto-merges)."""
352
+ client = _make_client(url, token)
353
+ data = _run_or_exit(lambda: client.openship_draft_pr(run_id, title=title, body=body))
354
+ _emit(data, as_json, json.dumps(data, indent=2))
355
+
356
+ # --- Checkpoints ---
357
+ cp_app = typer.Typer(help="List and restore file-level checkpoints.", add_completion=False)
358
+ cli.add_typer(cp_app, name="checkpoints")
359
+
360
+ @cp_app.command("list")
361
+ def cp_list(
362
+ run_id: str = typer.Argument(..., help="Run ID."),
363
+ url: Optional[str] = url_opt,
364
+ token: Optional[str] = token_opt,
365
+ as_json: bool = json_opt,
366
+ ) -> None:
367
+ """List saved checkpoints for a run."""
368
+ client = _make_client(url, token)
369
+ data = _run_or_exit(lambda: client.list_checkpoints(run_id))
370
+ lines = [f"{c['id']} {c.get('message', '')}" for c in data.get("checkpoints", [])]
371
+ _emit(data, as_json, "\n".join(lines) or "(no checkpoints)")
372
+
373
+ @cp_app.command("restore")
374
+ def cp_restore(
375
+ run_id: str = typer.Argument(..., help="Run ID."),
376
+ checkpoint_id: str = typer.Argument(..., help="Checkpoint ID."),
377
+ url: Optional[str] = url_opt,
378
+ token: Optional[str] = token_opt,
379
+ as_json: bool = json_opt,
380
+ ) -> None:
381
+ """Restore workspace/worktree files to a saved checkpoint."""
382
+ client = _make_client(url, token)
383
+ data = _run_or_exit(lambda: client.restore_checkpoint(run_id, checkpoint_id))
384
+ _emit(data, as_json, f"Restored checkpoint {checkpoint_id} on {run_id}")
385
+
386
+ # --- Approvals / Agent Inbox ---
387
+ apr_app = typer.Typer(help="Inspect and resolve Agent Inbox approval requests.", add_completion=False)
388
+ cli.add_typer(apr_app, name="approvals")
389
+
390
+ @apr_app.command("list")
391
+ def apr_list(
392
+ status_filter: Optional[str] = typer.Option(None, "--status", help="Filter by status (pending, approved, denied)."),
393
+ url: Optional[str] = url_opt,
394
+ token: Optional[str] = token_opt,
395
+ as_json: bool = json_opt,
396
+ ) -> None:
397
+ """List approval requests in the Agent Inbox."""
398
+ client = _make_client(url, token)
399
+ data = _run_or_exit(lambda: client.list_approvals(status=status_filter))
400
+ lines = [
401
+ f"{a['id']} [{a['status']}] {a['risk_level']} {a['tool_name']} (run={a['run_id']})"
402
+ for a in data.get("approvals", [])
403
+ ]
404
+ _emit(data, as_json, "\n".join(lines) or "(no approvals)")
405
+
406
+ @apr_app.command("approve")
407
+ def apr_approve(
408
+ approval_id: str = typer.Argument(..., help="Approval ID."),
409
+ always: bool = typer.Option(False, "--always", help="Persist narrow allow rule outside the repo."),
410
+ feedback: str = typer.Option("", "--feedback", help="Optional note."),
411
+ url: Optional[str] = url_opt,
412
+ token: Optional[str] = token_opt,
413
+ as_json: bool = json_opt,
414
+ ) -> None:
415
+ """Approve a pending Agent Inbox request."""
416
+ client = _make_client(url, token)
417
+ scope = "always" if always else "once"
418
+ data = _run_or_exit(lambda: client.resolve_approval(approval_id, approved=True, scope=scope, feedback=feedback))
419
+ _emit(data, as_json, f"Approved {approval_id} (scope={scope})")
420
+
421
+ @apr_app.command("deny")
422
+ def apr_deny(
423
+ approval_id: str = typer.Argument(..., help="Approval ID."),
424
+ feedback: str = typer.Option("", "--feedback", help="Optional steering note."),
425
+ url: Optional[str] = url_opt,
426
+ token: Optional[str] = token_opt,
427
+ as_json: bool = json_opt,
428
+ ) -> None:
429
+ """Deny a pending Agent Inbox request."""
430
+ client = _make_client(url, token)
431
+ data = _run_or_exit(lambda: client.resolve_approval(approval_id, approved=False, scope="once", feedback=feedback))
432
+ _emit(data, as_json, f"Denied {approval_id}")
433
+
434
+ # --- Live Dashboard UI Remote Control ---
435
+ @cli.command("ui")
436
+ def ui_control_cmd(
437
+ run: Optional[str] = typer.Option(None, "--run", help="Focus run ID in the main pane."),
438
+ split: Optional[str] = typer.Option(None, "--split", help="Open run ID in side-by-side split pane."),
439
+ clear_split: bool = typer.Option(False, "--clear-split", help="Close side-by-side split pane."),
440
+ tab: Optional[str] = typer.Option(None, "--tab", help="Switch right pane tab: diff, inbox, or terminal."),
441
+ new_run: bool = typer.Option(False, "--new-run", help="Open the New Agent Run modal."),
442
+ workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Pre-select workspace ID for --new-run."),
443
+ refresh: bool = typer.Option(False, "--refresh", help="Trigger live data refresh in the browser."),
444
+ url: Optional[str] = url_opt,
445
+ token: Optional[str] = token_opt,
446
+ as_json: bool = json_opt,
447
+ ) -> None:
448
+ """Control the live open browser dashboard from the CLI."""
449
+ client = _make_client(url, token)
450
+ data = _run_or_exit(
451
+ lambda: client.ui_control(
452
+ run_id=run,
453
+ split_run_id=split,
454
+ clear_split=clear_split,
455
+ tab=tab,
456
+ open_new_run=new_run,
457
+ workspace_id=workspace,
458
+ refresh=refresh,
459
+ )
460
+ )
461
+ _emit(data, as_json, f"Dispatched live UI control: {json.dumps(data.get('control', {}))}")
462
+
463
+ # --- MCP Server (stdio) & Client Config ---
464
+ @cli.command()
465
+ def mcp(
466
+ url: Optional[str] = url_opt,
467
+ token: Optional[str] = token_opt,
468
+ ) -> None:
469
+ """Start the MCP stdio server so external agents can control the live dashboard."""
470
+ from aiui_code.mcp_server import run_stdio_server
471
+
472
+ client = _make_client(url, token)
473
+ run_stdio_server(client)
474
+
475
+ @cli.command("mcp-config")
476
+ def mcp_config_cmd(
477
+ url: Optional[str] = url_opt,
478
+ token: Optional[str] = token_opt,
479
+ transport: str = typer.Option("stdio", "--transport", help="Transport: stdio or http."),
480
+ ) -> None:
481
+ """Print ready-to-paste MCP client config JSON (Antigravity, Claude, Cursor, Codex)."""
482
+ from aiui_code.mcp_server import mcp_client_config
483
+
484
+ if transport not in {"stdio", "http"}:
485
+ raise typer.BadParameter("transport must be 'stdio' or 'http'")
486
+ typer.echo(json.dumps(mcp_client_config(url=url, token=token, transport=transport), indent=2))