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
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 @@ -706,9 +707,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 @@ -722,7 +722,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 @@ -791,6 +792,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 @@ -809,7 +813,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, edited_documents=edited_documents)
skills=plan['available'], conversation_id=chain.conversation_id, edited_documents=edited_documents,
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
9 changes: 5 additions & 4 deletions apps/api/src/opendirector_api/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,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 @@ -466,12 +466,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
18 changes: 18 additions & 0 deletions apps/api/src/opendirector_api/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@
from opendirector.domain.capabilities import Capability
from opendirector.domain.capability_messages import english_capability_message, missing_tool_model_message

from opendirector.domain.creation.assets import ASSET_DOWNLOAD_ENGLISH

ENGLISH_BY_CODE = {
**ASSET_DOWNLOAD_ENGLISH,
'keyframe_unsupported': 'This model or mode does not support keyframes. Clear the keyframe times or choose another model.',
'keyframe_mode': 'Keyframes work in Universal reference mode only, not with first/last frames, continuation or structure control.',
'keyframe_kind': 'A keyframe must be an image.',
Expand Down Expand Up @@ -211,6 +214,21 @@ def localized_error_for_language(
translated = english_capability_message(chinese)
if translated:
return translated
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':
chat = re.fullmatch(r'聊天引用 ([0-9a-f-]+) 的来源或素材版本已失效,请重新选择此引用。', chinese)
if chat:
return f'Chat reference {chat[1]} has a stale source or asset version. Select it again and retry.'
unknown = re.fullmatch(r'聊天引用 ([0-9a-f-]+) 不属于当前对话。', chinese)
if unknown:
return f'Chat reference {unknown[1]} does not belong to the current conversation.'
# A generic operation code must not hide a more specific HTTP status.
generic = code in {"operation_rejected", "invalid_input"}
if generic and status in {413, 502, 504}:
Expand Down
26 changes: 26 additions & 0 deletions docs/guides/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,3 +198,29 @@ Updates and resizes require the `canvas_item` revision returned by `show`. Recei
`canvas text show` reads `/api/creation/projects/{projectId}/assets/{assetId}/content` through a bounded HTTP stream on both CLI transports, retaining UTF-8 BOM and CRLF. Its cap is `MAX_CREATION_TEXT_BYTES` (1,048,576 bytes); the shared agent `read` tool still uses its original 64 KiB budget. The API address comes from `--url` or `OPENDIRECTOR_API_URL`, which the application launcher supplies to Agent Shell.

`canvas text show` 在两种 CLI 传输方式下都通过有界 HTTP 流读取 `/api/creation/projects/{projectId}/assets/{assetId}/content`,保留 UTF-8 BOM 和 CRLF。上限为 `MAX_CREATION_TEXT_BYTES`(1,048,576 字节);共用 Agent `read` 工具仍保留原有的 64 KiB 预算。API 地址来自 `--url` 或 `OPENDIRECTOR_API_URL`,应用启动器会将该环境变量传给 Agent Shell。

## 在 Agent 命令中使用聊天引用

在 Agent 会话中,`project show` 按消息中的顺序返回 `turnReferences`。选择画布节点时,每项记录节点 ID 和提交时选中的 `AssetRef`。直接上传到聊天的文件只携带 `AssetRef`。创建生成节点时,可重复传入 `--turn-reference` 来固定引用版本。视频裁切需要画布视频节点,会发布一个新节点并在编辑快照中保存来源和裁切时间。

```bash
opendirector canvas create-generation --file plan.json --turn-reference IMAGE_REFERENCE_ID
opendirector video trim --turn-reference VIDEO_REFERENCE_ID --start 1.2 --end 1.7 --name clip.mp4
```

### Using chat references in Agent commands

Inside an Agent turn, `project show` returns `turnReferences` in message order. A selection from the canvas carries its source node ID and the `AssetRef` captured at submission. A file uploaded directly to chat carries only an `AssetRef`. Repeat `--turn-reference` on `canvas create-generation` to pin selected versions. `video trim` requires a video canvas node and publishes a new node with an edit snapshot recording its source and time range.


## 下载原始素材

从 `project show` 获取素材 ID 和版本,用 `asset download` 将指定版本的原始字节写入新文件。下载无需编辑租约,与项目登记分开。Agent Shell 使用当前项目,输出路径须位于本轮执行目录内。

```bash
opendirector --project PROJECT_UUID asset download --id ASSET_UUID --revision 1 --output ./source.mp4
```

### Download original assets

Use `project show` to get the asset ID and revision. `asset download` copies the original bytes of that revision to a new file. This read requires no editing lease or asset registration. In Agent Shell the active project is already selected, and the output path must stay inside the current execution directory.
Binary file not shown.
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
3 changes: 3 additions & 0 deletions packages/core/src/opendirector/agent/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from pydantic import JsonValue

from opendirector.agent.references import TurnReference
from opendirector.domain.agent_runtime import RuntimeId
from opendirector.infrastructure.local_projects import write_json

Expand All @@ -23,6 +24,8 @@ class RunContext:
messages: list[dict[str, JsonValue]]
selected_skills: list[str]
model_selections: dict[str, str | None] = field(default_factory=dict)
turn_references: tuple[TurnReference, ...] = ()
earlier_references: tuple[TurnReference, ...] = ()
conversation_id: UUID | None = None
thinking: str = 'auto'
runtime_model: str | None = None
Expand Down
17 changes: 16 additions & 1 deletion packages/core/src/opendirector/agent/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,18 @@
from dataclasses import dataclass
import json
from pathlib import Path
from typing import Annotated
from uuid import UUID

from pydantic import JsonValue, TypeAdapter, ValidationError
from pydantic import Field, JsonValue, TypeAdapter, ValidationError

from opendirector.agent.context import AgentEvent, RunContext
from opendirector.agent.tools import AgentTools, tools
from opendirector.domain.projects import ProjectError
from opendirector.domain.creation.commands import COMMAND_MODELS
from opendirector.domain.rule_facts import MAX_REFERENCES

REFERENCE_IDS = TypeAdapter(Annotated[list[UUID], Field(min_length=1, max_length=MAX_REFERENCES)])


@dataclass(frozen=True, kw_only=True)
Expand Down Expand Up @@ -107,6 +112,16 @@ async def execute(self, call_id: str, name: str, arguments: dict[str, JsonValue]
self.run.edited_documents[changed['id']] = changed['revision']
if name == 'read_project':
value['modelSelections'] = dict(self.model_selections)
references = self.run.turn_references
if 'referenceIds' in arguments:
ids = REFERENCE_IDS.validate_python(arguments['referenceIds'])
known = {ref.id: ref for ref in (*self.run.earlier_references, *references)}
unknown = next((identity for identity in ids if identity not in known), None)
if unknown is not None:
raise ProjectError(f'聊天引用 {unknown} 不属于当前对话。', 409, code='reference_invalid')
references = tuple(known[identity] for identity in dict.fromkeys(ids))
if references:
value['turnReferences'] = [ref.observation() for ref in references]
error = None
if isinstance(value, dict):
if value.get('status') == 'rejected':
Expand Down
102 changes: 102 additions & 0 deletions packages/core/src/opendirector/agent/references.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"""Resolve chat inputs to project-owned sources before entering any runtime."""
from collections.abc import Iterable
from typing import Literal
from uuid import UUID, uuid5

from pydantic import BaseModel, Field, JsonValue, ValidationError

from opendirector.application.creation_canvas import asset_ref, current_asset
from opendirector.domain.creation.assets import AssetRef
from opendirector.domain.creation.base import CanvasItemVersion, Contract, Fingerprint
from opendirector.domain.creation.project import ProjectSnapshot
from opendirector.domain.projects import ProjectError
from opendirector.domain.rule_facts import MAX_REFERENCES


class ChatReference(BaseModel):
assetId: UUID
nodeId: UUID | None = None
sourceRole: str | None = Field(default=None, max_length=32)
binding: Literal['asset'] | None = None
fingerprint: Fingerprint | None = None


class TurnReference(Contract):
id: UUID = Field(description='Stable identifier for one selected source in this chat turn.')
name: str = Field(description='Source label captured when the request was accepted.')
asset: AssetRef = Field(description='Exact project asset version captured at chat submission.')
sourceVersion: CanvasItemVersion | None = Field(default=None, description='Selected canvas item and its version.')
sourceRole: str | None = Field(default=None, description='Selected slot within the canvas item, when applicable.')

def observation(self) -> dict[str, JsonValue]:
value = self.model_dump(mode='json', exclude_none=True)
pinned = {'binding': 'pinned', 'source': value['asset']}
if self.sourceVersion is not None:
value['sourceItemId'] = str(self.sourceVersion.id)
pinned['sourceVersion'] = value['sourceVersion']
if self.sourceRole:
pinned['subjectRole'] = self.sourceRole.split(':', 1)[0]
value['pinned'] = pinned
return value


def resolve_turn_references(snapshot: ProjectSnapshot, turn_id: UUID,
content: Iterable[dict[str, JsonValue]], attachment_ids: Iterable[UUID]) -> tuple[TurnReference, ...]:
assets = {asset.id: asset for asset in snapshot.assets}
items = {item.id: item for item in snapshot.canvasItems}
documents = {document.id: document for document in snapshot.editorDocuments}
references: dict[tuple[UUID | None, UUID | str | None], TurnReference] = {}
attached: set[UUID] = set()

def invalid(identity: UUID | int) -> ProjectError:
return ProjectError(f'聊天引用 {identity} 的来源或素材版本已失效,请重新选择此引用。',
409, code='reference_invalid')

def resolve(part: ChatReference) -> None:
node_id = part.nodeId if part.binding != 'asset' else None
role = part.sourceRole if node_id is not None else None
asset = assets.get(part.assetId)
if asset is None or (part.fingerprint and part.fingerprint != asset.fingerprint):
raise invalid(node_id or part.assetId)
frozen = asset_ref(asset)
version = None
name = asset.name
if node_id is not None:
item = items.get(node_id)
if item is None:
raise invalid(node_id)
if item.kind == 'subject' and item.binding.role == 'editor':
data = documents[item.binding.objectRef.id].data
slots = {'main': data.main, 'voice': data.voice,
**{f'auxiliary:{i}': source for i, source in enumerate(data.auxiliaries)}}
source = slots.get(role)
matches = (source is not None and source.assetId == asset.id and source.fingerprint == asset.fingerprint
and source.revision <= asset.revision)
if matches:
frozen = source
else:
source = current_asset(snapshot, item)
matches = role is None and source is not None and source.id == asset.id
if not matches:
raise invalid(node_id)
version = CanvasItemVersion(objectType='canvas_item', id=item.id, revision=item.revision)
name = item.title or name
attached.add(asset.id)
key = (node_id, role) if node_id is not None else (None, asset.id)
if key not in references:
references[key] = TurnReference(id=uuid5(turn_id, f'input:{len(references)}'), name=name,
sourceVersion=version, sourceRole=role, asset=frozen)

for index, part in enumerate(content, start=1):
if part.get('type') == 'reference':
try:
reference = ChatReference.model_validate(part)
except ValidationError:
raise invalid(index) from None
resolve(reference)
for asset_id in attachment_ids:
if asset_id not in attached:
resolve(ChatReference(assetId=asset_id))
if len(references) > MAX_REFERENCES:
raise ProjectError('聊天引用超过数量上限,请移除部分引用。', code='invalid_input')
return tuple(references.values())
Loading