aiui-code 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.
- aiui_code/__init__.py +14 -0
- aiui_code/approvals.py +214 -0
- aiui_code/checkpoints.py +68 -0
- aiui_code/events.py +74 -0
- aiui_code/git_diff.py +179 -0
- aiui_code/plugin.py +104 -0
- aiui_code/pty_service.py +99 -0
- aiui_code/routes.py +357 -0
- aiui_code/runner.py +502 -0
- aiui_code/security.py +103 -0
- aiui_code/server.py +118 -0
- aiui_code/static/code.css +1 -0
- aiui_code/static/code.js +1141 -0
- aiui_code/workspaces.py +197 -0
- aiui_code/worktrees.py +138 -0
- aiui_code-0.1.0.dist-info/METADATA +80 -0
- aiui_code-0.1.0.dist-info/RECORD +20 -0
- aiui_code-0.1.0.dist-info/WHEEL +4 -0
- aiui_code-0.1.0.dist-info/entry_points.txt +5 -0
- aiui_code-0.1.0.dist-info/licenses/LICENSE +21 -0
aiui_code/__init__.py
ADDED
|
@@ -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}")
|
aiui_code/approvals.py
ADDED
|
@@ -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)
|
aiui_code/checkpoints.py
ADDED
|
@@ -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}
|
aiui_code/events.py
ADDED
|
@@ -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)
|
aiui_code/git_diff.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Git diff inspection, safe commits, and lazy OpenShip PR/review bridge."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from dataclasses import asdict, dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from aiui_code.security import resolve_within_root, run_argv
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class DiffFileSummary:
|
|
15
|
+
path: str
|
|
16
|
+
status: str
|
|
17
|
+
additions: int
|
|
18
|
+
deletions: int
|
|
19
|
+
patch: str
|
|
20
|
+
|
|
21
|
+
def to_dict(self) -> dict[str, Any]:
|
|
22
|
+
return asdict(self)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _split_patches(unified: str) -> dict[str, str]:
|
|
26
|
+
"""Split a multi-file `git diff` string into `{relative_path: file_patch}`."""
|
|
27
|
+
patches: dict[str, str] = {}
|
|
28
|
+
current_path = ""
|
|
29
|
+
buf: list[str] = []
|
|
30
|
+
for line in unified.splitlines(keepends=True):
|
|
31
|
+
if line.startswith("diff --git "):
|
|
32
|
+
if current_path and buf:
|
|
33
|
+
patches[current_path] = "".join(buf)
|
|
34
|
+
buf = [line]
|
|
35
|
+
parts = line.strip().split(" ")
|
|
36
|
+
b_part = parts[-1] if len(parts) >= 4 else ""
|
|
37
|
+
current_path = b_part[2:] if b_part.startswith("b/") else b_part
|
|
38
|
+
else:
|
|
39
|
+
buf.append(line)
|
|
40
|
+
if current_path and buf:
|
|
41
|
+
patches[current_path] = "".join(buf)
|
|
42
|
+
return patches
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _synthetic_untracked_patch(root: Path, rel_path: str) -> tuple[str, int]:
|
|
46
|
+
"""Build a unified diff patch for an untracked text file inside ``root``."""
|
|
47
|
+
full = resolve_within_root(root, rel_path)
|
|
48
|
+
if not full.is_file():
|
|
49
|
+
return "", 0
|
|
50
|
+
raw = full.read_bytes()
|
|
51
|
+
if b"\x00" in raw[:4096]:
|
|
52
|
+
return f"diff --git a/{rel_path} b/{rel_path}\nnew file mode 100644\nBinary files /dev/null and b/{rel_path} differ\n", 0
|
|
53
|
+
text = raw.decode("utf-8", errors="replace")
|
|
54
|
+
lines = text.splitlines()
|
|
55
|
+
count = len(lines)
|
|
56
|
+
header = (
|
|
57
|
+
f"diff --git a/{rel_path} b/{rel_path}\n"
|
|
58
|
+
f"new file mode 100644\n"
|
|
59
|
+
f"--- /dev/null\n"
|
|
60
|
+
f"+++ b/{rel_path}\n"
|
|
61
|
+
f"@@ -0,0 +1,{count} @@\n"
|
|
62
|
+
)
|
|
63
|
+
body = "".join(f"+{ln}\n" for ln in lines)
|
|
64
|
+
return header + body, count
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class GitDiffService:
|
|
68
|
+
"""Computes live changed files, unified patches, commits, and OpenShip actions."""
|
|
69
|
+
|
|
70
|
+
async def diff_summary(self, cwd: Path | str) -> dict[str, Any]:
|
|
71
|
+
root = Path(cwd).expanduser().resolve()
|
|
72
|
+
rc, inside, _ = await run_argv(["git", "rev-parse", "--is-inside-work-tree"], cwd=root)
|
|
73
|
+
if rc != 0 or inside.strip().lower() != "true":
|
|
74
|
+
return {"is_git": False, "branch": "", "files": [], "additions": 0, "deletions": 0}
|
|
75
|
+
|
|
76
|
+
_, br_out, _ = await run_argv(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
|
|
77
|
+
_, status_out, _ = await run_argv(["git", "status", "--porcelain=v1"], cwd=root)
|
|
78
|
+
_, numstat_out, _ = await run_argv(["git", "diff", "HEAD", "--numstat"], cwd=root)
|
|
79
|
+
_, patch_out, _ = await run_argv(["git", "diff", "HEAD", "-U3"], cwd=root)
|
|
80
|
+
|
|
81
|
+
# Fallback if repo has no HEAD commit yet.
|
|
82
|
+
if not numstat_out and not patch_out:
|
|
83
|
+
_, numstat_out, _ = await run_argv(["git", "diff", "--numstat"], cwd=root)
|
|
84
|
+
_, patch_out, _ = await run_argv(["git", "diff", "-U3"], cwd=root)
|
|
85
|
+
|
|
86
|
+
stats: dict[str, tuple[int, int]] = {}
|
|
87
|
+
for line in numstat_out.splitlines():
|
|
88
|
+
parts = line.split("\t")
|
|
89
|
+
if len(parts) >= 3:
|
|
90
|
+
adds = int(parts[0]) if parts[0].isdigit() else 0
|
|
91
|
+
dels = int(parts[1]) if parts[1].isdigit() else 0
|
|
92
|
+
stats[parts[2]] = (adds, dels)
|
|
93
|
+
|
|
94
|
+
patches = _split_patches(patch_out)
|
|
95
|
+
files: list[DiffFileSummary] = []
|
|
96
|
+
seen: set[str] = set()
|
|
97
|
+
|
|
98
|
+
for line in status_out.splitlines():
|
|
99
|
+
if len(line) < 4:
|
|
100
|
+
continue
|
|
101
|
+
code = line[:2].strip() or "M"
|
|
102
|
+
rel = line[3:].strip()
|
|
103
|
+
if " -> " in rel:
|
|
104
|
+
rel = rel.split(" -> ", 1)[1].strip()
|
|
105
|
+
rel = rel.strip('"')
|
|
106
|
+
if rel in seen:
|
|
107
|
+
continue
|
|
108
|
+
seen.add(rel)
|
|
109
|
+
|
|
110
|
+
if code == "??":
|
|
111
|
+
patch, adds = _synthetic_untracked_patch(root, rel)
|
|
112
|
+
dels = 0
|
|
113
|
+
st = "added"
|
|
114
|
+
else:
|
|
115
|
+
adds, dels = stats.get(rel, (0, 0))
|
|
116
|
+
patch = patches.get(rel, "")
|
|
117
|
+
st = "deleted" if "D" in code else ("added" if "A" in code else "modified")
|
|
118
|
+
files.append(DiffFileSummary(path=rel, status=st, additions=adds, deletions=dels, patch=patch))
|
|
119
|
+
|
|
120
|
+
total_adds = sum(f.additions for f in files)
|
|
121
|
+
total_dels = sum(f.deletions for f in files)
|
|
122
|
+
return {
|
|
123
|
+
"is_git": True,
|
|
124
|
+
"branch": br_out.strip(),
|
|
125
|
+
"files": [f.to_dict() for f in files],
|
|
126
|
+
"additions": total_adds,
|
|
127
|
+
"deletions": total_dels,
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async def commit(self, cwd: Path | str, message: str) -> dict[str, Any]:
|
|
131
|
+
msg = (message or "").strip()
|
|
132
|
+
if not msg:
|
|
133
|
+
raise ValueError("Commit message must not be empty")
|
|
134
|
+
root = Path(cwd).expanduser().resolve()
|
|
135
|
+
rc, _, err = await run_argv(["git", "add", "-A"], cwd=root)
|
|
136
|
+
if rc != 0:
|
|
137
|
+
raise RuntimeError(f"git add failed: {err.strip()}")
|
|
138
|
+
rc, out, err = await run_argv(["git", "commit", "-m", msg], cwd=root)
|
|
139
|
+
if rc != 0:
|
|
140
|
+
raise RuntimeError(f"git commit failed: {(err or out).strip()}")
|
|
141
|
+
_, sha_out, _ = await run_argv(["git", "rev-parse", "--short", "HEAD"], cwd=root)
|
|
142
|
+
return {"committed": True, "sha": sha_out.strip(), "output": out.strip()}
|
|
143
|
+
|
|
144
|
+
async def openship_review(self, cwd: Path | str) -> dict[str, Any]:
|
|
145
|
+
"""Lazily invoke praisonai_code.ship.ui_service self-review when available."""
|
|
146
|
+
root = Path(cwd).expanduser().resolve()
|
|
147
|
+
|
|
148
|
+
def _run() -> dict[str, Any]:
|
|
149
|
+
try:
|
|
150
|
+
from praisonai_code.ship import ui_service
|
|
151
|
+
except Exception as exc:
|
|
152
|
+
return {"available": False, "error": f"praisonai-code OpenShip unavailable: {exc}"}
|
|
153
|
+
status = ui_service.get_repo_status(str(root))
|
|
154
|
+
bundle = ui_service.get_diff_bundle(str(root))
|
|
155
|
+
return {
|
|
156
|
+
"available": True,
|
|
157
|
+
"branch": getattr(status, "branch", ""),
|
|
158
|
+
"dirty": getattr(status, "dirty", False),
|
|
159
|
+
"changed_files": len(bundle) if isinstance(bundle, list) else 0,
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return await asyncio.to_thread(_run)
|
|
163
|
+
|
|
164
|
+
async def openship_draft_pr(self, cwd: Path | str, *, title: str, body: str = "") -> dict[str, Any]:
|
|
165
|
+
"""Lazily create a draft PR via praisonai_code.ship.ui_service (never auto-merges)."""
|
|
166
|
+
root = Path(cwd).expanduser().resolve()
|
|
167
|
+
clean_title = (title or "").strip()
|
|
168
|
+
if not clean_title:
|
|
169
|
+
raise ValueError("Draft PR title is required")
|
|
170
|
+
|
|
171
|
+
def _run() -> dict[str, Any]:
|
|
172
|
+
try:
|
|
173
|
+
from praisonai_code.ship import ui_service
|
|
174
|
+
except Exception as exc:
|
|
175
|
+
return {"available": False, "error": f"praisonai-code OpenShip unavailable: {exc}"}
|
|
176
|
+
res = ui_service.create_draft_pr(str(root), title=clean_title, body=body)
|
|
177
|
+
return res if isinstance(res, dict) else {"result": str(res)}
|
|
178
|
+
|
|
179
|
+
return await asyncio.to_thread(_run)
|
aiui_code/plugin.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""PraisonAIUI entry-point plugin (`praisonaiui.plugins`: `code = aiui_code.plugin:plugin`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from contextlib import asynccontextmanager
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from praisonaiui.plugin_registry import NavGroupSpec, SettingsField, SettingsSectionSpec
|
|
10
|
+
|
|
11
|
+
from aiui_code import __version__
|
|
12
|
+
from aiui_code.routes import CodeServiceContainer, build_routes
|
|
13
|
+
|
|
14
|
+
_STATIC = Path(__file__).parent / "static"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CodePlugin:
|
|
18
|
+
"""Standalone multi-agent coding workspace plugin for PraisonAIUI."""
|
|
19
|
+
|
|
20
|
+
name = "code"
|
|
21
|
+
version = __version__
|
|
22
|
+
sdk = 1
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
*,
|
|
27
|
+
state_dir: Path | None = None,
|
|
28
|
+
allow_web_add: bool = True,
|
|
29
|
+
enable_terminal: bool = False,
|
|
30
|
+
) -> None:
|
|
31
|
+
self.services = CodeServiceContainer(
|
|
32
|
+
state_dir=state_dir,
|
|
33
|
+
allow_web_add=allow_web_add,
|
|
34
|
+
enable_terminal=enable_terminal,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
def pages(self) -> list[dict[str, Any]]:
|
|
38
|
+
return [
|
|
39
|
+
{
|
|
40
|
+
"id": "code",
|
|
41
|
+
"title": "Code",
|
|
42
|
+
"kind": "react",
|
|
43
|
+
"module": "code.js",
|
|
44
|
+
"icon": "terminal",
|
|
45
|
+
"group": "Code",
|
|
46
|
+
"order": 150,
|
|
47
|
+
"layout": "full",
|
|
48
|
+
"description": "Multi-agent coding workspaces, isolated worktrees, diff review, and approvals",
|
|
49
|
+
}
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
def nav_groups(self) -> list[NavGroupSpec]:
|
|
53
|
+
return [NavGroupSpec(name="Code", order=150)]
|
|
54
|
+
|
|
55
|
+
def settings(self) -> list[SettingsSectionSpec]:
|
|
56
|
+
return [
|
|
57
|
+
SettingsSectionSpec(
|
|
58
|
+
id="workspace",
|
|
59
|
+
title="PraisonAI Code",
|
|
60
|
+
description="Defaults for coding agent runs and worktree isolation.",
|
|
61
|
+
fields=(
|
|
62
|
+
SettingsField(
|
|
63
|
+
key="default_engine",
|
|
64
|
+
label="Default engine",
|
|
65
|
+
type="select",
|
|
66
|
+
default="praisonai",
|
|
67
|
+
options=(
|
|
68
|
+
{"value": "praisonai", "label": "PraisonAI Agent"},
|
|
69
|
+
{"value": "claude-code", "label": "Claude Code CLI"},
|
|
70
|
+
{"value": "codex-cli", "label": "OpenAI Codex CLI"},
|
|
71
|
+
{"value": "gemini-cli", "label": "Gemini CLI"},
|
|
72
|
+
{"value": "grok-cli", "label": "Grok CLI"},
|
|
73
|
+
),
|
|
74
|
+
),
|
|
75
|
+
SettingsField(
|
|
76
|
+
key="default_worktree",
|
|
77
|
+
label="Isolate runs in git worktrees",
|
|
78
|
+
type="boolean",
|
|
79
|
+
default=True,
|
|
80
|
+
),
|
|
81
|
+
),
|
|
82
|
+
)
|
|
83
|
+
]
|
|
84
|
+
|
|
85
|
+
def routes(self):
|
|
86
|
+
return build_routes(self.services)
|
|
87
|
+
|
|
88
|
+
def static_dir(self) -> Path:
|
|
89
|
+
return _STATIC
|
|
90
|
+
|
|
91
|
+
@asynccontextmanager
|
|
92
|
+
async def lifespan(self, app: Any):
|
|
93
|
+
try:
|
|
94
|
+
yield
|
|
95
|
+
finally:
|
|
96
|
+
await self.services.shutdown()
|
|
97
|
+
|
|
98
|
+
def cli_commands(self):
|
|
99
|
+
from aiui_code.server import build_cli
|
|
100
|
+
|
|
101
|
+
return build_cli(self)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
plugin = CodePlugin()
|