Skip to content
Open
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
132 changes: 126 additions & 6 deletions apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

from opendirector.agent.catalog import model_choices
from opendirector.agent.context import RunContext, RuntimeId
from opendirector.agent.interactions import Interaction, InteractionGate
from opendirector.agent.citations import referenced_sources, with_trace_sources
from opendirector.agent.runtime import AgentRuntimes, runtime_available, configured_runtimes, runtime_spec, runtime_catalog, runtime_status
from opendirector.agent.skills import skills
Expand Down Expand Up @@ -60,6 +61,12 @@ class Draft(BaseModel):
skills: list[str] = Field(default_factory=list, max_length=1)


class InteractionAnswer(BaseModel):
model_config = ConfigDict(extra='forbid')
text: str = Field(default='', max_length=2000)
optionId: str | None = Field(default=None, max_length=80)


class Turn(BaseModel):
conversationId: UUID | None = None
model_config = ConfigDict(extra='forbid')
Expand Down Expand Up @@ -226,6 +233,68 @@ def stamped(message):
result = public_conversation(value)
return with_trace_sources(result, directory)

def set_interaction(self, project_id: UUID, interaction: Interaction, *, text: str = '') -> None:
"""Persist one turn's authoritative interaction state.

The message keeps its partial text so a reload shows the question with
the context that produced it. Only this turn's assistant record changes.
"""
with self.projects.local.transaction() as db:
self.projects._recover()
directory, _ = self.projects._find(db, project_id)
folder = child(directory, 'agent-runs')
folder.mkdir(exist_ok=True)
file = child(folder, 'conversation.json')
value = read_json(file) if file.exists() else {'messages': [], **Draft().model_dump()}
target = next((message for message in value['messages']
if message.get('id') == interaction.messageId), None)
if target is None:
raise ProjectError('对话中没有对应这一轮的回复。', 409)
target['interaction'] = interaction.payload()
if interaction.status == 'pending':
target['status'] = 'awaiting_decision'
elif interaction.status == 'answered':
target['status'] = 'streaming'
if text:
target['text'] = text
durable_json(file, value)

def reacquire_agent_session(self, project_id: UUID, session: str) -> None:
"""Re-take the Agent write lease after a user decision paused the turn."""
with self.projects.local.transaction() as db:
self.projects._recover()
directory, _ = self.projects._find(db, project_id)
self.projects.local.start_agent_session(db, project_id, directory, session)

def interrupt_stale(self, project_id: UUID) -> dict:
"""A restarted server has no live run, so an open wait is interrupted.

This is a read-repair on conversation load: it prevents the UI from
offering an answer that no process can receive.
"""
with self.projects.local.transaction() as db:
self.projects._recover()
directory, _ = self.projects._find(db, project_id)
file = child(child(directory, 'agent-runs'), 'conversation.json')
if not file.exists():
value = {'messages': [], **Draft().model_dump()}
value['conversationId'] = str(uuid5(project_id, 'assistant'))
return with_trace_sources(public_conversation(value), directory)
value = read_json(file)
changed = False
for message in value.get('messages', []):
if message.get('status') not in {'streaming', 'awaiting_decision'}:
continue
message['status'] = 'interrupted'
interaction = message.get('interaction')
if isinstance(interaction, dict) and interaction.get('status') == 'pending':
interaction['status'] = 'cancelled'
changed = True
if changed:
durable_json(file, value)
value['conversationId'] = value.get('conversationId') or str(uuid5(project_id, 'assistant'))
return with_trace_sources(public_conversation(value), directory)

def queue(self, project_id: UUID, session: str, message: dict, conversation_id: UUID | None = None) -> dict:
"""Store a supplementary message that runs after the active turn.

Expand Down Expand Up @@ -482,6 +551,7 @@ class Chain:
task: asyncio.Task | None = None
stopped: bool = False
last: dict | None = None
interactions: InteractionGate | None = None


def agent_routes(projects, generation, configs, provider=None, *, active=None) -> APIRouter:
Expand Down Expand Up @@ -572,9 +642,11 @@ def turn_jobs(project_id: UUID, turn_id: UUID):
async def conversation(project_id: UUID):
value = await asyncio.to_thread(conversations.update, project_id)
running = active.get(project_id)
# A streaming message without a chain was interrupted (for example by a
# restart); with one, the client can attach to the turn it is running.
if running is not None:
# A streaming or awaiting message without a chain was interrupted (for
# example by a restart); with one, the client can attach to the turn.
if running is None:
value = await asyncio.to_thread(conversations.interrupt_stale, project_id)
else:
value = {**value, 'activeTurnId': str(running.turn)}
return value

Expand Down Expand Up @@ -737,6 +809,10 @@ async def produce_one(chain: Chain, plan: dict) -> tuple[dict | None, str | None
timing: dict = {}
turn_started = time.monotonic()
renewal: asyncio.Task | None = None
gate: InteractionGate | None = None

async def persist_interaction(interaction: Interaction) -> None:
await asyncio.to_thread(conversations.set_interaction, project_id, interaction, text=text)

async def renew_session() -> None:
"""Keep the project writable while a turn outlives the lease it started under."""
Expand All @@ -748,9 +824,30 @@ async def renew_session() -> None:
except Exception:
logger.exception(f'agent.session.renew.failed project_id={project_id}')

async def pause_for_user() -> None:
"""A waiting decision must not hold the project against the user."""
nonlocal renewal
if renewal is not None:
renewal.cancel()
with suppress(asyncio.CancelledError):
await renewal
renewal = None
await asyncio.to_thread(projects.local.release_agent_session, run_session)

async def resume_after_user() -> None:
"""Re-take the lease only after a valid answer is ready to continue."""
nonlocal renewal
await asyncio.to_thread(conversations.reacquire_agent_session, project_id, run_session)
if renewal is None:
renewal = asyncio.create_task(renew_session())

try:
saved = plan['start']
chain.conversation_id = UUID(saved['conversationId'])
gate = InteractionGate(turn_id=turn_id, conversation_id=chain.conversation_id,
persist=persist_interaction, emit=chain.events.put,
wait=pause_for_user, resume=resume_after_user)
chain.interactions = gate
chain.events.put({'type': 'start', 'conversation': saved})
renewal = asyncio.create_task(renew_session())
previous_sources = {source['id']: source for reply in saved['messages'][:-2]
Expand Down Expand Up @@ -778,7 +875,8 @@ async def renew_session() -> None:
session=run_session, directory=plan['directory'], config=plan['config'], messages=context,
selected_skills=message.get('skills') or [], thinking=plan['thinking'],
model_selections=plan['model_selections'], runtime_model=message.get('runtimeModel'),
skills=plan['available'], conversation_id=chain.conversation_id)
skills=plan['available'], conversation_id=chain.conversation_id,
interactions=gate)
async with aclosing(runtimes.stream(run)) as stream:
async for event in stream:
if event['type'] == 'delta':
Expand Down Expand Up @@ -825,6 +923,8 @@ async def renew_session() -> None:
status=500, code='operation_rejected')
logger.exception(f'agent.turn.failed project_id={project_id} turn_id={turn_id}')
finally:
if gate is not None:
await gate.close()
for activity in activities:
if activity['status'] == 'running':
activity['status'] = 'interrupted'
Expand Down Expand Up @@ -873,8 +973,17 @@ async def run_chain(chain: Chain, plan: dict) -> None:
break
run_session = str(uuid4())
async with admission.setdefault(project_id, asyncio.Lock()):
dispatched = None if chain.stopped else await asyncio.to_thread(
conversations.dispatch, project_id, chain.session, run_session)
try:
dispatched = None if chain.stopped else await asyncio.to_thread(
conversations.dispatch, project_id, chain.session, run_session)
except ProjectError as failure:
# The user closed the tab while this turn waited. No
# later message can be admitted through that session;
# keep the finished turn readable and cancel the queue.
if failure.code != 'session_expired':
raise
await asyncio.to_thread(conversations.cancel_queued, project_id, None)
break
if dispatched is None:
break
chain.turn = UUID(dispatched['message']['id'])
Expand Down Expand Up @@ -921,6 +1030,17 @@ def rejected(turn_id: UUID, failure: ProjectError, accept_language: str | None)
status=failure.status, code=failure.code)})
return StreamingResponse(events.follow(), media_type='text/event-stream')

@router.post('/interactions/{interaction_id}/answer')
async def answer_interaction(project_id: UUID, interaction_id: str, value: InteractionAnswer,
x_opendirector_session: UUID = Header()):
await asyncio.to_thread(conversations.path, project_id, str(x_opendirector_session))
chain = active.get(project_id)
if chain is None or chain.interactions is None:
raise ProjectError('该询问已回答、取消或不存在。', 409)
if not await chain.interactions.answer(interaction_id, value.model_dump(exclude_none=True)):
raise ProjectError('该询问已回答、取消或不存在。', 409)
return {'ok': True, 'interactionId': interaction_id}

@router.post('/turns/{turn_id}/stop')
async def stop(project_id: UUID, turn_id: UUID, x_opendirector_session: UUID = Header()):
session = str(x_opendirector_session)
Expand Down
1 change: 1 addition & 0 deletions docs/development/i18n.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ npm run check:i18n
| 错误、状态与后端回执 | [errors.ts](../../src/i18n/messages/zh-CN/errors.ts) | [errors.ts](../../src/i18n/messages/en-US/errors.ts) |
| 后端请求错误 | [api.ts](../../src/i18n/messages/zh-CN/api.ts) | [api.ts](../../src/i18n/messages/en-US/api.ts) |
| 工具编辑器 | [tools.ts](../../src/i18n/messages/zh-CN/tools.ts) | [tools.ts](../../src/i18n/messages/en-US/tools.ts) |
| 任务通知 | [taskNotifications.ts](../../src/i18n/messages/zh-CN/taskNotifications.ts) | [taskNotifications.ts](../../src/i18n/messages/en-US/taskNotifications.ts) |

审校时重点看:英文长度是否导致按钮换行、专有名词是否统一、错误文案是否给出下一步动作、数量与占位符是否自然。

Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/opendirector/agent/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from pydantic import JsonValue

from opendirector.agent.interactions import InteractionGate
from opendirector.domain.agent_runtime import RuntimeId
from opendirector.infrastructure.local_projects import write_json

Expand All @@ -27,6 +28,7 @@ class RunContext:
thinking: str = 'auto'
runtime_model: str | None = None
skills: list[dict[str, str]] = field(default_factory=list)
interactions: InteractionGate | None = None

def native_session_path(self) -> Path | None:
if self.conversation_id is None:
Expand Down
17 changes: 17 additions & 0 deletions packages/core/src/opendirector/agent/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,21 @@ async def call(self, call_id: str, name: str, arguments: dict[str, JsonValue]) -
return await asyncio.shield(task)

async def execute(self, call_id: str, name: str, arguments: dict[str, JsonValue]) -> ToolResult:
if name == 'ask_user':
try:
if self.closed or self.run.interactions is None:
raise ProjectError('本轮不能等待用户输入。', 409)
if not call_id or len(call_id) > 512:
raise ProjectError('工具调用标识或名称无效。')
schema = next(item['function']['parameters'] for item in tools() if item['function']['name'] == name)
if 'properties' in schema and (set(arguments) - set(schema['properties']) or set(schema.get('required', [])) - set(arguments)):
raise ProjectError('工具参数缺失或包含未定义字段。')
return ToolResult(value=await self.run.interactions.ask(call_id, arguments))
except (ProjectError, ValueError, KeyError, OSError) as failure:
details = {'error': str(failure)}
if isinstance(failure, ProjectError):
details['code'] = failure.code
return ToolResult(value=details, error=str(failure))
async with (nullcontext() if _read_only(name, arguments) else self.execution_lock):
try:
if self.closed:
Expand Down Expand Up @@ -126,6 +141,8 @@ async def execute(self, call_id: str, name: str, arguments: dict[str, JsonValue]

async def close(self) -> None:
self.closed = True
if self.run.interactions is not None:
await self.run.interactions.close()
for identity, task in self.calls.values():
name, arguments = json.loads(identity)
if name == 'query' and isinstance(arguments, dict) and arguments.get('type') in WAITING_QUERIES:
Expand Down
Loading
Loading