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
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
DEEPSEEK_API_KEY=your-deepseek-api-key
DEEPSEEK_BASE_URL=https://api.deepseek.com
MAIN_MODEL=deepseek-flash
# Comma-separated model allow-list shown in the Dashboard model selector.
AGENT_AVAILABLE_MODELS=deepseek-flash,deepseek-v4-pro

GITEE_TOKEN=your-gitee-token
GITEE_API_BASE_URL=https://gitee.com/api/v5
Expand Down Expand Up @@ -53,6 +55,13 @@ LOCAL_SHELL_WORKSPACE=
LOCAL_SHELL_PROJECTS_DIR=projects
LOCAL_SHELL_SHARED_PYTHON_VENV=
LOCAL_SHELL_ENABLE_COMMAND_GUARD=true

# Durable multi-task queue and optional per-run OpenSandbox backend.
AGENT_MAX_CONCURRENT_RUNS=2
OPEN_SANDBOX_DOMAIN=http://127.0.0.1:8080
OPEN_SANDBOX_IMAGE=python:3.11
# Keep local until the OpenSandbox registry allows a full-stack image with Node/npm.
CODING_AGENT_RUNTIME_BACKEND=local
LOCAL_SHELL_ALLOW_NETWORK=false

AGENT_MAX_TOOL_CALLS=100
Expand Down
515 changes: 298 additions & 217 deletions agent/api/dashboard_routes.py

Large diffs are not rendered by default.

15 changes: 15 additions & 0 deletions agent/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
"""
from __future__ import annotations

from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

Expand All @@ -33,9 +35,22 @@
# ---------------------------------------------------------------
# 创建 FastAPI 应用实例
# ---------------------------------------------------------------
@asynccontextmanager
async def lifespan(_app: FastAPI):
from agent.core.run_queue import get_run_worker_pool

pool = get_run_worker_pool()
pool.start()
try:
yield
finally:
pool.stop()


app = FastAPI(
title="CODING Backend", # 应用名称
version="0.1.0", # 应用版本号
lifespan=lifespan,
)

# ---------------------------------------------------------------
Expand Down
22 changes: 17 additions & 5 deletions agent/core/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,24 @@
INTENT_MODEL_MAX_TOKENS = 200


def available_agent_models() -> list[str]:
"""Return the allow-listed model IDs offered by the Dashboard.

DeepSeek model IDs share the configured OpenAI-compatible endpoint and key.
Deployments may narrow or extend the list with AGENT_AVAILABLE_MODELS.
"""

configured = get_env("MAIN_MODEL", "deepseek-v4-pro").strip()
raw_models = get_env("AGENT_AVAILABLE_MODELS", "deepseek-flash,deepseek-v4-pro")
models = [item.strip() for item in raw_models.split(",") if item.strip()]
return list(dict.fromkeys([configured, *models]))


def make_main_model(model_id: str | None = None) -> BaseChatModel:
"""创建编码智能体使用的 DeepSeek 模型。

本地部署版只保留一个主模型,默认对齐 open-swe 使用的 `deepseek-v4-pro`。
这里不引入多模型 profile、fallback、路由器等生产级能力,
让开发者先理解“模型配置”和“Agent 编排”之间的关系。
默认支持 DeepSeek 当前的 Flash 与 Pro 模型;部署可以通过
`AGENT_AVAILABLE_MODELS` 限制选择范围。模型 ID 仍由服务端 allow-list 校验。

`thinking: disabled` 与 open-swe 的 DeepSeek 调用方式保持一致,
避免模型输出额外思考内容影响工具调用和最终回复。
Expand All @@ -29,8 +41,8 @@ def make_main_model(model_id: str | None = None) -> BaseChatModel:

configured_model = get_env("MAIN_MODEL", "deepseek-v4-pro").strip()
selected_model = (model_id or configured_model).strip()
if selected_model != configured_model:
raise ValueError(f"请求模型 {selected_model!r} 未在服务端 MAIN_MODEL 配置中启用")
if selected_model not in available_agent_models():
raise ValueError(f"请求模型 {selected_model!r} 未在服务端 AGENT_AVAILABLE_MODELS 配置中启用")

return init_chat_model(
model=selected_model,
Expand Down
24 changes: 22 additions & 2 deletions agent/core/repository_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import logging
import re
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any
Expand All @@ -12,6 +13,10 @@
from agent.repository import Repository, parse_repo_url

logger = logging.getLogger(__name__)
_TRANSIENT_GIT_NETWORK_ERRORS = (
"failed to receive handshake", "ssl/tls connection", "connection reset",
"connection timed out", "could not resolve host", "early eof", "remote end hung up",
)


class RepositoryWorkspaceError(RuntimeError):
Expand All @@ -34,6 +39,16 @@ def task_branch_name(thread_id: str) -> str:

def _run(backend: Any, command: str, *, cwd: str, timeout: int = 300) -> Any:
result = backend.run(command, cwd=cwd, timeout=timeout)
if command.startswith("git fetch"):
for attempt in range(1, 4):
detail = f"{result.stderr}\n{result.stdout}".lower()
if result.exit_code == 0 or not any(token in detail for token in _TRANSIENT_GIT_NETWORK_ERRORS):
break
if attempt == 3:
break
logger.warning("Transient Git fetch network failure; retry %s/2 in %s second(s)", attempt, attempt)
time.sleep(attempt)
result = backend.run(command, cwd=cwd, timeout=timeout)
combined_output = f"{result.stdout}\n{result.stderr}".lower()
if result.exit_code != 0 and command.startswith("git fetch") and "cannot open .git/fetch_head" in combined_output:
# Preserve the existing Windows recovery for a stale/locked FETCH_HEAD,
Expand Down Expand Up @@ -136,6 +151,7 @@ def prepare_repository_workspace(
*,
thread_id: str | None = None,
create_task_branch: bool = False,
workspace_directory: str | None = None,
) -> PreparedRepositoryWorkspace:
"""Clone or validate the exact selected repository, then select a safe base.

Expand All @@ -144,13 +160,17 @@ def prepare_repository_workspace(
its non-interactive provider credentials and token redaction remain in effect.
"""

directory = repo_project_dir(repo).replace("\\", "/")
directory = (workspace_directory or repo_project_dir(repo)).replace("\\", "/").strip("/")
if not directory or any(part in {".", ".."} for part in directory.split("/")):
raise RepositoryWorkspaceError("任务工作区路径不安全")
target = backend.workspace.resolve(directory)
project_root = backend.projects_dir
project_root.mkdir(parents=True, exist_ok=True)

if not target.exists():
clone = backend.run(f"git clone -- {repo.clone_url} {target.name}", cwd="projects", timeout=600)
target.parent.mkdir(parents=True, exist_ok=True)
relative_target = target.relative_to(project_root).as_posix()
clone = backend.run(f"git clone -- {repo.clone_url} {relative_target}", cwd="projects", timeout=600)
if clone.exit_code != 0:
detail = (clone.stderr or clone.stdout or "克隆失败").strip()
raise RepositoryWorkspaceError(f"无法克隆所选 {repo.provider} 仓库 {repo.full_name}:{detail}")
Expand Down
196 changes: 196 additions & 0 deletions agent/core/run_queue.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
"""Durable, bounded Agent run workers backed by the business store."""
from __future__ import annotations

import logging
import os
import threading
import uuid
from typing import Any

from agent.core.graph import get_store
from agent.core.runtime import run_agent_task, run_plain_chat_task

logger = logging.getLogger(__name__)


class RunCancelled(Exception):
"""Raised at an Agent event boundary after a cooperative cancellation request."""


class RunLeaseLost(Exception):
"""Raised when a worker can no longer prove ownership of its run."""


class RunWorkerPool:
def __init__(self, *, concurrency: int | None = None, lease_seconds: int = 90) -> None:
self.concurrency = max(1, concurrency or int(os.getenv("AGENT_MAX_CONCURRENT_RUNS", "2")))
self.lease_seconds = lease_seconds
self._stop = threading.Event()
self._threads: list[threading.Thread] = []

def start(self) -> None:
if self._threads:
return
self._stop.clear()
store = get_store()
try:
store.interrupt_stale_runs()
except Exception:
logger.exception("Could not reconcile stale Agent runs at startup")
for index in range(self.concurrency):
thread = threading.Thread(
target=self._worker_loop,
name=f"agent-run-worker-{index + 1}",
daemon=True,
)
self._threads.append(thread)
thread.start()
reaper = threading.Thread(target=self._reconcile_loop, name="agent-run-reaper", daemon=True)
self._threads.append(reaper)
reaper.start()
logger.info("Agent run worker pool started: concurrency=%s", self.concurrency)

def stop(self) -> None:
self._stop.set()
for thread in self._threads:
thread.join(timeout=2)
self._threads.clear()

def _worker_loop(self) -> None:
store = get_store()
worker_id = f"{os.getenv('CODING_WORKER_ID', 'api')}-{uuid.uuid4().hex[:8]}"
poll_seconds = max(0.1, float(os.getenv("AGENT_QUEUE_POLL_SECONDS", "0.5")))
while not self._stop.is_set():
try:
item = store.claim_next_run(
worker_id=worker_id,
ttl_seconds=self.lease_seconds,
max_active=self.concurrency,
)
if item is None:
self._stop.wait(poll_seconds)
continue
self._execute(item, worker_id)
except Exception:
logger.exception("Agent run queue worker failed while polling")
self._stop.wait(min(5, poll_seconds * 4))

def _reconcile_loop(self) -> None:
store = get_store()
interval = max(2, int(os.getenv("AGENT_RUN_REAPER_SECONDS", "10")))
while not self._stop.wait(interval):
try:
store.interrupt_stale_runs()
except Exception:
logger.exception("Could not reconcile expired Agent run leases")

def _execute(self, item: dict[str, Any], worker_id: str) -> None:
store = get_store()
run_id = str(item["run_id"])
thread_id = str(item["thread_id"])
payload = item.get("payload") or {}
heartbeat_stop = threading.Event()
ownership_lost = threading.Event()

def heartbeat() -> None:
while not heartbeat_stop.wait(max(5, self.lease_seconds // 3)):
try:
if not store.renew_run_lease(
run_id=run_id, worker_id=worker_id, ttl_seconds=self.lease_seconds
):
logger.warning("Run lease lost: run_id=%s", run_id)
ownership_lost.set()
return
except Exception:
logger.exception("Run lease heartbeat failed: run_id=%s", run_id)
ownership_lost.set()
return

def emit(event: str, data: dict[str, Any]) -> None:
if event not in {"thread_done", "done"} and store.is_run_cancel_requested(run_id):
raise RunCancelled("Run cancelled by user")
if event not in {"thread_done", "done"} and ownership_lost.is_set():
raise RunLeaseLost("Run worker lease was lost; task stopped to prevent duplicate execution")
event_payload = dict(data)
event_payload.setdefault("thread_id", thread_id)
event_payload.setdefault("run_id", run_id)
store.append_run_stream_event(
thread_id=thread_id, run_id=run_id, event=event, payload=event_payload
)

heartbeat_thread = threading.Thread(target=heartbeat, name=f"run-heartbeat-{run_id[:8]}", daemon=True)
heartbeat_thread.start()
try:
emit("run_status", {"status": "running"})
if payload.get("chat_only"):
run_plain_chat_task(
thread_id=thread_id, run_id=run_id,
model_id=payload.get("model_id"), event_sink=emit,
)
else:
run_agent_task(
repo_url=payload["repo_url"],
prompt=payload["content"],
thread_id=thread_id,
run_id=run_id,
event_sink=emit,
interaction_action=payload.get("interaction_action"),
plan_id=payload.get("plan_id"),
intervention_id=payload.get("intervention_id"),
model_id=payload.get("model_id"),
worker_id=worker_id,
)
if store.is_run_cancel_requested(run_id):
raise RunCancelled("Run cancelled by user")
if ownership_lost.is_set():
raise RunLeaseLost("Run worker lease was lost; task stopped to prevent duplicate execution")
terminal = store.get_run(thread_id, run_id) or {}
status = terminal.get("status") or "completed"
if status in {"queued", "running", "cancelling"}:
status = "completed"
store.finish_queued_run(thread_id=thread_id, run_id=run_id, status=status)
emit("thread_done", {"id": thread_id, "thread_id": thread_id, "status": status})
emit("done", {"status": status})
except RunCancelled as exc:
store.finish_queued_run(thread_id=thread_id, run_id=run_id, status="cancelled", error=str(exc))
store.update_thread_status(thread_id, "cancelled")
emit_terminal(store, thread_id, run_id, "cancelled", str(exc))
except RunLeaseLost as exc:
store.finish_queued_run(thread_id=thread_id, run_id=run_id, status="interrupted", error=str(exc))
store.update_thread_status(thread_id, "interrupted")
emit_terminal(store, thread_id, run_id, "interrupted", str(exc))
except Exception as exc:
logger.exception("Agent run failed: thread_id=%s run_id=%s", thread_id, run_id)
store.finish_queued_run(thread_id=thread_id, run_id=run_id, status="failed", error=str(exc))
store.update_thread_status(thread_id, "failed")
emit_terminal(store, thread_id, run_id, "failed", str(exc))
finally:
heartbeat_stop.set()
heartbeat_thread.join(timeout=1)


def emit_terminal(store: Any, thread_id: str, run_id: str, status: str, message: str) -> None:
for event, payload in (
("error", {"message": message, "thread_id": thread_id, "run_id": run_id}),
("thread_done", {"id": thread_id, "thread_id": thread_id, "status": status}),
("done", {"status": status}),
):
try:
store.append_run_stream_event(thread_id=thread_id, run_id=run_id, event=event, payload=payload)
except Exception:
logger.exception("Could not persist terminal run event: run_id=%s event=%s", run_id, event)


_pool: RunWorkerPool | None = None
_pool_lock = threading.Lock()


def get_run_worker_pool() -> RunWorkerPool:
global _pool
with _pool_lock:
if _pool is None:
_pool = RunWorkerPool()
return _pool


__all__ = ["RunCancelled", "RunLeaseLost", "RunWorkerPool", "get_run_worker_pool"]
Loading
Loading