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
83 changes: 60 additions & 23 deletions apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from pathlib import Path
import time
from typing import Annotated, Literal
from uuid import UUID, uuid5
from uuid import UUID, uuid4, uuid5

from anyio import CancelScope
from fastapi import APIRouter, Header
Expand Down Expand Up @@ -121,17 +121,17 @@ def path(self, project_id: UUID, session: str | None = None) -> Path:
self.projects._recover()
directory, _, _ = self.projects._load(db, project_id)
if session:
self.projects._lease(db, project_id, directory, session)
self.projects._lease(db, project_id, directory, session, browser_only=True)
return directory

def update(self, project_id: UUID, session: str | None = None, *, draft: Draft | None = None,
begin: dict | None = None, finish: dict | None = None, conversation_id: UUID | None = None,
before_begin=None) -> dict:
before_begin=None, agent_session: str | None = None) -> dict:
with self.projects.local.transaction() as db:
self.projects._recover()
directory, _, _ = self.projects._load(db, project_id)
if session:
self.projects._lease(db, project_id, directory, session)
self.projects._lease(db, project_id, directory, session, browser_only=True)
folder = child(directory, 'agent-runs')
folder.mkdir(exist_ok=True)
file = child(folder, 'conversation.json')
Expand All @@ -149,6 +149,8 @@ def update(self, project_id: UUID, session: str | None = None, *, draft: Draft |
raise ProjectError('这条消息已接受,请读取对话,不要重复发送。', 409)
if before_begin is not None:
before_begin()
if agent_session is not None:
self.projects.local.start_agent_session(db, project_id, directory, agent_session)
value['messages'].append(begin)
value['messages'].append({'id': str(uuid5(UUID(begin['id']), 'assistant')),
'role': 'assistant', 'text': '', 'status': 'streaming',
Expand Down Expand Up @@ -236,7 +238,7 @@ def activate(self, project_id: UUID, conversation_id: UUID, session: str, *, cre
with self.projects.local.transaction() as db:
self.projects._recover()
directory, _, _ = self.projects._load(db, project_id)
self.projects._lease(db, project_id, directory, session)
self.projects._lease(db, project_id, directory, session, browser_only=True)
folder = child(directory, 'agent-runs')
folder.mkdir(exist_ok=True)
file = child(folder, 'conversation.json')
Expand Down Expand Up @@ -472,6 +474,16 @@ def validate_connection():
if config is not None:
current = configs.resolve(str(value.modelId), 'agent')
generation.availability.require(current, _assistant_request(current), prepared)
async def renew_agent_session(run_session: str) -> None:
while True:
await asyncio.sleep(projects.local.LEASE_SECONDS / 3)
try:
if not await asyncio.to_thread(projects.local.renew_agent_session, run_session):
return
except Exception:
# A transient lock or I/O failure can recover before the lease expires.
logger.exception('Could not renew Agent project write session')

async def produce() -> None:
text, status, error, accepted = '', 'complete', None, False
activities = []
Expand All @@ -480,6 +492,9 @@ async def produce() -> None:
sources = {}
previous_sources = {}
plan = None
run_session = str(uuid4())
renewal = None
admission_write = None
try:
user = {'id': str(value.id), 'role': 'user', 'text': value.text, 'content': value.content,
'assets': [{'id': str(asset.id), 'name': asset.name, 'type': asset.metadata.mimeType,
Expand All @@ -488,9 +503,19 @@ async def produce() -> None:
'skills': value.skills, 'runtime': value.runtime, 'runtimeModel': value.runtimeModel,
'modelSelections': dict(value.modelSelections),
'model': model, 'modelIsCliDefault': model_is_cli_default, 'status': 'complete'}
saved = await asyncio.to_thread(conversations.update, project_id, session, begin=user,
conversation_id=value.conversationId, before_begin=validate_connection)
admission_write = asyncio.create_task(asyncio.to_thread(
conversations.update, project_id, session, begin=user,
conversation_id=value.conversationId, before_begin=validate_connection,
agent_session=run_session))
try:
saved = await asyncio.shield(admission_write)
except asyncio.CancelledError:
# A worker already writing admission can outlive task cancellation.
await admission_write
accepted = True
raise
accepted = True
renewal = asyncio.create_task(renew_agent_session(run_session))
events.put({'type': 'start', 'conversation': saved})
previous_sources = {source['id']: source for message in saved['messages'][:-2]
for source in message.get('sources', [])}
Expand All @@ -512,7 +537,7 @@ async def produce() -> None:
context[-1]['content'] += '\nUser model preferences for this turn: ' + json.dumps(preferences, ensure_ascii=False)
context[-1]['content'] += '\nUse these models for new generation unless the user explicitly requests another. If unavailable or unsuitable, explain and ask before substituting. Keep existing nodes on their configured models unless the user requests a change.'
run = RunContext(runtime=value.runtime, project_id=project_id, turn_id=value.id,
session=session, directory=directory, config=config, messages=context,
session=run_session, directory=directory, config=config, messages=context,
selected_skills=value.skills, thinking=value.thinking, model_selections=model_selections,
runtime_model=value.runtimeModel, skills=available, conversation_id=UUID(saved['conversationId']))
async with aclosing(runtimes.stream(run)) as stream:
Expand Down Expand Up @@ -560,21 +585,33 @@ async def produce() -> None:
status=500, code='operation_rejected')
logger.exception(f'agent.turn.failed project_id={project_id} turn_id={value.id}')
finally:
# Measurement is best effort: losing the ledger is acceptable,
# losing the turn's reply is not.
if accepted:
agent_timing.write(directory, value.id, timing, round(time.monotonic() - turn_started, 3))
for activity in activities:
if activity['status'] == 'running':
activity['status'] = 'interrupted'
saved = await asyncio.to_thread(conversations.update, project_id, finish={
'id': str(uuid5(value.id, 'assistant')), 'role': 'assistant', 'text': text, 'status': status,
'model': model, 'modelIsCliDefault': model_is_cli_default,
'runtime': value.runtime, 'thinking': value.thinking, 'tools': activities,
'sources': list(sources.values()),
**({'plan': plan} if plan is not None else {})}, conversation_id=value.conversationId)
else:
saved = None
try:
# Measurement is best effort: losing the ledger is acceptable,
# losing the turn's reply is not.
if accepted:
agent_timing.write(directory, value.id, timing, round(time.monotonic() - turn_started, 3))
for activity in activities:
if activity['status'] == 'running':
activity['status'] = 'interrupted'
saved = await asyncio.to_thread(conversations.update, project_id, finish={
'id': str(uuid5(value.id, 'assistant')), 'role': 'assistant', 'text': text, 'status': status,
'model': model, 'modelIsCliDefault': model_is_cli_default,
'runtime': value.runtime, 'thinking': value.thinking, 'tools': activities,
'sources': list(sources.values()),
**({'plan': plan} if plan is not None else {})}, conversation_id=value.conversationId)
else:
saved = None
finally:
if renewal is not None:
renewal.cancel()
with suppress(asyncio.CancelledError):
await renewal
if admission_write is not None:
try:
await asyncio.to_thread(projects.local.release_agent_session, run_session)
except Exception:
# The lease still expires when renewal stops.
logger.exception('Could not release Agent project write session')
events.put({'type': 'end', 'conversation': saved, 'error': error})

if project_id in active:
Expand Down
4 changes: 4 additions & 0 deletions docs/architecture/agent-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ Default 与 OpenCode CLI 分别配置。外部 CLI 不读取 OpenDirector 保存

业务入口使用 Typer CLI,通过 `opendirector --help` 和子命令的 `--help` 渐进发现操作。查询、编辑及生成命令调用共用业务服务。Agent 通过受令牌保护的本轮连接继承工程范围、编辑会话、执行目录和操作回执;CLI 子进程退出不终止已接受的后台任务。普通终端通过现有 HTTP API 连接服务,写入申请独立编辑会话并遵守工程锁,查询不申请租约。`--session` 可使用已有授权会话。`--operation-id` 提供稳定修改身份,同身份相同输入重放返回原回执,不同输入拒绝。

接受轮次时,服务端校验画布的工程会话,并为本轮签发独立的工程写入租约。运行期间服务端负责续租,画布关闭或断线后仍可执行本轮已授权的写入。运行结束或停止后释放租约。工程路径、对象锁和预期版本仍由共享业务服务校验,重新打开画布后用户可以继续编辑。

The server validates the canvas session when it accepts a turn and grants the turn its own project write lease. The server renews that lease while the turn runs, including after the canvas closes or disconnects, and releases it when the turn completes or stops. The shared services still check the project path, object locks and expected revisions. A reopened canvas can edit concurrently.

新文件通过 `opendirector asset import` 登记,再根据需要调用 `opendirector canvas add-material` 展示。发布回执、素材登记和画布展示分别表达,不以创建节点代替文件交付。

## Skill 加载与媒体输入
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,13 @@ def __init__(self, local: LocalProjects):
def _checkpoint(self, stage):
"""Fault-injection boundary. Never participates in production decisions."""

def _lease(self, db, project_id, path, session):
def _lease(self, db, project_id, path, session, *, browser_only=False):
if session is None:
raise ProjectError('修改工程需要已打开的会话。', 409)
identifier(session)
lease = db.execute('SELECT path FROM sessions WHERE id=? AND project_id=? AND expires>?',
(session, str(project_id), time.time())).fetchone()
agent_key = session if browser_only else self.local.agent_session_key(session)
lease = db.execute('SELECT path FROM sessions WHERE id IN (?,?) AND project_id=? AND expires>?',
(session, agent_key, str(project_id), time.time())).fetchone()
if lease is None:
# A stable code lets the page renew its lease and resend instead of failing every save.
raise ProjectError('工程已关闭或会话已过期,请重新打开后保存。', 409, code='session_expired')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ def write_json(path: Path, value) -> None:
class LocalProjects:
"""Coordination only; never reads, migrates or repairs old project data."""
LEASE_SECONDS = 60
# A run blocks project moves and deletion like a browser lease. Its
# separate key lets browsers open or release their own editing session.
_AGENT_SESSION_PREFIX = "agent:"

def __init__(self, repository: Path):
self.repository = repository.resolve()
Expand Down Expand Up @@ -122,14 +125,35 @@ def _conflict(parent: Path, name: str, source: Path | None = None):
def _open(self, db, project: dict, session: str):
identifier(session)
project_id = project["id"]
if db.execute("SELECT 1 FROM sessions WHERE project_id=? AND id<>? AND expires>?", (project_id, session, time.time())).fetchone():
if db.execute("SELECT 1 FROM sessions WHERE project_id=? AND id<>? AND id NOT LIKE ? AND expires>?",
(project_id, session, self._AGENT_SESSION_PREFIX + "%", time.time())).fetchone():
raise ProjectError("该项目正在其他窗口中打开,请先关闭后再试。", 409, code="project_open_elsewhere")
lease = db.execute("SELECT path FROM sessions WHERE id=? AND project_id=? AND expires>?", (session, project_id, time.time())).fetchone()
if lease and lease["path"] != project["path"]:
raise ProjectError("项目目录已在应用外改名或移动,请复制未保存内容并刷新页面。", 409)
db.execute("INSERT INTO sessions(id,project_id,expires,path) VALUES (?,?,?,?) ON CONFLICT(id) DO UPDATE SET project_id=excluded.project_id,expires=excluded.expires,path=excluded.path", (session, project_id, time.time() + self.LEASE_SECONDS, project["path"]))


def agent_session_key(self, session: str) -> str:
return self._AGENT_SESSION_PREFIX + identifier(session)

def start_agent_session(self, db, project_id, path: Path, session: str):
"""Called in the transaction that validates the browser lease and accepts the turn."""
now = time.time()
db.execute("DELETE FROM sessions WHERE expires<=? AND id LIKE ?",
(now, self._AGENT_SESSION_PREFIX + "%"))
db.execute("INSERT INTO sessions(id,project_id,expires,path) VALUES (?,?,?,?)",
(self.agent_session_key(session), str(project_id), now + self.LEASE_SECONDS, str(path)))

def renew_agent_session(self, session: str) -> bool:
with self.transaction() as db:
now = time.time()
return bool(db.execute("UPDATE sessions SET expires=? WHERE id=? AND expires>?",
(now + self.LEASE_SECONDS, self.agent_session_key(session), now)).rowcount)

def release_agent_session(self, session: str):
self.release(self.agent_session_key(session))

def release(self, session: str):
with self.transaction() as db:
db.execute("DELETE FROM sessions WHERE id=?", (session,))
Loading
Loading