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
140 changes: 139 additions & 1 deletion apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
thinking: Literal['auto', 'low', 'medium', 'high'] = 'auto'
modelSelections: dict[str, str | None] = Field(default_factory=dict)
skills: list[str] = Field(default_factory=list, max_length=1)
delivery: Literal['queue', 'insert'] = 'queue'


def draft_content_is_empty(content):
Expand Down Expand Up @@ -195,6 +196,35 @@
durable_json(file, value)
return queued

def insert(self, project_id: UUID, session: str, message: dict,
conversation_id: UUID | None = None) -> dict:
"""Store a message that was handed to the turn already running.

It is written directly before the streaming reply, so the transcript
reads the way the model met it: after the user's first message and
before the answer was finished.
"""
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)
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()}
value['conversationId'] = value.get('conversationId') or str(uuid5(project_id, 'assistant'))
if conversation_id is not None and str(conversation_id) != value['conversationId']:
raise ProjectError('当前对话已切换,请重新加载后重试;原对话未覆盖。', 409)
if any(item['id'] == message['id'] for item in value['messages']):
raise ProjectError('这条消息已接受,请读取对话,不要重复发送。', 409)
inserted = {**message, 'status': 'inserted'}
index = len(value['messages'])
if index and value['messages'][-1].get('status') == 'streaming':
index -= 1
value['messages'].insert(index, inserted)
durable_json(file, value)
return inserted

def dispatch(self, project_id: UUID, session: str | None = None,
agent_session: str | None = None) -> dict | None:
"""Start the oldest queued message as this turn's user message.
Expand Down Expand Up @@ -248,6 +278,52 @@
durable_json(file, value)
return cancelled

def retract(self, project_id: UUID, session: str, message_id: UUID) -> dict:
"""Take a message back while it is still waiting in the queue.

A message that already started belongs to the conversation now: it can
be stopped, but removing it would leave the reply it produced without
the words that asked for it.
"""
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)
file = child(child(directory, 'agent-runs'), 'conversation.json')
value = read_json(file) if file.exists() else {'messages': [], **Draft().model_dump()}
found = next((item for item in value['messages'] if item['id'] == str(message_id)), None)
if found is None:
raise ProjectError('这条消息不在当前对话里,请重新加载。', 404)
if found.get('status') != 'queued':
raise ProjectError('这条消息已经开始执行,停止回复后才能撤回。', 409)
value['messages'] = [item for item in value['messages'] if item['id'] != str(message_id)]
durable_json(file, value)
result = public_conversation(value)
return {'retracted': str(message_id), 'conversation': with_trace_sources(result, directory)}

def retract(self, project_id: UUID, session: str, message_id: UUID) -> dict:
"""Take a message back while it is still waiting in the queue.

A message that already started belongs to the conversation now: it can
be stopped, but removing it would leave the reply it produced without
the words that asked for it.
"""
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)
file = child(child(directory, 'agent-runs'), 'conversation.json')
value = read_json(file) if file.exists() else {'messages': [], **Draft().model_dump()}
found = next((item for item in value['messages'] if item['id'] == str(message_id)), None)
if found is None:
raise ProjectError('这条消息不在当前对话里,请重新加载。', 404)
if found.get('status') != 'queued':
raise ProjectError('这条消息已经开始执行,停止回复后才能撤回。', 409)
value['messages'] = [item for item in value['messages'] if item['id'] != str(message_id)]
durable_json(file, value)
result = public_conversation(value)
return {'retracted': str(message_id), 'conversation': with_trace_sources(result, directory)}

def list(self, project_id: UUID) -> dict:
directory = self.path(project_id)
file = child(child(directory, 'agent-runs'), 'conversation.json')
Expand Down Expand Up @@ -416,6 +492,7 @@
task: asyncio.Task | None = None
stopped: bool = False
last: dict | None = None
steer: asyncio.Queue[str] | None = None


def agent_routes(projects, generation, configs, provider=None, *, active=None) -> APIRouter:
Expand Down Expand Up @@ -614,7 +691,7 @@
config = await asyncio.to_thread(configs.resolve, message['modelConfigId'], 'agent')
except Exception:
logger.warning('agent.queue.model_missing project_id=%s message_id=%s',
project_id, message.get('id'))
available = await skills(projects.local.repository, directory) if spec.supportsSkills else []
model_selections = dict(message.get('modelSelections') or {})
return {'session': session, 'directory': directory, 'config': config, 'available': available,
Expand Down Expand Up @@ -679,7 +756,7 @@
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, steer=chain.steer)
async with aclosing(runtimes.stream(run)) as stream:
async for event in stream:
if event['type'] == 'delta':
Expand Down Expand Up @@ -768,6 +845,7 @@
turn_id, saved, error, status = chain.turn, None, None, 'complete'
try:
while True:
chain.steer = asyncio.Queue()
saved, error, status = await produce_one(chain, plan)
turn_id = UUID(plan['message']['id'])
if status != 'complete' or chain.stopped:
Expand All @@ -789,6 +867,7 @@
status, error = 'stopped', None
raise
finally:
chain.steer = None
chain.events.put({'type': 'end', 'turnId': str(turn_id), 'nextTurnId': None,
'conversation': saved if saved is not None else chain.last, 'error': error})
if active.get(project_id) is chain:
Expand Down Expand Up @@ -888,8 +967,32 @@
"""
session = str(x_opendirector_session)
async with admission.setdefault(project_id, asyncio.Lock()):
if value.delivery == 'insert' and (value.assets or value.content or value.skills):
# Checked before the run settings are rebuilt: a supplement is
# text for the turn that is already running, nothing else.
raise ProjectError('运行中插入只支持文字,请等回复结束后再附带素材或技能。', 409)
plan = await prepare(project_id, value, session, accept_language)
chain = active.get(project_id)
if value.delivery == 'insert':
# Text handed to the turn that is already running. It reaches the
# model through the runtime's own channel, never through a second
# turn, so the answer keeps the work it has already done.
if chain is None:
raise ProjectError('当前没有正在执行的回复,直接发送即可。', 409)
if value.conversationId is not None and chain.conversation_id is not None \
and str(value.conversationId) != str(chain.conversation_id):
raise ProjectError('当前对话已切换,请重新加载后重试;原对话未覆盖。', 409)
spec = runtime_spec(value.runtime)
if not spec.supportsSteering:
raise ProjectError(f'{spec.label} 不支持在回复执行中插入内容,请改用排队。', 409)
if chain.steer is None:
raise ProjectError('这一轮回复刚刚结束,请重新发送。', 409)
chain.steer.put_nowait(value.text)
inserted = await asyncio.to_thread(conversations.insert, project_id, session,
plan['message'], value.conversationId)
chain.events.put({'type': 'steered', 'message': inserted})
return JSONResponse({'inserted': inserted, 'chainId': str(chain.id),
'turnId': str(chain.turn)}, status_code=202)
if chain is not None:
if value.conversationId is not None and chain.conversation_id is not None \
and str(value.conversationId) != str(chain.conversation_id):
Expand All @@ -912,4 +1015,39 @@
started['run_session'] = start_session
return launch(project_id, started, UUID(dispatched['conversation']['conversationId']))

@router.delete('/messages/{message_id}')
async def retract(project_id: UUID, message_id: UUID, x_opendirector_session: UUID = Header()):
"""Take back a message that has not started yet.

Retracting under the admission lock is what keeps it from being picked
up in the same instant: the message is either still waiting and goes
away, or it has started and the caller is told to stop it instead.
"""
session = str(x_opendirector_session)
async with admission.setdefault(project_id, asyncio.Lock()):
result = await asyncio.to_thread(conversations.retract, project_id, session, message_id)
chain = active.get(project_id)
if chain is not None:
chain.events.put({'type': 'retracted', 'messageId': str(message_id)})
return result

@router.post('/queue/dispatch')
async def dispatch(project_id: UUID, x_opendirector_session: UUID = Header(),
accept_language: str | None = Header(default=None, alias='Accept-Language')):
"""Continue the queue when nothing is running.

Messages outlive a restart, and a turn that failed leaves them waiting;
this starts the oldest one so the user does not have to retype it.
"""
session = str(x_opendirector_session)
async with admission.setdefault(project_id, asyncio.Lock()):
if project_id in active:
raise ProjectError('当前工程已有回复正在执行。', 409)
dispatched = await asyncio.to_thread(conversations.dispatch, project_id, session)
if dispatched is None:
raise ProjectError('没有等待执行的排队消息。', 409)
plan = await plan_for(project_id, dispatched['message'], session, accept_language)
plan['start'] = dispatched['conversation']
return launch(project_id, plan, UUID(dispatched['conversation']['conversationId']))

return router
6 changes: 3 additions & 3 deletions docs/architecture/agent-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Harness 指承担模型调用、工具执行和上下文管理的 Agent 执行
| --- | --- | --- |
| Default | 固定版本的 bundled OpenCode | OpenDirector 模型配置,经本地模型代理访问服务 |
| OpenCode CLI | opencode,优先 PATH,再查找常见 CLI 安装目录 | CLI 原生配置与模型目录 |
| Codex | 优先 PATH 中的 codex,再查找常见桌面版与 CLI 安装目录 | 原生认证与模型目录;隔离启动前解析所选模型或默认模型 |
| Codex | 优先 PATH 中的 codex,再查找常见桌面版与 CLI 安装目录;以 `app-server` 常驻进程通信,沙箱与审批策略作为协议参数传入 | 原生认证与模型目录;隔离启动前解析所选模型或默认模型 |
| Claude Code | claude,优先 PATH,再查找常见 CLI 安装目录 | 原生认证、环境变量与初始化模型目录 |
| JiuwenSwarm | jiuwenswarm-process,优先 PATH,再查找常见 CLI 安装目录,通过 stdin/stdout JSONL 直接调用 | 本机 Jiuwen 模型目录、配置与环境变量 |
| DeepSeek Harness | dsh,优先 PATH,再查找常见 CLI 安装目录,以 acp profile 运行标准 JSON-RPC | CLI 原生 profile、模型目录与认证 |
Expand Down Expand Up @@ -55,7 +55,7 @@ Default 将模型配置中的输入模态传入 bundled OpenCode。外部 harnes

Search citations keep their native markers in the original reply and trace. Completed Codex MCP web-search results supply validated source IDs, HTTP(S) URLs and titles through `sources` events; the conversation retains this metadata with the reply. The UI splits tool activities using raw text offsets before formatting prose citations as source links, and uses the same formatting for copying. Code examples remain literal. Missing sources and incomplete final markers have a localized fallback. For saved Codex replies without source metadata, queries derive it from the matching turn's project-local trace without rewriting the conversation; a bounded metadata cache is invalidated by trace modification time and size. Reading a trace never requests a model call.

同一工程同时只执行一个回复。运行期间仍可提交补充消息:`POST /assistant/messages` 在空闲时直接开始一轮,在运行中返回 202 并按 `queueSeq` 把消息排入投递队列,本轮结束后依次运行。`end` 事件带 `nextTurnId` 时事件流不关闭,客户端因此能在同一条连接上接着收到下一轮;断线重连用 `GET /turns/{turn_id}/events?after=<seq>` 从已收到的最后一帧续读;链已经推进到下一轮时,客户端手里上一轮的 turn id 同样能找到这条链,不必等页面刷新。排队消息立即出现在会话里并可读;停止时整条链一起停止,排队消息标记为 `cancelled` 并保留下来供用户重新发送。运行事件转换为回复正文和工具活动,保存到对应会话;原生事件与业务工具事件追加到 `agent-runs/<turn-id>.<runtime>.jsonl`。Default 使用 `opencode` 作为轨迹文件的 runtime 名称。
同一工程同时只执行一个回复。运行期间仍可提交补充消息:`POST /assistant/messages` 在空闲时直接开始一轮,在运行中返回 202 并按 `queueSeq` 把消息排入投递队列,本轮结束后依次运行。`end` 事件带 `nextTurnId` 时事件流不关闭,客户端因此能在同一条连接上接着收到下一轮;断线重连用 `GET /turns/{turn_id}/events?after=<seq>` 从已收到的最后一帧续读;链已经推进到下一轮时,客户端手里上一轮的 turn id 同样能找到这条链,不必等页面刷新。排队消息立即出现在会话里并可读;停止时整条链一起停止,排队消息标记为 `cancelled` 并保留下来供用户重新发送。运行中还可以把补充文字直接交给这一轮:`POST /assistant/messages` 带 `delivery: "insert"` 时,文字经 runtime 的原生通道进入正在执行的模型循环,而不是另起一轮,因此这一轮已经做的工作不会重来。插入只接受纯文字,素材与技能要等回复结束后再发;runtime 不支持同轮插入时返回 409 并说明原因,用户可改用排队。Codex 通过 `turn/steer` 提供该通道;其它 runtime 在接入原生通道前一律排队。运行事件转换为回复正文和工具活动,保存到对应会话;原生事件与业务工具事件追加到 `agent-runs/<turn-id>.<runtime>.jsonl`。Default 使用 `opencode` 作为轨迹文件的 runtime 名称。

Default 的模型网关在 `agent-runs/<turn-id>.model.jsonl` 记录实际转发的请求体,包括生效的系统消息、会话上下文、工具 Schema 与模型参数。请求 ID 关联上游 HTTP 状态、响应头等待耗时和传输错误。该文件仅供本地调试,创建权限为 `0600`,不记录 HTTP 鉴权头。回复片段、工具结果和 token 用量仍见原生轨迹。

Expand Down Expand Up @@ -91,7 +91,7 @@ English summary: a Job created by an Agent `generation.submit` records `agentRun
| Harness | 执行约束 |
| --- | --- |
| OpenCode | 工具权限配置开放 Shell、文件读取、已发现技能和业务 CLI |
| Codex | workspace-write 沙箱,开放 Shell 和业务 CLI |
| Codex | `app-server` 以 workspace-write 沙箱、`never` 审批策略启动线程,开放 Shell 和业务 CLI |
| Claude Code | 明确允许 Skill、Bash、Read 和业务 CLI |
| JiuwenSwarm | 明确允许 skill_tool、list_skill、read_file、bash 和业务 CLI |
| DeepSeek Harness | 沿用原生工具与权限;Skill 限于本轮快照,业务操作通过 Shell 调用 opendirector,未承接的审批不自动批准 |
Expand Down
Loading
Loading