aiui-code 0.1.0__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.
@@ -0,0 +1,11 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .venv/
7
+ dist/
8
+ build/
9
+ frontend/node_modules/
10
+ frontend/dist/
11
+ .DS_Store
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mervin Praison
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: aiui-code
3
+ Version: 0.1.0
4
+ Summary: Multi-agent coding workspace Web UI plugin for PraisonAIUI (aiui)
5
+ Project-URL: Homepage, https://github.com/MervinPraison/aiui-code
6
+ Project-URL: Repository, https://github.com/MervinPraison/aiui-code
7
+ Project-URL: Documentation, https://github.com/MervinPraison/PraisonAIUI/blob/main/docs/features/plugins.md
8
+ Project-URL: Issues, https://github.com/MervinPraison/aiui-code/issues
9
+ Author: Mervin Praison
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: aiui,coding-agent,diff-review,plugin,praisonai,praisonaiui,worktree
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Software Development :: User Interfaces
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: aiui>=0.3.197
23
+ Requires-Dist: starlette>=0.37
24
+ Requires-Dist: typer>=0.9
25
+ Provides-Extra: code
26
+ Requires-Dist: praisonai-code>=0.2.0; extra == 'code'
27
+ Provides-Extra: dev
28
+ Requires-Dist: httpx>=0.27; extra == 'dev'
29
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
30
+ Requires-Dist: pytest>=8.0; extra == 'dev'
31
+ Requires-Dist: ruff>=0.6; extra == 'dev'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # `aiui-code` — PraisonAI Code Web UI Plugin
35
+
36
+ Standalone multi-agent coding workspace Web UI plugin for [PraisonAIUI (`aiui`)](https://ui.praison.ai). Plugs dynamically into `PraisonAIUI` via Python entry points (`praisonaiui.plugins`) with **zero UI code in `praisonaiagents` or `praisonai-code`** and **zero coding-domain bloat in `aiui`**.
37
+
38
+ ## Features
39
+
40
+ - **Workspaces → Parallel Agent Runs:** Register multiple local folders/repos, launch concurrent runs, and `Cmd/Ctrl`-click a second run for **2-pane split comparison**.
41
+ - **Isolated Git Worktrees:** Automatic per-run `.praisonai/worktrees/<slug>` isolation (backed lazily by `praisonaiagents.GitWorktreeAdapter`) with one-click **Commit**, **Merge Worktree**, and **Discard**.
42
+ - **Live Diff Review + Inline Line Comments:** Unified & side-by-side split diff viewer; click any line to attach inline review comments and press **`Cmd/Ctrl+Enter`** to send structured `file:line` feedback directly back to the agent.
43
+ - **Unified Agent Inbox & Per-Agent Approvals:** Per-agent `WebApprovalBackend` prevents concurrent runs from colliding, syncs to `@aiui/sdk` notifications, and persists narrow "Allow Always" rules strictly outside cloned repos (`~/.praisonai/permissions/`).
44
+ - **Multi-Engine Choice:** PraisonAI Agent (100+ LLMs / Ollama), Claude Code CLI, OpenAI Codex CLI, Gemini CLI, and Grok CLI.
45
+ - **Mid-Flight Steering, Interrupts, Checkpoints & OpenShip:** Steer running agents mid-flight, restore file checkpoints, run OpenShip Self-Review, or open Draft PRs (never auto-merges).
46
+ - **Opt-In Terminal & 390 px Mobile Handoff:** Structured read-only command logs by default; pass `--enable-terminal` for an interactive workspace PTY. Responsive 4-tab layout on mobile.
47
+
48
+ ## Quickstart
49
+
50
+ ```bash
51
+ pip install aiui-code
52
+ aiui code serve --workspace /path/to/your/repo
53
+ # → http://127.0.0.1:8766/code
54
+ ```
55
+
56
+ With authentication for remote/Tailscale access:
57
+
58
+ ```bash
59
+ export GATEWAY_AUTH_TOKEN="your-secret-token"
60
+ export AIUI_REQUIRE_TOKEN=1
61
+ aiui code serve --workspace /path/to/repo --host 0.0.0.0 --port 8766 --require-auth
62
+ ```
63
+
64
+ List detected engines:
65
+
66
+ ```bash
67
+ aiui code engines
68
+ ```
69
+
70
+ ## Development
71
+
72
+ ```bash
73
+ # Frontend (externalizes react & @aiui/sdk)
74
+ cd frontend && npm ci && npm test && npm run build
75
+
76
+ # Backend + plugin contract tests
77
+ pip install -e ".[dev]"
78
+ ruff check src tests
79
+ pytest -v
80
+ ```
@@ -0,0 +1,47 @@
1
+ # `aiui-code` — PraisonAI Code Web UI Plugin
2
+
3
+ Standalone multi-agent coding workspace Web UI plugin for [PraisonAIUI (`aiui`)](https://ui.praison.ai). Plugs dynamically into `PraisonAIUI` via Python entry points (`praisonaiui.plugins`) with **zero UI code in `praisonaiagents` or `praisonai-code`** and **zero coding-domain bloat in `aiui`**.
4
+
5
+ ## Features
6
+
7
+ - **Workspaces → Parallel Agent Runs:** Register multiple local folders/repos, launch concurrent runs, and `Cmd/Ctrl`-click a second run for **2-pane split comparison**.
8
+ - **Isolated Git Worktrees:** Automatic per-run `.praisonai/worktrees/<slug>` isolation (backed lazily by `praisonaiagents.GitWorktreeAdapter`) with one-click **Commit**, **Merge Worktree**, and **Discard**.
9
+ - **Live Diff Review + Inline Line Comments:** Unified & side-by-side split diff viewer; click any line to attach inline review comments and press **`Cmd/Ctrl+Enter`** to send structured `file:line` feedback directly back to the agent.
10
+ - **Unified Agent Inbox & Per-Agent Approvals:** Per-agent `WebApprovalBackend` prevents concurrent runs from colliding, syncs to `@aiui/sdk` notifications, and persists narrow "Allow Always" rules strictly outside cloned repos (`~/.praisonai/permissions/`).
11
+ - **Multi-Engine Choice:** PraisonAI Agent (100+ LLMs / Ollama), Claude Code CLI, OpenAI Codex CLI, Gemini CLI, and Grok CLI.
12
+ - **Mid-Flight Steering, Interrupts, Checkpoints & OpenShip:** Steer running agents mid-flight, restore file checkpoints, run OpenShip Self-Review, or open Draft PRs (never auto-merges).
13
+ - **Opt-In Terminal & 390 px Mobile Handoff:** Structured read-only command logs by default; pass `--enable-terminal` for an interactive workspace PTY. Responsive 4-tab layout on mobile.
14
+
15
+ ## Quickstart
16
+
17
+ ```bash
18
+ pip install aiui-code
19
+ aiui code serve --workspace /path/to/your/repo
20
+ # → http://127.0.0.1:8766/code
21
+ ```
22
+
23
+ With authentication for remote/Tailscale access:
24
+
25
+ ```bash
26
+ export GATEWAY_AUTH_TOKEN="your-secret-token"
27
+ export AIUI_REQUIRE_TOKEN=1
28
+ aiui code serve --workspace /path/to/repo --host 0.0.0.0 --port 8766 --require-auth
29
+ ```
30
+
31
+ List detected engines:
32
+
33
+ ```bash
34
+ aiui code engines
35
+ ```
36
+
37
+ ## Development
38
+
39
+ ```bash
40
+ # Frontend (externalizes react & @aiui/sdk)
41
+ cd frontend && npm ci && npm test && npm run build
42
+
43
+ # Backend + plugin contract tests
44
+ pip install -e ".[dev]"
45
+ ruff check src tests
46
+ pytest -v
47
+ ```
@@ -0,0 +1,77 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.24"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "aiui-code"
7
+ version = "0.1.0"
8
+ description = "Multi-agent coding workspace Web UI plugin for PraisonAIUI (aiui)"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ authors = [{ name = "Mervin Praison" }]
12
+ keywords = ["praisonai", "aiui", "praisonaiui", "coding-agent", "worktree", "diff-review", "plugin"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Intended Audience :: Developers",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Topic :: Software Development :: User Interfaces",
22
+ ]
23
+ requires-python = ">=3.10"
24
+ dependencies = [
25
+ "aiui>=0.3.197",
26
+ "starlette>=0.37",
27
+ "typer>=0.9",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/MervinPraison/aiui-code"
32
+ Repository = "https://github.com/MervinPraison/aiui-code"
33
+ Documentation = "https://github.com/MervinPraison/PraisonAIUI/blob/main/docs/features/plugins.md"
34
+ Issues = "https://github.com/MervinPraison/aiui-code/issues"
35
+
36
+ [project.optional-dependencies]
37
+ code = [
38
+ "praisonai-code>=0.2.0",
39
+ ]
40
+ dev = [
41
+ "pytest>=8.0",
42
+ "pytest-asyncio>=0.23",
43
+ "httpx>=0.27",
44
+ "ruff>=0.6",
45
+ ]
46
+
47
+ [project.entry-points."praisonaiui.plugins"]
48
+ code = "aiui_code.plugin:plugin"
49
+
50
+ [project.scripts]
51
+ aiui-code = "aiui_code.server:main"
52
+
53
+ [tool.hatch.build.targets.wheel]
54
+ packages = ["src/aiui_code"]
55
+ core-metadata-version = "2.4"
56
+
57
+ [tool.hatch.build.targets.sdist]
58
+ core-metadata-version = "2.4"
59
+ include = [
60
+ "/src",
61
+ "/tests",
62
+ "/README.md",
63
+ "/LICENSE",
64
+ "/pyproject.toml",
65
+ ]
66
+
67
+ [tool.ruff]
68
+ line-length = 100
69
+ target-version = "py310"
70
+
71
+ [tool.ruff.lint]
72
+ select = ["E", "F", "I", "UP", "B", "RUF"]
73
+ ignore = ["B008", "E501"]
74
+
75
+ [tool.pytest.ini_options]
76
+ asyncio_mode = "auto"
77
+ testpaths = ["tests"]
@@ -0,0 +1,14 @@
1
+ """aiui-code: Multi-agent coding workspace Web UI plugin for PraisonAIUI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["CodePlugin", "__version__", "plugin"]
7
+
8
+
9
+ def __getattr__(name: str):
10
+ if name in ("CodePlugin", "plugin"):
11
+ from aiui_code.plugin import CodePlugin, plugin
12
+
13
+ return CodePlugin if name == "CodePlugin" else plugin
14
+ raise AttributeError(f"module 'aiui_code' has no attribute {name!r}")
@@ -0,0 +1,214 @@
1
+ """Per-agent approval backend and unified Inbox with repo-untrusted permission storage."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import hashlib
7
+ import uuid
8
+ from dataclasses import asdict, dataclass
9
+ from datetime import datetime, timezone
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from aiui_code.events import RunEventBus
14
+
15
+
16
+ def user_permissions_dir(project_dir: Path | str) -> Path:
17
+ """Resolve per-project permissions strictly outside the repo under ~/.praisonai/permissions."""
18
+ try:
19
+ from praisonai_code.cli.approval_backend import user_permissions_dir as _upstream
20
+
21
+ return Path(_upstream(str(project_dir)))
22
+ except Exception:
23
+ resolved = str(Path(project_dir).expanduser().resolve(strict=False))
24
+ digest = hashlib.sha256(resolved.encode("utf-8")).hexdigest()[:16]
25
+ return Path.home() / ".praisonai" / "permissions" / "projects" / digest
26
+
27
+
28
+ @dataclass
29
+ class PendingApproval:
30
+ id: str
31
+ run_id: str
32
+ workspace_id: str
33
+ tool_name: str
34
+ arguments: dict[str, Any]
35
+ risk_level: str
36
+ diff_preview: str
37
+ created_at: str
38
+ status: str = "pending"
39
+ decision: str = ""
40
+ feedback: str = ""
41
+
42
+ def to_dict(self) -> dict[str, Any]:
43
+ return asdict(self)
44
+
45
+
46
+ class ApprovalInbox:
47
+ """Tracks pending & resolved approvals across all concurrent runs."""
48
+
49
+ def __init__(self, event_bus: RunEventBus) -> None:
50
+ self._events = event_bus
51
+ self._records: dict[str, PendingApproval] = {}
52
+ self._futures: dict[str, asyncio.Future[dict[str, Any]]] = {}
53
+ # Session-scoped narrow allow rules per workspace: (workspace_id, tool_name, scope_pattern)
54
+ self._always_allow: set[tuple[str, str, str]] = set()
55
+
56
+ def list(self, *, status: str | None = None) -> list[dict[str, Any]]:
57
+ items = list(self._records.values())
58
+ if status:
59
+ items = [item for item in items if item.status == status]
60
+ items.sort(key=lambda r: r.created_at, reverse=True)
61
+ return [item.to_dict() for item in items]
62
+
63
+ def get(self, approval_id: str) -> PendingApproval | None:
64
+ return self._records.get(approval_id)
65
+
66
+ async def request(
67
+ self,
68
+ *,
69
+ run_id: str,
70
+ workspace_id: str,
71
+ project_dir: Path | str,
72
+ tool_name: str,
73
+ arguments: dict[str, Any],
74
+ risk_level: str = "medium",
75
+ diff_preview: str = "",
76
+ timeout: float = 300.0,
77
+ ) -> dict[str, Any]:
78
+ pattern = str(arguments.get("command") or arguments.get("path") or tool_name)[:120]
79
+ if risk_level != "critical" and (workspace_id, tool_name, pattern) in self._always_allow:
80
+ return {"approved": True, "scope": "always", "reason": "Matched narrow allow rule"}
81
+
82
+ approval_id = f"apr_{uuid.uuid4().hex[:10]}"
83
+ rec = PendingApproval(
84
+ id=approval_id,
85
+ run_id=run_id,
86
+ workspace_id=workspace_id,
87
+ tool_name=tool_name,
88
+ arguments=dict(arguments),
89
+ risk_level=risk_level,
90
+ diff_preview=diff_preview,
91
+ created_at=datetime.now(timezone.utc).isoformat(),
92
+ )
93
+ loop = asyncio.get_running_loop()
94
+ fut: asyncio.Future[dict[str, Any]] = loop.create_future()
95
+ self._records[approval_id] = rec
96
+ self._futures[approval_id] = fut
97
+
98
+ self._events.publish(run_id, "approval.requested", rec.to_dict())
99
+ try:
100
+ return await asyncio.wait_for(fut, timeout=timeout)
101
+ except asyncio.TimeoutError:
102
+ rec.status = "expired"
103
+ rec.decision = "deny"
104
+ self._futures.pop(approval_id, None)
105
+ self._events.publish(run_id, "approval.resolved", rec.to_dict())
106
+ return {"approved": False, "scope": "once", "reason": "Approval timed out"}
107
+
108
+ def resolve(
109
+ self,
110
+ approval_id: str,
111
+ *,
112
+ approved: bool,
113
+ scope: str = "once",
114
+ feedback: str = "",
115
+ project_dir: Path | str | None = None,
116
+ ) -> PendingApproval:
117
+ rec = self._records.get(approval_id)
118
+ if rec is None:
119
+ raise KeyError(f"Unknown approval: {approval_id!r}")
120
+ if rec.status != "pending":
121
+ return rec
122
+
123
+ rec.status = "approved" if approved else "denied"
124
+ rec.decision = "always" if (approved and scope == "always") else ("once" if approved else "deny")
125
+ rec.feedback = feedback.strip()
126
+
127
+ if approved and scope == "always" and rec.risk_level != "critical":
128
+ pattern = str(rec.arguments.get("command") or rec.arguments.get("path") or rec.tool_name)[:120]
129
+ self._always_allow.add((rec.workspace_id, rec.tool_name, pattern))
130
+ if project_dir is not None:
131
+ self._persist_permission(project_dir, rec.tool_name, pattern)
132
+
133
+ fut = self._futures.pop(approval_id, None)
134
+ if fut is not None and not fut.done():
135
+ fut.set_result(
136
+ {
137
+ "approved": approved,
138
+ "scope": scope,
139
+ "feedback": rec.feedback,
140
+ "reason": rec.feedback or ("Approved in web Inbox" if approved else "Denied in web Inbox"),
141
+ }
142
+ )
143
+ self._events.publish(rec.run_id, "approval.resolved", rec.to_dict())
144
+ return rec
145
+
146
+ @staticmethod
147
+ def _persist_permission(project_dir: Path | str, tool_name: str, pattern: str) -> None:
148
+ """Persist narrow allow rule outside the repo via PermissionManager when installed."""
149
+ try:
150
+ from praisonaiagents.permissions import PermissionManager
151
+
152
+ storage = user_permissions_dir(project_dir)
153
+ storage.mkdir(parents=True, exist_ok=True)
154
+ pm = PermissionManager(storage_dir=str(storage))
155
+ if hasattr(pm, "allow"):
156
+ pm.allow(tool_name, pattern)
157
+ except Exception:
158
+ pass
159
+
160
+ def cancel_for_run(self, run_id: str) -> None:
161
+ for apr_id, rec in list(self._records.items()):
162
+ if rec.run_id == run_id and rec.status == "pending":
163
+ rec.status = "cancelled"
164
+ rec.decision = "deny"
165
+ fut = self._futures.pop(apr_id, None)
166
+ if fut is not None and not fut.done():
167
+ fut.set_result({"approved": False, "scope": "once", "reason": "Run cancelled"})
168
+
169
+
170
+ class WebApprovalBackend:
171
+ """Adapter compatible with praisonaiagents.approval.ApprovalRegistry.set_backend()."""
172
+
173
+ def __init__(
174
+ self,
175
+ inbox: ApprovalInbox,
176
+ *,
177
+ run_id: str,
178
+ workspace_id: str,
179
+ project_dir: Path | str,
180
+ loop: asyncio.AbstractEventLoop | None = None,
181
+ ) -> None:
182
+ self._inbox = inbox
183
+ self._run_id = run_id
184
+ self._workspace_id = workspace_id
185
+ self._project_dir = project_dir
186
+ self._loop = loop
187
+
188
+ async def request_approval(self, request: Any) -> Any:
189
+ result = await self._inbox.request(
190
+ run_id=self._run_id,
191
+ workspace_id=self._workspace_id,
192
+ project_dir=self._project_dir,
193
+ tool_name=str(getattr(request, "tool_name", "tool")),
194
+ arguments=dict(getattr(request, "arguments", {}) or {}),
195
+ risk_level=str(getattr(request, "risk_level", "medium")),
196
+ diff_preview=str((getattr(request, "context", {}) or {}).get("diff_preview", "")),
197
+ )
198
+ try:
199
+ from praisonaiagents.approval import ApprovalDecision
200
+
201
+ return ApprovalDecision(
202
+ approved=bool(result["approved"]),
203
+ reason=str(result.get("reason", "")),
204
+ scope=str(result.get("scope", "once")),
205
+ feedback=result.get("feedback") or None,
206
+ )
207
+ except Exception:
208
+ return result
209
+
210
+ def request_approval_sync(self, request: Any, timeout: float | None = None) -> Any:
211
+ if self._loop is None:
212
+ raise RuntimeError("WebApprovalBackend sync approval requires a running event loop")
213
+ fut = asyncio.run_coroutine_threadsafe(self.request_approval(request), self._loop)
214
+ return fut.result(timeout=timeout or 300.0)
@@ -0,0 +1,68 @@
1
+ """Lazy file-level checkpoint bridge to praisonai_code.cli.features.checkpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import inspect
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ async def _maybe_await(val: Any) -> Any:
12
+ if inspect.isawaitable(val):
13
+ return await val
14
+ return val
15
+
16
+
17
+ class CheckpointBridge:
18
+ """Wraps CheckpointsHandler lazily (supports both async and sync upstream methods)."""
19
+
20
+ def _handler(self, workspace_dir: Path | str):
21
+ try:
22
+ from praisonai_code.cli.features.checkpoints import CheckpointsHandler
23
+ except Exception:
24
+ return None
25
+ return CheckpointsHandler(workspace_dir=str(workspace_dir))
26
+
27
+ async def save(self, workspace_dir: Path | str, message: str = "") -> dict[str, Any]:
28
+ h = self._handler(workspace_dir)
29
+ if h is None:
30
+ return {"available": False, "checkpoint_id": None}
31
+ if inspect.iscoroutinefunction(h.save):
32
+ cp = await h.save(message or "aiui-code turn")
33
+ else:
34
+ cp = await _maybe_await(await asyncio.to_thread(h.save, message or "aiui-code turn"))
35
+ cp_id = getattr(cp, "id", None) or (cp.get("id") if isinstance(cp, dict) else str(cp or ""))
36
+ return {"available": True, "checkpoint_id": cp_id}
37
+
38
+ async def list_checkpoints(self, workspace_dir: Path | str) -> list[dict[str, Any]]:
39
+ h = self._handler(workspace_dir)
40
+ if h is None:
41
+ return []
42
+ if inspect.iscoroutinefunction(h.list_checkpoints):
43
+ items = await h.list_checkpoints() or []
44
+ else:
45
+ items = await _maybe_await(await asyncio.to_thread(h.list_checkpoints)) or []
46
+ out: list[dict[str, Any]] = []
47
+ for item in items:
48
+ if isinstance(item, dict):
49
+ out.append(item)
50
+ else:
51
+ out.append(
52
+ {
53
+ "id": str(getattr(item, "id", "")),
54
+ "message": str(getattr(item, "message", "")),
55
+ "timestamp": str(getattr(item, "timestamp", "")),
56
+ }
57
+ )
58
+ return out
59
+
60
+ async def restore(self, workspace_dir: Path | str, checkpoint_id: str) -> dict[str, Any]:
61
+ h = self._handler(workspace_dir)
62
+ if h is None:
63
+ return {"restored": False, "error": "CheckpointsHandler unavailable"}
64
+ if inspect.iscoroutinefunction(h.restore):
65
+ res = await h.restore(checkpoint_id)
66
+ else:
67
+ res = await _maybe_await(await asyncio.to_thread(h.restore, checkpoint_id))
68
+ return {"restored": bool(res) if isinstance(res, bool) else True, "checkpoint_id": checkpoint_id}
@@ -0,0 +1,74 @@
1
+ """Normalized in-memory WebSocket event bus with per-run replay and global inbox fan-out."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import itertools
7
+ from collections import deque
8
+ from datetime import datetime, timezone
9
+ from typing import Any
10
+
11
+
12
+ class RunEventBus:
13
+ """Stores replayable events per run and fans out live events to WebSocket subscribers."""
14
+
15
+ def __init__(self, *, max_history: int = 500) -> None:
16
+ self._seq = itertools.count(1)
17
+ self._max_history = max_history
18
+ self._history: dict[str, deque[dict[str, Any]]] = {}
19
+ self._run_subs: dict[str, set[asyncio.Queue[dict[str, Any]]]] = {}
20
+ self._global_subs: set[asyncio.Queue[dict[str, Any]]] = set()
21
+
22
+ def publish(self, run_id: str, event_type: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
23
+ event = {
24
+ "seq": next(self._seq),
25
+ "run_id": run_id,
26
+ "type": event_type,
27
+ "timestamp": datetime.now(timezone.utc).isoformat(),
28
+ "payload": payload or {},
29
+ }
30
+ buf = self._history.setdefault(run_id, deque(maxlen=self._max_history))
31
+ buf.append(event)
32
+
33
+ for q in list(self._run_subs.get(run_id, ())):
34
+ self._offer(q, event)
35
+ for q in list(self._global_subs):
36
+ self._offer(q, event)
37
+ return event
38
+
39
+ @staticmethod
40
+ def _offer(q: asyncio.Queue[dict[str, Any]], event: dict[str, Any]) -> None:
41
+ try:
42
+ q.put_nowait(event)
43
+ except asyncio.QueueFull:
44
+ try:
45
+ q.get_nowait()
46
+ q.put_nowait(event)
47
+ except asyncio.QueueEmpty:
48
+ pass
49
+
50
+ def history(self, run_id: str, *, after_seq: int = 0) -> list[dict[str, Any]]:
51
+ buf = self._history.get(run_id)
52
+ if not buf:
53
+ return []
54
+ return [e for e in buf if e["seq"] > after_seq]
55
+
56
+ def subscribe_run(self, run_id: str) -> asyncio.Queue[dict[str, Any]]:
57
+ q: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=256)
58
+ self._run_subs.setdefault(run_id, set()).add(q)
59
+ return q
60
+
61
+ def unsubscribe_run(self, run_id: str, q: asyncio.Queue[dict[str, Any]]) -> None:
62
+ subs = self._run_subs.get(run_id)
63
+ if subs:
64
+ subs.discard(q)
65
+ if not subs:
66
+ del self._run_subs[run_id]
67
+
68
+ def subscribe_global(self) -> asyncio.Queue[dict[str, Any]]:
69
+ q: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=256)
70
+ self._global_subs.add(q)
71
+ return q
72
+
73
+ def unsubscribe_global(self, q: asyncio.Queue[dict[str, Any]]) -> None:
74
+ self._global_subs.discard(q)