aiui-code 0.1.2__tar.gz → 0.2.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.
- {aiui_code-0.1.2 → aiui_code-0.2.0}/PKG-INFO +1 -1
- {aiui_code-0.1.2 → aiui_code-0.2.0}/pyproject.toml +1 -1
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/__init__.py +1 -1
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/checkpoints.py +4 -1
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/cli_control.py +24 -0
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/client.py +6 -0
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/git_diff.py +56 -20
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/mcp_server.py +39 -2
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/plugin.py +15 -1
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/pty_service.py +35 -8
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/routes.py +22 -1
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/runner.py +177 -30
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/security.py +2 -2
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/server.py +4 -1
- aiui_code-0.2.0/src/aiui_code/static/code.css +1 -0
- aiui_code-0.2.0/src/aiui_code/static/code.js +1860 -0
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/workspaces.py +5 -1
- {aiui_code-0.1.2 → aiui_code-0.2.0}/tests/test_browser_e2e.py +2 -1
- {aiui_code-0.1.2 → aiui_code-0.2.0}/tests/test_cli_and_mcp.py +8 -3
- {aiui_code-0.1.2 → aiui_code-0.2.0}/tests/test_security.py +6 -1
- {aiui_code-0.1.2 → aiui_code-0.2.0}/tests/test_workspaces_and_diff.py +30 -0
- aiui_code-0.1.2/src/aiui_code/static/code.css +0 -1
- aiui_code-0.1.2/src/aiui_code/static/code.js +0 -1385
- {aiui_code-0.1.2 → aiui_code-0.2.0}/.gitignore +0 -0
- {aiui_code-0.1.2 → aiui_code-0.2.0}/LICENSE +0 -0
- {aiui_code-0.1.2 → aiui_code-0.2.0}/README.md +0 -0
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/approvals.py +0 -0
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/events.py +0 -0
- {aiui_code-0.1.2 → aiui_code-0.2.0}/src/aiui_code/worktrees.py +0 -0
- {aiui_code-0.1.2 → aiui_code-0.2.0}/tests/conftest.py +0 -0
- {aiui_code-0.1.2 → aiui_code-0.2.0}/tests/test_plugin_contract.py +0 -0
- {aiui_code-0.1.2 → aiui_code-0.2.0}/tests/test_runner_and_approvals.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: aiui-code
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
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
|
|
@@ -32,7 +32,10 @@ class CheckpointBridge:
|
|
|
32
32
|
cp = await h.save(message or "aiui-code turn")
|
|
33
33
|
else:
|
|
34
34
|
cp = await _maybe_await(await asyncio.to_thread(h.save, message or "aiui-code turn"))
|
|
35
|
-
|
|
35
|
+
if isinstance(cp, bool):
|
|
36
|
+
cp_id = None
|
|
37
|
+
else:
|
|
38
|
+
cp_id = getattr(cp, "id", None) or (cp.get("id") if isinstance(cp, dict) else (str(cp) if cp else None))
|
|
36
39
|
return {"available": True, "checkpoint_id": cp_id}
|
|
37
40
|
|
|
38
41
|
async def list_checkpoints(self, workspace_dir: Path | str) -> list[dict[str, Any]]:
|
|
@@ -239,6 +239,30 @@ def attach_control_commands(cli: typer.Typer) -> None:
|
|
|
239
239
|
data = _run_or_exit(lambda: client.interrupt(run_id))
|
|
240
240
|
_emit(data, as_json, f"Interrupted {run_id}")
|
|
241
241
|
|
|
242
|
+
@runs_app.command("retry")
|
|
243
|
+
def runs_retry(
|
|
244
|
+
run_id: str = typer.Argument(..., help="Run ID to retry."),
|
|
245
|
+
url: Optional[str] = url_opt,
|
|
246
|
+
token: Optional[str] = token_opt,
|
|
247
|
+
as_json: bool = json_opt,
|
|
248
|
+
) -> None:
|
|
249
|
+
"""Retry a failed or interrupted run."""
|
|
250
|
+
client = _make_client(url, token)
|
|
251
|
+
data = _run_or_exit(lambda: client.retry_run(run_id))
|
|
252
|
+
_emit(data, as_json, f"Retrying {data['id']} (status={data['status']})")
|
|
253
|
+
|
|
254
|
+
@runs_app.command("delete")
|
|
255
|
+
def runs_delete(
|
|
256
|
+
run_id: str = typer.Argument(..., help="Run ID to delete."),
|
|
257
|
+
url: Optional[str] = url_opt,
|
|
258
|
+
token: Optional[str] = token_opt,
|
|
259
|
+
as_json: bool = json_opt,
|
|
260
|
+
) -> None:
|
|
261
|
+
"""Delete a run from the dashboard."""
|
|
262
|
+
client = _make_client(url, token)
|
|
263
|
+
data = _run_or_exit(lambda: client.delete_run(run_id))
|
|
264
|
+
_emit(data, as_json, f"Deleted run {run_id}")
|
|
265
|
+
|
|
242
266
|
@runs_app.command("watch")
|
|
243
267
|
def runs_watch(
|
|
244
268
|
run_id: str = typer.Argument(..., help="Run ID to tail until terminal state."),
|
|
@@ -157,6 +157,12 @@ class CodeClient:
|
|
|
157
157
|
def get_run(self, run_id: str) -> dict[str, Any]:
|
|
158
158
|
return self._request("GET", f"/runs/{urllib.parse.quote(run_id, safe='')}")
|
|
159
159
|
|
|
160
|
+
def delete_run(self, run_id: str) -> dict[str, Any]:
|
|
161
|
+
return self._request("DELETE", f"/runs/{urllib.parse.quote(run_id, safe='')}")
|
|
162
|
+
|
|
163
|
+
def retry_run(self, run_id: str) -> dict[str, Any]:
|
|
164
|
+
return self._request("POST", f"/runs/{urllib.parse.quote(run_id, safe='')}/retry", body={})
|
|
165
|
+
|
|
160
166
|
def send_message(
|
|
161
167
|
self,
|
|
162
168
|
run_id: str,
|
|
@@ -23,22 +23,42 @@ class DiffFileSummary:
|
|
|
23
23
|
|
|
24
24
|
|
|
25
25
|
def _split_patches(unified: str) -> dict[str, str]:
|
|
26
|
-
"""Split a multi-file `git diff` string into `{relative_path: file_patch}
|
|
26
|
+
"""Split a multi-file `git diff` string into `{relative_path: file_patch}` (handles spaces)."""
|
|
27
27
|
patches: dict[str, str] = {}
|
|
28
28
|
current_path = ""
|
|
29
29
|
buf: list[str] = []
|
|
30
|
+
|
|
31
|
+
def _flush() -> None:
|
|
32
|
+
if current_path and buf:
|
|
33
|
+
patches[current_path] = "".join(buf)
|
|
34
|
+
|
|
30
35
|
for line in unified.splitlines(keepends=True):
|
|
31
36
|
if line.startswith("diff --git "):
|
|
32
|
-
|
|
33
|
-
patches[current_path] = "".join(buf)
|
|
37
|
+
_flush()
|
|
34
38
|
buf = [line]
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
39
|
+
# Fallback path extraction; refined below when +++ b/ or --- a/ is seen.
|
|
40
|
+
raw = line[len("diff --git ") :].strip()
|
|
41
|
+
if " b/" in raw:
|
|
42
|
+
current_path = raw.rsplit(" b/", 1)[1].strip('"')
|
|
43
|
+
else:
|
|
44
|
+
parts = raw.split(" ")
|
|
45
|
+
b_part = parts[-1] if parts else ""
|
|
46
|
+
current_path = b_part[2:] if b_part.startswith("b/") else b_part
|
|
38
47
|
else:
|
|
48
|
+
if line.startswith("+++ "):
|
|
49
|
+
raw_target = line[4:].rstrip("\r\n\t ")
|
|
50
|
+
if raw_target.startswith('"') and raw_target.endswith('"'):
|
|
51
|
+
raw_target = raw_target[1:-1]
|
|
52
|
+
if raw_target.startswith("b/"):
|
|
53
|
+
current_path = raw_target[2:]
|
|
54
|
+
elif line.startswith("--- ") and not current_path:
|
|
55
|
+
raw_src = line[4:].rstrip("\r\n\t ")
|
|
56
|
+
if raw_src.startswith('"') and raw_src.endswith('"'):
|
|
57
|
+
raw_src = raw_src[1:-1]
|
|
58
|
+
if raw_src.startswith("a/"):
|
|
59
|
+
current_path = raw_src[2:]
|
|
39
60
|
buf.append(line)
|
|
40
|
-
|
|
41
|
-
patches[current_path] = "".join(buf)
|
|
61
|
+
_flush()
|
|
42
62
|
return patches
|
|
43
63
|
|
|
44
64
|
|
|
@@ -74,14 +94,14 @@ class GitDiffService:
|
|
|
74
94
|
return {"is_git": False, "branch": "", "files": [], "additions": 0, "deletions": 0}
|
|
75
95
|
|
|
76
96
|
_, 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)
|
|
97
|
+
_, status_out, _ = await run_argv(["git", "-c", "core.quotePath=false", "status", "--porcelain=v1", "-uall"], cwd=root)
|
|
98
|
+
_, numstat_out, _ = await run_argv(["git", "-c", "core.quotePath=false", "diff", "HEAD", "--numstat"], cwd=root)
|
|
99
|
+
_, patch_out, _ = await run_argv(["git", "-c", "core.quotePath=false", "diff", "HEAD", "-U3"], cwd=root)
|
|
80
100
|
|
|
81
101
|
# Fallback if repo has no HEAD commit yet.
|
|
82
102
|
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)
|
|
103
|
+
_, numstat_out, _ = await run_argv(["git", "-c", "core.quotePath=false", "diff", "--numstat"], cwd=root)
|
|
104
|
+
_, patch_out, _ = await run_argv(["git", "-c", "core.quotePath=false", "diff", "-U3"], cwd=root)
|
|
85
105
|
|
|
86
106
|
stats: dict[str, tuple[int, int]] = {}
|
|
87
107
|
for line in numstat_out.splitlines():
|
|
@@ -142,7 +162,7 @@ class GitDiffService:
|
|
|
142
162
|
return {"committed": True, "sha": sha_out.strip(), "output": out.strip()}
|
|
143
163
|
|
|
144
164
|
async def openship_review(self, cwd: Path | str) -> dict[str, Any]:
|
|
145
|
-
"""Lazily invoke praisonai_code.ship.ui_service
|
|
165
|
+
"""Lazily invoke praisonai_code.ship.ui_service status + diff bundle review."""
|
|
146
166
|
root = Path(cwd).expanduser().resolve()
|
|
147
167
|
|
|
148
168
|
def _run() -> dict[str, Any]:
|
|
@@ -150,30 +170,46 @@ class GitDiffService:
|
|
|
150
170
|
from praisonai_code.ship import ui_service
|
|
151
171
|
except Exception as exc:
|
|
152
172
|
return {"available": False, "error": f"praisonai-code OpenShip unavailable: {exc}"}
|
|
153
|
-
status = ui_service.get_repo_status(
|
|
154
|
-
bundle = ui_service.get_diff_bundle(
|
|
173
|
+
status = ui_service.get_repo_status(root)
|
|
174
|
+
bundle = ui_service.get_diff_bundle(root)
|
|
175
|
+
if isinstance(bundle, tuple) and len(bundle) >= 2:
|
|
176
|
+
base_ref, file_diffs = str(bundle[0] or ""), list(bundle[1] or [])
|
|
177
|
+
elif isinstance(bundle, list):
|
|
178
|
+
base_ref, file_diffs = "", bundle
|
|
179
|
+
else:
|
|
180
|
+
base_ref, file_diffs = "", []
|
|
155
181
|
return {
|
|
156
182
|
"available": True,
|
|
157
183
|
"branch": getattr(status, "branch", ""),
|
|
184
|
+
"base_ref": base_ref,
|
|
158
185
|
"dirty": getattr(status, "dirty", False),
|
|
159
|
-
"changed_files": len(
|
|
186
|
+
"changed_files": len(file_diffs),
|
|
187
|
+
"files": [getattr(f, "path", str(f)) for f in file_diffs[:50]],
|
|
160
188
|
}
|
|
161
189
|
|
|
162
190
|
return await asyncio.to_thread(_run)
|
|
163
191
|
|
|
164
|
-
async def openship_draft_pr(
|
|
165
|
-
|
|
192
|
+
async def openship_draft_pr(
|
|
193
|
+
self,
|
|
194
|
+
cwd: Path | str,
|
|
195
|
+
*,
|
|
196
|
+
title: str,
|
|
197
|
+
body: str = "",
|
|
198
|
+
confirm: bool = False,
|
|
199
|
+
) -> dict[str, Any]:
|
|
200
|
+
"""Lazily preview or create a draft PR via praisonai_code.ship.ui_service (never auto-merges)."""
|
|
166
201
|
root = Path(cwd).expanduser().resolve()
|
|
167
202
|
clean_title = (title or "").strip()
|
|
168
203
|
if not clean_title:
|
|
169
204
|
raise ValueError("Draft PR title is required")
|
|
205
|
+
message = f"{clean_title}\n\n{body.strip()}" if body.strip() else clean_title
|
|
170
206
|
|
|
171
207
|
def _run() -> dict[str, Any]:
|
|
172
208
|
try:
|
|
173
209
|
from praisonai_code.ship import ui_service
|
|
174
210
|
except Exception as exc:
|
|
175
211
|
return {"available": False, "error": f"praisonai-code OpenShip unavailable: {exc}"}
|
|
176
|
-
res = ui_service.create_draft_pr(
|
|
212
|
+
res = ui_service.create_draft_pr(root, message=message, confirm=confirm)
|
|
177
213
|
return res if isinstance(res, dict) else {"result": str(res)}
|
|
178
214
|
|
|
179
215
|
return await asyncio.to_thread(_run)
|
|
@@ -151,6 +151,22 @@ MCP_TOOLS: list[dict[str, Any]] = [
|
|
|
151
151
|
required=["run_id"],
|
|
152
152
|
),
|
|
153
153
|
},
|
|
154
|
+
{
|
|
155
|
+
"name": "code_retry_run",
|
|
156
|
+
"description": "Retry a failed or interrupted run using its latest prompt.",
|
|
157
|
+
"inputSchema": _obj_schema(
|
|
158
|
+
{"run_id": {"type": "string", "description": "Run ID."}},
|
|
159
|
+
required=["run_id"],
|
|
160
|
+
),
|
|
161
|
+
},
|
|
162
|
+
{
|
|
163
|
+
"name": "code_delete_run",
|
|
164
|
+
"description": "Stop (if running) and delete a run from the dashboard.",
|
|
165
|
+
"inputSchema": _obj_schema(
|
|
166
|
+
{"run_id": {"type": "string", "description": "Run ID."}},
|
|
167
|
+
required=["run_id"],
|
|
168
|
+
),
|
|
169
|
+
},
|
|
154
170
|
{
|
|
155
171
|
"name": "code_get_diff",
|
|
156
172
|
"description": "Get changed files, +/- line stats, and unified diff patches for a run's workspace/worktree.",
|
|
@@ -477,6 +493,10 @@ def _dispatch_client_tool(client: CodeClient, name: str, args: dict[str, Any]) -
|
|
|
477
493
|
return client.steer(str(args["run_id"]), str(args["instruction"]))
|
|
478
494
|
if name == "code_stop_run":
|
|
479
495
|
return client.interrupt(str(args["run_id"]))
|
|
496
|
+
if name == "code_retry_run":
|
|
497
|
+
return client.retry_run(str(args["run_id"]))
|
|
498
|
+
if name == "code_delete_run":
|
|
499
|
+
return client.delete_run(str(args["run_id"]))
|
|
480
500
|
if name == "code_get_diff":
|
|
481
501
|
return client.diff(str(args["run_id"]))
|
|
482
502
|
if name == "code_commit_run":
|
|
@@ -543,7 +563,7 @@ async def _dispatch_service_tool(svc: Any, name: str, args: dict[str, Any]) -> A
|
|
|
543
563
|
return rec.to_dict()
|
|
544
564
|
if name == "code_remove_workspace":
|
|
545
565
|
ws_id = str(args["workspace_id"])
|
|
546
|
-
if not svc.workspaces.remove(ws_id):
|
|
566
|
+
if not svc.workspaces.remove(ws_id, from_web=True):
|
|
547
567
|
raise KeyError(f"Workspace not found: {ws_id!r}")
|
|
548
568
|
return {"removed": True, "id": ws_id}
|
|
549
569
|
if name == "code_list_files":
|
|
@@ -580,6 +600,14 @@ async def _dispatch_service_tool(svc: Any, name: str, args: dict[str, Any]) -> A
|
|
|
580
600
|
return await svc.runner.steer(str(args["run_id"]), str(args["instruction"]))
|
|
581
601
|
if name == "code_stop_run":
|
|
582
602
|
return await svc.runner.interrupt(str(args["run_id"]))
|
|
603
|
+
if name == "code_retry_run":
|
|
604
|
+
rec = await svc.runner.retry_run(str(args["run_id"]))
|
|
605
|
+
return rec.to_dict()
|
|
606
|
+
if name == "code_delete_run":
|
|
607
|
+
run_id = str(args["run_id"])
|
|
608
|
+
if not await svc.runner.delete_run(run_id):
|
|
609
|
+
raise KeyError(f"Run not found: {run_id!r}")
|
|
610
|
+
return {"deleted": True, "id": run_id}
|
|
583
611
|
if name == "code_get_diff":
|
|
584
612
|
rec = svc.runner.get_run(str(args["run_id"]))
|
|
585
613
|
if rec is None:
|
|
@@ -671,7 +699,7 @@ def run_stdio_server(client: CodeClient) -> None:
|
|
|
671
699
|
stripped = line.strip()
|
|
672
700
|
if not stripped:
|
|
673
701
|
continue
|
|
674
|
-
if stripped.startswith(b"{"):
|
|
702
|
+
if stripped.startswith((b"{", b"[")):
|
|
675
703
|
return json.loads(stripped.decode("utf-8")), False
|
|
676
704
|
# Content-Length header framing (LSP / legacy MCP clients)
|
|
677
705
|
headers: dict[str, str] = {}
|
|
@@ -708,6 +736,15 @@ def run_stdio_server(client: CodeClient) -> None:
|
|
|
708
736
|
continue
|
|
709
737
|
if msg is None:
|
|
710
738
|
break
|
|
739
|
+
if isinstance(msg, list):
|
|
740
|
+
replies = []
|
|
741
|
+
for item in msg:
|
|
742
|
+
r = await handler.handle_message(item)
|
|
743
|
+
if r is not None:
|
|
744
|
+
replies.append(r)
|
|
745
|
+
if replies:
|
|
746
|
+
_write_message(replies, framed) # type: ignore[arg-type]
|
|
747
|
+
continue
|
|
711
748
|
reply = await handler.handle_message(msg)
|
|
712
749
|
if reply is not None:
|
|
713
750
|
_write_message(reply, framed)
|
|
@@ -6,7 +6,7 @@ from contextlib import asynccontextmanager
|
|
|
6
6
|
from pathlib import Path
|
|
7
7
|
from typing import Any
|
|
8
8
|
|
|
9
|
-
from praisonaiui.plugin_registry import NavGroupSpec, SettingsField, SettingsSectionSpec
|
|
9
|
+
from praisonaiui.plugin_registry import LayoutSpec, NavGroupSpec, SettingsField, SettingsSectionSpec
|
|
10
10
|
|
|
11
11
|
from aiui_code import __version__
|
|
12
12
|
from aiui_code.routes import CodeServiceContainer, build_routes
|
|
@@ -52,6 +52,20 @@ class CodePlugin:
|
|
|
52
52
|
def nav_groups(self) -> list[NavGroupSpec]:
|
|
53
53
|
return [NavGroupSpec(name="Code", order=150)]
|
|
54
54
|
|
|
55
|
+
def layouts(self) -> list[LayoutSpec]:
|
|
56
|
+
return [
|
|
57
|
+
LayoutSpec(
|
|
58
|
+
id="code",
|
|
59
|
+
title="PraisonAI Code",
|
|
60
|
+
description="Full-bleed multi-agent coding workspace frame without duplicate sidebar.",
|
|
61
|
+
order=10,
|
|
62
|
+
module="code.js",
|
|
63
|
+
css="code.css",
|
|
64
|
+
home="code",
|
|
65
|
+
primary=("code",),
|
|
66
|
+
)
|
|
67
|
+
]
|
|
68
|
+
|
|
55
69
|
def settings(self) -> list[SettingsSectionSpec]:
|
|
56
70
|
return [
|
|
57
71
|
SettingsSectionSpec(
|
|
@@ -1,18 +1,27 @@
|
|
|
1
|
-
"""Opt-in interactive PTY terminal WebSocket service (disabled by default)."""
|
|
1
|
+
"""Opt-in interactive PTY terminal WebSocket service (disabled by default, POSIX-safe)."""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
|
-
import fcntl
|
|
7
6
|
import os
|
|
8
|
-
import pty
|
|
9
7
|
import signal
|
|
10
8
|
import struct
|
|
11
|
-
import termios
|
|
12
9
|
from pathlib import Path
|
|
13
10
|
|
|
14
11
|
from starlette.websockets import WebSocket, WebSocketDisconnect
|
|
15
12
|
|
|
13
|
+
try:
|
|
14
|
+
import fcntl
|
|
15
|
+
import pty
|
|
16
|
+
import termios
|
|
17
|
+
|
|
18
|
+
_POSIX_PTY_AVAILABLE = True
|
|
19
|
+
except ImportError: # Windows
|
|
20
|
+
fcntl = None # type: ignore[assignment]
|
|
21
|
+
pty = None # type: ignore[assignment]
|
|
22
|
+
termios = None # type: ignore[assignment]
|
|
23
|
+
_POSIX_PTY_AVAILABLE = False
|
|
24
|
+
|
|
16
25
|
|
|
17
26
|
class PtySessionManager:
|
|
18
27
|
"""Spawns bounded workspace-scoped shells when `--enable-terminal` is enabled."""
|
|
@@ -25,6 +34,9 @@ class PtySessionManager:
|
|
|
25
34
|
if not self.enabled:
|
|
26
35
|
await ws.close(code=4403, reason="Interactive PTY terminal is disabled (start with --enable-terminal)")
|
|
27
36
|
return
|
|
37
|
+
if not _POSIX_PTY_AVAILABLE:
|
|
38
|
+
await ws.close(code=4501, reason="Interactive PTY terminal requires a POSIX OS")
|
|
39
|
+
return
|
|
28
40
|
|
|
29
41
|
await ws.accept()
|
|
30
42
|
shell = os.environ.get("SHELL") or "/bin/sh"
|
|
@@ -76,22 +88,37 @@ class PtySessionManager:
|
|
|
76
88
|
finally:
|
|
77
89
|
loop.remove_reader(master_fd)
|
|
78
90
|
pump_task.cancel()
|
|
91
|
+
try:
|
|
92
|
+
await pump_task
|
|
93
|
+
except (asyncio.CancelledError, Exception):
|
|
94
|
+
pass
|
|
79
95
|
try:
|
|
80
96
|
os.close(master_fd)
|
|
81
97
|
except OSError:
|
|
82
98
|
pass
|
|
83
99
|
self._terminate_pid(proc.pid)
|
|
100
|
+
try:
|
|
101
|
+
await asyncio.wait_for(proc.wait(), timeout=2.0)
|
|
102
|
+
except (asyncio.TimeoutError, Exception):
|
|
103
|
+
try:
|
|
104
|
+
proc.kill()
|
|
105
|
+
await proc.wait()
|
|
106
|
+
except Exception:
|
|
107
|
+
pass
|
|
84
108
|
self._pids.discard(proc.pid)
|
|
85
109
|
|
|
86
110
|
@staticmethod
|
|
87
111
|
def _terminate_pid(pid: int) -> None:
|
|
88
|
-
|
|
89
|
-
os.killpg(pid, signal.SIGTERM)
|
|
90
|
-
except OSError:
|
|
112
|
+
if hasattr(os, "killpg"):
|
|
91
113
|
try:
|
|
92
|
-
os.
|
|
114
|
+
os.killpg(pid, signal.SIGTERM)
|
|
115
|
+
return
|
|
93
116
|
except OSError:
|
|
94
117
|
pass
|
|
118
|
+
try:
|
|
119
|
+
os.kill(pid, signal.SIGTERM)
|
|
120
|
+
except OSError:
|
|
121
|
+
pass
|
|
95
122
|
|
|
96
123
|
async def shutdown(self) -> None:
|
|
97
124
|
for pid in list(self._pids):
|
|
@@ -102,7 +102,11 @@ def build_routes(svc: CodeServiceContainer) -> list[BaseRoute]:
|
|
|
102
102
|
|
|
103
103
|
async def delete_workspace(request: Request) -> JSONResponse:
|
|
104
104
|
ws_id = request.path_params["ws_id"]
|
|
105
|
-
|
|
105
|
+
try:
|
|
106
|
+
removed = svc.workspaces.remove(ws_id, from_web=True)
|
|
107
|
+
except SecurityError as exc:
|
|
108
|
+
return JSONResponse({"error": str(exc)}, status_code=403)
|
|
109
|
+
if not removed:
|
|
106
110
|
return JSONResponse({"error": "Workspace not found"}, status_code=404)
|
|
107
111
|
return JSONResponse({"removed": True, "id": ws_id})
|
|
108
112
|
|
|
@@ -151,6 +155,20 @@ def build_routes(svc: CodeServiceContainer) -> list[BaseRoute]:
|
|
|
151
155
|
}
|
|
152
156
|
)
|
|
153
157
|
|
|
158
|
+
async def delete_run(request: Request) -> JSONResponse:
|
|
159
|
+
run_id = request.path_params["run_id"]
|
|
160
|
+
if not await svc.runner.delete_run(run_id):
|
|
161
|
+
return JSONResponse({"error": "Run not found"}, status_code=404)
|
|
162
|
+
return JSONResponse({"deleted": True, "id": run_id})
|
|
163
|
+
|
|
164
|
+
async def retry_run(request: Request) -> JSONResponse:
|
|
165
|
+
run_id = request.path_params["run_id"]
|
|
166
|
+
try:
|
|
167
|
+
rec = await svc.runner.retry_run(run_id)
|
|
168
|
+
except KeyError:
|
|
169
|
+
return JSONResponse({"error": "Run not found"}, status_code=404)
|
|
170
|
+
return JSONResponse(rec.to_dict())
|
|
171
|
+
|
|
154
172
|
async def post_message(request: Request) -> JSONResponse:
|
|
155
173
|
run_id = request.path_params["run_id"]
|
|
156
174
|
body = await _json_body(request)
|
|
@@ -255,6 +273,7 @@ def build_routes(svc: CodeServiceContainer) -> list[BaseRoute]:
|
|
|
255
273
|
rec.cwd,
|
|
256
274
|
title=str(body.get("title") or rec.title),
|
|
257
275
|
body=str(body.get("body") or ""),
|
|
276
|
+
confirm=bool(body.get("confirm", False)),
|
|
258
277
|
)
|
|
259
278
|
except ValueError as exc:
|
|
260
279
|
return JSONResponse({"error": str(exc)}, status_code=400)
|
|
@@ -386,6 +405,8 @@ def build_routes(svc: CodeServiceContainer) -> list[BaseRoute]:
|
|
|
386
405
|
Route("/runs", list_runs, methods=["GET"]),
|
|
387
406
|
Route("/runs", create_run, methods=["POST"]),
|
|
388
407
|
Route("/runs/{run_id}", get_run, methods=["GET"]),
|
|
408
|
+
Route("/runs/{run_id}", delete_run, methods=["DELETE"]),
|
|
409
|
+
Route("/runs/{run_id}/retry", retry_run, methods=["POST"]),
|
|
389
410
|
Route("/runs/{run_id}/message", post_message, methods=["POST"]),
|
|
390
411
|
Route("/runs/{run_id}/steer", post_steer, methods=["POST"]),
|
|
391
412
|
Route("/runs/{run_id}/interrupt", post_interrupt, methods=["POST"]),
|