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
4 changes: 3 additions & 1 deletion apps/api/src/opendirector_api/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ def projection(project_id: UUID):
return canvas.projection(project_id)

@router.post('/projects/{project_id}/queries')
async def query(project_id: UUID, value: CreationQuery):
async def query(project_id: UUID, value: CreationQuery, request: Request):
if value.projectId != project_id:
raise ProjectError('查询不属于当前工程。')
if value.type in {'pipeline.plan', 'pipeline.execution.get', 'pipeline.executions.list'}:
Expand All @@ -306,6 +306,8 @@ async def query(project_id: UUID, value: CreationQuery):
return {'executions': await executor.history(project_id, value.groupId)}
return await executor.status(project_id, value.objectId)
result = await canvas.query(value)
if value.type == 'receipt.get':
return localized_receipt(request, CommandReceipt.model_validate(result))
if value.type == 'asset.preview' and 'preview' in result:
result['preview'].pop('path')
result['preview']['url'] = f'/api/creation/projects/{project_id}/assets/{value.objectId}/preview'
Expand Down
5 changes: 4 additions & 1 deletion apps/api/src/opendirector_api/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,10 @@
"chat_incomplete_response": "The model response did not finish normally (it may have hit a length limit or content filter). Any generated content has been preserved.",
"invalid_input": "The request is invalid. Check the required fields and their formats.",
"invalid_project": "The project or asset identifier is invalid.",
"command_conflict": "This operation ID was already used with different input. Use a new operation ID for changed input, or inspect the original receipt.",
"missing_receipt": "No committed receipt was found for this command or operation ID.",
"missing_object": "The requested item no longer exists.",
"not_found": "The requested item no longer exists.",
"command_conflict": "This identifier was already used with different input. Use a new identifier.",
"revision_conflict": "This item changed since it was loaded. Reload it and try again.",
"preview_expired": "The preview expired. Generate it again.",
"reference_invalid": "A reference is no longer valid. Select it again and retry.",
Expand Down Expand Up @@ -250,6 +251,8 @@ def localized_error_for_language(
translated = english_capability_message(chinese)
if translated:
return translated
if code == 'command_conflict' and chinese == '该工程标识已经使用。':
return 'This project ID is already in use.'
if code == 'invalid_input' and chinese == '聊天引用超过数量上限,请移除部分引用。':
return 'The chat reference limit was exceeded. Remove some references and retry.'
if code == 'invalid_input' and chinese == '视频裁切需要视频来源节点。':
Expand Down
6 changes: 4 additions & 2 deletions docs/guides/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,11 @@ opendirector --project PROJECT_UUID job wait --all --timeout 300

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

修改命令可在子命令前传 `--operation-id UUID`。相同身份及输入重试复用原回执,输入不同则拒绝。文件导入重放也核对登记文件的内容指纹。需要跨进程恢复暂存上传时,预先通过 `--session UUID` 保持相同会话身份。结果未知时先查询回执,再决定后续操作。
修改命令可在子命令前传 `--operation-id UUID`。相同身份及输入重试复用原回执,输入不同则以错误码 `command_conflict` 拒绝,并返回省略或更换 `--operation-id` 及查看原回执的指引(Agent 模式下附带 `receiptCommand` 与 `guidance`)。文件导入重放也核对登记文件的内容指纹。需要跨进程恢复暂存上传时,预先通过 `--session UUID` 保持相同会话身份。结果未知时先用 `opendirector --project PROJECT_UUID receipt show OPERATION_OR_COMMAND_UUID`(或 `query receipt.get --object-id UUID`)查询原操作回执,未找到已提交回执时返回 404 与错误码 `missing_receipt`。

读取类查询 `job.get`、`object.get`、`canvas.status` 与 `job.status` 不占用本轮执行锁,因此等待任务不会阻塞同轮其他工具调用。`job.status` 是 `job wait` 使用的批量查询:一次快照读取回答整组任务,并按需等待终态。
Pass `--operation-id UUID` before a write subcommand for idempotent retries. Replaying the same ID with identical input returns the original receipt; changing the input is rejected with `command_conflict` (in Agent mode, with `guidance` and a `receiptCommand` when an operation UUID is present). When an outcome is unknown, run `opendirector --project PROJECT_UUID receipt show OPERATION_OR_COMMAND_UUID` (or `query receipt.get --object-id UUID`) before deciding whether to submit a new operation; missing receipts return 404 with `missing_receipt`.

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

普通终端写入申请独立编辑租约,完成后释放。浏览器窗口打开工程后会一直保留编辑权,关闭标签页也不会释放,此时 CLI 写入会返回占用错误,并提示可改用 `--take-over`。在子命令前加 `--take-over` 会把编辑权从该窗口移到本次命令:原窗口立即转为预览,未完成的保存会被拒绝,之后可用“在此编辑”收回。Agent 使用 `--take-over` 前须先征得用户同意。本次命令持有的编辑权与普通 CLI 写入一样为 60 秒且不自动续期,进程被强行终止也不会长期占用;单条命令(例如上传大文件)超过 60 秒时,写入可能因会话过期被拒,原窗口此时已转为预览,需要重新执行或在窗口中收回。使用 `--session UUID` 时,接管的编辑权留在该会话、命令结束后不释放,仍在 60 秒后过期,除非该会话自行续期。

Expand Down
34 changes: 32 additions & 2 deletions packages/core/src/opendirector/agent/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,41 @@ def event(self, name: str) -> AgentEvent:

# 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'})
READ_ONLY_QUERIES = frozenset({'job.status', 'job.get', 'object.get', 'canvas.status', 'receipt.get'})
# 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'})

COMMAND_CONFLICT_ZH = (
'工具调用标识被用于不同输入。修改输入后请省略 --operation-id 或使用新的操作标识;'
'如需确认原操作是否已提交,请查询原操作回执。'
)


def _command_conflict(call_id: str) -> ToolResult:
receipt_command = None
if call_id.startswith('cli:'):
raw = call_id.removeprefix('cli:')
try:
receipt_command = f'opendirector receipt show {UUID(raw)}'
except ValueError:
receipt_command = None
guidance = (
f'Reuse an operation ID only for identical retries. Omit --operation-id or pass a new UUID for changed input, '
f'or run `{receipt_command}` to inspect the original operation receipt.'
if receipt_command else
'Reuse a call ID only for identical retries. Use a new call ID for changed input, '
'or query receipt.get with the commandId from the original tool result to inspect its receipt.'
)
value: dict[str, JsonValue] = {
'error': COMMAND_CONFLICT_ZH,
'code': 'command_conflict',
'callId': call_id,
'guidance': guidance,
**({'receiptCommand': receipt_command} if receipt_command else {}),
}
return ToolResult(value=value, error=COMMAND_CONFLICT_ZH)


def _read_only(name, arguments) -> bool:
"""Whether this call may skip the execution lock.
Expand Down Expand Up @@ -81,7 +111,7 @@ async def call(self, call_id: str, name: str, arguments: dict[str, JsonValue]) -
previous = self.calls.get(call_id)
if previous is not None:
if previous[0] != identity:
return ToolResult(value={'error': '工具调用标识被用于不同输入。'}, error='工具调用标识被用于不同输入。')
return _command_conflict(call_id)
task = previous[1]
else:
task = asyncio.create_task(self.execute(call_id, name, deepcopy(arguments)))
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/opendirector/agent/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,14 @@ def recording():
# A rejected query must name the accepted types rather than echo a
# tag list the model has to reinterpret.
raise ProjectError(query_guidance(failure)) from None
if query.type == 'receipt.get':
candidates = (
query.objectId,
agent_command_id(turn_id, 'cli:' + str(query.objectId)),
agent_command_id(turn_id, str(query.objectId)),
)
found = await asyncio.to_thread(self.projects.receipt_any, project_id, candidates)
return found.model_dump(mode='json')
if query.type in {'pipeline.plan', 'pipeline.execution.get', 'pipeline.executions.list'}:
executor = getattr(self.generation, 'pipelines', None)
if executor is None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1014,6 +1014,8 @@ async def query(self, query: Query) -> JsonValue:
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 == 'receipt.get':
return to_jsonable_python(await asyncio.to_thread(self.projects.receipt, query.projectId, query.objectId))
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
40 changes: 40 additions & 0 deletions packages/core/src/opendirector/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
"canvas": "Display, arrange, hide and configure canvas items.",
"video": "Create video generation nodes or trim a source video.",
"job": "Inspect, wait for, cancel or recover generation jobs.",
"receipt": "Inspect persisted receipts for earlier commands or operation IDs.",
"artifact": "Register files from the active agent execution directory.",
"generation-spec": "Create, edit and restore generation settings and prompts.",
"reference": "Add, update, restore or remove generation input references.",
Expand Down Expand Up @@ -524,6 +525,14 @@ def compression_task(ctx: typer.Context, task_id: Annotated[UUID, typer.Argument
}


class _CliCallError(ProjectError):
def __init__(self, message: str, status: int = 400, *, code: str | None = None,
guidance: str | None = None, receipt_command: str | None = None):
super().__init__(message, status, code=code)
self.guidance = guidance
self.receipt_command = receipt_command


class Client:
def __init__(self, project, url, session, operation_id, take_over=False):
self.project = project
Expand Down Expand Up @@ -585,6 +594,12 @@ def call(self, name, arguments, *, identity=None):
with connection.makefile("rb") as reader:
response = json.loads(reader.readline(64 * 1024 * 1024))
if response.get("error"):
detail = response.get("value") if isinstance(response.get("value"), dict) else {}
guidance = detail.get("guidance") if isinstance(detail.get("guidance"), str) else None
receipt_command = detail.get("receiptCommand") if isinstance(detail.get("receiptCommand"), str) else None
if guidance or receipt_command:
raise _CliCallError(response["error"], code=response.get('code'),
guidance=guidance, receipt_command=receipt_command)
raise ProjectError(response["error"], code=response.get('code'))
return response["value"]

Expand Down Expand Up @@ -1347,6 +1362,15 @@ def job_wait(ctx: typer.Context, job_ids: Annotated[list[UUID] | None, typer.Arg
raise typer.Exit(2)


@group("receipt").command("show", help="Read the persisted receipt for a command ID or this turn's --operation-id.")
def receipt_show(ctx: typer.Context,
operation_id: Annotated[UUID, typer.Argument(help="Command ID or operation ID from an earlier attempt.")]):
client = ctx.obj
client.command = ctx.command_path
emit(client.query("receipt.get", objectId=str(operation_id)) if client.live
else client.request("GET", client.path(f"/receipts/{operation_id}")))


@app.command("capabilities", help="List every business command with its required fields; one call replaces per-command --help discovery.")
def capabilities(compact: Annotated[bool, typer.Option("--compact", help="Only names, summaries and required fields.")] = False):
from typing import get_args
Expand Down Expand Up @@ -1543,12 +1567,28 @@ def main():
value = {"error": str(error)}
if isinstance(error, ProjectError):
value['code'] = error.code
guidance = error.guidance if isinstance(error, _CliCallError) else None
receipt_command = error.receipt_command if isinstance(error, _CliCallError) else None
language = os.environ.get('OPENDIRECTOR_LANGUAGE', 'en-US')
translated = timeline_error_message(error.code, language)
if not language.lower().startswith('zh'):
translated = translated or ASSET_DOWNLOAD_ENGLISH.get(error.code)
if translated is None and error.code == 'missing_receipt':
translated = 'No committed receipt was found for this command or operation ID.'
elif (translated is None and error.code == 'command_conflict'
and (isinstance(error, _CliCallError) or any('\u3400' <= ch <= '\u9fff' for ch in str(error)))):
command_hint = receipt_command or 'opendirector receipt show <operation-id>'
translated = (
'This project ID is already in use.' if str(error) == '该工程标识已经使用。' else
f'This operation ID was already used with different input. Omit --operation-id or pass a new UUID '
f'for changed input, or run `{command_hint}` to inspect the original receipt.'
)
value['error'] = (translated or url_import_message(error.code, language, str(error))
or contract_message(error.code, language, str(error)) or str(error))
if guidance:
value['guidance'] = guidance
if receipt_command:
value['receiptCommand'] = receipt_command
emit(value)
raise SystemExit(1)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,11 @@ class AssetPreviewQuery(QueryBase):
objectId: UUID = Field(description='Asset ID.')


class ReceiptQuery(QueryBase):
type: Literal['receipt.get'] = Field(description='Read the persisted receipt for a command ID or current-turn operation ID.')
objectId: UUID = Field(description='Command ID or operation ID to inspect.')


class PipelinePlanQuery(QueryBase):
type: Literal['pipeline.plan'] = Field(description='Compile a Pipeline DAG read-only and preview cache hits, dependencies, and issues.')
scope: PipelineScope = Field(description='Target canvas scope to compile.')
Expand All @@ -732,7 +737,7 @@ class PipelineExecutionsQuery(QueryBase):


Query = Annotated[ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery |
CanvasStatusQuery | JobStatusQuery | AssetPreviewQuery | PipelinePlanQuery |
CanvasStatusQuery | JobStatusQuery | AssetPreviewQuery | ReceiptQuery | PipelinePlanQuery |
PipelineExecutionQuery | PipelineExecutionsQuery, Field(discriminator='type')]


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -519,11 +519,15 @@ def history_index(self, project_id):
) for r in records if r.visible_in_history)

def receipt(self, project_id, command_id):
records = self.records(project_id)
found = next((record.receipt for record in records if str(record.command.commandId) == str(command_id)), None)
if found is None:
raise ProjectError('没有该命令的已提交回执。', 404)
return found.model_copy(deep=True)
return self.receipt_any(project_id, (command_id,))

def receipt_any(self, project_id, command_ids):
by_id = {str(record.command.commandId): record.receipt for record in self.records(project_id)}
for command_id in command_ids:
found = by_id.get(str(command_id))
if found is not None:
return found.model_copy(deep=True)
raise ProjectError('没有该命令的已提交回执。', 404, code='missing_receipt')

def changes(self, project_id, *, after=0, limit=100):
if type(after) is not int or after < 0 or type(limit) is not int or not 1 <= limit <= 200:
Expand Down
12 changes: 8 additions & 4 deletions packages/core/src/opendirector/integrations/minimax_video.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@
from opendirector.integrations.generation_errors import protocol_failure, provider_failure, transport_failure
from opendirector.integrations.http_settings import MODEL_HTTP_HOOKS, auth_headers, trust_environment
from opendirector.integrations.reference_inputs import data_uri, image_type, references, request_size, reference_text
from opendirector.integrations.volcengine import bounded
from opendirector.integrations.volcengine import DEFAULT_POLL_RETRY_DELAYS, bounded, retry_poll
from opendirector.media.probe import probe, require_ffprobe

class MinimaxVideoGeneration:
def __init__(self, store, transport=None, poll_interval=3):
def __init__(self, store, transport=None, poll_interval=3, retry_delays=DEFAULT_POLL_RETRY_DELAYS):
self.store, self.transport, self.poll_interval = store, transport, poll_interval
self.retry_delays = retry_delays

def validate(self, kind, config):
if kind != 'video' or config['modelId'] not in MINIMAX_MODELS:
Expand Down Expand Up @@ -130,9 +131,12 @@ async def generate(self, config, task, submitted, *, result_ready=None):
raise protocol_failure(stage)
await submitted(external_id)
stage = 'poll'
query_url = base + '/query/video_generation/' + quote(external_id, safe='')
async def read_status():
async with client.stream('GET', query_url, headers=auth_headers(config)) as response:
return json.loads(await bounded(response, stage=stage, secrets=secrets, limit=1024 * 1024))
while True:
async with client.stream('GET', base + '/query/video_generation/' + quote(external_id, safe=''), headers=auth_headers(config)) as response:
value = json.loads(await bounded(response, stage=stage, secrets=secrets, limit=1024 * 1024))
value = await retry_poll(read_status, self.retry_delays)
remote = value['task']
if remote['id'] != external_id:
raise protocol_failure(stage)
Expand Down
Loading
Loading