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: 6 additions & 3 deletions apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,7 @@ async def produce_one(chain: Chain, plan: dict) -> tuple[dict | None, str | None
text, status, error = '', 'complete', None
activities: list[dict] = []
edited_documents: dict[str, int] = {}
positions: dict[str, int] = {}
sources: dict = {}
previous_sources: dict = {}
steps = None
Expand Down Expand Up @@ -838,14 +839,16 @@ async def renew_session() -> None:
# Measurement is a side ledger: the per-call numbers must
# not become part of the tool call the turn persists.
agent_timing.note(timing, event)
previous = next((item for item in activities if item['id'] == event['id']), None)
position = positions.get(event['id'])
previous = activities[position] if position is not None else None
activity = {**{key: item for key, item in event.items()
if key not in {'type', 'timing'}},
'textOffset': previous['textOffset'] if previous else len(text)}
if previous is None:
if position is None:
positions[event['id']] = len(activities)
activities.append(activity)
else:
activities[activities.index(previous)] = activity
activities[position] = activity
event = {'type': 'tool', **activity}
chain.events.put(event)
except asyncio.CancelledError:
Expand Down
4 changes: 3 additions & 1 deletion docs/architecture/agent-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ Antigravity 沿用本机 agy 的账号登录,命令行里不传模型凭证。

适配层为每轮创建 `agent-runs/<turn-id>/work/`,启动 harness 并注入本轮 CLI 执行入口。子进程 cwd、PWD 和 ACP 工作区始终指向本轮执行目录;会话身份单独持久化。原生工具以此目录为工作目录,通过继承的 PATH 查找 FFmpeg、ffprobe 等程序。

业务入口使用 Typer CLI,通过 `opendirector --help` 和子命令的 `--help` 渐进发现操作。查询、编辑及生成命令调用共用业务服务。Agent 通过受令牌保护的本轮连接继承工程范围、编辑会话、执行目录和操作回执;CLI 子进程退出不终止已接受的后台任务。普通终端通过现有 HTTP API 连接服务,写入申请独立编辑会话并遵守工程锁,查询不申请租约。`--session` 可使用已有授权会话。`--operation-id` 提供稳定修改身份,同身份相同输入重放返回原回执,不同输入拒绝。
业务入口使用 Typer CLI。Agent 每轮先运行一次 `opendirector capabilities`,取得全部业务命令及其必填字段,只有某个字段的结构不明确时才用 `opendirector COMMAND --help-field payload` 查看;系统提示和各 runtime 的本轮执行上下文共用同一句发现规则(`CLI_DISCOVERY`),不再提示逐个命令运行 `--help`。人在终端里仍可用 `opendirector --help` 和子命令的 `--help`。

工具记录的 `status` 表示这次调用本身的结果:一个等待窗口在 job 仍未结束时返回,也是 `complete`。`job.status` 和 `canvas.status` 的等待另外记录 `waitOutcome`(`kind`、`settled`,以及各 job 状态的计数或画布项状态),用来区分已结束的等待和超时返回的窗口。执行记录把 `complete` 且 `waitOutcome.settled` 为 `false` 的等待显示为"未结束",进度"已完成"不计入它们,并单独显示"N 次返回时任务未结束";没有 `waitOutcome` 的旧记录照常显示。查询、编辑及生成命令调用共用业务服务。Agent 通过受令牌保护的本轮连接继承工程范围、编辑会话、执行目录和操作回执;CLI 子进程退出不终止已接受的后台任务。普通终端通过现有 HTTP API 连接服务,写入申请独立编辑会话并遵守工程锁,查询不申请租约。`--session` 可使用已有授权会话。`--operation-id` 提供稳定修改身份,同身份相同输入重放返回原回执,不同输入拒绝。

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

Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/opendirector/agent/cli_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import sys
import time

from opendirector.agent.gateway import wait_outcome
from opendirector.domain.projects import ProjectError


Expand Down Expand Up @@ -69,9 +70,11 @@ async def connection(reader, writer):
if outcome.error and isinstance(outcome.value, dict) and isinstance(outcome.value.get('code'), str):
response['code'] = outcome.value['code']
detail = json.dumps(outcome.value, ensure_ascii=False, indent=2)
observed = None if outcome.error else wait_outcome(name, arguments, outcome.value)
await queue.put({**outcome.event(display_name), 'id': 'cli:' + key,
'arguments': arguments, 'result': detail[:65536],
'resultTruncated': len(detail) > 65536,
**({'waitOutcome': observed} if observed else {}),
'timing': {'spawn': spawn, 'work': round(time.monotonic() - received, 3)}})
except (ProjectError, ValueError, KeyError, OSError, TimeoutError) as failure:
response = {'error': str(failure)}
Expand Down
23 changes: 23 additions & 0 deletions packages/core/src/opendirector/agent/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,29 @@ def _command_conflict(call_id: str) -> ToolResult:
return ToolResult(value=value, error=COMMAND_CONFLICT_ZH)


def wait_outcome(name, arguments, value):
"""What a completed wait actually observed, recorded beside the tool record.

A wait window is a successful call even when its jobs are still running, so
the record's status alone cannot tell a finished wait from one that timed
out (#449). This records the observed states as data; how the execution
record presents them is left to the interface.
"""
if name != 'query' or not isinstance(arguments, dict) or not isinstance(value, dict):
return None
kind = arguments.get('type')
if kind == 'job.status' and isinstance(value.get('jobs'), list):
statuses = {}
for job in value['jobs']:
status = job.get('status') if isinstance(job, dict) else None
if isinstance(status, str):
statuses[status] = statuses.get(status, 0) + 1
return {'kind': kind, 'settled': value.get('terminal') is True, 'statuses': statuses}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

terminal 是「所有任务均已进入终态」,不是「本次等待条件已满足」。一个已成功、一个仍在跑时,until=any 正常返回,却和 until=all 到时、waitSeconds=0 查询一起显示「未结束」并从完成数扣掉。可以把调用完成与返回时的任务状态分开,若要报窗口是否满足再带上实际 wait 条件。

if kind == 'canvas.status' and isinstance(value.get('status'), str):
return {'kind': kind, 'settled': value['status'] not in {'queued', 'running'}, 'status': value['status']}
return None


def _read_only(name, arguments) -> bool:
"""Whether this call may skip the execution lock.

Expand Down
5 changes: 2 additions & 3 deletions packages/core/src/opendirector/agent/jiuwenswarm.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from opendirector.agent.gateway import ToolGateway
from opendirector.agent.skill_snapshot import prepare_skills, copy_skill_tree
from opendirector.agent.directory_links import link_directory, unlink_directory
from opendirector.agent.tools import SUGGESTED_REPLIES, SYSTEM
from opendirector.agent.tools import CLI_DISCOVERY, SUGGESTED_REPLIES, SYSTEM
from opendirector.agent import cli_transport
from opendirector.agent.cli_discovery import cli_executable
from opendirector.agent.process import terminate
Expand Down Expand Up @@ -193,8 +193,7 @@ async def stream(self, run: RunContext, gateway: ToolGateway):
'Use inherited PATH to discover installed programs with command -v. '
'Read source assets at their supplied absolute paths; do not move or modify them. '
'Write intermediate files and outputs into the execution directory. '
'Use opendirector --help to discover project commands and use opendirector for project changes.\n'
+ SUGGESTED_REPLIES + '\n'
+ CLI_DISCOVERY + SUGGESTED_REPLIES + '\n'
+ json.dumps(run.messages[-1:] if session_id else run.messages, ensure_ascii=False)),
'agent': {'name': 'opendirector', 'instructions': SYSTEM,
'tools': ['skill_tool', 'list_skill', 'read_file', 'bash']},
Expand Down
5 changes: 2 additions & 3 deletions packages/core/src/opendirector/agent/native.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from opendirector.agent.citations import search_sources
from opendirector.agent.gateway import ToolGateway
from opendirector.agent.process import terminate
from opendirector.agent.tools import ROOT, SUGGESTED_REPLIES, SYSTEM, runtime_instructions
from opendirector.agent.tools import CLI_DISCOVERY, ROOT, SUGGESTED_REPLIES, SYSTEM, runtime_instructions
from opendirector.installation import BUNDLED
from opendirector.agent.skill_snapshot import prepare_skills
from opendirector.agent.directory_links import link_directory, unlink_directory
Expand Down Expand Up @@ -277,8 +277,7 @@ async def stream(self, run: RunContext, gateway: ToolGateway):
'Use inherited PATH to discover installed programs with Get-Command in PowerShell or command -v in POSIX shells. '
'Read source assets at their supplied absolute paths; do not move or modify them. '
'Write all intermediate files and outputs into the execution directory. '
'Use opendirector --help to discover OpenDirector commands and opendirector <group> <command> --help for usage. Use opendirector for project changes.\n'
+ SUGGESTED_REPLIES)
+ CLI_DISCOVERY + SUGGESTED_REPLIES)
prompt = execution_context + '\n' + json.dumps(context[-1:] if session_id else context, ensure_ascii=False)
skill_instruction = ''
if selected:
Expand Down
9 changes: 7 additions & 2 deletions packages/core/src/opendirector/agent/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,14 @@ def query_guidance(failure):
if name not in EXCLUDED}
for command_name, command_model in COMMANDS.items():
assert command_model.__doc__ and command_model.__doc__.strip(), f'Missing command metadata: {command_name}'
SYSTEM = '''You are OpenDirector, a video creation assistant.
CLI_DISCOVERY_RULE = (
'Run opendirector capabilities once, and inspect a command with opendirector COMMAND --help-field payload '
'only when one field\'s shape is unclear. Do not run --help for each command.'
)
SYSTEM = f'''You are OpenDirector, a video creation assistant.
Respond directly when the user's request can be answered without project state or tool execution.
When the task needs project capabilities, run the opendirector executable on PATH through the harness's native shell tool.
Run opendirector capabilities once, and inspect a command with opendirector COMMAND --help-field payload only when one field's shape is unclear. Do not run --help for each command.
{CLI_DISCOVERY_RULE}
Accepted receipts return ready-to-run next commands with current revisions; use them instead of re-reading the project.
Wait for generation with opendirector job wait --all; one call covers every unfinished job, so do not start one wait per job.
After performing requested creative work, summarize the delivered result and material limitations. Keep execution IDs, revisions and receipts in tool details unless requested.
Expand All @@ -90,6 +94,7 @@ def query_guidance(failure):
identifiers and code unchanged. If a tool error is shown in another language, explain it in the user's language.
'''

CLI_DISCOVERY = f'{CLI_DISCOVERY_RULE} Use opendirector for project changes.\n'
SUGGESTED_REPLIES = (
'When there are useful next steps, finish the reply with 3 to 5 distinct suggestions the user '
'could send verbatim. Use single-line plain-text phrases in the language of the user, '
Expand Down
32 changes: 26 additions & 6 deletions packages/core/src/opendirector/application/creation_canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -785,7 +785,10 @@ def _mutate(self, data, kind, payload):
raise ContractError('capability_unsupported', '未实现该业务命令。')

def item_status(self, project_id: UUID, item_id: UUID) -> dict:
snapshot = self.projects.snapshot(project_id)
return self._item_view(self.projects.snapshot(project_id), item_id)

@staticmethod
def _item_view(snapshot, item_id: UUID) -> dict:
item = next((item for item in snapshot.canvasItems if item.id == item_id), None)
if item is None:
raise ProjectError('画布组件不在当前工程中。', 404)
Expand Down Expand Up @@ -814,7 +817,9 @@ def item_status(self, project_id: UUID, item_id: UUID) -> dict:

def job_states(self, project_id: UUID, object_ids: tuple[UUID, ...] = ()) -> dict:
"""Read the requested jobs and their deliveries from one snapshot; unfinished jobs when none are named."""
snapshot = self.projects.snapshot(project_id)
return self._job_views(self.projects.snapshot(project_id), object_ids)

def _job_views(self, snapshot, object_ids: tuple[UUID, ...] = ()) -> dict:
jobs = {job.id: job for job in snapshot.jobs}
if object_ids:
missing = [str(identity) for identity in object_ids if identity not in jobs]
Expand Down Expand Up @@ -856,13 +861,26 @@ def unfinished_jobs(self, project_id: UUID) -> tuple[UUID, ...]:
return tuple(job.id for job in self.projects.snapshot(project_id).jobs
if job.status not in self.TERMINAL_JOB_STATES)

def _refresh(self, project_id: UUID, head, view, build):
"""One project read per poll tick; copy and rebuild only after a commit.

Every job, result and canvas change is a commit with a new head, and the
views read nothing but the snapshot, so an unchanged head leaves the
previous view current. The head and snapshot come from the same record,
so a commit landing between them cannot be missed.
"""
head, snapshot = self.projects.snapshot_if_changed(project_id, head)
return head, view if snapshot is None else build(snapshot)

async def wait_jobs(self, project_id: UUID, object_ids: tuple[UUID, ...] = (), wait_seconds: float = 0,
until: str = 'all') -> dict:
"""Answer for a whole set of jobs with at most one snapshot read per poll tick."""
"""Answer for a whole set of jobs, copying the snapshot only when the project changed."""
group = object_ids or await asyncio.to_thread(self.unfinished_jobs, project_id)
deadline = asyncio.get_running_loop().time() + wait_seconds
head, state = None, None
while True:
state = await asyncio.to_thread(self.job_states, project_id, group)
head, state = await asyncio.to_thread(self._refresh, project_id, head, state,
lambda snapshot: self._job_views(snapshot, group))
jobs = state['jobs']
settled = state['terminal'] or (bool(jobs) and until == 'any' and any(
job['status'] in self.TERMINAL_JOB_STATES for job in jobs))
Expand All @@ -872,14 +890,16 @@ async def wait_jobs(self, project_id: UUID, object_ids: tuple[UUID, ...] = (), w
await asyncio.sleep(min(0.5, remaining))

async def wait_item_status(self, project_id: UUID, item_id: UUID, wait_seconds: float = 0) -> dict:
current = await asyncio.to_thread(self.item_status, project_id, item_id)
def build(snapshot):
return self._item_view(snapshot, item_id)
head, current = await asyncio.to_thread(self._refresh, project_id, None, None, build)
deadline = asyncio.get_running_loop().time() + wait_seconds
while current['status'] in {'queued', 'running'}:
remaining = deadline - asyncio.get_running_loop().time()
if remaining <= 0:
break
await asyncio.sleep(min(0.5, remaining))
updated = await asyncio.to_thread(self.item_status, project_id, item_id)
head, updated = await asyncio.to_thread(self._refresh, project_id, head, current, build)
if updated != current:
return updated
return current
Expand Down
18 changes: 4 additions & 14 deletions packages/core/src/opendirector/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
from typer._click.exceptions import UsageError

from opendirector.agent.tools import COMMANDS, command_help
from opendirector.application.creation_canvas import DELIVERY_GUIDANCE
from opendirector.domain.creation.assets import (
ASSET_DOWNLOAD_ENGLISH, ASSET_REVISION_HEADER, AssetDownloadFile, AssetDownloadReceipt,
)
Expand Down Expand Up @@ -709,19 +708,10 @@ def query(self, kind, **arguments):
self.request("POST", self.path("/queries"),
json={"type": kind, "queryId": str(uuid4()), "projectId": str(self.project), **arguments}))
if kind == "job.get" and result.get("status") == "succeeded" and result.get("asset"):
snapshot = self.snapshot()
asset_id = result["asset"]["assetId"]
results = [value for value in snapshot["results"] if value["asset"]["assetId"] == asset_id]
adopted_specs = {spec["id"] for spec in snapshot["generationSpecs"]
if any(value["id"] == spec.get("currentResultId") for value in results)}
items = [item for item in snapshot["canvasItems"] if
(item["binding"]["role"] == "generation" and item["binding"]["objectRef"]["id"] in adopted_specs
and not item["binding"].get("materialOverride")) or
(item["binding"]["role"] == "material" and item["binding"]["objectRef"]["assetId"] == asset_id)]
result = {**result, "delivery": {"registered": True, "asset": result["asset"],
"adopted": bool(adopted_specs), "canvasItems": [{key: item[key] for key in
("id", "revision", "visible", "position", "width", "height")} for item in items],
"guidance": DELIVERY_GUIDANCE}}
views = self.query("job.status", objectIds=[result["id"]], waitSeconds=0)["jobs"]
delivery = views[0].get("delivery") if views else None
if delivery is not None:
result = {**result, "delivery": delivery}
return result


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -382,18 +382,27 @@ def _current(self, db, project_id, path, manifest):
"""
return self._current_record(db, project_id, path, manifest)[0]

def snapshot(self, project_id):
def _read_snapshot(self, project_id, known_head=None):
path, manifest = self._published_manifest(project_id)
while True:
try:
record, _ = self._current_record(None, project_id, path, manifest)
return record.snapshot.model_copy(deep=True)
head = record.command.commandId
if known_head is not None and head == known_head:
return head, None
return head, record.snapshot.model_copy(deep=True)
except (OSError, ProjectError):
current = self._published_manifest(project_id)
if current == (path, manifest):
raise
path, manifest = current

def snapshot(self, project_id):
return self._read_snapshot(project_id)[1]

def snapshot_if_changed(self, project_id, known_head):
return self._read_snapshot(project_id, known_head)

def head(self, project_id):
"""The current head commit, cheap enough to gate content-addressed caches.

Expand Down
Loading
Loading