diff --git a/MANIFEST.in b/MANIFEST.in index 5c087363e..4250a2505 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -2,9 +2,11 @@ include build_backend.py setup.py pyproject.toml README.md README.zh-CN.md include package.json package-lock.json index.html tsconfig.json vite.config.ts .nvmrc recursive-include src * recursive-include packages/core/src *.py +recursive-include packages/core/src/opendirector/application/motion_runtime * recursive-include apps/api/src *.py include apps/api/src/opendirector_api/example-canvases.json recursive-include packages/agent/skills * +recursive-include packages/agent/motion-skills * prune packages/core/src/opendirector/_bundled prune node_modules prune dist diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index 77e81c7f1..52d810fae 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -34,6 +34,7 @@ from opendirector.domain.timeline_errors import timeline_error, timeline_error_message from opendirector.infrastructure.creation_projects import CreationProjects from opendirector.media.fonts import MAX_FONT_BYTES, inspect_font +from opendirector.media.system_fonts import list_local_system_fonts from opendirector_api.models import AssetSource, Session, UrlSource from opendirector_api.localization import localized_receipt @@ -104,6 +105,11 @@ def localized_video_task(request: Request, task: VideoConversionTask) -> VideoCo ), }) + @router.get('/fonts/local') + def local_system_fonts(response: Response): + response.headers['Cache-Control'] = 'private, max-age=300' + return {'fonts': list(list_local_system_fonts())} + @router.post('/fonts/inspect', response_model=FontCoverageResponse) async def inspect_preview_font(request: Request, response: Response, content_length: int | None = Header(default=None, ge=0)): diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 849b8bdb9..0bad0e78c 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -140,10 +140,42 @@ "antigravity_denied": "Antigravity requested a tool outside OpenDirector's allowed scope. It was denied and this turn has no reply.", "antigravity_empty": "Antigravity returned no reply for this turn. Check the native trace.", "agent_dependency_unavailable": "Bundled Agent is unavailable. Reinstall with pip install --force-reinstall opendirector; for a source checkout, use pip install -e .", + "motion_model_missing": "No chat/agent model is configured. Add an Agent model in Model Settings first.", + "motion_media_missing": "One or more connected media assets referenced by this composition are missing or unreadable. Reconnect the media node and try again.", + "motion_chrome_not_found": "Chrome or Chromium is required for Web Motion MP4 export. Install Google Chrome or set OPENDIRECTOR_CHROME_BIN.", + "motion_ffmpeg_not_found": "FFmpeg is required for Web Motion MP4 export. Install ffmpeg and ensure it is on PATH.", + "motion_render_not_found": "Render job not found.", + "motion_render_not_ready": "Render job is not finished yet.", + "motion_render_missing": "Rendered video file is missing.", + "motion_render_failed": "Web Motion MP4 render failed.", + "motion_render_cancelled": "Web Motion MP4 render was cancelled.", + "motion_render_project_mismatch": "Render job does not belong to the target project.", + "motion_inspect_failed": "Frame inspection failed. Please try again.", + "motion_inspect_cancelled": "Frame inspection was cancelled.", + "motion_inspect_timeout": "Frame inspection timed out. Please try again.", + "motion_chat_failed": "Motion Director chat failed. Please try again.", + "motion_api_unavailable": "Motion commands require a running API. Start the API and check OPENDIRECTOR_API_URL.", + "motion_provider_input": "The model service rejected the input or parameters. Check your request and model capabilities.", + "motion_provider_reference": "The model service rejected the reference media. Replace the reference asset and try again.", + "motion_provider_authentication": "Model service authentication failed. Check the API key in Model Settings.", + "motion_provider_permission": "The model service denied access. Check your API key, model permissions, and safety policy.", + "motion_provider_quota": "Model account balance or quota is insufficient. Check your account quota and try again.", + "motion_provider_rate_limit": "The model service is busy or rate-limited. Wait a moment and try again.", + "motion_provider_temporary": "The model service is temporarily unavailable. Please try again later.", + "motion_provider_protocol": "The model service returned an invalid response. Check the model configuration and try again.", + "motion_provider_error": "The model service could not complete the request. Please try again.", + "motion_empty_message": "Enter a motion instruction before sending.", + "motion_output_length_limit": "The generated motion code exceeded the model's single-turn output limit and was truncated. Try lowering Thinking effort (or turning it off), or break the request into smaller steps.", + "motion_thinking_length_limit": "Model reasoning exhausted the single-turn output limit before producing motion code. Lower Thinking effort to Off or Low and try again.", + "chat_thinking_length_limit": "The model's reasoning exhausted the maximum output token limit before producing a reply. Increase the max output tokens or lower the thinking effort and try again.", + "chat_output_length_limit": "The model response reached the maximum output token limit and was truncated. Increase the max output tokens and try again.", + "chat_content_filtered": "The model response was blocked by the provider's content safety rules. Adjust the prompt and try again.", + "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.", "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.", @@ -224,6 +256,8 @@ def localized_error_for_language( 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 status == 409 and chinese == '此动效发布正在进行,请等待结果。': + return 'This motion publication is already running. Wait for its result.' if code == 'reference_invalid': chat = re.fullmatch(r'聊天引用 ([0-9a-f-]+) 的来源或素材版本已失效,请重新选择此引用。', chinese) if chat: diff --git a/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py index cc524c683..ec65a556b 100644 --- a/apps/api/src/opendirector_api/main.py +++ b/apps/api/src/opendirector_api/main.py @@ -21,6 +21,8 @@ from opendirector.application.model_availability import ModelAvailability from opendirector.application.preferences import Preferences from opendirector.application.prompt_optimization import PromptOptimization +from opendirector.application.motion_generation import MotionGeneration +from opendirector.application.motion_web_render import motion_web_render_manager from opendirector.application.tool_tasks import ToolTasks from opendirector.application.creation_tool_assets import CreationToolAssets from opendirector.infrastructure.local_projects import LocalProjects @@ -29,6 +31,7 @@ from opendirector.integrations.chat_completions import ChatCompletions from opendirector_api.creation import creation_routes, preview_until_disconnect from opendirector_api.agent import agent_routes +from opendirector_api.motion import motion_routes from opendirector_api.library import library_routes from opendirector_api.voices import voice_routes from opendirector_api.examples import router as example_routes @@ -67,6 +70,7 @@ def create_app(store: LocalProjects | None = None, chat_provider=None, generatio creation_tools = ToolTasks(store, model_configs, CreationToolAssets(creation_projects), projects=creation_projects, availability=availability) creation_generation.tool_tasks = creation_tools catalog = ModelCatalog(model_configs, chat_provider or ChatCompletions(), availability) + motion_generation = MotionGeneration(model_configs, chat_provider or ChatCompletions()) active_agents = {} @@ -86,6 +90,7 @@ async def lifespan(app): await pipelines.close() await creation_tools.close() finally: + motion_web_render_manager.shutdown() await creation_generation.close() availability.probe.close() @@ -94,12 +99,13 @@ async def lifespan(app): PromptOptimization(creation_projects, model_configs, chat_provider or ChatCompletions(), cli_rewrite=_cli_prompt_rewrite))) app.include_router(agent_routes(creation_projects, creation_generation, model_configs, chat_provider, active=active_agents)) + app.include_router(motion_routes(motion_generation, projects=creation_projects)) app.include_router(library_routes(creation_projects)) app.include_router(voice_routes(creation_generation.voices)) app.include_router(example_routes) app.state.desktop_activity = lambda: dict( agents=len(active_agents), generations=sum(not job.future.done() for job in creation_generation.jobs.values()), - tools=sum(not job.done() for job in creation_tools.jobs.values())) + tools=sum(not job.done() for job in creation_tools.jobs.values()) + motion_web_render_manager.active_job_count()) @app.exception_handler(RequestValidationError) @@ -348,7 +354,13 @@ def placement(project_id: UUID, task_id: UUID, value: ToolPlacement, x_opendirec # StaticFiles confines reads to this directory and rejects escaping symlinks. font_root = dist / "fonts" if font_root.is_dir() and not font_root.is_symlink() and font_root.resolve().is_relative_to(dist.resolve()): - app.mount("/fonts", StaticFiles(directory=font_root), name="fonts") + class _CorsFontStaticFiles(StaticFiles): + async def get_response(self, path: str, scope): + response = await super().get_response(path, scope) + response.headers["Access-Control-Allow-Origin"] = "*" + return response + + app.mount("/fonts", _CorsFontStaticFiles(directory=font_root), name="fonts") @app.get("/") def index(): diff --git a/apps/api/src/opendirector_api/motion.py b/apps/api/src/opendirector_api/motion.py new file mode 100644 index 000000000..cbc4a54fa --- /dev/null +++ b/apps/api/src/opendirector_api/motion.py @@ -0,0 +1,692 @@ +from __future__ import annotations + +import asyncio +import json +import logging +import re +import threading +from typing import Annotated, Any, Literal +from urllib.parse import urlsplit +from uuid import UUID + +from fastapi import APIRouter, Header, Request +from fastapi.responses import FileResponse, HTMLResponse, Response, StreamingResponse +from pydantic import BaseModel, ConfigDict, Field, field_validator +from starlette.concurrency import run_in_threadpool + +from opendirector.application.creation_assets import CreationAssets +from opendirector.application.creation_media_publication import ( + prepare_motion_publication, + publish_rendered_motion_mp4, +) +from opendirector.application.motion_director_agent import stream_motion_director_chat +from opendirector.application.motion_generation import MotionGeneration +from opendirector.application.motion_skills import motion_skills_directory_hint, public_motion_skills +from opendirector.application.motion_web_render import ( + inspect_web_motion_frames, + motion_web_render_manager, + resolve_bundled_static_file, +) +from opendirector.domain.creation.assets import UploadInfo +from opendirector.domain.generation import GenerationError +from opendirector.domain.projects import ProjectError +from opendirector.infrastructure.creation_files import file_identity +from opendirector.infrastructure.creation_projects import CreationProjects +from opendirector.infrastructure.local_projects import LocalProjects +from opendirector.ports.files import CHUNK_BYTES +from opendirector.ports.gateway import gateway +from opendirector_api.localization import localized_error, localized_error_for_language, localized_receipt + +logger = logging.getLogger(__name__) + +_CHINESE_MOTION_ERROR_BY_CODE: dict[str, str] = { + "motion_model_missing": "未配置对话 / Agent 模型,请先在「模型设置」中添加 Agent 模型。", + "motion_empty_message": "请输入动效指令后再发送。", + "motion_media_missing": "动效引用的媒体资产缺失或无法读取,请重新连接素材节点后重试。", + "motion_chrome_not_found": "本机未找到 Chrome / Chromium 浏览器,无法渲染 Web 动效。请安装 Chrome 或设置 OPENDIRECTOR_CHROME_BIN。", + "motion_ffmpeg_not_found": "本机未找到 FFmpeg,无法导出 MP4。请安装 ffmpeg 并确保其在 PATH 中。", + "motion_render_not_found": "未找到对应的动效导出任务。", + "motion_render_not_ready": "动效导出任务尚未完成。", + "motion_render_missing": "动效导出视频文件不存在。", + "motion_render_failed": "Web 动效导出失败。", + "motion_render_cancelled": "已取消 Web 动效导出。", + "motion_render_project_mismatch": "该导出任务不属于目标项目。", + "motion_inspect_failed": "动效帧检查失败,请稍后重试。", + "motion_inspect_cancelled": "动效帧检查已取消。", + "motion_inspect_timeout": "动效帧检查超时,请重试。", + "motion_chat_failed": "AI 动效导演对话失败,请稍后重试。", + "motion_output_length_limit": "本次生成的动效代码超过模型单次输出长度上限而被截断。建议将左下角「思考强度」调低或关闭,或分步生成。", + "motion_thinking_length_limit": "模型思考过程耗尽了单次输出上限,未能输出动效代码。请将左下角「思考强度」调为「关闭」或「低」后重试。", + "chat_content_filtered": "模型回复被内容安全规则拦截,请调整描述后重试。", + "chat_incomplete_response": "模型回复未正常完成,已生成内容已保留,请重试。", + "invalid_input": "请求参数无效,请检查字段后重试。", + "invalid_project": "项目或资产标识无效。", + "missing_object": "请求的对象不存在。", + "not_found": "请求的对象不存在。", + "session_expired": "工程已关闭或会话已过期,请重新打开后保存。", + "command_conflict": "该标识已用于不同输入,请使用新的标识。", + "reference_invalid": "动效来源已变化。", + "revision_conflict": "动效输出与已保存的版本不一致。", + "role_restricted": "该节点当前不允许此操作。", + "storage_busy": "此动效发布正在进行,请等待结果。", + "storage_unavailable": "项目存储服务不可用,请稍后重试。", +} + +_SAFE_MOTION_ERROR_CODES: dict[str, str] = {code: code for code in _CHINESE_MOTION_ERROR_BY_CODE} + +_CHINESE_GENERATION_FAILURE_BY_CATEGORY: dict[str, tuple[str, str]] = { + "input": ("motion_provider_input", "生成服务拒绝了输入内容或参数。请检查生成要求、参数和模型支持范围。"), + "reference": ("motion_provider_reference", "生成服务拒绝了参考素材。请更换符合服务要求的参考素材后重试。"), + "authentication": ("motion_provider_authentication", "生成服务鉴权失败。请在模型设置中检查 API Key。"), + "permission": ("motion_provider_permission", "生成服务拒绝了访问请求。请检查 API Key、模型调用权限和服务安全策略。"), + "quota": ("motion_provider_quota", "模型账户余额或套餐额度不足。请核对账户余额和套餐额度。"), + "rate_limit": ("motion_provider_rate_limit", "模型服务繁忙或请求受限。请稍后再试。"), + "temporary": ("motion_provider_temporary", "生成服务暂时不可用,请稍后重试。"), + "submission_unknown": ("motion_provider_temporary", "生成请求状态未知,请稍后重试。"), + "local": ("motion_chat_failed", "本地动效请求准备失败,请检查配置后重试。"), + "protocol": ("motion_provider_protocol", "模型服务返回了异常响应,请检查模型配置后重试。"), + "provider": ("motion_provider_error", "模型服务未能完成当前操作,请稍后重试。"), +} + +_RASTER_IMAGE_DATA_URL_RE = re.compile( + r"^data:image/(?:png|jpe?g|webp|gif);base64,[A-Za-z0-9+/=\s]+$", + re.I, +) + + +def _normalize_optional_data_url(value: str | None) -> str | None: + if value is None: + return None + cleaned = value.strip() + return cleaned or None + + +def _is_loopback_base_url(base_url: str) -> bool: + parts = urlsplit(str(base_url or "").strip()) + return parts.scheme.lower() == "http" and (parts.hostname or "").lower() in {"127.0.0.1", "localhost", "::1"} + + +class MotionTextInput(BaseModel): + model_config = ConfigDict(allow_inf_nan=False) + title: str = Field(default="", max_length=255) + content: str = Field(default="", max_length=64000) + + +class MotionImageInput(BaseModel): + model_config = ConfigDict(allow_inf_nan=False) + id: str = Field(default="", max_length=120) + assetId: str | None = Field(default=None, max_length=64) + mimeType: str | None = Field(default=None, max_length=128) + title: str = Field(default="", max_length=255) + width: int | None = Field(default=None, ge=1, le=16384) + height: int | None = Field(default=None, ge=1, le=16384) + src: str | None = Field(default=None, max_length=8_000_000) + dataUrl: str | None = Field(default=None, max_length=3_000_000) + + @field_validator("dataUrl") + @classmethod + def _clean_data_url(cls, value: str | None) -> str | None: + return _normalize_optional_data_url(value) + + +class MotionVideoInput(BaseModel): + model_config = ConfigDict(allow_inf_nan=False) + id: str = Field(default="", max_length=120) + assetId: str | None = Field(default=None, max_length=64) + mimeType: str | None = Field(default=None, max_length=128) + title: str = Field(default="", max_length=255) + width: int | None = Field(default=None, ge=1, le=16384) + height: int | None = Field(default=None, ge=1, le=16384) + durationSeconds: float | None = Field(default=None, gt=0, le=3600) + src: str | None = Field(default=None, max_length=8_000_000) + dataUrl: str | None = Field(default=None, max_length=3_000_000) + + @field_validator("dataUrl") + @classmethod + def _clean_data_url(cls, value: str | None) -> str | None: + return _normalize_optional_data_url(value) + + +class MotionChatMessage(BaseModel): + model_config = ConfigDict(allow_inf_nan=False) + role: Literal["user", "assistant"] + content: str = Field(min_length=1, max_length=32000) + + +class MotionReferenceAttachment(BaseModel): + model_config = ConfigDict(allow_inf_nan=False) + name: str | None = Field(default=None, max_length=120) + imageDataUrl: str = Field(max_length=3_000_000) + svgSource: str | None = Field(default=None, max_length=250_000) + + @field_validator("imageDataUrl") + @classmethod + def _validate_image_data_url(cls, value: str) -> str: + cleaned = _normalize_optional_data_url(value) + if cleaned is None or not _RASTER_IMAGE_DATA_URL_RE.match(cleaned): + raise ValueError("imageDataUrl must be a valid PNG, JPEG, WebP, or GIF base64 data URL") + return cleaned + + @field_validator("svgSource") + @classmethod + def _validate_svg_source(cls, value: str | None) -> str | None: + if value is None: + return None + cleaned = value.strip() + if not cleaned: + return None + if " APIRouter: + router = APIRouter(prefix="/api/creation/motion", tags=["motion"]) + _assets_cache: list[CreationAssets | None] = [CreationAssets(projects) if projects is not None else None] + _assets_lock = threading.Lock() + + def _get_creation_assets() -> CreationAssets | None: + if _assets_cache[0] is not None: + return _assets_cache[0] + configs = getattr(motion_generation, "model_configs", None) or getattr(motion_generation, "configs", None) + repo = getattr(configs, "repository", None) + if repo is None: + cfg_dir = getattr(configs, "directory", None) + if cfg_dir is not None: + repo = cfg_dir.parent + if repo is None: + return None + with _assets_lock: + if _assets_cache[0] is None: + try: + _assets_cache[0] = CreationAssets(CreationProjects(LocalProjects(repo))) + except Exception: + return None + return _assets_cache[0] + + @router.get("/skills") + async def list_motion_skills(): + return { + "skills": public_motion_skills(), + "skillsDir": motion_skills_directory_hint(), + } + + @router.post("/chat") + async def chat_motion_director(body: MotionChatRequest, request: Request): + base_url = str(request.base_url).rstrip("/") + extra_headers = {"X-OpenDirector-Request": "1"} + desktop_token = request.headers.get("x-opendirector-desktop") + if desktop_token: + extra_headers["X-OpenDirector-Desktop"] = desktop_token + session_header = (request.headers.get("x-opendirector-session") or "").strip() or None + if session_header: + extra_headers["X-OpenDirector-Session"] = session_header + assets_svc = _get_creation_assets() if body.projectId else None + + async def event_stream(): + try: + async for event in stream_motion_director_chat( + motion_generation, + messages=[m.model_dump() for m in body.messages], + model_id=body.modelId, + thinking=body.thinking, + language=body.language, + width=body.width, + height=body.height, + fps=body.fps, + duration=body.duration, + current_web=body.currentWeb, + selected_element_ids=body.selectedElementIds, + script_error=body.scriptError, + pinned_skills=list(dict.fromkeys([*body.skills, *body.pinnedSkills])), + texts=[item.model_dump() for item in body.texts], + images=[item.model_dump() for item in body.images], + videos=[item.model_dump() for item in body.videos], + audio_titles=body.audioTitles, + reference_images=[item.model_dump() for item in body.referenceImages], + style_apply_layout=body.styleApplyLayout, + style_directive=body.styleDirective, + render_base_url=base_url if _is_loopback_base_url(base_url) else None, + render_headers=extra_headers, + project_id=body.projectId, + assets_service=assets_svc, + session=session_header, + require_session=bool(body.projectId), + ): + if await request.is_disconnected(): + break + yield f"data: {json.dumps(event, ensure_ascii=False)}\n\n" + except asyncio.CancelledError: + raise + except GenerationError as exc: + lang_pref = request.headers.get("accept-language") or body.language + err_code, chinese_msg = _CHINESE_GENERATION_FAILURE_BY_CATEGORY.get( + exc.details.category, + ("motion_provider_error", "模型服务未能完成当前操作,请稍后重试。"), + ) + err_msg = localized_error_for_language(lang_pref, chinese=chinese_msg, status=exc.status, code=err_code) + yield f"data: {json.dumps({'type': 'error', 'message': err_msg}, ensure_ascii=False)}\n\n" + except ProjectError as exc: + lang_pref = request.headers.get("accept-language") or body.language + raw_code = exc.code or "motion_chat_failed" + if raw_code == "chat_output_length_limit": + raw_code = "motion_output_length_limit" + elif raw_code == "chat_thinking_length_limit": + raw_code = "motion_thinking_length_limit" + err_code = _SAFE_MOTION_ERROR_CODES.get(raw_code, "motion_chat_failed") + chinese_msg = _CHINESE_MOTION_ERROR_BY_CODE[err_code] + err_msg = localized_error_for_language(lang_pref, chinese=chinese_msg, status=exc.status, code=err_code) + yield f"data: {json.dumps({'type': 'error', 'message': err_msg}, ensure_ascii=False)}\n\n" + except Exception: + lang_pref = request.headers.get("accept-language") or body.language + err_msg = localized_error_for_language( + lang_pref, + chinese="AI 动效导演对话失败,请稍后重试。", + status=500, + code="motion_chat_failed", + ) + yield f"data: {json.dumps({'type': 'error', 'message': err_msg}, ensure_ascii=False)}\n\n" + + return StreamingResponse( + event_stream(), + media_type="text/event-stream", + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, + ) + + @router.post("/inspect-frames") + async def inspect_motion_frames(body: MotionInspectFramesRequest, request: Request): + base_url = str(request.base_url).rstrip("/") + extra_headers = {"X-OpenDirector-Request": "1"} + desktop_token = request.headers.get("x-opendirector-desktop") + if desktop_token: + extra_headers["X-OpenDirector-Desktop"] = desktop_token + visual_bindings = [m.model_dump() for m in body.mediaBindings if m.kind in {"image", "video"}] + assets_svc = _get_creation_assets() if body.projectId else None + cancel_ev = threading.Event() + watch_done = asyncio.Event() + + async def _watch_disconnect() -> None: + while not watch_done.is_set(): + try: + if await request.is_disconnected(): + cancel_ev.set() + return + except Exception: + return + try: + await asyncio.wait_for(watch_done.wait(), timeout=0.2) + except asyncio.TimeoutError: + continue + + watcher = asyncio.create_task(_watch_disconnect()) + try: + result = await asyncio.to_thread( + inspect_web_motion_frames, + web=body.web, + width=body.width, + height=body.height, + fps=body.fps, + duration=body.duration, + clip_id=body.clipId, + targets=body.targets or None, + times=body.times or None, + frame_indices=body.frameIndices or None, + include_image=body.includeImage, + mode=body.mode, + time_range=body.range, + count=body.count, + seam_at=body.seamAt, + mobile_preview=body.mobilePreview, + media_bindings=visual_bindings, + base_url=base_url if _is_loopback_base_url(base_url) else None, + extra_headers=extra_headers, + project_id=body.projectId, + assets_service=assets_svc, + cancel_event=cancel_ev, + ) + if isinstance(result, dict) and result.get("ok") is False: + out = dict(result) + raw_code = str(out.get("errorCode") or out.get("code") or "motion_inspect_failed") + err_code = _SAFE_MOTION_ERROR_CODES.get(raw_code, "motion_inspect_failed") + err_status = 400 if err_code == "invalid_input" else 500 + chinese_msg = _CHINESE_MOTION_ERROR_BY_CODE[err_code] + out["errorCode"] = err_code + out["error"] = localized_error( + request, + chinese=chinese_msg, + status=err_status, + code=err_code, + ) + return out + return result + except asyncio.CancelledError: + cancel_ev.set() + raise + except ProjectError as exc: + err_code = _SAFE_MOTION_ERROR_CODES.get(exc.code or "", "motion_inspect_failed") + chinese_msg = _CHINESE_MOTION_ERROR_BY_CODE[err_code] + return { + "ok": False, + "errorCode": err_code, + "error": localized_error(request, chinese=chinese_msg, status=exc.status, code=err_code), + } + except Exception: + logger.exception("motion_api.inspect_frames_failed") + return { + "ok": False, + "errorCode": "motion_inspect_failed", + "error": localized_error( + request, + chinese="动效帧检查失败,请稍后重试。", + status=500, + code="motion_inspect_failed", + ), + } + finally: + watch_done.set() + watcher.cancel() + + @router.get("/render-assets/three.min.js") + async def get_motion_render_three(): + path = await run_in_threadpool(resolve_bundled_static_file, "assets/motion-templates/three.min.js") + if path is None: + return Response(status_code=404, content="Not found") + return FileResponse( + path=str(path), + media_type="application/javascript", + headers={"Cache-Control": "public, max-age=3600"}, + ) + + @router.get("/render-assets/LICENSE") + async def get_motion_render_three_license(): + path = await run_in_threadpool(resolve_bundled_static_file, "assets/motion-templates/LICENSE") + if path is None: + return Response(status_code=404, content="Not found") + return FileResponse( + path=str(path), + media_type="text/plain; charset=utf-8", + headers={"Cache-Control": "public, max-age=3600"}, + ) + + @router.get("/render-page/{token}") + async def get_motion_render_page(token: str): + bundle = motion_web_render_manager.get_page_bundle(token) + if bundle is None: + return Response(status_code=404, content="Not found") + html, csp = bundle + return HTMLResponse( + content=html, + headers={ + "Content-Security-Policy": csp, + "Cache-Control": "no-store", + "X-Content-Type-Options": "nosniff", + }, + ) + + @router.post("/render-jobs") + async def start_motion_render_job(body: MotionWebRenderRequest, request: Request): + base_url = str(request.base_url).rstrip("/") + extra_headers = {"X-OpenDirector-Request": "1"} + desktop_token = request.headers.get("x-opendirector-desktop") + if desktop_token: + extra_headers["X-OpenDirector-Desktop"] = desktop_token + visual_bindings = [m.model_dump() for m in body.mediaBindings if m.kind in {"image", "video"}] + audio_sources = [m.model_dump() for m in body.mediaBindings if m.kind in {"audio", "video"}] + assets_svc = _get_creation_assets() if body.projectId else None + return await run_in_threadpool( + lambda: motion_web_render_manager.start_job( + web=body.web, + width=body.width, + height=body.height, + fps=body.fps, + duration=body.duration, + media_bindings=visual_bindings, + audio_sources=audio_sources, + audio_volume=body.audioVolume, + video_audio_volume=body.videoAudioVolume, + base_url=base_url if _is_loopback_base_url(base_url) else None, + extra_headers=extra_headers, + project_id=body.projectId, + assets_service=assets_svc, + ) + ) + + @router.get("/render-jobs/{job_id}") + async def get_motion_render_job(job_id: str, request: Request): + status = dict(motion_web_render_manager.get_status(job_id)) + if status.get("status") == "failed" and status.get("error"): + err_code = _SAFE_MOTION_ERROR_CODES.get(str(status.get("errorCode") or ""), "motion_render_failed") + status["error"] = localized_error( + request, + chinese=_CHINESE_MOTION_ERROR_BY_CODE[err_code], + status=500, + code=err_code, + ) + return status + + @router.get("/render-jobs/{job_id}/video") + async def download_motion_render_video(job_id: str): + out_path = motion_web_render_manager.get_video_path(job_id) + return FileResponse( + path=str(out_path), + media_type="video/mp4", + headers={"Cache-Control": "no-store"}, + ) + + @router.post("/render-jobs/{job_id}/stage-upload", response_model=UploadInfo) + async def stage_motion_render_upload( + job_id: str, + body: MotionStageUploadRequest, + x_opendirector_session: UUID = Header(), + ): + out_path = motion_web_render_manager.get_video_path( + job_id, + expected_project_id=str(body.projectId), + ) + assets_svc = _get_creation_assets() + if assets_svc is None: + raise ProjectError("项目存储服务不可用,请稍后重试。", status=503, code="storage_unavailable") + + def _stage() -> UploadInfo: + session_str = str(x_opendirector_session) + out_fingerprint, _ = file_identity(out_path) + expected_name = gateway().asset_name(body.name) + try: + existing = assets_svc.uploads.info(body.projectId, body.handle, session_str) + except ProjectError as exc: + if exc.status != 404: + raise + existing = None + if existing is not None and existing.status in {"ready", "registered"}: + if existing.fingerprint != out_fingerprint or existing.name != expected_name: + raise ProjectError( + "该上传标识已用于不同文件,请使用新的上传标识。", + status=409, + code="command_conflict", + ) + return existing + writer = assets_svc.uploads.begin( + body.projectId, + body.handle, + session_str, + body.name, + expected_kind="video", + ) + try: + with out_path.open("rb") as stream: + while chunk := stream.read(CHUNK_BYTES): + writer.write(chunk) + return writer.finish() + finally: + writer.abort() + + return await run_in_threadpool(_stage) + + @router.post("/publish-prepare") + async def prepare_motion_render_publication( + body: MotionPublishRequest, + request: Request, + x_opendirector_session: UUID = Header(), + ): + assets_svc = _get_creation_assets() + if assets_svc is None: + raise ProjectError("项目存储服务不可用,请稍后重试。", status=503, code="storage_unavailable") + replayed, value = await run_in_threadpool( + lambda: prepare_motion_publication( + assets_svc.projects, + body.projectId, + command_id=body.commandId, + item_id=body.itemId, + editor_id=body.editorId, + title=body.title, + session=str(x_opendirector_session), + source="ui", + ) + ) + if replayed: + receipt, meta = value + return { + "replayed": True, + **localized_receipt(request, receipt).model_dump(mode="json"), + **meta, + "editorId": meta["sourceEditorId"], + } + owner, original = value + return { + "replayed": False, + "itemId": str(owner.id), + "editorId": str(original.id), + "width": int(original.data.width), + "height": int(original.data.height), + "fps": int(original.data.fps), + "duration": float(original.data.duration), + } + + @router.post("/render-jobs/{job_id}/publish") + async def publish_motion_render_job( + job_id: str, + body: MotionPublishRequest, + request: Request, + x_opendirector_session: UUID = Header(), + ): + out_path = motion_web_render_manager.get_video_path( + job_id, + expected_project_id=str(body.projectId), + ) + assets_svc = _get_creation_assets() + if assets_svc is None: + raise ProjectError("项目存储服务不可用,请稍后重试。", status=503, code="storage_unavailable") + receipt, meta = await run_in_threadpool( + lambda: publish_rendered_motion_mp4( + assets_svc.projects, + body.projectId, + item_id=body.itemId, + editor_id=body.editorId, + mp4_path=out_path, + command_id=body.commandId, + title=body.title, + session=str(x_opendirector_session), + source="ui", + ) + ) + return { + **localized_receipt(request, receipt).model_dump(mode="json"), + **meta, + "editorId": meta["sourceEditorId"], + "jobId": job_id, + } + + @router.delete("/render-jobs/{job_id}") + async def cancel_motion_render_job(job_id: str): + await run_in_threadpool(motion_web_render_manager.cancel_job, job_id) + return {"ok": True} + + return router diff --git a/apps/desktop/scripts/prepare-runtime.mjs b/apps/desktop/scripts/prepare-runtime.mjs index 9a5cba68f..606690c00 100644 --- a/apps/desktop/scripts/prepare-runtime.mjs +++ b/apps/desktop/scripts/prepare-runtime.mjs @@ -50,6 +50,9 @@ for (const name of ['ffmpeg', 'ffprobe']) { writeFileSync(join(runtime, 'bin', `LICENSE.${name}.txt`), license.stdout + license.stderr); run(join(runtime, 'bin', executable), ['-version']); } +copyFileSync(join(root, 'node_modules/three/LICENSE'), join(runtime, 'bin/LICENSE.three.txt')); +run(python, ['-I', '-X', 'utf8', '-c', + 'from opendirector.installation import web_root; w = web_root() / "assets/motion-templates"; assert (w / "three.min.js").is_file() and "three.js authors" in (w / "LICENSE").read_text(encoding="utf-8")']); const pythonRelative = relative(runtime, python); const desktopExecutable = process.platform === 'darwin' ? '../../MacOS/OpenDirector' : process.platform === 'win32' ? '../../OpenDirector.exe' : '../../opendirector-desktop'; const workspace = process.platform === 'darwin' ? '$HOME/Library/Application Support/OpenDirector/workspace' : '${XDG_CONFIG_HOME:-$HOME/.config}/OpenDirector/workspace'; diff --git a/apps/desktop/scripts/smoke.mjs b/apps/desktop/scripts/smoke.mjs index 75bca79c3..34bae00ff 100644 --- a/apps/desktop/scripts/smoke.mjs +++ b/apps/desktop/scripts/smoke.mjs @@ -20,6 +20,9 @@ try { const harnessBin = execFileSync(join(runtime, python), ['-I', '-B', '-X', 'utf8', '-c', 'from opendirector.installation import BUNDLED; print(BUNDLED / "bin")'], { encoding: 'utf8' }).trim(); await access(join(harnessBin, process.platform === 'win32' ? 'opencode.exe' : 'opencode')); + await access(join(runtime, 'bin/LICENSE.three.txt')); + execFileSync(join(runtime, python), ['-I', '-B', '-X', 'utf8', '-c', + 'from opendirector.installation import web_root; w = web_root() / "assets/motion-templates"; assert (w / "three.min.js").is_file() and "three.js authors" in (w / "LICENSE").read_text(encoding="utf-8")'], { encoding: 'utf8' }); const video = process.platform === 'win32' ? await createLargeVideo(join(directory, 'large-video.mp4')) : null; diff --git a/apps/desktop/tests/packaged-host.test.mjs b/apps/desktop/tests/packaged-host.test.mjs index df4a85f14..50609d569 100644 --- a/apps/desktop/tests/packaged-host.test.mjs +++ b/apps/desktop/tests/packaged-host.test.mjs @@ -25,6 +25,10 @@ test('Packaged Python starts privately, inspects work, rejects unauthenticated m const response = await fetch(host.url + '/api/health', { headers: { 'X-OpenDirector-Desktop': host.token, 'X-OpenDirector-Request': '1' } }); assert.deepEqual(await response.json(), { status: 'ok' }); + const threeLicense = await fetch(host.url + '/assets/motion-templates/LICENSE', { headers: { + 'X-OpenDirector-Desktop': host.token, 'X-OpenDirector-Request': '1' } }); + assert.equal(threeLicense.status, 200); + assert.match(await threeLicense.text(), /three\.js authors/); const ownSession = randomUUID(); const otherSession = randomUUID(); host.registerSession(ownSession); diff --git a/build_backend.py b/build_backend.py index cec3032e6..32922d4ff 100644 --- a/build_backend.py +++ b/build_backend.py @@ -23,7 +23,14 @@ def prepare_resources(): if bundled.exists(): shutil.rmtree(bundled) shutil.copytree(ROOT / 'dist', bundled / 'web') + for required_rel in ('assets/motion-templates/three.min.js', 'assets/motion-templates/LICENSE'): + target = bundled / 'web' / required_rel + if not target.is_file() or target.stat().st_size == 0: + raise RuntimeError(f'Missing required bundled Motion Studio asset: {required_rel}') shutil.copytree(ROOT / 'packages/agent/skills', bundled / 'skills') + motion_skills_dir = ROOT / 'packages/agent/motion-skills' + if motion_skills_dir.is_dir(): + shutil.copytree(motion_skills_dir, bundled / 'motion-skills') npm_package = ROOT / 'node_modules/opencode-ai' metadata = json.loads((npm_package / 'package.json').read_text()) if os.name == 'nt': diff --git a/docs/architecture/unified-project.md b/docs/architecture/unified-project.md index aeb927527..411e0440c 100644 --- a/docs/architecture/unified-project.md +++ b/docs/architecture/unified-project.md @@ -151,3 +151,13 @@ UI、Agent 和后台完成写入共享可恢复变更通道。通知提示对象 生成结果保留服务端返回的原始文件,不自动裁剪、丢帧、重编码或替换音轨。请求时长与帧数属于执行输入,输出媒体事实依据实际文件记录;模型对齐产生的差异如实保留。片段范围通过时间线显式编辑,转码和音轨调整产生独立派生素材,保留原始结果及来源关系。首次下载、失败恢复及各操作入口遵循同一规则。 浏览器与后台的执行职责必须明确。Agent 可以修改时间线,不代表后台已经能够导出视频;只有存在可调用渲染服务并验证真实输出,才可声称支持关闭浏览器后的自主导出。浏览器合成也可以作为明确需要客户端参与的能力保留。 + +### 动效编辑文档与后台渲染 / Motion documents and background rendering + +`MotionDocument`(`kind: "motion"`)与 `MotionCanvasItem` 将声明式 Web 动效合成(HTML、CSS、确定性时间驱动脚本、剪辑级覆盖参数、关联的文本/图片/视频/音频素材及对话记录)作为统一工程的一等编辑文档持久保存。画布连线接入的媒体素材在浏览器预览时通过受鉴权的本地资产路径解析,导出与帧审看统一经由 `/api/creation/motion/*`(技能目录、AI 导演对话、帧审看 `/inspect-frames`、无头浏览器加 FFmpeg 渲染 `/render-jobs` 与零内存拷贝暂存 `/stage-upload`)以及只读本机字体枚举 `/api/creation/fonts/local` 提供。 + +服务端无头浏览器渲染通过 CDP `Fetch` 拦截将网络访问限制在同源本机服务(或离线测试的受控静态目录),仅向同源本机请求附加桌面鉴权头,拒绝任意 `file://` 及非同源外网媒体绑定。正式发布导出视频沿用共享的 `asset.import` 与 `canvas.publishMedia` 原子提交,并计入桌面活动保护。CLI 与 Agent 可通过 `editor create`/`editor save` 与 `opendirector motion skills|inspect|render` 访问同一套业务能力。 + +`MotionDocument` (`kind: "motion"`) and `MotionCanvasItem` persist declarative Web Motion compositions (HTML, CSS, deterministic time-driven scripts, per-clip overrides, connected text/image/video/audio inputs, and director chat history) as first-class project editor documents. Canvas preview hydrates connected project assets through authenticated local reads; frame inspection, AI direction, and headless Chrome + FFmpeg MP4 rendering run through `/api/creation/motion/*` and read-only local font discovery `/api/creation/fonts/local`. + +Server-side headless Chrome enforces origin isolation via CDP `Fetch`, scoping desktop authentication headers exclusively to same-origin loopback requests and rejecting arbitrary `file://` or cross-origin media bindings. Publishing rendered MP4s uses the shared `stage-upload`, `asset.import`, and `canvas.publishMedia` commit path and reports active renders to desktop activity guards. CLI and Agent callers share these capabilities through `editor` commands and `opendirector motion skills|inspect|render`. diff --git a/docs/development/i18n.md b/docs/development/i18n.md index d022c53cd..eb0efcd05 100644 --- a/docs/development/i18n.md +++ b/docs/development/i18n.md @@ -108,6 +108,7 @@ npm run check:i18n | 错误、状态与后端回执 | [errors.ts](../../src/i18n/messages/zh-CN/errors.ts) | [errors.ts](../../src/i18n/messages/en-US/errors.ts) | | 后端请求错误 | [api.ts](../../src/i18n/messages/zh-CN/api.ts) | [api.ts](../../src/i18n/messages/en-US/api.ts) | | 工具编辑器 | [tools.ts](../../src/i18n/messages/zh-CN/tools.ts) | [tools.ts](../../src/i18n/messages/en-US/tools.ts) | +| 动效工作室 | [motion.ts](../../src/i18n/messages/zh-CN/motion.ts) | [motion.ts](../../src/i18n/messages/en-US/motion.ts) | 审校时重点看:英文长度是否导致按钮换行、专有名词是否统一、错误文案是否给出下一步动作、数量与占位符是否自然。 diff --git a/docs/guides/cli.md b/docs/guides/cli.md index cd5b33912..dfe51011a 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -240,3 +240,20 @@ opendirector video compress --asset-id ASSET_ID --operation-id TASK_ID --preset opendirector video compression-task TASK_ID opendirector video compression-task TASK_ID --action publish ``` + +## Web Motion documents and rendering / 动效编辑文档与渲染 + +Motion nodes are saved as `editor` documents with `kind: "motion"` and managed via `editor create`, `editor save`, `canvas show`, and `canvas attach-editor`. Use the `motion` command group to inspect skills, run rendered frame diagnostics, export local MP4 files, or atomically publish the rendered MP4 as a video node linked to its source Motion node (`provenance.source: "rendered"` and `provenance.sourceItemId`) through the same server-side headless Chrome + FFmpeg pipeline used by Motion Studio: + +动效节点以 `kind: "motion"` 的编辑文档保存,可通过 `editor create`、`editor save`、`canvas show`、`canvas attach-editor` 管理。通过 `motion` 子命令组可查询技能、审看帧布局、导出本地 MP4,或将渲染后的 MP4 作为关联到源动效节点的视频结果节点(`provenance.source: "rendered"` 与 `provenance.sourceItemId`)原子发布到画布,与 Motion Studio 界面流程保持一致: + +```bash +opendirector motion skills +opendirector --project PROJECT_UUID motion inspect --editor-id EDITOR_UUID --mode overview +opendirector --project PROJECT_UUID motion render --editor-id EDITOR_UUID --output ./motion-out.mp4 +opendirector --project PROJECT_UUID --operation-id OP_UUID motion render --publish-item-id MOTION_ITEM_UUID --title "Intro.mp4" +``` + +`motion render` waits for `/api/creation/motion/render-jobs`; `--output` writes a local MP4 with exclusive file creation (`xb`), and `--publish-item-id` commits `canvas.publishMedia` with a frozen execution snapshot so the canvas projects the linked result edge from the source Motion node. Reuse the same `--operation-id` to safely replay a published render without re-rendering. Local Chrome/Chromium/Edge and FFmpeg are required (`OPENDIRECTOR_CHROME_BIN` and `OPENDIRECTOR_FFMPEG_BIN` override binary discovery). + +`motion render` 会等待 `/api/creation/motion/render-jobs` 完成;`--output` 以独占方式(`xb`)写入本地 MP4,`--publish-item-id` 则提交包含冻结执行快照的 `canvas.publishMedia`,使画布自动投影源动效节点到结果视频节点的关联连线。重试时复用同一 `--operation-id` 可幂等回放已发布结果而无需重复渲染。帧审看与 MP4 导出依赖本机 Chrome/Chromium/Edge 和 FFmpeg(可通过 `OPENDIRECTOR_CHROME_BIN` 与 `OPENDIRECTOR_FFMPEG_BIN` 指定路径)。 diff --git a/packages/agent/motion-skills/README.md b/packages/agent/motion-skills/README.md new file mode 100644 index 000000000..6dcfb863f --- /dev/null +++ b/packages/agent/motion-skills/README.md @@ -0,0 +1,30 @@ +# Motion Director Dedicated Skills + +Place dedicated skills for OpenDirector's **Motion Director Agent** here (or in `/.opendirector/motion-skills/` for local custom skills without modifying tracked files). + +## Folder Structure + +```text +.opendirector/motion-skills/ +└── my-director-skill/ + ├── SKILL.md # Required: YAML frontmatter (name, description) + markdown guidance + └── references/ # Optional companion .md / .json reference files + └── templates.md +``` + +Example `SKILL.md`: + +```markdown +--- +name: promo-packaging +description: Broadcast promo video packaging rhythm, safe zones, and lower-third typography rules. +--- + +# Promo Packaging Skill +... +``` + +The Motion Director automatically discovers all skills (earlier entries override later ones with the same name): +1. `/.opendirector/motion-skills/` (user-global, highest priority) +2. `/.opendirector/motion-skills/` (workspace-local overrides) +3. `packages/agent/motion-skills/` (built-in) diff --git a/packages/agent/motion-skills/motion-director/SKILL.md b/packages/agent/motion-skills/motion-director/SKILL.md new file mode 100644 index 000000000..70c26234c --- /dev/null +++ b/packages/agent/motion-skills/motion-director/SKILL.md @@ -0,0 +1,32 @@ +--- +name: motion-director +description: OpenDirector Web Motion Director protocol for conceiving, directing, styling, animating, packaging footage, and surgically editing declarative HTML+CSS+SVG compositions in Motion Studio. +--- + +# OpenDirector Motion Director Protocol + +Direct editable motion films on OpenDirector's HTML + CSS + SVG + Canvas + Three.js engine (`MotionWebDoc`, orthogonal `data-clip-id` overrides, 4-track timeline, deterministic Headless Chrome + FFmpeg export). + +> **Direct from the real subject**: Begin with the brief, brand, or connected source — never a generic layout. Lock one visual premise, what the eye follows from frame 0, and three visual states per beat: **opening, mid-action silhouette, and landed still**. Spend boldness in one unmistakable signature; keep everything else quiet and disciplined. + +**References (`read_motion_skill` — parallel calls share one turn)**: +- **Before `replace_composition` on new films / redesigns** (skip on routine local edits), parallel-read `references/visual-craft-and-choreography.md` (overlap, easing, silhouettes, cuts, revisions) + `references/visual-recipes.md` (domain truth & `ctx.clipT` fragments), plus `references/web-motion-cookbook.md` (engine API, bare-statement `script(ctx)`, `ctx.THREE`, `Fusion Pixel`) when using scripts, 3D, or pixel worlds. + +## 1. Mode, Scope & Honesty +- **CONSULT vs EXECUTE**: Questions, critiques, or diagnostics are `CONSULT` (zero mutations). `EXECUTE` commits through tools — never dump raw code into chat. +- **Route by scope**: + - **Local edit**: touch only what is asked (`patch_clips`, `set_scene_theme`, `upsert_clip_html`, `patch_css`, `patch_script`), respecting `locked` clips and untouched user overrides. + - **New film / full redesign**: on Step 1, parallel-read the references above (skip `inspect_scene` when `clips: 0`) → plan visual premise, grounds, hero footprint `≥40%`, text `≥28px` at 1080p, overlap & seams → build via `replace_composition` → verify below. + - **Template / reference adaptation**: keep structural rhythm or palette/material mood while fitting the new subject and stress-testing real copy length. +- **Clean prose & honest receipts**: Match the user's message language. Keep tool names, JSON, paths, and clip IDs out of prose; stay silent between sequential tool calls unless surfacing a blocker. Report only `ok: true` commits; never claim pixel checks without `inspect_frames`; never fabricate video, ASR, music, or metrics. Reuse uploads via `prepare_reference_asset` (`svg` for `.svg`, `mount` for rasters — never redraw marks) or `generate_image` (`useReferenceImage` mockups, `transparent` sprites). + +## 2. Positive Motion Craft & Engine Floor +- **Overlap linked phases (`30–50%`)**: start the next step while the previous step is still in motion (e.g., an incoming subject overlaps its supporting reveal, or a trace triggers its fill/callout before finishing). Every mid-action frame should read as coherent growth, never isolated scaffolding waiting seconds to connect. +- **Smallest necessary geometry**: use the lightest visual mark that communicates an action; let hero marks, saturated brand color fields, real data, or footage fill `45–70%` of the stage. Keep copy terse (`≥28px` readable body; cut words rather than shrinking type) and hold readable text still (`≥1.0s` settled, `~0.3s/word`, `≥0.15s` clean gap between sequential text beats). +- **Role-based motion & distinct worlds**: match curves to roles (crisp tracing for drawing, long-tailed ease-out for settling, smooth in-out for travel/color floods, faster exits). Land titles completely still. Move across fresh framing and grounds between beats through a shared color, contour, or object on screen. +- **Live state & runtime contract**: Trust `[LIVE STUDIO CONTEXT]` — when theme is `unset`, derive palette boldly from the subject/brand; when existing/user colors are set, respect them. Set `data-exit="none"` explicitly on hard-cut clips (omitting `data-exit` with `data-end` defaults to a `0.45s` fade). Follow `WEB_MOTION_CRAFT_CONTRACT` (`script(ctx)` bare top-level statements, orthogonal transforms, unlocked `data-track="video"`, never pasting raw `texts[]` prompts on screen). + +## 3. Focused Verification, Revisions & Delivery +- **Verify the real motion**: resolve structural `lintWarnings` first. On new films/redesigns, call `inspect_frames` once (`overview` 4 beats; add `range`/`seam`/`mobile` only for moving beats, cuts, or phone text), batch genuine fixes into 1–2 cycles max, and stop speculative tweaks when turn budget is low; if `persistedFindings` repeats, change strategy. Skip on routine copy, theme, or timing tweaks unless asked. +- **Revision verbs**: *critique* (report `t · clip · issue → fix · kept` without editing, naming the strongest beat); *distill* (remove extra layers/copy while keeping one focal accent); *clarify* (tighten headline and reading order); *bolder* (calm the beat before, commit to one decisive scale/color/framing move); *retime* (adjust spans and holds first); *polish* (refine alignment, stagger, and cut seams). +- **Delivery**: `web_update` updates the live draft (MP4 export is user-triggered). For new films/redesigns, close briefly with what changed, strongest beat kept, 2–3 timestamps worth eyeballing, whether pixels were inspected (state honestly on text-only models), and any missing real assets/audio; for routine local edits, simply confirm what changed concisely. diff --git a/packages/agent/motion-skills/motion-director/references/visual-craft-and-choreography.md b/packages/agent/motion-skills/motion-director/references/visual-craft-and-choreography.md new file mode 100644 index 000000000..b2e725992 --- /dev/null +++ b/packages/agent/motion-skills/motion-director/references/visual-craft-and-choreography.md @@ -0,0 +1,85 @@ +# Motion Choreography, Visual Restraint & Revision Reference + +Companion guide to `motion-director/SKILL.md` focused on how motion graphics actually move, stage intermediate frames, cut cleanly between worlds, and respond to focused revisions. + +--- + +## 1. Phase Overlap, Lead/Follow & Stillness + +Motion feels authored when phases causally drive one another rather than queuing mechanically: + +- **30–50% phase overlap**: when Stage A leads into Stage B (e.g. stroke draw → fill reveal, or axis → curve trace → peak callout), start Stage B when Stage A is `30–50%` complete. Fully sequential steps feel robotic; everything arriving simultaneously feels flat. +- **Compress setup, reward the payoff**: keep construction or reveal setups tight (`1.5–3.0s` total) so later hero moments and applications get generous screen time. +- **Lead-then-settle**: the hero subject moves first and **settles to complete stillness**; supporting labels arrive `60–140ms` later and stay dead still while the viewer reads. +- **Reading holds**: give readable lines `~0.3s/word` (`~0.18s/CJK char`) and **`≥1.0s` of completely settled stillness** after arrival. If time is tight, cut words or tighten setup rather than speeding entrances or shrinking font size. + +--- + +## 2. Intermediate Silhouettes & Smallest Geometry + +Scrub halfway through any reveal or construction beat and judge that single frame as a first-time viewer: + +- **Recognizable mid-flight**: even at `35%` progress, the viewer should already read the subject's silhouette, direction, or emerging structure — never disconnected scaffolding or half-empty layout chrome waiting seconds to resolve. +- **Smallest necessary geometry & intentional craft (avoid default AI clichés)**: draw the lightest visual form that serves the brief, and commit to a clear visual medium/direction rather than falling back to generic defaults. Avoid unrequested tropes unless the subject or reference genuinely calls for them: empty dark voids with floating glows/particles, fake HUD/timecode/BPM bars, decorative viewport borders or corner brackets, oversized target reticles, identical 3-card grids, uniform fade-in-up reveals, or docking a mark in a corner across unrelated scenes. Keep any requested guides or auxiliary marks quiet so the primary subject owns the frame. +- **Single-point boldness**: put visual weight in **one** defining element per frame (a saturated full-bleed color field, monumental typography, a physical close-up, or one clean silhouette filling `45–70%` of the stage) and keep surrounding negative space disciplined. + +--- + +## 3. Ease by Role + +Different visual jobs require different velocity profiles — never apply one identical ease to every move: + +| Role | Timing & Curve | Why | +| --- | --- | --- | +| **Drawing / tracing tool** | Crisp near-linear or gentle `easeOut` (`0.35–0.7s`) | Reads like a deliberate pen or plotter stroke | +| **Hero landing / settle** | Long-tailed `ctx.easeOut(u)` (`0.45–0.75s`) | Arrives decisively and cushions into stillness | +| **Camera travel / color flood** | Smooth symmetric `ctx.ease(u)` (`0.4–0.65s`) | Carries the eye cleanly across space or ground | +| **Exit / departure** | `40–50%` shorter than entrance, accelerating out | Clears space cleanly without lingering | +| **Tactile pop (position/scale only)** | `ctx.easeOutBack(u)` sparingly (`0.25–0.4s`) | Playful physical snap — never on opacity, color, or technical marks | + +--- + +## 4. Motivated Cuts & Shifting Visual Worlds + +Carry the viewer through distinct grounds, lighting, and framing across beats rather than keeping every scene locked inside one unchanging frame: + +- **Color flood**: the hero hue expands to become the next scene's full-bleed ground. +- **Contour / shape match**: one geometry transforms into the next (a color field becomes the next frame's ground; a horizontal rule becomes a chart axis or horizon). +- **Eye-line / screen position handoff**: pick up Beat N+1 where the viewer's eye rested at the end of Beat N (`TL / TR / BL / BR / H1 / H2 / V1 / V2`). +- **Motion direction match**: cut near peak velocity with the incoming element continuing the same vector. +- **Clean beat cut**: hold a short calm pause (`0.25–0.5s`) before a sharp contrast cut in scale or ground. + +--- + +## 5. Video Scale & Coupled Adjustments + +Video is viewed at arm's length or on phones — web UI sizing disappears: +- **Display headlines**: `72–150px` (`-0.02em` to `-0.04em` tracking); **readable body**: `28–42px` (`≥2.6%` of short side); **short chapter/unit tags**: `18–24px` crisp contrast; **hero subject**: `45–70%` of frame width or height (preserve natural aspect ratio — scale by width or height, never stretch non-square subjects). +- **Color presence**: brand grounds and accents should read at real video saturation (including bold bright or light surfaces with tactile contrast, not only dark washes). +- **Coupled adjustments**: short hold → cut copy; awkward real-copy wrap → rebalance framing/scale; visual noise → delete competing elements first rather than blurring or dimming. + +--- + +## 6. Focused Revision Verbs (On Demand) + +When responding to user direction or a frame review, state findings as `t · clip · issue → exact fix · what stays` (never numeric scores like `8.5/10`), and protect the piece's strongest beat: + +- **`critique`**: diagnose clarity, timing, seam, and hierarchy issues without mutating; name the strongest beat to preserve. +- **`distill`**: subtract redundant labels, framing chrome, or secondary motion while keeping one vivid focal accent intact. +- **`clarify`**: cut copy to headline + concrete fact and verify paused reading order. +- **`bolder`**: calm or tighten the beat immediately before the hero moment, then commit to one decisive scale, color, or framing move. +- **`retime`**: adjust clip spans, overlaps, and settled holds before touching easing curves. +- **`polish`**: refine optical alignment, stagger cadence, and cut seams without altering composition structure. + +--- + +## 7. Motion-Aware Frame Review Modes (`inspect_frames`) + +Use the right inspection mode for the question you are verifying (the turn reuses one warm browser session): + +- **`overview`** (default 2D contact sheet, 3–4 beats): verify overall framing, intermediate silhouettes, safe zones, and visual hierarchy. Add `mobilePreview: true` when verifying dense copy or vertical `9:16` framing alongside a beat check. +- **`range`** (6–8 frame motion burst over `[start, end]`): verify continuous movement, velocity curves, and ``/`Three.js` animation. Inspect `motionSummary` for `isStaticAcrossRange`, `stutterWarnings`, reversals, and `flashSpikes`. +- **`seam`** (`±0.2s` pre/post cut strip split by an amber cut divider at `seamAt`): verify beat handoffs and cut cleanliness. Inspect `seamReport` for `seamJump`, `blankFlashDetected`, `doubleExposureClips`, and abrupt opacity pops. +- **`mobile`** (true 360px phone-width sheet): verify arm's-length phone legibility without cropping. Inspect `legibility` against the `≥2.6%` short-side floor (`28px` at `1080p`), `textOverflowCount`, `safeZoneBleedCount`, and persistent `textOverlapPairs` (single-frame motion crossings are demoted to `transientOverlaps`). +- **Triage P0 → P1, verify once**: prioritize **P0** (runtime error, unreadable text, cropped/occluded hero, jarring cut) and high-impact **P1** (static stretch, rough seam) over minor polish; batch fixes in one edit pass and re-inspect only what changed (a second pass only if a P0 remains). +- **Anti-loop discipline**: if `persistedFindings` flags a defect that survived your previous edit, switch strategy (layout structure, clip bounds, or timing architecture) instead of repeating small numeric tweaks. diff --git a/packages/agent/motion-skills/motion-director/references/visual-recipes.md b/packages/agent/motion-skills/motion-director/references/visual-recipes.md new file mode 100644 index 000000000..be5709d65 --- /dev/null +++ b/packages/agent/motion-skills/motion-director/references/visual-recipes.md @@ -0,0 +1,143 @@ +# Domain Grounding & Seek-Safe Timing Fragments + +Companion reference to `motion-director/SKILL.md` pairing domain truth for the four common video types with minimal, seek-safe `ctx.clipT` timing fragments. Keep every edit orthogonal (`data-clip-id`, animate CSS `transform` or inner descendants, never clobber root `style.translate/scale/rotate`). + +--- + +## 1. Domain Grounding by Subject + +### A. Brand Identity, Launch & Visual Showcase +- **Honor real brand assets & color presence**: preserve the real mark geometry, proportions, and signature hues at full video saturation (when a brand owns a vivid blue, red, emerald, or crisp white, let it flood the full stage cleanly). +- **Proportional vector & asset fidelity**: match any inline `` and container ratio (`width: ; height: auto;`) to the subject's natural `W:H` ratio rather than defaulting to a square box, preserve exterior and interior geometry cleanly, and set total `duration` to fit all planned beats rather than cramming. +- **Distinct visual worlds across beats**: contrast lighting, ground color, and framing across chapters (e.g., concise opening reveal → bold color or material world → real-world product/context showcase → settled closing lockup held `≥1.5s`) tailored to the brief. +- **Terse visual-first copy**: keep chapter tags to `2–6` words and let the mark and materials speak without explanatory paragraphs or persistent slide chrome. + +### B. Data Stories, Benchmarks & Business Reviews +- **One focal metric per beat**: give the core number monumental presence (`tabular-nums`, `88–180px`) and hold it completely still for `≥1.0s` after arrival. +- **Charts in reading order**: reveal baseline/axis → reference target → progressive trace via `ctx.clipT` → one direct callout pinned onto the key point (no disconnected legends). Carry a bar or line across the seam into the next beat's geometry. +- **Non-negotiable accuracy**: proportions match actual values; units, time scope, and illustrative-data notices stay visible; never animate cumulative `0→N` counters for non-cumulative ratios; keep semantic status colors consistent. + +### C. Explainers, Mechanisms, Stories & Tactile Worlds +- **One concrete subject end to end**: walk one real example, artifact, or character through one complete causal loop rather than listing disconnected points. +- **Grow one visual progressively**: start from the simplest true form and reveal each new part as its step arrives, with short labels pinned directly to the parts they name. +- **Tactile craft cadence**: use two-clock timing for pixel or illustrated worlds (`Math.floor(localT * 10) / 10` for character/pose steps over smooth camera & captions), rest-space textures anchored in local coordinates, bundled `Fusion Pixel` on pixelated low-res canvases, or `ctx.THREE` (`preserveDrawingBuffer: true`) for real 3D object or stage depth. + +### D. Documentary, Footage & Photo Packaging +- **Footage owns the frame**: mount `` full-bleed inside an unlocked `data-track="video"` clip (`z-index: 1`, never `data-locked="true"`). Size each video clip span (`data-end - data-start`) within the connected clip's actual `durationSeconds` unless looping is intended (videos wrap modulo source duration). +- **Audio boundary**: the director sees connected audio titles only (no built-in music/TTS/beat-analysis tool); connected audio and eligible video sound are mixed automatically during export. Never claim exact beat-sync or authored SFX unless audio timestamps were explicitly provided. +- **Localized legibility**: place a subtle gradient scrim strictly behind text margins; anchor crisp titles and lower-thirds in negative space and exit cleanly before shot cuts. + +### E. Source-Faithful Reference Asset Routing +When the user uploads a reference file or connects an image node, check its probed `sourceKind`, `graphicType`, `sharpness`, `hasAlpha`, `removeBackgroundRecommended`, `palette`, and `recommendedChannels` first — and execute independent calls in parallel in one turn. **Never redraw, guess, or trace a raster brand logo/mark into approximate SVG wireframes**: +- **Native `.svg` Source (`prepare_reference_asset(mode="svg")`)**: when a real `.svg` source file is attached (`sourceKind=vector_svg`), retrieve its exact lossless sanitized `` markup and `viewBox` — ideal for precision `stroke-dashoffset` contour drawing, path disassembly, and brand color floods with zero geometric distortion. +- **Raster Image Mounting (`prepare_reference_asset(mode="mount")`)**: persists PNG/JPG/WebP assets losslessly (preserving original pixels & true RGBA alpha) as a local URL for `` placement. When an opaque flat logo sits on a uniform solid background (`removeBackgroundRecommended=true`) and will composite onto a contrasting stage, pass `removeBackground: true` for fringe-free transparent alpha. Leave the mark's real pixels intact and create refined motion via framing, 3D perspective, `clip-path`/mask wipe reveals, specular light sweeps, procedural vector rulers/grids/reticles around the mark, and exact extracted HEX color fields. +- **Reference-Conditioned Mockups (`generate_image(..., useReferenceImage=true)`)**: when image generation is configured and the brief calls for realistic physical mockups, packaging, signage, apparel, or styled scenes featuring the uploaded mark/subject, generate them in parallel with `useReferenceImage: true` instead of hand-coding crude CSS approximations. +- **Blurry or atmospheric uploads (`soft_or_blurry`)**: mount as a heavily blurred ambient backdrop (`mode="mount"`) or condition `generate_image(useReferenceImage=true)`. + +--- + +## 2. Minimal Seek-Safe Timing Fragments (`ctx.clipT`) + +All `script` snippets below are **bare top-level statements** (never wrap in `ctx => ...`). Query matching clips by class/role and read `ctx.clipT(el.dataset.clipId)` so dragging, trimming, or **splitting** clips on the timeline keeps internal choreography locked across every split piece. Always place titles/captions in separate leaf `data-track="text" data-editable="text"` clips. + +### Fragment 1: Mounted Raster Logo Reveal (`Guides → Mask Wipe + Specular Sweep`, Split-Safe) +Keep raster logo pixels 100% untouched via ``, animate procedural crisp guides + `clip-path` wipe + light sweep, and place the caption in its own leaf `data-track="text"` clip: + +```js +ctx.root.querySelectorAll('[data-clip-id][data-role="logo-reveal"]').forEach((el) => { + const lt = ctx.clipT(el.dataset.clipId); + const win = (a, b) => ctx.clamp((lt - a) / Math.max(0.001, b - a), 0, 1); + // 1. Procedural crisp vector guides draw in first (0.00–0.65s) + const guide = el.querySelector(".lr-guide"); + if (guide) { + const gp = ctx.easeOut(win(0.0, 0.65)); + guide.style.opacity = (gp * (1 - 0.55 * win(1.05, 1.45))).toFixed(3); + guide.style.transform = `scale(${(0.94 + 0.06 * gp).toFixed(4)})`; + } + // 2. Original lossless wipes in with 40% overlap (0.35–1.05s) + specular highlight sweep + const mark = el.querySelector(".lr-mark"); + if (mark) { + const mp = ctx.ease(win(0.35, 1.05)); + mark.style.clipPath = `inset(0 ${((1 - mp) * 100).toFixed(2)}% 0 0)`; + mark.style.transform = `scale(${(1.04 - 0.04 * mp).toFixed(4)})`; + } + const sheen = el.querySelector(".lr-sheen"); + if (sheen) { + const sp = ctx.ease(win(0.75, 1.35)); + sheen.style.opacity = (Math.sin(sp * Math.PI) * 0.65).toFixed(3); + sheen.style.transform = `translate3d(${((sp - 0.5) * 220).toFixed(1)}%, 0, 0) skewX(-18deg)`; + } +}); +``` + +### Fragment 2: Native `.svg` Stroke → Fill Reveal (True SVG Uploads Only) +Use when `prepare_reference_asset(mode="svg")` returned real lossless vector paths (with captions in a separate leaf `data-track="text"` clip): + +```js +ctx.root.querySelectorAll('[data-clip-id][data-role="svg-reveal"]').forEach((el) => { + const lt = ctx.clipT(el.dataset.clipId); + const win = (a, b) => ctx.clamp((lt - a) / Math.max(0.001, b - a), 0, 1); + el.querySelectorAll(".sr-stroke").forEach((path, i) => { + if (path._len == null) path._len = path.getTotalLength ? path.getTotalLength() : 100; + const p = ctx.easeOut(win(i * 0.14, 0.72 + i * 0.16)); + path.style.strokeDasharray = `${path._len} ${path._len}`; + path.style.strokeDashoffset = (path._len * (1 - p)).toFixed(2); + }); + const fill = el.querySelector(".sr-fill"); + if (fill) { + const fp = ctx.ease(win(0.55, 1.15)); + fill.style.clipPath = `inset(0 ${((1 - fp) * 100).toFixed(2)}% 0 0)`; + } +}); +``` + +### Fragment 2: Object-to-Ground Color Flood / Split-Wipe Handoff +Carry a color plane or divider cleanly across one registered frame using `ctx.clipT`: + +```js +const frame = ctx.clip("compare-frame"); +if (frame) { + const lt = ctx.clipT("compare-frame"); + const after = frame.querySelector(".cf-after"); + const rule = frame.querySelector(".cf-rule"); + const u = ctx.ease(ctx.clamp((lt - 0.85) / 0.85, 0, 1)); + if (after) after.style.clipPath = `inset(0 ${((1 - u) * 100).toFixed(2)}% 0 0)`; + if (rule) rule.style.transform = `translate3d(${(u * frame.clientWidth).toFixed(1)}px, 0, 0)`; +} +``` + +### Fragment 3: Proportional Data Trace with Direct Peak Callout +Reveal the trace linearly/cleanly with `ctx.clipT`, then reveal the pinned callout only as the trace reaches the peak: + +```js +const plot = ctx.clip("data-plot"); +if (plot) { + const lt = ctx.clipT("data-plot"); + const trace = plot.querySelector("#dp-trace"); + const peak = plot.querySelector("#dp-peak"); + const drawU = ctx.easeOut(ctx.clamp((lt - 0.2) / 1.35, 0, 1)); + if (trace) trace.style.strokeDashoffset = ((1 - drawU) * 100).toFixed(2); + if (peak) { + const popU = ctx.easeOut(ctx.clamp((lt - 1.35) / 0.35, 0, 1)); + peak.style.opacity = popU.toFixed(3); + peak.style.transform = `translate3d(0, ${((1 - popU) * 12).toFixed(1)}px, 0)`; + } +} +``` + +### Fragment 4: Full-Bleed Footage with Localized Edge Scrim +```html +
+ +
+
+

Direct from the studio floor

+``` +```css +.vid-bg { position: absolute; inset: 0; z-index: 1; } +.vid-bg video { width: 100%; height: 100%; object-fit: cover; display: block; } +.vid-scrim { position: absolute; inset: 0; z-index: 5; pointer-events: none; + background: linear-gradient(180deg, transparent 58%, rgba(10, 12, 16, 0.72) 100%); } +.vid-label { position: absolute; left: 96px; bottom: 84px; margin: 0; z-index: 20; + padding-left: 20px; border-left: 4px solid var(--accent); font-size: 40px; font-weight: 700; color: #FFFFFF; } +``` diff --git a/packages/agent/motion-skills/motion-director/references/web-motion-cookbook.md b/packages/agent/motion-skills/motion-director/references/web-motion-cookbook.md new file mode 100644 index 000000000..2b601a540 --- /dev/null +++ b/packages/agent/motion-skills/motion-director/references/web-motion-cookbook.md @@ -0,0 +1,160 @@ +# Declarative Web Motion Engine Mechanics Cookbook + +Pure engine reference matching OpenDirector's actual single-source runtime (`motion-runtime-core.js` + `motion-runtime-base.css`), shared identically by live Studio preview, `inspect_frames`, and Headless Chrome + FFmpeg MP4 export. + +--- + +## 1. Stage & `data-*` Clip Contract + +The logical root is `#stage` (`baseWidth × baseHeight`, matching the project aspect — e.g. `1920×1080`, `1080×1920`, or `1080×1080`). Place all clips directly inside `#stage` (never wrap in another `
`). + +```html +

Built for real editing

+``` + +- `data-clip-id` (**required, unique**): binds selection, drag/resize/rotate, Inspector controls, timeline clips, and `overrides[id]`. +- **Tight-bounded foreground boxes (never full-stage scene bundles)**: give every editable foreground visual its own tightly sized `[data-clip-id]` box, put headlines/captions in separate leaf `data-track="text" data-editable="text"` clips, and keep full-bleed grounds/scrims `data-locked="true"`. **Never write `[data-clip-id] { inset: 0 }` or bundle background + graphics + copy into one `1920×1080` clip** — full-stage unlocked wrappers absorb pointer hits, break marquee selection and dragging, and prevent direct text editing. +- `data-track`: `"text"` | `"motion"` | `"video"`. +- `data-editable="text"`: attach ONLY to plain text leaf elements (no nested SVG/child elements) so users can double-click to edit inline on stage without breaking `word-pop` / `typewriter`. +- **Half-open visibility `[start, end)` (final frame inclusive)**: clips with `data-end` stay visible while `start <= t < end` (and inclusive at the final composition frame `t == duration`), so exact back-to-back cuts (`end="3.0"` → `start="3.0"`) never double-expose on frame `3.0`. Omit `data-end` to stay until composition duration. +- **Implicit entrance/exit defaults (critical for hard cuts!)**: omitting `data-enter` defaults to `fade` (`0.65s`), and setting an explicit `data-end` without `data-exit` **automatically defaults to `fade` (`0.45s`)**! Always write `data-exit="none"` on any clip that should hold crisp until a hard cut, and `data-enter="none"` when custom script/mask choreography drives arrival. +- **Built-in effects**: + - `data-enter` (15): `none`, `fade`, `slide-up`, `slide-down`, `slide-left`, `slide-right`, `scale`, `zoom-in`, `pop`, `typewriter`, `wipe-up`, `wipe-left`, `blur-in`, `word-pop`, `flip-3d`. + - `data-exit` (9): `none`, `fade`, `slide-up`, `slide-down`, `slide-left`, `slide-right`, `scale`, `wipe`, `blur-out`. + - `data-loop` (6): `none`, `float`, `pulse`, `breathe`, `sway`, `shimmer`. +- `data-locked="true"`: reserve strictly for pure ambient backdrops or edge legibility scrims — **never lock `data-track="video"` or editable foreground clips**. + +### Connected Media Slots +- Video: `
` +- Image: `
...
` +- The runtime binds sources, seeks videos frame-accurately honoring `mediaStartOffset` (wrapping modulo video duration if clip exceeds source length), and applies `data-fit` (`cover` / `contain`). Stage `