Skip to content
Draft
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
17 changes: 12 additions & 5 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.references import TurnReference, resolve_turn_references
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 @@ -675,9 +676,8 @@ async def prepare(project_id: UUID, value: Turn, session: str, accept_language:
raise ProjectError('技能已失效,请重新选择。', 409)
snapshot = await asyncio.to_thread(projects.snapshot, project_id)
assets = {str(asset.id): asset for asset in snapshot.assets}
for asset_id in value.assets:
if str(asset_id) not in assets:
raise ProjectError('引用素材不属于当前工程。', 409)
turn_refs = resolve_turn_references(snapshot, value.id, value.content or (), value.assets)
attachment_ids = dict.fromkeys(str(ref.asset.assetId) for ref in turn_refs)
model = config['modelId'] if config else value.runtimeModel
model_is_cli_default = spec.modelSource == 'cli' and not model
model_selections = dict(value.modelSelections)
Expand All @@ -691,7 +691,8 @@ async def prepare(project_id: UUID, value: Turn, session: str, accept_language:
'message': {'id': str(value.id), 'role': 'user', 'text': value.text, 'content': value.content,
'assets': [{'id': str(asset.id), 'name': asset.name, 'type': asset.metadata.mimeType,
'size': asset.metadata.size, 'fingerprint': asset.fingerprint}
for asset in (assets[str(key)] for key in value.assets)],
for asset in (assets[key] for key in attachment_ids)],
'turnReferences': [ref.model_dump(mode='json', exclude_none=True) for ref in turn_refs],
'skills': value.skills, 'runtime': value.runtime, 'runtimeModel': value.runtimeModel,
'modelSelections': dict(value.modelSelections), 'model': model,
'modelIsCliDefault': model_is_cli_default,
Expand Down Expand Up @@ -760,6 +761,9 @@ async def renew_session() -> None:
context = []
for reply in saved['messages'][:-1]:
content = reply['text'] or '(empty reply)'
bound = [TurnReference.model_validate(ref).observation() for ref in reply.get('turnReferences', [])]
if bound:
content += '\nProject references in chat order: ' + json.dumps(bound, ensure_ascii=False)
references = []
for attachment in reply.get('assets', []):
asset = assets.get(attachment['id'])
Expand All @@ -778,7 +782,10 @@ 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,
turn_references=tuple(TurnReference.model_validate(ref) for ref in message.get('turnReferences', [])),
earlier_references=tuple(TurnReference.model_validate(ref) for reply in saved['messages'][:-2]
for ref in reply.get('turnReferences', [])))
async with aclosing(runtimes.stream(run)) as stream:
async for event in stream:
if event['type'] == 'delta':
Expand Down
11 changes: 6 additions & 5 deletions apps/api/src/opendirector_api/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from opendirector.application.creation_timeline_packages import CreationTimelinePackages
from opendirector.application.creation_video_compatibility import CreationVideoCompatibility, VideoConversionTask
from opendirector.domain.creation.timeline_packages import TimelinePackageImportRequest, TimelinePackageImportReceipt
from opendirector.domain.creation.assets import Asset, UploadInfo
from opendirector.domain.creation.assets import ASSET_REVISION_HEADER, Asset, UploadInfo
from opendirector.domain.creation.base import MediaKind
from opendirector.domain.creation.commands import Command, CommandReceipt, Query as CreationQuery
from opendirector.domain.creation.project import ProjectSnapshot, ViewState
Expand Down Expand Up @@ -281,7 +281,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 Down Expand Up @@ -454,12 +454,13 @@ def browser_image(project_id: UUID, asset_id: UUID,
'X-Content-Type-Options': 'nosniff'})

@router.get('/projects/{project_id}/assets/{asset_id}/content')
def content(project_id: UUID, asset_id: UUID, range_header: str | None = Header(default=None, alias='Range'),
def content(project_id: UUID, asset_id: UUID, revision: int | None = Query(default=None, ge=1),
range_header: str | None = Header(default=None, alias='Range'),
if_none_match: str | None = Header(default=None, alias='If-None-Match')):
stream, asset = assets.open_media(project_id, asset_id)
stream, asset = assets.open_media(project_id, asset_id, revision=revision)
size, etag = asset.metadata.size, '"' + asset.fingerprint + '"'
headers = {'Accept-Ranges': 'bytes', 'ETag': etag, 'Cache-Control': 'private, no-cache',
'X-Content-Type-Options': 'nosniff',
'X-Content-Type-Options': 'nosniff', ASSET_REVISION_HEADER: str(asset.revision),
'Content-Disposition': ('attachment' if asset.kind == 'file' else 'inline')
+ "; filename*=utf-8''" + quote(asset.name, safe='')}
if range_header is None and if_none_match == etag:
Expand Down
114 changes: 114 additions & 0 deletions apps/api/src/opendirector_api/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from opendirector.domain.timeline_errors import timeline_error_message

from opendirector.domain.creation.assets import ASSET_DOWNLOAD_ENGLISH
from opendirector.domain.creation.commands import CommandReceipt
from opendirector.domain.capabilities import Capability
from opendirector.domain.capability_messages import english_capability_message, missing_tool_model_message
Expand Down Expand Up @@ -42,13 +43,36 @@
'prompt_optimization_too_large': 'The references are too large for prompt optimization. Reduce their size or number and try again.',
'prompt_optimization_result': 'The model did not return a usable prompt. Your original text was kept.',
'prompt_optimization_provider': 'The text model could not optimize the prompt. Check its settings and try again. Your original text was kept.',
**ASSET_DOWNLOAD_ENGLISH,
"desktop_auth_required": "The desktop connection has expired. Reopen the application.",
'h3_timeline_guides_single_model': 'Configure timeline guides for an individual FastH3 model.',
'h3_timeline_guides_source_limit': 'An H3 segment accepts one source video reference.',
'h3_timeline_guides_deployment': 'Enable timeline guides only for a compatible self-hosted FastH3 video endpoint.',
'h3_timeline_guides_unsupported': 'H3 source video segments require a self-hosted H3 endpoint with timeline guides and Reference mode.',
'image_quality_unsupported': 'This model does not support the selected image quality. Choose Auto or select another model.',
'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.',
'bigmodel_video_output': 'Choose a supported CogVideoX-3 pixel size and a 5- or 10-second duration. The size determines the aspect ratio.',
'bigmodel_video_image': 'CogVideoX-3 frame images must be valid PNG or JPEG files, up to 5 MB each.',
'bigmodel_video_frames': 'Use text, one first-frame image, or an explicit first/last pair. Each frame slot accepts one image; a last frame requires a first frame. Reference and continuation modes are not supported.',
'bigmodel_video_prompt': 'CogVideoX-3 prompts allow up to 512 characters. Provide a prompt or frame image.',
'bigmodel_video_cancel': 'Remote BigModel video cancellation is not connected. The task may continue running and incur charges.',
'workflow_assembly_busy': 'This assembly run is already processing. Wait for its result.',
'workflow_media_invalid': 'The source frame range, dimensions, frame rate, or soundtrack does not match the assembly.',
'workflow_media_failed': 'Media processing failed. Check FFmpeg and the source videos.',
'segment_run_busy': 'This Run has an unresolved execution. Check its execution status before starting again.',
'segment_run_unavailable': 'The Run execution service is unavailable.',
'segment_run_no_execution': 'This Run has no execution available to pause or resume.',
'segment_run_not_paused': 'This Run has no paused execution to resume.',
'segment_run_invalid_state': 'This action is unavailable in the execution’s current state.',
'segment_run_stale_execution': 'This Run’s execution changed. Refresh its status and select the execution again.',
'segment_run_incompatible_result': 'The selected result is incompatible with this Run’s frozen inputs or selected guides.',
'segment_run_candidate_missing': 'The selected candidate is unavailable in this execution.',
'segment_run_guide_mismatch': 'The continuation guide does not match the result produced by its upstream step in this execution.',
'segment_run_job_missing': 'The segment execution did not return a matching job.',
'segment_run_job_unsettled': 'The original segment job can still be recovered. Check that job before starting again.',
'segment_run_reconciliation_pending': 'The original provider task is still unresolved.',
'segment_run_remote_missing': 'The provider could not find the original task. Regenerate this segment to continue.',
'submission_unknown': 'The provider may have received the request. Check that submission before retrying.',
'execution_file_link': 'Execution files must not have hard links.',
'kling_model': 'This Kling protocol does not support the selected model.',
'kling_mode': 'Kling currently supports first/last frames and image-reference generation.',
Expand Down Expand Up @@ -188,6 +212,96 @@ def localized_error_for_language(
return specific
if not wants_english_language(language):
return chinese
run_messages = {
'只能通过发布命令创建 Run。': 'Use the Run publication command to create a published Run.',
'只能通过复制 Run 创建分段草稿。': 'Use the Run copy command to create a segmented Run draft.',
'分段草稿须从已发布的 Run 创建。': 'Create a segment draft from a published Run.',
'请先发布 Run 草稿。': 'Publish the Run draft before starting it.',
'计划已发布。请复制为草稿后再修改。': 'This Run is published. Make a draft copy to edit it.',
'计划已发布。请回到草稿后再修改。': 'This Run is published. Return it to draft before editing.',
'请选择可见且未锁定的已发布 Run。': 'Select a visible, unlocked published Run.',
'请先解锁 Run 计划节点。': 'Unlock the Run plan node first.',
'已发布片段须通过 Run 执行。': 'Start the published Run to execute its segments.',
'部署配置已变化,请发布新的 Run。': 'The model deployment configuration changed. Publish a new Run.',
'请选择未发布且未锁定的 Run 草稿。': 'Select an unlocked, visible top-level Run draft.',
'发布 Run 需要可见时间线和未使用的成片节点。': 'A Run needs a visible timeline and an unused output slot.',
'此时间线或成片节点已属于其他 Run。': 'The timeline or output slot belongs to another Run.',
'Run 时间线须匹配帧率,并配置画面轨与原声音轨。': 'Use a timeline with the source frame rate, a video track, and an original soundtrack track.',
'Run 原声须覆盖完整交付区间。': 'The original soundtrack must cover the full delivery range.',
'发布前须固定随机种子、清除素材覆盖并等待已有任务结束。': 'Set a sampling seed, clear asset overrides, and wait for existing jobs before publishing.',
'发布 Run 前须固定素材和肖像的引用版本。': 'Pin asset and portrait reference versions before publishing.',
'每个分段须固定一个源视频引用。': 'Pin one source video reference for each segment.',
'Run 需要可见的片段节点。': 'Make all segment nodes visible before publishing this Run.',
'分段 Run 需要 FastH3 部署。': 'Segmented Runs require a FastH3 deployment.',
'Run 续接片段需要支持时间线导帧的部署。': 'Continuations require a deployment that supports timeline guides.',
'Run 帧数或帧率与实际源片不一致。': 'The frame count or frame rate does not match the source video.',
'工程在核对期间已更新,请重新发布 Run。': 'The project changed during validation. Review and publish the Run again.',
'模型配置在核对期间已更新,请重新发布 Run。': 'The model configuration changed during validation. Review and publish the Run again.',
}
if chinese in run_messages:
return run_messages[chinese]
if code == 'invalid_input':
measured = re.fullmatch(r'片段「(.*)」实测输入 (\d+) 帧,请求 (\d+) 帧。.*', chinese, re.DOTALL)
if measured:
name, actual, requested = measured.groups()
return (f'{name}: input {actual} frames, requested {requested} frames. '
'Both must match 17k+5 with k >= 6 (at least 107 frames).')
if re.fullmatch(r'片段「.*」无法按 24 FPS 解码数帧。', chinese, re.DOTALL):
return 'The segment input could not be decoded and counted at 24 FPS.'
if code == 'invalid_input' and chinese == '分组片段提交时必须指定来源画布节点(originItemId)。':
return 'Submitting a grouped segment requires its source canvas node (originItemId).'
if code == 'invalid_input' and chinese == '聊天引用超过数量上限,请移除部分引用。':
return 'The chat reference limit was exceeded. Remove some references and retry.'
if code == 'invalid_input' and chinese == '视频裁切需要视频来源节点。':
return 'Select a video canvas node as the source for this trim.'
if code == 'invalid_input' and chinese == '裁切结束时间超出来源视频时长。':
return 'The trim ends after the source video. Choose an end time within the source duration.'
if status == 409 and chinese == '此视频裁切正在进行,请等待结果。':
return 'This trim is already running. Wait for its result.'
if code == 'reference_invalid':
fasth3_image = re.fullmatch(r'FastH3 参考图“(.+)”的两边须为 256–5760 像素,宽高比须为 0.4–2.5。', chinese, re.DOTALL)
if fasth3_image:
return f'Each side of the FastH3 reference image “{fasth3_image[1]}” must be 256–5760 pixels and its aspect ratio must be 0.4–2.5.'
guide_plan_messages = {
'已确认的导帧计划不能取消约束、改换锚点或移除原有片段。': 'A confirmed guide plan must retain its guide requirement, anchor and existing steps.',
'H3 分段计划必须启用时间线导帧约束。': 'Enable the timeline guide requirement for this H3 segment plan.',
'导帧计划的每个片段都必须绑定视频生成配置。': 'Bind each guide plan step to a video generation configuration.',
'导帧计划中的片段必须使用各自的生成配置。': 'Each guide plan step needs its own generation configuration.',
'已接受任务的导帧部署已变化或不再支持导帧。': 'The deployment captured by this job changed or no longer supports timeline guides.',
}
if chinese in guide_plan_messages:
return guide_plan_messages[chinese]
wrong_step = re.fullmatch(r'必须从计划中的片段节点 ([0-9a-f-]{36}) 提交。', chinese)
if wrong_step:
return f'Submit from the planned segment node {wrong_step[1]}.'
wrong_plan = re.fullmatch(r'片段「(.+)」的导帧计划与冻结任务不一致。', chinese, re.DOTALL)
if wrong_plan:
return f'The guide plan for segment “{wrong_plan[1]}” differs from the frozen job.'
wrong_source = re.fullmatch(r'片段「(.+)」的冻结导帧来源与本次采用的上游结果不一致。', chinese, re.DOTALL)
if wrong_source:
return f'The frozen guide source for segment “{wrong_source[1]}” differs from the adopted upstream result.'
unavailable_guide = re.fullmatch(r'片段「(.+)」的冻结导帧素材无法读取。', chinese, re.DOTALL)
if unavailable_guide:
return f'The frozen guide asset for segment “{unavailable_guide[1]}” could not be read.'
chat_reference = re.fullmatch(r'聊天引用 ([0-9a-f-]+) 的来源或素材版本已失效,请重新选择此引用。', chinese)
if chat_reference:
return f'Chat reference {chat_reference[1]} has a stale source or asset version. Select it again and retry.'
unknown_chat_reference = re.fullmatch(r'聊天引用 ([0-9a-f-]+) 不属于当前对话。', chinese)
if unknown_chat_reference:
return f'Chat reference {unknown_chat_reference[1]} does not belong to the current conversation.'
guide_segment = re.fullmatch(r'片段「(.+)」必须使用有效的 H3 时间线导帧。', chinese, re.DOTALL)
if guide_segment:
return f'Segment “{guide_segment[1]}” requires a valid H3 timeline guide.'
segment = re.fullmatch(r'组装片段「(.+)」的生成任务缺少来源画布节点(originItemId)。', chinese, re.DOTALL)
if segment:
return f'The generation job for assembly segment “{segment[1]}” is missing its source canvas node (originItemId).'
job = re.fullmatch(
r'生成任务「([0-9a-f-]{36})」(规格 ([0-9a-f-]{36}))缺少来源画布节点(originItemId),无法确定对应的组装片段。',
chinese,
)
if job:
return (f'Generation job {job[1]} (spec {job[2]}) is missing its source canvas node (originItemId). '
'The assembly segment could not be identified.')
if code == 'tool_model_missing':
return missing_tool_model_message(required_capability, english=True)
if code == 'model_list_http_error':
Expand Down
6 changes: 5 additions & 1 deletion build_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ def prepare_resources():
if bundled.exists():
shutil.rmtree(bundled)
shutil.copytree(ROOT / 'dist', bundled / 'web')
shutil.copytree(ROOT / 'packages/agent/skills', bundled / 'skills')
skill_ignore = shutil.ignore_patterns('__pycache__', '*.pyc', '*.pyo')
shutil.copytree(ROOT / 'packages/agent/skills', bundled / 'skills', ignore=skill_ignore)
h3_skill = ROOT / '.agents/upstream/minimax-h3/skills/h3-prompt-writing'
if (h3_skill / 'SKILL.md').is_file():
shutil.copytree(h3_skill, bundled / 'skills/h3-prompt-writing', ignore=skill_ignore)
npm_package = ROOT / 'node_modules/opencode-ai'
metadata = json.loads((npm_package / 'package.json').read_text())
if os.name == 'nt':
Expand Down
Loading
Loading