Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions agents/conversation_mgr.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def rename_session(session_id: str, title: str) -> bool:
s = data.get("sessions", {}).get(session_id)
if not s:
return False
s["title"] = title[:60] or "新对话"
s["title"] = title[:60].strip() or "新对话"
s["updated_at"] = _now()
_save_all(data)
return True
Expand Down Expand Up @@ -155,7 +155,7 @@ def append_messages(session_id: str, new_messages: list[dict]) -> dict | None:
if s.get("title", "新对话") == "新对话":
for m in msgs:
if m.get("role") == "user" and isinstance(m.get("content"), str):
s["title"] = m["content"][:28] or "新对话"
s["title"] = m["content"][:28].strip() or "新对话"
break
# rolling trim
if len(msgs) > _MAX_MESSAGES_PER_SESSION:
Expand Down
21 changes: 12 additions & 9 deletions agents/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,18 @@ def docker_cp(host_path: str, container: str, container_path: str) -> None:

def docker_exec(container: str, cmd: str, timeout: int = 300) -> tuple[int, str, str]:
"""Execute shell command in container and return (code, stdout, stderr)."""
result = subprocess.run(
["docker", "exec", container, "sh", "-c", cmd],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
)
return result.returncode, result.stdout, result.stderr
try:
result = subprocess.run(
["docker", "exec", container, "sh", "-c", cmd],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
)
return result.returncode, result.stdout, result.stderr
except subprocess.TimeoutExpired:
return -1, "", f"Command timed out after {timeout}s"


def vol_host() -> Path:
Expand Down
8 changes: 4 additions & 4 deletions sandbox/healer.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,14 @@ def heal(script_path: str, stderr: str, iteration: int) -> tuple[str, bool]:
"""
修复脚本。
返回 (fixed_code_or_empty, is_logic_err)。
如果是逻辑错误或超过最大迭代次数,返回 ("", True)。
如果是逻辑错误返回 ("", True);超过最大迭代次数返回 ("", False)。
"""
if iteration >= MAX_ITER:
return "", True

if is_logic_error(stderr):
return "", True

if iteration >= MAX_ITER:
return "", False

code = Path(script_path).read_text(encoding="utf-8")
tb = extract_traceback(stderr)

Expand Down
4 changes: 2 additions & 2 deletions sandbox/loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ def execute_with_healing(script_name: str) -> dict:

if exit_code == 0:
artifacts = archive_artifacts()
_update_ctx({"status": "success", "iterations": iteration, "last_error": None})
return {"status": "success", "artifacts": artifacts, "iterations": iteration}
_update_ctx({"status": "success", "iterations": iteration + 1, "last_error": None})
return {"status": "success", "artifacts": artifacts, "iterations": iteration + 1}

fixed_code, is_logic = heal(script_host_path, stderr, iteration)

Expand Down
16 changes: 12 additions & 4 deletions ui/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import json
import os
import re
import shlex
import subprocess
import sys
import time
Expand Down Expand Up @@ -633,9 +634,16 @@ async def list_files():

@app.get("/api/figures/{filename}")
async def get_figure(filename: str):
safe_roots = [FIGURES_DIR.resolve(), (PAPER_DIR / "figures").resolve()]
for p in [FIGURES_DIR / filename, PAPER_DIR / "figures" / filename]:
if p.exists() and p.is_file():
return FileResponse(str(p))
try:
resolved = p.resolve()
except Exception:
continue
if not any(str(resolved).startswith(str(root)) for root in safe_roots):
raise HTTPException(400, "Invalid filename")
if resolved.exists() and resolved.is_file():
return FileResponse(str(resolved))
raise HTTPException(404, f"Figure not found: {filename}")


Expand Down Expand Up @@ -1351,7 +1359,7 @@ async def pip_install_endpoint(request: Request):
"""Install a Python package inside the sandbox container (or locally)."""
body = await request.json()
package: str = body.get("package", "").strip()
if not package or any(c in package for c in [";", "&", "|", "`", "$"]):
if not package or not re.match(r'^[A-Za-z0-9_.\-\[\]]+$', package):
raise HTTPException(400, "Invalid package name")

loop = asyncio.get_event_loop()
Expand All @@ -1361,7 +1369,7 @@ def _run_pip():
from sandbox.runner import docker_exec, container_name
exit_code, stdout, stderr = docker_exec(
container_name(),
f"pip install {package} --quiet",
f"pip install {shlex.quote(package)} --quiet",
timeout=120,
)
return {"success": exit_code == 0, "output": (stdout + stderr).strip()}
Expand Down
Loading