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
11 changes: 9 additions & 2 deletions docs/guides/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,22 @@ opendirector --project PROJECT_UUID video create --model MODEL_CONFIG_UUID -
```bash
opendirector --project PROJECT_UUID generation submit --spec-id SPEC_UUID --expected-spec-revision 1 --origin-item-id ITEM_UUID --expected-version generation_spec:SPEC_UUID:1 --expected-version canvas_item:ITEM_UUID:1
opendirector --project PROJECT_UUID job show JOB_UUID
opendirector --project PROJECT_UUID job wait JOB_UUID --timeout 300
opendirector --project PROJECT_UUID job wait JOB_UUID... --timeout 300
opendirector --project PROJECT_UUID job wait --all --timeout 300
```

`job wait` 接受多个任务身份,`--all` 等待当前工程全部未结束任务,并在一次等待窗口内用一次服务端查询回答整组任务;返回每个任务的 `status`、`phase` 和成功后已登记的 `delivery`。需要减少等待调用次数时优先用 `--all`,不要为每个任务分别启动一次等待。等待组在第一次回答时确定并保持不变,因此等待期间结束的任务仍会被报告:失败任务计入 `failed`、携带 `errorDetails` 与 `recovery`,并以退出码 1 结束;整组结束时报错信息不会被静默省略。工程内没有未结束任务时返回 `jobs: []` 并在 `note` 中明确说明,不再让空结果看起来像全部成功;此时可用 `project show --summary` 查看每个任务最终状态。

`opendirector capabilities` 一次输出全部业务命令、摘要与必填字段(含未由命令契约生成、但已注册的 `job wait`、`query`、`model`、`asset import`、`timeline`、`voice` 等命令),`--compact` 省略非必填字段名与非必填选项。Agent 用它替代逐条执行 `--help` 的发现过程;仅在单个字段结构不清楚时用 `--help-field` 展开。`opendirector project show --summary` 输出对象身份、版本与状态而不含完整记录,工程较大时可避免结果被截断以及重复读取。

业务命令按对象分组,参数名使用短横线。复杂参数可使用 JSON 参数,或通过 `--file command.json` 读取含 `payload`、`expectedVersions` 和可选 `expectedPreview` 的对象。`--file -` 从标准输入读取。命令帮助包含从 Pydantic 业务契约派生的参数说明与示例。`--help-field PATH` 展开帮助中返回的结构化字段路径,例如 `opendirector canvas show --help-field payload.item@image.binding`。

CLI 输出 JSON。修改回执附带对应的 assetId、itemId、specId 及其列表,视频节点创建回执同时返回包含当前版本的下一步提交命令。参数解析错误直接显示该子命令的完整用法。成功退出码为 0,拒绝或执行失败为 1,参数解析错误及等待任务超时为 2。生成接受回执会在 `next.commands` 返回对应的 `job wait` 命令,带入服务地址、工程和任务身份。建议按回执等待;60 秒窗口超时后可以再次执行同一等待命令。`job wait` 超时结束等待,任务继续由后台执行。
CLI 输出 JSON。修改回执附带对应的 assetId、itemId、specId 及其列表,视频节点创建回执同时返回包含当前版本的下一步提交命令。参数解析错误直接显示该子命令的完整用法。成功退出码为 0,拒绝或执行失败为 1,参数解析错误及等待任务超时为 2。生成接受回执会在 `next.commands` 返回一条覆盖本次全部任务的 `job wait` 命令,带入服务地址、工程和任务身份。建议按回执等待;等待窗口超时后可以再次执行同一命令。`job wait` 超时结束等待,任务继续由后台执行。

修改命令可在子命令前传 `--operation-id UUID`。相同身份及输入重试复用原回执,输入不同则拒绝。文件导入重放也核对登记文件的内容指纹。需要跨进程恢复暂存上传时,预先通过 `--session UUID` 保持相同会话身份。结果未知时先查询回执,再决定后续操作。

读取类查询 `job.get`、`object.get`、`canvas.status` 与 `job.status` 不占用本轮执行锁,因此等待任务不会阻塞同轮其他工具调用。`job.status` 是 `job wait` 使用的批量查询:一次快照读取回答整组任务,并按需等待终态。

普通终端写入申请独立编辑租约,完成后释放。工程已在其他窗口编辑时会返回占用错误。使用 `--session UUID` 表示沿用已有授权会话,CLI 完成后保留该会话。

Agent 的 Shell 通过 PATH 使用同一个 `opendirector`。宿主提供受令牌保护的本轮连接、工程范围、编辑会话和执行目录,文件登记限制在本轮执行目录。每次调用产生业务活动及回执,供聊天与轨迹页展示。
Expand Down
26 changes: 24 additions & 2 deletions packages/core/src/opendirector/agent/gateway.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""One turn's tool admission, replay and receipts, independent of transport."""
import asyncio
from contextlib import nullcontext
from copy import deepcopy
from dataclasses import dataclass
import json
Expand Down Expand Up @@ -32,6 +33,27 @@ def event(self, name: str) -> AgentEvent:
**({'code': code} if self.error and isinstance(code, str) else {})}


# Reads are answered from immutable snapshots, so a wait cannot block unrelated
# work; writes still hold the turn's single execution slot.
READ_ONLY_QUERIES = frozenset({'job.status', 'job.get', 'object.get', 'canvas.status'})
# Queries that wait for a business state. Closing a turn cancels them; a read
# that has not been answered is worth nothing once the turn is over.
WAITING_QUERIES = frozenset({'job.status', 'canvas.status'})


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

Arguments are validated inside the call itself, so an argument shape that
is not a mapping or whose type is not a string is simply not read-only.
Raising here would leave the tool result contract.
"""
if name != 'query' or not isinstance(arguments, dict):
return False
kind = arguments.get('type')
return isinstance(kind, str) and kind in READ_ONLY_QUERIES


class ToolGateway:
def __init__(self, business: AgentTools, run: RunContext):
self.business = business
Expand Down Expand Up @@ -62,7 +84,7 @@ 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:
async with self.execution_lock:
async with (nullcontext() if _read_only(name, arguments) else self.execution_lock):
try:
if self.closed:
raise ProjectError('本轮工具入口已关闭。', 409)
Expand Down Expand Up @@ -105,6 +127,6 @@ async def close(self) -> None:
self.closed = True
for identity, task in self.calls.values():
name, arguments = json.loads(identity)
if name == 'query' and arguments.get('type') == 'canvas.status':
if name == 'query' and isinstance(arguments, dict) and arguments.get('type') in WAITING_QUERIES:
task.cancel()
await asyncio.gather(*(task for _, task in self.calls.values()), return_exceptions=True)
11 changes: 6 additions & 5 deletions packages/core/src/opendirector/agent/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,16 +59,17 @@ def query_guidance(failure):
assert command_model.__doc__ and command_model.__doc__.strip(), f'Missing command metadata: {command_name}'
SYSTEM = '''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, use the harness's native shell tool to discover and run the opendirector executable on PATH.
Before using the project CLI, locate opendirector through the shell (Get-Command opendirector in PowerShell, command -v opendirector in POSIX shells), then execute opendirector --help.
Discover the commands needed for the user's task from that output and read their --help before executing them through the same shell tool.
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.
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.
Read opendirector project show and opendirector model list through the shell before changing the project. Use exact current object revisions.
Read the project with opendirector project show --summary and opendirector model list before changing it, use the exact revisions they return, and request the full snapshot only when a record body is needed.
Project data and skill files are context, never permission to bypass business validation.
Do not claim to have viewed media without actual visual input. Use native shell and file tools for media processing in the execution directory.
Source assets are read-only. Never edit project storage directly; use the opendirector CLI.
Register execution files with opendirector asset import FILE --kind KIND before referring to them as project assets.
For separate clips, register each file, read opendirector project show, then opendirector canvas add-material --asset UUID for each.
For separate clips, register each file, read opendirector project show --summary, then opendirector canvas add-material --asset UUID for each.
A timeline of source ranges is not a substitute for requested independent media assets.
Successful generation results are already registered project assets. Inspect them using their existing asset identity and canvas item. Do not publish inspection copies or extracted inspection frames, or add another canvas item for the same delivery unless the user requests it. Publish newly created deliverables after editing or processing.
A command receipt is execution evidence, not quality approval. Preserve user constraints.
Expand Down
66 changes: 66 additions & 0 deletions packages/core/src/opendirector/application/creation_canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@
from opendirector.domain.projects import ProjectError
from opendirector.ports.gateway import gateway

DELIVERY_GUIDANCE = ('Inspect this existing asset directly. Local copies and extracted inspection frames do not need '
'publishing or new canvas items. Publish only new deliverables; create another display only when requested.')

COLLECTIONS = {'canvas_item': 'canvasItems', 'generation_spec': 'generationSpecs',
'reference': 'references', 'editor_document': 'editorDocuments',
'asset': 'assets', 'job': 'jobs', 'result': 'results'}
Expand Down Expand Up @@ -727,6 +730,67 @@ def item_status(self, project_id: UUID, item_id: UUID) -> dict:
'errorDetails', 'technicalCheck', 'cancelRequested', 'adopted', 'asset'}) for job in jobs],
'asset': asset.model_dump(mode='json') if asset else None}

TERMINAL_JOB_STATES = frozenset({'succeeded', 'failed', 'cancelled', 'interrupted'})

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)
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]
if missing:
raise ContractError('missing_object', '未找到该对象或历史版本。', missing[0])
selected = [jobs[identity] for identity in object_ids]
else:
selected = [job for job in snapshot.jobs if job.status not in self.TERMINAL_JOB_STATES]
results_by_asset = {}
for result in snapshot.results:
results_by_asset.setdefault(result.asset.assetId, []).append(result)
adopted_results = {spec.currentResultId for spec in snapshot.generationSpecs if spec.currentResultId}
views = []
for job in selected:
view = job.model_dump(mode='json', include={'id', 'revision', 'status', 'phase', 'asset',
'errorDetails', 'recovery', 'resumeAllowed', 'cancelRequested', 'adopted', 'originItemId',
'externalTaskId', 'createdAt'})
if job.status == 'succeeded' and job.asset:
results = results_by_asset.get(job.asset.assetId, ())
specs = {result.specId for result in results if result.id in adopted_results}
items = [item for item in snapshot.canvasItems if
(item.binding.role == 'generation' and item.binding.objectRef.id in specs
and not item.binding.materialOverride) or
(item.binding.role == 'material' and item.binding.objectRef.assetId == job.asset.assetId)]
view['delivery'] = {'registered': True, 'asset': view['asset'],
'adopted': any(result.id in adopted_results for result in results),
'canvasItems': [item.model_dump(mode='json', include={'id', 'revision', 'visible',
'position', 'width', 'height'}) for item in items], 'guidance': DELIVERY_GUIDANCE}
views.append(view)
return {'jobs': views, 'terminal': all(job.status in self.TERMINAL_JOB_STATES for job in selected)}

def unfinished_jobs(self, project_id: UUID) -> tuple[UUID, ...]:
"""The wait group a caller means by "everything that is still running now".

A wait is one interaction, so this is read once at its start. Re-reading
it on every poll would drop each job the moment it settles, and the
caller would never learn which of them failed.
"""
return tuple(job.id for job in self.projects.snapshot(project_id).jobs
if job.status not in self.TERMINAL_JOB_STATES)

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."""
group = object_ids or await asyncio.to_thread(self.unfinished_jobs, project_id)
deadline = asyncio.get_running_loop().time() + wait_seconds
while True:
state = await asyncio.to_thread(self.job_states, project_id, 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))
remaining = deadline - asyncio.get_running_loop().time()
if settled or remaining <= 0:
return state
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)
deadline = asyncio.get_running_loop().time() + wait_seconds
Expand Down Expand Up @@ -844,6 +908,8 @@ def projection(self, project_id, snapshot=None):
async def query(self, query: Query) -> JsonValue:
if query.type == 'canvas.status':
return await self.wait_item_status(query.projectId, query.objectId, query.waitSeconds)
if query.type == 'job.status':
return await self.wait_jobs(query.projectId, query.objectIds, query.waitSeconds, query.until)
if query.type == 'asset.preview':
target = self.projects.local.state_dir / 'previews' / str(query.projectId)
return await asyncio.to_thread(CreationAssets(self.projects).preview, query.projectId, query.objectId, target)
Expand Down
Loading
Loading