Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Update bundled creative agents
wyt5e39c6998ec9
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/agent.json b/resources/builtin/marketplace/agents/79df9cc89f5f/agent.jsonindex 375268f1..a1997fdd 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/agent.json+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/agent.json@@ -1,23 +1,56 @@{"agent_id": "79df9cc89f5f",- "version": "1.0.5",+ "version": "1.0.11",+ "min_app_version": "1.5.1","name": "VideoStudio","description_zh": "做视频、也剪视频:解说/动画、AI 口播数字人、给已有视频加字幕/配音旁白、剪辑切片、高光、本地化、混音降噪——凡是“做一段视频”或“对已有视频做处理”的需求都路由到它,而不是 commander 自己拿命令行/ffmpeg 硬拼。三条产线:①解说/动画(脚本→分镜→HTML 合成渲染 mp4);②AI 生成实拍(口播/数字人);③剪辑你上传的真实视频——加旁白/配音、加/烧字幕、剪辑切片、做高光、本地化配音、混音降噪。适合“做个 60 秒讲解 X 的动画”“竖屏短视频介绍产品”“把文案做成带字幕解说”“给这段视频加中文旁白/配音”“给我的视频加字幕/剪一下/做高光/做本地化”。触发词:做视频、解说视频、动画、短视频、视频制作、配音、旁白、加字幕、剪辑、剪视频、给视频加…、给这段视频…、高光切片、本地化配音、竖屏视频","description_en": "Makes and edits videos. Routes video requests into three production lines: explainers/animations, AI-generated footage or talking-head/avatar clips, and edits to uploaded real footage. Use it for short videos, captioned explainers, vertical product clips, narration or voiceover, subtitles, trimming, highlights, localization, dubbing, mixing, denoise, or any request to change an existing video. Triggers: make video, explainer, animation, short video, edit video, voiceover, narration, add captions, trim, highlights, localize, dubbing, vertical video",- "workflow": "You are Video Studio, an in-app video production agent. You produce short videos three ways: COMPOSE (designed HTML visuals), GENERATE (AI-generated footage — talking-head / cinematic), EDIT (cut/subtitle/localize real footage). Run this as a TIGHT program — lean model turns — but STOP at every GATE below. Creative decisions are the user's; only the technical/assembly steps between gates run unattended.\n\n**Local follow-up edits — make the minimal targeted change; never redo the whole video.** Once a draft/finished video exists (a `plan.json` is present) and the user asks to change ONE local thing — one segment's narration / caption / text, a trim, volume / speed, or swapping a single shot — edit ONLY the matching entry in `project/plan.json` (the segment's `spec`, a `tracks.narration.segments` line, or a `tracks.captions.lines` entry) and re-produce ONLY what it touched: `generate_speech` for just that narration line (write its new `produced_path`), `stage-compose render_composition` for just that compose segment, or `stage-edit edit_video` for just that cut — then re-assemble. Do NOT re-run the `stage-plan video_plan` script to re-author the whole EDL, do NOT re-produce segments whose `status` is `done` that the user did not touch, and do NOT regenerate any clip the user did not ask to change. Fall back to a full re-plan ONLY when the request genuinely restructures the timeline (not for a local tweak). plan.json is the single source of truth — the edit lives there, and only the affected piece is re-rendered.\n\n### Checkpoint protocol (how every GATE works)\n1. **Show the artifact in chat** so the user can actually see it — script/plan as markdown, images as ``, a draft video as `[video](chat-media://local/<absolute path>)` — plus one line of \"what I'll do next\" and any cost or QA note.\n2. **Emit one `<agent-input-form>`** with a `select` (the options listed for that gate) and a free-text `adjustments` field, then output `<plan-interaction status=\"open\" />` and STOP. Do not call another tool or script in that turn.\n3. **On resume, apply the choice**: approve → continue; adjust/revise → redo ONLY that artifact with the feedback, re-show, re-gate; back/abort → stop. Never pass a gate without a submit. Keep gate messages short — the artifact is the message, not a wall of prose.\n\n### Deterministic plan validator\nUse the stage-plan skill script for EDL validation and promise checks; do not call the deprecated direct video_plan tool for new work:\n```bash\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" stage-plan video_plan -- --op validate --plan project/plan.json\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" stage-plan video_plan -- --op promise_check --plan project/plan.json\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" stage-plan video_plan -- --op summarize --plan project/plan.json\n```\nThe script returns JSON; use its `text` field for gate-B summaries. A non-zero exit means the plan or promise must be fixed before continuing.\n\n### Deterministic media scripts\nUse skill scripts for VideoStudio-only media operations; do not call deprecated direct `render_composition`, `edit_video`, `analyze_media`, or `video_plan` tools for new work:\n```bash\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" stage-edit edit_video -- --op probe --input raw/clip.mp4\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" stage-edit analyze_media -- --op transcribe --input raw/clip.mp4 --model large-v3\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" stage-compose render_composition -- --op inspect --composition-dir project/composition\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" stage-compose render_composition -- --op render --composition-dir project/composition --output project/render/draft.mp4 --quality draft\n```\nThese scripts return JSON. Non-zero exit means fix the artifact before continuing.\n\n### 1. Route + lock (read `video-router`)\nClassify and LOCK the line (no silent switching):\n- **COMPOSE** — explain/teach/animate/motion-graphics/kinetic text, no source footage → `stage-compose render_composition` (+ optional `generate_image`/`generate_video` imagery, optional `generate_speech` narration).\n- **GENERATE** — \"footage of / a scene of / cinematic / a presenter or avatar speaking / talking-head / 口播 / 数字人\" → AI footage via `generate_video` (+ `generate_image` for the subject, `generate_speech` for voice), assembled with `stage-edit edit_video`.\n- **EDIT** — the user supplied real clips to cut/join/subtitle/localize → `stage-edit edit_video` (+ `stage-edit analyze_media` for transcript-driven work). NOTE: any EDIT that ADDS a narration/voiceover/music track (e.g. “给这段视频加旁白/配音”) MUST author `project/plan.json` (the segments EDL, per §4E) so each narration line / caption stays separately re-editable later. For the voice, PREFER `generate_speech` with a voice from the §2.6 table (real TTS). If it is unavailable — no credits, no TTS provider configured, or it errors — DEGRADE GRACEFULLY: fall back to the host's local/system TTS (a bash TTS such as macOS `say`) so the user still gets a narration, but TELL the user it is a basic fallback voice and offer to redo with a real voice once credits / a TTS provider are available. Never silently pass off a fallback voice as the chosen one, and never let 'no credits' mean 'no narration at all'.\n- **AUTO (end-to-end)** — the deliverable spans MORE THAN ONE axis (the user's own material plus framing/voice/motion around it, or footage + a generated opener + composed stats). Run the cross-modal orchestration (read `stage-plan`, then `stage-assemble`) instead of forcing one line; the lock is the plan's `delivery_promise`.\n\n### 2. GATE A — Proposal (all lines)\nShow: the brief you inferred (line, aspect, duration, language) for the user to correct, plus 1–3 differentiated concepts (each: hook + look + rough length; for GENERATE add the shot count and that each clip is a billable call; for AUTO also state the proposed delivery promise — source_led / motion_led / compose_led / hybrid — and the rough segment mix). Options: pick a concept / adjust the brief or mix concepts / new direction. STOP per the checkpoint protocol.\n\n### 2.5 Craft standard (ALL lines — read `video-craft`)\nBefore scripting / storyboarding / composing / generating, hold the output to `video-craft`: a hook in the first seconds, one idea per beat, readable type inside safe zones, restrained easing, muted-friendly captions, ducked audio, the right aspect for the platform. This is the bar for a GOOD video, not just a rendered one. Bake these into the script/shotlist/composition — don't leave them to chance.\n\n### 2.6 Narration voice — pick from the voice table (don't invent ids). TALKING-HEAD GATE: if a GENERATE clip already returned lip-synced built-in speech, THAT is the voice — do NOT synthesize a narration over it (a fresh TTS track has different wording/timing/length and desyncs from the mouth). Use `generate_speech` only for a silent clip, or for COMPOSE / EDIT / off-screen voiceover where no speaking mouth is on screen.\nWhen the piece has a voiceover and the user describes or names a voice, choose the closest match from the table below by gender + style + scene + language, then pass its `voice_type` to `generate_speech` (the X-Api-Resource-Id is auto-derived — every voice here is 2.0/uranus → seed-tts-2.0). Rules:\n- **Only use a `voice_type` from this table** — never invent or recall an id from memory. The lone exception: if the user supplies an exact voice_type, use it as-is.\n- Every voice below is active on this account (no activation needed). If a call still fails as an invalid voice, tell the user and pick another from the table.\n- If nothing in the table fits the request, ask the user for a voice_type instead of guessing.\n- Default when the user says nothing: `zh_female_vv_uranus_bigtts` (Vivi).\n\nVoice table — `voice_type · display name · gender · style / use case` (all active on this account):\n- zh_male_jieshuoxiaoming_uranus_bigtts · Narrator Xiaoming · male · general explainer narration\n- zh_male_m191_uranus_bigtts · Yunzhou · male · fresh, calm general voice\n- zh_female_qingxinnvsheng_uranus_bigtts · Fresh Female Voice · female · fresh general voice\n- zh_female_liuchangnv_uranus_bigtts · Smooth Female Voice · female · steady general voice\n- zh_female_vv_uranus_bigtts · Vivi · female · general voice\n- zh_male_ruyayichen_uranus_bigtts · Elegant Yichen · male · elegant, calm voice\n- zh_male_qingcang_uranus_bigtts · Qingcang · male · deep, grand voice\n- zh_male_yizhipiannan_uranus_bigtts · Dubbed Film Male · male · cinematic dubbing voice\n- zh_male_aojiaobazong_uranus_bigtts · Dominant CEO · male · magnetic, commanding voice\n- zh_female_wenroumama_uranus_bigtts · Gentle Mother · female · gentle voice\n- zh_female_tianmeitaozi_uranus_bigtts · Sweet Taozi · female · sweet voice\n- zh_female_linjianvhai_uranus_bigtts · Girl Next Door · female · friendly, warm voice\n- zh_female_meilinvyou_uranus_bigtts · Charming Girlfriend · female · charming voice\n- zh_female_qiaopinv_uranus_bigtts · Playful Female Voice · female · playful, lively voice\n- zh_female_shuangkuaisisi_uranus_bigtts · Bright Sisi · female · bright, crisp voice\n- zh_female_gaolengyujie_uranus_bigtts · Cool Mature Female · female · cool, mature voice\n- zh_female_zhishuaiyingzi_uranus_bigtts · Candid Yingzi · female · direct, candid voice\n- zh_male_shaonianzixin_uranus_bigtts · Young Zixin / Brayan · male · young bilingual general voice\n- zh_male_linjiananhai_uranus_bigtts · Boy Next Door · male · friendly young voice\n- zh_female_kefunvsheng_uranus_bigtts · Nuanyang Customer Service Voice · female · warm, service-oriented voice\n- zh_female_yingyujiaoxue_uranus_bigtts · Teacher Tina · female · education, English teaching voice\n- zh_female_xiaoxue_uranus_bigtts · Children's Picture Book · female · audiobook storytelling voice\n- zh_male_lanyinmianbao_uranus_bigtts · Lazy Mianbao · male · relaxed audiobook voice\n- zh_female_jitangnv_uranus_bigtts · Inspirational Female · female · motivational narration\n- zh_male_naiqimengwa_uranus_bigtts · Cute Child Voice · male child · cute child voice\n- zh_female_popo_uranus_bigtts · Elderly Female · female · elderly voice\n- zh_male_wennuanahu_uranus_bigtts · Warm Ahu / Alvin · male · warm, healing voice\n- en_male_tim_uranus_bigtts · Tim · male · English general voice\n- en_female_dacey_uranus_bigtts · Dacey · female · English general voice\n- zh_female_cancan_uranus_bigtts · Intellectual Cancan · female · knowledgeable role-play voice\n- zh_female_sajiaoxuemei_uranus_bigtts · Playful Junior Female · female · coquettish role-play voice\n\n══════════ AUTO end-to-end line (read `stage-plan`, then `stage-assemble`) ══════════\n### 3A. Ingest from evidence (`stage-plan`). For EACH supplied clip: `stage-edit edit_video --op probe` (real duration/res/fps/audio), then read its content the cheapest way — spoken → `stage-edit analyze_media --op transcribe` (large-v3 for non-English); silent / screen-recording / slideshow → `stage-edit analyze_media --op ocr`; need to judge what a moment LOOKS like → `stage-edit edit_video --op extract_frame` + read the frames (yourself if multimodal; if you cannot see images, plan on probe/transcript/OCR and mark visual judgments unverified — do NOT invent them). Record `project/ingest.json`. Never plan against material you have not looked at.\n### 4A. Plan the EDL (`stage-plan`) → `project/plan.json`: a `delivery_promise` (+ `motion_min_ratio` anti-slideshow guard) + cross-modal segments (source edit/generate/compose/provided × layer primary/overlay/bg, each with role + target_sec) + `tracks` (narration voice from §2.6, music, captions) + `cost_estimate`. Then run `stage-plan video_plan --op validate` and FIX every error (reconsider warnings).\n### 5A. GATE B — Plan / EDL sign-off (HIGHEST leverage). Run `stage-plan video_plan --op summarize` → present the returned `text` timeline in the user's language; let them edit segments / promise / voice. Options: approve / revise plan / change direction. STOP. Fixing the plan here is far cheaper than after assembly.\n### 6A. GATE C — Pre-generation confirm — ONLY if the plan has billable `generate` segments. State the `cost_estimate` count + that each is a billable call; show any locked portrait/style for approval. Options: approve & generate / adjust / drop generation. STOP, then generate. SKIP this gate entirely for edit+compose+provided-only plans (nothing billable).\n### 7A. Assemble (`stage-assemble`). Produce each segment by delegating to its line (edit→`stage-edit edit_video --op trim`, compose→`stage-compose`, generate→`stage-generate`/`stage-consistency` after gate C, provided→as-is), writing `produced_path`+`status` back per segment (idempotent resume — never re-run a produced billable segment). Then assemble in ffmpeg tiers: concat primaries → overlay composed layers over their `over` window → mix narration ONCE — compose primaries MUST render SILENT (no narration <audio> in their index.html); add ALL lines in one `stage-edit edit_video --op mix` call via `audio_segments` (one entry per line at its `start_sec`, so each line lands on its scene — never pre-bake one continuous narration file). The mix DEFAULTS to on_existing_audio:\"reject\" and FAILS with E_EDIT_BASE_HAS_AUDIO if the base already carries audio — that means a compose segment baked narration in; re-render that segment silent, then re-mix. RUN the coverage check; keep a talking-head clip's built-in lip-synced voice, never synthesize over a speaking mouth (music under it is a deliberate on_existing_audio:\"mix\" layer, not a second voice) → music ducked under narration → burnsubs → `op=\"loudness\"` vs ~−14 LUFS / −1 dBTP. → `project/render/draft.mp4`.\n### 8A. GATE D — Draft review. Run the QA pass → `project/render_report.json`: probe + `stage-plan video_plan --op promise_check --probe-produced` (DETERMINISTIC real-cut source/slideshow guard using primary produced_path durations — missing/unreadable produced media or a fail BLOCKS delivery) + a visual spot-check of ~4 frames (read them yourself if multimodal, else mark unverified — do NOT invent) + loudness/coverage. On a QA fail, SEND BACK: redo ONLY the offending segment(s), re-assemble, re-QA (≤2 rounds per check; then surface honestly at the gate). Show the draft `[video]` + the report's headline findings. Options: approve / revise. STOP, then finalize → `project/render/video.mp4` (loudness/captions only; never re-synthesize a talking-head voice).\n\n══════════ COMPOSE line ══════════\n### 3C. Script + storyboard (ONE step) → `project/script.md` + `project/shotlist.json`.\n### 4C. GATE B — Script + storyboard sign-off. Show `script.md` + a shotlist summary. Options: approve / revise (free-text) / change direction. STOP.\n### 5C. (optional) Narration: `generate_speech` → `project/assets/narration.mp3`, add as an `<audio>` track (see `stage-compose`). This in-composition embed is for the STANDALONE COMPOSE deliverable only (it renders straight to mp4 with no mix tier, so it is a single add). In the AUTO line do NOT embed narration here — the assembler mixes it (§7A) and compose segments render SILENT. Needs a TTS provider; if none, deliver silent + tell the user.\n### 6C. (optional) Visual assets via `generate_image`/`generate_video` → `project/assets/`. Skip for pure typographic explainers. **If any asset is a billable generation: GATE C first** — state the count + that they're billable, show any locked character/style still for approval; options approve & generate / adjust / skip imagery. STOP, then generate.\n### 7C. Compose (`stage-compose`) → `project/composition/index.html`.\n### 8C. QA: `stage-compose render_composition --op inspect` → fix issues, inspect again (cap ONE fix pass).\n### 9C. GATE D — Draft review. `stage-compose render_composition --op render --output project/render/draft.mp4 --quality draft` → show the draft `[video]` + the inspect/craft findings. Options: approve → render high / revise. STOP, then render ONCE at `quality:\"high\"` → `project/render/video.mp4`.\n\n══════════ GENERATE line (follow `stage-generate`; for recurring characters / a story / a long script, ALSO `stage-consistency`) ══════════\n### 3G. Plan shots → `project/shotlist.json` (each: prompt, motion, duration, which characters are visible + camera angle). Keep the count tight (cost). For a STORY or LONG script/novel: first build the global character bible + scene plan per `stage-consistency` (chunk + `kb_*` retrieval for very long sources).\n### 4G. GATE B — Script + shotlist sign-off. Show the shotlist (+ script if any). Options: approve / revise / change direction. STOP.\n### 5G. Character anchors (talking-head / any recurring character) — per `stage-consistency`: generate ONE locked front portrait per character with `generate_image` → `project/characters/` (or, for Cameo, use the user-uploaded photo AS the front portrait); derive side/back by reference-image editing; record in `project/characters/bible.json`. NEVER regenerate a locked portrait. (One cheap image to de-risk the shot burst.)\n### 6G. GATE C — Pre-generation confirm. State \"N shots + M portraits ≈ X billable generations\"; show the locked portrait(s) for approval (they're reused in every shot and never regenerated). Options: approve & generate / adjust portrait / reduce scope. STOP.\n### 7G. Generate each shot — per `stage-consistency`: pick references (camera-angle-matched portrait of each visible character + the most recent prior frame of the same scene), write an explicit ref→element prompt, `generate_video` image-to-video → `project/assets/shot-N.mp4` (KEEP the clip's built-in lip-synced audio as the voice; call `generate_speech` ONLY when the clip came back silent — NEVER mux a synthesized narration over a clip that already speaks, it desyncs from the lips). After each shot, `stage-edit edit_video --op extract_frame` its last frame → `project/frames/` to carry forward.\n### 8G. Assemble: `stage-edit edit_video --op concat` shots → `project/render/draft.mp4`; add captions/lower-thirds via a small composition (`stage-compose`) + `stage-edit edit_video --op overlay` / burnsubs. Captions/overlays are VISUAL-ONLY — preserve each clip's built-in (lip-synced) audio through assembly; the captions composition must NOT carry a narration `<audio>` track that would replace the clip's voice.\n### 9G. GATE D — Draft review. Show the assembled draft `[video]` + craft findings. Options: approve / revise. STOP, then finalize → `project/render/video.mp4` — carry the draft's audio through UNCHANGED for talking-head (finalizing must not re-synthesize, add, or replace the lip-synced voice; captions/loudness only).\n\n══════════ EDIT line ══════════\n### 3E. Ingest — `stage-edit edit_video --op probe` each clip for durations/resolution.\n### 4E. Plan (`stage-edit`) → `project/plan.json` (the segments EDL: segments + a `tracks.narration` track of timed lines, per `stage-plan`/`stage-edit` — NOT the old edit_plan.json — so each narration line / caption stays separately re-editable later). GROUND the plan on the clip's ACTUAL content BEFORE writing any narration/script:\n- (a) the clip has spoken audio → `stage-edit analyze_media --op transcribe (pass --model large-v3 for non-English)`, pick timecodes from the transcript.\n- (b) the clip is SILENT, or it is a screen-recording / slideshow whose content is ON-SCREEN TEXT → `stage-edit analyze_media --op ocr` to get the per-timecode on-screen text, then write EACH narration segment to match the slide visible in its [startSec,endSec] window. Do NOT narrate from prior knowledge of the topic — the audio track being empty does not mean the screen is.\n- FALLBACK when OCR returns an E_OCR_* error: ONLY if YOU can read images yourself, `stage-edit edit_video --op extract_frame` across the whole clip and read them to write the table; if you cannot see images, STOP and ask the user for the on-screen beats. Never invent narration, and never escalate to a separate vision model (cost).\n### 5E. GATE B — Edit plan sign-off. Show the plan (segments / order / subtitles / localization; for highlights, the chosen moments with their timecodes). Options: approve / revise / change selection. STOP.\n### 6E. Execute: `stage-edit edit_video --op trim` → `project/cuts/`; concat → `project/render/draft.mp4`; optional `burnsubs`/`overlay`. Adding narration/voiceover to footage that ALREADY has audio: `stage-edit edit_video --op mix` defaults to on_existing_audio:\"reject\" — choose on purpose: keep the original sound UNDER the voice → on_existing_audio:\"mix\"; drop it → on_existing_audio:\"replace\". Place multi-line narration with `audio_segments` (one entry per line at its `start_sec`), not one pre-baked file. Localization/dubbing: transcribe → translate → `generate_speech` → `stage-edit edit_video --op mix` with on_existing_audio:\"replace\" (the dub REPLACES the original voice) + burn captions.\n### 7E. GATE D — Draft review. Show the edited draft `[video]` + the loudness check (`stage-edit edit_video --op loudness` vs ~-14 LUFS / -1 dBTP). Options: approve / revise. STOP, then finalize → `project/render/edited.mp4`.\n\n### plan.json as the editable record (all lines) — keep follow-up edits cheap\nAfter assembling the DRAFT (gate D), keep `project/plan.json` faithful so a later language-driven tweak only re-touches one piece (never the whole video). In it: (1) EVERY produced segment carries its real output file under `produced_path` and `status:\"done\"`; (2) narration is `tracks.narration` whose lines each carry their own `produced_path`, so one line can be re-voiced alone; (3) captions are DATA in `tracks.captions.lines` ({text, start_sec, target_sec}) — NOT burned into the picture — so a typo is a one-line edit re-burned at assemble; (4) set top-level `\"draft\": \"render/draft.mp4\"`. Do NOT stop at the plan — produce the media first, THEN write these paths. At gate D, tell the user they can ask for follow-up changes in chat (trim / retime / fix a caption / re-voice a line / regenerate a shot) and you will change only that — edits happen on the DRAFT; export the final ONLY after they are happy.\n\n### Deliver (all lines)\nRun the `video-craft` pre-publish review pass on the FINAL file (readable / timed / on-message / consistent / audio [talking-head: confirm the clip's built-in lip-synced voice is intact and was NOT replaced by a synthesized narration] / platform; fix any blocker first). Present `[video](chat-media://local/<absolute path returned>)` + a one-line summary. End the turn.",+ "workflow": "You are Video Studio, an in-app video production agent for short videos. Your job is to route the request into one locked production line, produce reviewable artifacts, and stop only at named user gates. Keep model turns lean: load the minimum line-specific skills and project files for the current stage.\n\n### Operating model\n- Route first, then lock one line. Do not silently switch lines after a gate; if the promise changes, ask the user.\n- User-facing gates are only: GATE A concept/brief, GATE B script/storyboard or EDL, optional GATE C billable/sensitive generation, and GATE D draft review.\n- Internal states do not ask the user: brief normalization, narration fit, design contract, HTML authoring, scene-map timing, QA lint/inspect, repair, render, plan/checkpoint updates, loudness/caption checks.\n- After a line is locked, read only the skills needed by that line. Do not carry AUTO/EDIT/GENERATE details into a COMPOSE-only task, or COMPOSE implementation details into EDIT/GENERATE tasks.\n- Use built-in tools and skill scripts as stable production interfaces. Do not inspect platform runtime/source code to discover how a tool/script works; failures are blockers or artifact issues to fix at the VideoStudio layer.\n\n### Gate protocol\nAt every named gate:\n1. Show the artifact in chat: script/plan as concise markdown, images as , draft video as [video](chat-media://local/<absolute path>).\n2. Add one line describing the next action and any cost/QA note.\n3. Emit one <agent-input-form> with a select and free-text adjustments field, then <plan-interaction status=\"open\" /> and stop. Do not call another tool after opening a gate.\n4. On resume: approve continues; revise changes only the gated artifact; change direction routes back to the appropriate earlier gate.\n\n### Route and lock\nRead video-router for routing. If a line is clear, lock it in the Gate A proposal.\n- COMPOSE: designed explainers, product promos, typography, diagrams, motion graphics, captions/lower-thirds, deterministic HTML/SVG composition.\n- GENERATE: AI-generated cinematic footage, talking-head/avatar, character or scene generation. Billable generation requires Gate C.\n- EDIT: user supplied real footage to cut, subtitle, dub, localize, mix, denoise, or make highlights.\n- AUTO: a true cross-line deliverable where supplied media, generated clips, composed overlays, narration, or editing must be woven into one EDL.\n\n### GATE A - Proposal\nShow inferred brief: line, aspect ratio, duration, language, and 1-3 concepts. Each concept includes hook, visual approach, rough length, and cost note if billable generation may be involved. When the user supplied brand assets, footage, or a site, inspect them before writing concepts and make at least one concept use a supplied asset as the opening hook. Options: pick concept, revise brief/mix, new direction. Stop.\n\n### Shared craft\nFor the locked line, apply video-craft before authoring the gated artifact. Keep it practical: hook, one idea per beat, readable safe-zone text, restrained motion, muted-friendly captions, and audio fit. Do not repeatedly reload the full craft skill inside the same production stage; keep a short checklist in the stage artifact.\n\n### COMPOSE line\nAfter Gate A locks COMPOSE, read stage-compose and frontend-design; read other line skills only if the approved concept explicitly needs them.\n1. Script + storyboard: write project/script.md and project/shotlist.json in one step.\n2. GATE B: show the script plus a compact shotlist summary. Options: approve, revise, change direction. Stop.\n3. On approval, run the COMPOSE production runbook from stage-compose: optional generate_speech once, write project/composition/design-contract.json, then model-author project/composition/index.html directly. For narrated/tightly timed work, also write project/composition/scene-map.json from the approved script/shotlist. Call `video_studio` with op `composition.draft` to prepare declared local vendor assets, check contract/scene-map/HTML consistency, block remote runtime resources, verify local assets, check shotlist/source alignment, verify narration-to-scene mapping, lint, inspect, render, normalize audio, sample video frames, check for frozen sampled runs, write evidence frames/contact sheet, and write the QA report. Repair at most two localized design-contract/scene-map/HTML issues if draft fails. If the draft report blocks on source_alignment or audio_timing, fix the scene-map/content before rendering again. Do not write or compile spec.json.\n4. GATE D: only after the draft command returns ok with zero blocking QA errors and any triggered composition-design-review has no concrete blockers, show project/render/draft.mp4 and the QA headline/report. Product, promo, version-update, portfolio, style_source, or visibly risky drafts trigger composition-design-review after draft ok and before Gate D. Options: approve high export, revise. Stop.\n5. Final: render high once after approval.\n\n### AUTO line\nRead stage-plan then stage-assemble. Probe/transcribe/OCR supplied media before planning. Write and validate project/plan.json, then Gate B on the EDL summary. Gate C appears only for billable generation. Assemble idempotently: never regenerate produced billable segments; mix narration once; keep compose segments silent when the assembler owns narration. Before Gate D, run stage-plan video_plan --op promise_check --probe-produced; any fail blocks delivery. Gate D shows draft plus QA report.\n\n### GENERATE line\nRead stage-generate; add stage-consistency for recurring characters or story continuity. Plan shots, Gate B on shotlist/script, Gate C before billable generation, then generate/assemble. Preserve built-in lip-synced audio for talking-head clips; do not synthesize over a speaking mouth.\n\n### EDIT line\nRead stage-edit and use actual media evidence before planning: probe every clip, transcribe spoken media, OCR silent/screen/slideshow media. Write project/plan.json, Gate B on the edit plan, then execute trims/concat/mix/subtitles/loudness. Gate D shows the draft and loudness/QA headline.\n\n### Follow-up edits\nIf a draft/final and project/plan.json exist and the user asks for one local change, edit only the affected segment, narration line, caption, trim, volume, speed, or shot. Reproduce only what changed and then re-assemble. Re-plan only when the request genuinely restructures the timeline.\n\n### Deliver\nEvery final response must include the produced media link or a clear blocker. Keep gate and delivery messages short; the artifact is the message.","created_at": "2026-06-23T19:35:00",- "updated_at": "2026-07-06T00:00:00",+ "updated_at": "2026-07-08T16:00:00.000Z","knowhow": [- "Routes video requests into compose, generate, edit, or hybrid production lines without hand-rolling ad hoc ffmpeg work.",- "Builds reusable project plans with scripts, shot lists, narration, captions, media segments, and plan.json edit records.",- "Produces reviewable drafts with checkpoints so users approve concepts, plans, billable generations, and final exports at the right moments.",- "Handles targeted follow-up edits by changing only the affected segment, narration line, caption, trim, or shot instead of rebuilding the whole video."+ "Routes video requests into COMPOSE, GENERATE, EDIT, or AUTO production lines and loads only the skills needed by the locked line.",+ "Separates user-visible gates from internal production states so technical work proceeds without extra approval loops.",+ "Builds reusable project artifacts: script.md, shotlist.json, composition design contract, scene-map, hand-authored HTML, render outputs, and plan.json edit records.",+ "Uses model-authored COMPOSE HTML as the default so visual quality and design extensibility stay under model control.",+ "Keeps follow-up edits localized to the affected segment, narration line, caption, trim, or shot instead of rebuilding the whole video.",+ "Blocks COMPOSE Gate D only when the draft command reports structural lint, contract/source/narration mapping, audio timing, video-frame QA, render, or non-visual inspect blockers; visual inspect findings travel as QA advisories on the draft.",+ "Uses SVG as the preferred visual layer for diagrams, lines, nodes, charts, progress, and background geometry while GSAP orchestrates deterministic motion.",+ "Applies a frontend-design aesthetic thesis before composition so subject matter drives typography, palette, layout signature, and motion choices.",+ "Imports DESIGN.md, brand, screenshot, Figma, or named style references into compact composition tokens without loading a whole external design system.",+ "Uses bounded composition design review for design-sensitive COMPOSE drafts so visible aesthetic blockers are caught without replacing draft QA or creating open-ended rerenders.",+ "Plans narration against scene time budgets before synthesis so TTS is not used as a duration search loop.",+ "Keeps produced media and plan.json faithful so later edits remain auditable and cheap.",+ "Blocks COMPOSE Gate D when contract-to-HTML consistency, source alignment, narration mapping, lint, non-visual inspect, audio timing, render, or video-frame QA fails.",+ "Removes fixed COMPOSE template compilation so placeholder layouts cannot replace model-authored visual design.",+ "Audits model-authored COMPOSE HTML against design-contract and scene-map before rendering so creative freedom stays bounded by approved content, canvas, timing, and assets.",+ "Writes draft contact sheets and per-sample evidence frames so design review is based on stable visual proof instead of open-ended video replay.",+ "Keeps COMPOSE SVG-first and uses GSAP only for purposeful deterministic timeline motion, with a local offline vendor path instead of CDN runtime dependencies.",+ "Uses an optional COMPOSE HTML Preview Gate before mp4 rendering when duration, scene count, complexity, or prior failure makes visual rework expensive; short/simple compositions skip it and render the draft directly."],"standards": ["Every deliverable must expose a visible artifact or draft preview before asking the user to approve the next production step.","Do not run billable media generation or pass major creative gates without explicit user approval.",- "Final video output must satisfy the agreed aspect ratio, duration intent, readable captions or safe-zone text, audio loudness, and platform fit.",- "Keep project/plan.json faithful to the produced media so later edits can be localized and auditable."+ "After routing, do not load unrelated line skills or inspect platform runtime/source code to discover script internals.",+ "Final video output must satisfy the agreed aspect ratio, duration intent, readable safe-zone text, audio loudness, and platform fit.",+ "Keep project/plan.json faithful to produced media so later edits can be localized and auditable.",+ "COMPOSE design-contract.json must include canvas, aesthetic, scenes, layout boxes, typography, color, motion, scene variation, and audio ownership.",+ "COMPOSE design-contract.json must include style_source when an external DESIGN.md, brand guide, screenshot, reference site, Figma note, existing app UI, or named style influenced the design.",+ "COMPOSE Gate D may open after draft QA has zero blocking errors; visual inspect advisories and composition-design-review fixes are shown as Gate D notes unless a concrete frame-specific blocker prevents review.",+ "Narration lines must fit target windows at a natural cadence before generate_speech is called; shorten text before synthesis when needed.",+ "A COMPOSE draft may be rendered and shown at Gate D after draft lint, contract/source/audio checks, video QA, and non-visual inspect blockers pass; visual readability/craft inspect findings do not stop the first mp4 draft.",+ "COMPOSE HTML/CSS/SVG must consume design-contract typography, layout, and baseline color tokens; purposeful supporting hues are allowed when they improve brand fidelity, hierarchy, data meaning, or scene variation.",+ "COMPOSE scene-map entries with narration audio must include per-scene narration text, narration_ref, or source_shots mapping so voiceover-to-visual alignment is auditable.",+ "COMPOSE production must use model-authored project/composition/index.html; fixed spec-to-template compilation is not part of the path.",+ "Narrated COMPOSE drafts must include project/composition/scene-map.json so source and voiceover alignment can be audited before Gate D.",+ "COMPOSE drafts must pass contract_html QA before rendering: design-contract exists, canvas/timing match, approved scene copy appears in HTML, and local assets resolve.",+ "COMPOSE index.html must not depend on http/https runtime resources; scripts, fonts, images, CSS, audio, and video must be vendored or produced inside the composition directory.",+ "Narrated COMPOSE drafts should use narration-map.json when line timing is available so narration_ref scene alignment is checked before Gate D.",+ "COMPOSE Gate D design review should use draft contact_sheet and frame_paths as primary evidence for first-frame, scene-midpoint, and payoff-frame judgment.",+ "COMPOSE may open an HTML Preview Gate before Gate D when target duration is at least 45 seconds, scene count is at least 7, a 20-45 second piece has dense/complex visuals, or a prior draft failed; use composition.inspect plus composition.snapshot and do not render mp4 while preview revisions are still being decided.",+ "COMPOSE visuals should be SVG-first; use GSAP only for purposeful timed reveals, transitions, or emphasis that improve comprehension.",+ "When COMPOSE HTML uses GSAP, it must load ./assets/vendor/gsap.min.js; the render script owns that offline vendor file, may replace old managed shims, and blocks incompatible user-provided vendor files. Do not manually patch assets/vendor/gsap.min.js inside a composition.",+ "COMPOSE draft repair is script-budgeted: the initial failed draft may be followed by two repair passes; if the second repair still fails, the real failing check is returned with repair_budget.budget_exhausted=true, and any later draft attempt returns E_REPAIR_BUDGET_EXCEEDED."],"category": "creation","icon": "flame",@@ -29,6 +62,9 @@"output_format": "artifact","skill_list": ["video-router",+ "frontend-design",+ "design-system-importer",+ "composition-design-review","video-craft","stage-compose","stage-edit",@@ -36,8 +72,7 @@"stage-generate","stage-consistency","stage-plan",- "stage-assemble",- "hybrid-launch-video-with-source-footage"+ "stage-assemble"],"inputs": [{diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/hyperframes_runtime.ts b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/hyperframes_runtime.tsindex 13b8c6c6..130cd0f7 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/hyperframes_runtime.ts+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/hyperframes_runtime.ts@@ -9,6 +9,7 @@*/import { spawn } from 'node:child_process';+import * as fs from 'node:fs';import {bundledNodeExecutable,@@ -46,6 +47,9 @@ export function buildHyperframesEnv(): NodeJS.ProcessEnv {if (ff.ffmpeg) env.HYPERFRAMES_FFMPEG_PATH = ff.ffmpeg;if (ff.ffprobe) env.HYPERFRAMES_FFPROBE_PATH = ff.ffprobe;+ for (const dir of [paths.NODE_NPM_CACHE_DIR, paths.NODE_NPM_PREFIX_DIR, paths.NODE_NPM_GLOBAL_BIN_DIR]) {+ try { fs.mkdirSync(dir, { recursive: true }); } catch { /* npm will surface a clearer error later */ }+ }env.NPM_CONFIG_CACHE = paths.NODE_NPM_CACHE_DIR;env.NPM_CONFIG_PREFIX = paths.NODE_NPM_PREFIX_DIR;env.NPM_CONFIG_FUND = 'false';@@ -65,13 +69,24 @@ export interface CaptureResult {aborted: boolean;}+const CAPTURE_HEARTBEAT_MS = 15_000;+/*** Run `npx hyperframes <args>` and capture stdout/stderr. For `--json` ops* (inspect / lint / transcribe) where the output is the product. Never rejects.+ * `onLine` receives complete output lines as they stream (for progress+ * surfacing); `onHeartbeat` fires periodically while the child is alive so+ * long silent phases (e.g. a first-run model download) stay observable.*/export function runHyperframesCapture(args: string[],- opts: { cwd?: string; signal?: AbortSignal; timeoutMs?: number },+ opts: {+ cwd?: string;+ signal?: AbortSignal;+ timeoutMs?: number;+ onLine?: (line: string, stream: 'stdout' | 'stderr') => void;+ onHeartbeat?: (elapsedSec: number) => void;+ },): Promise<CaptureResult> {const runner = resolveHyperframesRunner();if (!runner) {@@ -93,15 +108,42 @@ export function runHyperframesCapture(const errChunks: string[] = [];let timedOut = false;const timer = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, timeoutMs);- child.stdout?.on('data', (c: Buffer) => out.push(c.toString('utf8')));- child.stderr?.on('data', (c: Buffer) => errChunks.push(c.toString('utf8')));+ const startedAtMs = Date.now();+ const heartbeat = opts.onHeartbeat+ ? setInterval(() => opts.onHeartbeat?.(Math.round((Date.now() - startedAtMs) / 1000)), CAPTURE_HEARTBEAT_MS)+ : null;+ (heartbeat as { unref?: () => void } | null)?.unref?.();+ const lineBufs: Record<'stdout' | 'stderr', string> = { stdout: '', stderr: '' };+ const pumpLines = (stream: 'stdout' | 'stderr', chunk: string) => {+ if (!opts.onLine) return;+ lineBufs[stream] += chunk;+ let nl: number;+ while ((nl = lineBufs[stream].indexOf('\n')) !== -1) {+ const line = lineBufs[stream].slice(0, nl);+ lineBufs[stream] = lineBufs[stream].slice(nl + 1);+ try { opts.onLine(line, stream); } catch { /* progress is best-effort */ }+ }+ if (lineBufs[stream].length > 64 * 1024) lineBufs[stream] = lineBufs[stream].slice(-8 * 1024);+ };+ child.stdout?.on('data', (c: Buffer) => {+ const s = c.toString('utf8');+ out.push(s);+ pumpLines('stdout', s);+ });+ child.stderr?.on('data', (c: Buffer) => {+ const s = c.toString('utf8');+ errChunks.push(s);+ pumpLines('stderr', s);+ });child.stdin?.end();child.on('error', (err) => {clearTimeout(timer);+ if (heartbeat) clearInterval(heartbeat);resolve({ code: -1, stdout: out.join(''), stderr: err.message, timedOut, aborted: !!opts.signal?.aborted });});child.on('close', (code) => {clearTimeout(timer);+ if (heartbeat) clearInterval(heartbeat);resolve({ code, stdout: out.join(''), stderr: errChunks.join(''), timedOut, aborted: !!opts.signal?.aborted });});});diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/ocr_runtime.ts b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/ocr_runtime.tsindex 216796e8..5af1af63 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/ocr_runtime.ts+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/ocr_runtime.ts@@ -100,6 +100,23 @@ function isFile(p: string): boolean {catch { return false; }}+// A successful verify constructs RapidOCR (loads the ONNX models) — too heavy+// to repeat per call. Once a venv verifies, remember it via a sentinel keyed by+// OCR_RUNTIME_KEY (versions + platform), so version bumps re-verify naturally.+function sentinelPath(venv: string): string {+ return path.join(venv, '.orkas-ocr-verified');+}++function sentinelMatches(venv: string): boolean {+ try { return fs.readFileSync(sentinelPath(venv), 'utf8').trim() === OCR_RUNTIME_KEY; }+ catch { return false; }+}++function writeSentinel(venv: string): void {+ try { fs.writeFileSync(sentinelPath(venv), `${OCR_RUNTIME_KEY}\n`); }+ catch { /* best-effort; next call just re-verifies */ }+}+function runtimeEnv(): NodeJS.ProcessEnv {return {...process.env,@@ -168,9 +185,14 @@ async function verifyRuntime(python: string, onProgress?: ProgressFn): Promise<Rasync function ensureRuntime(onProgress?: ProgressFn): Promise<RuntimeResult> {const venv = venvDir();const python = venvPython(venv);+ if (isFile(python) && sentinelMatches(venv)) {+ onProgress?.({ phase: 'ocr_runtime_ready', message: 'Local OCR runtime is ready' });+ return { ok: true, python, venv, installed: false };+ }onProgress?.({ phase: 'ocr_runtime_check', message: 'Checking local OCR runtime' });const existingVerification = await verifyRuntime(python, onProgress);if (existingVerification.ok === true) {+ writeSentinel(venv);onProgress?.({ phase: 'ocr_runtime_ready', message: 'Local OCR runtime is ready' });return { ok: true, python, venv, installed: false };}@@ -255,6 +277,7 @@ async function ensureRuntime(onProgress?: ProgressFn): Promise<RuntimeResult> {const installedVerification = await verifyRuntime(python, onProgress);if (installedVerification.ok === true) {+ writeSentinel(venv);onProgress?.({ phase: 'ocr_runtime_ready', message: 'Local OCR runtime installed and ready' });return { ok: true, python, venv, installed: true };}@@ -271,10 +294,11 @@ async function runOcrProcess(payload: string,onProgress: ProgressFn | undefined,signal: AbortSignal | undefined,+ timeoutMs: number = OCR_TIMEOUT_MS,): Promise<string> {const res = await withHeartbeat(execFileAsync(python, ['-c', PYTHON_OCR_SCRIPT, payload], {- timeout: OCR_TIMEOUT_MS,+ timeout: timeoutMs,env: runtimeEnv(),windowsHide: true,maxBuffer: 8 * 1024 * 1024,@@ -517,6 +541,67 @@ export async function ocrImageText(input: {}}+export type OcrImagesTextResult =+ | { ok: true; results: Array<{ text: string; items: Array<{ text: string; score?: number }>; error?: string }> }+ | {+ ok: false;+ errorCode: 'E_OCR_RUNTIME_MISSING' | 'E_OCR_INSTALL_FAILED' | 'E_OCR_UNSUPPORTED_FILE' | 'E_OCR_FAILED';+ message: string;+ };++/**+ * Batch OCR: many images through ONE Python process / ONE RapidOCR model load+ * (the per-frame path paid a full engine load per image — the dominant local+ * cost when sampling video frames). Results align with `absPaths` by index; a+ * failed frame carries `error` and empty text instead of failing the batch.+ */+export async function ocrImagesText(input: {+ absPaths: string[];+ signal?: AbortSignal;+ onProgress?: ProgressFn;+}): Promise<OcrImagesTextResult> {+ if (!input.absPaths.length) return { ok: true, results: [] };+ const bad = input.absPaths.find((p) => extKind(p) !== 'image');+ if (bad) {+ return { ok: false, errorCode: 'E_OCR_UNSUPPORTED_FILE', message: `ocrImagesText needs image files: ${bad}` };+ }+ const runtime = await ensureRuntime(input.onProgress);+ if (runtime.ok === false) {+ return { ok: false, errorCode: runtime.errorCode, message: runtime.message };+ }+ const payload = JSON.stringify({ paths: input.absPaths, kind: 'images', pages: '', scale: 2 });+ // One model load plus a per-frame budget; a single-image call keeps OCR_TIMEOUT_MS.+ const timeoutMs = Math.max(OCR_TIMEOUT_MS, 60_000 + 10_000 * input.absPaths.length);+ let stdout = '';+ try {+ stdout = await runOcrProcess(runtime.python, payload, input.onProgress, input.signal, timeoutMs);+ } catch (err) {+ return { ok: false, errorCode: 'E_OCR_FAILED', message: `Local OCR failed: ${(err as Error).message}` };+ }+ try {+ const parsed = JSON.parse(stdout) as {+ ok?: boolean;+ error?: unknown;+ pages?: Array<{ text?: string; items?: Array<{ text: string; score?: number }>; error?: string }>;+ };+ if (!parsed?.ok) {+ return { ok: false, errorCode: 'E_OCR_FAILED', message: String(parsed?.error || 'Local OCR failed') };+ }+ const pages = Array.isArray(parsed.pages) ? parsed.pages : [];+ const results = input.absPaths.map((_, i) => {+ const page = pages[i] || {};+ return {+ text: String(page.text || '').trim(),+ items: Array.isArray(page.items) ? page.items : [],+ ...(page.error ? { error: String(page.error) } : {}),+ };+ });+ return { ok: true, results };+ } catch (err) {+ return { ok: false, errorCode: 'E_OCR_FAILED', message: `Local OCR returned invalid output: ${(err as Error).message}` };+ }+}+// Keep this script dependency-light and resilient across RapidOCR package API// changes. The pinned `rapidocr` package needs a string model_root_dir here:// passing its default pathlib.Path trips OmegaConf on some Python versions.@@ -621,13 +706,22 @@ def run_ocr(engine, image_path):def main():args = json.loads(sys.argv[1])- src = args["path"]+ src = args.get("path")kind = args["kind"]engine = load_engine()pages = []if kind == "image":r = run_ocr(engine, src)pages.append({"page": 1, **r})+ elif kind == "images":+ # Batch mode: OCR many images under ONE engine load. A bad frame must+ # not fail the batch — report it per-item and keep going.+ for idx, image_path in enumerate(args["paths"]):+ try:+ r = run_ocr(engine, image_path)+ pages.append({"page": idx + 1, **r})+ except Exception as exc:+ pages.append({"page": idx + 1, "text": "", "items": [], "error": str(exc)})elif kind == "pdf":import pypdfium2 as pdfiumpdf = pdfium.PdfDocument(src)diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_analyze.ts b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_analyze.tsindex 99dfa566..190ed3c1 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_analyze.ts+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_analyze.ts@@ -23,7 +23,7 @@ import {detectQuality,} from './video_edit';import type { QualityThresholds } from './video_decide';-import { ocrImageText } from './ocr_runtime';+import { ocrImageText, ocrImagesText } from './ocr_runtime';import { redactPaths } from './redact';import { createLogger } from './logger-shim';@@ -31,6 +31,20 @@ const log = createLogger('video-analyze');const round2 = (n: number): number => Math.round((Number.isFinite(n) ? n : 0) * 100) / 100;+/** Minimum interval between forwarded transcribe output lines. */+const TRANSCRIBE_LINE_EMIT_MIN_MS = 3_000;++/** Best-effort progress JSONL on stderr (same protocol as video_edit); the+ * direct-CLI runner forwards these lines to the user-facing tool progress. */+function emitAnalyzeProgress(op: AnalyzeOp, event: Record<string, unknown>): void {+ const payload = { type: 'progress', source: 'video_analyze', op, phase: op, ...event };+ try {+ process.stderr.write(`${JSON.stringify(payload)}\n`);+ } catch {+ // Progress must never break the media operation.+ }+}+export type AnalyzeOp = 'transcribe' | 'silence' | 'ocr' | 'scenes' | 'quality';export interface AnalyzeParams {@@ -172,12 +186,25 @@ export async function analyzeMedia(p: AnalyzeParams): Promise<AnalyzeResult> {const args = ['transcribe', p.inputAbsPath, '--json'];if (p.model) args.push('--model', p.model);// Run in the input's dir so the emitted transcript.json lands in scope.+ let lastLineEmitMs = 0;const r = await runHyperframesCapture(args, {cwd: path.dirname(p.inputAbsPath),...(p.signal ? { signal: p.signal } : {}),// Generous: the first non-English transcribe downloads the large-v3 model// (~3GB) before processing; a tight timeout would fail mid-download.timeoutMs: 45 * 60 * 1000,+ onHeartbeat: (elapsedSec) => emitAnalyzeProgress('transcribe', { status: 'heartbeat', elapsed_sec: elapsedSec }),+ // Surface hyperframes' own progress lines (model download, transcribe+ // stages) — stderr only; stdout is the JSON product.+ onLine: (line, stream) => {+ if (stream !== 'stderr') return;+ const text = line.trim();+ if (!text) return;+ const now = Date.now();+ if (now - lastLineEmitMs < TRANSCRIBE_LINE_EMIT_MIN_MS) return;+ lastLineEmitMs = now;+ emitAnalyzeProgress('transcribe', { status: 'output', detail: redactPaths(text).slice(0, 200) });+ },});if (r.aborted) return { ok: false, errorCode: 'E_ANALYZE_ABORTED', message: 'transcribe aborted.' };if (r.timedOut) return { ok: false, errorCode: 'E_ANALYZE_TIMEOUT', message: 'transcribe timed out.' };@@ -212,8 +239,9 @@ export async function analyzeMedia(p: AnalyzeParams): Promise<AnalyzeResult> {return { ok: true, op: 'ocr', summary: { op: 'ocr', engine: 'local:rapidocr-onnxruntime', kind: 'image', text: r.text } };}- // Video: sample frames across the timeline → OCR each → collapse identical- // consecutive reads into a per-slide timecode table.+ // Video: sample frames across the timeline → ONE batch OCR (single Python+ // process / single model load instead of a cold engine per frame) →+ // collapse identical consecutive reads into a per-slide timecode table.const durationSec = (await probeMediaDurationSec(p.inputAbsPath, p.signal)) ?? 0;if (durationSec <= 0) {return { ok: false, errorCode: 'E_ANALYZE_FAILED', message: 'could not probe video duration for frame sampling.' };@@ -221,24 +249,34 @@ export async function analyzeMedia(p: AnalyzeParams): Promise<AnalyzeResult> {const times = sampleTimecodes(durationSec, p.intervalSec ?? 2.5, p.maxFrames ?? 16);const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'orkas-ocr-'));try {- const frames: Array<{ tSec: number; text: string }> = [];let firstErr: { errorCode: string; message: string } | null = null;+ const extracted: Array<{ tSec: number; framePath: string }> = [];for (const t of times) {if (p.signal?.aborted) return { ok: false, errorCode: 'E_ANALYZE_ABORTED', message: 'ocr aborted.' };const out = path.join(tmp, `f-${Math.round(t * 1000)}.png`);const ex = await extractFrameAt(p.inputAbsPath, t, out, p.signal);if (ex.ok === false) { if (!firstErr) firstErr = ex; continue; }- const r = await ocrImageText({ absPath: out, ...(p.signal ? { signal: p.signal } : {}) });- if (r.ok === false) {- // Runtime install/missing is fatal for the whole op — surface it so the- // workflow can apply its own fallback. A per-frame read error is not.- if (r.errorCode === 'E_OCR_RUNTIME_MISSING' || r.errorCode === 'E_OCR_INSTALL_FAILED') {- return { ok: false, errorCode: r.errorCode, message: r.message };- }- if (!firstErr) firstErr = r;- continue;- }- frames.push({ tSec: t, text: r.text });+ extracted.push({ tSec: t, framePath: out });+ }+ if (!extracted.length) {+ return { ok: false, errorCode: firstErr?.errorCode ?? 'E_ANALYZE_FAILED', message: firstErr?.message ?? 'ocr produced no frames.' };+ }+ emitAnalyzeProgress('ocr', { status: 'ocr_batch', frames: extracted.length });+ const batch = await ocrImagesText({+ absPaths: extracted.map((f) => f.framePath),+ ...(p.signal ? { signal: p.signal } : {}),+ onProgress: (ev) => emitAnalyzeProgress('ocr', { status: ev.phase, ...(ev.message ? { detail: ev.message } : {}) }),+ });+ if (batch.ok === false) {+ // Runtime install/missing is surfaced as-is so the workflow can apply+ // its own fallback; a whole-batch OCR failure is an analyze failure.+ return { ok: false, errorCode: batch.errorCode, message: batch.message };+ }+ const frames: Array<{ tSec: number; text: string }> = [];+ for (let i = 0; i < extracted.length; i++) {+ const r = batch.results[i];+ if (!r || r.error) { if (!firstErr && r?.error) firstErr = { errorCode: 'E_OCR_FAILED', message: r.error }; continue; }+ frames.push({ tSec: extracted[i].tSec, text: r.text });}if (!frames.length) {return { ok: false, errorCode: firstErr?.errorCode ?? 'E_ANALYZE_FAILED', message: firstErr?.message ?? 'ocr produced no frames.' };diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_craft_lint.ts b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_craft_lint.tsindex 9f6d0d67..43b4f74c 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_craft_lint.ts+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_craft_lint.ts@@ -131,10 +131,12 @@ export function lintCompositionCraft(html: string, opts?: { canvasHeight?: numbe/** Render findings as a short text block to append to the QA findings the model* reads. Empty string when there are none (so callers can concatenate freely). */-export function formatCraftFindings(findings: CraftFinding[]): string {+export function formatCraftFindings(findings: CraftFinding[], opts?: { strict?: boolean }): string {if (!findings.length) return '';return [- '[craft] static threshold checks (advisory, from the video-craft skill):',+ opts?.strict+ ? '[craft] static threshold checks (FONT_TOO_SMALL blocks under --strict-craft; PALETTE_LARGE is advisory):'+ : '[craft] static threshold checks (advisory, from the video-craft skill):',...findings.map((f) => ` - ${f.code}: ${f.message}`),].join('\n');}diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_edit.ts b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_edit.tsindex 93280263..8937a641 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_edit.ts+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_edit.ts@@ -76,7 +76,7 @@ const MIN_TRIM_OUTPUT_SEC = 0.1;const RUN_PROGRESS_HEARTBEAT_MS = 15_000;const RUN_PROGRESS_MIN_EMIT_MS = 2_000;-export type EditOp = 'probe' | 'trim' | 'concat' | 'burnsubs' | 'overlay' | 'extract_frame' | 'loudness' | 'mix' | 'trim_silence' | 'remove_fillers';+export type EditOp = 'probe' | 'trim' | 'concat' | 'burnsubs' | 'overlay' | 'extract_frame' | 'loudness' | 'normalize_loudness' | 'mix' | 'trim_silence' | 'remove_fillers';/** ebur128 loudness measurement (video-craft §7 targets: ~-14 LUFS integrated,* true-peak ≤ ~-1 dBTP). A field is null when the source is silent (ffmpeg@@ -567,6 +567,23 @@ function ffmpegFailure(op: EditOp, r: { code: number | null; stderr: string; timreturn fail('E_EDIT_FAILED', `${op} failed (exit ${r.code}). ${tail || 'No diagnostic output.'}`);}+async function measureLoudness(+ ffmpeg: string,+ ffprobe: string,+ inputAbsPath: string,+ signal?: AbortSignal,+): Promise<EditResult> {+ const durationSec = await probeDurationSec(ffprobe, inputAbsPath, signal);+ // ebur128 prints its Summary to stderr; -f null discards the decoded output.+ const r = await run(ffmpeg, withFfmpegProgress([+ '-hide_banner', '-nostats', '-i', inputAbsPath, '-af', 'ebur128=peak=true', '-f', 'null', '-',+ ]), signal, { op: 'loudness', phase: 'analyze', durationSec });+ if (r.code !== 0) return ffmpegFailure('loudness', r);+ const loudness = parseEbur128Summary(r.stderr);+ if (!loudness) return fail('E_EDIT_LOUDNESS_PARSE', 'Could not parse the ffmpeg ebur128 loudness summary.');+ return { ok: true, op: 'loudness', loudness };+}+/** ffprobe a file's container duration (seconds), falling back to the first* audio stream's duration. Returns 0 when neither is available. */async function probeDurationSec(ffprobe: string, input: string, signal?: AbortSignal): Promise<number> {@@ -765,15 +782,7 @@ export async function editVideo(p: EditParams): Promise<EditResult> {if (p.op === 'loudness') {if (!p.inputAbsPath) return fail('E_EDIT_ARG', 'loudness requires input_path');- const durationSec = await probeDurationSec(bins.ffprobe, p.inputAbsPath, p.signal);- // ebur128 prints its Summary to stderr; -f null discards the decoded output.- const r = await run(bins.ffmpeg, withFfmpegProgress([- '-hide_banner', '-nostats', '-i', p.inputAbsPath, '-af', 'ebur128=peak=true', '-f', 'null', '-',- ]), p.signal, { op: 'loudness', phase: 'analyze', durationSec });- if (r.code !== 0) return ffmpegFailure('loudness', r);- const loudness = parseEbur128Summary(r.stderr);- if (!loudness) return fail('E_EDIT_LOUDNESS_PARSE', 'Could not parse the ffmpeg ebur128 loudness summary.');- return { ok: true, op: 'loudness', loudness };+ return measureLoudness(bins.ffmpeg, bins.ffprobe, p.inputAbsPath, p.signal);}if (!p.outputAbsPath) return fail('E_EDIT_ARG', `${p.op} requires output_path`);@@ -799,6 +808,31 @@ export async function editVideo(p: EditParams): Promise<EditResult> {return { ok: true, op: 'trim', path: p.outputAbsPath, bytes: checked.bytes };}+ if (p.op === 'normalize_loudness') {+ if (!p.inputAbsPath) return fail('E_EDIT_ARG', 'normalize_loudness requires input_path');+ const base = await probeBasic(bins.ffprobe, p.inputAbsPath, p.signal);+ if (!base.hasAudio) return fail('E_EDIT_NO_AUDIO', 'normalize_loudness requires an input with an audio stream.');+ const ln = `loudnorm=I=${MIX_LOUDNORM.I}:TP=${MIX_LOUDNORM.TP}:LRA=${MIX_LOUDNORM.LRA},aresample=${MIX_OUTPUT_SR}`;+ const r = await run(bins.ffmpeg, withFfmpegProgress([+ '-y', '-i', p.inputAbsPath,+ '-map', '0:v?', '-map', '0:a:0',+ '-c:v', 'copy',+ '-filter:a:0', ln,+ '-c:a', 'aac', '-ar', String(MIX_OUTPUT_SR),+ '-movflags', '+faststart', p.outputAbsPath,+ ]), p.signal, { op: 'normalize_loudness', phase: 'edit', durationSec: base.durationSec });+ if (r.code !== 0) return ffmpegFailure('normalize_loudness', r);+ const loudnessResult = await measureLoudness(bins.ffmpeg, bins.ffprobe, p.outputAbsPath, p.signal);+ if (loudnessResult.ok === false) return loudnessResult;+ return {+ ok: true,+ op: 'normalize_loudness',+ path: p.outputAbsPath,+ bytes: await statSize(p.outputAbsPath),+ loudness: loudnessResult.loudness,+ };+ }+if (p.op === 'concat') {const inputs = p.inputAbsPaths ?? [];if (inputs.length < 2) return fail('E_EDIT_ARG', 'concat requires input_paths with at least 2 entries');diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_render.ts b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_render.tsindex 5f2ac1dc..e35d2051 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_render.ts+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_render.ts@@ -19,6 +19,7 @@*/import * as fs from 'node:fs/promises';+import * as os from 'node:os';import * as path from 'node:path';import { spawn } from 'node:child_process';@@ -26,7 +27,7 @@ import { spawn } from 'node:child_process';// HYPERFRAMES_SPEC). render/inspect, transcribe, and tts all share it so the// hyperframes version can never drift between them.import { HYPERFRAMES_SPEC, resolveHyperframesRunner, buildHyperframesEnv } from './hyperframes_runtime';-import { lintCompositionCraft, formatCraftFindings } from './video_craft_lint';+import { lintCompositionCraft, formatCraftFindings, type CraftFinding } from './video_craft_lint';import { redactPaths } from './redact';import { createLogger } from './logger-shim';@@ -36,6 +37,147 @@ const log = createLogger('video-render');* legitimate, so this is generous; normal completion / user abort happen far* sooner via ctx.signal. */const RENDER_TIMEOUT_MS = 20 * 60 * 1000;+/** Constrained machines software-render frame-by-frame — far slower — so the+ * outer watchdog and HyperFrames' own timeouts must not preempt a legitimately+ * slow (but progressing) render. */+const CONSTRAINED_RENDER_TIMEOUT_MS = 40 * 60 * 1000;+const CONSTRAINED_PROTOCOL_TIMEOUT_MS = 15 * 60 * 1000; // vs hyperframes 5min default+const CONSTRAINED_PLAYER_READY_TIMEOUT_MS = 3 * 60 * 1000; // vs 45s default+const CONSTRAINED_BROWSER_TIMEOUT_MS = 3 * 60 * 1000; // vs 60s default+/** inspect/lint only expose --timeout (runtime init); bump it on slow machines. */+const CONSTRAINED_QA_INIT_TIMEOUT_MS = 30 * 1000; // vs 5s default++/** RAM at or below this (GB) trips the constrained render profile — matches+ * HyperFrames' own low-memory auto-threshold so the two agree. */+export const LOW_RAM_GB = 8;+/** Cost heuristic marking a render infeasible under software rendering on a+ * constrained machine within a reasonable budget. ~1080x1920@30s@30fps (~1863)+ * is fine; 60s@60fps (~7452) is heavy. Keep the knobs here; log the decision. */+export const HEAVY_RENDER_COST = 3000;++/** True when this machine should use the low-memory render profile. `gpuMode`+ * (from a prior attempt's output) forces it even on a high-RAM box. */+export function isConstrainedMachine(totalRamGB: number, observedGpuMode?: string): boolean {+ return totalRamGB <= LOW_RAM_GB || observedGpuMode === 'software';+}++/** Coarse render cost = frames × megapixels. Pure, unit-tested. */+export function estimateRenderCost(width: number, height: number, durationSec: number, fps: number): number {+ const frames = Math.max(1, durationSec) * Math.max(1, fps);+ const megapixels = Math.max(1, (width * height) / 1_000_000);+ return Math.round(frames * megapixels);+}++/** What to do with a heavy render on a constrained machine: a draft degrades+ * (cheaper, still reviewable); a final never silently degrades — it fails fast+ * with an actionable message instead of a long hang. */+export function renderCostDecision(opts: { constrained: boolean; costUnits: number; isFinal: boolean }): 'proceed' | 'degrade' | 'fail_fast' {+ if (!opts.constrained || opts.costUnits <= HEAVY_RENDER_COST) return 'proceed';+ return opts.isFinal ? 'fail_fast' : 'degrade';+}++/** Lower fps first (product decision). Returns a reduced fps, or the same value+ * when it is already at/below the floor (caller then proceeds as-is). */+export function degradedFps(fps: number): number {+ if (fps > 30) return 30;+ return fps; // already ≤30; fps degrade exhausted+}++/** Error/crash tails were truncated to ~1000 chars, which hides the native V8+ * crash backtrace weak/no-GPU machines produce. Keep a generous tail in the+ * result; the full stdout+stderr is persisted to `logPath` when given. */+const RENDER_LOG_TAIL_CHARS = 8000;++/** HyperFrames QA emits no trace of its own; a heartbeat is the only liveness+ * signal while headless Chrome seeks the timeline. */+const QA_PROGRESS_HEARTBEAT_MS = 15_000;++/** Machine + HyperFrames render facts parsed from the child's own output, so a+ * failed/slow render is self-explaining (was it software-rendering? how much+ * RAM? a native worker crash or a timeout?). */+export interface RenderDiagnostics {+ gpuMode?: 'hardware' | 'software' | 'unknown';+ workers?: string;+ protocolTimeoutMs?: number;+ playerReadyTimeoutMs?: number;+ browserTimeoutMs?: number;+ totalRamGB?: number;+ crashSignature?: 'native_worker_crash' | 'timeout' | null;+}++export function machineRamGB(): number {+ return Math.round((os.totalmem() / 1024 ** 3) * 10) / 10;+}++/** Parse HyperFrames' own `Pipeline started {...}` JSON and the gpu-probe line+ * from the combined child output. Pure — unit-tested against real log lines. */+export function parseRenderDiagnostics(output: string): RenderDiagnostics {+ const d: RenderDiagnostics = {};+ const s = String(output || '');+ // The `Pipeline started {...}` line carries nested objects (e.g. "fps":{...}),+ // so take the whole line's first `{` .. last `}` rather than a lazy match.+ const line = s.split(/\r?\n/).find((l) => l.includes('Pipeline started') && l.includes('{'));+ if (line) {+ const start = line.indexOf('{');+ const end = line.lastIndexOf('}');+ if (start !== -1 && end > start) {+ try {+ const j = JSON.parse(line.slice(start, end + 1)) as Record<string, unknown>;+ const gm = j.browserGpuMode;+ if (gm === 'hardware' || gm === 'software') d.gpuMode = gm;+ if (j.requestedWorkers != null) d.workers = String(j.requestedWorkers);+ const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);+ d.protocolTimeoutMs = num(j.protocolTimeoutMs) ?? num(j.protocolTimeout);+ d.playerReadyTimeoutMs = num(j.playerReadyTimeoutMs) ?? num(j.playerReadyTimeout);+ d.browserTimeoutMs = num(j.browserTimeoutMs) ?? num(j.browserTimeout);+ } catch { /* not the line we wanted */ }+ }+ }+ if (!d.gpuMode) {+ const m = s.match(/browserGpuMode\s*(?:auto\s*(?:→|->)\s*)?["']?(hardware|software)["']?/i);+ if (m) d.gpuMode = m[1].toLowerCase() as 'hardware' | 'software';+ }+ return d;+}++/** Classify a native crash vs a timeout from the child's stderr + exit code.+ * `exit null` + V8 isolate/snapshot symbols is the weak-machine crash we saw. */+export function classifyRenderCrash(+ stderr: string,+ code: number | null,+ timedOut: boolean,+): 'native_worker_crash' | 'timeout' | null {+ if (timedOut) return 'timeout';+ const s = String(stderr || '');+ if (+ /NewIsolate|SnapshotData|MultiIsolatePlatform|v8::internal|Segmentation fault|SIGSEGV|SIGABRT|Fatal error/i.test(s)+ && code !== 0+ ) return 'native_worker_crash';+ return null;+}++/** Best-effort: persist the full combined child log to `logPath`. Never throws+ * (a diagnostics write must not fail the render). Returns the path or null. */+async function writeRenderLog(logPath: string | undefined, combined: string): Promise<string | null> {+ if (!logPath) return null;+ try {+ await fs.mkdir(path.dirname(logPath), { recursive: true }).catch(() => {});+ await fs.writeFile(logPath, combined, 'utf8');+ return logPath;+ } catch {+ return null;+ }+}++/** Compact human line for a failure message / report, from parsed diagnostics. */+function diagnosticsSummary(d: RenderDiagnostics): string {+ const parts: string[] = [];+ if (d.gpuMode) parts.push(`gpu=${d.gpuMode}`);+ if (typeof d.totalRamGB === 'number') parts.push(`ram=${d.totalRamGB}GB`);+ if (d.workers) parts.push(`workers=${d.workers}`);+ if (d.crashSignature) parts.push(`crash=${d.crashSignature}`);+ return parts.join(' ');+}export type RenderQuality = 'draft' | 'standard' | 'high';export type RenderFormat = 'mp4' | 'webm';@@ -52,17 +194,32 @@ export interface RenderCompositionParams {variables?: Record<string, unknown>;signal?: AbortSignal;onProgress?: (event: { phase: string; message: string }) => void;+ /** When set, the full combined child stdout+stderr is written here for+ * diagnosis (path-sandboxed by the caller). */+ logPath?: string;+ /** Low-memory / no-GPU render profile: pin 1 worker + bump timeouts so a slow+ * software render finishes instead of crashing/timing out. */+ constrained?: boolean;}export type RenderCompositionResult =- | { ok: true; path: string; bytes: number }- | { ok: false; errorCode: string; message: string };+ | { ok: true; path: string; bytes: number; diagnostics?: RenderDiagnostics; logPath?: string }+ | { ok: false; errorCode: string; message: string; diagnostics?: RenderDiagnostics; logPath?: string };function buildRenderArgs(p: RenderCompositionParams): string[] {const args = ['render', '--output', p.outputAbsPath];if (p.quality) args.push('--quality', p.quality);if (typeof p.fps === 'number') args.push('--fps', String(p.fps));if (p.format) args.push('--format', p.format);+ if (p.constrained) {+ args.push(+ '--low-memory-mode',+ '--workers', '1',+ '--protocol-timeout', String(CONSTRAINED_PROTOCOL_TIMEOUT_MS),+ '--player-ready-timeout', String(CONSTRAINED_PLAYER_READY_TIMEOUT_MS),+ '--browser-timeout', String(CONSTRAINED_BROWSER_TIMEOUT_MS),+ );+ }if (p.variables && Object.keys(p.variables).length) {args.push('--variables', JSON.stringify(p.variables));}@@ -132,14 +289,16 @@ export async function renderComposition(p: RenderCompositionParams): Promise<Ren}const errChunks: string[] = [];+ const outChunks: string[] = [];let stdoutBuf = '';let settled = false;let timedOut = false;+ const renderTimeoutMs = p.constrained ? CONSTRAINED_RENDER_TIMEOUT_MS : RENDER_TIMEOUT_MS;const timer = setTimeout(() => {timedOut = true;child.kill('SIGKILL');- }, RENDER_TIMEOUT_MS);+ }, renderTimeoutMs);const pumpProgress = (chunk: string) => {stdoutBuf += chunk;@@ -152,7 +311,11 @@ export async function renderComposition(p: RenderCompositionParams): Promise<Ren}};- child.stdout?.on('data', (c: Buffer) => pumpProgress(c.toString('utf8')));+ child.stdout?.on('data', (c: Buffer) => {+ const s = c.toString('utf8');+ outChunks.push(s);+ pumpProgress(s);+ });child.stderr?.on('data', (c: Buffer) => {const s = c.toString('utf8');errChunks.push(s);@@ -177,33 +340,45 @@ export async function renderComposition(p: RenderCompositionParams): Promise<Ren});child.on('close', async (code: number | null) => {+ const stdout = outChunks.join('');+ const stderr = errChunks.join('').trim();+ const combined = stdout + (stderr ? `\n--- stderr ---\n${stderr}` : '');+ const diagnostics: RenderDiagnostics = {+ ...parseRenderDiagnostics(combined),+ totalRamGB: machineRamGB(),+ crashSignature: classifyRenderCrash(stderr, code, timedOut),+ };+ const logPath = (await writeRenderLog(p.logPath, combined)) ?? undefined;+ const withDiag = (r: RenderCompositionResult): RenderCompositionResult =>+ ({ ...r, diagnostics, ...(logPath ? { logPath } : {}) });+ const summary = diagnosticsSummary(diagnostics);+if (timedOut) {- finish({ ok: false, errorCode: 'E_RENDER_TIMEOUT', message: `Render timed out after ${RENDER_TIMEOUT_MS}ms.` });+ finish(withDiag({ ok: false, errorCode: 'E_RENDER_TIMEOUT', message: `Render timed out after ${renderTimeoutMs}ms.${summary ? ` [${summary}]` : ''}` }));return;}if (p.signal?.aborted) {- finish({ ok: false, errorCode: 'E_RENDER_ABORTED', message: 'Render aborted.' });+ finish(withDiag({ ok: false, errorCode: 'E_RENDER_ABORTED', message: 'Render aborted.' }));return;}if (code !== 0) {- const stderr = errChunks.join('').trim();- const tail = stderr.slice(-1500);- log.warn(`hyperframes render exited ${code}: ${redactPaths(tail.slice(-300))}`);- return finish({+ const tail = stderr.slice(-RENDER_LOG_TAIL_CHARS);+ log.warn(`hyperframes render exited ${code}: ${redactPaths(tail.slice(-300))}${summary ? ` [${summary}]` : ''}`);+ return finish(withDiag({ok: false,errorCode: 'E_RENDER_FAILED',- message: `HyperFrames render failed (exit ${code}). ${tail || 'No diagnostic output.'}`,- });+ message: `HyperFrames render failed (exit ${code}).${summary ? ` [${summary}]` : ''}${logPath ? ` Full log: ${logPath}.` : ''} ${tail || 'No diagnostic output.'}`,+ }));}const st = await fs.stat(p.outputAbsPath).catch(() => null);if (!st || !st.isFile() || st.size === 0) {- return finish({+ return finish(withDiag({ok: false,errorCode: 'E_RENDER_NO_OUTPUT',message: `Render reported success but no output file was produced at ${p.outputAbsPath}.`,- });+ }));}- finish({ ok: true, path: p.outputAbsPath, bytes: st.size });+ finish(withDiag({ ok: true, path: p.outputAbsPath, bytes: st.size }));});});}@@ -211,13 +386,40 @@ export async function renderComposition(p: RenderCompositionParams): Promise<Renexport type QaOp = 'lint' | 'inspect';export type QaResult =- | { ok: true; op: QaOp; findings: string }- | { ok: false; errorCode: string; message: string };+ | { ok: true; op: QaOp; findings: string; diagnostics?: RenderDiagnostics; logPath?: string }+ | { ok: false; errorCode: string; message: string; diagnostics?: RenderDiagnostics; logPath?: string };/** Backstop for a wedged QA pass. `inspect` spawns headless Chrome to seek the* timeline; a few minutes is generous. */const QA_TIMEOUT_MS = 5 * 60 * 1000;+function withStrictCraftFindings(findings: string, craftFindings: CraftFinding[]): string {+ const blockingFindings = craftFindings.filter((f) => f.code === 'FONT_TOO_SMALL');+ if (!blockingFindings.length) return findings;+ try {+ const parsed = JSON.parse(findings) as Record<string, unknown>;+ const existingIssues = Array.isArray(parsed.issues) ? parsed.issues : [];+ const craftIssues = blockingFindings.map((f) => ({+ code: f.code,+ severity: 'error',+ selector: 'document',+ message: f.message,+ fixHint: 'Raise all readable text to the video-craft legibility floor before rendering.',+ source: 'video-craft',+ }));+ const add = craftIssues.length;+ const numberField = (key: string) => (typeof parsed[key] === 'number' ? parsed[key] as number : 0);+ parsed.ok = false;+ parsed.errorCount = numberField('errorCount') + add;+ parsed.issueCount = numberField('issueCount') + add;+ parsed.totalIssueCount = numberField('totalIssueCount') + add;+ parsed.issues = [...existingIssues, ...craftIssues];+ return JSON.stringify(parsed, null, 2);+ } catch {+ return `${findings}\n\n[craft] BLOCKING strict checks:\n${blockingFindings.map((f) => ` - ${f.code}: ${f.message}`).join('\n')}`;+ }+}+/*** Run a HyperFrames QA pass (`lint` structural / `inspect` visual) over the* composition dir and return its `--json` findings. `inspect` seeks the rendered@@ -228,7 +430,14 @@ const QA_TIMEOUT_MS = 5 * 60 * 1000;*/export async function qaComposition(op: QaOp,- p: { projectDirAbs: string; signal?: AbortSignal },+ p: {+ projectDirAbs: string;+ signal?: AbortSignal;+ strictCraft?: boolean;+ onProgress?: (event: { phase: string; message: string }) => void;+ logPath?: string;+ constrained?: boolean;+ },): Promise<QaResult> {const runner = resolveHyperframesRunner();if (!runner) {@@ -242,6 +451,8 @@ export async function qaComposition(const env = buildHyperframesEnv();const args = [runner.npxCli, '--yes', HYPERFRAMES_SPEC, op, '--json'];+ // inspect/lint only expose --timeout (runtime init); a slow machine needs longer.+ if (p.constrained) args.push('--timeout', String(CONSTRAINED_QA_INIT_TIMEOUT_MS));return new Promise<QaResult>((resolve) => {let child: ReturnType<typeof spawn>;@@ -256,30 +467,64 @@ export async function qaComposition(let settled = false;let timedOut = false;const timer = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, QA_TIMEOUT_MS);+ const startedAtMs = Date.now();+ const heartbeat = p.onProgress+ ? setInterval(() => p.onProgress?.({ phase: `qa.${op}`, message: `${op} running (${Math.round((Date.now() - startedAtMs) / 1000)}s elapsed)` }), QA_PROGRESS_HEARTBEAT_MS)+ : null;+ (heartbeat as { unref?: () => void } | null)?.unref?.();+ let traceBuf = '';+ const pumpTrace = (chunk: string) => {+ if (!p.onProgress) return;+ traceBuf += chunk;+ let nl: number;+ while ((nl = traceBuf.indexOf('\n')) !== -1) {+ const line = traceBuf.slice(0, nl);+ traceBuf = traceBuf.slice(nl + 1);+ const ev = parseTraceLine(line);+ if (ev) p.onProgress?.(ev);+ }+ };child.stdout?.on('data', (c: Buffer) => out.push(c.toString('utf8')));- child.stderr?.on('data', (c: Buffer) => errOut.push(c.toString('utf8')));+ child.stderr?.on('data', (c: Buffer) => { const s = c.toString('utf8'); errOut.push(s); pumpTrace(s); });child.stdin?.end();- const finish = (r: QaResult) => { if (settled) return; settled = true; clearTimeout(timer); resolve(r); };+ const finish = (r: QaResult) => { if (settled) return; settled = true; clearTimeout(timer); if (heartbeat) clearInterval(heartbeat); resolve(r); };child.on('error', (err: Error) => {if (p.signal?.aborted) return finish({ ok: false, errorCode: 'E_QA_ABORTED', message: `${op} aborted.` });finish({ ok: false, errorCode: 'E_QA_SPAWN', message: err.message });});- child.on('close', async () => {+ child.on('close', async (code: number | null) => {if (timedOut) return finish({ ok: false, errorCode: 'E_QA_TIMEOUT', message: `${op} timed out.` });if (p.signal?.aborted) return finish({ ok: false, errorCode: 'E_QA_ABORTED', message: `${op} aborted.` });const findings = out.join('').trim();if (!findings) {- const stderr = errOut.join('').trim().slice(-1000);- return finish({ ok: false, errorCode: 'E_QA_NO_OUTPUT', message: `${op} produced no findings. ${stderr}` });+ const stderrFull = errOut.join('').trim();+ const combined = out.join('') + (stderrFull ? `\n--- stderr ---\n${stderrFull}` : '');+ const diagnostics: RenderDiagnostics = {+ ...parseRenderDiagnostics(combined),+ totalRamGB: machineRamGB(),+ crashSignature: classifyRenderCrash(stderrFull, code, false),+ };+ const logPath = (await writeRenderLog(p.logPath, combined)) ?? undefined;+ const summary = diagnosticsSummary(diagnostics);+ return finish({+ ok: false,+ errorCode: 'E_QA_NO_OUTPUT',+ message: `${op} produced no findings.${summary ? ` [${summary}]` : ''}${logPath ? ` Full log: ${logPath}.` : ''} ${stderrFull.slice(-RENDER_LOG_TAIL_CHARS) || 'No diagnostic output.'}`,+ diagnostics,+ ...(logPath ? { logPath } : {}),+ });}// Append advisory craft-threshold findings (pure static scan of the HTML).// Best-effort: a read failure must never fail the QA pass.let craft = '';+ let finalFindings = findings;try {const html = await fs.readFile(indexHtml, 'utf8');- craft = formatCraftFindings(lintCompositionCraft(html));+ const craftFindings = lintCompositionCraft(html);+ if (p.strictCraft) finalFindings = withStrictCraftFindings(findings, craftFindings);+ craft = formatCraftFindings(craftFindings, { strict: !!p.strictCraft });} catch { /* advisory only; ignore */ }- finish({ ok: true, op, findings: craft ? `${findings}\n\n${craft}` : findings });+ finish({ ok: true, op, findings: craft ? `${finalFindings}\n\n${craft}` : finalFindings });});});}diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/composition-design-review/SKILL.md b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/composition-design-review/SKILL.mdnew file mode 100644index 00000000..c4bb387c--- /dev/null+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/composition-design-review/SKILL.md@@ -0,0 +1,88 @@+---+ownerAgent: 79df9cc89f5f+name: composition-design-review+min_app_version: "1.5.1"+description_zh: VideoStudio 的 COMPOSE 设计审查层 - 在 stage-compose draft/inspect 后,检查 HTML/动态图形视频的模板感、首帧、视觉层级、可读性、风格一致、动效目的和 DESIGN.md/品牌 token 执行情况,只输出可执行修复。+description_en: Design review layer for VideoStudio COMPOSE drafts. Use after stage-compose draft/inspect to assess template feel, first frame, hierarchy, readability, style consistency, purposeful motion, and adherence to DESIGN.md/brand tokens, returning only actionable fixes.+category: creation+---++# composition-design-review++Use this after `video_studio` `op: "composition.draft"` returns a draft/report, but only when the compose task is design-sensitive. It is a design QA layer, not a renderer, line router, or generic video craft checklist.++Do not open a new user Gate. Read `steps.inspect.draft_disposition` when present. Draft visual/readability inspect findings are review evidence, not automatic blockers. If findings are blockers, make at most one localized repair to the contract/scene-map/HTML and re-run the draft command before Gate D. If findings are `fix` or `polish`, include them in the Gate D note unless they are trivial to repair in the same pass.++## Activation++Run this review only when one of these is true:++- The approved brief is brand, product, promo, launch, version-update, portfolio, or other design-led COMPOSE work.+- `project/composition/design-contract.json` contains a `style_source`.+- The draft report or sampled frames show a visible design risk that deterministic QA cannot judge, such as a weak first frame, flat hierarchy, repeated scene grammar, or motion that hides the message.++Do not run this review for ordinary edit/TTS/clip-selection work, simple caption cards, or generic "make it polished" wording without a visible design risk.++## Review Inputs++Read only the relevant artifacts:++- `project/composition/design-contract.json`+- `project/composition/scene-map.json` when narration/timing alignment matters+- `project/composition/qa/inspect.json` or `project/render/draft-report.json`+- Sampled evidence frames from the draft report when available: `video_qa.contact_sheet`, `video_qa.frame_paths`, first frame, one mid-frame per scene, and payoff/closing frame+- The approved script/shotlist only when a finding depends on message intent++## Findings Rubric++Tag each finding as `blocker`, `fix`, or `polish`.++Blockers must identify a specific scene/frame, the visible evidence, and the smallest repair. A finding is not a blocker just because the design could be more distinctive, or because inspect reported a visual advisory that does not break the approved promise.++Blockers:++- First frame is blank, unreadable, or fails to state the approved promise in a promo/version-update/launch deliverable.+- Text is unreadable in the supplied evidence frame, hides the approved promise/CTA, or materially blocks comprehension because of size, safe-zone, overlap, occlusion, or contrast.+- The draft report's `contract_html` step says approved scene copy, canvas, assets, or runtime dependencies do not match the model-authored HTML.+- Visual language contradicts an explicit style source or ignores required brand tokens.+- The piece reads as a slideshow when the approved promise was motion graphics.+- Motion hides the message, distracts from the focal point, or breaks narration timing.+- A protected logo/asset/layout was copied without ownership or permission.++Fix:++- First frame is truthful and readable but could be a stronger thumbnail.+- Text has a visible safe-zone, size, overlap, occlusion, or contrast advisory, but the main message remains readable and the draft is useful for Gate D review.+- Repeated layout, transition, or card pattern three or more times in a row.+- Palette uses extra chromatic colors beyond the contract.+- Type hierarchy is flat or labels feel like UI residue instead of video graphics.+- Scene density is too high for phone viewing.+- Style-source adaptation is vague: it borrows mood words but no concrete tokens.++Polish:++- Easing, stagger, spacing, shadow, stroke, or texture could better support the tone.+- A stronger thumbnail frame or payoff hold would improve memorability.+- A minor token mismatch that does not hurt comprehension.++## Repair Preference++Fix the highest-level artifact that caused the issue:++1. `design-contract.json` when the thesis, tokens, or layout budget are wrong.+2. `scene-map.json` when timing, narration mapping, or source-shot mapping is wrong.+3. `index.html` for visual hierarchy, typography, layout, motion, asset, or scene variation fixes.++Do not solve design problems by only nudging pixels. If the issue is "too generic", change the signature device or scene grammar. If the issue is "too dense", remove or split content.++## Output Format++Return a compact review object or bullets:++- `verdict`: pass | repair | block+- `review_scope`: why this review was triggered+- `design_direction`: one line+- `blockers`: concrete location + evidence + repair+- `fixes`: concrete location + repair+- `polish`: optional+- `next_action`: rerun draft, open Gate D, or surface blockerdiff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/design-system-importer/SKILL.md b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/design-system-importer/SKILL.mdnew file mode 100644index 00000000..a4ff053c--- /dev/null+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/design-system-importer/SKILL.md@@ -0,0 +1,74 @@+---+ownerAgent: 79df9cc89f5f+name: design-system-importer+description_zh: VideoStudio 的设计系统输入层 - 当用户提供 DESIGN.md、品牌规范、参考网站/截图、Figma 导出的设计说明或"做成某某风格"时,把外部风格压缩成 stage-compose 可用的 design-contract/style tokens,避免整包加载风格库。+description_en: Design-system input layer for VideoStudio. Use when a user provides DESIGN.md, brand guidelines, a reference site/screenshot, Figma-exported design notes, or asks for a named style. Convert the style into compact stage-compose design-contract/style tokens without loading a whole design library.+category: creation+---++# design-system-importer++Use this only when COMPOSE or an AUTO compose segment has an external style source: a `DESIGN.md`, brand guide, visual reference, screenshot, existing website, Figma notes, or an explicit user request such as "make it feel like Linear/Stripe/Notion" or "follow this brand".++Do not use it for ordinary editing, TTS, shot generation, or clip selection. Do not introduce a new user Gate. The output is an internal style extraction that feeds `project/composition/design-contract.json` and the hand-authored `project/composition/index.html`.++Do not use it for vague adjectives like "modern", "clean", "premium", "dynamic", or "more polished" when no source is named. In those cases, let `frontend-design` choose the aesthetic thesis directly from the video brief.++## Input Priority++Prefer concrete local material over memory:++1. User-provided `DESIGN.md`, brand guide, or style brief.+2. User-provided screenshot/image/video stills.+3. Existing product/app UI in the workspace.+4. A named public style reference only when the user explicitly names it. If current details matter and the source was not provided, retrieve or ask for it instead of inventing specifics.++Adapt style; do not copy logos, protected assets, proprietary text, or trademarked UI one-to-one.+Keep extraction small enough to fit inside the design contract. Do not load or recreate an entire external design system.++## Extract Compact Tokens++Write a `style_source` object into `project/composition/design-contract.json`:++```json+{+ "style_source": {+ "source_type": "design_md | brand_guide | screenshot | site | named_reference | existing_app",+ "source_basis": "file path, user note, or inspected artifact",+ "adaptation_boundary": "what may be borrowed vs what must not be copied",+ "confidence": "high | medium | low"+ }+}+```++Then normalize the source into tokens that hand-authored HTML/CSS/SVG can consume:++- `color_tokens`: background, surface, text, muted, primary accent, optional secondary accent, plus intended contrast relationship.+- `typography_tokens`: display, body, data/label, caption roles; scale and weight intent; avoid relying on fonts that are not available.+- `shape_tokens`: radius, stroke, shadow, divider, border, and density.+- `layout_language`: grid, editorial, cinematic, dashboard, diagrammatic, poster, product-demo, or another concrete grammar.+- `motion_language`: entrance, transition, emphasis, data-build, and exit patterns; keep it compatible with GSAP timeline seeking.+- `asset_rules`: what images/icons/marks are allowed, need replacement, or must be avoided.+- `do_not_copy`: logos, exact layouts, trademarked copy, screenshots, or protected illustrations unless the user owns them.++Keep the imported style small. If more than 6 chromatic colors or 3 font roles are needed, summarize the conflict and pick the smallest faithful subset.++## Map To Video++Web and brand systems are not videos. Convert them for motion:++- First frame: choose the style's strongest thumbnail-friendly signal.+- Safe zones: enlarge type and spacing beyond web density.+- Scene variation: turn repeated web sections into distinct beats.+- Motion: make the brand grammar move with purpose; do not animate every component.+- Captions: keep ordinary subtitles in `tracks.captions.lines`, not in the style system.++## Output++After extraction, the design contract must state:++- What source was used.+- Which tokens were adopted.+- Which tokens were deliberately simplified.+- Which elements must not be copied.+- What visual signature will make the video feel related to the reference without becoming a clone.diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/frontend-design/SKILL.md b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/frontend-design/SKILL.mdnew file mode 100644index 00000000..4fc04eb0--- /dev/null+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/frontend-design/SKILL.md@@ -0,0 +1,89 @@+---+ownerAgent: 79df9cc89f5f+name: frontend-design+description_zh: VideoStudio 的 HTML/动态图形审美层——在 stage-compose 写 design-contract.json 与 index.html 前,用主题世界、字体、配色、布局签名、动效克制和反模板检查,把普通可渲染页面提升为有明确视觉观点的视频画面。+description_en: Aesthetic direction for VideoStudio HTML and motion-graphics compositions. Use before stage-compose writes design-contract.json and index.html to choose a subject-specific visual point of view, type, palette, layout signature, restrained motion, and anti-template checks.+category: creation+---++# frontend-design++Use this as the design-lead layer for VideoStudio COMPOSE work. It shapes HTML/SVG motion graphics before `stage-compose` turns them into `project/composition/design-contract.json` and `index.html`.++This skill does not pick the video production line, replace `video-craft`, or relax Orkas renderer constraints. If there is a conflict, renderer determinism, safe zones, legibility, audio ownership, and user-approved creative direction win.++## Design Thesis++Before writing HTML, choose a compact visual thesis:++- `subject_world`: the real materials, artifacts, interface metaphors, gestures, environment, or culture of the topic.+- `audience`: who must understand this at phone size and what they already know.+- `one_job`: what this video frame sequence must make clear.+- `tone`: one or two precise words that shape type, color, spacing, and motion.+- `signature_device`: one memorable visual move that belongs to this brief.+- `aesthetic_risk`: one justified choice that avoids generic output without hurting readability.++Keep the thesis specific. "Modern tech style" is not a thesis. "Battery-lab oscilloscope traces become the progress line" is.++## Avoid Template Gravity++Reject choices that could fit almost any brief:++- Purple/blue neon gradients, glass panels, generic bento cards, floating UI cards, decorative blobs, and stock SaaS dashboards unless the subject truly calls for them.+- Numbered markers, timelines, terminal windows, blueprint grids, or newspaper rules when the content is not actually sequential, technical, architectural, or editorial.+- A palette made from one hue family with lighter/darker variations only.+- Long labels in circles, tiny badges, dense microcopy, or walls of text doing the visual's job.+- Motion everywhere. Spend motion on the one thing the viewer must notice.++If the first design idea feels like a reusable demo template, revise the thesis before coding.++## Contract Fields++Add an `aesthetic` object to `project/composition/design-contract.json`:++```json+{+ "aesthetic": {+ "subject_world": "what the visual language borrows from",+ "audience": "who it is for",+ "one_job": "the frame sequence's job",+ "tone": ["precise", "brief"],+ "signature_device": "one remembered visual behavior",+ "aesthetic_risk": "the deliberate non-default choice",+ "anti_template_check": "what was rejected as too generic"+ }+}+```++The rest of the contract must make the thesis executable:++- `typography_tokens`: role-based, not just sizes. Include display, body, data/label, and caption roles when needed.+- `color_tokens`: named baseline values with rationale. Include neutrals, primary accent, and any purposeful supporting accents needed for brand, hierarchy, data meaning, or scene variation.+- `layout_boxes`: describe visual hierarchy, not only coordinates. Name the focal zone and supporting zones.+- `motion_budget`: state what carries meaning, what stays still, and how each transition maps to the story.+- `scene_variation`: prevent three near-identical card/title scenes in a row.++## HTML Direction++When writing `index.html`:++- Derive the main CSS variables from `design-contract.json`; keep extra chromatic colors intentional and named enough to audit. Do not flatten the design or recolor the whole video only to reduce a static palette count.+- Let one element carry personality: a custom progress line, typographic reveal, diagram grammar, texture, data mark, or transition family. Keep surrounding elements quiet.+- Use type as design material: contrast display/body roles, make title/body hierarchy unmistakable, and keep labels large enough for the video-craft floor.+- Use structural marks only when they encode meaning: steps for sequences, coordinates for maps, ticks for time, nodes for relationships, brackets for comparison.+- Prefer SVG for diagrams, paths, meters, masks, charts, and signature geometry; keep prose and captions as real HTML text.+- Default to SVG/static held states first. Use GSAP only when a timed reveal, transition, or emphasis genuinely improves comprehension; animate SVG groups or a few containers instead of many HTML cards.+- For vertical video, design for platform UI: keep essential text away from the bottom action area and make the first frame readable as a thumbnail.+- Respect `prefers-reduced-motion` in CSS where practical, but drive render-critical animation through the paused GSAP timeline.++## Build Loop++1. Draft the thesis and contract.+2. Self-critique the contract: name the most generic choice and replace it.+3. Write HTML/SVG from the contract.+4. Run the draft QA command. If `draft_disposition.blocking_error_count` or structural/video/audio QA fails, repair the contract or scene structure first; do not only nudge CSS numbers. Treat visual/readability findings as draft notes unless they make the approved message unreadable.+5. After a rendered draft, judge the first frame, one mid-frame, and the payoff frame for: clear focal point, subject-specific visual language, readable type, and motion with purpose.++## Output Standard++When reporting a COMPOSE draft or blocker, include the short design direction used: thesis, signature device, and any inspect/craft issue that forced a design change.diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/hybrid-launch-video-with-source-footage/SKILL.md b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/hybrid-launch-video-with-source-footage/SKILL.mddeleted file mode 100644index 05bd5b44..00000000--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/hybrid-launch-video-with-source-footage/SKILL.md+++ /dev/null@@ -1,41 +0,0 @@-----name: "Hybrid Launch Video With Source Footage"-description: "WHEN producing a branded launch video that must include supplied footage, use a gated hybrid EDL and verify the source-footage promise before delivery."-createdAt: "2026-06-28T23:02:02.562Z"-updatedAt: "2026-06-28T23:02:02.562Z"-patchCount: 0-tags:- - "video"- - "launch"- - "branding"- - "edl"- - "audio"-----## Procedure--1. **Collect brand constraints**- - ALWAYS inspect the website and supplied assets before writing concepts.- - ALWAYS restate required tone, color direction, language, duration, aspect ratio, subtitles, and must-use footage.--2. **Gate A: concepts**- - ALWAYS offer 2–3 distinct concepts with hook, visual style, message, duration, and best use case.- - WHEN the user has supplied a mascot/logo/footage, THEN make at least one concept use it as the opening hook.--3. **Gate B: script + EDL**- - ALWAYS write a timed timeline with scene durations, visual action, subtitles/VO, and asset usage.- - WHEN footage must appear, THEN encode it as `source_required` / delivery promise in the plan.- - ALWAYS validate the plan and run the anti-slideshow / motion-ratio promise check before presenting the plan.--4. **Draft assembly**- - ALWAYS keep subtitles readable and short; place them as native overlays tied to timeline beats.- - ALWAYS include the supplied footage in the rendered timeline, not only as a reference frame.- - WHEN using TTS, THEN generate narration to fit the target duration; shorten copy if it would require rushed speech.--5. **Audio sync QA**- - NEVER deliver a draft with duplicate narration/music creating two voices.- - WHEN narration sync matters, THEN split the script by scene beats and mix each segment at its exact timeline offset.- - ALWAYS verify single voice track, coverage across intended scenes, and acceptable CTA/music-only tail before presenting.--6. **Delivery report**- - ALWAYS report duration, resolution/aspect ratio, audio status, subtitle/readability status, source-footage inclusion, and motion-ratio/promise-check result.- - WHEN there is a known gap such as a silent CTA tail, THEN state it explicitly as acceptable or ask whether to change it.\ No newline at end of filediff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-assemble/SKILL.md b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-assemble/SKILL.mdindex b697e1d6..2e779f80 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-assemble/SKILL.md+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-assemble/SKILL.md@@ -1,6 +1,7 @@---ownerAgent: 79df9cc89f5fname: stage-assemble+min_app_version: "1.5.1"description_zh: 把已审批的跨模态 EDL(plan.json)确定性地装配成成片的知识——按序产出每个片段(剪辑/合成/生成/已提供,分别委派给对应产线),再按 ffmpeg 层级装配:主轨拼接→合成叠层→混旁白(覆盖校验)→烧字幕→响度核对;带断点续跑,交 D 门前做 QA。AUTO 端到端产线的装配核心。description_en: Knowledge for deterministically assembling an approved cross-modal EDL (plan.json) into a finished video — produce each segment (edit / compose / generate / provided, each delegated to its line), then assemble in ffmpeg tiers: concat the primary track → overlay composed layers → mix narration (with a coverage check) → burn captions → verify loudness; idempotent-resumable, with QA before gate D. The assembly core of the AUTO end-to-end line.category: creation@@ -8,26 +9,25 @@ category: creation# stage-assemble-How to execute a validated `project/plan.json` into one finished file. By the time you are here the plan passed the `stage-plan video_plan --op validate` script and the user approved it at gate B. Walk it; do not re-plan. Host-neutral: VideoStudio-specific media work runs through skill scripts (`stage-edit edit_video`, `stage-compose render_composition`, `stage-plan video_plan` via `bin/run-skill.cjs`); generic built-in capabilities remain `generate_video` / `generate_image` / `generate_speech`.+How to execute a validated `project/plan.json` into one finished file. By the time you are here the plan passed the `stage-plan video_plan --op validate` script and the user approved it at gate B. Walk it; do not re-plan. Host-neutral: VideoStudio-specific edit/plan work runs through skill scripts (`stage-edit edit_video`, `stage-plan video_plan` via `bin/run-skill.cjs`), while composition and transcription run through the required built-in `video_studio` runtime; generic built-in capabilities remain `generate_video` / `generate_image` / `generate_speech`.## Script calls used here```bash"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-edit edit_video -- --op concat --inputs project/parts/a.mp4,project/parts/b.mp4 --output project/render/primary.mp4"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-edit edit_video -- --op mix --input project/render/primary.mp4 --audio-segments @project/audio_segments.json --output project/render/mixed.mp4-"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-edit edit_video -- --op loudness --input project/render/draft.mp4-"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-compose render_composition -- --op render --composition-dir project/composition --output project/parts/card.mp4 --quality draft+"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-edit edit_video -- --op normalize_loudness --input project/render/draft.mp4 --output project/render/video.mp4```-When this document says `stage-edit edit_video --op ...`, call the matching `bin/run-skill.cjs` command above with the relevant paths. Do not call deprecated direct tools.+When this document says `stage-edit edit_video --op ...`, call the matching `bin/run-skill.cjs` command above with the relevant paths. For compose/transcription work, call `video_studio` directly. Do not call deprecated direct tools.## Step 1 — Produce each segment (delegate by source)Iterate segments in `order`. For each, produce its `produced_path` according to `source`, then write that path + `status:"done"` back into the segment so a resume never re-produces it:- **edit** → `stage-edit`: `stage-edit edit_video --op trim` the `input_id` to `[in_sec, out_sec]` → `project/cuts/<id>.mp4`.-- **compose** → `stage-compose`: build a small composition for `spec.kind` (title card, lower-third, stat card, captions) → `stage-compose render_composition --op render` to `project/parts/<id>.mp4` (or keep as an overlay element for step 2).-- **generate** → `stage-generate` (+ `stage-consistency` for recurring characters): only AFTER gate C. `generate_video`/`generate_image` → `project/assets/<id>.mp4`. Generate at most ~4 shots in flight (the `run_worker` fan-out cap — do not assume unlimited parallelism); a failed shot retries without blocking the batch. Per `stage-consistency`: feed each shot the segment's `refs` (locked portrait + the prior same-scene shot's last frame) and honor its `variation_type`, then extract this shot's last frame to carry the look forward so multi-shot characters do not drift.+- **compose** → `stage-compose`: build a small visual-only composition for `spec.kind` (title card, lower-third, stat card, captions) under `project/compositions/<id>/` → call `video_studio` `op: "composition.draft"` to `project/parts/<id>.mp4` with `report_path: "project/reports/<id>-compose-report.json"`. This keeps compose segments on the same contract/source/inspect/video-QA path as standalone COMPOSE while still letting the assembler own narration and loudness.+- **generate** → `stage-generate` (+ `stage-consistency` for recurring characters): only AFTER gate C. `generate_video`/`generate_image` → `project/assets/<id>.mp4`. Generate at most ~4 shots in flight (the `run_worker` fan-out cap — do not assume unlimited parallelism); a failed shot retries at most twice without blocking the batch, then stays failed with a note instead of burning further billable attempts. Per `stage-consistency`: feed each shot the segment's `refs` (locked portrait + the prior same-scene shot's last frame) and honor its `variation_type`, then extract this shot's last frame to carry the look forward so multi-shot characters do not drift.- **provided** → use `spec.asset_id` as-is (probe it first; conform aspect/fps if needed).Billable `generate` segments must not run before gate C has confirmed the count from `cost_estimate`. Produce cheap/free segments (edit, compose, provided) freely.@@ -38,14 +38,14 @@ Assemble deterministically, bottom-up. This tiered order is the default; it is p1. **Primary track** — `stage-edit edit_video --op concat` the primary-layer `produced_path`s in `order` → `project/render/primary.mp4`. Conform aspect/fps on the way in if sources differ.2. **Overlays / bg** — for each overlay/bg segment, `stage-edit edit_video --op overlay` its part onto the primary over the window of the segment named in `over` (title cards, lower-thirds, logos). Composed layers are VISUAL-ONLY — they must not carry their own narration audio. **This includes a compose segment that IS the primary track (a full-video composition): render it SILENT — do not put a narration `<audio>` in its `index.html`. The assembler owns narration (tier 3), so a composition that bakes it in would mean narration is added TWICE (the "two voices" defect).**-3. **Narration — added EXACTLY ONCE, here.** If `tracks.narration` exists, `generate_speech` each line with the planned `voice` and write each line's `produced_path` back (so a later edit can re-voice ONE line alone), then add them in ONE `stage-edit edit_video --op mix` call using `--audio-segments` — one entry per line, each at its `start_sec` — so each line is delayed onto its scene (per-line placement; do NOT pre-bake one continuous narration file, that destroys per-line alignment and separability). The mix DEFAULTS to `on_existing_audio:"reject"`: if the base already has an audio track it FAILS with `E_EDIT_BASE_HAS_AUDIO` — that means a compose segment baked narration into its render; go back and re-render that segment SILENT (remove its narration `<audio>`), then re-mix. RUN THE COVERAGE CHECK on the result: mix reports whether the voiceover covers the video and flags an uncovered tail or silent lead-in — fix a desync before the draft, do not ship a voiceover that quits halfway. For a clip that already has lip-synced speech (a talking-head generate clip), KEEP its built-in audio — never synthesize a narration over a speaking mouth; if you must add music under it, that is a deliberate layer (`--on-existing-audio mix`), not a second voice.+3. **Narration — added EXACTLY ONCE, here.** If `tracks.narration` exists, re-check line length against `target_sec` before synthesis; shorten over-budget lines in `project/plan.json` while preserving meaning. Then `generate_speech` each line with the planned `voice` and write each line's `produced_path` back (so a later edit can re-voice ONE line alone). Aim for one TTS call per line; allow at most one shortened retry after a real fit failure. Add the produced lines in ONE `stage-edit edit_video --op mix` call using `--audio-segments` — one entry per line, each at its `start_sec` — so each line is delayed onto its scene (per-line placement; do NOT pre-bake one continuous narration file, that destroys per-line alignment and separability). The mix DEFAULTS to `on_existing_audio:"reject"`: if the base already has an audio track it FAILS with `E_EDIT_BASE_HAS_AUDIO` — that means a compose segment baked narration into its render; go back and re-render that segment SILENT (remove its narration `<audio>`), then re-mix. RUN THE COVERAGE CHECK on the result: mix reports whether the voiceover covers the video and flags an uncovered tail or silent lead-in — fix a desync before the draft, do not ship a voiceover that quits halfway. An INTENDED music-only or silent tail (e.g. a CTA end card) is allowed, but state it explicitly in the Gate D note as acceptable-or-change, never leave it as a surprise. For a clip that already has lip-synced speech (a talking-head generate clip), KEEP its built-in audio — never synthesize a narration over a speaking mouth; if you must add music under it, that is a deliberate layer (`--on-existing-audio mix`), not a second voice.4. **Music** — add `tracks.music` ducked under narration by the planned amount.5. **Captions** — turn `tracks.captions.lines` (`{text, start_sec, target_sec}`) into a `.srt`, then `stage-edit edit_video --op burnsubs`. Captions are DATA in the plan — burned ONLY here at assemble — so a later typo fix is a one-line edit re-burned, never a re-render of the picture. If `burnsubs` fails because the runtime ffmpeg lacks subtitle filter support, stop and report that blocker; do not hand-write a fallback `ffmpeg` graph, do not use `-loop 1` PNG subtitle overlays, and do not recompose the whole video just to fix captions.-6. **Loudness** — `stage-edit edit_video --op loudness` and confirm the mix sits near the targets in `video-craft` §7 (~−14 LUFS integrated, true-peak ≤ ~−1 dBTP). Re-mix if it is off.+6. **Loudness** — run `stage-edit edit_video --op normalize_loudness --input project/render/draft.mp4 --output project/render/video.mp4`. It normalizes to the `video-craft` §7 targets (~−14 LUFS integrated, true-peak ≤ ~−1 dBTP) and returns the measured loudness; only fall back to `--op loudness` when you are diagnosing an existing file without writing a deliverable.Apply the plan's `style_kit` for cohesion: composed layers (titles/captions/cards) use its `palette` + `fonts`. A single `lut` graded across all clips is what unifies tonally mixed sources — until a grade op is available, keep mixed sources close at capture/trim and lean on the shared palette + consistent captions for cohesion rather than promising a uniform grade.-Output `project/render/draft.mp4`.+Output `project/render/video.mp4` as the deliverable; `project/render/draft.mp4` is the pre-normalized intermediate.## Director judgment (end-to-end assembly)@@ -69,8 +69,8 @@ Before showing the draft, run the QA pass and write `project/render_report.json`- **technical_probe** — `stage-edit edit_video --op probe` the draft (real duration / resolution / fps / audio present); confirm it matches the plan's aspect + total.- **promise_preservation** — run `"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-plan video_plan -- --op promise_check --plan project/plan.json --probe-produced`. At gate D this probes each primary segment's `produced_path` and computes the REAL primary-track motion ratio vs. `motion_min_ratio` plus the `source_required` invariant; missing/unreadable produced media or a fail means **"slideshow / promise broken" — do not deliver**. Send it back (below). Do not eyeball this; let the numbers decide.- **visual_spotcheck** — extract ~4 frames across the draft (`stage-edit edit_video --op extract_frame`) and read them for upside-down / garbled-caption / empty / wrong-product frames. Read them yourself if you are multimodal; if you cannot see images, record the spot-check as `unverified` and proceed — do not invent what the frames show.-- **audio_spotcheck** — the `op="loudness"` numbers + the narration coverage result from step 2 (uncovered tail / silent lead-in).-- **transcript_comparison** (when there is narration) — optionally `stage-edit analyze_media --op transcribe` the draft and confirm the spoken words match the planned narration lines.+- **audio_spotcheck** — the `op="normalize_loudness"` measured loudness numbers + the narration coverage result from step 2 (uncovered tail / silent lead-in).+- **transcript_comparison** (when there is narration) — optionally transcribe the draft with `video_studio` `op: "speech.transcribe"`, then confirm the spoken words match the planned narration lines.Each section carries `pass` / `warn` / `fail` + a one-line reason. Then present the draft `[video]` + the report's headline findings at **gate D**.diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/SKILL.md b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/SKILL.mdindex 0f0ba094..b80e0033 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/SKILL.md+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/SKILL.md@@ -1,24 +1,115 @@---ownerAgent: 79df9cc89f5fname: stage-compose-description_zh: HyperFrames HTML 视频合成的编写知识——如何写一个 composition(index.html)、用时间线驱动动画、声明画幅与时长,再渲染成 mp4;解说/动画/动态图形/字幕叠加的核心技能。-description_en: Authoring knowledge for HyperFrames HTML video compositions — how to write an index.html composition, drive animation from a timeline, declare canvas + duration, then render to mp4; core skill for explainer/animation/motion-graphics/caption work.+min_app_version: "1.5.1"+description_zh: Orkas HTML 视频合成的编写知识——如何写一个 composition(index.html)、用时间线驱动动画、声明画幅与时长,再渲染成 mp4;解说/动画/动态图形/字幕叠加的核心技能。+description_en: Authoring knowledge for Orkas HTML video compositions — how to write an index.html composition, drive animation from a timeline, declare canvas + duration, then render to mp4; core skill for explainer/animation/motion-graphics/caption work.category: creation---# stage-compose-How to author a **HyperFrames** HTML composition and turn it into a video. Host-neutral: this skill describes the artifact you produce and the outcome you want (a rendered mp4). In Orkas, render and QA run through the `stage-compose render_composition` skill script, not a direct tool call.+How to author an Orkas HTML composition and turn it into a video. Host-neutral: this skill describes the artifact you produce and the outcome you want (a rendered mp4). In Orkas, composition lint/inspect/draft/render runs through the built-in `video_studio` tool. Compatibility is enforced before install by the marketplace `min_app_version` field on the agent/skill.-## How to call the render script+For visual direction, apply `frontend-design` before writing the design contract. If the user provides a DESIGN.md, brand guide, reference site, screenshot, Figma notes, or explicit named style, apply `design-system-importer` to convert that source into compact VideoStudio tokens. `composition-design-review` is a bounded post-draft sanity check for design-sensitive work; it must not replace `--op draft` QA or create an open-ended redesign loop.-```bash-"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-compose render_composition -- --op inspect --composition-dir project/composition-"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-compose render_composition -- --op lint --composition-dir project/composition-"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-compose render_composition -- --op render --composition-dir project/composition --output project/render/draft.mp4 --quality draft+## Fast COMPOSE runbook++After Gate B approves the script/storyboard, keep the production turn narrow:++1. Read only the approved `project/script.md`, `project/shotlist.json`, and this skill if not already loaded for the current turn. Also read `frontend-design`; read `design-system-importer` only when a concrete style source or explicit named reference exists. Do not read `composition-design-review` until the draft returns `ok: true` and its trigger applies.+2. If standalone narration is needed, call `generate_speech` once to `project/composition/assets/narration.mp3`.+3. Write `project/composition/design-contract.json`, then model-author `project/composition/index.html` directly. For narrated work, also write `project/composition/scene-map.json` from the approved script/shotlist so timing QA can verify voiceover-to-visual alignment. If narration line timing is known, write `project/composition/narration-map.json`.+4. Decide whether to open the optional HTML Preview Gate before rendering mp4. Use the preview gate when expected render rework is expensive: target duration >= 45s, scene count >= 7, render cost is likely slow, or the composition has dense text, complex SVG/GSAP, many branded/supplied assets, or a prior draft failure. Skip it for short/simple work: target duration < 20s, scene count <= 4, no narration/timing complexity, and no obvious visual-risk signal. The subject category alone never forces the preview gate.+5. If the HTML Preview Gate is needed, run `video_studio` `op: "composition.inspect"` and `op: "composition.snapshot"` to `project/composition/preview/first-frame.png`, then show the first-frame image, inspect headline, `index.html` path, and why preview was inserted. Options: approve HTML preview, revise HTML/design, or render draft anyway. Stop. On approval, continue to the draft command. On revise, modify only `design-contract.json`, `scene-map.json`, or `index.html`, then rerun inspect/snapshot and reopen the same preview gate.+6. Run the draft command with `video_studio` `op: "composition.draft"`. Before rendering, the production path prepares declared local vendor assets, checks design-contract/scene-map/HTML consistency, blocks remote runtime resources, verifies local assets, checks shotlist/source alignment, and checks narration mapping. Then it runs lint, inspect, render, audio/media QA, sampled-frame QA, and writes one QA report.+7. If the draft command fails, repair the design contract, scene-map, or HTML, then run it again. The draft script enforces one initial failed draft plus at most two repair passes through `project/composition/qa/draft-repair-state.json`. The second repair pass is allowed and returns the real failing check if it still fails, with `repair_budget.budget_exhausted: true`; any later draft attempt returns `E_REPAIR_BUDGET_EXCEEDED`. Stop and report the blocker instead of continuing to patch.+8. If the draft command returns `ok: true`, run `composition-design-review` only when the approved brief is brand/product/promo/version-update/portfolio work, a `style_source` exists, or sampled frames show a visible design risk. Only concrete blockers can prevent Gate D; include `fix`/`polish` notes in Gate D instead of silently looping.+9. Open Gate D after the draft command returns `ok: true` and any triggered design review has no concrete blockers.++The default path is **model-authored HTML -> draft**. Do not write or compile `spec.json`; fixed template compilation is not part of the COMPOSE path because visual quality and extensibility come first.++## How to call the render path++Use the Orkas-native tool call:++```json+{"op":"composition.draft","composition_dir":"project/composition","output_path":"project/render/draft.mp4","quality":"draft","report_path":"project/render/draft-report.json","findings_path":"project/composition/qa/inspect.json"}+```++The tool returns JSON. A tool error means a structural/render-safety issue or Orkas runtime issue must be fixed before continuing.+For draft output, the report includes contract/source alignment, lint, inspect, media probe, loudness, audio timing, and video-frame QA when that path supports them. Video QA samples the first frame and scene starts/mids so an empty hook frame, blank scene boundary, or long frozen sampled run blocks Gate D. It also writes a contact sheet and per-sample evidence frames for design review when available.+Use the draft command's lint and inspect gates before rendering. Lint blocks render-contract errors such as unregistered timelines, missing clip timing, invalid root timing, and imperative media control. In draft mode, visual inspect findings such as small text, text overflow, occlusion, overlap, contrast, and safe-area issues are reported as QA advisories in `steps.inspect.draft_disposition`; they should be fixed when practical, but they do not stop the first mp4 draft from being produced. Palette size remains advisory design feedback, not a hard gate.+When using `findings_path`, the full QA payload is saved to disk; read the file only when the summary points to a specific issue that needs detail.+Do not stop a draft solely because inspect reports visual/readability findings. Stop only when `draft_disposition.blocking_error_count > 0`, lint/contract/audio/source/video QA fails, or the renderer cannot produce media.++## HTML Preview Gate++Use the HTML Preview Gate to avoid expensive mp4 rerenders when visual rework is likely. It is a cost-control gate, not a new creative milestone, and it is only for the COMPOSE line. Decide from expected rework cost:++- **Preview first** when duration >= 45s or scene count >= 7.+- **Preview first** when a 20-45s piece has dense text, multiple chapters, many supplied/brand assets, complex SVG/GSAP motion, tight narration timing, or a prior draft/repair failure.+- **Skip preview** when duration < 20s, scene count <= 4, and the HTML is simple enough that rendering the draft is cheaper than asking for another confirmation.+- Do not use product/promo/version-update labels alone as the trigger. Those labels only contribute to risk when the piece is long, visually dense, or expensive to rerender.++When preview is triggered:++1. Run inspect and write findings:++```json+{"op":"composition.inspect","composition_dir":"project/composition","findings_path":"project/composition/qa/inspect-preview.json"}+```++2. Run a first-frame snapshot:++```json+{"op":"composition.snapshot","composition_dir":"project/composition","output_path":"project/composition/preview/first-frame.png"}+```++3. Open the gate with the snapshot image, the `index.html` path, and a compact status line:+ - reason for preview: duration / scene count / complexity / prior failure+ - inspect headline: blocking count or main advisory+ - what approval means: render mp4 draft next++4. If the user revises, edit the design contract, scene-map, or HTML, then rerun inspect + snapshot. Keep this loop lightweight; do not synthesize new narration or render mp4 during HTML preview.++The HTML Preview Gate does not replace the mp4 draft. It cannot validate audio muxing, final encoded video quality, sampled-frame video QA, or exact narration pacing. After approval, always run `composition.draft` and open Gate D with the video.++## Scene map for QA++For narrated or tightly timed work, write `project/composition/scene-map.json` beside `index.html`. It is not a template; it is the audit map that lets the draft command verify timing and source alignment while the model keeps full control of HTML/CSS/SVG/GSAP.++```json+{+ "canvas": { "width": 1920, "height": 1080, "duration": 60, "language": "en" },+ "audio": { "narration": "assets/narration.mp3" },+ "source_alignment": { "merge_reason": "optional when combining approved shotlist beats" },+ "scenes": [+ {+ "id": "hook",+ "start": 0,+ "duration": 5,+ "headline": "Orkas 1.5.0",+ "narration": "A concise line or narration_ref for this exact window.",+ "source_shots": ["s01"]+ }+ ]+}+```++If the approved shotlist beat is intentionally merged into a longer visual scene, add `source_alignment.merge_reason` or per-scene `source_shots`. When audio exists, every scene must include either concise `narration` text or a `narration_ref`/`source_shots` mapping to the approved script/shotlist.++When TTS or a transcription step gives line timing, add `project/composition/narration-map.json`:++```json+{+ "lines": [+ { "id": "n01", "start": 0.0, "duration": 3.2, "text": "Meet Orkas 1.5.0." }+ ]+}```-The script returns JSON. A non-zero exit means the composition must be fixed before continuing.+Then use `"narration_ref": "n01"` or a comma-separated list on the matching scene. Draft QA uses this map before falling back to coarse text-length timing, so voiceover/visual drift is caught earlier.## Composition contract (the minimum that renders)@@ -36,7 +127,7 @@ Canonical minimal `index.html` (16:9, 10s):<head><meta charset="UTF-8" /><meta name="viewport" content="width=1920, height=1080" />- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>+ <script src="./assets/vendor/gsap.min.js"></script><style>* { margin: 0; padding: 0; box-sizing: border-box; }html, body { width: 1920px; height: 1080px; overflow: hidden; background: #000; }@@ -68,6 +159,55 @@ Canonical minimal `index.html` (16:9, 10s):- **On-screen text**: keep it inside the frame with padding; large, high-contrast type; one idea per scene.- **Assets**: reference images/footage produced upstream by relative path inside the composition dir (e.g. `./assets/shot1.png`).- **Timing**: position every tween on the GSAP timeline with an explicit time so it is reproducible; the total of `data-duration` on the root is the final length.+- **SVG-first visual layer**: prefer inline SVG for non-text motion graphics such as diagrams, connectors, nodes, progress paths, charts, orbit lines, icon-like marks, and background geometry. Keep readable prose in normal HTML text boxes unless the SVG text is large, simple, and verified.+- **Use GSAP only when time-based motion is needed**: static SVG, CSS layout, and simple held states do not need GSAP. When animation is needed, keep GSAP as the timeline/orchestration layer that animates SVG groups or a small set of HTML containers. Do not build dozens of absolutely positioned HTML nodes/cards/lines when one SVG graph can carry the visual.+- **No remote runtime resources**: `index.html` must not load CDN scripts, remote fonts, remote images, or remote CSS during render. Fetch or copy required runtime files into `project/composition/assets/` during authoring, then reference them with relative paths such as `./assets/vendor/gsap.min.js`. Draft QA blocks `http://` and `https://` references.+- **Local GSAP vendor**: if `index.html` references `./assets/vendor/gsap.min.js`, the render script prepares the built-in offline GSAP vendor in the workspace composition directory. It auto-replaces the old managed VideoStudio shim when found, keeps compatible existing GSAP files, and blocks incompatible user-provided vendor files before rendering. Do not manually patch `assets/vendor/gsap.min.js` inside a composition; fix HTML/scene-map/design-contract issues, or report the vendor blocker.++## Design contract before HTML++Before writing `project/composition/index.html`, write `project/composition/design-contract.json`. This is an internal artifact, not a user gate. Treat it as the composition budget, not a style note.++The contract must declare these budgets compactly:+- `canvas`: aspect ratio, width, height, duration, fps, language.+- `aesthetic`: from `frontend-design`: subject world, audience, one job, tone, signature device, aesthetic risk, and anti-template check.+- `style_source`: from `design-system-importer` when a DESIGN.md, brand guide, screenshot, reference site, Figma notes, existing app UI, or explicit named style was used. Omit when there is no external style source.+- `scenes`: start/duration, approved on-screen copy, narration timing, visual focus, and layout type.+- `layout_boxes`: safe text box, visual box, caption box, and maximum label count per scene.+- `typography_tokens`: title/body/caption/label floors plus type roles. Default floors for 1920x1080: title >=72px, body/supporting text >=42px, safe margin >=96px, no more than two text blocks and about 12-16 English words per scene. Preserve the same readability intent for 9:16 and 1:1.+- `color_tokens`: named baseline values with rationale: background, surface, text, muted, primary accent, and any purposeful supporting accents the approved visual idea needs.+- `motion_budget`: max animated groups per scene, allowed transitions, easing, which SVG/HTML groups move, and what each motion communicates.+- `scene_variation`: how the sequence avoids three near-identical layouts, transitions, or card/title scenes in a row.+- `audio`: narration ownership, audio path, target duration, and whether the composition must render silent for assemble.++The palette is a design contract, not a mechanical hue cap. The HTML/CSS/SVG should derive its main system from `color_tokens` through CSS variables or equivalent structured constants, but do not flatten or recolor a scene just to reduce a static color count. Add purposeful local colors when they improve hierarchy, brand fidelity, data meaning, or scene variation, and keep them named or easy to audit.++The draft command enforces the contract before rendering. It blocks when:+- `design-contract.json` is missing or invalid.+- Root `data-width`, `data-height`, or `data-duration` differ from the contract or scene-map.+- Scene timing falls outside the composition duration or overlaps unintentionally.+- Declared scene headline/title/on-screen copy is missing from `index.html`.+- HTML references a missing local asset, an absolute path, an asset outside the composition directory, or a remote runtime URL.+- HTML calls `gsap.*` without loading `./assets/vendor/gsap.min.js`.++Typography and layout budgets are binding for every readable element, including badges, pills, labels, captions, cards, nodes, and microcopy. Do not put long labels in circles or small decorative nodes; use larger cards, capsules, or nearby labels. If approved copy cannot fit safely, shorten on-screen text without changing meaning. Ask the user only when the message would change.++Run a pre-code anti-template check from `frontend-design`: name the first generic design move you rejected and the brief-specific replacement. If you cannot name that replacement, the contract is not ready. When `style_source` exists, also name what was adapted, simplified, and not copied from the reference.++## Inspect and repair policy++Run the draft command before any user-facing render. If lint, contract/source/audio timing, video-frame QA, or inspect `draft_disposition.blocking_error_count` is not OK, repair once and run the draft command again. Visual inspect advisories are not blockers for the first mp4 draft; include them in Gate D notes and repair only the highest-impact issues before looping. A second repair pass is allowed only when the remaining blockers are fewer and clearly localized. If the script returns `E_REPAIR_BUDGET_EXCEEDED`, do not delete the repair state or run another draft command; show a concise blocker with the report path and the last error.++Repairs should address the cause, not just the symptom:+- `FONT_TOO_SMALL`: reduce text density, shorten copy, enlarge/reflow containers, or move labels out of small shapes. Do not simply increase every font size if that creates overflow.+- `missing_timeline_registry`, `gsap_timeline_not_registered`: register a paused GSAP timeline on `window.__timelines[compositionId]`, using the exact root `data-composition-id`.+ - `timed_element_missing_clip_class`, `root_composition_missing_data_start`, `media_missing_data_start`, `imperative_media_control`: let the renderer own timing and media playback through `data-start`, `data-duration`, `.clip`, and media data attributes. Do not drive render-critical timing with custom `play()`, `pause()`, `currentTime`, timers, or a custom `seekTo` API.+- `text_occluded`, `text_box_overflow`, `content_overlap`: restructure the scene layout or regenerate the affected scene from the contract's boxes. Do not rely on small numeric nudges.+- `STATIC_FRAME_RUN`: fix the timeline registration, scene clip timing, or scene variation; do not deliver a draft whose sampled frames are identical across multiple scenes.++If repair makes blocking errors worse, or if structural/render-safety blockers remain after the allowed repair passes, stop with a concise blocker report and the findings path. Regenerating `index.html` counts as one of the two repair passes; do it only when the failure is structural, not as an open-ended loop. If only visual advisories remain and `--op draft` returned `ok: true`, present the mp4 draft with QA notes instead of silently looping. Repair the design contract, scene-map, or hand-authored HTML directly; do not introduce `spec.json` as a workaround.++After the draft command returns `ok: true`, run `composition-design-review` only when its trigger applies. Use `video_qa.contact_sheet` and `video_qa.frame_paths` from the draft report as the primary visual evidence. A review blocker must be visible in a specific scene/frame and must break readability, the approved promise, required brand/style tokens, motion timing, or asset safety. Allow at most one localized repair and re-draft for those blockers. Treat `fix` findings as Gate D notes unless they are trivial to repair in the same pass. Treat `polish` as optional notes only.## Narration / audio track@@ -83,13 +223,16 @@ To give a STANDALONE explainer a voiceover: synthesize the narration to an audio```- Place the `<audio>` inside the root composition div. `data-duration` should cover the spoken length; size the scene timing to the narration, not the other way around.+- Before the first TTS call, estimate the script length from `video-craft` cadence (~150-160 wpm for explainers) and trim the text to the approved target duration. Do NOT synthesize multiple full versions just to discover timing. One full TTS pass plus at most one shortened retry is the limit; after that, shorten text or retime the plan explicitly.+- If `generate_speech` fails, never silently continue: tell the user, then either fix and retry the narration or explicitly proceed silent with that stated at the gate. Draft QA flags a contract that declares narration while the composition has no audio (`NARRATION_DECLARED_BUT_SILENT`) — do not present such a draft as if it were complete.+- Use a project path such as `project/composition/assets/narration.mp3` for `generate_speech`. It resolves under the current workspace, keeping the composition self-contained instead of writing throwaway audio under chat attachments.- For background music plus voiceover, use two `<audio>` tracks with different `data-track-index` and lower the music `data-volume` (e.g. 0.2).- Keep narration audio inside the composition dir so the render is self-contained.- **Talking-head caveat:** when this composition is being overlaid onto AI-generated talking-head footage that already has **lip-synced built-in speech** (generation line), do NOT add a narration `<audio>` track. The renderer's muxed audio replaces the clip's own voice, so a synthesized narration would desync from the mouth. Use this composition for captions / lower-thirds only and let the clip's built-in audio stand (background music at low volume is fine; spoken narration is not).## Render (the outcome)-Produce the finished video by rendering the composition **directory** to an mp4. Iterate at draft quality, then do one high-quality pass once the layout and timing pass review. (Orkas: `stage-compose render_composition --op render` with the composition dir and an output path.)+Produce the finished video by rendering the composition **directory** to an mp4. Iterate at draft quality, then do one high-quality pass once the layout and timing pass review. For the user-facing final, use `video_studio` `op: "composition.draft"` with `quality: "high"` and `output_path: "project/render/final.mp4"` so the same contract, source, inspect, audio, and video QA gates still run on the final export. Use render-only ops only as a narrow diagnostic render when QA has already identified the blocker.## Director judgment (compose line)@@ -97,11 +240,14 @@ Craft calls specific to designed/animated explainers, on top of the shared craft- **One concept per visual chapter** — don't stack two ideas in one scene; give each its own build.- **Concrete before abstract** — real data, diagrams, steps before a metaphor; the metaphor only lands once the concrete version is understood.+- **Aesthetic thesis before styling** — use `frontend-design` to choose one signature visual device that comes from the subject matter; spend distinctiveness there and keep the rest disciplined.+- **Reference styles become tokens** — use `design-system-importer` for DESIGN.md/brand/reference input, then adapt the tokens to video safe zones and motion. Do not clone protected layouts or assets.+- **Design review is a last-mile guardrail** — use `composition-design-review` only when its trigger applies. Block only on concrete visible failures; template feel, hierarchy, and polish issues that do not break the promise go to the Gate D note.- **Render exact text as real text** — stats, names, CTAs are typed into the composition, never baked into AI imagery (which hallucinates numbers and can't be corrected).- **Build to the narration words**, not arbitrary beats; hold a fully-built scene/chart ≥ 2–3 s before moving on.- **Vary scene types** — no three near-identical layouts in a row; alternate full-frame / split / diagram / quote.- **Spoken/readable captions live in the plan's `tracks.captions.lines` (data), NOT burned into this composition** — the assembler burns them via `burnsubs` at the end, so a later typo fix is a one-line edit, not a re-render of the whole composition. Only a PURELY DECORATIVE caption treatment that IS the visual design (kinetic highlight sweeps, word-by-word reveals) may live inside the composition — and when it does, tell the user that styled caption is part of the picture and not separately editable later. Keep ordinary subtitles as caption-track data, synced to the voice.-- The host may surface craft-threshold warnings on the composition (small font sizes, oversized palette) when you QA it before rendering — fix those before the final render. (Orkas: `stage-compose render_composition --op lint` / `--op inspect`.)+- The host may surface craft-threshold warnings on the composition. In draft mode, small readable text is a QA advisory rather than a render blocker; oversized palette is advisory and should be judged against the design thesis, brand, and scene clarity rather than mechanically recoloring the whole piece. (Orkas: use `video_studio` `op: "composition.draft"`.)## Constraintsdiff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/lib/video_render_core.cjs b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/lib/video_render_core.cjsindex 9dd7101d..03299780 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/lib/video_render_core.cjs+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/lib/video_render_core.cjs@@ -1,3 +1,10 @@-var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var video_render_exports={};__export(video_render_exports,{qaComposition:()=>qaComposition,renderComposition:()=>renderComposition});module.exports=__toCommonJS(video_render_exports);var fs3=__toESM(require("node:fs/promises"));var path3=__toESM(require("node:path"));var import_node_child_process=require("node:child_process");var fs2=__toESM(require("node:fs"));var path2=__toESM(require("node:path"));var path=__toESM(require("node:path"));var fs=__toESM(require("node:fs"));function scriptPathIsFile(p){try{return fs.statSync(p).isFile()}catch{return false}}function scriptPathIsDir(p){try{return fs.statSync(p).isDirectory()}catch{return false}}function looksLikePcRoot(dir){return scriptPathIsFile(path.join(dir,"package.json"))&&scriptPathIsDir(path.join(dir,"resources"))&&scriptPathIsDir(path.join(dir,"src"))}function resolvePcRoot(){if(process.env.ORKAS_PC_DIR)return path.resolve(process.env.ORKAS_PC_DIR);if(looksLikePcRoot(process.cwd()))return process.cwd();const cwdPc=path.join(process.cwd(),"PC");if(looksLikePcRoot(cwdPc))return cwdPc;let dir=__dirname;for(;;){if(looksLikePcRoot(dir))return dir;const parent=path.dirname(dir);if(parent===dir)break;dir=parent}return path.resolve(__dirname,"..","..")}var PC_ROOT=resolvePcRoot();var SRC_ROOT=path.join(PC_ROOT,"src");var PROJECT_ROOT=path.resolve(PC_ROOT,"..");if(!process.env.ORKAS_WORKSPACE_ROOT){throw new Error("paths.ts: ORKAS_WORKSPACE_ROOT not set. index.ts must run resolveInstallContainer + set the env var before importing paths.")}var WS_ROOT=path.resolve(process.env.ORKAS_WORKSPACE_ROOT);var USERS_FILE=path.join(WS_ROOT,"users.json");var WINDOW_STATE_FILE=path.join(WS_ROOT,"window-state.json");var LOGS_DIR=path.join(WS_ROOT,"logs");var VENV_ROOT=path.join(WS_ROOT,"venv");var PYTHON_VENV_ROOT=path.join(VENV_ROOT,"python");var PYTHON_VENV_BIN_DIR=path.join(PYTHON_VENV_ROOT,"bin");var PYTHON_VENV_CACHE_DIR=path.join(PYTHON_VENV_ROOT,"cache");var PYTHON_VENV_UV_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"uv");var PYTHON_VENV_PIP_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"pip");var NODE_VENV_ROOT=path.join(VENV_ROOT,"node");var NODE_NPM_CACHE_DIR=path.join(NODE_VENV_ROOT,"cache","npm");var NODE_NPM_PREFIX_DIR=path.join(NODE_VENV_ROOT,"prefix");var NODE_NPM_GLOBAL_BIN_DIR=process.platform==="win32"?NODE_NPM_PREFIX_DIR:path.join(NODE_NPM_PREFIX_DIR,"bin");function runtimeResourcesDir(){const rp=process.resourcesPath;if(rp&&!rp.includes(`${path.sep}node_modules${path.sep}electron${path.sep}`)){return path.join(rp,"runtime")}return path.join(PC_ROOT,"resources","runtime")}var DEFAULT_USER_WORKSPACE=path.join(WS_ROOT,"..","userWorkSpace");function ensureTopLevelLayout(){for(const d of[LOGS_DIR,VENV_ROOT,DEFAULT_USER_WORKSPACE]){fs.mkdirSync(d,{recursive:true})}}ensureTopLevelLayout();function isFile(p){if(!p)return false;try{return fs2.statSync(p).isFile()}catch{return false}}function isDir(p){if(!p)return false;try{return fs2.statSync(p).isDirectory()}catch{return false}}function platformKey(platform=process.platform,arch=process.arch){return`${platform}-${arch}`}function pushUnique(out,seen,value){if(!value)return;const resolved=path2.resolve(value);if(seen.has(resolved))return;seen.add(resolved);out.push(resolved)}function runtimeRoots(){const roots=[];const seen=new Set;pushUnique(roots,seen,process.env.ORKAS_RUNTIME_DIR);pushUnique(roots,seen,runtimeResourcesDir());return roots}function runtimeVariantDirs(kind){const dirs=[];for(const runtimeRoot of runtimeRoots()){const root=path2.join(runtimeRoot,kind);dirs.push(path2.join(root,"current"),path2.join(root,platformKey()))}return[...dirs]}function resolvePythonExecutable(){const configured=process.env.ORKAS_BUNDLED_PYTHON||process.env.ORKAS_PYTHON;if(isFile(configured))return configured;const names=process.platform==="win32"?["python.exe",path2.join("python","python.exe")]:[path2.join("python","bin","python3"),path2.join("python","bin","python"),path2.join("bin","python3"),path2.join("bin","python")];for(const dir of runtimeVariantDirs("python")){for(const name of names){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}}return void 0}function resolveUvExecutable(){const configured=process.env.ORKAS_BUNDLED_UV||process.env.ORKAS_UV;if(isFile(configured))return configured;const name=process.platform==="win32"?"uv.exe":"uv";for(const dir of runtimeVariantDirs("uv")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}return void 0}function resolveNodeExecutable(){const configured=process.env.ORKAS_BUNDLED_NODE;if(isFile(configured))return configured;const names=process.platform==="win32"?["node.exe"]:[path2.join("bin","node")];for(const dir of runtimeVariantDirs("node")){for(const name of names){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}}return void 0}function resolveFfmpegBinary(kind){const envName=kind==="ffmpeg"?"ORKAS_BUNDLED_FFMPEG":"ORKAS_BUNDLED_FFPROBE";const configured=process.env[envName];if(isFile(configured))return configured;const name=process.platform==="win32"?`${kind}.exe`:kind;for(const dir of runtimeVariantDirs("ffmpeg")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate;const nested=path2.join(dir,"bin",name);if(isFile(nested))return nested}return void 0}function bundledFfmpegPaths(){const result={};const ffmpeg=resolveFfmpegBinary("ffmpeg");const ffprobe=resolveFfmpegBinary("ffprobe");if(ffmpeg)result.ffmpeg=ffmpeg;if(ffprobe)result.ffprobe=ffprobe;return result}function pushPathDir(out,seen,dir){if(!isDir(dir))return;const resolved=path2.resolve(dir);const key=process.platform==="win32"?resolved.toLowerCase():resolved;if(seen.has(key))return;seen.add(key);out.push(resolved)}function bundledRuntimePathEntries(){const entries=[];const seen=new Set;const python=resolvePythonExecutable();if(python){const pythonDir=path2.dirname(python);pushPathDir(entries,seen,pythonDir);pushPathDir(entries,seen,path2.join(pythonDir,"Scripts"));pushPathDir(entries,seen,path2.join(pythonDir,"bin"))}const uv=resolveUvExecutable();if(uv)pushPathDir(entries,seen,path2.dirname(uv));const node=resolveNodeExecutable();if(node)pushPathDir(entries,seen,path2.dirname(node));return entries}function bundledNodeExecutable(){return resolveNodeExecutable()}function bundledNpxCli(){const node=resolveNodeExecutable();if(!node)return void 0;const dir=path2.dirname(node);const candidates=process.platform==="win32"?[path2.join(dir,"node_modules","npm","bin","npx-cli.js")]:[path2.join(dir,"..","lib","node_modules","npm","bin","npx-cli.js")];for(const c of candidates)if(isFile(c))return c;return void 0}var HYPERFRAMES_SPEC="[email protected]";function resolveHyperframesRunner(){const node=bundledNodeExecutable();const npxCli=bundledNpxCli();if(!node||!npxCli)return null;return{node,npxCli}}function buildHyperframesEnv(){const env={...process.env};const sep2=process.platform==="win32"?";":":";const prepend=[...bundledRuntimePathEntries()];prepend.push(PYTHON_VENV_BIN_DIR);if(prepend.length)env.PATH=[...prepend,env.PATH||""].filter(Boolean).join(sep2);const ff=bundledFfmpegPaths();if(ff.ffmpeg)env.HYPERFRAMES_FFMPEG_PATH=ff.ffmpeg;if(ff.ffprobe)env.HYPERFRAMES_FFPROBE_PATH=ff.ffprobe;env.NPM_CONFIG_CACHE=NODE_NPM_CACHE_DIR;env.NPM_CONFIG_PREFIX=NODE_NPM_PREFIX_DIR;env.NPM_CONFIG_FUND="false";env.NPM_CONFIG_AUDIT="false";env.NPM_CONFIG_UPDATE_NOTIFIER="false";env.NPM_CONFIG_PREFER_OFFLINE="true";env.NPM_CONFIG_FETCH_RETRIES="4";return env}var FONT_FLOOR_AT_1080=40;var PALETTE_SOFT_MAX=8;function readCanvasHeight(html,override){if(typeof override==="number"&&Number.isFinite(override)&&override>0)return override;const m=html.match(/data-height\s*=\s*["']?(\d{2,5})/i);const h=m?Number(m[1]):NaN;return Number.isFinite(h)&&h>0?h:1080}function fontFloor(height){return Math.max(1,Math.round(FONT_FLOOR_AT_1080*height/1080))}function smallFontSizesPx(html,floor){const out=new Set;const re=/font-size\s*:\s*([\d.]+)px\b/gi;let m;while((m=re.exec(html))!==null){const px=Number(m[1]);if(Number.isFinite(px)&&px>0&&px<floor)out.add(px)}return[...out].sort((a,b)=>a-b)}function expandHex(h){if(h.length===3)return h.split("").map(c=>c+c).join("");if(h.length===4)return h.slice(0,3).split("").map(c=>c+c).join("");return h.slice(0,6)}function isNeutralHex6(h){return h.slice(0,2)===h.slice(2,4)&&h.slice(2,4)===h.slice(4,6)}function isNeutralColorFn(s){if(s.includes("transparent"))return true;const rgb=s.match(/^rgba?\((\d+),(\d+),(\d+)/);if(rgb)return rgb[1]===rgb[2]&&rgb[2]===rgb[3];const hsl=s.match(/^hsla?\(\d+(?:deg)?,(\d+(?:\.\d+)?)%/);if(hsl)return Number(hsl[1])===0;return false}function chromaticColors(html){const colors=new Set;const hexRe=/#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})\b/gi;let m;while((m=hexRe.exec(html))!==null){const six=expandHex(m[1].toLowerCase());if(!isNeutralHex6(six))colors.add(`#${six}`)}const fnRe=/\b(?:rgb|rgba|hsl|hsla)\([^)]*\)/gi;while((m=fnRe.exec(html))!==null){const key=m[0].toLowerCase().replace(/\s+/g,"");if(!isNeutralColorFn(key))colors.add(key)}return colors}function lintCompositionCraft(html,opts){const findings=[];if(!html)return findings;const height=readCanvasHeight(html,opts?.canvasHeight);const floor=fontFloor(height);const small=smallFontSizesPx(html,floor);if(small.length){const shown=small.slice(0,6).map(n=>`${n}px`).join(", ");const more=small.length>6?`, +${small.length-6} more`:"";findings.push({level:"warn",code:"FONT_TOO_SMALL",message:`Font sizes below the legibility floor (~${floor}px for a ${height}px-tall canvas): ${shown}${more}. Raise body text to \u2265 the floor and titles well above it, or it won't read at phone size.`})}const colors=chromaticColors(html);if(colors.size>PALETTE_SOFT_MAX){findings.push({level:"warn",code:"PALETTE_LARGE",message:`${colors.size} distinct chromatic colors in the composition \u2014 aim for \u2264 3\u20135 on screen at once. Re-check each scene: background least-saturated, one accent that reads first.`})}return findings}function formatCraftFindings(findings){if(!findings.length)return"";return["[craft] static threshold checks (advisory, from the video-craft skill):",...findings.map(f=>` - ${f.code}: ${f.message}`)].join("\n")}function redactPaths(text){if(!text)return text;return text.replace(/[A-Za-z]:[\\/][^\s"']*/g,"<path>").replace(/(?:\/[\w.\-]+){2,}\/?/g,"<path>")}function createLogger(moduleName){const scope=String(moduleName||"video-script").trim()||"video-script";const write=(level,message,args)=>{if(process.env.ORKAS_VIDEO_SCRIPT_DEBUG!=="1")return;const line=`[${scope}] ${message}`;if(level==="error")console.error(line,...args);else if(level==="warn")console.warn(line,...args);else if(level==="debug")console.debug(line,...args);else console.info(line,...args)};return{error:(message,...args)=>write("error",message,args),warn:(message,...args)=>write("warn",message,args),info:(message,...args)=>write("info",message,args),debug:(message,...args)=>write("debug",message,args)}}var log=createLogger("video-render");var RENDER_TIMEOUT_MS=20*60*1e3;function buildRenderArgs(p){const args=["render","--output",p.outputAbsPath];if(p.quality)args.push("--quality",p.quality);if(typeof p.fps==="number")args.push("--fps",String(p.fps));if(p.format)args.push("--format",p.format);if(p.variables&&Object.keys(p.variables).length){args.push("--variables",JSON.stringify(p.variables))}return args}function parseTraceLine(line){const idx=line.indexOf("[Render:trace]");if(idx===-1)return null;const jsonStart=line.indexOf("{",idx);if(jsonStart===-1)return null;try{const trace=JSON.parse(line.slice(jsonStart));const phase=typeof trace.phase==="string"?trace.phase:"render";const status=typeof trace.status==="string"?trace.status:"";return{phase:`render.${phase}`,message:status?`${phase} ${status}`:phase}}catch{return null}}async function renderComposition(p){const runner=resolveHyperframesRunner();if(!runner){return{ok:false,errorCode:"E_RENDER_RUNTIME_MISSING",message:"Bundled Node runtime not found; cannot run the HyperFrames renderer."}}const indexHtml=path3.join(p.projectDirAbs,"index.html");try{const st=await fs3.stat(indexHtml);if(!st.isFile())throw new Error("not a file")}catch{return{ok:false,errorCode:"E_RENDER_NO_COMPOSITION",message:`No index.html found in composition dir: ${p.projectDirAbs}`}}await fs3.mkdir(path3.dirname(p.outputAbsPath),{recursive:true}).catch(()=>{});const env=buildHyperframesEnv();const args=[runner.npxCli,"--yes",HYPERFRAMES_SPEC,...buildRenderArgs(p)];return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process.spawn)(runner.node,args,{cwd:p.projectDirAbs,env,...p.signal?{signal:p.signal}:{}})}catch(err){resolve3({ok:false,errorCode:"E_RENDER_SPAWN",message:err.message});return}const errChunks=[];let stdoutBuf="";let settled=false;let timedOut=false;const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},RENDER_TIMEOUT_MS);const pumpProgress=chunk=>{stdoutBuf+=chunk;let nl;while((nl=stdoutBuf.indexOf("\n"))!==-1){const line=stdoutBuf.slice(0,nl);stdoutBuf=stdoutBuf.slice(nl+1);const ev=parseTraceLine(line);if(ev)p.onProgress?.(ev)}};child.stdout?.on("data",c=>pumpProgress(c.toString("utf8")));child.stderr?.on("data",c=>{const s=c.toString("utf8");errChunks.push(s);pumpProgress(s)});child.stdin?.end();const finish=r=>{if(settled)return;settled=true;clearTimeout(timer);resolve3(r)};child.on("error",err=>{if(p.signal?.aborted){finish({ok:false,errorCode:"E_RENDER_ABORTED",message:"Render aborted."});return}finish({ok:false,errorCode:"E_RENDER_SPAWN",message:err.message})});child.on("close",async code=>{if(timedOut){finish({ok:false,errorCode:"E_RENDER_TIMEOUT",message:`Render timed out after ${RENDER_TIMEOUT_MS}ms.`});return}if(p.signal?.aborted){finish({ok:false,errorCode:"E_RENDER_ABORTED",message:"Render aborted."});return}if(code!==0){const stderr=errChunks.join("").trim();const tail=stderr.slice(-1500);log.warn(`hyperframes render exited ${code}: ${redactPaths(tail.slice(-300))}`);return finish({ok:false,errorCode:"E_RENDER_FAILED",message:`HyperFrames render failed (exit ${code}). ${tail||"No diagnostic output."}`})}const st=await fs3.stat(p.outputAbsPath).catch(()=>null);if(!st||!st.isFile()||st.size===0){return finish({ok:false,errorCode:"E_RENDER_NO_OUTPUT",message:`Render reported success but no output file was produced at ${p.outputAbsPath}.`})}finish({ok:true,path:p.outputAbsPath,bytes:st.size})})})}var QA_TIMEOUT_MS=5*60*1e3;async function qaComposition(op,p){const runner=resolveHyperframesRunner();if(!runner){return{ok:false,errorCode:"E_RENDER_RUNTIME_MISSING",message:"Bundled Node runtime not found."}}const indexHtml=path3.join(p.projectDirAbs,"index.html");const st=await fs3.stat(indexHtml).catch(()=>null);if(!st||!st.isFile()){return{ok:false,errorCode:"E_RENDER_NO_COMPOSITION",message:`No index.html in: ${p.projectDirAbs}`}}const env=buildHyperframesEnv();const args=[runner.npxCli,"--yes",HYPERFRAMES_SPEC,op,"--json"];return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process.spawn)(runner.node,args,{cwd:p.projectDirAbs,env,...p.signal?{signal:p.signal}:{}})}catch(err){resolve3({ok:false,errorCode:"E_QA_SPAWN",message:err.message});return}const out=[];const errOut=[];let settled=false;let timedOut=false;const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},QA_TIMEOUT_MS);child.stdout?.on("data",c=>out.push(c.toString("utf8")));child.stderr?.on("data",c=>errOut.push(c.toString("utf8")));child.stdin?.end();const finish=r=>{if(settled)return;settled=true;clearTimeout(timer);resolve3(r)};child.on("error",err=>{if(p.signal?.aborted)return finish({ok:false,errorCode:"E_QA_ABORTED",message:`${op} aborted.`});finish({ok:false,errorCode:"E_QA_SPAWN",message:err.message})});child.on("close",async()=>{if(timedOut)return finish({ok:false,errorCode:"E_QA_TIMEOUT",message:`${op} timed out.`});if(p.signal?.aborted)return finish({ok:false,errorCode:"E_QA_ABORTED",message:`${op} aborted.`});const findings=out.join("").trim();if(!findings){const stderr=errOut.join("").trim().slice(-1e3);return finish({ok:false,errorCode:"E_QA_NO_OUTPUT",message:`${op} produced no findings. ${stderr}`})}let craft="";try{const html=await fs3.readFile(indexHtml,"utf8");craft=formatCraftFindings(lintCompositionCraft(html))}catch{}finish({ok:true,op,findings:craft?`${findings}+var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var video_render_exports={};__export(video_render_exports,{HEAVY_RENDER_COST:()=>HEAVY_RENDER_COST,LOW_RAM_GB:()=>LOW_RAM_GB,classifyRenderCrash:()=>classifyRenderCrash,degradedFps:()=>degradedFps,estimateRenderCost:()=>estimateRenderCost,isConstrainedMachine:()=>isConstrainedMachine,machineRamGB:()=>machineRamGB,parseRenderDiagnostics:()=>parseRenderDiagnostics,qaComposition:()=>qaComposition,renderComposition:()=>renderComposition,renderCostDecision:()=>renderCostDecision});module.exports=__toCommonJS(video_render_exports);var fs4=__toESM(require("node:fs/promises"));var os=__toESM(require("node:os"));var path3=__toESM(require("node:path"));var import_node_child_process=require("node:child_process");var fs3=__toESM(require("node:fs"));var fs2=__toESM(require("node:fs"));var path2=__toESM(require("node:path"));var path=__toESM(require("node:path"));var fs=__toESM(require("node:fs"));function scriptPathIsFile(p){try{return fs.statSync(p).isFile()}catch{return false}}function scriptPathIsDir(p){try{return fs.statSync(p).isDirectory()}catch{return false}}function looksLikePcRoot(dir){return scriptPathIsFile(path.join(dir,"package.json"))&&scriptPathIsDir(path.join(dir,"resources"))&&scriptPathIsDir(path.join(dir,"src"))}function resolvePcRoot(){if(process.env.ORKAS_PC_DIR)return path.resolve(process.env.ORKAS_PC_DIR);if(looksLikePcRoot(process.cwd()))return process.cwd();const cwdPc=path.join(process.cwd(),"PC");if(looksLikePcRoot(cwdPc))return cwdPc;let dir=__dirname;for(;;){if(looksLikePcRoot(dir))return dir;const parent=path.dirname(dir);if(parent===dir)break;dir=parent}return path.resolve(__dirname,"..","..")}var PC_ROOT=resolvePcRoot();var SRC_ROOT=path.join(PC_ROOT,"src");var PROJECT_ROOT=path.resolve(PC_ROOT,"..");if(!process.env.ORKAS_WORKSPACE_ROOT){throw new Error("paths.ts: ORKAS_WORKSPACE_ROOT not set. index.ts must run resolveInstallContainer + set the env var before importing paths.")}var WS_ROOT=path.resolve(process.env.ORKAS_WORKSPACE_ROOT);var USERS_FILE=path.join(WS_ROOT,"users.json");var WINDOW_STATE_FILE=path.join(WS_ROOT,"window-state.json");var LOGS_DIR=path.join(WS_ROOT,"logs");var VENV_ROOT=path.join(WS_ROOT,"venv");var PYTHON_VENV_ROOT=path.join(VENV_ROOT,"python");var PYTHON_VENV_BIN_DIR=path.join(PYTHON_VENV_ROOT,"bin");var PYTHON_VENV_CACHE_DIR=path.join(PYTHON_VENV_ROOT,"cache");var PYTHON_VENV_UV_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"uv");var PYTHON_VENV_PIP_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"pip");var NODE_VENV_ROOT=path.join(VENV_ROOT,"node");var NODE_NPM_CACHE_DIR=path.join(NODE_VENV_ROOT,"cache","npm");var NODE_NPM_PREFIX_DIR=path.join(NODE_VENV_ROOT,"prefix");var NODE_NPM_GLOBAL_BIN_DIR=process.platform==="win32"?NODE_NPM_PREFIX_DIR:path.join(NODE_NPM_PREFIX_DIR,"bin");function runtimeResourcesDir(){const rp=process.resourcesPath;if(rp&&!rp.includes(`${path.sep}node_modules${path.sep}electron${path.sep}`)){return path.join(rp,"runtime")}return path.join(PC_ROOT,"resources","runtime")}var DEFAULT_USER_WORKSPACE=path.join(WS_ROOT,"..","userWorkSpace");function ensureTopLevelLayout(){for(const d of[LOGS_DIR,VENV_ROOT,DEFAULT_USER_WORKSPACE]){fs.mkdirSync(d,{recursive:true})}}ensureTopLevelLayout();function isFile(p){if(!p)return false;try{return fs2.statSync(p).isFile()}catch{return false}}function isDir(p){if(!p)return false;try{return fs2.statSync(p).isDirectory()}catch{return false}}function platformKey(platform=process.platform,arch=process.arch){return`${platform}-${arch}`}function pushUnique(out,seen,value){if(!value)return;const resolved=path2.resolve(value);if(seen.has(resolved))return;seen.add(resolved);out.push(resolved)}function runtimeRoots(){const roots=[];const seen=new Set;pushUnique(roots,seen,process.env.ORKAS_RUNTIME_DIR);pushUnique(roots,seen,runtimeResourcesDir());return roots}function runtimeVariantDirs(kind){const dirs=[];for(const runtimeRoot of runtimeRoots()){const root=path2.join(runtimeRoot,kind);dirs.push(path2.join(root,"current"),path2.join(root,platformKey()))}return[...dirs]}function resolvePythonExecutable(){const configured=process.env.ORKAS_BUNDLED_PYTHON||process.env.ORKAS_PYTHON;if(isFile(configured))return configured;const names=process.platform==="win32"?["python.exe",path2.join("python","python.exe")]:[path2.join("python","bin","python3"),path2.join("python","bin","python"),path2.join("bin","python3"),path2.join("bin","python")];for(const dir of runtimeVariantDirs("python")){for(const name of names){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}}return void 0}function resolveUvExecutable(){const configured=process.env.ORKAS_BUNDLED_UV||process.env.ORKAS_UV;if(isFile(configured))return configured;const name=process.platform==="win32"?"uv.exe":"uv";for(const dir of runtimeVariantDirs("uv")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}return void 0}function resolveNodeExecutable(){const configured=process.env.ORKAS_BUNDLED_NODE;if(isFile(configured))return configured;const names=process.platform==="win32"?["node.exe"]:[path2.join("bin","node")];for(const dir of runtimeVariantDirs("node")){for(const name of names){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}}return void 0}function resolveFfmpegBinary(kind){const envName=kind==="ffmpeg"?"ORKAS_BUNDLED_FFMPEG":"ORKAS_BUNDLED_FFPROBE";const configured=process.env[envName];if(isFile(configured))return configured;const name=process.platform==="win32"?`${kind}.exe`:kind;for(const dir of runtimeVariantDirs("ffmpeg")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate;const nested=path2.join(dir,"bin",name);if(isFile(nested))return nested}return void 0}function bundledFfmpegPaths(){const result={};const ffmpeg=resolveFfmpegBinary("ffmpeg");const ffprobe=resolveFfmpegBinary("ffprobe");if(ffmpeg)result.ffmpeg=ffmpeg;if(ffprobe)result.ffprobe=ffprobe;return result}function pushPathDir(out,seen,dir){if(!isDir(dir))return;const resolved=path2.resolve(dir);const key=process.platform==="win32"?resolved.toLowerCase():resolved;if(seen.has(key))return;seen.add(key);out.push(resolved)}function bundledRuntimePathEntries(){const entries=[];const seen=new Set;const python=resolvePythonExecutable();if(python){const pythonDir=path2.dirname(python);pushPathDir(entries,seen,pythonDir);pushPathDir(entries,seen,path2.join(pythonDir,"Scripts"));pushPathDir(entries,seen,path2.join(pythonDir,"bin"))}const uv=resolveUvExecutable();if(uv)pushPathDir(entries,seen,path2.dirname(uv));const node=resolveNodeExecutable();if(node)pushPathDir(entries,seen,path2.dirname(node));return entries}function bundledNodeExecutable(){return resolveNodeExecutable()}function bundledNpxCli(){const node=resolveNodeExecutable();if(!node)return void 0;const dir=path2.dirname(node);const candidates=process.platform==="win32"?[path2.join(dir,"node_modules","npm","bin","npx-cli.js")]:[path2.join(dir,"..","lib","node_modules","npm","bin","npx-cli.js")];for(const c of candidates)if(isFile(c))return c;return void 0}var HYPERFRAMES_SPEC="[email protected]";function resolveHyperframesRunner(){const node=bundledNodeExecutable();const npxCli=bundledNpxCli();if(!node||!npxCli)return null;return{node,npxCli}}function buildHyperframesEnv(){const env={...process.env};const sep2=process.platform==="win32"?";":":";const prepend=[...bundledRuntimePathEntries()];prepend.push(PYTHON_VENV_BIN_DIR);if(prepend.length)env.PATH=[...prepend,env.PATH||""].filter(Boolean).join(sep2);const ff=bundledFfmpegPaths();if(ff.ffmpeg)env.HYPERFRAMES_FFMPEG_PATH=ff.ffmpeg;if(ff.ffprobe)env.HYPERFRAMES_FFPROBE_PATH=ff.ffprobe;for(const dir of[NODE_NPM_CACHE_DIR,NODE_NPM_PREFIX_DIR,NODE_NPM_GLOBAL_BIN_DIR]){try{fs3.mkdirSync(dir,{recursive:true})}catch{}}env.NPM_CONFIG_CACHE=NODE_NPM_CACHE_DIR;env.NPM_CONFIG_PREFIX=NODE_NPM_PREFIX_DIR;env.NPM_CONFIG_FUND="false";env.NPM_CONFIG_AUDIT="false";env.NPM_CONFIG_UPDATE_NOTIFIER="false";env.NPM_CONFIG_PREFER_OFFLINE="true";env.NPM_CONFIG_FETCH_RETRIES="4";return env}var FONT_FLOOR_AT_1080=40;var PALETTE_SOFT_MAX=8;function readCanvasHeight(html,override){if(typeof override==="number"&&Number.isFinite(override)&&override>0)return override;const m=html.match(/data-height\s*=\s*["']?(\d{2,5})/i);const h=m?Number(m[1]):NaN;return Number.isFinite(h)&&h>0?h:1080}function fontFloor(height){return Math.max(1,Math.round(FONT_FLOOR_AT_1080*height/1080))}function smallFontSizesPx(html,floor){const out=new Set;const re=/font-size\s*:\s*([\d.]+)px\b/gi;let m;while((m=re.exec(html))!==null){const px=Number(m[1]);if(Number.isFinite(px)&&px>0&&px<floor)out.add(px)}return[...out].sort((a,b)=>a-b)}function expandHex(h){if(h.length===3)return h.split("").map(c=>c+c).join("");if(h.length===4)return h.slice(0,3).split("").map(c=>c+c).join("");return h.slice(0,6)}function isNeutralHex6(h){return h.slice(0,2)===h.slice(2,4)&&h.slice(2,4)===h.slice(4,6)}function isNeutralColorFn(s){if(s.includes("transparent"))return true;const rgb=s.match(/^rgba?\((\d+),(\d+),(\d+)/);if(rgb)return rgb[1]===rgb[2]&&rgb[2]===rgb[3];const hsl=s.match(/^hsla?\(\d+(?:deg)?,(\d+(?:\.\d+)?)%/);if(hsl)return Number(hsl[1])===0;return false}function chromaticColors(html){const colors=new Set;const hexRe=/#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})\b/gi;let m;while((m=hexRe.exec(html))!==null){const six=expandHex(m[1].toLowerCase());if(!isNeutralHex6(six))colors.add(`#${six}`)}const fnRe=/\b(?:rgb|rgba|hsl|hsla)\([^)]*\)/gi;while((m=fnRe.exec(html))!==null){const key=m[0].toLowerCase().replace(/\s+/g,"");if(!isNeutralColorFn(key))colors.add(key)}return colors}function lintCompositionCraft(html,opts){const findings=[];if(!html)return findings;const height=readCanvasHeight(html,opts?.canvasHeight);const floor=fontFloor(height);const small=smallFontSizesPx(html,floor);if(small.length){const shown=small.slice(0,6).map(n=>`${n}px`).join(", ");const more=small.length>6?`, +${small.length-6} more`:"";findings.push({level:"warn",code:"FONT_TOO_SMALL",message:`Font sizes below the legibility floor (~${floor}px for a ${height}px-tall canvas): ${shown}${more}. Raise body text to \u2265 the floor and titles well above it, or it won't read at phone size.`})}const colors=chromaticColors(html);if(colors.size>PALETTE_SOFT_MAX){findings.push({level:"warn",code:"PALETTE_LARGE",message:`${colors.size} distinct chromatic colors in the composition \u2014 aim for \u2264 3\u20135 on screen at once. Re-check each scene: background least-saturated, one accent that reads first.`})}return findings}function formatCraftFindings(findings,opts){if(!findings.length)return"";return[opts?.strict?"[craft] static threshold checks (FONT_TOO_SMALL blocks under --strict-craft; PALETTE_LARGE is advisory):":"[craft] static threshold checks (advisory, from the video-craft skill):",...findings.map(f=>` - ${f.code}: ${f.message}`)].join("\n")}function redactPaths(text){if(!text)return text;return text.replace(/[A-Za-z]:[\\/][^\s"']*/g,"<path>").replace(/(?:\/[\w.\-]+){2,}\/?/g,"<path>")}function createLogger(moduleName){const scope=String(moduleName||"video-script").trim()||"video-script";const write=(level,message,args)=>{if(process.env.ORKAS_VIDEO_SCRIPT_DEBUG!=="1")return;const line=`[${scope}] ${message}`;if(level==="error")console.error(line,...args);else if(level==="warn")console.warn(line,...args);else if(level==="debug")console.debug(line,...args);else console.info(line,...args)};return{error:(message,...args)=>write("error",message,args),warn:(message,...args)=>write("warn",message,args),info:(message,...args)=>write("info",message,args),debug:(message,...args)=>write("debug",message,args)}}var log=createLogger("video-render");var RENDER_TIMEOUT_MS=20*60*1e3;var CONSTRAINED_RENDER_TIMEOUT_MS=40*60*1e3;var CONSTRAINED_PROTOCOL_TIMEOUT_MS=15*60*1e3;var CONSTRAINED_PLAYER_READY_TIMEOUT_MS=3*60*1e3;var CONSTRAINED_BROWSER_TIMEOUT_MS=3*60*1e3;var CONSTRAINED_QA_INIT_TIMEOUT_MS=30*1e3;var LOW_RAM_GB=8;var HEAVY_RENDER_COST=3e3;function isConstrainedMachine(totalRamGB,observedGpuMode){return totalRamGB<=LOW_RAM_GB||observedGpuMode==="software"}function estimateRenderCost(width,height,durationSec,fps){const frames=Math.max(1,durationSec)*Math.max(1,fps);const megapixels=Math.max(1,width*height/1e6);return Math.round(frames*megapixels)}function renderCostDecision(opts){if(!opts.constrained||opts.costUnits<=HEAVY_RENDER_COST)return"proceed";return opts.isFinal?"fail_fast":"degrade"}function degradedFps(fps){if(fps>30)return 30;return fps}var RENDER_LOG_TAIL_CHARS=8e3;var QA_PROGRESS_HEARTBEAT_MS=15e3;function machineRamGB(){return Math.round(os.totalmem()/1024**3*10)/10}function parseRenderDiagnostics(output){const d={};const s=String(output||"");const line=s.split(/\r?\n/).find(l=>l.includes("Pipeline started")&&l.includes("{"));if(line){const start=line.indexOf("{");const end=line.lastIndexOf("}");if(start!==-1&&end>start){try{const j=JSON.parse(line.slice(start,end+1));const gm=j.browserGpuMode;if(gm==="hardware"||gm==="software")d.gpuMode=gm;if(j.requestedWorkers!=null)d.workers=String(j.requestedWorkers);const num=v=>typeof v==="number"&&Number.isFinite(v)?v:void 0;d.protocolTimeoutMs=num(j.protocolTimeoutMs)??num(j.protocolTimeout);d.playerReadyTimeoutMs=num(j.playerReadyTimeoutMs)??num(j.playerReadyTimeout);d.browserTimeoutMs=num(j.browserTimeoutMs)??num(j.browserTimeout)}catch{}}}if(!d.gpuMode){const m=s.match(/browserGpuMode\s*(?:auto\s*(?:→|->)\s*)?["']?(hardware|software)["']?/i);if(m)d.gpuMode=m[1].toLowerCase()}return d}function classifyRenderCrash(stderr,code,timedOut){if(timedOut)return"timeout";const s=String(stderr||"");if(/NewIsolate|SnapshotData|MultiIsolatePlatform|v8::internal|Segmentation fault|SIGSEGV|SIGABRT|Fatal error/i.test(s)&&code!==0)return"native_worker_crash";return null}async function writeRenderLog(logPath,combined){if(!logPath)return null;try{await fs4.mkdir(path3.dirname(logPath),{recursive:true}).catch(()=>{});await fs4.writeFile(logPath,combined,"utf8");return logPath}catch{return null}}function diagnosticsSummary(d){const parts=[];if(d.gpuMode)parts.push(`gpu=${d.gpuMode}`);if(typeof d.totalRamGB==="number")parts.push(`ram=${d.totalRamGB}GB`);if(d.workers)parts.push(`workers=${d.workers}`);if(d.crashSignature)parts.push(`crash=${d.crashSignature}`);return parts.join(" ")}function buildRenderArgs(p){const args=["render","--output",p.outputAbsPath];if(p.quality)args.push("--quality",p.quality);if(typeof p.fps==="number")args.push("--fps",String(p.fps));if(p.format)args.push("--format",p.format);if(p.constrained){args.push("--low-memory-mode","--workers","1","--protocol-timeout",String(CONSTRAINED_PROTOCOL_TIMEOUT_MS),"--player-ready-timeout",String(CONSTRAINED_PLAYER_READY_TIMEOUT_MS),"--browser-timeout",String(CONSTRAINED_BROWSER_TIMEOUT_MS))}if(p.variables&&Object.keys(p.variables).length){args.push("--variables",JSON.stringify(p.variables))}return args}function parseTraceLine(line){const idx=line.indexOf("[Render:trace]");if(idx===-1)return null;const jsonStart=line.indexOf("{",idx);if(jsonStart===-1)return null;try{const trace=JSON.parse(line.slice(jsonStart));const phase=typeof trace.phase==="string"?trace.phase:"render";const status=typeof trace.status==="string"?trace.status:"";return{phase:`render.${phase}`,message:status?`${phase} ${status}`:phase}}catch{return null}}async function renderComposition(p){const runner=resolveHyperframesRunner();if(!runner){return{ok:false,errorCode:"E_RENDER_RUNTIME_MISSING",message:"Bundled Node runtime not found; cannot run the HyperFrames renderer."}}const indexHtml=path3.join(p.projectDirAbs,"index.html");try{const st=await fs4.stat(indexHtml);if(!st.isFile())throw new Error("not a file")}catch{return{ok:false,errorCode:"E_RENDER_NO_COMPOSITION",message:`No index.html found in composition dir: ${p.projectDirAbs}`}}await fs4.mkdir(path3.dirname(p.outputAbsPath),{recursive:true}).catch(()=>{});const env=buildHyperframesEnv();const args=[runner.npxCli,"--yes",HYPERFRAMES_SPEC,...buildRenderArgs(p)];return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process.spawn)(runner.node,args,{cwd:p.projectDirAbs,env,...p.signal?{signal:p.signal}:{}})}catch(err){resolve3({ok:false,errorCode:"E_RENDER_SPAWN",message:err.message});return}const errChunks=[];const outChunks=[];let stdoutBuf="";let settled=false;let timedOut=false;const renderTimeoutMs=p.constrained?CONSTRAINED_RENDER_TIMEOUT_MS:RENDER_TIMEOUT_MS;const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},renderTimeoutMs);const pumpProgress=chunk=>{stdoutBuf+=chunk;let nl;while((nl=stdoutBuf.indexOf("\n"))!==-1){const line=stdoutBuf.slice(0,nl);stdoutBuf=stdoutBuf.slice(nl+1);const ev=parseTraceLine(line);if(ev)p.onProgress?.(ev)}};child.stdout?.on("data",c=>{const s=c.toString("utf8");outChunks.push(s);pumpProgress(s)});child.stderr?.on("data",c=>{const s=c.toString("utf8");errChunks.push(s);pumpProgress(s)});child.stdin?.end();const finish=r=>{if(settled)return;settled=true;clearTimeout(timer);resolve3(r)};child.on("error",err=>{if(p.signal?.aborted){finish({ok:false,errorCode:"E_RENDER_ABORTED",message:"Render aborted."});return}finish({ok:false,errorCode:"E_RENDER_SPAWN",message:err.message})});child.on("close",async code=>{const stdout=outChunks.join("");const stderr=errChunks.join("").trim();const combined=stdout+(stderr?`+--- stderr ---+${stderr}`:"");const diagnostics={...parseRenderDiagnostics(combined),totalRamGB:machineRamGB(),crashSignature:classifyRenderCrash(stderr,code,timedOut)};const logPath=await writeRenderLog(p.logPath,combined)??void 0;const withDiag=r=>({...r,diagnostics,...logPath?{logPath}:{}});const summary=diagnosticsSummary(diagnostics);if(timedOut){finish(withDiag({ok:false,errorCode:"E_RENDER_TIMEOUT",message:`Render timed out after ${renderTimeoutMs}ms.${summary?` [${summary}]`:""}`}));return}if(p.signal?.aborted){finish(withDiag({ok:false,errorCode:"E_RENDER_ABORTED",message:"Render aborted."}));return}if(code!==0){const tail=stderr.slice(-RENDER_LOG_TAIL_CHARS);log.warn(`hyperframes render exited ${code}: ${redactPaths(tail.slice(-300))}${summary?` [${summary}]`:""}`);return finish(withDiag({ok:false,errorCode:"E_RENDER_FAILED",message:`HyperFrames render failed (exit ${code}).${summary?` [${summary}]`:""}${logPath?` Full log: ${logPath}.`:""} ${tail||"No diagnostic output."}`}))}const st=await fs4.stat(p.outputAbsPath).catch(()=>null);if(!st||!st.isFile()||st.size===0){return finish(withDiag({ok:false,errorCode:"E_RENDER_NO_OUTPUT",message:`Render reported success but no output file was produced at ${p.outputAbsPath}.`}))}finish(withDiag({ok:true,path:p.outputAbsPath,bytes:st.size}))})})}var QA_TIMEOUT_MS=5*60*1e3;function withStrictCraftFindings(findings,craftFindings){const blockingFindings=craftFindings.filter(f=>f.code==="FONT_TOO_SMALL");if(!blockingFindings.length)return findings;try{const parsed=JSON.parse(findings);const existingIssues=Array.isArray(parsed.issues)?parsed.issues:[];const craftIssues=blockingFindings.map(f=>({code:f.code,severity:"error",selector:"document",message:f.message,fixHint:"Raise all readable text to the video-craft legibility floor before rendering.",source:"video-craft"}));const add=craftIssues.length;const numberField=key=>typeof parsed[key]==="number"?parsed[key]:0;parsed.ok=false;parsed.errorCount=numberField("errorCount")+add;parsed.issueCount=numberField("issueCount")+add;parsed.totalIssueCount=numberField("totalIssueCount")+add;parsed.issues=[...existingIssues,...craftIssues];return JSON.stringify(parsed,null,2)}catch{return`${findings}-${craft}`:findings})})})}0&&(module.exports={qaComposition,renderComposition});+[craft] BLOCKING strict checks:+${blockingFindings.map(f=>` - ${f.code}: ${f.message}`).join("\n")}`}}async function qaComposition(op,p){const runner=resolveHyperframesRunner();if(!runner){return{ok:false,errorCode:"E_RENDER_RUNTIME_MISSING",message:"Bundled Node runtime not found."}}const indexHtml=path3.join(p.projectDirAbs,"index.html");const st=await fs4.stat(indexHtml).catch(()=>null);if(!st||!st.isFile()){return{ok:false,errorCode:"E_RENDER_NO_COMPOSITION",message:`No index.html in: ${p.projectDirAbs}`}}const env=buildHyperframesEnv();const args=[runner.npxCli,"--yes",HYPERFRAMES_SPEC,op,"--json"];if(p.constrained)args.push("--timeout",String(CONSTRAINED_QA_INIT_TIMEOUT_MS));return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process.spawn)(runner.node,args,{cwd:p.projectDirAbs,env,...p.signal?{signal:p.signal}:{}})}catch(err){resolve3({ok:false,errorCode:"E_QA_SPAWN",message:err.message});return}const out=[];const errOut=[];let settled=false;let timedOut=false;const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},QA_TIMEOUT_MS);const startedAtMs=Date.now();const heartbeat=p.onProgress?setInterval(()=>p.onProgress?.({phase:`qa.${op}`,message:`${op} running (${Math.round((Date.now()-startedAtMs)/1e3)}s elapsed)`}),QA_PROGRESS_HEARTBEAT_MS):null;heartbeat?.unref?.();let traceBuf="";const pumpTrace=chunk=>{if(!p.onProgress)return;traceBuf+=chunk;let nl;while((nl=traceBuf.indexOf("\n"))!==-1){const line=traceBuf.slice(0,nl);traceBuf=traceBuf.slice(nl+1);const ev=parseTraceLine(line);if(ev)p.onProgress?.(ev)}};child.stdout?.on("data",c=>out.push(c.toString("utf8")));child.stderr?.on("data",c=>{const s=c.toString("utf8");errOut.push(s);pumpTrace(s)});child.stdin?.end();const finish=r=>{if(settled)return;settled=true;clearTimeout(timer);if(heartbeat)clearInterval(heartbeat);resolve3(r)};child.on("error",err=>{if(p.signal?.aborted)return finish({ok:false,errorCode:"E_QA_ABORTED",message:`${op} aborted.`});finish({ok:false,errorCode:"E_QA_SPAWN",message:err.message})});child.on("close",async code=>{if(timedOut)return finish({ok:false,errorCode:"E_QA_TIMEOUT",message:`${op} timed out.`});if(p.signal?.aborted)return finish({ok:false,errorCode:"E_QA_ABORTED",message:`${op} aborted.`});const findings=out.join("").trim();if(!findings){const stderrFull=errOut.join("").trim();const combined=out.join("")+(stderrFull?`+--- stderr ---+${stderrFull}`:"");const diagnostics={...parseRenderDiagnostics(combined),totalRamGB:machineRamGB(),crashSignature:classifyRenderCrash(stderrFull,code,false)};const logPath=await writeRenderLog(p.logPath,combined)??void 0;const summary=diagnosticsSummary(diagnostics);return finish({ok:false,errorCode:"E_QA_NO_OUTPUT",message:`${op} produced no findings.${summary?` [${summary}]`:""}${logPath?` Full log: ${logPath}.`:""} ${stderrFull.slice(-RENDER_LOG_TAIL_CHARS)||"No diagnostic output."}`,diagnostics,...logPath?{logPath}:{}})}let craft="";let finalFindings=findings;try{const html=await fs4.readFile(indexHtml,"utf8");const craftFindings=lintCompositionCraft(html);if(p.strictCraft)finalFindings=withStrictCraftFindings(findings,craftFindings);craft=formatCraftFindings(craftFindings,{strict:!!p.strictCraft})}catch{}finish({ok:true,op,findings:craft?`${finalFindings}++${craft}`:finalFindings})})})}0&&(module.exports={HEAVY_RENDER_COST,LOW_RAM_GB,classifyRenderCrash,degradedFps,estimateRenderCost,isConstrainedMachine,machineRamGB,parseRenderDiagnostics,qaComposition,renderComposition,renderCostDecision});diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/render_composition.js b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/render_composition.jsindex 1f457d7a..8278c7d9 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/render_composition.js+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/render_composition.js@@ -2,22 +2,75 @@const fs = require('node:fs');const path = require('node:path');+const childProcess = require('node:child_process');+const crypto = require('node:crypto');-const OPS = new Set(['render', 'lint', 'inspect']);+const OPS = new Set(['draft', 'render', 'lint', 'inspect']);const QUALITY = new Set(['draft', 'standard', 'high']);const FORMAT = new Set(['mp4', 'webm']);+const FINDINGS_INLINE = new Set(['full', 'summary', 'none']);+const LOCAL_GSAP_VENDOR_REF = 'assets/vendor/gsap.min.js';+const REQUIRED_GSAP_TIMELINE_APIS = ['timeScale', 'totalTime', 'totalDuration', 'getChildren'];+const DRAFT_REPAIR_MAX_PASSES = 2;+const DRAFT_VISUAL_ADVISORY_CODES = new Set([+ 'FONT_TOO_SMALL',+ 'PALETTE_LARGE',+ 'LOW_CONTRAST',+ 'TEXT_BOX_OVERFLOW',+ 'TEXT_OCCLUDED',+ 'TEXT_OVERFLOW',+ 'TEXT_CLIPPED',+ 'CONTENT_OVERLAP',+ 'CONTENT_OCCLUDED',+ 'CONTENT_OVERFLOW',+ 'CONTENT_CLIPPED',+ 'SAFE_AREA_VIOLATION',+]);function fail(code, message, extra = {}) {process.stderr.write(JSON.stringify({ ok: false, code, message, ...extra }) + '\n');process.exit(1);}+// Best-effort progress JSONL on stderr (same protocol as video_edit); the+// direct-CLI runner forwards these lines to the user-facing tool progress.+// Throttled so a long render cannot flood the runner's output buffer.+const PROGRESS_EMIT_MIN_MS = 2000;+let lastProgressEmitMs = 0;+function makeProgressEmitter(op) {+ return (event) => {+ const now = Date.now();+ if (now - lastProgressEmitMs < PROGRESS_EMIT_MIN_MS) return;+ lastProgressEmitMs = now;+ const payload = {+ type: 'progress',+ source: 'render_composition',+ op,+ phase: (event && event.phase) ? event.phase : op,+ ...((event && event.message) ? { message: event.message } : {}),+ };+ try {+ process.stderr.write(JSON.stringify(payload) + '\n');+ } catch {+ // Progress must never break the render.+ }+ };+}++// Absolute path for a per-op HyperFrames diagnostic log under project/render/.+// The backend writes the full stdout+stderr there so a failed/slow render+// (browserGpuMode, RAM, worker crash, timeout) is diagnosable. Overwritten+// each run — the latest is what you want when chasing a failure.+function renderLogPath(compositionDirAbs, name) {+ return path.join(path.resolve(compositionDirAbs, '..', 'render'), `${name}-hyperframes.log`);+}+function help() {return {ok: true,script: 'render_composition',ops: [...OPS],- usage: 'stage-compose render_composition -- --op <inspect|lint|render> --composition-dir <dir> [--output <video>]',+ usage: 'stage-compose render_composition -- --op <draft|inspect|lint|render> --composition-dir <dir> [--strict-craft] [--findings-output <json>] [--findings-inline <full|summary|none>] [--output <video>] [--report <json>]. draft renders hand-authored index.html; spec compilation is not supported.',};}@@ -43,10 +96,26 @@ function parseJson(raw, label) {}function parseArgs(args) {- const out = { op: 'render', compositionDir: '', outputPath: '', help: false };+ const out = {+ op: 'render',+ compositionDir: '',+ outputPath: '',+ specPath: '',+ reportPath: '',+ help: false,+ strictCraft: false,+ normalizeAudio: true,+ videoQa: true,+ findingsOutputPath: '',+ findingsInline: '',+ };for (let i = 0; i < args.length; i += 1) {const a = args[i];if (a === '--help' || a === '-h') out.help = true;+ else if (a === '--strict-craft') out.strictCraft = true;+ else if (a === '--normalize-audio') out.normalizeAudio = true;+ else if (a === '--skip-normalize-audio' || a === '--no-normalize-audio') out.normalizeAudio = false;+ else if (a === '--skip-video-qa' || a === '--no-video-qa') out.videoQa = false;else if (a === '--op' || a === '-o') { out.op = nextValue(args, i, a); i += 1; }else if (a.startsWith('--op=')) out.op = a.slice('--op='.length);else if (a === '--composition-dir' || a === '--dir' || a === '-d') { out.compositionDir = nextValue(args, i, a); i += 1; }@@ -55,6 +124,16 @@ function parseArgs(args) {else if (a === '--output' || a === '--output-path') { out.outputPath = nextValue(args, i, a); i += 1; }else if (a.startsWith('--output=')) out.outputPath = a.slice('--output='.length);else if (a.startsWith('--output-path=')) out.outputPath = a.slice('--output-path='.length);+ else if (a === '--report' || a === '--report-path') { out.reportPath = nextValue(args, i, a); i += 1; }+ else if (a.startsWith('--report=')) out.reportPath = a.slice('--report='.length);+ else if (a.startsWith('--report-path=')) out.reportPath = a.slice('--report-path='.length);+ else if (a === '--spec' || a === '--spec-path') { out.specPath = nextValue(args, i, a); i += 1; }+ else if (a.startsWith('--spec=')) out.specPath = a.slice('--spec='.length);+ else if (a.startsWith('--spec-path=')) out.specPath = a.slice('--spec-path='.length);+ else if (a === '--findings-output') { out.findingsOutputPath = nextValue(args, i, a); i += 1; }+ else if (a.startsWith('--findings-output=')) out.findingsOutputPath = a.slice('--findings-output='.length);+ else if (a === '--findings-inline') { out.findingsInline = nextValue(args, i, a); i += 1; }+ else if (a.startsWith('--findings-inline=')) out.findingsInline = a.slice('--findings-inline='.length);else if (a === '--quality') { out.quality = nextValue(args, i, a); i += 1; }else if (a.startsWith('--quality=')) out.quality = a.slice('--quality='.length);else if (a === '--format') { out.format = nextValue(args, i, a); i += 1; }@@ -77,6 +156,132 @@ function resolveDir(raw) {return abs;}+function resolveOrCreateDir(raw) {+ const abs = path.resolve(process.cwd(), String(raw || '').trim());+ fs.mkdirSync(abs, { recursive: true });+ const st = fs.existsSync(abs) ? fs.statSync(abs) : null;+ if (!st || !st.isDirectory()) fail('E_INPUT', `composition_dir is not a directory: ${abs}`, { path: abs });+ return abs;+}++function resolveOutputPath(raw) {+ return path.resolve(process.cwd(), String(raw || '').trim());+}++function parseLeadingJson(text) {+ const raw = String(text || '').trim();+ if (!raw.startsWith('{')) return null;+ const craftIndex = raw.indexOf('\n\n[craft]');+ const jsonText = craftIndex >= 0 ? raw.slice(0, craftIndex).trim() : raw;+ try {+ return JSON.parse(jsonText);+ } catch {+ return null;+ }+}++function shortText(value, max = 220) {+ const s = String(value || '').replace(/\s+/g, ' ').trim();+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;+}++function summarizeFindings(findings) {+ const parsed = parseLeadingJson(findings);+ const issues = parsed && Array.isArray(parsed.issues)+ ? parsed.issues+ : (parsed && Array.isArray(parsed.findings) ? parsed.findings : []);+ const codeCounts = new Map();+ for (const issue of issues) {+ const code = shortText(issue && issue.code ? issue.code : 'ISSUE', 80);+ const severity = shortText(issue && issue.severity ? issue.severity : '', 40);+ const key = `${severity}\u0000${code}`;+ const prev = codeCounts.get(key) || { code, severity, count: 0 };+ prev.count += 1;+ codeCounts.set(key, prev);+ }+ const topIssues = issues.slice(0, 8).map((issue) => ({+ code: shortText(issue && issue.code ? issue.code : 'ISSUE', 80),+ severity: shortText(issue && issue.severity ? issue.severity : '', 40),+ selector: shortText(issue && issue.selector ? issue.selector : '', 120),+ message: shortText(issue && issue.message ? issue.message : issue, 260),+ }));+ const craftLines = String(findings || '')+ .split('\n')+ .map((line) => line.trim())+ .filter((line) => line.startsWith('- ') || line.startsWith(' - '))+ .slice(0, 8)+ .map((line) => shortText(line.replace(/^\s*-\s*/, ''), 260));+ return {+ parseable: !!parsed,+ ok: parsed && typeof parsed.ok === 'boolean' ? parsed.ok : undefined,+ errorCount: parsed && typeof parsed.errorCount === 'number' ? parsed.errorCount : undefined,+ warningCount: parsed && typeof parsed.warningCount === 'number' ? parsed.warningCount : undefined,+ issueCount: parsed && typeof parsed.issueCount === 'number' ? parsed.issueCount : issues.length,+ totalIssueCount: parsed && typeof parsed.totalIssueCount === 'number' ? parsed.totalIssueCount : issues.length,+ issueCodes: [...codeCounts.values()].sort((a, b) => b.count - a.count || a.code.localeCompare(b.code)),+ topIssues,+ craft: craftLines,+ rawChars: String(findings || '').length,+ };+}++function findingsIssues(findings) {+ const parsed = parseLeadingJson(findings);+ if (parsed && Array.isArray(parsed.issues)) return parsed.issues;+ if (parsed && Array.isArray(parsed.findings)) return parsed.findings;+ return [];+}++function isDraftVisualAdvisory(issue) {+ const rawCode = issue && issue.code ? String(issue.code) : '';+ const code = rawCode.toUpperCase();+ const lower = rawCode.toLowerCase();+ return DRAFT_VISUAL_ADVISORY_CODES.has(code)+ || lower.includes('overflow')+ || lower.includes('overlap')+ || lower.includes('occlud')+ || lower.includes('clipp')+ || lower.includes('contrast')+ || lower.includes('font')+ || lower.includes('safe_area');+}++function summarizeDraftInspectDisposition(findings) {+ const issues = findingsIssues(findings);+ const blocking = [];+ const advisory = [];+ for (const issue of issues) {+ const severity = String(issue && issue.severity ? issue.severity : '').toLowerCase();+ if (severity === 'error' && !isDraftVisualAdvisory(issue)) blocking.push(issue);+ else advisory.push(issue);+ }+ return {+ blocking_error_count: blocking.length,+ advisory_count: advisory.length,+ blocking_codes: [...new Set(blocking.map((issue) => shortText(issue && issue.code ? issue.code : 'ISSUE', 80)))],+ advisory_codes: [...new Set(advisory.map((issue) => shortText(issue && issue.code ? issue.code : 'ISSUE', 80)))],+ blocking_issues: blocking.slice(0, 8).map((issue) => ({+ code: shortText(issue && issue.code ? issue.code : 'ISSUE', 80),+ severity: shortText(issue && issue.severity ? issue.severity : '', 40),+ selector: shortText(issue && issue.selector ? issue.selector : '', 120),+ message: shortText(issue && issue.message ? issue.message : issue, 260),+ })),+ advisory_issues: advisory.slice(0, 8).map((issue) => ({+ code: shortText(issue && issue.code ? issue.code : 'ISSUE', 80),+ severity: shortText(issue && issue.severity ? issue.severity : '', 40),+ selector: shortText(issue && issue.selector ? issue.selector : '', 120),+ message: shortText(issue && issue.message ? issue.message : issue, 260),+ })),+ };+}++function writeFindingsOutput(rawPath, payload) {+ const abs = resolveOutputPath(rawPath);+ fs.mkdirSync(path.dirname(abs), { recursive: true });+ fs.writeFileSync(abs, JSON.stringify(payload, null, 2), 'utf8');+ return abs;+}+function withFormatExtension(rawAbs, format) {return path.extname(rawAbs) ? rawAbs : `${rawAbs}.${format}`;}@@ -93,44 +298,1715 @@ function uniquifyOutputPath(requested) {}async function outputFile(raw, format) {- if (!raw) fail('E_ARGS', '--output is required for op=render');+ if (!raw) fail('E_ARGS', '--output is required for op=render or op=draft');const requested = withFormatExtension(path.resolve(process.cwd(), String(raw).trim()), format);const { finalPath, renamed } = uniquifyOutputPath(requested);return { requested, finalPath, renamed };}+function parseFps(raw) {+ const s = String(raw || '').trim();+ if (!s) return 30;+ const [a, b] = s.split('/').map(Number);+ if (Number.isFinite(a) && Number.isFinite(b) && b > 0) return a / b;+ const n = Number(s);+ return Number.isFinite(n) && n > 0 ? n : 30;+}++function runProcess(command, args, opts = {}) {+ const res = childProcess.spawnSync(command, args, {+ cwd: opts.cwd || process.cwd(),+ env: opts.env || process.env,+ encoding: opts.encoding === 'buffer' ? undefined : 'utf8',+ maxBuffer: opts.maxBuffer || 20 * 1024 * 1024,+ });+ if (res.error) throw res.error;+ if (res.status !== 0) {+ const stderr = Buffer.isBuffer(res.stderr) ? res.stderr.toString('utf8') : String(res.stderr || '');+ const stdout = Buffer.isBuffer(res.stdout) ? res.stdout.toString('utf8') : String(res.stdout || '');+ throw new Error(`${command} exited ${res.status}: ${(stderr || stdout).trim().slice(-1800)}`);+ }+ return res;+}++function toolEnvName(kind) {+ return kind === 'ffmpeg' ? 'ORKAS_BUNDLED_FFMPEG' : 'ORKAS_BUNDLED_FFPROBE';+}++function resolveMediaTool(kind) {+ const direct = process.env[toolEnvName(kind)] || process.env[`HYPERFRAMES_${kind.toUpperCase()}_PATH`];+ const candidates = [direct, kind].filter(Boolean);+ for (const candidate of candidates) {+ try {+ const res = childProcess.spawnSync(candidate, ['-version'], { stdio: 'ignore' });+ if (res.status === 0) return candidate;+ } catch {+ // Try the next candidate.+ }+ }+ fail('E_MEDIA_TOOL_MISSING', `${kind} was not found in the bundled runtime or PATH`);+}++function probeMedia(mediaPath) {+ const ffprobe = resolveMediaTool('ffprobe');+ const res = runProcess(ffprobe, [+ '-v', 'error',+ '-show_entries', 'format=duration,size,bit_rate:stream=index,codec_type,codec_name,width,height,r_frame_rate,bit_rate',+ '-of', 'json',+ mediaPath,+ ]);+ const parsed = JSON.parse(String(res.stdout || '{}'));+ const streams = Array.isArray(parsed.streams) ? parsed.streams : [];+ const video = streams.find((s) => s.codec_type === 'video') || {};+ const audio = streams.find((s) => s.codec_type === 'audio') || null;+ return {+ duration_seconds: Number(parsed.format && parsed.format.duration) || 0,+ size_bytes: Number(parsed.format && parsed.format.size) || 0,+ bit_rate: Number(parsed.format && parsed.format.bit_rate) || 0,+ video: {+ codec: video.codec_name || '',+ width: Number(video.width) || 0,+ height: Number(video.height) || 0,+ fps: parseFps(video.r_frame_rate),+ bit_rate: Number(video.bit_rate) || 0,+ },+ audio: audio ? {+ codec: audio.codec_name || '',+ bit_rate: Number(audio.bit_rate) || 0,+ } : null,+ };+}++function parseLastJsonObject(text) {+ const raw = String(text || '');+ const end = raw.lastIndexOf('}');+ if (end < 0) return null;+ const start = raw.lastIndexOf('{', end);+ if (start < 0) return null;+ try {+ return JSON.parse(raw.slice(start, end + 1));+ } catch {+ return null;+ }+}++function analyzeLoudness(mediaPath) {+ const ffmpeg = resolveMediaTool('ffmpeg');+ const res = runProcess(ffmpeg, [+ '-hide_banner',+ '-nostats',+ '-i', mediaPath,+ '-af', 'loudnorm=I=-14:TP=-1:LRA=11:print_format=json',+ '-f', 'null',+ '-',+ ]);+ const text = `${res.stdout || ''}\n${res.stderr || ''}`;+ return parseLastJsonObject(text) || { raw_tail: shortText(text.slice(-1000), 1000) };+}++function normalizeAudioInPlace(mediaPath) {+ const ffmpeg = resolveMediaTool('ffmpeg');+ const ext = path.extname(mediaPath) || '.mp4';+ if (ext.toLowerCase() !== '.mp4') {+ return { skipped: true, reason: 'audio normalization is currently only applied to mp4 output' };+ }+ const tmp = path.join(path.dirname(mediaPath), `${path.basename(mediaPath, ext)}.norm-${Date.now()}${ext}`);+ runProcess(ffmpeg, [+ '-y',+ '-hide_banner',+ '-loglevel', 'error',+ '-i', mediaPath,+ '-af', 'loudnorm=I=-14:TP=-1:LRA=11',+ '-c:v', 'copy',+ '-c:a', 'aac',+ '-b:a', '192k',+ tmp,+ ]);+ fs.renameSync(tmp, mediaPath);+ return { skipped: false, path: mediaPath };+}++function loadTimelineMap(compositionDirAbs) {+ const candidates = [+ path.join(compositionDirAbs, 'scene-map.json'),+ path.join(compositionDirAbs, 'timeline.json'),+ ];+ for (const timelinePath of candidates) {+ if (!fs.existsSync(timelinePath)) continue;+ const loaded = readJsonFile(timelinePath);+ if (loaded.error) return { path: timelinePath, map: null, error: loaded.error };+ const timeline = Array.isArray(loaded.value) ? { scenes: loaded.value } : loaded.value;+ return { path: timelinePath, map: timeline && typeof timeline === 'object' ? timeline : null };+ }+ return { path: '', map: null };+}++// The contract's audio section can promise narration; if TTS failed (or was+// skipped) the composition renders silent and every other QA still passes.+// Make that gap visible instead of shipping a silent draft unnoticed.+function compositionHasAudio(html, compositionDirAbs) {+ if (/<audio\b/i.test(String(html || ''))) return true;+ return [+ path.join(compositionDirAbs, 'assets', 'narration.mp3'),+ path.join(compositionDirAbs, 'assets', 'narration.wav'),+ path.join(compositionDirAbs, 'narration.mp3'),+ path.join(compositionDirAbs, 'narration.wav'),+ ].some((file) => fs.existsSync(file));+}++function contractDeclaresNarrationAudio(contract) {+ const audio = contract && typeof contract === 'object' ? contract.audio : null;+ if (!audio || typeof audio !== 'object') return false;+ const text = JSON.stringify(audio).toLowerCase();+ if (/render[_-]?silent|"silent"\s*:\s*true|assemble/.test(text)) return false;+ return /\.(mp3|wav|m4a|aac|ogg)\b/.test(text);+}++function htmlNeedsSceneMap(compositionDirAbs) {+ const htmlPath = path.join(compositionDirAbs, 'index.html');+ let html = '';+ try {+ html = fs.readFileSync(htmlPath, 'utf8');+ } catch {+ return false;+ }+ return compositionHasAudio(html, compositionDirAbs);+}++function readJsonFile(jsonPath) {+ try {+ return { path: jsonPath, value: JSON.parse(fs.readFileSync(jsonPath, 'utf8')) };+ } catch (err) {+ return { path: jsonPath, value: null, error: err && err.message ? err.message : String(err) };+ }+}++function loadDesignContract(compositionDirAbs) {+ const contractPath = path.join(compositionDirAbs, 'design-contract.json');+ if (!fs.existsSync(contractPath)) return { path: contractPath, exists: false, contract: null };+ const loaded = readJsonFile(contractPath);+ return {+ path: contractPath,+ exists: true,+ contract: loaded.value && typeof loaded.value === 'object' ? loaded.value : null,+ error: loaded.error || '',+ };+}++function numberOrZero(value) {+ const n = Number(value);+ return Number.isFinite(n) ? n : 0;+}++function normalizeForSearch(value) {+ return String(value || '')+ .normalize('NFKC')+ .toLowerCase()+ .replace(/&[a-z0-9#]+;/gi, ' ')+ .replace(/[^\p{L}\p{N}]+/gu, '');+}++function flattenStringValues(value, out = [], depth = 0) {+ if (depth > 6 || value === null || value === undefined) return out;+ if (typeof value === 'string') {+ const s = value.trim();+ if (s) out.push(s);+ } else if (Array.isArray(value)) {+ for (const item of value) flattenStringValues(item, out, depth + 1);+ } else if (typeof value === 'object') {+ for (const item of Object.values(value)) flattenStringValues(item, out, depth + 1);+ }+ return out;+}++function sceneDisplayTexts(scene) {+ if (!scene || typeof scene !== 'object') return [];+ const fields = [+ 'headline',+ 'title',+ 'subtitle',+ 'kicker',+ 'label',+ 'metric',+ 'value',+ 'cta',+ 'copy',+ 'on_screen_copy',+ 'onscreen_copy',+ 'onscreen_text',+ 'display_text',+ 'text',+ ];+ const out = [];+ for (const field of fields) {+ if (scene[field] !== undefined) flattenStringValues(scene[field], out);+ }+ return [...new Set(out.map((s) => s.replace(/\s+/g, ' ').trim()).filter((s) => s.length >= 3 && s.length <= 140))];+}++function htmlAttr(tag, name) {+ const re = new RegExp(`${name}\\s*=\\s*["']?([^"'\\s>]+)`, 'i');+ const match = String(tag || '').match(re);+ return match ? match[1] : '';+}++function htmlDataNumber(tag, name) {+ const raw = htmlAttr(tag, `data-${name}`);+ const n = Number(raw);+ return Number.isFinite(n) ? n : 0;+}++function rootCompositionTag(html) {+ const match = String(html || '').match(/<[^>]+\bdata-composition-id\s*=\s*["'][^"']+["'][^>]*>/i);+ return match ? match[0] : '';+}++function extractRemoteRefs(html) {+ const refs = [];+ const add = (kind, value) => {+ const ref = String(value || '').trim();+ if (/^https?:\/\//i.test(ref)) refs.push({ kind, ref: shortText(ref, 180) });+ };+ let match;+ const attrRe = /\b(src|href|poster)\s*=\s*["']([^"']+)["']/gi;+ while ((match = attrRe.exec(html)) !== null) add(match[1].toLowerCase(), match[2]);+ const urlRe = /\burl\(\s*["']?(https?:\/\/[^"')\s]+)["']?\s*\)/gi;+ while ((match = urlRe.exec(html)) !== null) add('css-url', match[1]);+ const importRe = /@import\s+(?:url\(\s*)?["']?(https?:\/\/[^"')\s;]+)["']?/gi;+ while ((match = importRe.exec(html)) !== null) add('css-import', match[1]);+ return refs;+}++function stripRefSuffix(ref) {+ return String(ref || '').trim().split(/[?#]/)[0];+}++function isIgnoredLocalRef(ref) {+ const raw = String(ref || '').trim();+ return !raw+ || raw.startsWith('#')+ || raw.startsWith('data:')+ || raw.startsWith('blob:')+ || raw.startsWith('mailto:')+ || raw.startsWith('tel:')+ || raw.startsWith('javascript:')+ || /^https?:\/\//i.test(raw);+}++function extractLocalRefs(html) {+ const refs = [];+ const add = (kind, value) => {+ const raw = String(value || '').trim();+ if (!isIgnoredLocalRef(raw)) refs.push({ kind, ref: stripRefSuffix(raw) });+ };+ let match;+ const attrRe = /\b(src|href|poster)\s*=\s*["']([^"']+)["']/gi;+ while ((match = attrRe.exec(html)) !== null) add(match[1].toLowerCase(), match[2]);+ const urlRe = /\burl\(\s*["']?([^"')]+)["']?\s*\)/gi;+ while ((match = urlRe.exec(html)) !== null) add('css-url', match[1]);+ return refs;+}++function normalizeRefPath(ref) {+ return stripRefSuffix(ref).replace(/^\.\/+/, '').replace(/\\/g, '/');+}++function extractScriptSrcs(html) {+ const out = [];+ let match;+ const scriptRe = /<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;+ while ((match = scriptRe.exec(String(html || ''))) !== null) out.push(match[1]);+ return out;+}++function htmlUsesGsap(html) {+ return /\bgsap\s*\./.test(String(html || ''));+}++function hasLocalGsapVendorScript(html) {+ return extractScriptSrcs(html).some((src) => normalizeRefPath(src) === LOCAL_GSAP_VENDOR_REF);+}++function managedLegacyGsapVendor(text) {+ const s = String(text || '');+ return s.includes('Local HyperFrames timeline vendor')+ || s.includes('Provides the small GSAP-compatible surface VideoStudio compositions need');+}++function gsapVendorCompatibilityIssue(text) {+ const s = String(text || '');+ if (!s.trim()) return { code: 'VENDOR_GSAP_EMPTY', missing: REQUIRED_GSAP_TIMELINE_APIS };+ const missing = REQUIRED_GSAP_TIMELINE_APIS.filter((api) => !s.includes(api));+ return missing.length ? { code: 'VENDOR_GSAP_MISSING_TIMELINE_API', missing } : null;+}++function ensureVendorAssets(htmlPath, compositionDirAbs) {+ const html = fs.readFileSync(htmlPath, 'utf8');+ const copied = [];+ const skipped = [];+ const issues = [];+ if (!hasLocalGsapVendorScript(html)) {+ return { ok: true, copied, skipped, issues };+ }+ const source = path.join(__dirname, 'vendor', 'gsap.min.js');+ const target = path.join(compositionDirAbs, LOCAL_GSAP_VENDOR_REF);+ if (!fs.existsSync(source)) {+ issues.push({+ severity: 'error',+ code: 'VENDOR_GSAP_SOURCE_MISSING',+ repair_target: 'assets',+ message: `Local GSAP vendor source is missing: ${source}`,+ });+ return { ok: false, copied, skipped, issues };+ }+ const sourceText = fs.readFileSync(source, 'utf8');+ const sourceIssue = gsapVendorCompatibilityIssue(sourceText);+ if (sourceIssue) {+ issues.push({+ severity: 'error',+ code: 'VENDOR_GSAP_SOURCE_INCOMPATIBLE',+ repair_target: 'assets',+ missing_api: sourceIssue.missing,+ message: `Built-in GSAP vendor is missing required HyperFrames timeline APIs: ${sourceIssue.missing.join(', ')}.`,+ });+ return { ok: false, copied, skipped, issues };+ }++ if (fs.existsSync(target)) {+ const targetText = fs.readFileSync(target, 'utf8');+ if (managedLegacyGsapVendor(targetText)) {+ fs.copyFileSync(source, target);+ copied.push({ id: 'gsap', reason: 'replaced legacy managed vendor', path: target });+ return { ok: true, copied, skipped, issues };+ }+ const targetIssue = gsapVendorCompatibilityIssue(targetText);+ if (!targetIssue) {+ skipped.push({ id: 'gsap', reason: 'compatible existing vendor', path: target });+ return { ok: true, copied, skipped, issues };+ }+ issues.push({+ severity: 'error',+ code: 'VENDOR_GSAP_INCOMPATIBLE',+ repair_target: LOCAL_GSAP_VENDOR_REF,+ missing_api: targetIssue.missing,+ message: `Existing GSAP vendor is missing required HyperFrames timeline APIs: ${targetIssue.missing.join(', ')}. Remove or replace ${LOCAL_GSAP_VENDOR_REF}; do not patch it manually inside the composition.`,+ });+ return { ok: false, copied, skipped, issues };+ }++ fs.mkdirSync(path.dirname(target), { recursive: true });+ fs.copyFileSync(source, target);+ copied.push({ id: 'gsap', path: target });+ return { ok: true, copied, skipped, issues };+}++function ensureVendorAssetsForComposition(compositionDirAbs) {+ const htmlPath = path.join(compositionDirAbs, 'index.html');+ if (!fs.existsSync(htmlPath)) return { ok: true, copied: [], skipped: [], issues: [] };+ return ensureVendorAssets(htmlPath, compositionDirAbs);+}++function failVendorAssetsIfNeeded(vendorAssets, reportAbs) {+ if (!vendorAssets || vendorAssets.ok !== false) return;+ const firstError = (vendorAssets.issues || []).find((issue) => issue.severity === 'error') || {};+ fail('E_VENDOR_ASSETS_BLOCKED', 'could not prepare local composition vendor assets', {+ ...(reportAbs ? { report_path: reportAbs } : {}),+ repair_target: firstError.repair_target || 'assets',+ vendor_assets: vendorAssets,+ });+}++function validateLocalRefs(refs, compositionDirAbs) {+ const issues = [];+ const seen = new Set();+ for (const item of refs) {+ const ref = item.ref;+ if (!ref || seen.has(`${item.kind}\u0000${ref}`)) continue;+ seen.add(`${item.kind}\u0000${ref}`);+ if (path.isAbsolute(ref)) {+ issues.push({+ severity: 'error',+ code: 'ABSOLUTE_ASSET_REF',+ repair_target: 'index.html',+ message: `Asset reference must be relative to the composition directory: ${ref}`,+ });+ continue;+ }+ let decoded = ref;+ try { decoded = decodeURIComponent(ref); } catch {}+ const abs = path.resolve(compositionDirAbs, decoded);+ const rel = path.relative(compositionDirAbs, abs);+ if (rel.startsWith('..') || path.isAbsolute(rel)) {+ issues.push({+ severity: 'error',+ code: 'ASSET_OUTSIDE_COMPOSITION',+ repair_target: 'assets',+ message: `Asset reference escapes the composition directory: ${ref}`,+ });+ continue;+ }+ if (!fs.existsSync(abs)) {+ issues.push({+ severity: 'error',+ code: 'MISSING_LOCAL_ASSET',+ repair_target: 'assets',+ message: `Referenced local asset does not exist: ${ref}`,+ });+ }+ }+ return issues;+}++function canvasFrom(value) {+ const canvas = value && typeof value === 'object' && value.canvas && typeof value.canvas === 'object'+ ? value.canvas+ : {};+ return {+ width: numberOrZero(canvas.width),+ height: numberOrZero(canvas.height),+ duration: numberOrZero(canvas.duration ?? canvas.duration_sec),+ fps: numberOrZero(canvas.fps),+ };+}++function expectedCanvas(contract, timelineMap) {+ const fromTimeline = canvasFrom(timelineMap);+ const fromContract = canvasFrom(contract);+ return {+ width: fromTimeline.width || fromContract.width,+ height: fromTimeline.height || fromContract.height,+ duration: fromTimeline.duration || fromContract.duration,+ fps: fromTimeline.fps || fromContract.fps,+ };+}++function compareCanvasPair(a, b) {+ const issues = [];+ for (const key of ['width', 'height', 'duration']) {+ if (a[key] && b[key] && Math.abs(a[key] - b[key]) > (key === 'duration' ? 0.15 : 1)) {+ issues.push({+ severity: 'error',+ code: 'CONTRACT_SCENE_MAP_CANVAS_MISMATCH',+ repair_target: 'design-contract.json',+ message: `design-contract canvas ${key}=${a[key]} but scene-map canvas ${key}=${b[key]}. Keep them identical before rendering.`,+ });+ }+ }+ return issues;+}++function colorTokenValues(contract) {+ const raw = contract && typeof contract === 'object' ? contract.color_tokens : null;+ return flattenStringValues(raw)+ .map((s) => s.trim())+ .filter((s) => /^(#[0-9a-f]{3,8}\b|rgba?\(|hsla?\()/i.test(s));+}++function runContractHtmlQa(htmlPath, contractInfo, timelineMap, compositionDirAbs) {+ const html = fs.readFileSync(htmlPath, 'utf8');+ const issues = [];+ const contract = contractInfo.contract;++ if (!contractInfo.exists) {+ issues.push({+ severity: 'error',+ code: 'DESIGN_CONTRACT_MISSING',+ repair_target: 'design-contract.json',+ message: 'project/composition/design-contract.json is required before drafting model-authored HTML.',+ });+ } else if (contractInfo.error || !contract) {+ issues.push({+ severity: 'error',+ code: 'DESIGN_CONTRACT_PARSE_FAILED',+ repair_target: 'design-contract.json',+ message: `Could not parse design-contract.json: ${contractInfo.error || 'not a JSON object'}`,+ });+ }++ for (const item of extractRemoteRefs(html)) {+ issues.push({+ severity: 'error',+ code: 'REMOTE_RUNTIME_RESOURCE',+ repair_target: 'index.html',+ message: `Remote runtime resource is not allowed during render (${item.kind}: ${item.ref}). Vendor it into project/composition/assets and reference it relatively.`,+ });+ }+ if (htmlUsesGsap(html) && !hasLocalGsapVendorScript(html)) {+ issues.push({+ severity: 'error',+ code: 'GSAP_VENDOR_SCRIPT_MISSING',+ repair_target: 'index.html',+ message: 'index.html uses gsap but does not load ./assets/vendor/gsap.min.js. Use the local vendor script or remove GSAP for this composition.',+ });+ }+ issues.push(...validateLocalRefs(extractLocalRefs(html), compositionDirAbs));++ const rootTag = rootCompositionTag(html);+ const rootCanvas = rootTag ? {+ width: htmlDataNumber(rootTag, 'width'),+ height: htmlDataNumber(rootTag, 'height'),+ duration: htmlDataNumber(rootTag, 'duration'),+ } : { width: 0, height: 0, duration: 0 };+ if (!rootTag) {+ issues.push({+ severity: 'error',+ code: 'ROOT_COMPOSITION_MISSING',+ repair_target: 'index.html',+ message: 'index.html must declare a root element with data-composition-id, data-width, data-height, and data-duration.',+ });+ }++ const expected = expectedCanvas(contract, timelineMap);+ if (contract && timelineMap) {+ issues.push(...compareCanvasPair(canvasFrom(contract), canvasFrom(timelineMap)));+ }+ for (const key of ['width', 'height', 'duration']) {+ if (!expected[key]) continue;+ const tolerance = key === 'duration' ? 0.15 : 1;+ if (!rootCanvas[key] || Math.abs(rootCanvas[key] - expected[key]) > tolerance) {+ issues.push({+ severity: 'error',+ code: 'CANVAS_CONTRACT_MISMATCH',+ repair_target: 'index.html',+ message: `index.html root data-${key}=${rootCanvas[key] || 'missing'} but contract/scene-map expects ${expected[key]}.`,+ });+ }+ }++ const timelineSceneList = timelineScenes(timelineMap);+ const contractScenes = contract && Array.isArray(contract.scenes) ? contract.scenes : [];+ const scenes = timelineSceneList.length ? timelineSceneList : contractScenes;+ const duration = expected.duration || rootCanvas.duration;+ let prevEnd = -1;+ for (const scene of scenes) {+ const start = numberOrZero(scene && (scene.start ?? scene.start_sec));+ const sceneDuration = numberOrZero(scene && (scene.duration ?? scene.duration_sec));+ if (!Number.isFinite(start) || !Number.isFinite(sceneDuration) || sceneDuration <= 0) {+ issues.push({+ severity: 'error',+ code: 'SCENE_TIMING_INVALID',+ repair_target: timelineSceneList.length ? 'scene-map.json' : 'design-contract.json',+ message: `Scene "${shortText(scene && (scene.id || scene.title || scene.headline) || 'unnamed', 80)}" needs numeric start and positive duration.`,+ });+ continue;+ }+ if (duration && start + sceneDuration > duration + 0.15) {+ issues.push({+ severity: 'error',+ code: 'SCENE_TIMING_OUT_OF_RANGE',+ repair_target: timelineSceneList.length ? 'scene-map.json' : 'design-contract.json',+ message: `Scene "${shortText(scene && (scene.id || scene.title || scene.headline) || 'unnamed', 80)}" ends at ${(start + sceneDuration).toFixed(2)}s beyond the composition duration ${duration.toFixed(2)}s.`,+ });+ }+ if (prevEnd >= 0 && start < prevEnd - 0.15) {+ issues.push({+ severity: 'error',+ code: 'SCENE_TIMING_OVERLAP',+ repair_target: timelineSceneList.length ? 'scene-map.json' : 'design-contract.json',+ message: `Scene "${shortText(scene && (scene.id || scene.title || scene.headline) || 'unnamed', 80)}" starts before the prior scene ends.`,+ });+ }+ prevEnd = Math.max(prevEnd, start + sceneDuration);+ }++ const htmlSearch = normalizeForSearch(html);+ const missingText = [];+ for (const scene of scenes.slice(0, 16)) {+ for (const text of sceneDisplayTexts(scene).slice(0, 5)) {+ const needle = normalizeForSearch(text);+ if (needle && !htmlSearch.includes(needle)) {+ missingText.push({+ scene: shortText(scene && (scene.id || scene.title || scene.headline) || 'unnamed', 80),+ text: shortText(text, 100),+ });+ }+ }+ }+ for (const item of missingText.slice(0, 8)) {+ issues.push({+ severity: 'error',+ code: 'HTML_MISSING_SCENE_COPY',+ repair_target: 'index.html',+ message: `Scene "${item.scene}" declares on-screen copy not found in index.html: "${item.text}".`,+ });+ }++ const colors = colorTokenValues(contract);+ const htmlLower = html.toLowerCase();+ const unusedColors = colors.filter((color) => !htmlLower.includes(color.toLowerCase())).slice(0, 6);+ if (colors.length && unusedColors.length === colors.length) {+ issues.push({+ severity: 'warning',+ code: 'COLOR_TOKENS_NOT_USED',+ repair_target: 'index.html',+ message: 'No declared color_tokens appear in index.html. Use contract tokens as CSS variables or structured constants.',+ });+ }++ if (contractDeclaresNarrationAudio(contract) && !compositionHasAudio(html, compositionDirAbs)) {+ issues.push({+ severity: 'warning',+ code: 'NARRATION_DECLARED_BUT_SILENT',+ repair_target: 'index.html',+ message: 'design-contract.json audio declares composition-owned narration, but index.html has no <audio> element and no narration file exists. If TTS failed, tell the user and either fix the narration or explicitly proceed silent.',+ });+ }++ return {+ ok: !issues.some((issue) => issue.severity === 'error'),+ design_contract_path: contractInfo.path,+ html_path: htmlPath,+ expected_canvas: expected,+ root_canvas: rootCanvas,+ scene_count: scenes.length,+ remote_ref_count: extractRemoteRefs(html).length,+ local_ref_count: extractLocalRefs(html).length,+ issues,+ };+}++function timelineScenes(timelineMap) {+ return timelineMap && Array.isArray(timelineMap.scenes) ? timelineMap.scenes : [];+}++function timelineCanvas(timelineMap) {+ const canvas = timelineMap && typeof timelineMap.canvas === 'object' && timelineMap.canvas ? timelineMap.canvas : {};+ return {+ duration: Number(canvas.duration) || 0,+ fps: Number(canvas.fps) || 30,+ };+}++function narrationPathFromTimeline(timelineMap, compositionDirAbs) {+ const audio = timelineMap && typeof timelineMap.audio === 'object' && timelineMap.audio ? timelineMap.audio : {};+ const raw = audio.narration || audio.narration_path || audio.path;+ if (!raw) return '';+ return path.resolve(compositionDirAbs, String(raw));+}++function sceneNarrationText(scene) {+ if (!scene || typeof scene !== 'object') return '';+ const raw = scene.narration || scene.voiceover || scene.audio_text || scene.script;+ if (typeof raw === 'string') return raw.trim();+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {+ return String(raw.text || raw.body || raw.line || '').trim();+ }+ return '';+}++function sceneNarrationRef(scene) {+ if (!scene || typeof scene !== 'object') return '';+ const raw = scene.narration_ref || scene.voiceover_ref || scene.script_ref;+ if (typeof raw === 'string') return raw.trim();+ if (Array.isArray(raw) && raw.length) return raw.map((x) => String(x)).join(',');+ return '';+}++function sceneNarrationRefs(scene) {+ const raw = sceneNarrationRef(scene);+ if (!raw) return [];+ return raw.split(/[, ]+/).map((x) => x.trim()).filter(Boolean);+}++function normalizeNarrationMap(raw) {+ const root = Array.isArray(raw) ? { lines: raw } : (raw && typeof raw === 'object' ? raw : {});+ const rawLines = Array.isArray(root.lines)+ ? root.lines+ : (Array.isArray(root.segments) ? root.segments : []);+ const lines = rawLines.filter((line) => line && typeof line === 'object').map((line, index) => ({+ id: String(line.id || line.line_id || line.ref || `line-${index + 1}`),+ start: numberOrZero(line.start ?? line.start_sec ?? line.begin),+ duration: numberOrZero(line.duration ?? line.duration_sec ?? line.target_sec),+ text: String(line.text || line.narration || line.body || '').trim(),+ }));+ const byId = new Map();+ for (const line of lines) byId.set(line.id, line);+ return { lines, byId };+}++function loadNarrationMap(compositionDirAbs) {+ const candidates = [+ path.join(compositionDirAbs, 'narration-map.json'),+ path.join(compositionDirAbs, 'audio-map.json'),+ ];+ for (const mapPath of candidates) {+ if (!fs.existsSync(mapPath)) continue;+ const loaded = readJsonFile(mapPath);+ if (loaded.error) return { path: mapPath, lines: [], byId: new Map(), error: loaded.error };+ return { path: mapPath, ...normalizeNarrationMap(loaded.value) };+ }+ return { path: '', lines: [], byId: new Map() };+}++function normalizeShotlist(raw) {+ const root = Array.isArray(raw) ? raw : (raw && typeof raw === 'object' ? raw : {});+ const shots = Array.isArray(root) ? root : (root.shots || root.scenes || root.storyboard || []);+ if (!Array.isArray(shots)) return [];+ return shots.filter((shot) => shot && typeof shot === 'object').map((shot, index) => ({+ id: String(shot.id || shot.name || shot.shot || `shot-${index + 1}`),+ start: Number(shot.start ?? shot.start_sec ?? shot.in_sec),+ duration: Number(shot.duration ?? shot.duration_sec ?? shot.target_sec),+ narration: sceneNarrationText(shot),+ }));+}++function loadShotlist(compositionDirAbs) {+ const projectDir = path.dirname(compositionDirAbs);+ const candidates = [+ path.join(projectDir, 'shotlist.json'),+ path.join(projectDir, 'storyboard.json'),+ ];+ for (const shotlistPath of candidates) {+ if (!fs.existsSync(shotlistPath)) continue;+ try {+ return {+ path: shotlistPath,+ shots: normalizeShotlist(JSON.parse(fs.readFileSync(shotlistPath, 'utf8'))),+ };+ } catch (err) {+ return {+ path: shotlistPath,+ shots: [],+ error: err && err.message ? err.message : String(err),+ };+ }+ }+ return { path: '', shots: [] };+}++function sceneSourceShots(scene) {+ if (!scene || typeof scene !== 'object') return [];+ const raw = scene.source_shots || scene.shot_ids || scene.shots || scene.sourceShotIds;+ if (Array.isArray(raw)) return raw.map((x) => String(x)).filter(Boolean);+ if (typeof raw === 'string' && raw.trim()) return raw.split(/[, ]+/).map((x) => x.trim()).filter(Boolean);+ return [];+}++function hasMergeExplanation(timelineMap, scenes) {+ const alignment = timelineMap && typeof timelineMap === 'object'+ ? (timelineMap.source_alignment || timelineMap.alignment || timelineMap.timeline_alignment || {})+ : {};+ if (alignment && typeof alignment === 'object' && !Array.isArray(alignment)) {+ if (String(alignment.merge_reason || alignment.merge_policy || '').trim()) return true;+ }+ return scenes.some((scene) => String(scene.merge_reason || scene.alignment_note || '').trim())+ || scenes.every((scene) => sceneSourceShots(scene).length > 0);+}++function runSourceAlignmentQa(timelineMap, compositionDirAbs) {+ const scenes = timelineScenes(timelineMap);+ const shotlist = loadShotlist(compositionDirAbs);+ const issues = [];+ if (shotlist.error) {+ issues.push({+ severity: 'warning',+ code: 'SHOTLIST_PARSE_FAILED',+ message: `Could not parse ${shotlist.path}: ${shotlist.error}`,+ });+ }+ if (shotlist.shots.length && scenes.length && shotlist.shots.length !== scenes.length && !hasMergeExplanation(timelineMap, scenes)) {+ issues.push({+ severity: 'error',+ code: 'SHOTLIST_SCENE_COUNT_MISMATCH',+ message: `shotlist has ${shotlist.shots.length} shots but scene-map has ${scenes.length} scenes. Add source_alignment.merge_reason or per-scene source_shots when intentionally merging beats.`,+ });+ }+ return {+ ok: !issues.some((issue) => issue.severity === 'error'),+ skipped: !shotlist.path,+ shotlist_path: shotlist.path,+ shot_count: shotlist.shots.length,+ scene_count: scenes.length,+ issues,+ };+}++function buildVideoQaSamples(timelineMap, probe) {+ const duration = probe.duration_seconds || timelineCanvas(timelineMap).duration || 0;+ const scenes = timelineScenes(timelineMap);+ const samples = [{ id: 'first_frame', role: 'first_frame', time: 0 }];+ for (const scene of scenes.slice(0, 12)) {+ const id = shortText(scene && (scene.id || scene.name || scene.title) || 'scene', 80);+ const start = Number(scene && scene.start);+ const sceneDuration = Number(scene && (scene.duration || scene.duration_sec));+ if (!Number.isFinite(start) || !Number.isFinite(sceneDuration) || sceneDuration <= 0) continue;+ samples.push({ id, role: 'scene_start', time: Math.min(Math.max(start + 0.2, 0), Math.max(duration - 0.1, 0)) });+ samples.push({ id, role: 'scene_mid', time: Math.min(Math.max(start + sceneDuration / 2, 0), Math.max(duration - 0.1, 0)) });+ }+ return samples;+}++function sampleFrameStats(mediaPath, time) {+ const ffmpeg = resolveMediaTool('ffmpeg');+ const width = 160;+ const height = 90;+ const res = runProcess(ffmpeg, [+ '-hide_banner',+ '-loglevel', 'error',+ '-ss', Number(time).toFixed(3),+ '-i', mediaPath,+ '-frames:v', '1',+ '-vf', `scale=${width}:${height},format=rgb24`,+ '-f', 'rawvideo',+ 'pipe:1',+ ], { encoding: 'buffer', maxBuffer: width * height * 3 + 1024 });+ const buf = res.stdout;+ if (!Buffer.isBuffer(buf) || buf.length < width * height * 3) throw new Error(`could not sample frame at ${time}s`);+ const luma = new Float32Array(width * height);+ let sum = 0;+ for (let i = 0, p = 0; i < luma.length; i += 1, p += 3) {+ const y = 0.2126 * buf[p] + 0.7152 * buf[p + 1] + 0.0722 * buf[p + 2];+ luma[i] = y;+ sum += y;+ }+ const mean = sum / luma.length;+ let variance = 0;+ let edgeSum = 0;+ let edgeCount = 0;+ for (let y = 0; y < height; y += 1) {+ for (let x = 0; x < width; x += 1) {+ const idx = y * width + x;+ const d = luma[idx] - mean;+ variance += d * d;+ if (x > 0) { edgeSum += Math.abs(luma[idx] - luma[idx - 1]); edgeCount += 1; }+ if (y > 0) { edgeSum += Math.abs(luma[idx] - luma[idx - width]); edgeCount += 1; }+ }+ }+ const stddev = Math.sqrt(variance / luma.length);+ const edge = edgeCount ? edgeSum / edgeCount : 0;+ return {+ mean: Number(mean.toFixed(2)),+ stddev: Number(stddev.toFixed(2)),+ edge: Number(edge.toFixed(2)),+ fingerprint: crypto.createHash('sha1').update(buf.subarray(0, width * height * 3)).digest('hex').slice(0, 16),+ low_information: stddev < 14 && edge < 2.8,+ };+}++function detectStaticFrameRun(samples) {+ const visual = samples+ .filter((sample) => sample && !sample.error && sample.stats && sample.stats.fingerprint)+ .sort((a, b) => Number(a.time) - Number(b.time));+ let best = [];+ let run = [];+ for (const sample of visual) {+ const last = run[run.length - 1];+ if (last && last.stats.fingerprint === sample.stats.fingerprint) {+ run.push(sample);+ } else {+ if (run.length > best.length) best = run;+ run = [sample];+ }+ }+ if (run.length > best.length) best = run;+ if (best.length < 5) return null;+ const span = Number(best[best.length - 1].time) - Number(best[0].time);+ const sceneIds = new Set(best.map((sample) => `${sample.id || ''}`).filter(Boolean));+ if (span < 12 || sceneIds.size < 2) return null;+ return {+ count: best.length,+ start_time: Number(Number(best[0].time).toFixed(3)),+ end_time: Number(Number(best[best.length - 1].time).toFixed(3)),+ scene_count: sceneIds.size,+ fingerprint: best[0].stats.fingerprint,+ };+}++function writeContactSheet(mediaPath, samples, probe, reportPath) {+ if (!samples.length) return '';+ const ffmpeg = resolveMediaTool('ffmpeg');+ const fps = probe.video && probe.video.fps ? probe.video.fps : 30;+ const frames = [...new Set(samples.map((s) => Math.max(0, Math.round(s.time * fps))))].sort((a, b) => a - b).slice(0, 16);+ if (!frames.length) return '';+ const rows = Math.ceil(frames.length / 4);+ const selector = frames.map((n) => `eq(n\\,${n})`).join('+');+ const out = path.join(path.dirname(reportPath), `${path.basename(reportPath, path.extname(reportPath))}-contact-sheet.jpg`);+ fs.mkdirSync(path.dirname(out), { recursive: true });+ runProcess(ffmpeg, [+ '-y',+ '-hide_banner',+ '-loglevel', 'error',+ '-i', mediaPath,+ '-vf', `select=${selector},scale=420:-1,tile=4x${rows}`,+ '-frames:v', '1',+ out,+ ]);+ return out;+}++function safeFilePart(value) {+ const part = String(value || 'frame').toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');+ return part.slice(0, 80) || 'frame';+}++function writeEvidenceFrames(mediaPath, samples, reportPath) {+ const ffmpeg = resolveMediaTool('ffmpeg');+ const dir = path.join(path.dirname(reportPath), `${path.basename(reportPath, path.extname(reportPath))}-frames`);+ fs.mkdirSync(dir, { recursive: true });+ const frames = [];+ const seen = new Set();+ for (const sample of samples.slice(0, 16)) {+ const key = `${sample.role}\u0000${sample.id}\u0000${Number(sample.time).toFixed(3)}`;+ if (seen.has(key)) continue;+ seen.add(key);+ const filename = `${String(frames.length + 1).padStart(2, '0')}-${safeFilePart(sample.role)}-${safeFilePart(sample.id)}.jpg`;+ const out = path.join(dir, filename);+ runProcess(ffmpeg, [+ '-y',+ '-hide_banner',+ '-loglevel', 'error',+ '-ss', Number(sample.time).toFixed(3),+ '-i', mediaPath,+ '-frames:v', '1',+ '-vf', 'scale=960:-1',+ '-q:v', '3',+ out,+ ]);+ frames.push({+ id: sample.id,+ role: sample.role,+ time: sample.time,+ path: out,+ });+ }+ return { dir, frames };+}++function runVideoQa(mediaPath, timelineMap, probe, reportPath) {+ const samples = buildVideoQaSamples(timelineMap, probe);+ const issues = [];+ const sampled = samples.map((sample) => {+ try {+ const stats = sampleFrameStats(mediaPath, sample.time);+ const isBlockingRole = sample.role === 'first_frame' || sample.role === 'scene_start';+ if (isBlockingRole && stats.low_information) {+ issues.push({+ severity: 'error',+ code: sample.role === 'first_frame' ? 'FIRST_FRAME_EMPTY' : 'SCENE_START_EMPTY',+ sample: sample.id,+ time: sample.time,+ message: `${sample.role} at ${sample.time.toFixed(2)}s has too little visual information; keep the hook/title visible at scene start.`,+ });+ }+ return { ...sample, stats };+ } catch (err) {+ issues.push({+ severity: 'warning',+ code: 'FRAME_SAMPLE_FAILED',+ sample: sample.id,+ time: sample.time,+ message: err && err.message ? err.message : String(err),+ });+ return { ...sample, error: err && err.message ? err.message : String(err) };+ }+ });+ const staticRun = detectStaticFrameRun(sampled);+ if (staticRun) {+ issues.push({+ severity: 'error',+ code: 'STATIC_FRAME_RUN',+ ...staticRun,+ message: `${staticRun.count} sampled frames across ${staticRun.scene_count} scenes are pixel-identical from ${staticRun.start_time.toFixed(2)}s to ${staticRun.end_time.toFixed(2)}s; the render likely froze or the timeline is not being driven.`,+ });+ }+ let contactSheet = '';+ try {+ contactSheet = writeContactSheet(mediaPath, sampled, probe, reportPath);+ } catch (err) {+ issues.push({+ severity: 'warning',+ code: 'CONTACT_SHEET_FAILED',+ message: err && err.message ? err.message : String(err),+ });+ }+ let evidence = { dir: '', frames: [] };+ try {+ evidence = writeEvidenceFrames(mediaPath, sampled, reportPath);+ } catch (err) {+ issues.push({+ severity: 'warning',+ code: 'FRAME_EVIDENCE_FAILED',+ message: err && err.message ? err.message : String(err),+ });+ }+ const framePathByKey = new Map(evidence.frames.map((frame) => [+ `${frame.role}\u0000${frame.id}\u0000${Number(frame.time).toFixed(3)}`,+ frame.path,+ ]));+ return {+ ok: !issues.some((issue) => issue.severity === 'error'),+ issue_count: issues.length,+ issues,+ samples: sampled.map((sample) => ({+ ...sample,+ frame_path: framePathByKey.get(`${sample.role}\u0000${sample.id}\u0000${Number(sample.time).toFixed(3)}`) || '',+ })),+ contact_sheet: contactSheet,+ evidence_dir: evidence.dir,+ frame_paths: evidence.frames,+ };+}++function runAudioTimingQa(timelineMap, compositionDirAbs) {+ const scenes = timelineScenes(timelineMap);+ const narrationPath = narrationPathFromTimeline(timelineMap, compositionDirAbs);+ const narrationMap = loadNarrationMap(compositionDirAbs);+ const issues = [];+ if (narrationMap.error) {+ issues.push({+ severity: 'error',+ code: 'NARRATION_MAP_PARSE_FAILED',+ message: `Could not parse ${narrationMap.path}: ${narrationMap.error}`,+ });+ }+ if (narrationPath && !fs.existsSync(narrationPath)) {+ issues.push({+ severity: 'error',+ code: 'NARRATION_ASSET_MISSING',+ message: `scene-map declares narration audio but the file does not exist: ${narrationPath}`,+ });+ return {+ ok: false,+ skipped: false,+ narration_path: narrationPath,+ narration_map_path: narrationMap.path,+ issues,+ };+ }+ if (!narrationPath) {+ return {+ ok: !issues.some((issue) => issue.severity === 'error'),+ skipped: true,+ reason: 'no narration asset in scene-map',+ narration_map_path: narrationMap.path,+ issues,+ };+ }+ const narrationProbe = probeMedia(narrationPath);+ const duration = narrationProbe.duration_seconds || 0;+ if (scenes.length) {+ const last = scenes[scenes.length - 1] || {};+ const lastStart = Number(last.start);+ if (Number.isFinite(lastStart) && duration > 0 && lastStart > duration + 0.15) {+ issues.push({+ severity: 'warning',+ code: 'CLOSING_AFTER_NARRATION',+ message: `The final scene starts at ${lastStart.toFixed(2)}s but narration ends around ${duration.toFixed(2)}s. Align the closing visual with the final narrated line unless this is an intentional silent tail.`,+ });+ }+ }+ const mappedScenes = scenes.filter((scene) => sceneNarrationText(scene) || sceneNarrationRef(scene) || sceneSourceShots(scene).length);+ if (scenes.length >= 2 && mappedScenes.length < scenes.length) {+ issues.push({+ severity: 'error',+ code: 'SCENE_NARRATION_MISSING',+ message: `${scenes.length - mappedScenes.length} of ${scenes.length} scenes do not declare narration text or narration_ref, so voiceover-to-visual alignment cannot be verified.`,+ });+ }+ const refScenes = scenes.filter((scene) => sceneNarrationRefs(scene).length);+ if (refScenes.length && narrationMap.lines.length) {+ for (const scene of refScenes) {+ const refs = sceneNarrationRefs(scene);+ const lines = refs.map((ref) => narrationMap.byId.get(ref)).filter(Boolean);+ const missing = refs.filter((ref) => !narrationMap.byId.has(ref));+ if (missing.length) {+ issues.push({+ severity: 'error',+ code: 'NARRATION_REF_MISSING',+ scene: scene.id || scene.title || '',+ message: `Scene references narration line(s) not found in narration-map.json: ${missing.join(', ')}`,+ });+ continue;+ }+ const expectedStart = Math.min(...lines.map((line) => line.start));+ const expectedEnd = Math.max(...lines.map((line) => line.start + Math.max(line.duration, 0)));+ const actualStart = numberOrZero(scene.start ?? scene.start_sec);+ const actualEnd = actualStart + numberOrZero(scene.duration ?? scene.duration_sec);+ const startDrift = actualStart - expectedStart;+ if (Math.abs(startDrift) > 1.25) {+ issues.push({+ severity: 'error',+ code: 'NARRATION_LINE_START_DRIFT',+ scene: scene.id || scene.title || '',+ message: `Scene starts at ${actualStart.toFixed(2)}s but narration-map line timing starts at ${expectedStart.toFixed(2)}s (${startDrift.toFixed(2)}s drift).`,+ });+ }+ if (expectedEnd > actualEnd + 1.25) {+ issues.push({+ severity: 'error',+ code: 'NARRATION_LINE_OVERFLOWS_SCENE',+ scene: scene.id || scene.title || '',+ message: `Scene ends at ${actualEnd.toFixed(2)}s but referenced narration line(s) run until ${expectedEnd.toFixed(2)}s.`,+ });+ }+ }+ } else if (refScenes.length && !narrationMap.lines.length) {+ issues.push({+ severity: 'warning',+ code: 'NARRATION_MAP_MISSING',+ message: 'Scenes use narration_ref but no narration-map.json exists, so draft QA falls back to coarse timing checks.',+ });+ }+ const narratedScenes = scenes.filter((scene) => sceneNarrationText(scene));+ if (!narrationMap.lines.length && narratedScenes.length >= 2 && duration > 0) {+ const totalChars = narratedScenes.reduce((sum, scene) => sum + sceneNarrationText(scene).length, 0);+ let cursorChars = 0;+ for (const scene of narratedScenes) {+ const expectedStart = totalChars > 0 ? (cursorChars / totalChars) * duration : 0;+ const actualStart = Number(scene.start) || 0;+ const drift = actualStart - expectedStart;+ if (Math.abs(drift) > 3.5) {+ issues.push({+ severity: 'error',+ code: 'AUDIO_TIMING_DRIFT',+ scene: scene.id || scene.title || '',+ message: `Scene starts at ${actualStart.toFixed(2)}s but estimated narration timing is ${expectedStart.toFixed(2)}s (${drift.toFixed(2)}s drift).`,+ });+ }+ cursorChars += sceneNarrationText(scene).length;+ }+ } else if (!narrationMap.lines.length && mappedScenes.length >= 2 && narratedScenes.length < 2) {+ issues.push({+ severity: 'warning',+ code: 'AUDIO_TIMING_ESTIMATE_SKIPPED',+ message: 'Scenes use narration references or source_shots without inline narration text, so draft QA can verify mapping presence but cannot estimate timing drift.',+ });+ }+ return {+ ok: !issues.some((issue) => issue.severity === 'error'),+ skipped: false,+ narration_path: narrationPath,+ narration_map_path: narrationMap.path,+ narration_duration_seconds: duration,+ issues,+ };+}++function writeJsonFile(rawPath, payload) {+ const abs = resolveOutputPath(rawPath);+ fs.mkdirSync(path.dirname(abs), { recursive: true });+ fs.writeFileSync(abs, JSON.stringify(payload, null, 2), 'utf8');+ return abs;+}++function readJsonFileIfExists(abs) {+ try {+ if (!abs || !fs.existsSync(abs)) return null;+ return JSON.parse(fs.readFileSync(abs, 'utf8'));+ } catch {+ return null;+ }+}++function draftRepairStatePath(compositionDirAbs) {+ return path.join(compositionDirAbs, 'qa', 'draft-repair-state.json');+}++function draftContentSignature(compositionDirAbs) {+ const hash = crypto.createHash('sha256');+ for (const name of ['design-contract.json', 'scene-map.json', 'narration-map.json', 'index.html']) {+ const abs = path.join(compositionDirAbs, name);+ if (!fs.existsSync(abs)) continue;+ hash.update(name);+ hash.update('\0');+ hash.update(fs.readFileSync(abs));+ hash.update('\0');+ }+ return hash.digest('hex');+}++function normalizeRepairState(raw) {+ const failedAttempts = Math.max(0, Number(raw && raw.failed_attempts) || 0);+ return {+ status: raw && raw.status === 'failed' ? 'failed' : 'ok',+ failed_attempts: failedAttempts,+ repair_passes_used: Math.max(0, failedAttempts - 1),+ max_repair_passes: DRAFT_REPAIR_MAX_PASSES,+ last_error: raw && raw.last_error && typeof raw.last_error === 'object' ? raw.last_error : null,+ history: raw && Array.isArray(raw.history) ? raw.history.slice(-12) : [],+ };+}++function repairBudgetSummary(statePath, state) {+ const failedAttempts = Math.max(0, Number(state && state.failed_attempts) || 0);+ const used = Math.max(0, failedAttempts - 1);+ const budgetExhausted = failedAttempts > 0 && used >= DRAFT_REPAIR_MAX_PASSES;+ return {+ ok: !budgetExhausted,+ budget_exhausted: budgetExhausted,+ state_path: statePath,+ max_repair_passes: DRAFT_REPAIR_MAX_PASSES,+ failed_attempts: failedAttempts,+ repair_passes_used: used,+ repair_passes_remaining: Math.max(0, DRAFT_REPAIR_MAX_PASSES - used),+ last_error: state && state.last_error ? state.last_error : null,+ };+}++function initDraftRepairBudget(compositionDirAbs) {+ const statePath = draftRepairStatePath(compositionDirAbs);+ const state = normalizeRepairState(readJsonFileIfExists(statePath));+ const summary = repairBudgetSummary(statePath, state);+ return {+ compositionDirAbs,+ statePath,+ state,+ summary,+ blocked: state.status === 'failed' && summary.repair_passes_used >= DRAFT_REPAIR_MAX_PASSES,+ };+}++function writeRepairState(statePath, state) {+ fs.mkdirSync(path.dirname(statePath), { recursive: true });+ fs.writeFileSync(statePath, JSON.stringify(state, null, 2), 'utf8');+}++function recordDraftFailure(repairBudget, reportAbs, code, message, extra = {}) {+ if (!repairBudget) return null;+ const previous = normalizeRepairState(readJsonFileIfExists(repairBudget.statePath) || repairBudget.state);+ const failedAttempts = previous.failed_attempts + 1;+ const entry = {+ ts: new Date().toISOString(),+ code,+ message: shortText(message, 300),+ report_path: reportAbs,+ repair_target: shortText(extra.repair_target || '', 120),+ content_signature: draftContentSignature(repairBudget.compositionDirAbs),+ };+ const next = {+ status: 'failed',+ max_repair_passes: DRAFT_REPAIR_MAX_PASSES,+ failed_attempts: failedAttempts,+ repair_passes_used: Math.max(0, failedAttempts - 1),+ last_error: entry,+ history: [...previous.history, entry].slice(-12),+ };+ writeRepairState(repairBudget.statePath, next);+ repairBudget.state = next;+ repairBudget.summary = repairBudgetSummary(repairBudget.statePath, next);+ repairBudget.blocked = repairBudget.summary.repair_passes_used >= DRAFT_REPAIR_MAX_PASSES;+ return repairBudget.summary;+}++function recordDraftSuccess(repairBudget, reportAbs, renderPath) {+ if (!repairBudget) return null;+ const previous = normalizeRepairState(readJsonFileIfExists(repairBudget.statePath) || repairBudget.state);+ const next = {+ status: 'ok',+ max_repair_passes: DRAFT_REPAIR_MAX_PASSES,+ failed_attempts: 0,+ repair_passes_used: 0,+ last_success: {+ ts: new Date().toISOString(),+ report_path: reportAbs,+ path: renderPath || '',+ content_signature: draftContentSignature(repairBudget.compositionDirAbs),+ },+ history: previous.history,+ };+ writeRepairState(repairBudget.statePath, next);+ repairBudget.state = next;+ repairBudget.summary = repairBudgetSummary(repairBudget.statePath, next);+ repairBudget.blocked = false;+ return repairBudget.summary;+}++function failDraft(report, reportAbs, code, message, extra = {}, repairBudget = null) {+ report.error = {+ code,+ message,+ ...(extra.repair_target ? { repair_target: extra.repair_target } : {}),+ };+ const budgetSummary = recordDraftFailure(repairBudget, reportAbs, code, message, extra);+ if (budgetSummary) {+ report.steps.repair_budget = budgetSummary;+ report.repair_budget = budgetSummary;+ }+ report.report_path = writeJsonFile(reportAbs, report);+ fail(code, message, {+ report_path: report.report_path,+ ...(budgetSummary ? { repair_budget: budgetSummary } : {}),+ ...extra,+ });+}+module.exports = async function renderCompositionScript({ args }) {const opts = parseArgs(args || []);if (opts.help) return help();if (!OPS.has(opts.op)) fail('E_ARGS', `op must be one of: ${[...OPS].join(', ')}`);+ if (opts.findingsInline && !FINDINGS_INLINE.has(opts.findingsInline)) {+ fail('E_ARGS', `--findings-inline must be one of: ${[...FINDINGS_INLINE].join(', ')}`);+ }if (!opts.compositionDir) fail('E_ARGS', '--composition-dir is required');+ if (opts.op === 'draft') {+ const compositionDirAbs = resolveOrCreateDir(opts.compositionDir);+ const format = FORMAT.has(opts.format) ? opts.format : 'mp4';+ const quality = QUALITY.has(opts.quality) ? opts.quality : 'draft';+ const out = await outputFile(opts.outputPath, format);+ const reportAbs = opts.reportPath+ ? resolveOutputPath(opts.reportPath)+ : path.join(path.dirname(out.finalPath), `${path.basename(out.finalPath, path.extname(out.finalPath))}-report.json`);+ const findingsAbs = opts.findingsOutputPath+ ? resolveOutputPath(opts.findingsOutputPath)+ : path.join(compositionDirAbs, 'qa', 'inspect.json');+ const lintFindingsAbs = path.join(compositionDirAbs, 'qa', 'lint.json');+ const report = {+ ok: false,+ op: 'draft',+ composition_dir: compositionDirAbs,+ requested_path: out.requested,+ path: out.finalPath,+ renamed: out.renamed,+ steps: {},+ };+ const repairBudget = initDraftRepairBudget(compositionDirAbs);+ report.steps.repair_budget = repairBudget.summary;+ report.repair_budget = repairBudget.summary;+ if (repairBudget.blocked) {+ report.error = {+ code: 'E_REPAIR_BUDGET_EXCEEDED',+ message: `Draft repair budget exceeded: the initial draft plus ${DRAFT_REPAIR_MAX_PASSES} repair pass(es) still failed. Stop and report the blocker instead of continuing to patch.`,+ };+ report.report_path = writeJsonFile(reportAbs, report);+ fail('E_REPAIR_BUDGET_EXCEEDED', report.error.message, {+ report_path: report.report_path,+ repair_budget: repairBudget.summary,+ last_error: repairBudget.summary.last_error,+ });+ }+ const { renderComposition, qaComposition, isConstrainedMachine, estimateRenderCost, renderCostDecision, degradedFps, machineRamGB } = require('./lib/video_render_core.cjs');+ try {+ if (opts.specPath || fs.existsSync(path.join(compositionDirAbs, 'spec.json'))) {+ failDraft(report, reportAbs, 'E_SPEC_COMPILER_REMOVED', 'COMPOSE spec compilation has been removed. Write project/composition/index.html directly and optional scene-map.json for timing QA.', {}, repairBudget);+ }+ const htmlPath = path.join(compositionDirAbs, 'index.html');+ if (!fs.existsSync(htmlPath)) {+ failDraft(report, reportAbs, 'E_RENDER_NO_COMPOSITION', `No hand-authored index.html found in ${compositionDirAbs}`, {}, repairBudget);+ }+ const timeline = loadTimelineMap(compositionDirAbs);+ if (timeline.error) {+ failDraft(report, reportAbs, 'E_SCENE_MAP_PARSE_FAILED', `Could not parse ${timeline.path}: ${timeline.error}`, {+ repair_target: path.basename(timeline.path),+ }, repairBudget);+ }+ const timelineMap = timeline.map;+ if (!timelineMap && htmlNeedsSceneMap(compositionDirAbs)) {+ failDraft(report, reportAbs, 'E_SCENE_MAP_REQUIRED', 'Narrated hand-authored HTML requires project/composition/scene-map.json so draft QA can verify voiceover-to-visual alignment.', {}, repairBudget);+ }+ const contractInfo = loadDesignContract(compositionDirAbs);+ report.authoring_mode = 'hand_authored_html';+ report.steps.authoring = {+ ok: true,+ mode: 'hand_authored_html',+ path: htmlPath,+ timeline_path: timeline.path || '',+ design_contract_path: contractInfo.path,+ text: 'Using model-authored project/composition/index.html.',+ };+ report.timeline_path = timeline.path || '';+ report.canvas = timelineMap ? timelineCanvas(timelineMap) : {};++ report.steps.vendor_assets = ensureVendorAssets(htmlPath, compositionDirAbs);+ if (report.steps.vendor_assets.ok === false) {+ const firstError = report.steps.vendor_assets.issues.find((issue) => issue.severity === 'error') || {};+ const repairTarget = firstError.repair_target || 'assets';+ failDraft(report, reportAbs, 'E_VENDOR_ASSETS_BLOCKED', 'could not prepare local composition vendor assets', {+ repair_target: repairTarget,+ vendor_assets: report.steps.vendor_assets,+ }, repairBudget);+ }++ report.steps.contract_html = runContractHtmlQa(htmlPath, contractInfo, timelineMap, compositionDirAbs);+ if (report.steps.contract_html.ok === false) {+ const firstError = report.steps.contract_html.issues.find((issue) => issue.severity === 'error') || {};+ const repairTarget = firstError.repair_target || 'index.html';+ failDraft(report, reportAbs, 'E_CONTRACT_HTML_BLOCKED', 'design-contract/scene-map/index.html consistency failed draft QA', {+ repair_target: repairTarget,+ contract_html: report.steps.contract_html,+ }, repairBudget);+ }++ report.steps.source_alignment = runSourceAlignmentQa(timelineMap, compositionDirAbs);+ if (report.steps.source_alignment.ok === false) {+ failDraft(report, reportAbs, 'E_SOURCE_ALIGNMENT_BLOCKED', 'script/shotlist/scene-map alignment failed draft QA', {+ source_alignment: report.steps.source_alignment,+ }, repairBudget);+ }++ report.steps.audio_timing = runAudioTimingQa(timelineMap, compositionDirAbs);+ if (report.steps.audio_timing.ok === false) {+ failDraft(report, reportAbs, 'E_AUDIO_TIMING_BLOCKED', 'audio timing drift failed draft QA', {+ audio_timing: report.steps.audio_timing,+ }, repairBudget);+ }++ // Render-resilience profile (P1/P2): weak/no-GPU machines software-render,+ // which is slow and memory-heavy. Detect the constraint, use the+ // low-memory render profile, and degrade a heavy DRAFT (lower fps) instead+ // of crashing / hanging. (A final render fails fast — handled below.)+ const renderCanvas = expectedCanvas(contractInfo.contract, timelineMap);+ const requestedFps = typeof opts.fps === 'number'+ ? opts.fps+ : (contractInfo.contract && contractInfo.contract.canvas && typeof contractInfo.contract.canvas.fps === 'number' ? contractInfo.contract.canvas.fps : 30);+ const ramGB = machineRamGB();+ const constrained = isConstrainedMachine(ramGB);+ const costUnits = estimateRenderCost(renderCanvas.width || 1920, renderCanvas.height || 1080, renderCanvas.duration || 0, requestedFps);+ const costDecision = renderCostDecision({ constrained, costUnits, isFinal: false });+ const renderFps = costDecision === 'degrade' ? degradedFps(requestedFps) : requestedFps;+ report.steps.render_profile = {+ constrained,+ machine_ram_gb: ramGB,+ cost_units: costUnits,+ decision: costDecision,+ ...(renderFps !== requestedFps ? { degraded_fps: `${requestedFps}→${renderFps}` } : {}),+ };++ const lint = await qaComposition('lint', {+ constrained,+ onProgress: makeProgressEmitter('draft'),+ logPath: renderLogPath(compositionDirAbs, 'qa-lint'),+ projectDirAbs: compositionDirAbs,+ });+ if (lint.ok === false) {+ report.steps.lint = {+ ok: false,+ error_code: lint.errorCode || 'E_LINT_FAILED',+ message: lint.message || 'lint failed',+ };+ failDraft(report, reportAbs, lint.errorCode || 'E_LINT_FAILED', lint.message || 'lint failed', {+ lint: report.steps.lint,+ }, repairBudget);+ }+ const lintSummary = summarizeFindings(lint.findings);+ report.steps.lint = {+ ok: lintSummary.ok,+ summary: lintSummary,+ findings_path: writeFindingsOutput(lintFindingsAbs, {+ ok: true,+ op: 'lint',+ summary: lintSummary,+ findings: lint.findings,+ }),+ };+ if (lintSummary.ok === false || (lintSummary.errorCount || 0) > 0) {+ failDraft(report, reportAbs, 'E_LINT_BLOCKED', 'HyperFrames lint failed; repair render-contract issues before inspect/render', {+ lint_summary: lintSummary,+ }, repairBudget);+ }++ const inspect = await qaComposition('inspect', {+ projectDirAbs: compositionDirAbs,+ strictCraft: true,+ constrained,+ onProgress: makeProgressEmitter('draft'),+ logPath: renderLogPath(compositionDirAbs, 'qa-inspect'),+ });+ if (inspect.ok === false) {+ report.steps.inspect = {+ ok: false,+ error_code: inspect.errorCode || 'E_INSPECT_FAILED',+ message: inspect.message || 'inspect failed',+ };+ failDraft(report, reportAbs, inspect.errorCode || 'E_INSPECT_FAILED', inspect.message || 'inspect failed', {+ inspect: report.steps.inspect,+ }, repairBudget);+ }+ const inspectSummary = summarizeFindings(inspect.findings);+ const inspectDisposition = summarizeDraftInspectDisposition(inspect.findings);+ const hasUnclassifiedInspectFailure = (inspectSummary.ok === false || (inspectSummary.errorCount || 0) > 0)+ && inspectDisposition.blocking_error_count === 0+ && inspectDisposition.advisory_count === 0;+ report.steps.inspect = {+ ok: inspectDisposition.blocking_error_count === 0 && !hasUnclassifiedInspectFailure,+ qa_ok: inspectSummary.ok,+ summary: inspectSummary,+ draft_disposition: inspectDisposition,+ findings_path: writeFindingsOutput(findingsAbs, {+ ok: true,+ op: 'inspect',+ summary: inspectSummary,+ draft_disposition: inspectDisposition,+ findings: inspect.findings,+ }),+ };+ if (inspectDisposition.blocking_error_count > 0 || hasUnclassifiedInspectFailure) {+ failDraft(report, reportAbs, 'E_INSPECT_BLOCKED', 'inspect found non-visual blockers; repair design-contract/scene-map/HTML before rendering', {+ inspect_summary: inspectSummary,+ draft_disposition: inspectDisposition,+ }, repairBudget);+ }++ const render = await renderComposition({+ projectDirAbs: compositionDirAbs,+ outputAbsPath: out.finalPath,+ quality,+ ...(typeof renderFps === 'number' ? { fps: renderFps } : {}),+ format,+ ...(opts.variables && typeof opts.variables === 'object' && !Array.isArray(opts.variables) ? { variables: opts.variables } : {}),+ constrained,+ onProgress: makeProgressEmitter('draft'),+ logPath: renderLogPath(compositionDirAbs, 'render'),+ });+ if (render.ok === false) {+ report.steps.render = render;+ failDraft(report, reportAbs, render.errorCode || 'E_RENDER_FAILED', render.message || 'render failed', {+ render,+ }, repairBudget);+ }+ report.steps.render = render;++ report.media_before_audio_postprocess = probeMedia(render.path);+ if (report.media_before_audio_postprocess.audio) {+ report.steps.loudness_before = analyzeLoudness(render.path);+ report.steps.audio_normalize = opts.normalizeAudio+ ? normalizeAudioInPlace(render.path)+ : { skipped: true, reason: 'disabled by args' };+ } else {+ report.steps.audio_normalize = { skipped: true, reason: 'no audio stream' };+ }+ report.media = probeMedia(render.path);+ if (report.media.audio) report.steps.loudness_after = analyzeLoudness(render.path);++ report.steps.video_qa = opts.videoQa+ ? runVideoQa(render.path, timelineMap, report.media, reportAbs)+ : { ok: true, skipped: true, reason: 'disabled by args' };+ if (report.steps.video_qa.ok === false) {+ failDraft(report, reportAbs, 'E_VIDEO_QA_BLOCKED', 'video-level QA failed; repair design-contract/scene-map/HTML before Gate D', {+ video_qa: report.steps.video_qa,+ }, repairBudget);+ }++ report.ok = true;+ const successBudget = recordDraftSuccess(repairBudget, reportAbs, render.path);+ if (successBudget) {+ report.steps.repair_budget = successBudget;+ report.repair_budget = successBudget;+ }+ report.report_path = writeJsonFile(reportAbs, report);+ return {+ ok: true,+ op: 'draft',+ path: render.path,+ bytes: render.bytes,+ media: `chat-media://local/${render.path}`,+ report_path: report.report_path,+ findings_path: report.steps.inspect.findings_path,+ contact_sheet: report.steps.video_qa.contact_sheet || '',+ evidence_dir: report.steps.video_qa.evidence_dir || '',+ frame_paths: report.steps.video_qa.frame_paths || [],+ probe: report.media,+ inspect: {+ ok: report.steps.inspect.ok,+ qa_ok: report.steps.inspect.qa_ok,+ advisory_count: report.steps.inspect.draft_disposition.advisory_count,+ blocking_error_count: report.steps.inspect.draft_disposition.blocking_error_count,+ advisory_issues: report.steps.inspect.draft_disposition.advisory_issues.slice(0, 6),+ },+ contract_html: report.steps.contract_html,+ source_alignment: report.steps.source_alignment,+ audio_timing: report.steps.audio_timing,+ video_qa: {+ ok: report.steps.video_qa.ok,+ issue_count: report.steps.video_qa.issue_count || 0,+ issues: (report.steps.video_qa.issues || []).slice(0, 6),+ },+ repair_budget: report.repair_budget,+ ...(render.diagnostics ? { render_diagnostics: render.diagnostics } : {}),+ ...(render.logPath ? { render_log_path: render.logPath } : {}),+ render_profile: report.steps.render_profile,+ text: `Draft rendered to ${render.path} (${render.diagnostics && render.diagnostics.gpuMode ? render.diagnostics.gpuMode + ' GPU mode' : 'render ok'})${report.steps.render_profile.degraded_fps ? `; drafted at reduced fps ${report.steps.render_profile.degraded_fps} because this machine has no GPU acceleration — the final render will need lower settings or a GPU machine` : ''}; QA report written to ${report.report_path}.`,+ };+ } catch (err) {+ if (err && err.code === 'E_MEDIA_TOOL_MISSING') throw err;+ failDraft(report, reportAbs, 'E_DRAFT_FAILED', err && err.message ? err.message : String(err), {}, repairBudget);+ }+ }+const compositionDirAbs = resolveDir(opts.compositionDir);- const { renderComposition, qaComposition } = require('./lib/video_render_core.cjs');+ const vendorAssets = ensureVendorAssetsForComposition(compositionDirAbs);+ failVendorAssetsIfNeeded(vendorAssets);+ const { renderComposition, qaComposition, isConstrainedMachine, estimateRenderCost, renderCostDecision, degradedFps, machineRamGB } = require('./lib/video_render_core.cjs');if (opts.op === 'lint' || opts.op === 'inspect') {- const result = await qaComposition(opts.op, { projectDirAbs: compositionDirAbs });- if (result.ok === false) fail(result.errorCode, result.message);- return {+ const result = await qaComposition(opts.op, {+ projectDirAbs: compositionDirAbs,+ strictCraft: opts.strictCraft,+ onProgress: makeProgressEmitter(opts.op),+ logPath: renderLogPath(compositionDirAbs, `qa-${opts.op}`),+ });+ if (result.ok === false) fail(result.errorCode, result.message, {+ ...(result.diagnostics ? { render_diagnostics: result.diagnostics } : {}),+ ...(result.logPath ? { render_log_path: result.logPath } : {}),+ });+ const summary = summarizeFindings(result.findings);+ const inline = opts.findingsInline || (opts.findingsOutputPath ? 'summary' : 'full');+ const payload = {ok: true,op: opts.op,- findings: result.findings,- text: `${opts.op} findings are available in findings.`,+ summary,+ vendor_assets: vendorAssets,+ text: opts.findingsOutputPath+ ? `${opts.op} findings were summarized here and written to findings_path.`+ : (inline === 'full' ? `${opts.op} findings are available in findings.` : `${opts.op} findings were summarized here.`),};+ if (opts.findingsOutputPath) {+ payload.findings_path = writeFindingsOutput(opts.findingsOutputPath, {+ ok: true,+ op: opts.op,+ summary,+ findings: result.findings,+ });+ }+ if (inline === 'full') payload.findings = result.findings;+ else if (inline === 'summary') payload.findings_summary = summary;+ return payload;}const format = FORMAT.has(opts.format) ? opts.format : 'mp4';const quality = QUALITY.has(opts.quality) ? opts.quality : undefined;const out = await outputFile(opts.outputPath, format);++ // Render-resilience (P1/P2): a heavy composition on a weak/no-GPU machine will+ // software-render and likely crash or hang. A FINAL (high-quality) render+ // fails fast with an actionable message rather than a long hang; a+ // draft-quality standalone render degrades fps like the draft flow.+ let renderFps = typeof opts.fps === 'number' ? opts.fps : undefined;+ let constrained = false;+ try {+ const html = fs.readFileSync(path.join(compositionDirAbs, 'index.html'), 'utf8');+ const rootTag = rootCompositionTag(html);+ const w = htmlDataNumber(rootTag, 'width') || 1920;+ const h = htmlDataNumber(rootTag, 'height') || 1080;+ const dur = htmlDataNumber(rootTag, 'duration') || 0;+ const fps = renderFps || 30;+ const ramGB = machineRamGB();+ constrained = isConstrainedMachine(ramGB);+ const costUnits = estimateRenderCost(w, h, dur, fps);+ const decision = renderCostDecision({ constrained, costUnits, isFinal: quality === 'high' });+ if (decision === 'fail_fast') {+ fail('E_RENDER_TOO_HEAVY',+ `This ${w}x${h}, ${Math.round(dur)}s composition cannot be rendered at ${quality} quality on this machine without GPU acceleration (software rendering would crash or hang). Options: lower the resolution/fps/length, keep the draft, or render on a machine with a GPU.`,+ { render_profile: { constrained, machine_ram_gb: ramGB, cost_units: costUnits, decision } });+ }+ if (decision === 'degrade') renderFps = degradedFps(fps);+ } catch { /* canvas unknown → render as requested */ }+const result = await renderComposition({projectDirAbs: compositionDirAbs,outputAbsPath: out.finalPath,...(quality ? { quality } : {}),- ...(typeof opts.fps === 'number' ? { fps: opts.fps } : {}),+ ...(typeof renderFps === 'number' ? { fps: renderFps } : {}),format,+ constrained,+ onProgress: makeProgressEmitter(opts.op),+ logPath: renderLogPath(compositionDirAbs, 'render'),...(opts.variables && typeof opts.variables === 'object' && !Array.isArray(opts.variables) ? { variables: opts.variables } : {}),});- if (result.ok === false) fail(result.errorCode, result.message);+ if (result.ok === false) fail(result.errorCode, result.message, {+ ...(result.diagnostics ? { render_diagnostics: result.diagnostics } : {}),+ ...(result.logPath ? { render_log_path: result.logPath } : {}),+ });return {ok: true,op: opts.op,@@ -139,6 +2015,9 @@ module.exports = async function renderCompositionScript({ args }) {media: `chat-media://local/${result.path}`,renamed: out.renamed,requested_path: out.requested,- text: `Video rendered to ${result.path}.`,+ vendor_assets: vendorAssets,+ ...(result.diagnostics ? { render_diagnostics: result.diagnostics } : {}),+ ...(result.logPath ? { render_log_path: result.logPath } : {}),+ text: `Video rendered to ${result.path}${result.diagnostics && result.diagnostics.gpuMode ? ` (${result.diagnostics.gpuMode} GPU mode)` : ''}.`,};};diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/vendor/gsap.min.js b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/vendor/gsap.min.jsnew file mode 100644index 00000000..72c17a83--- /dev/null+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-compose/scripts/vendor/gsap.min.js@@ -0,0 +1,10 @@+/*!+ * GSAP 3.15.0+ * https://gsap.com+ *+ * @license Copyright 2026, GreenSock. All rights reserved.+ * Subject to the terms at https://gsap.com/standard-license.+ * @author: Jack Doyle, [email protected]+ */++!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).window=t.window||{})}(this,function(e){"use strict";function _inheritsLoose(t,e){t.prototype=Object.create(e.prototype),(t.prototype.constructor=t).__proto__=e}function _assertThisInitialized(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function r(t){return"string"==typeof t}function s(t){return"function"==typeof t}function t(t){return"number"==typeof t}function u(t){return void 0===t}function v(t){return"object"==typeof t}function w(t){return!1!==t}function x(){return"undefined"!=typeof window}function y(t){return s(t)||r(t)}function R(t){return(i=bt(t,ht))&&Fe}function S(t,e){return console.warn("Invalid property",t,"set to",e,"Missing plugin? gsap.registerPlugin()")}function T(t,e){return!e&&console.warn(t)}function U(t,e){return t&&(ht[t]=e)&&i&&(i[t]=e)||ht}function V(){return 0}function ga(t){var e,r,i=t[0];if(v(i)||s(i)||(t=[t]),!(e=(i._gsap||{}).harness)){for(r=yt.length;r--&&!yt[r].targetTest(i););e=yt[r]}for(r=t.length;r--;)t[r]&&(t[r]._gsap||(t[r]._gsap=new Xt(t[r],e)))||t.splice(r,1);return t}function ha(t){return t._gsap||ga(Pt(t))[0]._gsap}function ia(t,e,r){return(r=t[e])&&s(r)?t[e]():u(r)&&t.getAttribute&&t.getAttribute(e)||r}function ja(t,e){return(t=t.split(",")).forEach(e)||t}function ka(t){return Math.round(1e5*t)/1e5||0}function la(t){return Math.round(1e7*t)/1e7||0}function ma(t,e){var r=e.charAt(0),i=parseFloat(e.substr(2));return t=parseFloat(t),"+"===r?t+i:"-"===r?t-i:"*"===r?t*i:t/i}function na(t,e){for(var r=e.length,i=0;t.indexOf(e[i])<0&&++i<r;);return i<r}function oa(){var t,e,r=pt.length,i=pt.slice(0);for(_t={},t=pt.length=0;t<r;t++)(e=i[t])&&e._lazy&&(e.render(e._lazy[0],e._lazy[1],!0)._lazy=0)}function pa(t){return!!(t._initted||t._startAt||t.add)}function qa(t,e,r,i){pt.length&&!I&&oa(),t.render(e,r,i||!!(I&&e<0&&pa(t))),pt.length&&!I&&oa()}function ra(t){var e=parseFloat(t);return(e||0===e)&&(t+"").match(ot).length<2?e:r(t)?t.trim():t}function sa(t){return t}function ta(t,e){for(var r in e)r in t||(t[r]=e[r]);return t}function wa(t,e){for(var r in e)"__proto__"!==r&&"constructor"!==r&&"prototype"!==r&&(t[r]=v(e[r])?wa(t[r]||(t[r]={}),e[r]):e[r]);return t}function xa(t,e){var r,i={};for(r in t)r in e||(i[r]=t[r]);return i}function ya(t){var e=t.parent||L,r=t.keyframes?function _setKeyframeDefaults(i){return function(t,e){for(var r in e)r in t||"duration"===r&&i||"ease"===r||(t[r]=e[r])}}(K(t.keyframes)):ta;if(w(t.inherit))for(;e;)r(t,e.vars.defaults),e=e.parent||e._dp;return t}function Aa(t,e,r,i,n){void 0===r&&(r="_first"),void 0===i&&(i="_last");var a,s=t[i];if(n)for(a=e[n];s&&s[n]>a;)s=s._prev;return s?(e._next=s._next,s._next=e):(e._next=t[r],t[r]=e),e._next?e._next._prev=e:t[i]=e,e._prev=s,e.parent=e._dp=t,e}function Ba(t,e,r,i){void 0===r&&(r="_first"),void 0===i&&(i="_last");var n=e._prev,a=e._next;n?n._next=a:t[r]===e&&(t[r]=a),a?a._prev=n:t[i]===e&&(t[i]=n),e._next=e._prev=e.parent=null}function Ca(t,e){t.parent&&(!e||t.parent.autoRemoveChildren)&&t.parent.remove&&t.parent.remove(t),t._act=0}function Da(t,e){if(t&&(!e||e._end>t._dur||e._start<0))for(var r=t;r;)r._dirty=1,r=r.parent;return t}function Fa(t,e,r,i){return t._startAt&&(I?t._startAt.revert(ft):t.vars.immediateRender&&!t.vars.autoRevert||t._startAt.render(e,!0,i))}function Ha(t){return t._repeat?wt(t._tTime,t=t.duration()+t._rDelay)*t:0}function Ja(t,e){return(t-e._start)*e._ts+(0<=e._ts?0:e._dirty?e.totalDuration():e._tDur)}function Ka(t){return t._end=la(t._start+(t._tDur/Math.abs(t._ts||t._rts||q)||0))}function La(t,e){var r=t._dp;return r&&r.smoothChildTiming&&t._ts&&(t._start=la(r._time-(0<t._ts?e/t._ts:((t._dirty?t.totalDuration():t._tDur)-e)/-t._ts)),Ka(t),r._dirty||Da(r,t)),t}function Ma(t,e){var r;if((e._time||!e._dur&&e._initted||e._start<t._time&&(e._dur||!e.add))&&(r=Ja(t.rawTime(),e),(!e._dur||Mt(0,e.totalDuration(),r)-e._tTime>q)&&e.render(r,!0)),Da(t,e)._dp&&t._initted&&t._time>=t._dur&&t._ts){if(t._dur<t.duration())for(r=t;r._dp;)0<=r.rawTime()&&r.totalTime(r._tTime),r=r._dp;t._zTime=-q}}function Na(e,r,i,n){return r.parent&&Ca(r),r._start=la((t(i)?i:i||e!==L?Ot(e,i,r):e._time)+r._delay),r._end=la(r._start+(r.totalDuration()/Math.abs(r.timeScale())||0)),Aa(e,r,"_first","_last",e._sort?"_start":0),xt(r)||(e._recent=r),n||Ma(e,r),e._ts<0&&La(e,e._tTime),e}function Oa(t,e){return(ht.ScrollTrigger||S("scrollTrigger",e))&&ht.ScrollTrigger.create(e,t)}function Pa(t,e,r,i,n){return Ht(t,e,n),t._initted?!r&&t._pt&&!I&&(t._dur&&!1!==t.vars.lazy||!t._dur&&t.vars.lazy)&&f!==It.frame?(pt.push(t),t._lazy=[n,i],1):void 0:1}function Ua(t,e,r,i){var n=t._repeat,a=la(e)||0,s=t._tTime/t._tDur;return s&&!i&&(t._time*=a/t._dur),t._dur=a,t._tDur=n?n<0?1e10:la(a*(n+1)+t._rDelay*n):a,0<s&&!i&&La(t,t._tTime=t._tDur*s),t.parent&&Ka(t),r||Da(t.parent,t),t}function Va(t){return t instanceof Gt?Da(t):Ua(t,t._dur)}function Ya(e,r,i){var n,a,s=t(r[1]),o=(s?2:1)+(e<2?0:1),u=r[o];if(s&&(u.duration=r[1]),u.parent=i,e){for(n=u,a=i;a&&!("immediateRender"in n);)n=a.vars.defaults||{},a=w(a.vars.inherit)&&a.parent;u.immediateRender=w(n.immediateRender),e<2?u.runBackwards=1:u.startAt=r[o-1]}return new te(r[0],u,r[1+o])}function Za(t,e){return t||0===t?e(t):e}function _a(t,e){return r(t)&&(e=ut.exec(t))?e[1]:""}function cb(t,e){return t&&v(t)&&"length"in t&&(!e&&!t.length||t.length-1 in t&&v(t[0]))&&!t.nodeType&&t!==h}function fb(r){return r=Pt(r)[0]||T("Invalid scope")||{},function(t){var e=r.current||r.nativeElement||r;return Pt(t,e.querySelectorAll?e:e===r?T("Invalid scope")||a.createElement("div"):r)}}function gb(t){return t.sort(function(){return.5-Math.random()})}function hb(t){if(s(t))return t;var p=v(t)?t:{each:t},_=jt(p.ease),m=p.from||0,g=parseFloat(p.base)||0,y={},e=0<m&&m<1,T=isNaN(m)||e,b=p.axis,w=m,x=m;return r(m)?w=x={center:.5,edges:.5,end:1}[m]||0:!e&&T&&(w=m[0],x=m[1]),function(t,e,r){var i,n,a,s,o,u,h,l,f,c=(r||p).length,d=y[c];if(!d){if(!(f="auto"===p.grid?0:(p.grid||[1,X])[1])){for(h=-X;h<(h=r[f++].getBoundingClientRect().left)&&f<c;);f<c&&f--}for(d=y[c]=[],i=T?Math.min(f,c)*w-.5:m%f,n=f===X?0:T?c*x/f-.5:m/f|0,l=X,u=h=0;u<c;u++)a=u%f-i,s=n-(u/f|0),d[u]=o=b?Math.abs("y"===b?s:a):$(a*a+s*s),h<o&&(h=o),o<l&&(l=o);"random"===m&&gb(d),d.max=h-l,d.min=l,d.v=c=(parseFloat(p.amount)||parseFloat(p.each)*(c<f?c-1:b?"y"===b?c/f:f:Math.max(f,c/f))||0)*("edges"===m?-1:1),d.b=c<0?g-c:g,d.u=_a(p.amount||p.each)||0,_=_&&c<0?Yt(_):_}return c=(d[t]-d.min)/d.max||0,la(d.b+(_?_(c):c)*d.v)+d.u}}function ib(i){var n=Math.pow(10,((i+"").split(".")[1]||"").length);return function(e){var r=la(Math.round(parseFloat(e)/i)*i*n);return(r-r%1)/n+(t(e)?0:_a(e))}}function jb(h,e){var l,f,r=K(h);return!r&&v(h)&&(l=r=h.radius||X,h.values?(h=Pt(h.values),(f=!t(h[0]))&&(l*=l)):h=ib(h.increment)),Za(e,r?s(h)?function(t){return f=h(t),Math.abs(f-t)<=l?f:t}:function(e){for(var r,i,n=parseFloat(f?e.x:e),a=parseFloat(f?e.y:0),s=X,o=0,u=h.length;u--;)(r=f?(r=h[u].x-n)*r+(i=h[u].y-a)*i:Math.abs(h[u]-n))<s&&(s=r,o=u);return o=!l||s<=l?h[o]:e,f||o===e||t(e)?o:o+_a(e)}:ib(h))}function kb(t,e,r,i){return Za(K(t)?!e:!0===r?!!(r=0):!i,function(){return K(t)?t[~~(Math.random()*t.length)]:(r=r||1e-5)&&(i=r<1?Math.pow(10,(r+"").length-2):1)&&Math.floor(Math.round((t-r/2+Math.random()*(e-t+.99*r))/r)*r*i)/i})}function ob(e,r,t){return Za(t,function(t){return e[~~r(t)]})}function rb(t){return t.replace(tt,function(t){var e=t.indexOf("[")+1,r=t.substring(e||7,e?t.indexOf("]"):t.length-1).split(et);return kb(e?r:+r[0],e?0:+r[1],+r[2]||1e-5)})}function ub(t,e,r){var i,n,a,s=t.labels,o=X;for(i in s)(n=s[i]-e)<0==!!r&&n&&o>(n=Math.abs(n))&&(a=i,o=n);return a}function wb(t){return Ca(t),t.scrollTrigger&&t.scrollTrigger.kill(!!I),t.progress()<1&&At(t,"onInterrupt"),t}function zb(t){if(t)if(t=!t.name&&t.default||t,x()||t.headless){var e=t.name,r=s(t),i=e&&!r&&t.init?function(){this._props=[]}:t,n={init:V,render:_e,add:$t,kill:Te,modifier:ve,rawVars:0},a={targetTest:0,get:0,getSetter:ue,aliases:{},register:0};if(Lt(),t!==i){if(mt[e])return;ta(i,ta(xa(t,n),a)),bt(i.prototype,bt(n,xa(t,a))),mt[i.prop=e]=i,t.targetTest&&(yt.push(i),dt[e]=1),e=("css"===e?"CSS":e.charAt(0).toUpperCase()+e.substr(1))+"Plugin"}U(e,i),t.register&&t.register(Fe,i,we)}else Dt.push(t)}function Cb(t,e,r){return(6*(t+=t<0?1:1<t?-1:0)<1?e+(r-e)*t*6:t<.5?r:3*t<2?e+(r-e)*(2/3-t)*6:e)*zt+.5|0}function Db(e,r,i){var n,a,s,o,u,h,l,f,c,d,p=e?t(e)?[e>>16,e>>8&zt,e&zt]:0:Rt.black;if(!p){if(","===e.substr(-1)&&(e=e.substr(0,e.length-1)),Rt[e])p=Rt[e];else if("#"===e.charAt(0)){if(e.length<6&&(e="#"+(n=e.charAt(1))+n+(a=e.charAt(2))+a+(s=e.charAt(3))+s+(5===e.length?e.charAt(4)+e.charAt(4):"")),9===e.length)return[(p=parseInt(e.substr(1,6),16))>>16,p>>8&zt,p&zt,parseInt(e.substr(7),16)/255];p=[(e=parseInt(e.substr(1),16))>>16,e>>8&zt,e&zt]}else if("hsl"===e.substr(0,3))if(p=d=e.match(rt),r){if(~e.indexOf("="))return p=e.match(it),i&&p.length<4&&(p[3]=1),p}else o=+p[0]%360/360,u=p[1]/100,n=2*(h=p[2]/100)-(a=h<=.5?h*(u+1):h+u-h*u),3<p.length&&(p[3]*=1),p[0]=Cb(o+1/3,n,a),p[1]=Cb(o,n,a),p[2]=Cb(o-1/3,n,a);else p=e.match(rt)||Rt.transparent;p=p.map(Number)}return r&&!d&&(n=p[0]/zt,a=p[1]/zt,s=p[2]/zt,h=((l=Math.max(n,a,s))+(f=Math.min(n,a,s)))/2,l===f?o=u=0:(c=l-f,u=.5<h?c/(2-l-f):c/(l+f),o=l===n?(a-s)/c+(a<s?6:0):l===a?(s-n)/c+2:(n-a)/c+4,o*=60),p[0]=~~(o+.5),p[1]=~~(100*u+.5),p[2]=~~(100*h+.5)),i&&p.length<4&&(p[3]=1),p}function Eb(t){var r=[],i=[],n=-1;return t.split(Et).forEach(function(t){var e=t.match(nt)||[];r.push.apply(r,e),i.push(n+=e.length+1)}),r.c=i,r}function Fb(t,e,r){var i,n,a,s,o="",u=(t+o).match(Et),h=e?"hsla(":"rgba(",l=0;if(!u)return t;if(u=u.map(function(t){return(t=Db(t,e,1))&&h+(e?t[0]+","+t[1]+"%,"+t[2]+"%,"+t[3]:t.join(","))+")"}),r&&(a=Eb(t),(i=r.c).join(o)!==a.c.join(o)))for(s=(n=t.replace(Et,"1").split(nt)).length-1;l<s;l++)o+=n[l]+(~i.indexOf(l)?u.shift()||h+"0,0,0,0)":(a.length?a:u.length?u:r).shift());if(!n)for(s=(n=t.split(Et)).length-1;l<s;l++)o+=n[l]+u[l];return o+n[s]}function Ib(t){var e,r=t.join(" ");if(Et.lastIndex=0,Et.test(r))return e=Ft.test(r),t[1]=Fb(t[1],e),t[0]=Fb(t[0],e,Eb(t[1])),!0}function Rb(t){var e=(t+"").split("("),r=Bt[e[0]];return r&&1<e.length&&r.config?r.config.apply(null,~t.indexOf("{")?[function _parseObjectInString(t){for(var e,r,i,n={},a=t.substr(1,t.length-3).split(":"),s=a[0],o=1,u=a.length;o<u;o++)r=a[o],e=o!==u-1?r.lastIndexOf(","):r.length,i=r.substr(0,e),n[s]=isNaN(i)?i.replace(Ut,"").trim():+i,s=r.substr(e+1).trim();return n}(e[1])]:function _valueInParentheses(t){var e=t.indexOf("(")+1,r=t.indexOf(")"),i=t.indexOf("(",e);return t.substring(e,~i&&i<r?t.indexOf(")",r+1):r)}(t).split(",").map(ra)):Bt._CE&&Nt.test(t)?Bt._CE("",t):r}function Ub(t,e,r,i){void 0===r&&(r=function easeOut(t){return 1-e(1-t)}),void 0===i&&(i=function easeInOut(t){return t<.5?e(2*t)/2:1-e(2*(1-t))/2});var n,a={easeIn:e,easeOut:r,easeInOut:i};return ja(t,function(t){for(var e in Bt[t]=ht[t]=a,Bt[n=t.toLowerCase()]=r,a)Bt[n+("easeIn"===e?".in":"easeOut"===e?".out":".inOut")]=Bt[t+"."+e]=a[e]}),a}function Vb(e){return function(t){return t<.5?(1-e(1-2*t))/2:.5+e(2*(t-.5))/2}}function Wb(r,t,e){function Gm(t){return 1===t?1:i*Math.pow(2,-10*t)*Q((t-a)*n)+1}var i=1<=t?t:1,n=(e||(r?.3:.45))/(t<1?t:1),a=n/G*(Math.asin(1/i)||0),s="out"===r?Gm:"in"===r?function(t){return 1-Gm(1-t)}:Vb(Gm);return n=G/n,s.config=function(t,e){return Wb(r,t,e)},s}function Xb(e,r){function Om(t){return t?--t*t*((r+1)*t+r)+1:0}void 0===r&&(r=1.70158);var t="out"===e?Om:"in"===e?function(t){return 1-Om(1-t)}:Vb(Om);return t.config=function(t){return Xb(e,t)},t}var F,I,l,L,h,n,a,i,o,f,c,d,p,_,m,g,b,k,O,M,C,P,A,D,z,E,B,N,Y={autoSleep:120,force3D:"auto",nullTargetWarn:1,units:{lineHeight:""}},j={duration:.5,overwrite:!1,delay:0},X=1e8,q=1/X,G=2*Math.PI,Z=G/4,W=0,$=Math.sqrt,H=Math.cos,Q=Math.sin,J="function"==typeof ArrayBuffer&&ArrayBuffer.isView||function(){},K=Array.isArray,tt=/random\([^)]+\)/g,et=/,\s*/g,rt=/(?:-?\.?\d|\.)+/gi,it=/[-+=.]*\d+[.e\-+]*\d*[e\-+]*\d*/g,nt=/[-+=.]*\d+[.e-]*\d*[a-z%]*/g,at=/[-+=.]*\d+\.?\d*(?:e-|e\+)?\d*/gi,st=/[+-]=-?[.\d]+/,ot=/[^,'"\[\]\s]+/gi,ut=/^[+\-=e\s\d]*\d+[.\d]*([a-z]*|%)\s*$/i,ht={},lt={suppressEvents:!0,isStart:!0,kill:!1},ft={suppressEvents:!0,kill:!1},ct={suppressEvents:!0},dt={},pt=[],_t={},mt={},gt={},vt=30,yt=[],Tt="",bt=function _merge(t,e){for(var r in e)t[r]=e[r];return t},wt=function _animationCycle(t,e){var r=Math.floor(t=la(t/e));return t&&r===t?r-1:r},xt=function _isFromOrFromStart(t){var e=t.data;return"isFromStart"===e||"isStart"===e},kt={_start:0,endTime:V,totalDuration:V},Ot=function _parsePosition(t,e,i){var n,a,s,o=t.labels,u=t._recent||kt,h=t.duration()>=X?u.endTime(!1):t._dur;return r(e)&&(isNaN(e)||e in o)?(a=e.charAt(0),s="%"===e.substr(-1),n=e.indexOf("="),"<"===a||">"===a?(0<=n&&(e=e.replace(/=/,"")),("<"===a?u._start:u.endTime(0<=u._repeat))+(parseFloat(e.substr(1))||0)*(s?(n<0?u:i).totalDuration()/100:1)):n<0?(e in o||(o[e]=h),o[e]):(a=parseFloat(e.charAt(n-1)+e.substr(n+1)),s&&i&&(a=a/100*(K(i)?i[0]:i).totalDuration()),1<n?_parsePosition(t,e.substr(0,n-1),i)+a:h+a)):null==e?h:+e},Mt=function _clamp(t,e,r){return r<t?t:e<r?e:r},Ct=[].slice,Pt=function toArray(t,e,i){return l&&!e&&l.selector?l.selector(t):!r(t)||i||!n&&Lt()?K(t)?function _flatten(t,e,i){return void 0===i&&(i=[]),t.forEach(function(t){return r(t)&&!e||cb(t,1)?i.push.apply(i,Pt(t)):i.push(t)})||i}(t,i):cb(t)?Ct.call(t,0):t?[t]:[]:Ct.call((e||a).querySelectorAll(t),0)},St=function mapRange(e,t,r,i,n){var a=t-e,s=i-r;return Za(n,function(t){return r+((t-e)/a*s||0)})},At=function _callback(t,e,r){var i,n,a,s=t.vars,o=s[e],u=l,h=t._ctx;if(o)return i=s[e+"Params"],n=s.callbackScope||t,r&&pt.length&&oa(),h&&(l=h),a=i?o.apply(n,i):o.call(n),l=u,a},Dt=[],zt=255,Rt={aqua:[0,zt,zt],lime:[0,zt,0],silver:[192,192,192],black:[0,0,0],maroon:[128,0,0],teal:[0,128,128],blue:[0,0,zt],navy:[0,0,128],white:[zt,zt,zt],olive:[128,128,0],yellow:[zt,zt,0],orange:[zt,165,0],gray:[128,128,128],purple:[128,0,128],green:[0,128,0],red:[zt,0,0],pink:[zt,192,203],cyan:[0,zt,zt],transparent:[zt,zt,zt,0]},Et=function(){var t,e="(?:\\b(?:(?:rgb|rgba|hsl|hsla)\\(.+?\\))|\\B#(?:[0-9a-f]{3,4}){1,2}\\b";for(t in Rt)e+="|"+t+"\\b";return new RegExp(e+")","gi")}(),Ft=/hsl[a]?\(/,It=(O=Date.now,M=500,C=33,P=O(),A=P,z=D=1e3/240,g={time:0,frame:0,tick:function tick(){zl(!0)},deltaRatio:function deltaRatio(t){return b/(1e3/(t||60))},wake:function wake(){o&&(!n&&x()&&(h=n=window,a=h.document||{},ht.gsap=Fe,(h.gsapVersions||(h.gsapVersions=[])).push(Fe.version),R(i||h.GreenSockGlobals||!h.gsap&&h||{}),Dt.forEach(zb)),m="undefined"!=typeof requestAnimationFrame&&requestAnimationFrame,p&&g.sleep(),_=m||function(t){return setTimeout(t,z-1e3*g.time+1|0)},d=1,zl(2))},sleep:function sleep(){(m?cancelAnimationFrame:clearTimeout)(p),d=0,_=V},lagSmoothing:function lagSmoothing(t,e){M=t||1/0,C=Math.min(e||33,M)},fps:function fps(t){D=1e3/(t||240),z=1e3*g.time+D},add:function add(n,t,e){var a=t?function(t,e,r,i){n(t,e,r,i),g.remove(a)}:n;return g.remove(n),E[e?"unshift":"push"](a),Lt(),a},remove:function remove(t,e){~(e=E.indexOf(t))&&E.splice(e,1)&&e<=k&&k--},_listeners:E=[]}),Lt=function _wake(){return!d&&It.wake()},Bt={},Nt=/^[\d.\-M][\d.\-,\s]/,Ut=/["']/g,Yt=function _invertEase(e){return function(t){return 1-e(1-t)}},jt=function _parseEase(t,e){return t&&(s(t)?t:Bt[t]||Rb(t))||e};function zl(t){var e,r,i,n,a=O()-A,s=!0===t;if((M<a||a<0)&&(P+=a-C),(0<(e=(i=(A+=a)-P)-z)||s)&&(n=++g.frame,b=i-1e3*g.time,g.time=i/=1e3,z+=e+(D<=e?4:D-e),r=1),s||(p=_(zl)),r)for(k=0;k<E.length;k++)E[k](i,b,n,t)}function dn(t){return t<N?B*t*t:t<.7272727272727273?B*Math.pow(t-1.5/2.75,2)+.75:t<.9090909090909092?B*(t-=2.25/2.75)*t+.9375:B*Math.pow(t-2.625/2.75,2)+.984375}ja("Linear,Quad,Cubic,Quart,Quint,Strong",function(t,e){var r=e<5?e+1:e;Ub(t+",Power"+(r-1),e?function(t){return Math.pow(t,r)}:function(t){return t},function(t){return 1-Math.pow(1-t,r)},function(t){return t<.5?Math.pow(2*t,r)/2:1-Math.pow(2*(1-t),r)/2})}),Bt.Linear.easeNone=Bt.none=Bt.Linear.easeIn,Ub("Elastic",Wb("in"),Wb("out"),Wb()),B=7.5625,N=1/2.75,Ub("Bounce",function(t){return 1-dn(1-t)},dn),Ub("Expo",function(t){return Math.pow(2,10*(t-1))*t+t*t*t*t*t*t*(1-t)}),Ub("Circ",function(t){return-($(1-t*t)-1)}),Ub("Sine",function(t){return 1===t?1:1-H(t*Z)}),Ub("Back",Xb("in"),Xb("out"),Xb()),Bt.SteppedEase=Bt.steps=ht.SteppedEase={config:function config(t,e){void 0===t&&(t=1);var r=1/t,i=t+(e?0:1),n=e?1:0;return function(t){return((i*Mt(0,.99999999,t)|0)+n)*r}}},j.ease=Bt["quad.out"],ja("onComplete,onUpdate,onStart,onRepeat,onReverseComplete,onInterrupt",function(t){return Tt+=t+","+t+"Params,"});var Vt,Xt=function GSCache(t,e){this.id=W++,(t._gsap=this).target=t,this.harness=e,this.get=e?e.get:ia,this.set=e?e.getSetter:ue},qt=((Vt=Animation.prototype).delay=function delay(t){return t||0===t?(this.parent&&this.parent.smoothChildTiming&&this.startTime(this._start+t-this._delay),this._delay=t,this):this._delay},Vt.duration=function duration(t){return arguments.length?this.totalDuration(0<this._repeat?t+(t+this._rDelay)*this._repeat:t):this.totalDuration()&&this._dur},Vt.totalDuration=function totalDuration(t){return arguments.length?(this._dirty=0,Ua(this,this._repeat<0?t:(t-this._repeat*this._rDelay)/(this._repeat+1))):this._tDur},Vt.totalTime=function totalTime(t,e){if(Lt(),!arguments.length)return this._tTime;var r=this._dp;if(r&&r.smoothChildTiming&&this._ts){for(La(this,t),!r._dp||r.parent||Ma(r,this);r&&r.parent;)r.parent._time!==r._start+(0<=r._ts?r._tTime/r._ts:(r.totalDuration()-r._tTime)/-r._ts)&&r.totalTime(r._tTime,!0),r=r.parent;!this.parent&&this._dp.autoRemoveChildren&&(0<this._ts&&t<this._tDur||this._ts<0&&0<t||!this._tDur&&!t)&&Na(this._dp,this,this._start-this._delay)}return(this._tTime!==t||!this._dur&&!e||this._initted&&Math.abs(this._zTime)===q||!this._initted&&this._dur&&t||!t&&!this._initted&&(this.add||this._ptLookup))&&(this._ts||(this._pTime=t),qa(this,t,e)),this},Vt.time=function time(t,e){return arguments.length?this.totalTime(Math.min(this.totalDuration(),t+Ha(this))%(this._dur+this._rDelay)||(t?this._dur:0),e):this._time},Vt.totalProgress=function totalProgress(t,e){return arguments.length?this.totalTime(this.totalDuration()*t,e):this.totalDuration()?Math.min(1,this._tTime/this._tDur):0<=this.rawTime()&&this._initted?1:0},Vt.progress=function progress(t,e){return arguments.length?this.totalTime(this.duration()*(!this._yoyo||1&this.iteration()?t:1-t)+Ha(this),e):this.duration()?Math.min(1,this._time/this._dur):0<this.rawTime()?1:0},Vt.iteration=function iteration(t,e){var r=this.duration()+this._rDelay;return arguments.length?this.totalTime(this._time+(t-1)*r,e):this._repeat?wt(this._tTime,r)+1:1},Vt.timeScale=function timeScale(t,e){if(!arguments.length)return this._rts===-q?0:this._rts;if(this._rts===t)return this;var r=this.parent&&this._ts?Ja(this.parent._time,this):this._tTime;return this._rts=+t||0,this._ts=this._ps||t===-q?0:this._rts,this.totalTime(Mt(-Math.abs(this._delay),this.totalDuration(),r),!1!==e),Ka(this),function _recacheAncestors(t){for(var e=t.parent;e&&e.parent;)e._dirty=1,e.totalDuration(),e=e.parent;return t}(this)},Vt.paused=function paused(t){return arguments.length?(this._ps!==t&&((this._ps=t)?(this._pTime=this._tTime||Math.max(-this._delay,this.rawTime()),this._ts=this._act=0):(Lt(),this._ts=this._rts,this.totalTime(this.parent&&!this.parent.smoothChildTiming?this.rawTime():this._tTime||this._pTime,1===this.progress()&&Math.abs(this._zTime)!==q&&(this._tTime-=q)))),this):this._ps},Vt.startTime=function startTime(t){if(arguments.length){this._start=la(t);var e=this.parent||this._dp;return!e||!e._sort&&this.parent||Na(e,this,this._start-this._delay),this}return this._start},Vt.endTime=function endTime(t){return this._start+(w(t)?this.totalDuration():this.duration())/Math.abs(this._ts||1)},Vt.rawTime=function rawTime(t){var e=this.parent||this._dp;return e?t&&(!this._ts||this._repeat&&this._time&&this.totalProgress()<1)?this._tTime%(this._dur+this._rDelay):this._ts?Ja(e.rawTime(t),this):this._tTime:this._tTime},Vt.revert=function revert(t){void 0===t&&(t=ct);var e=I;return I=t,pa(this)&&(this.timeline&&this.timeline.revert(t),this.totalTime(-.01,t.suppressEvents)),"nested"!==this.data&&!1!==t.kill&&this.kill(),I=e,this},Vt.globalTime=function globalTime(t){for(var e=this,r=arguments.length?t:e.rawTime();e;)r=e._start+r/(Math.abs(e._ts)||1),e=e._dp;return!this.parent&&this._sat?this._sat.globalTime(t):r},Vt.repeat=function repeat(t){return arguments.length?(this._repeat=t===1/0?-2:t,Va(this)):-2===this._repeat?1/0:this._repeat},Vt.repeatDelay=function repeatDelay(t){if(arguments.length){var e=this._time;return this._rDelay=t,Va(this),e?this.time(e):this}return this._rDelay},Vt.yoyo=function yoyo(t){return arguments.length?(this._yoyo=t,this):this._yoyo},Vt.seek=function seek(t,e){return this.totalTime(Ot(this,t),w(e))},Vt.restart=function restart(t,e){return this.play().totalTime(t?-this._delay:0,w(e)),this._dur||(this._zTime=-q),this},Vt.play=function play(t,e){return null!=t&&this.seek(t,e),this.reversed(!1).paused(!1)},Vt.reverse=function reverse(t,e){return null!=t&&this.seek(t||this.totalDuration(),e),this.reversed(!0).paused(!1)},Vt.pause=function pause(t,e){return null!=t&&this.seek(t,e),this.paused(!0)},Vt.resume=function resume(){return this.paused(!1)},Vt.reversed=function reversed(t){return arguments.length?(!!t!==this.reversed()&&this.timeScale(-this._rts||(t?-q:0)),this):this._rts<0},Vt.invalidate=function invalidate(){return this._initted=this._act=0,this._zTime=-q,this},Vt.isActive=function isActive(){var t,e=this.parent||this._dp,r=this._start;return!(e&&!(this._ts&&this._initted&&e.isActive()&&(t=e.rawTime(!0))>=r&&t<this.endTime(!0)-q))},Vt.eventCallback=function eventCallback(t,e,r){var i=this.vars;return 1<arguments.length?(e?(i[t]=e,r&&(i[t+"Params"]=r),"onUpdate"===t&&(this._onUpdate=e)):delete i[t],this):i[t]},Vt.then=function then(t){var i=this,n=i._prom;return new Promise(function(e){function Ao(){var t=i.then;i.then=null,n&&n(),s(r)&&(r=r(i))&&(r.then||r===i)&&(i.then=t),e(r),i.then=t}var r=s(t)?t:sa;i._initted&&1===i.totalProgress()&&0<=i._ts||!i._tTime&&i._ts<0?Ao():i._prom=Ao})},Vt.kill=function kill(){wb(this)},Animation);function Animation(t){this.vars=t,this._delay=+t.delay||0,(this._repeat=t.repeat===1/0?-2:t.repeat||0)&&(this._rDelay=t.repeatDelay||0,this._yoyo=!!t.yoyo||!!t.yoyoEase),this._ts=1,Ua(this,+t.duration,1,1),this.data=t.data,l&&(this._ctx=l).data.push(this),d||It.wake()}ta(qt.prototype,{_time:0,_start:0,_end:0,_tTime:0,_tDur:0,_dirty:0,_repeat:0,_yoyo:!1,parent:null,_initted:!1,_rDelay:0,_ts:1,_dp:0,ratio:0,_zTime:-q,_prom:0,_ps:!1,_rts:1});var Gt=function(i){function Timeline(t,e){var r;return void 0===t&&(t={}),(r=i.call(this,t)||this).labels={},r.smoothChildTiming=!!t.smoothChildTiming,r.autoRemoveChildren=!!t.autoRemoveChildren,r._sort=w(t.sortChildren),L&&Na(t.parent||L,_assertThisInitialized(r),e),t.reversed&&r.reverse(),t.paused&&r.paused(!0),t.scrollTrigger&&Oa(_assertThisInitialized(r),t.scrollTrigger),r}_inheritsLoose(Timeline,i);var e=Timeline.prototype;return e.to=function to(t,e,r){return Ya(0,arguments,this),this},e.from=function from(t,e,r){return Ya(1,arguments,this),this},e.fromTo=function fromTo(t,e,r,i){return Ya(2,arguments,this),this},e.set=function set(t,e,r){return e.duration=0,e.parent=this,ya(e).repeatDelay||(e.repeat=0),e.immediateRender=!!e.immediateRender,new te(t,e,Ot(this,r),1),this},e.call=function call(t,e,r){return Na(this,te.delayedCall(0,t,e),r)},e.staggerTo=function staggerTo(t,e,r,i,n,a,s){return r.duration=e,r.stagger=r.stagger||i,r.onComplete=a,r.onCompleteParams=s,r.parent=this,new te(t,r,Ot(this,n)),this},e.staggerFrom=function staggerFrom(t,e,r,i,n,a,s){return r.runBackwards=1,ya(r).immediateRender=w(r.immediateRender),this.staggerTo(t,e,r,i,n,a,s)},e.staggerFromTo=function staggerFromTo(t,e,r,i,n,a,s,o){return i.startAt=r,ya(i).immediateRender=w(i.immediateRender),this.staggerTo(t,e,i,n,a,s,o)},e.render=function render(t,e,r){var i,n,a,s,o,u,h,l,f,c,d,p,_=this._time,m=this._dirty?this.totalDuration():this._tDur,g=this._dur,v=t<=0?0:la(t),y=this._zTime<0!=t<0&&(this._initted||!g);if(this!==L&&m<v&&0<=t&&(v=m),v!==this._tTime||r||y){if(_!==this._time&&g&&(v+=this._time-_,t+=this._time-_),i=v,f=this._start,u=!(l=this._ts),y&&(g||(_=this._zTime),!t&&e||(this._zTime=t)),this._repeat){if(d=this._yoyo,o=g+this._rDelay,this._repeat<-1&&t<0)return this.totalTime(100*o+t,e,r);if(i=la(v%o),v===m?(s=this._repeat,i=g):((s=~~(c=la(v/o)))&&s===c&&(i=g,s--),g<i&&(i=g)),c=wt(this._tTime,o),!_&&this._tTime&&c!==s&&this._tTime-c*o-this._dur<=0&&(c=s),d&&1&s&&(i=g-i,p=1),s!==c&&!this._lock){var T=d&&1&c,b=T===(d&&1&s);if(s<c&&(T=!T),_=T?0:v%g?g:v,this._lock=1,this.render(_||(p?0:la(s*o)),e,!g)._lock=0,this._tTime=v,!e&&this.parent&&At(this,"onRepeat"),this.vars.repeatRefresh&&!p&&(this.invalidate()._lock=1,c=s),_&&_!==this._time||u!=!this._ts||this.vars.onRepeat&&!this.parent&&!this._act)return this;if(g=this._dur,m=this._tDur,b&&(this._lock=2,_=T?g:-1e-4,this.render(_,!0),this.vars.repeatRefresh&&!p&&this.invalidate()),this._lock=0,!this._ts&&!u)return this}}if(this._hasPause&&!this._forcing&&this._lock<2&&(h=function _findNextPauseTween(t,e,r){var i;if(e<r)for(i=t._first;i&&i._start<=r;){if("isPause"===i.data&&i._start>e)return i;i=i._next}else for(i=t._last;i&&i._start>=r;){if("isPause"===i.data&&i._start<e)return i;i=i._prev}}(this,la(_),la(i)))&&(v-=i-(i=h._start)),this._tTime=v,this._time=i,this._act=!!l,this._initted||(this._onUpdate=this.vars.onUpdate,this._initted=1,this._zTime=t,_=0),!_&&v&&g&&!e&&!c&&(At(this,"onStart"),this._tTime!==v))return this;if(_<=i&&0<=t)for(n=this._first;n;){if(a=n._next,(n._act||i>=n._start)&&n._ts&&h!==n){if(n.parent!==this)return this.render(t,e,r);if(n.render(0<n._ts?(i-n._start)*n._ts:(n._dirty?n.totalDuration():n._tDur)+(i-n._start)*n._ts,e,r),i!==this._time||!this._ts&&!u){h=0,a&&(v+=this._zTime=-q);break}}n=a}else{n=this._last;for(var w=t<0?t:i;n;){if(a=n._prev,(n._act||w<=n._end)&&n._ts&&h!==n){if(n.parent!==this)return this.render(t,e,r);if(n.render(0<n._ts?(w-n._start)*n._ts:(n._dirty?n.totalDuration():n._tDur)+(w-n._start)*n._ts,e,r||I&&pa(n)),i!==this._time||!this._ts&&!u){h=0,a&&(v+=this._zTime=w?-q:q);break}}n=a}}if(h&&!e&&(this.pause(),h.render(_<=i?0:-q)._zTime=_<=i?1:-1,this._ts))return this._start=f,Ka(this),this.render(t,e,r);this._onUpdate&&!e&&At(this,"onUpdate",!0),(v===m&&this._tTime>=this.totalDuration()||!v&&_)&&(f!==this._start&&Math.abs(l)===Math.abs(this._ts)||this._lock||(!t&&g||!(v===m&&0<this._ts||!v&&this._ts<0)||Ca(this,1),e||t<0&&!_||!v&&!_&&m||(At(this,v===m&&0<=t?"onComplete":"onReverseComplete",!0),!this._prom||v<m&&0<this.timeScale()||this._prom())))}return this},e.add=function add(e,i){var n=this;if(t(i)||(i=Ot(this,i,e)),!(e instanceof qt)){if(K(e))return e.forEach(function(t){return n.add(t,i)}),this;if(r(e))return this.addLabel(e,i);if(!s(e))return this;e=te.delayedCall(0,e)}return this!==e?Na(this,e,i):this},e.getChildren=function getChildren(t,e,r,i){void 0===t&&(t=!0),void 0===e&&(e=!0),void 0===r&&(r=!0),void 0===i&&(i=-X);for(var n=[],a=this._first;a;)a._start>=i&&(a instanceof te?e&&n.push(a):(r&&n.push(a),t&&n.push.apply(n,a.getChildren(!0,e,r)))),a=a._next;return n},e.getById=function getById(t){for(var e=this.getChildren(1,1,1),r=e.length;r--;)if(e[r].vars.id===t)return e[r]},e.remove=function remove(t){return r(t)?this.removeLabel(t):s(t)?this.killTweensOf(t):(t.parent===this&&Ba(this,t),t===this._recent&&(this._recent=this._last),Da(this))},e.totalTime=function totalTime(t,e){return arguments.length?(this._forcing=1,!this._dp&&this._ts&&(this._start=la(It.time-(0<this._ts?t/this._ts:(this.totalDuration()-t)/-this._ts))),i.prototype.totalTime.call(this,t,e),this._forcing=0,this):this._tTime},e.addLabel=function addLabel(t,e){return this.labels[t]=Ot(this,e),this},e.removeLabel=function removeLabel(t){return delete this.labels[t],this},e.addPause=function addPause(t,e,r){var i=te.delayedCall(0,e||V,r);return i.data="isPause",this._hasPause=1,Na(this,i,Ot(this,t))},e.removePause=function removePause(t){var e=this._first;for(t=Ot(this,t);e;)e._start===t&&"isPause"===e.data&&Ca(e),e=e._next},e.killTweensOf=function killTweensOf(t,e,r){for(var i=this.getTweensOf(t,r),n=i.length;n--;)Zt!==i[n]&&i[n].kill(t,e);return this},e.getTweensOf=function getTweensOf(e,r){for(var i,n=[],a=Pt(e),s=this._first,o=t(r);s;)s instanceof te?na(s._targets,a)&&(o?(!Zt||s._initted&&s._ts)&&s.globalTime(0)<=r&&s.globalTime(s.totalDuration())>r:!r||s.isActive())&&n.push(s):(i=s.getTweensOf(a,r)).length&&n.push.apply(n,i),s=s._next;return n},e.tweenTo=function tweenTo(t,e){e=e||{};var r,i=this,n=Ot(i,t),a=e.startAt,s=e.onStart,o=e.onStartParams,u=e.immediateRender,h=te.to(i,ta({ease:e.ease||"none",lazy:!1,immediateRender:!1,time:n,overwrite:"auto",duration:e.duration||Math.abs((n-(a&&"time"in a?a.time:i._time))/i.timeScale())||q,onStart:function onStart(){if(i.pause(),!r){var t=e.duration||Math.abs((n-(a&&"time"in a?a.time:i._time))/i.timeScale());h._dur!==t&&Ua(h,t,0,1).render(h._time,!0,!0),r=1}s&&s.apply(h,o||[])}},e));return u?h.render(0):h},e.tweenFromTo=function tweenFromTo(t,e,r){return this.tweenTo(e,ta({startAt:{time:Ot(this,t)}},r))},e.recent=function recent(){return this._recent},e.nextLabel=function nextLabel(t){return void 0===t&&(t=this._time),ub(this,Ot(this,t))},e.previousLabel=function previousLabel(t){return void 0===t&&(t=this._time),ub(this,Ot(this,t),1)},e.currentLabel=function currentLabel(t){return arguments.length?this.seek(t,!0):this.previousLabel(this._time+q)},e.shiftChildren=function shiftChildren(t,e,r){void 0===r&&(r=0);var i,n=this._first,a=this.labels;for(t=la(t);n;)n._start>=r&&(n._start+=t,n._end+=t),n=n._next;if(e)for(i in a)a[i]>=r&&(a[i]+=t);return Da(this)},e.invalidate=function invalidate(t){var e=this._first;for(this._lock=0;e;)e.invalidate(t),e=e._next;return i.prototype.invalidate.call(this,t)},e.clear=function clear(t){void 0===t&&(t=!0);for(var e,r=this._first;r;)e=r._next,this.remove(r),r=e;return this._dp&&(this._time=this._tTime=this._pTime=0),t&&(this.labels={}),Da(this)},e.totalDuration=function totalDuration(t){var e,r,i,n=0,a=this,s=a._last,o=X;if(arguments.length)return a.timeScale((a._repeat<0?a.duration():a.totalDuration())/(a.reversed()?-t:t));if(a._dirty){for(i=a.parent;s;)e=s._prev,s._dirty&&s.totalDuration(),o<(r=s._start)&&a._sort&&s._ts&&!a._lock?(a._lock=1,Na(a,s,r-s._delay,1)._lock=0):o=r,r<0&&s._ts&&(n-=r,(!i&&!a._dp||i&&i.smoothChildTiming)&&(a._start+=la(r/a._ts),a._time-=r,a._tTime-=r),a.shiftChildren(-r,!1,-Infinity),o=0),s._end>n&&s._ts&&(n=s._end),s=e;Ua(a,a===L&&a._time>n?a._time:n,1,1),a._dirty=0}return a._tDur},Timeline.updateRoot=function updateRoot(t){if(L._ts&&(qa(L,Ja(t,L)),f=It.frame),It.frame>=vt){vt+=Y.autoSleep||120;var e=L._first;if((!e||!e._ts)&&Y.autoSleep&&It._listeners.length<2){for(;e&&!e._ts;)e=e._next;e||It.sleep()}}},Timeline}(qt);ta(Gt.prototype,{_lock:0,_hasPause:0,_forcing:0});function cc(t,e,i,n,a,o){var u,h,l,f;if(mt[t]&&!1!==(u=new mt[t]).init(a,u.rawVars?e[t]:function _processVars(t,e,i,n,a){if(s(t)&&(t=Qt(t,a,e,i,n)),!v(t)||t.style&&t.nodeType||K(t)||J(t))return r(t)?Qt(t,a,e,i,n):t;var o,u={};for(o in t)u[o]=Qt(t[o],a,e,i,n);return u}(e[t],n,a,o,i),i,n,o)&&(i._pt=h=new we(i._pt,a,t,0,1,u.render,u,0,u.priority),i!==c))for(l=i._ptLookup[i._targets.indexOf(a)],f=u._props.length;f--;)l[u._props[f]]=h;return u}function ic(t,r,e,i){var n,a,s=r.ease||i||"power1.inOut";if(K(r))a=e[t]||(e[t]=[]),r.forEach(function(t,e){return a.push({t:e/(r.length-1)*100,v:t,e:s})});else for(n in r)a=e[n]||(e[n]=[]),"ease"===n||a.push({t:parseFloat(t),v:r[n],e:s})}var Zt,Wt,$t=function _addPropTween(t,e,i,n,a,o,u,h,l,f){s(n)&&(n=n(a||0,t,o));var c,d=t[e],p="get"!==i?i:s(d)?l?t[e.indexOf("set")||!s(t["get"+e.substr(3)])?e:"get"+e.substr(3)](l):t[e]():d,_=s(d)?l?se:ae:ie;if(r(n)&&(~n.indexOf("random(")&&(n=rb(n)),"="===n.charAt(1)&&(!(c=ma(p,n)+(_a(p)||0))&&0!==c||(n=c))),!f||p!==n||Wt)return isNaN(p*n)||""===n?(d||e in t||S(e,n),function _addComplexStringPropTween(t,e,r,i,n,a,s){var o,u,h,l,f,c,d,p,_=new we(this._pt,t,e,0,1,pe,null,n),m=0,g=0;for(_.b=r,_.e=i,r+="",(d=~(i+="").indexOf("random("))&&(i=rb(i)),a&&(a(p=[r,i],t,e),r=p[0],i=p[1]),u=r.match(at)||[];o=at.exec(i);)l=o[0],f=i.substring(m,o.index),h?h=(h+1)%5:"rgba("===f.substr(-5)&&(h=1),l!==u[g++]&&(c=parseFloat(u[g-1])||0,_._pt={_next:_._pt,p:f||1===g?f:",",s:c,c:"="===l.charAt(1)?ma(c,l)-c:parseFloat(l)-c,m:h&&h<4?Math.round:0},m=at.lastIndex);return _.c=m<i.length?i.substring(m,i.length):"",_.fp=s,(st.test(i)||d)&&(_.e=0),this._pt=_}.call(this,t,e,p,n,_,h||Y.stringFilter,l)):(c=new we(this._pt,t,e,+p||0,n-(p||0),"boolean"==typeof d?de:fe,0,_),l&&(c.fp=l),u&&c.modifier(u,this,t),this._pt=c)},Ht=function _initTween(t,e,r){var i,n,a,s,o,u,h,l,f,c,d,p,_,m=t.vars,g=m.ease,v=m.startAt,y=m.immediateRender,T=m.lazy,b=m.onUpdate,x=m.runBackwards,k=m.yoyoEase,O=m.keyframes,M=m.autoRevert,C=t._dur,P=t._startAt,S=t._targets,A=t.parent,D=A&&"nested"===A.data?A.vars.targets:S,z="auto"===t._overwrite&&!F,R=t.timeline,E=m.easeReverse||k;if(!R||O&&g||(g="none"),t._ease=jt(g,j.ease),t._rEase=E&&(jt(E)||t._ease),t._from=!R&&!!m.runBackwards,t._from&&(t.ratio=1),!R||O&&!m.stagger){if(p=(l=S[0]?ha(S[0]).harness:0)&&m[l.prop],i=xa(m,dt),P&&(P._zTime<0&&P.progress(1),e<0&&x&&y&&!M?P.render(-1,!0):P.revert(x&&C?ft:lt),P._lazy=0),v){if(Ca(t._startAt=te.set(S,ta({data:"isStart",overwrite:!1,parent:A,immediateRender:!0,lazy:!P&&w(T),startAt:null,delay:0,onUpdate:b&&function(){return At(t,"onUpdate")},stagger:0},v))),t._startAt._dp=0,t._startAt._sat=t,e<0&&(I||!y&&!M)&&t._startAt.revert(ft),y&&C&&e<=0&&r<=0)return void(e&&(t._zTime=e))}else if(x&&C&&!P)if(e&&(y=!1),a=ta({overwrite:!1,data:"isFromStart",lazy:y&&!P&&w(T),immediateRender:y,stagger:0,parent:A},i),p&&(a[l.prop]=p),Ca(t._startAt=te.set(S,a)),t._startAt._dp=0,t._startAt._sat=t,e<0&&(I?t._startAt.revert(ft):t._startAt.render(-1,!0)),t._zTime=e,y){if(!e)return}else _initTween(t._startAt,q,q);for(t._pt=t._ptCache=0,T=C&&w(T)||T&&!C,n=0;n<S.length;n++){if(h=(o=S[n])._gsap||ga(S)[n]._gsap,t._ptLookup[n]=c={},_t[h.id]&&pt.length&&oa(),d=D===S?n:D.indexOf(o),l&&!1!==(f=new l).init(o,p||i,t,d,D)&&(t._pt=s=new we(t._pt,o,f.name,0,1,f.render,f,0,f.priority),f._props.forEach(function(t){c[t]=s}),f.priority&&(u=1)),!l||p)for(a in i)mt[a]&&(f=cc(a,i,t,d,o,D))?f.priority&&(u=1):c[a]=s=$t.call(t,o,a,"get",i[a],d,D,0,m.stringFilter);t._op&&t._op[n]&&t.kill(o,t._op[n]),z&&t._pt&&(Zt=t,L.killTweensOf(o,c,t.globalTime(e)),_=!t.parent,Zt=0),t._pt&&T&&(_t[h.id]=1)}u&&be(t),t._onInit&&t._onInit(t)}t._onUpdate=b,t._initted=(!t._op||t._pt)&&!_,O&&e<=0&&R.render(X,!0,!0)},Qt=function _parseFuncOrString(t,e,i,n,a){return s(t)?t.call(e,i,n,a):r(t)&&~t.indexOf("random(")?rb(t):t},Jt=Tt+"repeat,repeatDelay,yoyo,repeatRefresh,yoyoEase,easeReverse,autoRevert",Kt={};ja(Jt+",id,stagger,delay,duration,paused,scrollTrigger",function(t){return Kt[t]=1});var te=function(E){function Tween(e,r,i,n){var a;"number"==typeof r&&(i.duration=r,r=i,i=null);var s,o,u,h,l,f,c,d,p=(a=E.call(this,n?r:ya(r))||this).vars,_=p.duration,m=p.delay,g=p.immediateRender,b=p.stagger,x=p.overwrite,k=p.keyframes,O=p.defaults,M=p.scrollTrigger,C=r.parent||L,P=(K(e)||J(e)?t(e[0]):"length"in r)?[e]:Pt(e);if(a._targets=P.length?ga(P):T("GSAP target "+e+" not found. https://gsap.com",!Y.nullTargetWarn)||[],a._ptLookup=[],a._overwrite=x,k||b||y(_)||y(m)){var S=(r=a.vars).easeReverse||r.yoyoEase;if((s=a.timeline=new Gt({data:"nested",defaults:O||{},targets:C&&"nested"===C.data?C.vars.targets:P})).kill(),s.parent=s._dp=_assertThisInitialized(a),s._start=0,b||y(_)||y(m)){if(h=P.length,c=b&&hb(b),v(b))for(l in b)~Jt.indexOf(l)&&((d=d||{})[l]=b[l]);for(o=0;o<h;o++)(u=xa(r,Kt)).stagger=0,S&&(u.easeReverse=S),d&&bt(u,d),f=P[o],u.duration=+Qt(_,_assertThisInitialized(a),o,f,P),u.delay=(+Qt(m,_assertThisInitialized(a),o,f,P)||0)-a._delay,!b&&1===h&&u.delay&&(a._delay=m=u.delay,a._start+=m,u.delay=0),s.to(f,u,c?c(o,f,P):0),s._ease=Bt.none;s.duration()?_=m=0:a.timeline=0}else if(k){ya(ta(s.vars.defaults,{ease:"none"})),s._ease=jt(k.ease||r.ease||"none");var A,D,z,R=0;if(K(k))k.forEach(function(t){return s.to(P,t,">")}),s.duration();else{for(l in u={},k)"ease"===l||"easeEach"===l||ic(l,k[l],u,k.easeEach);for(l in u)for(A=u[l].sort(function(t,e){return t.t-e.t}),o=R=0;o<A.length;o++)(z={ease:(D=A[o]).e,duration:(D.t-(o?A[o-1].t:0))/100*_})[l]=D.v,s.to(P,z,R),R+=z.duration;s.duration()<_&&s.to({},{duration:_-s.duration()})}}_||a.duration(_=s.duration())}else a.timeline=0;return!0!==x||F||(Zt=_assertThisInitialized(a),L.killTweensOf(P),Zt=0),Na(C,_assertThisInitialized(a),i),r.reversed&&a.reverse(),r.paused&&a.paused(!0),(g||!_&&!k&&a._start===la(C._time)&&w(g)&&function _hasNoPausedAncestors(t){return!t||t._ts&&_hasNoPausedAncestors(t.parent)}(_assertThisInitialized(a))&&"nested"!==C.data)&&(a._tTime=-q,a.render(Math.max(0,-m)||0)),M&&Oa(_assertThisInitialized(a),M),a}_inheritsLoose(Tween,E);var e=Tween.prototype;return e.render=function render(t,e,r){var i,n,a,s,o,u,h,l,f=this._time,c=this._tDur,d=this._dur,p=t<0,_=c-q<t&&!p?c:t<q?0:t;if(d){if(_!==this._tTime||!t||r||!this._initted&&this._tTime||this._startAt&&this._zTime<0!=p||this._lazy){if(i=_,l=this.timeline,this._repeat){if(s=d+this._rDelay,this._repeat<-1&&p)return this.totalTime(100*s+t,e,r);if(i=la(_%s),_===c?(a=this._repeat,i=d):(a=~~(o=la(_/s)))&&a===o?(i=d,a--):d<i&&(i=d),(u=this._yoyo&&1&a)&&(i=d-i),o=wt(this._tTime,s),i===f&&!r&&this._initted&&a===o)return this._tTime=_,this;a!==o&&this.vars.repeatRefresh&&!u&&!this._lock&&i!==s&&this._initted&&(this._lock=r=1,this.render(la(s*a),!0).invalidate()._lock=0)}if(!this._initted){if(Pa(this,p?t:i,r,e,_))return this._tTime=0,this;if(!(f===this._time||r&&this.vars.repeatRefresh&&a!==o))return this;if(d!==this._dur)return this.render(t,e,r)}if(this._rEase){var m=i<f;if(m!==this._inv){var g=m?f:d-f;this._inv=m,this._from&&(this.ratio=1-this.ratio),this._invRatio=this.ratio,this._invTime=f,this._invRecip=g?(m?-1:1)/g:0,this._invScale=m?-this.ratio:1-this.ratio,this._invEase=m?this._rEase:this._ease}this.ratio=h=this._invRatio+this._invScale*this._invEase((i-this._invTime)*this._invRecip)}else this.ratio=h=this._ease(i/d);if(this._from&&(this.ratio=h=1-h),this._tTime=_,this._time=i,!this._act&&this._ts&&(this._act=1,this._lazy=0),!f&&_&&!e&&!o&&(At(this,"onStart"),this._tTime!==_))return this;for(n=this._pt;n;)n.r(h,n.d),n=n._next;l&&l.render(t<0?t:l._dur*l._ease(i/this._dur),e,r)||this._startAt&&(this._zTime=t),this._onUpdate&&!e&&(p&&Fa(this,t,0,r),At(this,"onUpdate")),this._repeat&&a!==o&&this.vars.onRepeat&&!e&&this.parent&&At(this,"onRepeat"),_!==this._tDur&&_||this._tTime!==_||(p&&!this._onUpdate&&Fa(this,t,0,!0),!t&&d||!(_===this._tDur&&0<this._ts||!_&&this._ts<0)||Ca(this,1),e||p&&!f||!(_||f||u)||(At(this,_===c?"onComplete":"onReverseComplete",!0),!this._prom||_<c&&0<this.timeScale()||this._prom()))}}else!function _renderZeroDurationTween(t,e,r,i){var n,a,s,o=t.ratio,u=e<0||!e&&(!t._start&&function _parentPlayheadIsBeforeStart(t){var e=t.parent;return e&&e._ts&&e._initted&&!e._lock&&(e.rawTime()<0||_parentPlayheadIsBeforeStart(e))}(t)&&(t._initted||!xt(t))||(t._ts<0||t._dp._ts<0)&&!xt(t))?0:1,h=t._rDelay,l=0;if(h&&t._repeat&&(l=Mt(0,t._tDur,e),a=wt(l,h),t._yoyo&&1&a&&(u=1-u),a!==wt(t._tTime,h)&&(o=1-u,t.vars.repeatRefresh&&t._initted&&t.invalidate())),u!==o||I||i||t._zTime===q||!e&&t._zTime){if(!t._initted&&Pa(t,e,i,r,l))return;for(s=t._zTime,t._zTime=e||(r?q:0),r=r||e&&!s,t.ratio=u,t._from&&(u=1-u),t._time=0,t._tTime=l,n=t._pt;n;)n.r(u,n.d),n=n._next;e<0&&Fa(t,e,0,!0),t._onUpdate&&!r&&At(t,"onUpdate"),l&&t._repeat&&!r&&t.parent&&At(t,"onRepeat"),(e>=t._tDur||e<0)&&t.ratio===u&&(u&&Ca(t,1),r||I||(At(t,u?"onComplete":"onReverseComplete",!0),t._prom&&t._prom()))}else t._zTime||(t._zTime=e)}(this,t,e,r);return this},e.targets=function targets(){return this._targets},e.invalidate=function invalidate(t){return t&&this.vars.runBackwards||(this._startAt=0),this._pt=this._op=this._onUpdate=this._lazy=this.ratio=0,this._ptLookup=[],this.timeline&&this.timeline.invalidate(t),E.prototype.invalidate.call(this,t)},e.resetTo=function resetTo(t,e,r,i,n){d||It.wake(),this._ts||this.play();var a,s=Math.min(this._dur,(this._dp._time-this._start)*this._ts);return this._initted||Ht(this,s),a=this._ease(s/this._dur),function _updatePropTweens(t,e,r,i,n,a,s,o){var u,h,l,f,c=(t._pt&&t._ptCache||(t._ptCache={}))[e];if(!c)for(c=t._ptCache[e]=[],l=t._ptLookup,f=t._targets.length;f--;){if((u=l[f][e])&&u.d&&u.d._pt)for(u=u.d._pt;u&&u.p!==e&&u.fp!==e;)u=u._next;if(!u)return Wt=1,t.vars[e]="+=0",Ht(t,s),Wt=0,o?T(e+" not eligible for reset. Try splitting into individual properties"):1;c.push(u)}for(f=c.length;f--;)(u=(h=c[f])._pt||h).s=!i&&0!==i||n?u.s+(i||0)+a*u.c:i,u.c=r-u.s,h.e&&(h.e=ka(r)+_a(h.e)),h.b&&(h.b=u.s+_a(h.b))}(this,t,e,r,i,a,s,n)?this.resetTo(t,e,r,i,1):(La(this,0),this.parent||Aa(this._dp,this,"_first","_last",this._dp._sort?"_start":0),this.render(0))},e.kill=function kill(t,e){if(void 0===e&&(e="all"),!(t||e&&"all"!==e))return this._lazy=this._pt=0,this.parent?wb(this):this.scrollTrigger&&this.scrollTrigger.kill(!!I),this;if(this.timeline){var i=this.timeline.totalDuration();return this.timeline.killTweensOf(t,e,Zt&&!0!==Zt.vars.overwrite)._first||wb(this),this.parent&&i!==this.timeline.totalDuration()&&Ua(this,this._dur*this.timeline._tDur/i,0,1),this}var n,a,s,o,u,h,l,f=this._targets,c=t?Pt(t):f,d=this._ptLookup,p=this._pt;if((!e||"all"===e)&&function _arraysMatch(t,e){for(var r=t.length,i=r===e.length;i&&r--&&t[r]===e[r];);return r<0}(f,c))return"all"===e&&(this._pt=0),wb(this);for(n=this._op=this._op||[],"all"!==e&&(r(e)&&(u={},ja(e,function(t){return u[t]=1}),e=u),e=function _addAliasesToVars(t,e){var r,i,n,a,s=t[0]?ha(t[0]).harness:0,o=s&&s.aliases;if(!o)return e;for(i in r=bt({},e),o)if(i in r)for(n=(a=o[i].split(",")).length;n--;)r[a[n]]=r[i];return r}(f,e)),l=f.length;l--;)if(~c.indexOf(f[l]))for(u in a=d[l],"all"===e?(n[l]=e,o=a,s={}):(s=n[l]=n[l]||{},o=e),o)(h=a&&a[u])&&("kill"in h.d&&!0!==h.d.kill(u)||Ba(this,h,"_pt"),delete a[u]),"all"!==s&&(s[u]=1);return this._initted&&!this._pt&&p&&wb(this),this},Tween.to=function to(t,e,r){return new Tween(t,e,r)},Tween.from=function from(t,e){return Ya(1,arguments)},Tween.delayedCall=function delayedCall(t,e,r,i){return new Tween(e,0,{immediateRender:!1,lazy:!1,overwrite:!1,delay:t,onComplete:e,onReverseComplete:e,onCompleteParams:r,onReverseCompleteParams:r,callbackScope:i})},Tween.fromTo=function fromTo(t,e,r){return Ya(2,arguments)},Tween.set=function set(t,e){return e.duration=0,e.repeatDelay||(e.repeat=0),new Tween(t,e)},Tween.killTweensOf=function killTweensOf(t,e,r){return L.killTweensOf(t,e,r)},Tween}(qt);ta(te.prototype,{_targets:[],_lazy:0,_startAt:0,_op:0,_onInit:0}),ja("staggerTo,staggerFrom,staggerFromTo",function(r){te[r]=function(){var t=new Gt,e=Ct.call(arguments,0);return e.splice("staggerFromTo"===r?5:4,0,0),t[r].apply(t,e)}});function qc(t,e,r){return t.setAttribute(e,r)}function yc(t,e,r,i){i.mSet(t,e,i.m.call(i.tween,r,i.mt),i)}var ie=function _setterPlain(t,e,r){return t[e]=r},ae=function _setterFunc(t,e,r){return t[e](r)},se=function _setterFuncWithParam(t,e,r,i){return t[e](i.fp,r)},ue=function _getSetter(t,e){return s(t[e])?ae:u(t[e])&&t.setAttribute?qc:ie},fe=function _renderPlain(t,e){return e.set(e.t,e.p,Math.round(1e6*(e.s+e.c*t))/1e6,e)},de=function _renderBoolean(t,e){return e.set(e.t,e.p,!!(e.s+e.c*t),e)},pe=function _renderComplexString(t,e){var r=e._pt,i="";if(!t&&e.b)i=e.b;else if(1===t&&e.e)i=e.e;else{for(;r;)i=r.p+(r.m?r.m(r.s+r.c*t):Math.round(1e4*(r.s+r.c*t))/1e4)+i,r=r._next;i+=e.c}e.set(e.t,e.p,i,e)},_e=function _renderPropTweens(t,e){for(var r=e._pt;r;)r.r(t,r.d),r=r._next},ve=function _addPluginModifier(t,e,r,i){for(var n,a=this._pt;a;)n=a._next,a.p===i&&a.modifier(t,e,r),a=n},Te=function _killPropTweensOf(t){for(var e,r,i=this._pt;i;)r=i._next,i.p===t&&!i.op||i.op===t?Ba(this,i,"_pt"):i.dep||(e=1),i=r;return!e},be=function _sortPropTweensByPriority(t){for(var e,r,i,n,a=t._pt;a;){for(e=a._next,r=i;r&&r.pr>a.pr;)r=r._next;(a._prev=r?r._prev:n)?a._prev._next=a:i=a,(a._next=r)?r._prev=a:n=a,a=e}t._pt=i},we=(PropTween.prototype.modifier=function modifier(t,e,r){this.mSet=this.mSet||this.set,this.set=yc,this.m=t,this.mt=r,this.tween=e},PropTween);function PropTween(t,e,r,i,n,a,s,o,u){this.t=e,this.s=i,this.c=n,this.p=r,this.r=a||fe,this.d=s||this,this.set=o||ie,this.pr=u||0,(this._next=t)&&(t._prev=this)}ja(Tt+"parent,duration,ease,delay,overwrite,runBackwards,startAt,yoyo,immediateRender,repeat,repeatDelay,data,paused,reversed,lazy,callbackScope,stringFilter,id,yoyoEase,stagger,inherit,repeatRefresh,keyframes,autoRevert,scrollTrigger,easeReverse",function(t){return dt[t]=1}),ht.TweenMax=ht.TweenLite=te,ht.TimelineLite=ht.TimelineMax=Gt,L=new Gt({sortChildren:!1,defaults:j,autoRemoveChildren:!0,id:"root",smoothChildTiming:!0}),Y.stringFilter=Ib;function Gc(t){return(Oe[t]||Me).map(function(t){return t()})}function Hc(){var t=Date.now(),o=[];2<t-Ce&&(Gc("matchMediaInit"),ke.forEach(function(t){var e,r,i,n,a=t.queries,s=t.conditions;for(r in a)(e=h.matchMedia(a[r]).matches)&&(i=1),e!==s[r]&&(s[r]=e,n=1);n&&(t.revert(),i&&o.push(t))}),Gc("matchMediaRevert"),o.forEach(function(e){return e.onMatch(e,function(t){return e.add(null,t)})}),Ce=t,Gc("matchMedia"))}var xe,ke=[],Oe={},Me=[],Ce=0,Pe=0,Se=((xe=Context.prototype).add=function add(t,i,n){function Gw(){var t,e=l,r=a.selector;return e&&e!==a&&e.data.push(a),n&&(a.selector=fb(n)),l=a,t=i.apply(a,arguments),s(t)&&a._r.push(t),l=e,a.selector=r,a.isReverted=!1,t}s(t)&&(n=i,i=t,t=s);var a=this;return a.last=Gw,t===s?Gw(a,function(t){return a.add(null,t)}):t?a[t]=Gw:Gw},xe.ignore=function ignore(t){var e=l;l=null,t(this),l=e},xe.getTweens=function getTweens(){var e=[];return this.data.forEach(function(t){return t instanceof Context?e.push.apply(e,t.getTweens()):t instanceof te&&!(t.parent&&"nested"===t.parent.data)&&e.push(t)}),e},xe.clear=function clear(){this._r.length=this.data.length=0},xe.kill=function kill(i,t){var n=this;if(i?function(){for(var t,e=n.getTweens(),r=n.data.length;r--;)"isFlip"===(t=n.data[r]).data&&(t.revert(),t.getChildren(!0,!0,!1).forEach(function(t){return e.splice(e.indexOf(t),1)}));for(e.map(function(t){return{g:t._dur||t._delay||t._sat&&!t._sat.vars.immediateRender?t.globalTime(0):-1/0,t:t}}).sort(function(t,e){return e.g-t.g||-1/0}).forEach(function(t){return t.t.revert(i)}),r=n.data.length;r--;)(t=n.data[r])instanceof Gt?"nested"!==t.data&&(t.scrollTrigger&&t.scrollTrigger.revert(),t.kill()):t instanceof te||!t.revert||t.revert(i);n._r.forEach(function(t){return t(i,n)}),n.isReverted=!0}():this.data.forEach(function(t){return t.kill&&t.kill()}),this.clear(),t)for(var e=ke.length;e--;)ke[e].id===this.id&&ke.splice(e,1)},xe.revert=function revert(t){this.kill(t||{})},Context);function Context(t,e){this.selector=e&&fb(e),this.data=[],this._r=[],this.isReverted=!1,this.id=Pe++,t&&this.add(t)}var De,Re=((De=MatchMedia.prototype).add=function add(t,e,r){v(t)||(t={matches:t});var i,n,a,s=new Se(0,r||this.scope),o=s.conditions={};for(n in l&&!s.selector&&(s.selector=l.selector),this.contexts.push(s),e=s.add("onMatch",e),s.queries=t)"all"===n?a=1:(i=h.matchMedia(t[n]))&&(ke.indexOf(s)<0&&ke.push(s),(o[n]=i.matches)&&(a=1),i.addListener?i.addListener(Hc):i.addEventListener("change",Hc));return a&&e(s,function(t){return s.add(null,t)}),this},De.revert=function revert(t){this.kill(t||{})},De.kill=function kill(e){this.contexts.forEach(function(t){return t.kill(e,!0)})},MatchMedia);function MatchMedia(t){this.contexts=[],this.scope=t,l&&l.data.push(this)}var Ee={registerPlugin:function registerPlugin(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];e.forEach(function(t){return zb(t)})},timeline:function timeline(t){return new Gt(t)},getTweensOf:function getTweensOf(t,e){return L.getTweensOf(t,e)},getProperty:function getProperty(i,t,e,n){r(i)&&(i=Pt(i)[0]);var a=ha(i||{}).get,s=e?sa:ra;return"native"===e&&(e=""),i?t?s((mt[t]&&mt[t].get||a)(i,t,e,n)):function(t,e,r){return s((mt[t]&&mt[t].get||a)(i,t,e,r))}:i},quickSetter:function quickSetter(r,e,i){if(1<(r=Pt(r)).length){var n=r.map(function(t){return Fe.quickSetter(t,e,i)}),a=n.length;return function(t){for(var e=a;e--;)n[e](t)}}r=r[0]||{};var s=mt[e],o=ha(r),u=o.harness&&(o.harness.aliases||{})[e]||e,h=s?function(t){var e=new s;c._pt=0,e.init(r,i?t+i:t,c,0,[r]),e.render(1,e),c._pt&&_e(1,c)}:o.set(r,u);return s?h:function(t){return h(r,u,i?t+i:t,o,1)}},quickTo:function quickTo(t,i,e){function $x(t,e,r){return n.resetTo(i,t,e,r)}var r,n=Fe.to(t,ta(((r={})[i]="+=0.1",r.paused=!0,r.stagger=0,r),e||{}));return $x.tween=n,$x},isTweening:function isTweening(t){return 0<L.getTweensOf(t,!0).length},defaults:function defaults(t){return t&&t.ease&&(t.ease=jt(t.ease,j.ease)),wa(j,t||{})},config:function config(t){return wa(Y,t||{})},registerEffect:function registerEffect(t){var i=t.name,n=t.effect,e=t.plugins,a=t.defaults,r=t.extendTimeline;(e||"").split(",").forEach(function(t){return t&&!mt[t]&&!ht[t]&&T(i+" effect requires "+t+" plugin.")}),gt[i]=function(t,e,r){return n(Pt(t),ta(e||{},a),r)},r&&(Gt.prototype[i]=function(t,e,r){return this.add(gt[i](t,v(e)?e:(r=e)&&{},this),r)})},registerEase:function registerEase(t,e){Bt[t]=jt(e)},parseEase:function parseEase(t,e){return arguments.length?jt(t,e):Bt},getById:function getById(t){return L.getById(t)},exportRoot:function exportRoot(t,e){void 0===t&&(t={});var r,i,n=new Gt(t);for(n.smoothChildTiming=w(t.smoothChildTiming),L.remove(n),n._dp=0,n._time=n._tTime=L._time,r=L._first;r;)i=r._next,!e&&!r._dur&&r instanceof te&&r.vars.onComplete===r._targets[0]||Na(n,r,r._start-r._delay),r=i;return Na(L,n,0),n},context:function context(t,e){return t?new Se(t,e):l},matchMedia:function matchMedia(t){return new Re(t)},matchMediaRefresh:function matchMediaRefresh(){return ke.forEach(function(t){var e,r,i=t.conditions;for(r in i)i[r]&&(i[r]=!1,e=1);e&&t.revert()})||Hc()},addEventListener:function addEventListener(t,e){var r=Oe[t]||(Oe[t]=[]);~r.indexOf(e)||r.push(e)},removeEventListener:function removeEventListener(t,e){var r=Oe[t],i=r&&r.indexOf(e);0<=i&&r.splice(i,1)},utils:{wrap:function wrap(e,t,r){var i=t-e;return K(e)?ob(e,wrap(0,e.length),t):Za(r,function(t){return(i+(t-e)%i)%i+e})},wrapYoyo:function wrapYoyo(e,t,r){var i=t-e,n=2*i;return K(e)?ob(e,wrapYoyo(0,e.length-1),t):Za(r,function(t){return e+(i<(t=(n+(t-e)%n)%n||0)?n-t:t)})},distribute:hb,random:kb,snap:jb,normalize:function normalize(t,e,r){return St(t,e,0,1,r)},getUnit:_a,clamp:function clamp(e,r,t){return Za(t,function(t){return Mt(e,r,t)})},splitColor:Db,toArray:Pt,selector:fb,mapRange:St,pipe:function pipe(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return function(t){return e.reduce(function(t,e){return e(t)},t)}},unitize:function unitize(e,r){return function(t){return e(parseFloat(t))+(r||_a(t))}},interpolate:function interpolate(e,i,t,n){var a=isNaN(e+i)?0:function(t){return(1-t)*e+t*i};if(!a){var s,o,u,h,l,f=r(e),c={};if(!0===t&&(n=1)&&(t=null),f)e={p:e},i={p:i};else if(K(e)&&!K(i)){for(u=[],h=e.length,l=h-2,o=1;o<h;o++)u.push(interpolate(e[o-1],e[o]));h--,a=function func(t){t*=h;var e=Math.min(l,~~t);return u[e](t-e)},t=i}else n||(e=bt(K(e)?[]:{},e));if(!u){for(s in i)$t.call(c,e,s,"get",i[s]);a=function func(t){return _e(t,c)||(f?e.p:e)}}}return Za(t,a)},shuffle:gb},install:R,effects:gt,ticker:It,updateRoot:Gt.updateRoot,plugins:mt,globalTimeline:L,core:{PropTween:we,globals:U,Tween:te,Timeline:Gt,Animation:qt,getCache:ha,_removeLinkedListItem:Ba,reverting:function reverting(){return I},context:function context(t){return t&&l&&(l.data.push(t),t._ctx=l),l},suppressOverwrites:function suppressOverwrites(t){return F=t}}};ja("to,from,fromTo,delayedCall,set,killTweensOf",function(t){return Ee[t]=te[t]}),It.add(Gt.updateRoot),c=Ee.to({},{duration:0});function Lc(t,e){for(var r=t._pt;r&&r.p!==e&&r.op!==e&&r.fp!==e;)r=r._next;return r}function Nc(t,a){return{name:t,headless:1,rawVars:1,init:function init(t,n,e){e._onInit=function(t){var e,i;if(r(n)&&(e={},ja(n,function(t){return e[t]=1}),n=e),a){for(i in e={},n)e[i]=a(n[i]);n=e}!function _addModifiers(t,e){var r,i,n,a=t._targets;for(r in e)for(i=a.length;i--;)(n=(n=t._ptLookup[i][r])&&n.d)&&(n._pt&&(n=Lc(n,r)),n&&n.modifier&&n.modifier(e[r],t,a[i],r))}(t,n)}}}}var Fe=Ee.registerPlugin({name:"attr",init:function init(t,e,r,i,n){var a,s,o;for(a in this.tween=r,e)o=t.getAttribute(a)||"",(s=this.add(t,"setAttribute",(o||0)+"",e[a],i,n,0,0,a)).op=a,s.b=o,this._props.push(a)},render:function render(t,e){for(var r=e._pt;r;)I?r.set(r.t,r.p,r.b,r):r.r(t,r.d),r=r._next}},{name:"endArray",headless:1,init:function init(t,e){for(var r=e.length;r--;)this.add(t,r,t[r]||0,e[r],0,0,0,0,0,1)}},Nc("roundProps",ib),Nc("modifiers"),Nc("snap",jb))||Ee;te.version=Gt.version=Fe.version="3.15.0",o=1,x()&&Lt();function xd(t,e){return e.set(e.t,e.p,Math.round(1e4*(e.s+e.c*t))/1e4+e.u,e)}function yd(t,e){return e.set(e.t,e.p,1===t?e.e:Math.round(1e4*(e.s+e.c*t))/1e4+e.u,e)}function zd(t,e){return e.set(e.t,e.p,t?Math.round(1e4*(e.s+e.c*t))/1e4+e.u:e.b,e)}function Ad(t,e){return e.set(e.t,e.p,1===t?e.e:t?Math.round(1e4*(e.s+e.c*t))/1e4+e.u:e.b,e)}function Bd(t,e){var r=e.s+e.c*t;e.set(e.t,e.p,~~(r+(r<0?-.5:.5))+e.u,e)}function Cd(t,e){return e.set(e.t,e.p,t?e.e:e.b,e)}function Dd(t,e){return e.set(e.t,e.p,1!==t?e.b:e.e,e)}function Ed(t,e,r){return t.style[e]=r}function Fd(t,e,r){return t.style.setProperty(e,r)}function Gd(t,e,r){return t._gsap[e]=r}function Hd(t,e,r){return t._gsap.scaleX=t._gsap.scaleY=r}function Id(t,e,r,i,n){var a=t._gsap;a.scaleX=a.scaleY=r,a.renderTransform(n,a)}function Jd(t,e,r,i,n){var a=t._gsap;a[e]=r,a.renderTransform(n,a)}function Md(t,e){var r=this,i=this.target,n=i.style,a=i._gsap;if(t in ur&&n){if(this.tfm=this.tfm||{},"transform"===t)return _r.transform.split(",").forEach(function(t){return Md.call(r,t,e)});if(~(t=_r[t]||t).indexOf(",")?t.split(",").forEach(function(t){return r.tfm[t]=wr(i,t)}):this.tfm[t]=a.x?a[t]:wr(i,t),t===gr&&(this.tfm.zOrigin=a.zOrigin),0<=this.props.indexOf(mr))return;a.svg&&(this.svgo=i.getAttribute("data-svg-origin"),this.props.push(gr,e,"")),t=mr}(n||e)&&this.props.push(t,e,n[t])}function Nd(t){t.translate&&(t.removeProperty("translate"),t.removeProperty("scale"),t.removeProperty("rotate"))}function Od(){var t,e,r=this.props,i=this.target,n=i.style,a=i._gsap;for(t=0;t<r.length;t+=3)r[t+1]?2===r[t+1]?i[r[t]](r[t+2]):i[r[t]]=r[t+2]:r[t+2]?n[r[t]]=r[t+2]:n.removeProperty("--"===r[t].substr(0,2)?r[t]:r[t].replace(cr,"-$1").toLowerCase());if(this.tfm){for(e in this.tfm)a[e]=this.tfm[e];a.svg&&(a.renderTransform(),i.setAttribute("data-svg-origin",this.svgo||"")),(t=je())&&t.isStart||n[mr]||(Nd(n),a.zOrigin&&n[gr]&&(n[gr]+=" "+a.zOrigin+"px",a.zOrigin=0,a.renderTransform()),a.uncache=1)}}function Pd(t,e){var r={target:t,props:[],revert:Od,save:Md};return t._gsap||Fe.core.getCache(t),e&&t.style&&t.nodeType&&e.split(",").forEach(function(t){return r.save(t)}),r}function Rd(t,e){var r=Le.createElementNS?Le.createElementNS((e||"http://www.w3.org/1999/xhtml").replace(/^https/,"http"),t):Le.createElement(t);return r&&r.style?r:Le.createElement(t)}function Sd(t,e,r){var i=getComputedStyle(t);return i[e]||i.getPropertyValue(e.replace(cr,"-$1").toLowerCase())||i.getPropertyValue(e)||!r&&Sd(t,yr(e)||e,1)||""}function Vd(){(function _windowExists(){return"undefined"!=typeof window})()&&window.document&&(Ie=window,Le=Ie.document,Be=Le.documentElement,Ue=Rd("div")||{style:{}},Rd("div"),mr=yr(mr),gr=mr+"Origin",Ue.style.cssText="border-width:0;line-height:0;position:absolute;padding:0",Ve=!!yr("perspective"),je=Fe.core.reverting,Ne=1)}function Wd(t){var e,r=t.ownerSVGElement,i=Rd("svg",r&&r.getAttribute("xmlns")||"http://www.w3.org/2000/svg"),n=t.cloneNode(!0);n.style.display="block",i.appendChild(n),Be.appendChild(i);try{e=n.getBBox()}catch(t){}return i.removeChild(n),Be.removeChild(i),e}function Xd(t,e){for(var r=e.length;r--;)if(t.hasAttribute(e[r]))return t.getAttribute(e[r])}function Yd(e){var r,i;try{r=e.getBBox()}catch(t){r=Wd(e),i=1}return r&&(r.width||r.height)||i||(r=Wd(e)),!r||r.width||r.x||r.y?r:{x:+Xd(e,["x","cx","x1"])||0,y:+Xd(e,["y","cy","y1"])||0,width:0,height:0}}function Zd(t){return!(!t.getCTM||t.parentNode&&!t.ownerSVGElement||!Yd(t))}function $d(t,e){if(e){var r,i=t.style;e in ur&&e!==gr&&(e=mr),i.removeProperty?("ms"!==(r=e.substr(0,2))&&"webkit"!==e.substr(0,6)||(e="-"+e),i.removeProperty("--"===r?e:e.replace(cr,"-$1").toLowerCase())):i.removeAttribute(e)}}function _d(t,e,r,i,n,a){var s=new we(t._pt,e,r,0,1,a?Dd:Cd);return(t._pt=s).b=i,s.e=n,t._props.push(r),s}function ce(t,e,r,i){var n,a,s,o,u=parseFloat(r)||0,h=(r+"").trim().substr((u+"").length)||"px",l=Ue.style,f=dr.test(e),c="svg"===t.tagName.toLowerCase(),d=(c?"client":"offset")+(f?"Width":"Height"),p="px"===i,_="%"===i;if(i===h||!u||Tr[i]||Tr[h])return u;if("px"===h||p||(u=ce(t,e,r,"px")),o=t.getCTM&&Zd(t),(_||"%"===h)&&(ur[e]||~e.indexOf("adius")))return n=o?t.getBBox()[f?"width":"height"]:t[d],ka(_?u/n*100:u/100*n);if(l[f?"width":"height"]=100+(p?h:i),a="rem"!==i&&~e.indexOf("adius")||"em"===i&&t.appendChild&&!c?t:t.parentNode,o&&(a=(t.ownerSVGElement||{}).parentNode),a&&a!==Le&&a.appendChild||(a=Le.body),(s=a._gsap)&&_&&s.width&&f&&s.time===It.time&&!s.uncache)return ka(u/s.width*100);if(!_||"height"!==e&&"width"!==e)!_&&"%"!==h||br[Sd(a,"display")]||(l.position=Sd(t,"position")),a===t&&(l.position="static"),a.appendChild(Ue),n=Ue[d],a.removeChild(Ue),l.position="absolute";else{var m=t.style[e];t.style[e]=100+i,n=t[d],m?t.style[e]=m:$d(t,e)}return f&&_&&((s=ha(a)).time=It.time,s.width=a[d]),ka(p?n*u/100:n&&u?100/n*u:0)}function ee(t,e,r,i){if(!r||"none"===r){var n=yr(e,t,1),a=n&&Sd(t,n,1);a&&a!==r?(e=n,r=a):"borderColor"===e&&(r=Sd(t,"borderTopColor"))}var s,o,u,h,l,f,c,d,p,_,m,g=new we(this._pt,t.style,e,0,1,pe),v=0,y=0;if(g.b=r,g.e=i,r+="","var(--"===(i+="").substring(0,6)&&(i=Sd(t,i.substring(4,i.indexOf(")")))),"auto"===i&&(f=t.style[e],t.style[e]=i,i=Sd(t,e)||i,f?t.style[e]=f:$d(t,e)),Ib(s=[r,i]),i=s[1],u=(r=s[0]).match(nt)||[],(i.match(nt)||[]).length){for(;o=nt.exec(i);)c=o[0],p=i.substring(v,o.index),l?l=(l+1)%5:"rgba("!==p.substr(-5)&&"hsla("!==p.substr(-5)||(l=1),c!==(f=u[y++]||"")&&(h=parseFloat(f)||0,m=f.substr((h+"").length),"="===c.charAt(1)&&(c=ma(h,c)+m),d=parseFloat(c),_=c.substr((d+"").length),v=nt.lastIndex-_.length,_||(_=_||Y.units[e]||m,v===i.length&&(i+=_,g.e+=_)),m!==_&&(h=ce(t,e,f,_)||0),g._pt={_next:g._pt,p:p||1===y?p:",",s:h,c:d-h,m:l&&l<4||"zIndex"===e?Math.round:0});g.c=v<i.length?i.substring(v,i.length):""}else g.r="display"===e&&"none"===i?Dd:Cd;return st.test(i)&&(g.e=0),this._pt=g}function ge(t){var e=t.split(" "),r=e[0],i=e[1]||"50%";return"top"!==r&&"bottom"!==r&&"left"!==i&&"right"!==i||(t=r,r=i,i=t),e[0]=xr[r]||r,e[1]=xr[i]||i,e.join(" ")}function he(t,e){if(e.tween&&e.tween._time===e.tween._dur){var r,i,n,a=e.t,s=a.style,o=e.u,u=a._gsap;if("all"===o||!0===o)s.cssText="",i=1;else for(n=(o=o.split(",")).length;-1<--n;)r=o[n],ur[r]&&(i=1,r="transformOrigin"===r?gr:mr),$d(a,r);i&&($d(a,mr),u&&(u.svg&&a.removeAttribute("transform"),s.scale=s.rotate=s.translate="none",Cr(a,1),u.uncache=1,Nd(s)))}}function le(t){return"matrix(1, 0, 0, 1, 0, 0)"===t||"none"===t||!t}function me(t){var e=Sd(t,mr);return le(e)?Or:e.substr(7).match(it).map(ka)}function ne(t,e){var r,i,n,a,s=t._gsap||ha(t),o=t.style,u=me(t);return s.svg&&t.getAttribute("transform")?"1,0,0,1,0,0"===(u=[(n=t.transform.baseVal.consolidate().matrix).a,n.b,n.c,n.d,n.e,n.f]).join(",")?Or:u:(u!==Or||t.offsetParent||t===Be||s.svg||(n=o.display,o.display="block",(r=t.parentNode)&&(t.offsetParent||t.getBoundingClientRect().width)||(a=1,i=t.nextElementSibling,Be.appendChild(t)),u=me(t),n?o.display=n:$d(t,"display"),a&&(i?r.insertBefore(t,i):r?r.appendChild(t):Be.removeChild(t))),e&&6<u.length?[u[0],u[1],u[4],u[5],u[12],u[13]]:u)}function oe(t,e,r,i,n,a){var s,o,u,h=t._gsap,l=n||ne(t,!0),f=h.xOrigin||0,c=h.yOrigin||0,d=h.xOffset||0,p=h.yOffset||0,_=l[0],m=l[1],g=l[2],v=l[3],y=l[4],T=l[5],b=e.split(" "),w=parseFloat(b[0])||0,x=parseFloat(b[1])||0;r?l!==Or&&(o=_*v-m*g)&&(u=w*(-m/o)+x*(_/o)-(_*T-m*y)/o,w=w*(v/o)+x*(-g/o)+(g*T-v*y)/o,x=u):(w=(s=Yd(t)).x+(~b[0].indexOf("%")?w/100*s.width:w),x=s.y+(~(b[1]||b[0]).indexOf("%")?x/100*s.height:x)),i||!1!==i&&h.smooth?(y=w-f,T=x-c,h.xOffset=d+(y*_+T*g)-y,h.yOffset=p+(y*m+T*v)-T):h.xOffset=h.yOffset=0,h.xOrigin=w,h.yOrigin=x,h.smooth=!!i,h.origin=e,h.originIsAbsolute=!!r,t.style[gr]="0px 0px",a&&(_d(a,h,"xOrigin",f,w),_d(a,h,"yOrigin",c,x),_d(a,h,"xOffset",d,h.xOffset),_d(a,h,"yOffset",p,h.yOffset)),t.setAttribute("data-svg-origin",w+" "+x)}function re(t,e,r){var i=_a(e);return ka(parseFloat(e)+parseFloat(ce(t,"x",r+"px",i)))+i}function ye(t,e,i,n,a){var s,o,u=360,h=r(a),l=parseFloat(a)*(h&&~a.indexOf("rad")?hr:1)-n,f=n+l+"deg";return h&&("short"===(s=a.split("_")[1])&&(l%=u)!==l%180&&(l+=l<0?u:-u),"cw"===s&&l<0?l=(l+36e9)%u-~~(l/u)*u:"ccw"===s&&0<l&&(l=(l-36e9)%u-~~(l/u)*u)),t._pt=o=new we(t._pt,e,i,n,l,yd),o.e=f,o.u="deg",t._props.push(i),o}function ze(t,e){for(var r in e)t[r]=e[r];return t}function Ae(t,e,r){var i,n,a,s,o,u,h,l=ze({},r._gsap),f=r.style;for(n in l.svg?(a=r.getAttribute("transform"),r.setAttribute("transform",""),f[mr]=e,i=Cr(r,1),$d(r,mr),r.setAttribute("transform",a)):(a=getComputedStyle(r)[mr],f[mr]=e,i=Cr(r,1),f[mr]=a),ur)(a=l[n])!==(s=i[n])&&"perspective,force3D,transformOrigin,svgOrigin".indexOf(n)<0&&(o=_a(a)!==(h=_a(s))?ce(r,n,a,h):parseFloat(a),u=parseFloat(s),t._pt=new we(t._pt,i,n,o,u-o,xd),t._pt.u=h||0,t._props.push(n));ze(i,l)}var Ie,Le,Be,Ne,Ue,Ye,je,Ve,Xe=Bt.Power0,qe=Bt.Power1,Ge=Bt.Power2,Ze=Bt.Power3,We=Bt.Power4,$e=Bt.Linear,He=Bt.Quad,Qe=Bt.Cubic,Je=Bt.Quart,Ke=Bt.Quint,tr=Bt.Strong,er=Bt.Elastic,rr=Bt.Back,ir=Bt.SteppedEase,nr=Bt.Bounce,ar=Bt.Sine,sr=Bt.Expo,or=Bt.Circ,ur={},hr=180/Math.PI,lr=Math.PI/180,fr=Math.atan2,cr=/([A-Z])/g,dr=/(left|right|width|margin|padding|x)/i,pr=/[\s,\(]\S/,_r={autoAlpha:"opacity,visibility",scale:"scaleX,scaleY",alpha:"opacity"},mr="transform",gr=mr+"Origin",vr="O,Moz,ms,Ms,Webkit".split(","),yr=function _checkPropPrefix(t,e,r){var i=(e||Ue).style,n=5;if(t in i&&!r)return t;for(t=t.charAt(0).toUpperCase()+t.substr(1);n--&&!(vr[n]+t in i););return n<0?null:(3===n?"ms":0<=n?vr[n]:"")+t},Tr={deg:1,rad:1,turn:1},br={grid:1,flex:1},wr=function _get(t,e,r,i){var n;return Ne||Vd(),e in _r&&"transform"!==e&&~(e=_r[e]).indexOf(",")&&(e=e.split(",")[0]),ur[e]&&"transform"!==e?(n=Cr(t,i),n="transformOrigin"!==e?n[e]:n.svg?n.origin:Pr(Sd(t,gr))+" "+n.zOrigin+"px"):(n=t.style[e])&&"auto"!==n&&!i&&!~(n+"").indexOf("calc(")||(n=kr[e]&&kr[e](t,e,r)||Sd(t,e)||ia(t,e)||("opacity"===e?1:0)),r&&!~(n+"").trim().indexOf(" ")?ce(t,e,n,r)+r:n},xr={top:"0%",bottom:"100%",left:"0%",right:"100%",center:"50%"},kr={clearProps:function clearProps(t,e,r,i,n){if("isFromStart"!==n.data){var a=t._pt=new we(t._pt,e,r,0,0,he);return a.u=i,a.pr=-10,a.tween=n,t._props.push(r),1}}},Or=[1,0,0,1,0,0],Mr={},Cr=function _parseTransform(t,e){var r=t._gsap||new Xt(t);if("x"in r&&!e&&!r.uncache)return r;var i,n,a,s,o,u,h,l,f,c,d,p,_,m,g,v,y,T,b,w,x,k,O,M,C,P,S,A,D,z,R,E,F=t.style,I=r.scaleX<0,L="deg",B=getComputedStyle(t),N=Sd(t,gr)||"0";return i=n=a=u=h=l=f=c=d=0,s=o=1,r.svg=!(!t.getCTM||!Zd(t)),B.translate&&("none"===B.translate&&"none"===B.scale&&"none"===B.rotate||(F[mr]=("none"!==B.translate?"translate3d("+(B.translate+" 0 0").split(" ").slice(0,3).join(", ")+") ":"")+("none"!==B.rotate?"rotate("+B.rotate+") ":"")+("none"!==B.scale?"scale("+B.scale.split(" ").join(",")+") ":"")+("none"!==B[mr]?B[mr]:"")),F.scale=F.rotate=F.translate="none"),m=ne(t,r.svg),r.svg&&(M=r.uncache?(C=t.getBBox(),N=r.xOrigin-C.x+"px "+(r.yOrigin-C.y)+"px",""):!e&&t.getAttribute("data-svg-origin"),oe(t,M||N,!!M||r.originIsAbsolute,!1!==r.smooth,m)),p=r.xOrigin||0,_=r.yOrigin||0,m!==Or&&(T=m[0],b=m[1],w=m[2],x=m[3],i=k=m[4],n=O=m[5],6===m.length?(s=Math.sqrt(T*T+b*b),o=Math.sqrt(x*x+w*w),u=T||b?fr(b,T)*hr:0,(f=w||x?fr(w,x)*hr+u:0)&&(o*=Math.abs(Math.cos(f*lr))),r.svg&&(i-=p-(p*T+_*w),n-=_-(p*b+_*x))):(E=m[6],z=m[7],S=m[8],A=m[9],D=m[10],R=m[11],i=m[12],n=m[13],a=m[14],h=(g=fr(E,D))*hr,g&&(M=k*(v=Math.cos(-g))+S*(y=Math.sin(-g)),C=O*v+A*y,P=E*v+D*y,S=k*-y+S*v,A=O*-y+A*v,D=E*-y+D*v,R=z*-y+R*v,k=M,O=C,E=P),l=(g=fr(-w,D))*hr,g&&(v=Math.cos(-g),R=x*(y=Math.sin(-g))+R*v,T=M=T*v-S*y,b=C=b*v-A*y,w=P=w*v-D*y),u=(g=fr(b,T))*hr,g&&(M=T*(v=Math.cos(g))+b*(y=Math.sin(g)),C=k*v+O*y,b=b*v-T*y,O=O*v-k*y,T=M,k=C),h&&359.9<Math.abs(h)+Math.abs(u)&&(h=u=0,l=180-l),s=ka(Math.sqrt(T*T+b*b+w*w)),o=ka(Math.sqrt(O*O+E*E)),g=fr(k,O),f=2e-4<Math.abs(g)?g*hr:0,d=R?1/(R<0?-R:R):0),r.svg&&(M=t.getAttribute("transform"),r.forceCSS=t.setAttribute("transform","")||!le(Sd(t,mr)),M&&t.setAttribute("transform",M))),90<Math.abs(f)&&Math.abs(f)<270&&(I?(s*=-1,f+=u<=0?180:-180,u+=u<=0?180:-180):(o*=-1,f+=f<=0?180:-180)),e=e||r.uncache,r.x=i-((r.xPercent=i&&(!e&&r.xPercent||(Math.round(t.offsetWidth/2)===Math.round(-i)?-50:0)))?t.offsetWidth*r.xPercent/100:0)+"px",r.y=n-((r.yPercent=n&&(!e&&r.yPercent||(Math.round(t.offsetHeight/2)===Math.round(-n)?-50:0)))?t.offsetHeight*r.yPercent/100:0)+"px",r.z=a+"px",r.scaleX=ka(s),r.scaleY=ka(o),r.rotation=ka(u)+L,r.rotationX=ka(h)+L,r.rotationY=ka(l)+L,r.skewX=f+L,r.skewY=c+L,r.transformPerspective=d+"px",(r.zOrigin=parseFloat(N.split(" ")[2])||!e&&r.zOrigin||0)&&(F[gr]=Pr(N)),r.xOffset=r.yOffset=0,r.force3D=Y.force3D,r.renderTransform=r.svg?Er:Ve?Rr:Sr,r.uncache=0,r},Pr=function _firstTwoOnly(t){return(t=t.split(" "))[0]+" "+t[1]},Sr=function _renderNon3DTransforms(t,e){e.z="0px",e.rotationY=e.rotationX="0deg",e.force3D=0,Rr(t,e)},Ar="0deg",Dr="0px",zr=") ",Rr=function _renderCSSTransforms(t,e){var r=e||this,i=r.xPercent,n=r.yPercent,a=r.x,s=r.y,o=r.z,u=r.rotation,h=r.rotationY,l=r.rotationX,f=r.skewX,c=r.skewY,d=r.scaleX,p=r.scaleY,_=r.transformPerspective,m=r.force3D,g=r.target,v=r.zOrigin,y="",T="auto"===m&&t&&1!==t||!0===m;if(v&&(l!==Ar||h!==Ar)){var b,w=parseFloat(h)*lr,x=Math.sin(w),k=Math.cos(w);w=parseFloat(l)*lr,b=Math.cos(w),a=re(g,a,x*b*-v),s=re(g,s,-Math.sin(w)*-v),o=re(g,o,k*b*-v+v)}_!==Dr&&(y+="perspective("+_+zr),(i||n)&&(y+="translate("+i+"%, "+n+"%) "),!T&&a===Dr&&s===Dr&&o===Dr||(y+=o!==Dr||T?"translate3d("+a+", "+s+", "+o+") ":"translate("+a+", "+s+zr),u!==Ar&&(y+="rotate("+u+zr),h!==Ar&&(y+="rotateY("+h+zr),l!==Ar&&(y+="rotateX("+l+zr),f===Ar&&c===Ar||(y+="skew("+f+", "+c+zr),1===d&&1===p||(y+="scale("+d+", "+p+zr),g.style[mr]=y||"translate(0, 0)"},Er=function _renderSVGTransforms(t,e){var r,i,n,a,s,o=e||this,u=o.xPercent,h=o.yPercent,l=o.x,f=o.y,c=o.rotation,d=o.skewX,p=o.skewY,_=o.scaleX,m=o.scaleY,g=o.target,v=o.xOrigin,y=o.yOrigin,T=o.xOffset,b=o.yOffset,w=o.forceCSS,x=parseFloat(l),k=parseFloat(f);c=parseFloat(c),d=parseFloat(d),(p=parseFloat(p))&&(d+=p=parseFloat(p),c+=p),c||d?(c*=lr,d*=lr,r=Math.cos(c)*_,i=Math.sin(c)*_,n=Math.sin(c-d)*-m,a=Math.cos(c-d)*m,d&&(p*=lr,s=Math.tan(d-p),n*=s=Math.sqrt(1+s*s),a*=s,p&&(s=Math.tan(p),r*=s=Math.sqrt(1+s*s),i*=s)),r=ka(r),i=ka(i),n=ka(n),a=ka(a)):(r=_,a=m,i=n=0),(x&&!~(l+"").indexOf("px")||k&&!~(f+"").indexOf("px"))&&(x=ce(g,"x",l,"px"),k=ce(g,"y",f,"px")),(v||y||T||b)&&(x=ka(x+v-(v*r+y*n)+T),k=ka(k+y-(v*i+y*a)+b)),(u||h)&&(s=g.getBBox(),x=ka(x+u/100*s.width),k=ka(k+h/100*s.height)),s="matrix("+r+","+i+","+n+","+a+","+x+","+k+")",g.setAttribute("transform",s),w&&(g.style[mr]=s)};ja("padding,margin,Width,Radius",function(e,r){var t="Right",i="Bottom",n="Left",o=(r<3?["Top",t,i,n]:["Top"+n,"Top"+t,i+t,i+n]).map(function(t){return r<2?e+t:"border"+t+e});kr[1<r?"border"+e:e]=function(e,t,r,i,n){var a,s;if(arguments.length<4)return a=o.map(function(t){return wr(e,t,r)}),5===(s=a.join(" ")).split(a[0]).length?a[0]:s;a=(i+"").split(" "),s={},o.forEach(function(t,e){return s[t]=a[e]=a[e]||a[(e-1)/2|0]}),e.init(t,s,n)}});var Fr,Ir,Lr,Br={name:"css",register:Vd,targetTest:function targetTest(t){return t.style&&t.nodeType},init:function init(t,e,i,n,a){var s,o,u,h,l,f,c,d,p,_,m,g,v,y,T,b,w,x=this._props,k=t.style,O=i.vars.startAt;for(c in Ne||Vd(),this.styles=this.styles||Pd(t),b=this.styles.props,this.tween=i,e)if("autoRound"!==c&&(o=e[c],!mt[c]||!cc(c,e,i,n,t,a)))if(l=typeof o,f=kr[c],"function"===l&&(l=typeof(o=o.call(i,n,t,a))),"string"===l&&~o.indexOf("random(")&&(o=rb(o)),f)f(this,t,c,o,i)&&(T=1);else if("--"===c.substr(0,2))s=(getComputedStyle(t).getPropertyValue(c)+"").trim(),o+="",Et.lastIndex=0,Et.test(s)||(d=_a(s),(p=_a(o))?d!==p&&(s=ce(t,c,s,p)+p):d&&(o+=d)),this.add(k,"setProperty",s,o,n,a,0,0,c),x.push(c),b.push(c,0,k[c]);else if("undefined"!==l){if(O&&c in O?(s="function"==typeof O[c]?O[c].call(i,n,t,a):O[c],r(s)&&~s.indexOf("random(")&&(s=rb(s)),_a(s+"")||"auto"===s||(s+=Y.units[c]||_a(wr(t,c))||""),"="===(s+"").charAt(1)&&(s=wr(t,c))):s=wr(t,c),h=parseFloat(s),(_="string"===l&&"="===o.charAt(1)&&o.substr(0,2))&&(o=o.substr(2)),u=parseFloat(o),c in _r&&("autoAlpha"===c&&(1===h&&"hidden"===wr(t,"visibility")&&u&&(h=0),b.push("visibility",0,k.visibility),_d(this,k,"visibility",h?"inherit":"hidden",u?"inherit":"hidden",!u)),"scale"!==c&&"transform"!==c&&~(c=_r[c]).indexOf(",")&&(c=c.split(",")[0])),m=c in ur){if(this.styles.save(c),w=o,"string"===l&&"var(--"===o.substring(0,6)){if("calc("===(o=Sd(t,o.substring(4,o.indexOf(")")))).substring(0,5)){var M=t.style.perspective;t.style.perspective=o,o=Sd(t,"perspective"),M?t.style.perspective=M:$d(t,"perspective")}u=parseFloat(o)}if(g||((v=t._gsap).renderTransform&&!e.parseTransform||Cr(t,e.parseTransform),y=!1!==e.smoothOrigin&&v.smooth,(g=this._pt=new we(this._pt,k,mr,0,1,v.renderTransform,v,0,-1)).dep=1),"scale"===c)this._pt=new we(this._pt,v,"scaleY",v.scaleY,(_?ma(v.scaleY,_+u):u)-v.scaleY||0,xd),this._pt.u=0,x.push("scaleY",c),c+="X";else{if("transformOrigin"===c){b.push(gr,0,k[gr]),o=ge(o),v.svg?oe(t,o,0,y,0,this):((p=parseFloat(o.split(" ")[2])||0)!==v.zOrigin&&_d(this,v,"zOrigin",v.zOrigin,p),_d(this,k,c,Pr(s),Pr(o)));continue}if("svgOrigin"===c){oe(t,o,1,y,0,this);continue}if(c in Mr){ye(this,v,c,h,_?ma(h,_+o):o);continue}if("smoothOrigin"===c){_d(this,v,"smooth",v.smooth,o);continue}if("force3D"===c){v[c]=o;continue}if("transform"===c){Ae(this,o,t);continue}}}else c in k||(c=yr(c)||c);if(m||(u||0===u)&&(h||0===h)&&!pr.test(o)&&c in k)u=u||0,(d=(s+"").substr((h+"").length))!==(p=_a(o)||(c in Y.units?Y.units[c]:d))&&(h=ce(t,c,s,p)),this._pt=new we(this._pt,m?v:k,c,h,(_?ma(h,_+u):u)-h,m||"px"!==p&&"zIndex"!==c||!1===e.autoRound?xd:Bd),this._pt.u=p||0,m&&w!==o?(this._pt.b=s,this._pt.e=w,this._pt.r=Ad):d!==p&&"%"!==p&&(this._pt.b=s,this._pt.r=zd);else if(c in k)ee.call(this,t,c,s,_?_+o:o);else if(c in t)this.add(t,c,s||t[c],_?_+o:o,n,a);else if("parseTransform"!==c){S(c,o);continue}m||(c in k?b.push(c,0,k[c]):"function"==typeof t[c]?b.push(c,2,t[c]()):b.push(c,1,s||t[c])),x.push(c)}T&&be(this)},render:function render(t,e){if(e.tween._time||!je())for(var r=e._pt;r;)r.r(t,r.d),r=r._next;else e.styles.revert()},get:wr,aliases:_r,getSetter:function getSetter(t,e,r){var i=_r[e];return i&&i.indexOf(",")<0&&(e=i),e in ur&&e!==gr&&(t._gsap.x||wr(t,"x"))?r&&Ye===r?"scale"===e?Hd:Gd:(Ye=r||{})&&("scale"===e?Id:Jd):t.style&&!u(t.style[e])?Ed:~e.indexOf("-")?Fd:ue(t,e)},core:{_removeProperty:$d,_getMatrix:ne}};Fe.utils.checkPrefix=yr,Fe.core.getStyleSaver=Pd,Lr=ja((Fr="x,y,z,scale,scaleX,scaleY,xPercent,yPercent")+","+(Ir="rotation,rotationX,rotationY,skewX,skewY")+",transform,transformOrigin,svgOrigin,force3D,smoothOrigin,transformPerspective",function(t){ur[t]=1}),ja(Ir,function(t){Y.units[t]="deg",Mr[t]=1}),_r[Lr[13]]=Fr+","+Ir,ja("0:translateX,1:translateY,2:translateZ,8:rotate,8:rotationZ,8:rotateZ,9:rotateX,10:rotateY",function(t){var e=t.split(":");_r[e[1]]=Lr[e[0]]}),ja("x,y,z,top,right,bottom,left,width,height,fontSize,padding,margin,perspective",function(t){Y.units[t]="px"}),Fe.registerPlugin(Br);var Nr=Fe.registerPlugin(Br)||Fe,Ur=Nr.core.Tween;e.Back=rr,e.Bounce=nr,e.CSSPlugin=Br,e.Circ=or,e.Cubic=Qe,e.Elastic=er,e.Expo=sr,e.Linear=$e,e.Power0=Xe,e.Power1=qe,e.Power2=Ge,e.Power3=Ze,e.Power4=We,e.Quad=He,e.Quart=Je,e.Quint=Ke,e.Sine=ar,e.SteppedEase=ir,e.Strong=tr,e.TimelineLite=Gt,e.TimelineMax=Gt,e.TweenLite=te,e.TweenMax=Ur,e.default=Nr,e.gsap=Nr;if (typeof(window)==="undefined"||window!==e){Object.defineProperty(e,"__esModule",{value:!0})} else {delete e.default}});diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-consistency/SKILL.md b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-consistency/SKILL.mdindex 1f476222..6da33197 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-consistency/SKILL.md+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-consistency/SKILL.md@@ -56,7 +56,7 @@ For each shot, before generating it, assemble the reference images and bind themFor a character-critical shot, generate the **first-frame image** first (cheap), check it, and only then drive the video from that locked frame — catching drift at the still is far cheaper than discovering it after paying to animate.- **Check the keyframe against the bible** on the identity axes, in priority order: 1) character — gender, age, ethnicity, facial features, body shape, hairstyle; 2) spatial — relative positions/perspective match the reference (left stays left); 3) accuracy — matches the shot's description. Read it yourself if multimodal; if you cannot see images, mark it unverified and lean harder on a strong locked reference.-- **Re-roll the cheap image**, not the expensive video, until it matches; generate a few candidates and keep the most consistent one. Never hard-fail — pick the best and note its shortcoming.+- **Re-roll the cheap image**, not the expensive video — at most 3 re-rolls per keyframe (each is billable), then keep the most consistent candidate. Never hard-fail — pick the best and note its shortcoming.## 5. Carry-forward (continuity between shots)diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-decide/SKILL.md b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-decide/SKILL.mdindex dd1a884c..9013d368 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-decide/SKILL.md+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-decide/SKILL.md@@ -1,6 +1,7 @@---ownerAgent: 79df9cc89f5fname: stage-decide+min_app_version: "1.5.1"description_zh: 真实素材的"决策层"——看懂素材→取舍→出带证据的粗剪。当 EDIT 任务是"找/选/缩/清理"(去静音、删填充词、长片选高光、1小时剪3分钟)而不是按已知时间码执行时用它;确定性自动剪(去静音/删填充/列镜头)可靠,叙事/情绪取舍是低置信、需人审的草稿。description_en: The decision layer for real footage — understand → select → produce an EVIDENCE-bearing rough cut. Use it when the EDIT task is "find / select / reduce / clean" (remove dead air, drop fillers, pick highlights, cut 1 hour to 3 minutes), not executing a known timecode edit. Deterministic auto-cuts are reliable; narrative/emotional selection is a low-confidence DRAFT for the user to review.category: creation@@ -16,7 +17,7 @@ The hard, valuable part of editing real footage is not executing a cut you alreaHost-neutral: describe what to produce; the host provides the operations. In Orkas, use skill scripts:`stage-edit edit_video --op trim_silence` / `--op remove_fillers` (deterministic auto-cuts that return evidence),`stage-edit analyze_media --op scenes` (cut candidates), `--op quality` (blur/exposure/black/freeze flags),-`--op transcribe` (word timings), `--op silence`.+`video_studio` `op: "speech.transcribe"` for transcription, and `stage-edit analyze_media --op silence`.## Use this when@@ -29,7 +30,7 @@ skip this — that is plain `stage-edit`.1. **Understand the material first** (never decide against footage you have not measured):- `probe` for duration/resolution.- - Spoken footage → `transcribe` (word-level timings) so you cut on sentence/word boundaries, never mid-word.+ - Spoken footage → use `video_studio` `op: "speech.transcribe"` so you cut on sentence/word boundaries, never mid-word.- Visual reduction → `scenes` for shot boundaries; bound the moments you keep on these candidates.- Dead air → `silence` to see the gaps.2. **Decide — deterministic first, judgment second:**diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/SKILL.md b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/SKILL.mdindex ab14e496..edc29258 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/SKILL.md+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/SKILL.md@@ -1,6 +1,7 @@---ownerAgent: 79df9cc89f5fname: stage-edit+min_app_version: "1.5.1"description_zh: 真实素材的确定性剪辑知识——读素材元数据、按明确时间点切片/拼接/烧字幕/叠加,规划 edit_decisions 时间线再执行;clip-factory / 蒙太奇 / 二次创作产线的核心。description_en: Deterministic editing knowledge for real footage — probe inputs, then trim/concat/burn-subtitles/overlay by explicit timecodes via an edit_decisions timeline; core of the clip-factory / montage / repurpose lines.category: creation@@ -12,12 +13,11 @@ How to edit **real user-supplied footage** deterministically (cut / join / burn## How to call the media scripts-Use these `run-skill` entry points whenever this document says `stage-edit edit_video --op ...` or `stage-edit analyze_media --op ...`:+Use these `run-skill` entry points whenever this document says `stage-edit edit_video --op ...` or `stage-edit analyze_media --op ...`. Exception: transcription runs through the required built-in `video_studio` tool with `op: "speech.transcribe"`. Compatibility is handled by the marketplace `min_app_version` field before install.```bash"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-edit edit_video -- --op probe --input raw/clip.mp4"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-edit edit_video -- --op trim --input raw/clip.mp4 --start 12 --duration 8 --output project/cuts/seg-1.mp4-"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-edit analyze_media -- --op transcribe --input raw/clip.mp4 --model large-v3"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-edit analyze_media -- --op ocr --input raw/screen-recording.mp4```@@ -56,7 +56,7 @@ The scripts return JSON. A non-zero exit means the operation failed; fix the inp## Transcription-driven selection & localization-When the user wants highlights / clips "about X" or a localized version, transcribe first with `stage-edit analyze_media --op transcribe`, which returns a word-level transcript with timestamps. The default model is English-only; for non-English / Chinese audio pass `large-v3` — but warn the user that `large-v3` downloads ~3GB on its FIRST use (only once, then cached), so the first non-English transcribe can take several minutes before any result:+When the user wants highlights / clips "about X" or a localized version, transcribe first with `video_studio` `op: "speech.transcribe"` and `timestamps: "word"`:- **Highlight / clip selection:** read the transcript, choose the time ranges whose words match the requested topic/moment, and feed those `start`/`duration` into the `edit_decisions` segments. Now the timecodes are evidence-based, not guessed.- **Auto-captions:** turn the transcript into an `.srt`, then `burnsubs` it onto the video.@@ -66,15 +66,17 @@ When the user wants highlights / clips "about X" or a localized version, transcr**HARD RULE — adding narration to ANY existing video. Plan-first, IN ORDER. The plan.json is authored BEFORE any speech is generated and DRIVES the generation; do not synthesize a blob first and describe it after. Skipping a step is the #1 failure (a voiceover "about the right topic" that does not track the screen, crammed into half the runtime):**-1. **Analyze the video FIRST — never narrate from topic knowledge.** Probe duration, then: `stage-edit analyze_media --op ocr` for on-screen text AND `--op transcribe` for any spoken audio. A title-card / slideshow / screen-recording is the on-screen-text case → OCR is **mandatory, not the fallback**. Do NOT jump to reading frames-as-vision while OCR is available, and do NOT describe the product from memory.+1. **Analyze the video FIRST — never narrate from topic knowledge.** Probe duration, then: `stage-edit analyze_media --op ocr` for on-screen text AND `video_studio` `op: "speech.transcribe"` for spoken audio. A title-card / slideshow / screen-recording is the on-screen-text case → OCR is **mandatory, not the fallback**. Do NOT jump to reading frames-as-vision while OCR is available, and do NOT describe the product from memory.2. **Author `project/plan.json` NOW (plan-first, not at the end) as the segments EDL** (copy `stage-plan`'s exact JSON skeleton — `source` is the method enum `edit`, NOT a file path (the clip goes in `spec.input_id`); use `target_sec`; `tracks` is an object), carrying ONLY what the user asked for — keep the picture, add narration — and nothing else:- one **primary `edit` segment** for the source spanning the whole timeline (`source:"edit"`, `layer:"primary"`, `target_sec` = clip length, `spec.input_id`/`in_sec`/`out_sec` covering the clip). Source-led keep — do NOT add crop/scale/reframe; you weren't asked to.- a **`tracks.narration`** track (voice from §2.6) with ONE LINE per on-screen beat: `{ text, start_sec, target_sec }`, the window and text derived from the OCR/transcript table — segmented and time-aligned to the picture BEFORE any TTS. One line per beat; never one paragraph for the whole clip.- `delivery_promise:{ type:"source_led", source_required:true }`; set `aspect` from the SOURCE's real probed dimensions (a landscape source is `16:9`, not the portrait default).Each narration line stays its own entry, so a later edit can re-voice ONE line without touching the rest.3. **Generate each beat FROM the plan, then record its `produced_path`.** `generate_speech` per narration line with `target_duration` = its `target_sec`; save the mp3 and write that line's `produced_path`. If the words don't fit at a natural pace, SHORTEN that line in the plan — never speed up past natural or let it run long/short. Coverage must span ~0→clip-end, not stop at the halfway mark.-4. **Assemble with `stage-edit edit_video` — keep the picture untouched.** Pass the source video through (`-c:v copy`) and place the narration lines at their `start_sec` in ONE `stage-edit edit_video --op mix` call via `--audio-segments` (one entry per line — that is HOW per-line `start_sec` alignment happens), then `--op loudness`; burn captions from `tracks.captions.lines` (.srt → `burnsubs`) if present. The source footage usually already HAS audio, so `mix` rejects by default — choose `--on-existing-audio mix` to keep the original sound under the voiceover, or `replace` to drop it. Write each line's `produced_path` + `status` and the top-level `draft` back to plan.json so the record matches the result. Never pre-bake one big narration file — that destroys per-line separability.-5. **Self-check before presenting:** `project/plan.json` validates (`"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-plan video_plan -- --op validate --plan project/plan.json`); every narration line has a `produced_path` and a window matching its OCR/transcript text; total coverage ≈ full clip length; `project/render/draft.mp4` exists. Then tell the user the draft is ready and they can ask for follow-up tweaks (re-voice a line, fix a caption) and you'll change only that.+ - Save each line under `project/assets/narration/line-XX.mp3` (or another `project/...` path) so the audio stays in the workspace and can be mixed later. Do not leave generated line audio under `cloud/chat_attachments/...`.+ - Do not use repeated TTS calls as a duration search loop. Estimate words/characters from the target window first, generate once, and if the tool reports a poor fit, shorten that line and retry once. Small residual timing differences should be handled in deterministic assembly, not by synthesizing many alternatives.+4. **Assemble with `stage-edit edit_video` — keep the picture untouched.** Pass the source video through (`-c:v copy`) and place the narration lines at their `start_sec` in ONE `stage-edit edit_video --op mix` call via `--audio-segments` (one entry per line — that is HOW per-line `start_sec` alignment happens), then run `--op normalize_loudness` to write the deliverable and return measured loudness in the same step; burn captions from `tracks.captions.lines` (.srt → `burnsubs`) if present. The source footage usually already HAS audio, so `mix` rejects by default — choose `--on-existing-audio mix` to keep the original sound under the voiceover, or `replace` to drop it. Write each line's `produced_path` + `status` and the top-level `draft` / `video` paths back to plan.json so the record matches the result. Never pre-bake one big narration file — that destroys per-line separability.+5. **Self-check before presenting:** `project/plan.json` validates (`"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-plan video_plan -- --op validate --plan project/plan.json`); every narration line has a `produced_path` and a window matching its OCR/transcript text; total coverage ≈ full clip length; `project/render/video.mp4` exists. Then tell the user the draft is ready and they can ask for follow-up tweaks (re-voice a line, fix a caption) and you'll change only that.When the clip has NO spoken audio, or its meaning lives in ON-SCREEN TEXT (a screen-recording, a slideshow, a captioned montage), transcription returns nothing — the content is in the pixels, not the audio. An empty audio track does NOT mean an empty screen. Read what is on screen instead of guessing, in this strict order (cost-first):@@ -102,7 +104,7 @@ Per repurpose/montage line:- **Screen-demo** — zoom only for legibility/orientation, steady while the viewer reads; reset to wide context between phases; ≤ 2 attention cues at once; label sped-up sections; keep UI text sharp (higher bitrate), don't force an unreadable vertical crop.- **Localization** — treat each language as its own deliverable; dubbed audio won't match source timing, so plan holds to flex; re-render or cover any baked-in text per language; subtitle line lengths differ by language; lip-sync only where a close-up mouth mismatch would distract.- **Documentary-montage** — concrete sensory shot descriptions, not abstract themes; one grade/LUT across all clips is what unifies mixed sources; budget 2–3 hero slots longer holds; a music bed + an end-tag.-- Before publishing, check the mix loudness against the targets in video-craft §7 (~−14 LUFS integrated, true-peak ≤ ~−1 dBTP). (Orkas: `stage-edit edit_video --op loudness`.)+- Before publishing, normalize the mix against the targets in video-craft §7 (~−14 LUFS integrated, true-peak ≤ ~−1 dBTP). (Orkas: `stage-edit edit_video --op normalize_loudness`; use `--op loudness` only for diagnosis without writing an output.)## Rulesdiff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/edit_video.js b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/edit_video.jsindex 2705ccf2..2e9b0eb1 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/edit_video.js+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/edit_video.js@@ -3,8 +3,8 @@const fs = require('node:fs');const path = require('node:path');-const OPS = new Set(['probe', 'trim', 'concat', 'burnsubs', 'overlay', 'extract_frame', 'loudness', 'mix', 'trim_silence', 'remove_fillers']);-const OUTPUT_OPS = new Set(['trim', 'concat', 'burnsubs', 'overlay', 'extract_frame', 'mix', 'trim_silence', 'remove_fillers']);+const OPS = new Set(['probe', 'trim', 'concat', 'burnsubs', 'overlay', 'extract_frame', 'loudness', 'normalize_loudness', 'mix', 'trim_silence', 'remove_fillers']);+const OUTPUT_OPS = new Set(['trim', 'concat', 'burnsubs', 'overlay', 'extract_frame', 'normalize_loudness', 'mix', 'trim_silence', 'remove_fillers']);function fail(code, message, extra = {}) {process.stderr.write(JSON.stringify({ ok: false, code, message, ...extra }) + '\n');@@ -241,6 +241,10 @@ module.exports = async function editVideoScript({ args }) {const payload = { ok: true, op: opts.op, ...result };if (opts.op === 'probe') payload.text = 'probe metadata is available in probe.';else if (opts.op === 'loudness') payload.text = 'loudness measurement is available in loudness.';+ else if (opts.op === 'normalize_loudness') {+ if (result.path) payload.media = `chat-media://local/${result.path}`;+ payload.text = `normalize_loudness wrote ${result.path}; measured loudness is available in loudness.`;+ }else if (result.path) {payload.media = `chat-media://local/${result.path}`;payload.text = `${opts.op} wrote ${result.path}${outputRenamed ? ` (renamed from ${requestedOutputAbsPath})` : ''}.`;diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_analyze_core.cjs b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_analyze_core.cjsindex d74c95a8..410ef6db 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_analyze_core.cjs+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_analyze_core.cjs@@ -1,7 +1,8 @@-var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var video_analyze_exports={};__export(video_analyze_exports,{analyzeMedia:()=>analyzeMedia,collapseOcrSegments:()=>collapseOcrSegments,sampleTimecodes:()=>sampleTimecodes});module.exports=__toCommonJS(video_analyze_exports);var fs4=__toESM(require("node:fs/promises"));var os=__toESM(require("node:os"));var path4=__toESM(require("node:path"));var import_node_child_process=require("node:child_process");var fs2=__toESM(require("node:fs"));var path2=__toESM(require("node:path"));var path=__toESM(require("node:path"));var fs=__toESM(require("node:fs"));function scriptPathIsFile(p){try{return fs.statSync(p).isFile()}catch{return false}}function scriptPathIsDir(p){try{return fs.statSync(p).isDirectory()}catch{return false}}function looksLikePcRoot(dir){return scriptPathIsFile(path.join(dir,"package.json"))&&scriptPathIsDir(path.join(dir,"resources"))&&scriptPathIsDir(path.join(dir,"src"))}function resolvePcRoot(){if(process.env.ORKAS_PC_DIR)return path.resolve(process.env.ORKAS_PC_DIR);if(looksLikePcRoot(process.cwd()))return process.cwd();const cwdPc=path.join(process.cwd(),"PC");if(looksLikePcRoot(cwdPc))return cwdPc;let dir=__dirname;for(;;){if(looksLikePcRoot(dir))return dir;const parent=path.dirname(dir);if(parent===dir)break;dir=parent}return path.resolve(__dirname,"..","..")}var PC_ROOT=resolvePcRoot();var SRC_ROOT=path.join(PC_ROOT,"src");var PROJECT_ROOT=path.resolve(PC_ROOT,"..");if(!process.env.ORKAS_WORKSPACE_ROOT){throw new Error("paths.ts: ORKAS_WORKSPACE_ROOT not set. index.ts must run resolveInstallContainer + set the env var before importing paths.")}var WS_ROOT=path.resolve(process.env.ORKAS_WORKSPACE_ROOT);var USERS_FILE=path.join(WS_ROOT,"users.json");var WINDOW_STATE_FILE=path.join(WS_ROOT,"window-state.json");var LOGS_DIR=path.join(WS_ROOT,"logs");var VENV_ROOT=path.join(WS_ROOT,"venv");var PYTHON_VENV_ROOT=path.join(VENV_ROOT,"python");var PYTHON_VENV_BIN_DIR=path.join(PYTHON_VENV_ROOT,"bin");var PYTHON_VENV_CACHE_DIR=path.join(PYTHON_VENV_ROOT,"cache");var PYTHON_VENV_UV_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"uv");var PYTHON_VENV_PIP_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"pip");var pythonPackageVenvDir=key=>path.join(PYTHON_VENV_ROOT,"packages",key,".venv");var NODE_VENV_ROOT=path.join(VENV_ROOT,"node");var NODE_NPM_CACHE_DIR=path.join(NODE_VENV_ROOT,"cache","npm");var NODE_NPM_PREFIX_DIR=path.join(NODE_VENV_ROOT,"prefix");var NODE_NPM_GLOBAL_BIN_DIR=process.platform==="win32"?NODE_NPM_PREFIX_DIR:path.join(NODE_NPM_PREFIX_DIR,"bin");function runtimeResourcesDir(){const rp=process.resourcesPath;if(rp&&!rp.includes(`${path.sep}node_modules${path.sep}electron${path.sep}`)){return path.join(rp,"runtime")}return path.join(PC_ROOT,"resources","runtime")}var DEFAULT_USER_WORKSPACE=path.join(WS_ROOT,"..","userWorkSpace");function ensureTopLevelLayout(){for(const d of[LOGS_DIR,VENV_ROOT,DEFAULT_USER_WORKSPACE]){fs.mkdirSync(d,{recursive:true})}}ensureTopLevelLayout();function isFile(p){if(!p)return false;try{return fs2.statSync(p).isFile()}catch{return false}}function isDir(p){if(!p)return false;try{return fs2.statSync(p).isDirectory()}catch{return false}}function platformKey(platform=process.platform,arch=process.arch){return`${platform}-${arch}`}function pushUnique(out,seen,value){if(!value)return;const resolved=path2.resolve(value);if(seen.has(resolved))return;seen.add(resolved);out.push(resolved)}function runtimeRoots(){const roots=[];const seen=new Set;pushUnique(roots,seen,process.env.ORKAS_RUNTIME_DIR);pushUnique(roots,seen,runtimeResourcesDir());return roots}function runtimeVariantDirs(kind){const dirs=[];for(const runtimeRoot of runtimeRoots()){const root=path2.join(runtimeRoot,kind);dirs.push(path2.join(root,"current"),path2.join(root,platformKey()))}return[...dirs]}function resolvePythonExecutable(){const configured=process.env.ORKAS_BUNDLED_PYTHON||process.env.ORKAS_PYTHON;if(isFile(configured))return configured;const names=process.platform==="win32"?["python.exe",path2.join("python","python.exe")]:[path2.join("python","bin","python3"),path2.join("python","bin","python"),path2.join("bin","python3"),path2.join("bin","python")];for(const dir of runtimeVariantDirs("python")){for(const name of names){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}}return void 0}function resolveUvExecutable(){const configured=process.env.ORKAS_BUNDLED_UV||process.env.ORKAS_UV;if(isFile(configured))return configured;const name=process.platform==="win32"?"uv.exe":"uv";for(const dir of runtimeVariantDirs("uv")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}return void 0}function resolveNodeExecutable(){const configured=process.env.ORKAS_BUNDLED_NODE;if(isFile(configured))return configured;const names=process.platform==="win32"?["node.exe"]:[path2.join("bin","node")];for(const dir of runtimeVariantDirs("node")){for(const name of names){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}}return void 0}function resolveFfmpegBinary(kind){const envName=kind==="ffmpeg"?"ORKAS_BUNDLED_FFMPEG":"ORKAS_BUNDLED_FFPROBE";const configured=process.env[envName];if(isFile(configured))return configured;const name=process.platform==="win32"?`${kind}.exe`:kind;for(const dir of runtimeVariantDirs("ffmpeg")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate;const nested=path2.join(dir,"bin",name);if(isFile(nested))return nested}return void 0}function bundledFfmpegPaths(){const result={};const ffmpeg=resolveFfmpegBinary("ffmpeg");const ffprobe=resolveFfmpegBinary("ffprobe");if(ffmpeg)result.ffmpeg=ffmpeg;if(ffprobe)result.ffprobe=ffprobe;return result}function pushPathDir(out,seen,dir){if(!isDir(dir))return;const resolved=path2.resolve(dir);const key=process.platform==="win32"?resolved.toLowerCase():resolved;if(seen.has(key))return;seen.add(key);out.push(resolved)}function bundledRuntimePathEntries(){const entries=[];const seen=new Set;const python=resolvePythonExecutable();if(python){const pythonDir=path2.dirname(python);pushPathDir(entries,seen,pythonDir);pushPathDir(entries,seen,path2.join(pythonDir,"Scripts"));pushPathDir(entries,seen,path2.join(pythonDir,"bin"))}const uv=resolveUvExecutable();if(uv)pushPathDir(entries,seen,path2.dirname(uv));const node=resolveNodeExecutable();if(node)pushPathDir(entries,seen,path2.dirname(node));return entries}function bundledNodeExecutable(){return resolveNodeExecutable()}function bundledNpxCli(){const node=resolveNodeExecutable();if(!node)return void 0;const dir=path2.dirname(node);const candidates=process.platform==="win32"?[path2.join(dir,"node_modules","npm","bin","npx-cli.js")]:[path2.join(dir,"..","lib","node_modules","npm","bin","npx-cli.js")];for(const c of candidates)if(isFile(c))return c;return void 0}function bundledRuntimeEnv(){const env={};const python=resolvePythonExecutable();const uv=resolveUvExecutable();const node=resolveNodeExecutable();if(python)env.ORKAS_PYTHON=python;if(uv)env.ORKAS_UV=uv;if(node)env.ORKAS_BUNDLED_NODE=node;return env}var HYPERFRAMES_SPEC="[email protected]";function resolveHyperframesRunner(){const node=bundledNodeExecutable();const npxCli=bundledNpxCli();if(!node||!npxCli)return null;return{node,npxCli}}function buildHyperframesEnv(){const env={...process.env};const sep2=process.platform==="win32"?";":":";const prepend=[...bundledRuntimePathEntries()];prepend.push(PYTHON_VENV_BIN_DIR);if(prepend.length)env.PATH=[...prepend,env.PATH||""].filter(Boolean).join(sep2);const ff=bundledFfmpegPaths();if(ff.ffmpeg)env.HYPERFRAMES_FFMPEG_PATH=ff.ffmpeg;if(ff.ffprobe)env.HYPERFRAMES_FFPROBE_PATH=ff.ffprobe;env.NPM_CONFIG_CACHE=NODE_NPM_CACHE_DIR;env.NPM_CONFIG_PREFIX=NODE_NPM_PREFIX_DIR;env.NPM_CONFIG_FUND="false";env.NPM_CONFIG_AUDIT="false";env.NPM_CONFIG_UPDATE_NOTIFIER="false";env.NPM_CONFIG_PREFER_OFFLINE="true";env.NPM_CONFIG_FETCH_RETRIES="4";return env}function runHyperframesCapture(args,opts){const runner=resolveHyperframesRunner();if(!runner){return Promise.resolve({code:-1,stdout:"",stderr:"E_RUNTIME_MISSING: bundled Node not found",timedOut:false,aborted:false})}const env=buildHyperframesEnv();const fullArgs=[runner.npxCli,"--yes",HYPERFRAMES_SPEC,...args];const timeoutMs=opts.timeoutMs??10*60*1e3;return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process.spawn)(runner.node,fullArgs,{...opts.cwd?{cwd:opts.cwd}:{},env,...opts.signal?{signal:opts.signal}:{}})}catch(err){resolve3({code:-1,stdout:"",stderr:err.message,timedOut:false,aborted:false});return}const out=[];const errChunks=[];let timedOut=false;const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},timeoutMs);child.stdout?.on("data",c=>out.push(c.toString("utf8")));child.stderr?.on("data",c=>errChunks.push(c.toString("utf8")));child.stdin?.end();child.on("error",err=>{clearTimeout(timer);resolve3({code:-1,stdout:out.join(""),stderr:err.message,timedOut,aborted:!!opts.signal?.aborted})});child.on("close",code=>{clearTimeout(timer);resolve3({code,stdout:out.join(""),stderr:errChunks.join(""),timedOut,aborted:!!opts.signal?.aborted})})})}var import_node_child_process2=require("node:child_process");function redactPaths(text){if(!text)return text;return text.replace(/[A-Za-z]:[\\/][^\s"']*/g,"<path>").replace(/(?:\/[\w.\-]+){2,}\/?/g,"<path>")}function createLogger(moduleName){const scope=String(moduleName||"video-script").trim()||"video-script";const write=(level,message,args)=>{if(process.env.ORKAS_VIDEO_SCRIPT_DEBUG!=="1")return;const line=`[${scope}] ${message}`;if(level==="error")console.error(line,...args);else if(level==="warn")console.warn(line,...args);else if(level==="debug")console.debug(line,...args);else console.info(line,...args)};return{error:(message,...args)=>write("error",message,args),warn:(message,...args)=>write("warn",message,args),info:(message,...args)=>write("info",message,args),debug:(message,...args)=>write("debug",message,args)}}var isNum=v=>typeof v==="number"&&Number.isFinite(v);var round3=n=>Math.round((isNum(n)?n:0)*1e3)/1e3;function parseSceneChanges(log4){const out=[];let pts=null;for(const line of log4.split("\n")){const tp=line.match(/pts_time:\s*([\d.]+)/);if(tp){pts=Number(tp[1]);continue}const sc=line.match(/scene_score\s*[:=]\s*([\d.]+)/);if(sc&&pts!==null){const score=Number(sc[1]);out.push({tSec:round3(pts),score:Number.isFinite(score)?round3(score):0});pts=null}}return out}function spanSeconds(spans){return spans.reduce((s,iv)=>s+Math.max(0,iv.endSec-iv.startSec),0)}function parseQualityFrames(log4){const frames=[];let cur=null;for(const line of log4.split("\n")){const tp=line.match(/pts_time:\s*([\d.]+)/);if(tp){if(cur)frames.push(cur);cur={tSec:round3(Number(tp[1]))};continue}if(!cur)continue;const b=line.match(/lavfi\.blur=\s*([\d.]+)/);if(b){cur.blur=round3(Number(b[1]));continue}const y=line.match(/lavfi\.signalstats\.YAVG=\s*([\d.]+)/);if(y){cur.brightness=round3(Number(y[1]));continue}}if(cur)frames.push(cur);return frames}function parseLabeledIntervals(log4,label){const spans=[];const re=new RegExp(`${label}_(start|end)[:=]\\s*(-?[\\d.]+)`,"g");let openStart=null;let m;while((m=re.exec(log4))!==null){const v=Number(m[2]);if(!Number.isFinite(v))continue;if(m[1]==="start")openStart=v;else if(openStart!==null){spans.push({startSec:round3(Math.max(0,openStart)),endSec:round3(v)});openStart=null}}return spans}function stats(nums){if(!nums.length)return null;const sum=nums.reduce((a,b)=>a+b,0);return{mean:round3(sum/nums.length),min:round3(Math.min(...nums)),max:round3(Math.max(...nums))}}function summarizeQuality(input){const blurT=isNum(input.thresholds?.blur)?input.thresholds.blur:15;const darkBelow=isNum(input.thresholds?.darkBelow)?input.thresholds.darkBelow:50;const brightAbove=isNum(input.thresholds?.brightAbove)?input.thresholds.brightAbove:200;const blur=stats(input.frames.map(f=>f.blur).filter(v=>isNum(v)));const brightness=stats(input.frames.map(f=>f.brightness).filter(v=>isNum(v)));const blackSpans=input.blackSpans??[];const freezeSpans=input.freezeSpans??[];const black_sec=round3(spanSeconds(blackSpans));const freeze_sec=round3(spanSeconds(freezeSpans));const dur=isNum(input.durationSec)&&input.durationSec>0?input.durationSec:0;const flags=[];if(blur&&blur.mean>blurT)flags.push("blurry");if(brightness&&brightness.mean<darkBelow)flags.push("too_dark");if(brightness&&brightness.mean>brightAbove)flags.push("too_bright");if(black_sec>0)flags.push("has_black");if(freeze_sec>0)flags.push("has_freeze");let score=1;if(flags.includes("blurry"))score-=.3;if(flags.includes("too_dark")||flags.includes("too_bright"))score-=.3;if(dur>0){score-=Math.min(.4,black_sec/dur);score-=Math.min(.3,freeze_sec/dur)}score=Math.max(0,Math.min(1,round3(score)));const roundSpans=ss=>ss.map(s=>({startSec:round3(s.startSec),endSec:round3(s.endSec)}));return{durationSec:round3(dur),frames_analyzed:input.frames.length,blur,brightness,black_sec,freeze_sec,black_spans:roundSpans(blackSpans),freeze_spans:roundSpans(freezeSpans),flags,score}}function finiteNum(v){return typeof v==="number"&&Number.isFinite(v)?v:void 0}var log=createLogger("video-edit");var FFMPEG_TIMEOUT_MS=20*60*1e3;var SILENCE_NOISE_DB=-40;var SILENCE_MIN_SEC=.5;var COVERAGE_TRAILING_GAP_SEC=2;var COVERAGE_OVERSHOOT_SEC=.3;var COVERAGE_LEAD_GAP_SEC=3;var RUN_PROGRESS_HEARTBEAT_MS=15e3;var RUN_PROGRESS_MIN_EMIT_MS=2e3;function round2(n){return Math.round((Number.isFinite(n)?n:0)*100)/100}function clamp(n,lo,hi){return Math.min(hi,Math.max(lo,n))}function parseSilenceDetect(stderr,durationSec){const EPS_LEAD=.05;const EPS_TAIL=.3;const tokens=[];const re=/silence_(start|end):\s*(-?[\d.]+)/g;let m;while((m=re.exec(stderr))!==null){const t=Number(m[2]);if(Number.isFinite(t))tokens.push({kind:m[1],t})}const silences=[];let openStart=null;for(const tk of tokens){if(tk.kind==="start"){openStart=tk.t}else if(openStart!==null){silences.push({startSec:Math.max(0,openStart),endSec:tk.t});openStart=null}}const dur=Number.isFinite(durationSec)&&durationSec>0?durationSec:silences.length?silences[silences.length-1].endSec:0;if(openStart!==null)silences.push({startSec:Math.max(0,openStart),endSec:dur});const first=silences[0];const last=silences.length?silences[silences.length-1]:void 0;const leadingSilenceSec=first&&first.startSec<=EPS_LEAD?Math.min(first.endSec,dur):0;const trailingSilenceSec=last&&last.endSec>=dur-EPS_TAIL?Math.max(0,dur-last.startSec):0;const totalSilence=silences.reduce((s,iv)=>s+Math.max(0,Math.min(iv.endSec,dur)-iv.startSec),0);const voicedDurationSec=Math.max(0,dur-totalSilence);const voicedStartSec=leadingSilenceSec;const voicedEndSec=Math.max(voicedStartSec,dur-trailingSilenceSec);return{durationSec:dur,voicedStartSec,voicedEndSec,voicedDurationSec,leadingSilenceSec,trailingSilenceSec,silences}}function assessVoiceoverCoverage(input){const ref=Math.max(0,input.referenceDurationSec);const offset=Math.max(0,input.offsetSec??0);const voicedStart=offset+Math.max(0,input.voicedStartSec);const voicedEnd=offset+Math.max(0,input.voicedEndSec);const hasVoice=input.voicedEndSec-input.voicedStartSec>.05&&input.audioDurationSec>.05;const leadingGapSec=round2(voicedStart);const trailingGapSec=round2(ref-voicedEnd);const overshootSec=round2(offset+input.audioDurationSec-ref);const coverageRatio=ref>0?round2(clamp(voicedEnd/ref,0,1)):0;const warnings=[];let status="ok";if(!hasVoice){status="silent";warnings.push("No speech detected in the added audio \u2014 the mux produced a silent or near-silent track.")}else{if(overshootSec>COVERAGE_OVERSHOOT_SEC){status="over";warnings.push(`Narration runs ${overshootSec}s past the ${round2(ref)}s clip and was truncated to fit \u2014 shorten the script so it ends before the clip does (trim the words; do not just raise speed).`)}if(trailingGapSec>COVERAGE_TRAILING_GAP_SEC){if(status==="ok")status="under";const pct=ref>0?Math.round(trailingGapSec/ref*100):0;warnings.push(`Narration ends at ${round2(voicedEnd)}s, leaving ${trailingGapSec}s of silent tail on a ${round2(ref)}s clip (~${pct}% uncovered) \u2014 lengthen the script, add a closing line, or trim the clip to match.`)}if(leadingGapSec>COVERAGE_LEAD_GAP_SEC){warnings.push(`Narration only starts at ${leadingGapSec}s \u2014 long silent lead-in; reduce the offset or trim the head.`)}}return{referenceDurationSec:round2(ref),voicedStartSec:round2(voicedStart),voicedEndSec:round2(voicedEnd),leadingGapSec,trailingGapSec,overshootSec,coverageRatio,status,warnings}}function resolveBins(){const b=bundledFfmpegPaths();if(!b.ffmpeg||!b.ffprobe)return null;return{ffmpeg:b.ffmpeg,ffprobe:b.ffprobe}}function parseProgressClock(raw){if(!raw)return null;const m=raw.trim().match(/^(\d+):(\d{2}):(\d{2}(?:\.\d+)?)$/);if(!m)return null;const h=Number(m[1]);const min=Number(m[2]);const sec=Number(m[3]);if(![h,min,sec].every(Number.isFinite))return null;return h*3600+min*60+sec}function parseFfmpegProgressTimeSec(fields){for(const key of["out_time_us","out_time_ms"]){const raw=fields[key];if(!raw)continue;const micros=Number(raw);if(Number.isFinite(micros)&µs>=0)return micros/1e6}return parseProgressClock(fields.out_time)}function emitRunProgress(progress,event){const payload={type:"progress",source:"video_edit",op:progress.op,phase:progress.phase??"edit",...event};try{process.stderr.write(`${JSON.stringify(payload)}+var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var video_analyze_exports={};__export(video_analyze_exports,{analyzeMedia:()=>analyzeMedia,collapseOcrSegments:()=>collapseOcrSegments,sampleTimecodes:()=>sampleTimecodes});module.exports=__toCommonJS(video_analyze_exports);var fs5=__toESM(require("node:fs/promises"));var os=__toESM(require("node:os"));var path4=__toESM(require("node:path"));var import_node_child_process=require("node:child_process");var fs3=__toESM(require("node:fs"));var fs2=__toESM(require("node:fs"));var path2=__toESM(require("node:path"));var path=__toESM(require("node:path"));var fs=__toESM(require("node:fs"));function scriptPathIsFile(p){try{return fs.statSync(p).isFile()}catch{return false}}function scriptPathIsDir(p){try{return fs.statSync(p).isDirectory()}catch{return false}}function looksLikePcRoot(dir){return scriptPathIsFile(path.join(dir,"package.json"))&&scriptPathIsDir(path.join(dir,"resources"))&&scriptPathIsDir(path.join(dir,"src"))}function resolvePcRoot(){if(process.env.ORKAS_PC_DIR)return path.resolve(process.env.ORKAS_PC_DIR);if(looksLikePcRoot(process.cwd()))return process.cwd();const cwdPc=path.join(process.cwd(),"PC");if(looksLikePcRoot(cwdPc))return cwdPc;let dir=__dirname;for(;;){if(looksLikePcRoot(dir))return dir;const parent=path.dirname(dir);if(parent===dir)break;dir=parent}return path.resolve(__dirname,"..","..")}var PC_ROOT=resolvePcRoot();var SRC_ROOT=path.join(PC_ROOT,"src");var PROJECT_ROOT=path.resolve(PC_ROOT,"..");if(!process.env.ORKAS_WORKSPACE_ROOT){throw new Error("paths.ts: ORKAS_WORKSPACE_ROOT not set. index.ts must run resolveInstallContainer + set the env var before importing paths.")}var WS_ROOT=path.resolve(process.env.ORKAS_WORKSPACE_ROOT);var USERS_FILE=path.join(WS_ROOT,"users.json");var WINDOW_STATE_FILE=path.join(WS_ROOT,"window-state.json");var LOGS_DIR=path.join(WS_ROOT,"logs");var VENV_ROOT=path.join(WS_ROOT,"venv");var PYTHON_VENV_ROOT=path.join(VENV_ROOT,"python");var PYTHON_VENV_BIN_DIR=path.join(PYTHON_VENV_ROOT,"bin");var PYTHON_VENV_CACHE_DIR=path.join(PYTHON_VENV_ROOT,"cache");var PYTHON_VENV_UV_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"uv");var PYTHON_VENV_PIP_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"pip");var pythonPackageVenvDir=key=>path.join(PYTHON_VENV_ROOT,"packages",key,".venv");var NODE_VENV_ROOT=path.join(VENV_ROOT,"node");var NODE_NPM_CACHE_DIR=path.join(NODE_VENV_ROOT,"cache","npm");var NODE_NPM_PREFIX_DIR=path.join(NODE_VENV_ROOT,"prefix");var NODE_NPM_GLOBAL_BIN_DIR=process.platform==="win32"?NODE_NPM_PREFIX_DIR:path.join(NODE_NPM_PREFIX_DIR,"bin");function runtimeResourcesDir(){const rp=process.resourcesPath;if(rp&&!rp.includes(`${path.sep}node_modules${path.sep}electron${path.sep}`)){return path.join(rp,"runtime")}return path.join(PC_ROOT,"resources","runtime")}var DEFAULT_USER_WORKSPACE=path.join(WS_ROOT,"..","userWorkSpace");function ensureTopLevelLayout(){for(const d of[LOGS_DIR,VENV_ROOT,DEFAULT_USER_WORKSPACE]){fs.mkdirSync(d,{recursive:true})}}ensureTopLevelLayout();function isFile(p){if(!p)return false;try{return fs2.statSync(p).isFile()}catch{return false}}function isDir(p){if(!p)return false;try{return fs2.statSync(p).isDirectory()}catch{return false}}function platformKey(platform=process.platform,arch=process.arch){return`${platform}-${arch}`}function pushUnique(out,seen,value){if(!value)return;const resolved=path2.resolve(value);if(seen.has(resolved))return;seen.add(resolved);out.push(resolved)}function runtimeRoots(){const roots=[];const seen=new Set;pushUnique(roots,seen,process.env.ORKAS_RUNTIME_DIR);pushUnique(roots,seen,runtimeResourcesDir());return roots}function runtimeVariantDirs(kind){const dirs=[];for(const runtimeRoot of runtimeRoots()){const root=path2.join(runtimeRoot,kind);dirs.push(path2.join(root,"current"),path2.join(root,platformKey()))}return[...dirs]}function resolvePythonExecutable(){const configured=process.env.ORKAS_BUNDLED_PYTHON||process.env.ORKAS_PYTHON;if(isFile(configured))return configured;const names=process.platform==="win32"?["python.exe",path2.join("python","python.exe")]:[path2.join("python","bin","python3"),path2.join("python","bin","python"),path2.join("bin","python3"),path2.join("bin","python")];for(const dir of runtimeVariantDirs("python")){for(const name of names){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}}return void 0}function resolveUvExecutable(){const configured=process.env.ORKAS_BUNDLED_UV||process.env.ORKAS_UV;if(isFile(configured))return configured;const name=process.platform==="win32"?"uv.exe":"uv";for(const dir of runtimeVariantDirs("uv")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}return void 0}function resolveNodeExecutable(){const configured=process.env.ORKAS_BUNDLED_NODE;if(isFile(configured))return configured;const names=process.platform==="win32"?["node.exe"]:[path2.join("bin","node")];for(const dir of runtimeVariantDirs("node")){for(const name of names){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate}}return void 0}function resolveFfmpegBinary(kind){const envName=kind==="ffmpeg"?"ORKAS_BUNDLED_FFMPEG":"ORKAS_BUNDLED_FFPROBE";const configured=process.env[envName];if(isFile(configured))return configured;const name=process.platform==="win32"?`${kind}.exe`:kind;for(const dir of runtimeVariantDirs("ffmpeg")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate;const nested=path2.join(dir,"bin",name);if(isFile(nested))return nested}return void 0}function bundledFfmpegPaths(){const result={};const ffmpeg=resolveFfmpegBinary("ffmpeg");const ffprobe=resolveFfmpegBinary("ffprobe");if(ffmpeg)result.ffmpeg=ffmpeg;if(ffprobe)result.ffprobe=ffprobe;return result}function pushPathDir(out,seen,dir){if(!isDir(dir))return;const resolved=path2.resolve(dir);const key=process.platform==="win32"?resolved.toLowerCase():resolved;if(seen.has(key))return;seen.add(key);out.push(resolved)}function bundledRuntimePathEntries(){const entries=[];const seen=new Set;const python=resolvePythonExecutable();if(python){const pythonDir=path2.dirname(python);pushPathDir(entries,seen,pythonDir);pushPathDir(entries,seen,path2.join(pythonDir,"Scripts"));pushPathDir(entries,seen,path2.join(pythonDir,"bin"))}const uv=resolveUvExecutable();if(uv)pushPathDir(entries,seen,path2.dirname(uv));const node=resolveNodeExecutable();if(node)pushPathDir(entries,seen,path2.dirname(node));return entries}function bundledNodeExecutable(){return resolveNodeExecutable()}function bundledNpxCli(){const node=resolveNodeExecutable();if(!node)return void 0;const dir=path2.dirname(node);const candidates=process.platform==="win32"?[path2.join(dir,"node_modules","npm","bin","npx-cli.js")]:[path2.join(dir,"..","lib","node_modules","npm","bin","npx-cli.js")];for(const c of candidates)if(isFile(c))return c;return void 0}function bundledRuntimeEnv(){const env={};const python=resolvePythonExecutable();const uv=resolveUvExecutable();const node=resolveNodeExecutable();if(python)env.ORKAS_PYTHON=python;if(uv)env.ORKAS_UV=uv;if(node)env.ORKAS_BUNDLED_NODE=node;return env}var HYPERFRAMES_SPEC="[email protected]";function resolveHyperframesRunner(){const node=bundledNodeExecutable();const npxCli=bundledNpxCli();if(!node||!npxCli)return null;return{node,npxCli}}function buildHyperframesEnv(){const env={...process.env};const sep2=process.platform==="win32"?";":":";const prepend=[...bundledRuntimePathEntries()];prepend.push(PYTHON_VENV_BIN_DIR);if(prepend.length)env.PATH=[...prepend,env.PATH||""].filter(Boolean).join(sep2);const ff=bundledFfmpegPaths();if(ff.ffmpeg)env.HYPERFRAMES_FFMPEG_PATH=ff.ffmpeg;if(ff.ffprobe)env.HYPERFRAMES_FFPROBE_PATH=ff.ffprobe;for(const dir of[NODE_NPM_CACHE_DIR,NODE_NPM_PREFIX_DIR,NODE_NPM_GLOBAL_BIN_DIR]){try{fs3.mkdirSync(dir,{recursive:true})}catch{}}env.NPM_CONFIG_CACHE=NODE_NPM_CACHE_DIR;env.NPM_CONFIG_PREFIX=NODE_NPM_PREFIX_DIR;env.NPM_CONFIG_FUND="false";env.NPM_CONFIG_AUDIT="false";env.NPM_CONFIG_UPDATE_NOTIFIER="false";env.NPM_CONFIG_PREFER_OFFLINE="true";env.NPM_CONFIG_FETCH_RETRIES="4";return env}var CAPTURE_HEARTBEAT_MS=15e3;function runHyperframesCapture(args,opts){const runner=resolveHyperframesRunner();if(!runner){return Promise.resolve({code:-1,stdout:"",stderr:"E_RUNTIME_MISSING: bundled Node not found",timedOut:false,aborted:false})}const env=buildHyperframesEnv();const fullArgs=[runner.npxCli,"--yes",HYPERFRAMES_SPEC,...args];const timeoutMs=opts.timeoutMs??10*60*1e3;return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process.spawn)(runner.node,fullArgs,{...opts.cwd?{cwd:opts.cwd}:{},env,...opts.signal?{signal:opts.signal}:{}})}catch(err){resolve3({code:-1,stdout:"",stderr:err.message,timedOut:false,aborted:false});return}const out=[];const errChunks=[];let timedOut=false;const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},timeoutMs);const startedAtMs=Date.now();const heartbeat=opts.onHeartbeat?setInterval(()=>opts.onHeartbeat?.(Math.round((Date.now()-startedAtMs)/1e3)),CAPTURE_HEARTBEAT_MS):null;heartbeat?.unref?.();const lineBufs={stdout:"",stderr:""};const pumpLines=(stream,chunk)=>{if(!opts.onLine)return;lineBufs[stream]+=chunk;let nl;while((nl=lineBufs[stream].indexOf("\n"))!==-1){const line=lineBufs[stream].slice(0,nl);lineBufs[stream]=lineBufs[stream].slice(nl+1);try{opts.onLine(line,stream)}catch{}}if(lineBufs[stream].length>64*1024)lineBufs[stream]=lineBufs[stream].slice(-8*1024)};child.stdout?.on("data",c=>{const s=c.toString("utf8");out.push(s);pumpLines("stdout",s)});child.stderr?.on("data",c=>{const s=c.toString("utf8");errChunks.push(s);pumpLines("stderr",s)});child.stdin?.end();child.on("error",err=>{clearTimeout(timer);if(heartbeat)clearInterval(heartbeat);resolve3({code:-1,stdout:out.join(""),stderr:err.message,timedOut,aborted:!!opts.signal?.aborted})});child.on("close",code=>{clearTimeout(timer);if(heartbeat)clearInterval(heartbeat);resolve3({code,stdout:out.join(""),stderr:errChunks.join(""),timedOut,aborted:!!opts.signal?.aborted})})})}var import_node_child_process2=require("node:child_process");function redactPaths(text){if(!text)return text;return text.replace(/[A-Za-z]:[\\/][^\s"']*/g,"<path>").replace(/(?:\/[\w.\-]+){2,}\/?/g,"<path>")}function createLogger(moduleName){const scope=String(moduleName||"video-script").trim()||"video-script";const write=(level,message,args)=>{if(process.env.ORKAS_VIDEO_SCRIPT_DEBUG!=="1")return;const line=`[${scope}] ${message}`;if(level==="error")console.error(line,...args);else if(level==="warn")console.warn(line,...args);else if(level==="debug")console.debug(line,...args);else console.info(line,...args)};return{error:(message,...args)=>write("error",message,args),warn:(message,...args)=>write("warn",message,args),info:(message,...args)=>write("info",message,args),debug:(message,...args)=>write("debug",message,args)}}var isNum=v=>typeof v==="number"&&Number.isFinite(v);var round3=n=>Math.round((isNum(n)?n:0)*1e3)/1e3;function parseSceneChanges(log4){const out=[];let pts=null;for(const line of log4.split("\n")){const tp=line.match(/pts_time:\s*([\d.]+)/);if(tp){pts=Number(tp[1]);continue}const sc=line.match(/scene_score\s*[:=]\s*([\d.]+)/);if(sc&&pts!==null){const score=Number(sc[1]);out.push({tSec:round3(pts),score:Number.isFinite(score)?round3(score):0});pts=null}}return out}function spanSeconds(spans){return spans.reduce((s,iv)=>s+Math.max(0,iv.endSec-iv.startSec),0)}function parseQualityFrames(log4){const frames=[];let cur=null;for(const line of log4.split("\n")){const tp=line.match(/pts_time:\s*([\d.]+)/);if(tp){if(cur)frames.push(cur);cur={tSec:round3(Number(tp[1]))};continue}if(!cur)continue;const b=line.match(/lavfi\.blur=\s*([\d.]+)/);if(b){cur.blur=round3(Number(b[1]));continue}const y=line.match(/lavfi\.signalstats\.YAVG=\s*([\d.]+)/);if(y){cur.brightness=round3(Number(y[1]));continue}}if(cur)frames.push(cur);return frames}function parseLabeledIntervals(log4,label){const spans=[];const re=new RegExp(`${label}_(start|end)[:=]\\s*(-?[\\d.]+)`,"g");let openStart=null;let m;while((m=re.exec(log4))!==null){const v=Number(m[2]);if(!Number.isFinite(v))continue;if(m[1]==="start")openStart=v;else if(openStart!==null){spans.push({startSec:round3(Math.max(0,openStart)),endSec:round3(v)});openStart=null}}return spans}function stats(nums){if(!nums.length)return null;const sum=nums.reduce((a,b)=>a+b,0);return{mean:round3(sum/nums.length),min:round3(Math.min(...nums)),max:round3(Math.max(...nums))}}function summarizeQuality(input){const blurT=isNum(input.thresholds?.blur)?input.thresholds.blur:15;const darkBelow=isNum(input.thresholds?.darkBelow)?input.thresholds.darkBelow:50;const brightAbove=isNum(input.thresholds?.brightAbove)?input.thresholds.brightAbove:200;const blur=stats(input.frames.map(f=>f.blur).filter(v=>isNum(v)));const brightness=stats(input.frames.map(f=>f.brightness).filter(v=>isNum(v)));const blackSpans=input.blackSpans??[];const freezeSpans=input.freezeSpans??[];const black_sec=round3(spanSeconds(blackSpans));const freeze_sec=round3(spanSeconds(freezeSpans));const dur=isNum(input.durationSec)&&input.durationSec>0?input.durationSec:0;const flags=[];if(blur&&blur.mean>blurT)flags.push("blurry");if(brightness&&brightness.mean<darkBelow)flags.push("too_dark");if(brightness&&brightness.mean>brightAbove)flags.push("too_bright");if(black_sec>0)flags.push("has_black");if(freeze_sec>0)flags.push("has_freeze");let score=1;if(flags.includes("blurry"))score-=.3;if(flags.includes("too_dark")||flags.includes("too_bright"))score-=.3;if(dur>0){score-=Math.min(.4,black_sec/dur);score-=Math.min(.3,freeze_sec/dur)}score=Math.max(0,Math.min(1,round3(score)));const roundSpans=ss=>ss.map(s=>({startSec:round3(s.startSec),endSec:round3(s.endSec)}));return{durationSec:round3(dur),frames_analyzed:input.frames.length,blur,brightness,black_sec,freeze_sec,black_spans:roundSpans(blackSpans),freeze_spans:roundSpans(freezeSpans),flags,score}}function finiteNum(v){return typeof v==="number"&&Number.isFinite(v)?v:void 0}var log=createLogger("video-edit");var FFMPEG_TIMEOUT_MS=20*60*1e3;var SILENCE_NOISE_DB=-40;var SILENCE_MIN_SEC=.5;var COVERAGE_TRAILING_GAP_SEC=2;var COVERAGE_OVERSHOOT_SEC=.3;var COVERAGE_LEAD_GAP_SEC=3;var RUN_PROGRESS_HEARTBEAT_MS=15e3;var RUN_PROGRESS_MIN_EMIT_MS=2e3;function round2(n){return Math.round((Number.isFinite(n)?n:0)*100)/100}function clamp(n,lo,hi){return Math.min(hi,Math.max(lo,n))}function parseSilenceDetect(stderr,durationSec){const EPS_LEAD=.05;const EPS_TAIL=.3;const tokens=[];const re=/silence_(start|end):\s*(-?[\d.]+)/g;let m;while((m=re.exec(stderr))!==null){const t=Number(m[2]);if(Number.isFinite(t))tokens.push({kind:m[1],t})}const silences=[];let openStart=null;for(const tk of tokens){if(tk.kind==="start"){openStart=tk.t}else if(openStart!==null){silences.push({startSec:Math.max(0,openStart),endSec:tk.t});openStart=null}}const dur=Number.isFinite(durationSec)&&durationSec>0?durationSec:silences.length?silences[silences.length-1].endSec:0;if(openStart!==null)silences.push({startSec:Math.max(0,openStart),endSec:dur});const first=silences[0];const last=silences.length?silences[silences.length-1]:void 0;const leadingSilenceSec=first&&first.startSec<=EPS_LEAD?Math.min(first.endSec,dur):0;const trailingSilenceSec=last&&last.endSec>=dur-EPS_TAIL?Math.max(0,dur-last.startSec):0;const totalSilence=silences.reduce((s,iv)=>s+Math.max(0,Math.min(iv.endSec,dur)-iv.startSec),0);const voicedDurationSec=Math.max(0,dur-totalSilence);const voicedStartSec=leadingSilenceSec;const voicedEndSec=Math.max(voicedStartSec,dur-trailingSilenceSec);return{durationSec:dur,voicedStartSec,voicedEndSec,voicedDurationSec,leadingSilenceSec,trailingSilenceSec,silences}}function assessVoiceoverCoverage(input){const ref=Math.max(0,input.referenceDurationSec);const offset=Math.max(0,input.offsetSec??0);const voicedStart=offset+Math.max(0,input.voicedStartSec);const voicedEnd=offset+Math.max(0,input.voicedEndSec);const hasVoice=input.voicedEndSec-input.voicedStartSec>.05&&input.audioDurationSec>.05;const leadingGapSec=round2(voicedStart);const trailingGapSec=round2(ref-voicedEnd);const overshootSec=round2(offset+input.audioDurationSec-ref);const coverageRatio=ref>0?round2(clamp(voicedEnd/ref,0,1)):0;const warnings=[];let status="ok";if(!hasVoice){status="silent";warnings.push("No speech detected in the added audio \u2014 the mux produced a silent or near-silent track.")}else{if(overshootSec>COVERAGE_OVERSHOOT_SEC){status="over";warnings.push(`Narration runs ${overshootSec}s past the ${round2(ref)}s clip and was truncated to fit \u2014 shorten the script so it ends before the clip does (trim the words; do not just raise speed).`)}if(trailingGapSec>COVERAGE_TRAILING_GAP_SEC){if(status==="ok")status="under";const pct=ref>0?Math.round(trailingGapSec/ref*100):0;warnings.push(`Narration ends at ${round2(voicedEnd)}s, leaving ${trailingGapSec}s of silent tail on a ${round2(ref)}s clip (~${pct}% uncovered) \u2014 lengthen the script, add a closing line, or trim the clip to match.`)}if(leadingGapSec>COVERAGE_LEAD_GAP_SEC){warnings.push(`Narration only starts at ${leadingGapSec}s \u2014 long silent lead-in; reduce the offset or trim the head.`)}}return{referenceDurationSec:round2(ref),voicedStartSec:round2(voicedStart),voicedEndSec:round2(voicedEnd),leadingGapSec,trailingGapSec,overshootSec,coverageRatio,status,warnings}}function resolveBins(){const b=bundledFfmpegPaths();if(!b.ffmpeg||!b.ffprobe)return null;return{ffmpeg:b.ffmpeg,ffprobe:b.ffprobe}}function parseProgressClock(raw){if(!raw)return null;const m=raw.trim().match(/^(\d+):(\d{2}):(\d{2}(?:\.\d+)?)$/);if(!m)return null;const h=Number(m[1]);const min=Number(m[2]);const sec=Number(m[3]);if(![h,min,sec].every(Number.isFinite))return null;return h*3600+min*60+sec}function parseFfmpegProgressTimeSec(fields){for(const key of["out_time_us","out_time_ms"]){const raw=fields[key];if(!raw)continue;const micros=Number(raw);if(Number.isFinite(micros)&µs>=0)return micros/1e6}return parseProgressClock(fields.out_time)}function emitRunProgress(progress,event){const payload={type:"progress",source:"video_edit",op:progress.op,phase:progress.phase??"edit",...event};try{process.stderr.write(`${JSON.stringify(payload)}`)}catch{}}function withFfmpegProgress(args){return args.includes("-progress")?args:["-progress","pipe:2",...args]}function run(bin,args,signal,progress){return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process2.spawn)(bin,args,{...signal?{signal}:{}})}catch(err){resolve3({code:-1,stdout:"",stderr:err.message,timedOut:false,aborted:false});return}const out=[];const errChunks=[];let timedOut=false;const startedAtMs=Date.now();let lastProgressEmitMs=0;let progressFields={};let progressLineBuffer="";const heartbeat=progress?setInterval(()=>{emitRunProgress(progress,{status:"heartbeat",elapsed_sec:round2((Date.now()-startedAtMs)/1e3)})},progress.heartbeatMs??RUN_PROGRESS_HEARTBEAT_MS):null;heartbeat?.unref?.();const emitFfmpegProgress=(status,force=false)=>{if(!progress)return;const now=Date.now();if(!force&&now-lastProgressEmitMs<RUN_PROGRESS_MIN_EMIT_MS)return;lastProgressEmitMs=now;const processedSec=parseFfmpegProgressTimeSec(progressFields);const configuredDurationSec=progress.durationSec;const durationSec=typeof configuredDurationSec==="number"&&Number.isFinite(configuredDurationSec)&&configuredDurationSec>0?configuredDurationSec:null;emitRunProgress(progress,{status:status==="end"?"completed":"running",elapsed_sec:round2((now-startedAtMs)/1e3),...processedSec!==null?{processed_sec:round2(processedSec)}:{},...processedSec!==null&&durationSec?{percent:round2(clamp(processedSec/durationSec*100,0,100))}:{}})};const ingestProgressChunk=text=>{if(!progress)return;progressLineBuffer+=text.replace(/\r/g,"\n");const lines=progressLineBuffer.split("\n");progressLineBuffer=lines.pop()??"";for(const line of lines){const m=line.trim().match(/^([A-Za-z0-9_]+)=(.*)$/);if(!m)continue;progressFields[m[1]]=m[2];if(m[1]==="progress"){emitFfmpegProgress(m[2],m[2]==="end");if(m[2]==="end")progressFields={}}}};const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},FFMPEG_TIMEOUT_MS);let settled=false;const finish=result=>{if(settled)return;settled=true;clearTimeout(timer);if(heartbeat)clearInterval(heartbeat);if(progress&&result.code!==0){emitRunProgress(progress,{status:result.aborted?"aborted":result.timedOut?"timed_out":"failed",elapsed_sec:round2((Date.now()-startedAtMs)/1e3),code:result.code})}resolve3(result)};child.stdout?.on("data",c=>out.push(c.toString("utf8")));child.stderr?.on("data",c=>{const text=c.toString("utf8");errChunks.push(text);ingestProgressChunk(text)});child.stdin?.end();child.on("error",err=>{finish({code:-1,stdout:out.join(""),stderr:err.message,timedOut,aborted:!!signal?.aborted})});child.on("close",code=>{finish({code,stdout:out.join(""),stderr:errChunks.join(""),timedOut,aborted:!!signal?.aborted})})})}function fail(errorCode,message){return{ok:false,errorCode,message}}function ffmpegFailure(op,r){if(r.aborted)return fail("E_EDIT_ABORTED",`${op} aborted.`);if(r.timedOut)return fail("E_EDIT_TIMEOUT",`${op} timed out.`);const tail=r.stderr.trim().slice(-1200);log.warn(`ffmpeg ${op} exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return fail("E_EDIT_FAILED",`${op} failed (exit ${r.code}). ${tail||"No diagnostic output."}`)}async function probeDurationSec(ffprobe,input,signal){const r=await run(ffprobe,["-v","error","-show_entries","format=duration","-of","default=nokey=1:noprint_wrappers=1",input],signal);const v=Number(r.stdout.trim());if(Number.isFinite(v)&&v>0)return v;const r2=await run(ffprobe,["-v","error","-select_streams","a:0","-show_entries","stream=duration","-of","default=nokey=1:noprint_wrappers=1",input],signal);const v2=Number(r2.stdout.trim());return Number.isFinite(v2)&&v2>0?v2:0}async function probeMediaDurationSec(inputAbsPath,signal){const bins=resolveBins();if(!bins)return null;const d=await probeDurationSec(bins.ffprobe,inputAbsPath,signal);return d>0?d:null}async function extractFrameAt(inputAbsPath,atSec,outAbsPath,signal){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const at=Number.isFinite(atSec)&&atSec>0?atSec:0;const r=await run(bins.ffmpeg,["-y","-ss",String(at),"-i",inputAbsPath,"-frames:v","1","-update","1",outAbsPath],signal);if(r.code!==0){const f=ffmpegFailure("extract_frame",r);return{ok:false,errorCode:f.errorCode,message:f.message}}return{ok:true}}async function measureSilenceCoverage(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const noise=opts?.noiseDb??SILENCE_NOISE_DB;const minSec=opts?.minSilenceSec??SILENCE_MIN_SEC;const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-af",`silencedetect=noise=${noise}dB:d=${minSec}`,"-f","null","-"]),opts?.signal,{op:"silence_detect",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"silence detect aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"silence detect timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg silencedetect exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`silence detect failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:true,timing:parseSilenceDetect(r.stderr,dur)}}async function detectSceneChanges(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const th=finiteNum(opts?.threshold);const threshold=th!==void 0&&th>=0&&th<=1?th:.4;const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-vf",`select='gt(scene,${threshold})',metadata=print`,"-an","-f","null","-"]),opts?.signal,{op:"scene_detect",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"scene detect aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"scene detect timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg scenedetect exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`scene detect failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:true,durationSec:dur,threshold,candidates:parseSceneChanges(`${r.stdout}${r.stderr}`)}}async function detectQuality(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const fpsN=finiteNum(opts?.fps);const fps=fpsN!==void 0&&fpsN>0&&fpsN<=30?fpsN:3;const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const vf=`fps=${fps},blackdetect=d=0.1:pix_th=0.10,freezedetect=n=0.003:d=0.5,blurdetect,signalstats,metadata=print`;const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-vf",vf,"-an","-f","null","-"]),opts?.signal,{op:"quality_scan",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"quality scan aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"quality scan timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg quality scan exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`quality scan failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}const logText=`${r.stdout}-${r.stderr}`;const report=summarizeQuality({durationSec:dur,frames:parseQualityFrames(logText),blackSpans:parseLabeledIntervals(logText,"black"),freezeSpans:parseLabeledIntervals(logText,"freeze"),...opts?.thresholds?{thresholds:opts.thresholds}:{}});return{ok:true,report}}var fs3=__toESM(require("node:fs"));var path3=__toESM(require("node:path"));var import_node_child_process3=require("node:child_process");var import_node_util=require("node:util");var execFileAsync=(0,import_node_util.promisify)(import_node_child_process3.execFile);var log2=createLogger("ocr-runtime");var OCR_RUNTIME_KEY=`ocr-rapidocr-3.9.0-onnxruntime-1.27.0-pypdfium2-5.10.1-${process.platform}-${process.arch}`;var RAPIDOCR_VERSION="3.9.0";var ONNXRUNTIME_VERSION="1.27.0";var PYPDFIUM2_VERSION="5.10.1";var OCR_TIMEOUT_MS=5*60*1e3;var INSTALL_TIMEOUT_MS=10*60*1e3;var VERIFY_TIMEOUT_MS=2*60*1e3;var OCR_PROGRESS_HEARTBEAT_MS=3e4;function venvDir(){return pythonPackageVenvDir(OCR_RUNTIME_KEY)}function venvPython(venv=venvDir()){return process.platform==="win32"?path3.join(venv,"Scripts","python.exe"):path3.join(venv,"bin","python")}function isFile2(p){try{return fs3.statSync(p).isFile()}catch{return false}}function runtimeEnv(){return{...process.env,...bundledRuntimeEnv(),PYTHONNOUSERSITE:"1",UV_CACHE_DIR:PYTHON_VENV_UV_CACHE_DIR,PIP_CACHE_DIR:PYTHON_VENV_PIP_CACHE_DIR}}async function withHeartbeat(promise,onProgress,phase,heartbeatMessage){let tick=0;const timer=onProgress?setInterval(()=>{tick+=1;onProgress({phase,message:heartbeatMessage,data:{heartbeat:true,seconds:tick*(OCR_PROGRESS_HEARTBEAT_MS/1e3)}})},OCR_PROGRESS_HEARTBEAT_MS):null;try{return await promise}finally{if(timer)clearInterval(timer)}}var VERIFY_RUNTIME_SCRIPT=String.raw`+${r.stderr}`;const report=summarizeQuality({durationSec:dur,frames:parseQualityFrames(logText),blackSpans:parseLabeledIntervals(logText,"black"),freezeSpans:parseLabeledIntervals(logText,"freeze"),...opts?.thresholds?{thresholds:opts.thresholds}:{}});return{ok:true,report}}var fs4=__toESM(require("node:fs"));var path3=__toESM(require("node:path"));var import_node_child_process3=require("node:child_process");var import_node_util=require("node:util");var execFileAsync=(0,import_node_util.promisify)(import_node_child_process3.execFile);var log2=createLogger("ocr-runtime");var OCR_RUNTIME_KEY=`ocr-rapidocr-3.9.0-onnxruntime-1.27.0-pypdfium2-5.10.1-${process.platform}-${process.arch}`;var RAPIDOCR_VERSION="3.9.0";var ONNXRUNTIME_VERSION="1.27.0";var PYPDFIUM2_VERSION="5.10.1";var OCR_TIMEOUT_MS=5*60*1e3;var INSTALL_TIMEOUT_MS=10*60*1e3;var VERIFY_TIMEOUT_MS=2*60*1e3;var OCR_PROGRESS_HEARTBEAT_MS=3e4;function venvDir(){return pythonPackageVenvDir(OCR_RUNTIME_KEY)}function venvPython(venv=venvDir()){return process.platform==="win32"?path3.join(venv,"Scripts","python.exe"):path3.join(venv,"bin","python")}function isFile2(p){try{return fs4.statSync(p).isFile()}catch{return false}}function sentinelPath(venv){return path3.join(venv,".orkas-ocr-verified")}function sentinelMatches(venv){try{return fs4.readFileSync(sentinelPath(venv),"utf8").trim()===OCR_RUNTIME_KEY}catch{return false}}function writeSentinel(venv){try{fs4.writeFileSync(sentinelPath(venv),`${OCR_RUNTIME_KEY}+`)}catch{}}function runtimeEnv(){return{...process.env,...bundledRuntimeEnv(),PYTHONNOUSERSITE:"1",UV_CACHE_DIR:PYTHON_VENV_UV_CACHE_DIR,PIP_CACHE_DIR:PYTHON_VENV_PIP_CACHE_DIR}}async function withHeartbeat(promise,onProgress,phase,heartbeatMessage){let tick=0;const timer=onProgress?setInterval(()=>{tick+=1;onProgress({phase,message:heartbeatMessage,data:{heartbeat:true,seconds:tick*(OCR_PROGRESS_HEARTBEAT_MS/1e3)}})},OCR_PROGRESS_HEARTBEAT_MS):null;try{return await promise}finally{if(timer)clearInterval(timer)}}var VERIFY_RUNTIME_SCRIPT=String.raw`import pathlibimport pypdfium2import onnxruntime@@ -11,7 +12,7 @@ from rapidocr import RapidOCRmodel_dir = pathlib.Path(rapidocr_pkg.__file__).resolve().parent / "models"RapidOCR(params={"Global.model_root_dir": str(model_dir)})print("ok")-`;async function verifyRuntime(python,onProgress){if(!isFile2(python))return{ok:false,message:`Python executable is missing: ${python}`};try{await withHeartbeat(execFileAsync(python,["-c",VERIFY_RUNTIME_SCRIPT],{timeout:VERIFY_TIMEOUT_MS,env:runtimeEnv(),windowsHide:true,maxBuffer:2*1024*1024}),onProgress,"ocr_runtime_verify","Still checking local OCR runtime");return{ok:true}}catch(err){return{ok:false,message:err.message}}}async function ensureRuntime(onProgress){const venv=venvDir();const python=venvPython(venv);onProgress?.({phase:"ocr_runtime_check",message:"Checking local OCR runtime"});const existingVerification=await verifyRuntime(python,onProgress);if(existingVerification.ok===true){onProgress?.({phase:"ocr_runtime_ready",message:"Local OCR runtime is ready"});return{ok:true,python,venv,installed:false}}const env=runtimeEnv();const uv=env.ORKAS_UV;const bundledPython=env.ORKAS_PYTHON;if(!uv||!bundledPython){onProgress?.({phase:"ocr_runtime_missing",message:"Bundled Python/uv runtime is unavailable"});return{ok:false,errorCode:"E_OCR_RUNTIME_MISSING",message:"Bundled Python/uv runtime is unavailable, so Local OCR cannot be installed on this build."}}try{fs3.mkdirSync(path3.dirname(venv),{recursive:true});onProgress?.({phase:"ocr_runtime_install",message:"Creating local OCR Python environment",data:{runtimePath:venv}});await withHeartbeat(execFileAsync(uv,["venv","--python",bundledPython,venv],{timeout:INSTALL_TIMEOUT_MS,env,windowsHide:true,maxBuffer:1024*1024}),onProgress,"ocr_runtime_install","Still creating local OCR Python environment");onProgress?.({phase:"ocr_runtime_install",message:"Downloading and installing local OCR packages",data:{packages:[`rapidocr==${RAPIDOCR_VERSION}`,`onnxruntime==${ONNXRUNTIME_VERSION}`,`pypdfium2==${PYPDFIUM2_VERSION}`]}});await withHeartbeat(execFileAsync(uv,["pip","install","--python",venvPython(venv),"--only-binary=:all:",`rapidocr==${RAPIDOCR_VERSION}`,`onnxruntime==${ONNXRUNTIME_VERSION}`,`pypdfium2==${PYPDFIUM2_VERSION}`],{timeout:INSTALL_TIMEOUT_MS,env,windowsHide:true,maxBuffer:4*1024*1024}),onProgress,"ocr_runtime_install","Still installing local OCR packages");onProgress?.({phase:"ocr_runtime_verify",message:"Verifying local OCR runtime"})}catch(err){log2.warn(`install failed: ${err.message}`);onProgress?.({phase:"ocr_runtime_install_failed",message:"Local OCR runtime install failed",data:{error:err.message}});return{ok:false,errorCode:"E_OCR_INSTALL_FAILED",message:`Local OCR runtime install failed: ${err.message}`}}const installedVerification=await verifyRuntime(python,onProgress);if(installedVerification.ok===true){onProgress?.({phase:"ocr_runtime_ready",message:"Local OCR runtime installed and ready"});return{ok:true,python,venv,installed:true}}onProgress?.({phase:"ocr_runtime_install_failed",message:"Local OCR runtime verification failed"});return{ok:false,errorCode:"E_OCR_INSTALL_FAILED",message:`Local OCR runtime installed, but verification failed: ${installedVerification.message}`}}async function runOcrProcess(python,payload,onProgress,signal){const res=await withHeartbeat(execFileAsync(python,["-c",PYTHON_OCR_SCRIPT,payload],{timeout:OCR_TIMEOUT_MS,env:runtimeEnv(),windowsHide:true,maxBuffer:8*1024*1024,...signal?{signal}:{}}),onProgress,"ocr_run","Still running local OCR");return res.stdout}function extKind(absPath){const ext=path3.extname(absPath).toLowerCase();if(ext===".pdf")return"pdf";if([".png",".jpg",".jpeg",".webp",".gif"].includes(ext))return"image";return"unsupported"}async function ocrImageText(input){if(extKind(input.absPath)!=="image"){return{ok:false,errorCode:"E_OCR_UNSUPPORTED_FILE",message:`ocrImageText needs an image file: ${input.absPath}`}}const runtime=await ensureRuntime(input.onProgress);if(runtime.ok===false){return{ok:false,errorCode:runtime.errorCode,message:runtime.message}}const payload=JSON.stringify({path:input.absPath,kind:"image",pages:"",scale:2});let stdout="";try{stdout=await runOcrProcess(runtime.python,payload,input.onProgress,input.signal)}catch(err){return{ok:false,errorCode:"E_OCR_FAILED",message:`Local OCR failed: ${err.message}`}}try{const parsed=JSON.parse(stdout);if(!parsed?.ok){return{ok:false,errorCode:"E_OCR_FAILED",message:String(parsed?.error||"Local OCR failed")}}const page=parsed.pages&&parsed.pages[0]||{};return{ok:true,text:String(page.text||"").trim(),items:Array.isArray(page.items)?page.items:[]}}catch(err){return{ok:false,errorCode:"E_OCR_FAILED",message:`Local OCR returned invalid output: ${err.message}`}}}var PYTHON_OCR_SCRIPT=String.raw`+`;async function verifyRuntime(python,onProgress){if(!isFile2(python))return{ok:false,message:`Python executable is missing: ${python}`};try{await withHeartbeat(execFileAsync(python,["-c",VERIFY_RUNTIME_SCRIPT],{timeout:VERIFY_TIMEOUT_MS,env:runtimeEnv(),windowsHide:true,maxBuffer:2*1024*1024}),onProgress,"ocr_runtime_verify","Still checking local OCR runtime");return{ok:true}}catch(err){return{ok:false,message:err.message}}}async function ensureRuntime(onProgress){const venv=venvDir();const python=venvPython(venv);if(isFile2(python)&&sentinelMatches(venv)){onProgress?.({phase:"ocr_runtime_ready",message:"Local OCR runtime is ready"});return{ok:true,python,venv,installed:false}}onProgress?.({phase:"ocr_runtime_check",message:"Checking local OCR runtime"});const existingVerification=await verifyRuntime(python,onProgress);if(existingVerification.ok===true){writeSentinel(venv);onProgress?.({phase:"ocr_runtime_ready",message:"Local OCR runtime is ready"});return{ok:true,python,venv,installed:false}}const env=runtimeEnv();const uv=env.ORKAS_UV;const bundledPython=env.ORKAS_PYTHON;if(!uv||!bundledPython){onProgress?.({phase:"ocr_runtime_missing",message:"Bundled Python/uv runtime is unavailable"});return{ok:false,errorCode:"E_OCR_RUNTIME_MISSING",message:"Bundled Python/uv runtime is unavailable, so Local OCR cannot be installed on this build."}}try{fs4.mkdirSync(path3.dirname(venv),{recursive:true});onProgress?.({phase:"ocr_runtime_install",message:"Creating local OCR Python environment",data:{runtimePath:venv}});await withHeartbeat(execFileAsync(uv,["venv","--python",bundledPython,venv],{timeout:INSTALL_TIMEOUT_MS,env,windowsHide:true,maxBuffer:1024*1024}),onProgress,"ocr_runtime_install","Still creating local OCR Python environment");onProgress?.({phase:"ocr_runtime_install",message:"Downloading and installing local OCR packages",data:{packages:[`rapidocr==${RAPIDOCR_VERSION}`,`onnxruntime==${ONNXRUNTIME_VERSION}`,`pypdfium2==${PYPDFIUM2_VERSION}`]}});await withHeartbeat(execFileAsync(uv,["pip","install","--python",venvPython(venv),"--only-binary=:all:",`rapidocr==${RAPIDOCR_VERSION}`,`onnxruntime==${ONNXRUNTIME_VERSION}`,`pypdfium2==${PYPDFIUM2_VERSION}`],{timeout:INSTALL_TIMEOUT_MS,env,windowsHide:true,maxBuffer:4*1024*1024}),onProgress,"ocr_runtime_install","Still installing local OCR packages");onProgress?.({phase:"ocr_runtime_verify",message:"Verifying local OCR runtime"})}catch(err){log2.warn(`install failed: ${err.message}`);onProgress?.({phase:"ocr_runtime_install_failed",message:"Local OCR runtime install failed",data:{error:err.message}});return{ok:false,errorCode:"E_OCR_INSTALL_FAILED",message:`Local OCR runtime install failed: ${err.message}`}}const installedVerification=await verifyRuntime(python,onProgress);if(installedVerification.ok===true){writeSentinel(venv);onProgress?.({phase:"ocr_runtime_ready",message:"Local OCR runtime installed and ready"});return{ok:true,python,venv,installed:true}}onProgress?.({phase:"ocr_runtime_install_failed",message:"Local OCR runtime verification failed"});return{ok:false,errorCode:"E_OCR_INSTALL_FAILED",message:`Local OCR runtime installed, but verification failed: ${installedVerification.message}`}}async function runOcrProcess(python,payload,onProgress,signal,timeoutMs=OCR_TIMEOUT_MS){const res=await withHeartbeat(execFileAsync(python,["-c",PYTHON_OCR_SCRIPT,payload],{timeout:timeoutMs,env:runtimeEnv(),windowsHide:true,maxBuffer:8*1024*1024,...signal?{signal}:{}}),onProgress,"ocr_run","Still running local OCR");return res.stdout}function extKind(absPath){const ext=path3.extname(absPath).toLowerCase();if(ext===".pdf")return"pdf";if([".png",".jpg",".jpeg",".webp",".gif"].includes(ext))return"image";return"unsupported"}async function ocrImageText(input){if(extKind(input.absPath)!=="image"){return{ok:false,errorCode:"E_OCR_UNSUPPORTED_FILE",message:`ocrImageText needs an image file: ${input.absPath}`}}const runtime=await ensureRuntime(input.onProgress);if(runtime.ok===false){return{ok:false,errorCode:runtime.errorCode,message:runtime.message}}const payload=JSON.stringify({path:input.absPath,kind:"image",pages:"",scale:2});let stdout="";try{stdout=await runOcrProcess(runtime.python,payload,input.onProgress,input.signal)}catch(err){return{ok:false,errorCode:"E_OCR_FAILED",message:`Local OCR failed: ${err.message}`}}try{const parsed=JSON.parse(stdout);if(!parsed?.ok){return{ok:false,errorCode:"E_OCR_FAILED",message:String(parsed?.error||"Local OCR failed")}}const page=parsed.pages&&parsed.pages[0]||{};return{ok:true,text:String(page.text||"").trim(),items:Array.isArray(page.items)?page.items:[]}}catch(err){return{ok:false,errorCode:"E_OCR_FAILED",message:`Local OCR returned invalid output: ${err.message}`}}}async function ocrImagesText(input){if(!input.absPaths.length)return{ok:true,results:[]};const bad=input.absPaths.find(p=>extKind(p)!=="image");if(bad){return{ok:false,errorCode:"E_OCR_UNSUPPORTED_FILE",message:`ocrImagesText needs image files: ${bad}`}}const runtime=await ensureRuntime(input.onProgress);if(runtime.ok===false){return{ok:false,errorCode:runtime.errorCode,message:runtime.message}}const payload=JSON.stringify({paths:input.absPaths,kind:"images",pages:"",scale:2});const timeoutMs=Math.max(OCR_TIMEOUT_MS,6e4+1e4*input.absPaths.length);let stdout="";try{stdout=await runOcrProcess(runtime.python,payload,input.onProgress,input.signal,timeoutMs)}catch(err){return{ok:false,errorCode:"E_OCR_FAILED",message:`Local OCR failed: ${err.message}`}}try{const parsed=JSON.parse(stdout);if(!parsed?.ok){return{ok:false,errorCode:"E_OCR_FAILED",message:String(parsed?.error||"Local OCR failed")}}const pages=Array.isArray(parsed.pages)?parsed.pages:[];const results=input.absPaths.map((_,i)=>{const page=pages[i]||{};return{text:String(page.text||"").trim(),items:Array.isArray(page.items)?page.items:[],...page.error?{error:String(page.error)}:{}}});return{ok:true,results}}catch(err){return{ok:false,errorCode:"E_OCR_FAILED",message:`Local OCR returned invalid output: ${err.message}`}}}var PYTHON_OCR_SCRIPT=String.raw`import json, os, pathlib, sys, tempfile, tracebackdef load_engine():@@ -112,13 +113,22 @@ def run_ocr(engine, image_path):def main():args = json.loads(sys.argv[1])- src = args["path"]+ src = args.get("path")kind = args["kind"]engine = load_engine()pages = []if kind == "image":r = run_ocr(engine, src)pages.append({"page": 1, **r})+ elif kind == "images":+ # Batch mode: OCR many images under ONE engine load. A bad frame must+ # not fail the batch — report it per-item and keep going.+ for idx, image_path in enumerate(args["paths"]):+ try:+ r = run_ocr(engine, image_path)+ pages.append({"page": idx + 1, **r})+ except Exception as exc:+ pages.append({"page": idx + 1, "text": "", "items": [], "error": str(exc)})elif kind == "pdf":import pypdfium2 as pdfiumpdf = pdfium.PdfDocument(src)@@ -149,4 +159,5 @@ try:main()except Exception as exc:print(json.dumps({"ok": False, "error": str(exc), "trace": traceback.format_exc()}, ensure_ascii=False))-`;var log3=createLogger("video-analyze");var round22=n=>Math.round((Number.isFinite(n)?n:0)*100)/100;var IMAGE_EXTS=new Set([".png",".jpg",".jpeg",".webp",".gif",".bmp"]);var VIDEO_EXTS=new Set([".mp4",".mov",".mkv",".webm",".avi",".m4v"]);function ocrInputKind(p){const ext=path4.extname(p).toLowerCase();if(IMAGE_EXTS.has(ext))return"image";if(VIDEO_EXTS.has(ext))return"video";return"unsupported"}function sampleTimecodes(durationSec,intervalSec,maxFrames){const dur=Number.isFinite(durationSec)&&durationSec>0?durationSec:0;if(dur<=0)return[0];const cap=Math.max(1,Math.min(Math.floor(Number.isFinite(maxFrames)&&maxFrames>0?maxFrames:16),60));const desired=Math.max(.5,Number.isFinite(intervalSec)&&intervalSec>0?intervalSec:2.5);const step=Math.max(desired,dur/cap);const out=[];for(let t=step/2;t<dur&&out.length<cap;t+=step){out.push(round22(t))}if(!out.length)out.push(round22(dur/2));return out}function collapseOcrSegments(frames,durationSec){const norm=s=>s.replace(/\s+/g," ").trim();const segs=[];for(const f of frames){const prev=segs[segs.length-1];if(prev&&norm(prev.text)===norm(f.text))prev.endSec=f.tSec;else segs.push({startSec:f.tSec,endSec:f.tSec,text:f.text})}for(let i=0;i<segs.length;i++){const next=segs[i+1];segs[i].startSec=round22(i===0?0:segs[i].startSec);segs[i].endSec=round22(next?next.startSec:Math.max(segs[i].endSec,durationSec))}return segs}async function analyzeMedia(p){const st=await fs4.stat(p.inputAbsPath).catch(()=>null);if(!st||!st.isFile()){return{ok:false,errorCode:"E_ANALYZE_NO_INPUT",message:`input is not a file: ${p.inputAbsPath}`}}if(p.op==="silence"){const meas=await measureSilenceCoverage(p.inputAbsPath,p.signal?{signal:p.signal}:{});if(meas.ok===false)return{ok:false,errorCode:meas.errorCode,message:meas.message};const t=meas.timing;const coverage=assessVoiceoverCoverage({referenceDurationSec:t.durationSec,offsetSec:0,audioDurationSec:t.durationSec,voicedStartSec:t.voicedStartSec,voicedEndSec:t.voicedEndSec});const summary={op:"silence",durationSec:round22(t.durationSec),voicedStartSec:round22(t.voicedStartSec),voicedEndSec:round22(t.voicedEndSec),voicedDurationSec:round22(t.voicedDurationSec),leadingSilenceSec:round22(t.leadingSilenceSec),trailingSilenceSec:round22(t.trailingSilenceSec),silences:t.silences.map(s=>({startSec:round22(s.startSec),endSec:round22(s.endSec)})),coverage};return{ok:true,op:"silence",summary}}if(p.op==="scenes"){const r=await detectSceneChanges(p.inputAbsPath,{...p.signal?{signal:p.signal}:{},...typeof p.threshold==="number"?{threshold:p.threshold}:{}});if(r.ok===false)return{ok:false,errorCode:r.errorCode,message:r.message};return{ok:true,op:"scenes",summary:{op:"scenes",durationSec:round22(r.durationSec),threshold:r.threshold,count:r.candidates.length,candidates:r.candidates.map(c=>({tSec:round22(c.tSec),score:c.score}))}}}if(p.op==="quality"){const r=await detectQuality(p.inputAbsPath,{...p.signal?{signal:p.signal}:{},...p.qualityThresholds?{thresholds:p.qualityThresholds}:{}});if(r.ok===false)return{ok:false,errorCode:r.errorCode,message:r.message};return{ok:true,op:"quality",summary:{op:"quality",...r.report}}}if(p.op==="transcribe"){const args=["transcribe",p.inputAbsPath,"--json"];if(p.model)args.push("--model",p.model);const r=await runHyperframesCapture(args,{cwd:path4.dirname(p.inputAbsPath),...p.signal?{signal:p.signal}:{},timeoutMs:45*60*1e3});if(r.aborted)return{ok:false,errorCode:"E_ANALYZE_ABORTED",message:"transcribe aborted."};if(r.timedOut)return{ok:false,errorCode:"E_ANALYZE_TIMEOUT",message:"transcribe timed out."};const out=r.stdout.trim();if(out){try{const parsed=JSON.parse(out);if(parsed&&parsed.ok===false){return{ok:false,errorCode:"E_ANALYZE_FAILED",message:String(parsed.error??"transcribe failed")}}return{ok:true,op:"transcribe",summary:parsed}}catch{}}if(r.code!==0){const tail=r.stderr.trim().slice(-1e3);log3.warn(`hyperframes transcribe exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_ANALYZE_FAILED",message:`transcribe failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:false,errorCode:"E_ANALYZE_NO_OUTPUT",message:"transcribe produced no parseable output."}}if(p.op==="ocr"){const kind=ocrInputKind(p.inputAbsPath);if(kind==="unsupported"){return{ok:false,errorCode:"E_ANALYZE_ARG",message:`ocr input must be an image or video: ${p.inputAbsPath}`}}if(kind==="image"){const r=await ocrImageText({absPath:p.inputAbsPath,...p.signal?{signal:p.signal}:{}});if(r.ok===false)return{ok:false,errorCode:r.errorCode,message:r.message};return{ok:true,op:"ocr",summary:{op:"ocr",engine:"local:rapidocr-onnxruntime",kind:"image",text:r.text}}}const durationSec=await probeMediaDurationSec(p.inputAbsPath,p.signal)??0;if(durationSec<=0){return{ok:false,errorCode:"E_ANALYZE_FAILED",message:"could not probe video duration for frame sampling."}}const times=sampleTimecodes(durationSec,p.intervalSec??2.5,p.maxFrames??16);const tmp=await fs4.mkdtemp(path4.join(os.tmpdir(),"orkas-ocr-"));try{const frames=[];let firstErr=null;for(const t of times){if(p.signal?.aborted)return{ok:false,errorCode:"E_ANALYZE_ABORTED",message:"ocr aborted."};const out=path4.join(tmp,`f-${Math.round(t*1e3)}.png`);const ex=await extractFrameAt(p.inputAbsPath,t,out,p.signal);if(ex.ok===false){if(!firstErr)firstErr=ex;continue}const r=await ocrImageText({absPath:out,...p.signal?{signal:p.signal}:{}});if(r.ok===false){if(r.errorCode==="E_OCR_RUNTIME_MISSING"||r.errorCode==="E_OCR_INSTALL_FAILED"){return{ok:false,errorCode:r.errorCode,message:r.message}}if(!firstErr)firstErr=r;continue}frames.push({tSec:t,text:r.text})}if(!frames.length){return{ok:false,errorCode:firstErr?.errorCode??"E_ANALYZE_FAILED",message:firstErr?.message??"ocr produced no frames."}}const segments=collapseOcrSegments(frames,durationSec);return{ok:true,op:"ocr",summary:{op:"ocr",engine:"local:rapidocr-onnxruntime",kind:"video",durationSec:round22(durationSec),sampledFrames:frames.length,segments}}}finally{await fs4.rm(tmp,{recursive:true,force:true}).catch(()=>{})}}return{ok:false,errorCode:"E_ANALYZE_ARG",message:`unknown op: ${String(p.op)}`}}0&&(module.exports={analyzeMedia,collapseOcrSegments,sampleTimecodes});+`;var log3=createLogger("video-analyze");var round22=n=>Math.round((Number.isFinite(n)?n:0)*100)/100;var TRANSCRIBE_LINE_EMIT_MIN_MS=3e3;function emitAnalyzeProgress(op,event){const payload={type:"progress",source:"video_analyze",op,phase:op,...event};try{process.stderr.write(`${JSON.stringify(payload)}+`)}catch{}}var IMAGE_EXTS=new Set([".png",".jpg",".jpeg",".webp",".gif",".bmp"]);var VIDEO_EXTS=new Set([".mp4",".mov",".mkv",".webm",".avi",".m4v"]);function ocrInputKind(p){const ext=path4.extname(p).toLowerCase();if(IMAGE_EXTS.has(ext))return"image";if(VIDEO_EXTS.has(ext))return"video";return"unsupported"}function sampleTimecodes(durationSec,intervalSec,maxFrames){const dur=Number.isFinite(durationSec)&&durationSec>0?durationSec:0;if(dur<=0)return[0];const cap=Math.max(1,Math.min(Math.floor(Number.isFinite(maxFrames)&&maxFrames>0?maxFrames:16),60));const desired=Math.max(.5,Number.isFinite(intervalSec)&&intervalSec>0?intervalSec:2.5);const step=Math.max(desired,dur/cap);const out=[];for(let t=step/2;t<dur&&out.length<cap;t+=step){out.push(round22(t))}if(!out.length)out.push(round22(dur/2));return out}function collapseOcrSegments(frames,durationSec){const norm=s=>s.replace(/\s+/g," ").trim();const segs=[];for(const f of frames){const prev=segs[segs.length-1];if(prev&&norm(prev.text)===norm(f.text))prev.endSec=f.tSec;else segs.push({startSec:f.tSec,endSec:f.tSec,text:f.text})}for(let i=0;i<segs.length;i++){const next=segs[i+1];segs[i].startSec=round22(i===0?0:segs[i].startSec);segs[i].endSec=round22(next?next.startSec:Math.max(segs[i].endSec,durationSec))}return segs}async function analyzeMedia(p){const st=await fs5.stat(p.inputAbsPath).catch(()=>null);if(!st||!st.isFile()){return{ok:false,errorCode:"E_ANALYZE_NO_INPUT",message:`input is not a file: ${p.inputAbsPath}`}}if(p.op==="silence"){const meas=await measureSilenceCoverage(p.inputAbsPath,p.signal?{signal:p.signal}:{});if(meas.ok===false)return{ok:false,errorCode:meas.errorCode,message:meas.message};const t=meas.timing;const coverage=assessVoiceoverCoverage({referenceDurationSec:t.durationSec,offsetSec:0,audioDurationSec:t.durationSec,voicedStartSec:t.voicedStartSec,voicedEndSec:t.voicedEndSec});const summary={op:"silence",durationSec:round22(t.durationSec),voicedStartSec:round22(t.voicedStartSec),voicedEndSec:round22(t.voicedEndSec),voicedDurationSec:round22(t.voicedDurationSec),leadingSilenceSec:round22(t.leadingSilenceSec),trailingSilenceSec:round22(t.trailingSilenceSec),silences:t.silences.map(s=>({startSec:round22(s.startSec),endSec:round22(s.endSec)})),coverage};return{ok:true,op:"silence",summary}}if(p.op==="scenes"){const r=await detectSceneChanges(p.inputAbsPath,{...p.signal?{signal:p.signal}:{},...typeof p.threshold==="number"?{threshold:p.threshold}:{}});if(r.ok===false)return{ok:false,errorCode:r.errorCode,message:r.message};return{ok:true,op:"scenes",summary:{op:"scenes",durationSec:round22(r.durationSec),threshold:r.threshold,count:r.candidates.length,candidates:r.candidates.map(c=>({tSec:round22(c.tSec),score:c.score}))}}}if(p.op==="quality"){const r=await detectQuality(p.inputAbsPath,{...p.signal?{signal:p.signal}:{},...p.qualityThresholds?{thresholds:p.qualityThresholds}:{}});if(r.ok===false)return{ok:false,errorCode:r.errorCode,message:r.message};return{ok:true,op:"quality",summary:{op:"quality",...r.report}}}if(p.op==="transcribe"){const args=["transcribe",p.inputAbsPath,"--json"];if(p.model)args.push("--model",p.model);let lastLineEmitMs=0;const r=await runHyperframesCapture(args,{cwd:path4.dirname(p.inputAbsPath),...p.signal?{signal:p.signal}:{},timeoutMs:45*60*1e3,onHeartbeat:elapsedSec=>emitAnalyzeProgress("transcribe",{status:"heartbeat",elapsed_sec:elapsedSec}),onLine:(line,stream)=>{if(stream!=="stderr")return;const text=line.trim();if(!text)return;const now=Date.now();if(now-lastLineEmitMs<TRANSCRIBE_LINE_EMIT_MIN_MS)return;lastLineEmitMs=now;emitAnalyzeProgress("transcribe",{status:"output",detail:redactPaths(text).slice(0,200)})}});if(r.aborted)return{ok:false,errorCode:"E_ANALYZE_ABORTED",message:"transcribe aborted."};if(r.timedOut)return{ok:false,errorCode:"E_ANALYZE_TIMEOUT",message:"transcribe timed out."};const out=r.stdout.trim();if(out){try{const parsed=JSON.parse(out);if(parsed&&parsed.ok===false){return{ok:false,errorCode:"E_ANALYZE_FAILED",message:String(parsed.error??"transcribe failed")}}return{ok:true,op:"transcribe",summary:parsed}}catch{}}if(r.code!==0){const tail=r.stderr.trim().slice(-1e3);log3.warn(`hyperframes transcribe exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_ANALYZE_FAILED",message:`transcribe failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:false,errorCode:"E_ANALYZE_NO_OUTPUT",message:"transcribe produced no parseable output."}}if(p.op==="ocr"){const kind=ocrInputKind(p.inputAbsPath);if(kind==="unsupported"){return{ok:false,errorCode:"E_ANALYZE_ARG",message:`ocr input must be an image or video: ${p.inputAbsPath}`}}if(kind==="image"){const r=await ocrImageText({absPath:p.inputAbsPath,...p.signal?{signal:p.signal}:{}});if(r.ok===false)return{ok:false,errorCode:r.errorCode,message:r.message};return{ok:true,op:"ocr",summary:{op:"ocr",engine:"local:rapidocr-onnxruntime",kind:"image",text:r.text}}}const durationSec=await probeMediaDurationSec(p.inputAbsPath,p.signal)??0;if(durationSec<=0){return{ok:false,errorCode:"E_ANALYZE_FAILED",message:"could not probe video duration for frame sampling."}}const times=sampleTimecodes(durationSec,p.intervalSec??2.5,p.maxFrames??16);const tmp=await fs5.mkdtemp(path4.join(os.tmpdir(),"orkas-ocr-"));try{let firstErr=null;const extracted=[];for(const t of times){if(p.signal?.aborted)return{ok:false,errorCode:"E_ANALYZE_ABORTED",message:"ocr aborted."};const out=path4.join(tmp,`f-${Math.round(t*1e3)}.png`);const ex=await extractFrameAt(p.inputAbsPath,t,out,p.signal);if(ex.ok===false){if(!firstErr)firstErr=ex;continue}extracted.push({tSec:t,framePath:out})}if(!extracted.length){return{ok:false,errorCode:firstErr?.errorCode??"E_ANALYZE_FAILED",message:firstErr?.message??"ocr produced no frames."}}emitAnalyzeProgress("ocr",{status:"ocr_batch",frames:extracted.length});const batch=await ocrImagesText({absPaths:extracted.map(f=>f.framePath),...p.signal?{signal:p.signal}:{},onProgress:ev=>emitAnalyzeProgress("ocr",{status:ev.phase,...ev.message?{detail:ev.message}:{}})});if(batch.ok===false){return{ok:false,errorCode:batch.errorCode,message:batch.message}}const frames=[];for(let i=0;i<extracted.length;i++){const r=batch.results[i];if(!r||r.error){if(!firstErr&&r?.error)firstErr={errorCode:"E_OCR_FAILED",message:r.error};continue}frames.push({tSec:extracted[i].tSec,text:r.text})}if(!frames.length){return{ok:false,errorCode:firstErr?.errorCode??"E_ANALYZE_FAILED",message:firstErr?.message??"ocr produced no frames."}}const segments=collapseOcrSegments(frames,durationSec);return{ok:true,op:"ocr",summary:{op:"ocr",engine:"local:rapidocr-onnxruntime",kind:"video",durationSec:round22(durationSec),sampledFrames:frames.length,segments}}}finally{await fs5.rm(tmp,{recursive:true,force:true}).catch(()=>{})}}return{ok:false,errorCode:"E_ANALYZE_ARG",message:`unknown op: ${String(p.op)}`}}0&&(module.exports={analyzeMedia,collapseOcrSegments,sampleTimecodes});diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_edit_core.cjs b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_edit_core.cjsindex 607fa220..d3e1783a 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_edit_core.cjs+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-edit/scripts/lib/video_edit_core.cjs@@ -1,4 +1,4 @@var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var video_edit_exports={};__export(video_edit_exports,{assessVoiceoverCoverage:()=>assessVoiceoverCoverage,buildMixFilter:()=>buildMixFilter,detectQuality:()=>detectQuality,detectSceneChanges:()=>detectSceneChanges,editVideo:()=>editVideo,escapeFfmpegFilterValue:()=>escapeFfmpegFilterValue,extractFrameAt:()=>extractFrameAt,mapWithConcurrencyLimit:()=>mapWithConcurrencyLimit,measureSilenceCoverage:()=>measureSilenceCoverage,parseEbur128Summary:()=>parseEbur128Summary,parseFfmpegProgressTimeSec:()=>parseFfmpegProgressTimeSec,parseSilenceDetect:()=>parseSilenceDetect,probeMediaDurationSec:()=>probeMediaDurationSec,validateTrimRequest:()=>validateTrimRequest});module.exports=__toCommonJS(video_edit_exports);var fs3=__toESM(require("node:fs/promises"));var os=__toESM(require("node:os"));var path3=__toESM(require("node:path"));var import_node_child_process=require("node:child_process");var import_node_crypto=require("node:crypto");var fs2=__toESM(require("node:fs"));var path2=__toESM(require("node:path"));var path=__toESM(require("node:path"));var fs=__toESM(require("node:fs"));function scriptPathIsFile(p){try{return fs.statSync(p).isFile()}catch{return false}}function scriptPathIsDir(p){try{return fs.statSync(p).isDirectory()}catch{return false}}function looksLikePcRoot(dir){return scriptPathIsFile(path.join(dir,"package.json"))&&scriptPathIsDir(path.join(dir,"resources"))&&scriptPathIsDir(path.join(dir,"src"))}function resolvePcRoot(){if(process.env.ORKAS_PC_DIR)return path.resolve(process.env.ORKAS_PC_DIR);if(looksLikePcRoot(process.cwd()))return process.cwd();const cwdPc=path.join(process.cwd(),"PC");if(looksLikePcRoot(cwdPc))return cwdPc;let dir=__dirname;for(;;){if(looksLikePcRoot(dir))return dir;const parent=path.dirname(dir);if(parent===dir)break;dir=parent}return path.resolve(__dirname,"..","..")}var PC_ROOT=resolvePcRoot();var SRC_ROOT=path.join(PC_ROOT,"src");var PROJECT_ROOT=path.resolve(PC_ROOT,"..");if(!process.env.ORKAS_WORKSPACE_ROOT){throw new Error("paths.ts: ORKAS_WORKSPACE_ROOT not set. index.ts must run resolveInstallContainer + set the env var before importing paths.")}var WS_ROOT=path.resolve(process.env.ORKAS_WORKSPACE_ROOT);var USERS_FILE=path.join(WS_ROOT,"users.json");var WINDOW_STATE_FILE=path.join(WS_ROOT,"window-state.json");var LOGS_DIR=path.join(WS_ROOT,"logs");var VENV_ROOT=path.join(WS_ROOT,"venv");var PYTHON_VENV_ROOT=path.join(VENV_ROOT,"python");var PYTHON_VENV_BIN_DIR=path.join(PYTHON_VENV_ROOT,"bin");var PYTHON_VENV_CACHE_DIR=path.join(PYTHON_VENV_ROOT,"cache");var PYTHON_VENV_UV_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"uv");var PYTHON_VENV_PIP_CACHE_DIR=path.join(PYTHON_VENV_CACHE_DIR,"pip");var NODE_VENV_ROOT=path.join(VENV_ROOT,"node");var NODE_NPM_CACHE_DIR=path.join(NODE_VENV_ROOT,"cache","npm");var NODE_NPM_PREFIX_DIR=path.join(NODE_VENV_ROOT,"prefix");var NODE_NPM_GLOBAL_BIN_DIR=process.platform==="win32"?NODE_NPM_PREFIX_DIR:path.join(NODE_NPM_PREFIX_DIR,"bin");function runtimeResourcesDir(){const rp=process.resourcesPath;if(rp&&!rp.includes(`${path.sep}node_modules${path.sep}electron${path.sep}`)){return path.join(rp,"runtime")}return path.join(PC_ROOT,"resources","runtime")}var DEFAULT_USER_WORKSPACE=path.join(WS_ROOT,"..","userWorkSpace");function ensureTopLevelLayout(){for(const d of[LOGS_DIR,VENV_ROOT,DEFAULT_USER_WORKSPACE]){fs.mkdirSync(d,{recursive:true})}}ensureTopLevelLayout();function isFile(p){if(!p)return false;try{return fs2.statSync(p).isFile()}catch{return false}}function platformKey(platform=process.platform,arch=process.arch){return`${platform}-${arch}`}function pushUnique(out,seen,value){if(!value)return;const resolved=path2.resolve(value);if(seen.has(resolved))return;seen.add(resolved);out.push(resolved)}function runtimeRoots(){const roots=[];const seen=new Set;pushUnique(roots,seen,process.env.ORKAS_RUNTIME_DIR);pushUnique(roots,seen,runtimeResourcesDir());return roots}function runtimeVariantDirs(kind){const dirs=[];for(const runtimeRoot of runtimeRoots()){const root=path2.join(runtimeRoot,kind);dirs.push(path2.join(root,"current"),path2.join(root,platformKey()))}return[...dirs]}function resolveFfmpegBinary(kind){const envName=kind==="ffmpeg"?"ORKAS_BUNDLED_FFMPEG":"ORKAS_BUNDLED_FFPROBE";const configured=process.env[envName];if(isFile(configured))return configured;const name=process.platform==="win32"?`${kind}.exe`:kind;for(const dir of runtimeVariantDirs("ffmpeg")){const candidate=path2.join(dir,name);if(isFile(candidate))return candidate;const nested=path2.join(dir,"bin",name);if(isFile(nested))return nested}return void 0}function bundledFfmpegPaths(){const result={};const ffmpeg=resolveFfmpegBinary("ffmpeg");const ffprobe=resolveFfmpegBinary("ffprobe");if(ffmpeg)result.ffmpeg=ffmpeg;if(ffprobe)result.ffprobe=ffprobe;return result}function redactPaths(text){if(!text)return text;return text.replace(/[A-Za-z]:[\\/][^\s"']*/g,"<path>").replace(/(?:\/[\w.\-]+){2,}\/?/g,"<path>")}function createLogger(moduleName){const scope=String(moduleName||"video-script").trim()||"video-script";const write=(level,message,args)=>{if(process.env.ORKAS_VIDEO_SCRIPT_DEBUG!=="1")return;const line=`[${scope}] ${message}`;if(level==="error")console.error(line,...args);else if(level==="warn")console.warn(line,...args);else if(level==="debug")console.debug(line,...args);else console.info(line,...args)};return{error:(message,...args)=>write("error",message,args),warn:(message,...args)=>write("warn",message,args),info:(message,...args)=>write("info",message,args),debug:(message,...args)=>write("debug",message,args)}}var isNum=v=>typeof v==="number"&&Number.isFinite(v);var round3=n=>Math.round((isNum(n)?n:0)*1e3)/1e3;var clamp=(n,lo,hi)=>Math.min(hi,Math.max(lo,n));function mergeSpans(spans){const clean=spans.filter(s=>isNum(s.startSec)&&isNum(s.endSec)&&s.endSec>s.startSec).map(s=>({startSec:s.startSec,endSec:s.endSec})).sort((a,b)=>a.startSec-b.startSec);const out=[];for(const s of clean){const last=out[out.length-1];if(last&&s.startSec<=last.endSec){last.endSec=Math.max(last.endSec,s.endSec)}else{out.push({...s})}}return out}function keepIntervalsFromRemovals(durationSec,removeSpans,opts={}){const dur=isNum(durationSec)&&durationSec>0?durationSec:0;if(dur<=0)return[];const padSec=isNum(opts.padSec)&&opts.padSec>=0?opts.padSec:.1;const minRemoveSec=isNum(opts.minRemoveSec)&&opts.minRemoveSec>=0?opts.minRemoveSec:.5;const minKeepSec=isNum(opts.minKeepSec)&&opts.minKeepSec>=0?opts.minKeepSec:.3;const shrunk=[];for(const s of removeSpans){if(!isNum(s.startSec)||!isNum(s.endSec))continue;const start=clamp(s.startSec+padSec,0,dur);const end=clamp(s.endSec-padSec,0,dur);if(end-start>=minRemoveSec)shrunk.push({startSec:start,endSec:end})}const removals=mergeSpans(shrunk);if(!removals.length)return[{startSec:0,endSec:round3(dur)}];const kept=[];let cursor=0;for(const r of removals){if(r.startSec-cursor>=minKeepSec)kept.push({startSec:round3(cursor),endSec:round3(r.startSec)});cursor=Math.max(cursor,r.endSec)}if(dur-cursor>=minKeepSec)kept.push({startSec:round3(cursor),endSec:round3(dur)});return kept}function complementIntervals(kept,durationSec){const dur=isNum(durationSec)&&durationSec>0?durationSec:0;const removed=[];let cursor=0;for(const k of kept){if(!isNum(k.startSec)||!isNum(k.endSec))continue;if(k.startSec>cursor)removed.push({startSec:round3(cursor),endSec:round3(k.startSec)});cursor=Math.max(cursor,k.endSec)}if(dur>cursor)removed.push({startSec:round3(cursor),endSec:round3(dur)});return removed}var DEFAULT_FILLERS=["um","uh","umm","uhh","erm","er","ah","eh","hmm","mm","mmm"];var normToken=s=>s.toLowerCase().replace(/[^a-z']/g,"").trim();function fillerSpansFromWords(words,fillers=DEFAULT_FILLERS,opts={}){const set=new Set(Array.from(fillers,f=>normToken(f)));const padSec=isNum(opts.padSec)&&opts.padSec>=0?opts.padSec:.03;const spans=[];for(const w of words){if(!w||typeof w.text!=="string"||!isNum(w.startSec)||!isNum(w.endSec))continue;if(w.endSec<=w.startSec)continue;if(set.has(normToken(w.text))){spans.push({startSec:Math.max(0,w.startSec-padSec),endSec:w.endSec+padSec})}}return spans}function normalizeTranscriptWords(json){const collect=[];const visit=(node,depth)=>{if(depth>32||!node||typeof node!=="object")return;const o=node;if(Array.isArray(o.words))collect.push(...o.words);if(Array.isArray(o.segments))for(const seg of o.segments)visit(seg,depth+1);if(o.result)visit(o.result,depth+1);if(o.transcript)visit(o.transcript,depth+1)};if(Array.isArray(json))collect.push(...json);else visit(json,0);const out=[];for(const raw of collect){if(!raw||typeof raw!=="object")continue;const w=raw;const text=w.word??w.text??w.w;if(typeof text!=="string"||!text.trim())continue;let start;let end;if(isNum(w.startSec)&&isNum(w.endSec)){start=w.startSec;end=w.endSec}else if(isNum(w.start)&&isNum(w.end)){start=w.start;end=w.end}else if(w.offsets&&typeof w.offsets==="object"){const off=w.offsets;if(isNum(off.from)&&isNum(off.to)){start=off.from/1e3;end=off.to/1e3}}if(start===void 0||end===void 0||end<=start)continue;out.push({text:text.trim(),startSec:start,endSec:end})}return out}function parseSceneChanges(log2){const out=[];let pts=null;for(const line of log2.split("\n")){const tp=line.match(/pts_time:\s*([\d.]+)/);if(tp){pts=Number(tp[1]);continue}const sc=line.match(/scene_score\s*[:=]\s*([\d.]+)/);if(sc&&pts!==null){const score=Number(sc[1]);out.push({tSec:round3(pts),score:Number.isFinite(score)?round3(score):0});pts=null}}return out}function buildKeepFilterComplex(intervals){const valid=intervals.filter(iv=>isNum(iv.startSec)&&isNum(iv.endSec)&&iv.endSec>iv.startSec);if(!valid.length)throw new Error("buildKeepFilterComplex: no intervals to keep");const expr=valid.map(iv=>`between(t,${iv.startSec.toFixed(3)},${iv.endSec.toFixed(3)})`).join("+");const filter=`[0:v]select='${expr}',setpts=N/FRAME_RATE/TB[v];[0:a]aselect='${expr}',asetpts=N/SR/TB[a]`;return{filter,maps:["-map","[v]","-map","[a]"]}}function spanSeconds(spans){return spans.reduce((s,iv)=>s+Math.max(0,iv.endSec-iv.startSec),0)}function decisionEvidence(removeSpans,keptIntervals,reason,confidence=.9){return{removed_spans:removeSpans.map(s=>({startSec:round3(s.startSec),endSec:round3(s.endSec)})),kept_intervals:keptIntervals.map(s=>({startSec:round3(s.startSec),endSec:round3(s.endSec)})),removed_count:removeSpans.length,removed_sec:round3(spanSeconds(removeSpans)),reason,confidence}}function parseQualityFrames(log2){const frames=[];let cur=null;for(const line of log2.split("\n")){const tp=line.match(/pts_time:\s*([\d.]+)/);if(tp){if(cur)frames.push(cur);cur={tSec:round3(Number(tp[1]))};continue}if(!cur)continue;const b=line.match(/lavfi\.blur=\s*([\d.]+)/);if(b){cur.blur=round3(Number(b[1]));continue}const y=line.match(/lavfi\.signalstats\.YAVG=\s*([\d.]+)/);if(y){cur.brightness=round3(Number(y[1]));continue}}if(cur)frames.push(cur);return frames}function parseLabeledIntervals(log2,label){const spans=[];const re=new RegExp(`${label}_(start|end)[:=]\\s*(-?[\\d.]+)`,"g");let openStart=null;let m;while((m=re.exec(log2))!==null){const v=Number(m[2]);if(!Number.isFinite(v))continue;if(m[1]==="start")openStart=v;else if(openStart!==null){spans.push({startSec:round3(Math.max(0,openStart)),endSec:round3(v)});openStart=null}}return spans}function stats(nums){if(!nums.length)return null;const sum=nums.reduce((a,b)=>a+b,0);return{mean:round3(sum/nums.length),min:round3(Math.min(...nums)),max:round3(Math.max(...nums))}}function summarizeQuality(input){const blurT=isNum(input.thresholds?.blur)?input.thresholds.blur:15;const darkBelow=isNum(input.thresholds?.darkBelow)?input.thresholds.darkBelow:50;const brightAbove=isNum(input.thresholds?.brightAbove)?input.thresholds.brightAbove:200;const blur=stats(input.frames.map(f=>f.blur).filter(v=>isNum(v)));const brightness=stats(input.frames.map(f=>f.brightness).filter(v=>isNum(v)));const blackSpans=input.blackSpans??[];const freezeSpans=input.freezeSpans??[];const black_sec=round3(spanSeconds(blackSpans));const freeze_sec=round3(spanSeconds(freezeSpans));const dur=isNum(input.durationSec)&&input.durationSec>0?input.durationSec:0;const flags=[];if(blur&&blur.mean>blurT)flags.push("blurry");if(brightness&&brightness.mean<darkBelow)flags.push("too_dark");if(brightness&&brightness.mean>brightAbove)flags.push("too_bright");if(black_sec>0)flags.push("has_black");if(freeze_sec>0)flags.push("has_freeze");let score=1;if(flags.includes("blurry"))score-=.3;if(flags.includes("too_dark")||flags.includes("too_bright"))score-=.3;if(dur>0){score-=Math.min(.4,black_sec/dur);score-=Math.min(.3,freeze_sec/dur)}score=Math.max(0,Math.min(1,round3(score)));const roundSpans=ss=>ss.map(s=>({startSec:round3(s.startSec),endSec:round3(s.endSec)}));return{durationSec:round3(dur),frames_analyzed:input.frames.length,blur,brightness,black_sec,freeze_sec,black_spans:roundSpans(blackSpans),freeze_spans:roundSpans(freezeSpans),flags,score}}function finiteNum(v){return typeof v==="number"&&Number.isFinite(v)?v:void 0}var log=createLogger("video-edit");var FFMPEG_TIMEOUT_MS=20*60*1e3;var MIX_OUTPUT_SR=48e3;var MIX_LOUDNORM={I:-14,TP:-1,LRA:11};var SILENCE_NOISE_DB=-40;var SILENCE_MIN_SEC=.5;var COVERAGE_TRAILING_GAP_SEC=2;var COVERAGE_OVERSHOOT_SEC=.3;var COVERAGE_LEAD_GAP_SEC=3;var MIX_COVERAGE_CONCURRENCY=4;var MIN_TRIM_OUTPUT_SEC=.1;var RUN_PROGRESS_HEARTBEAT_MS=15e3;var RUN_PROGRESS_MIN_EMIT_MS=2e3;function parseEbur128Summary(stderr){const num=re=>{const m=stderr.match(re);if(!m)return null;if(/inf/i.test(m[1]))return null;const v=Number(m[1]);return Number.isFinite(v)?v:null};const hasIntegrated=/\bI:\s*(-?(?:inf|[\d.]+))\s*LUFS/i.test(stderr);if(!hasIntegrated)return null;return{integratedLufs:num(/\bI:\s*(-?(?:inf|[\d.]+))\s*LUFS/i),loudnessRangeLu:num(/\bLRA:\s*(-?(?:inf|[\d.]+))\s*LU\b/i),truePeakDbfs:num(/\bPeak:\s*(-?(?:inf|[\d.]+))\s*dBFS/i)}}function escapeFfmpegFilterValue(value){return value.replace(/\\/g,"\\\\").replace(/:/g,"\\:").replace(/'/g,"\\'").replace(/,/g,"\\,").replace(/;/g,"\\;").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function round2(n){return Math.round((Number.isFinite(n)?n:0)*100)/100}function clamp2(n,lo,hi){return Math.min(hi,Math.max(lo,n))}async function mapWithConcurrencyLimit(items,limit,worker){const width=Math.max(1,Math.min(items.length,Math.floor(limit)||1));const results=new Array(items.length);let next=0;await Promise.all(Array.from({length:width},async()=>{while(next<items.length){const index=next++;results[index]=await worker(items[index],index)}}));return results}function validateTrimRequest(inputDurationSec,startSec,durationSec){if(durationSec<MIN_TRIM_OUTPUT_SEC){return fail("E_EDIT_TRIM_RANGE",`trim duration must be at least ${MIN_TRIM_OUTPUT_SEC}s; got ${round2(durationSec)}s.`)}if(Number.isFinite(inputDurationSec)&&inputDurationSec>0){const remaining=inputDurationSec-startSec;if(remaining<MIN_TRIM_OUTPUT_SEC){return fail("E_EDIT_TRIM_RANGE",`trim start ${round2(startSec)}s is outside or too close to the end of the ${round2(inputDurationSec)}s input; choose a start at least ${MIN_TRIM_OUTPUT_SEC}s before the end.`)}}return null}function parseSilenceDetect(stderr,durationSec){const EPS_LEAD=.05;const EPS_TAIL=.3;const tokens=[];const re=/silence_(start|end):\s*(-?[\d.]+)/g;let m;while((m=re.exec(stderr))!==null){const t=Number(m[2]);if(Number.isFinite(t))tokens.push({kind:m[1],t})}const silences=[];let openStart=null;for(const tk of tokens){if(tk.kind==="start"){openStart=tk.t}else if(openStart!==null){silences.push({startSec:Math.max(0,openStart),endSec:tk.t});openStart=null}}const dur=Number.isFinite(durationSec)&&durationSec>0?durationSec:silences.length?silences[silences.length-1].endSec:0;if(openStart!==null)silences.push({startSec:Math.max(0,openStart),endSec:dur});const first=silences[0];const last=silences.length?silences[silences.length-1]:void 0;const leadingSilenceSec=first&&first.startSec<=EPS_LEAD?Math.min(first.endSec,dur):0;const trailingSilenceSec=last&&last.endSec>=dur-EPS_TAIL?Math.max(0,dur-last.startSec):0;const totalSilence=silences.reduce((s,iv)=>s+Math.max(0,Math.min(iv.endSec,dur)-iv.startSec),0);const voicedDurationSec=Math.max(0,dur-totalSilence);const voicedStartSec=leadingSilenceSec;const voicedEndSec=Math.max(voicedStartSec,dur-trailingSilenceSec);return{durationSec:dur,voicedStartSec,voicedEndSec,voicedDurationSec,leadingSilenceSec,trailingSilenceSec,silences}}function assessVoiceoverCoverage(input){const ref=Math.max(0,input.referenceDurationSec);const offset=Math.max(0,input.offsetSec??0);const voicedStart=offset+Math.max(0,input.voicedStartSec);const voicedEnd=offset+Math.max(0,input.voicedEndSec);const hasVoice=input.voicedEndSec-input.voicedStartSec>.05&&input.audioDurationSec>.05;const leadingGapSec=round2(voicedStart);const trailingGapSec=round2(ref-voicedEnd);const overshootSec=round2(offset+input.audioDurationSec-ref);const coverageRatio=ref>0?round2(clamp2(voicedEnd/ref,0,1)):0;const warnings=[];let status="ok";if(!hasVoice){status="silent";warnings.push("No speech detected in the added audio \u2014 the mux produced a silent or near-silent track.")}else{if(overshootSec>COVERAGE_OVERSHOOT_SEC){status="over";warnings.push(`Narration runs ${overshootSec}s past the ${round2(ref)}s clip and was truncated to fit \u2014 shorten the script so it ends before the clip does (trim the words; do not just raise speed).`)}if(trailingGapSec>COVERAGE_TRAILING_GAP_SEC){if(status==="ok")status="under";const pct=ref>0?Math.round(trailingGapSec/ref*100):0;warnings.push(`Narration ends at ${round2(voicedEnd)}s, leaving ${trailingGapSec}s of silent tail on a ${round2(ref)}s clip (~${pct}% uncovered) \u2014 lengthen the script, add a closing line, or trim the clip to match.`)}if(leadingGapSec>COVERAGE_LEAD_GAP_SEC){warnings.push(`Narration only starts at ${leadingGapSec}s \u2014 long silent lead-in; reduce the offset or trim the head.`)}}return{referenceDurationSec:round2(ref),voicedStartSec:round2(voicedStart),voicedEndSec:round2(voicedEnd),leadingGapSec,trailingGapSec,overshootSec,coverageRatio,status,warnings}}function buildMixFilter(opts){const{sr,segmentStartSec,baseHasAudio,mode,padWholeDurSec,loudnorm}=opts;const chains=[];const segLabels=[];segmentStartSec.forEach((startSec,i)=>{const idx=i+1;const parts=[`[${idx}:a]aresample=${sr}`];const ms=Math.round(Math.max(0,startSec)*1e3);if(ms>0)parts.push(`adelay=${ms}:all=1`);chains.push(`${parts.join(",")}[seg${i}]`);segLabels.push(`[seg${i}]`)});let bed;if(segLabels.length<=1){bed=segLabels[0]??""}else{chains.push(`${segLabels.join("")}amix=inputs=${segLabels.length}:duration=longest:normalize=0[vobed]`);bed="[vobed]"}const tail=`${padWholeDurSec&&padWholeDurSec>0?`apad=whole_dur=${padWholeDurSec.toFixed(3)},`:""}${loudnorm},aresample=${sr}`;if(baseHasAudio&&mode==="mix"){chains.push(`[0:a]aresample=${sr}[base]`);chains.push(`[base]${bed}amix=inputs=2:duration=longest:normalize=0,${tail}[aout]`)}else{chains.push(`${bed}${tail}[aout]`)}return chains.join(";")}function totalSpanSeconds(spans){return spans.reduce((sum,iv)=>sum+Math.max(0,iv.endSec-iv.startSec),0)}function resolveBins(){const b=bundledFfmpegPaths();if(!b.ffmpeg||!b.ffprobe)return null;return{ffmpeg:b.ffmpeg,ffprobe:b.ffprobe}}function parseProgressClock(raw){if(!raw)return null;const m=raw.trim().match(/^(\d+):(\d{2}):(\d{2}(?:\.\d+)?)$/);if(!m)return null;const h=Number(m[1]);const min=Number(m[2]);const sec=Number(m[3]);if(![h,min,sec].every(Number.isFinite))return null;return h*3600+min*60+sec}function parseFfmpegProgressTimeSec(fields){for(const key of["out_time_us","out_time_ms"]){const raw=fields[key];if(!raw)continue;const micros=Number(raw);if(Number.isFinite(micros)&µs>=0)return micros/1e6}return parseProgressClock(fields.out_time)}function emitRunProgress(progress,event){const payload={type:"progress",source:"video_edit",op:progress.op,phase:progress.phase??"edit",...event};try{process.stderr.write(`${JSON.stringify(payload)}-`)}catch{}}function withFfmpegProgress(args){return args.includes("-progress")?args:["-progress","pipe:2",...args]}function run(bin,args,signal,progress){return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process.spawn)(bin,args,{...signal?{signal}:{}})}catch(err){resolve3({code:-1,stdout:"",stderr:err.message,timedOut:false,aborted:false});return}const out=[];const errChunks=[];let timedOut=false;const startedAtMs=Date.now();let lastProgressEmitMs=0;let progressFields={};let progressLineBuffer="";const heartbeat=progress?setInterval(()=>{emitRunProgress(progress,{status:"heartbeat",elapsed_sec:round2((Date.now()-startedAtMs)/1e3)})},progress.heartbeatMs??RUN_PROGRESS_HEARTBEAT_MS):null;heartbeat?.unref?.();const emitFfmpegProgress=(status,force=false)=>{if(!progress)return;const now=Date.now();if(!force&&now-lastProgressEmitMs<RUN_PROGRESS_MIN_EMIT_MS)return;lastProgressEmitMs=now;const processedSec=parseFfmpegProgressTimeSec(progressFields);const configuredDurationSec=progress.durationSec;const durationSec=typeof configuredDurationSec==="number"&&Number.isFinite(configuredDurationSec)&&configuredDurationSec>0?configuredDurationSec:null;emitRunProgress(progress,{status:status==="end"?"completed":"running",elapsed_sec:round2((now-startedAtMs)/1e3),...processedSec!==null?{processed_sec:round2(processedSec)}:{},...processedSec!==null&&durationSec?{percent:round2(clamp2(processedSec/durationSec*100,0,100))}:{}})};const ingestProgressChunk=text=>{if(!progress)return;progressLineBuffer+=text.replace(/\r/g,"\n");const lines=progressLineBuffer.split("\n");progressLineBuffer=lines.pop()??"";for(const line of lines){const m=line.trim().match(/^([A-Za-z0-9_]+)=(.*)$/);if(!m)continue;progressFields[m[1]]=m[2];if(m[1]==="progress"){emitFfmpegProgress(m[2],m[2]==="end");if(m[2]==="end")progressFields={}}}};const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},FFMPEG_TIMEOUT_MS);let settled=false;const finish=result=>{if(settled)return;settled=true;clearTimeout(timer);if(heartbeat)clearInterval(heartbeat);if(progress&&result.code!==0){emitRunProgress(progress,{status:result.aborted?"aborted":result.timedOut?"timed_out":"failed",elapsed_sec:round2((Date.now()-startedAtMs)/1e3),code:result.code})}resolve3(result)};child.stdout?.on("data",c=>out.push(c.toString("utf8")));child.stderr?.on("data",c=>{const text=c.toString("utf8");errChunks.push(text);ingestProgressChunk(text)});child.stdin?.end();child.on("error",err=>{finish({code:-1,stdout:out.join(""),stderr:err.message,timedOut,aborted:!!signal?.aborted})});child.on("close",code=>{finish({code,stdout:out.join(""),stderr:errChunks.join(""),timedOut,aborted:!!signal?.aborted})})})}async function statSize(p){const st=await fs3.stat(p).catch(()=>null);return st&&st.isFile()?st.size:0}async function validateTrimOutput(ffprobe,outputAbsPath,signal){const bytes=await statSize(outputAbsPath);if(bytes<=0){return{ok:false,errorCode:"E_EDIT_EMPTY_OUTPUT",message:"trim produced an empty output file; check the requested start/duration."}}const durationSec=await probeDurationSec(ffprobe,outputAbsPath,signal);if(signal?.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"trim output validation aborted."};if(durationSec<MIN_TRIM_OUTPUT_SEC){return{ok:false,errorCode:"E_EDIT_EMPTY_OUTPUT",message:`trim produced a ${round2(durationSec)}s output, which is too short to use; check the requested start/duration.`}}return{ok:true,bytes,durationSec}}function fail(errorCode,message){return{ok:false,errorCode,message}}function ffmpegFailure(op,r){if(r.aborted)return fail("E_EDIT_ABORTED",`${op} aborted.`);if(r.timedOut)return fail("E_EDIT_TIMEOUT",`${op} timed out.`);const tail=r.stderr.trim().slice(-1200);log.warn(`ffmpeg ${op} exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return fail("E_EDIT_FAILED",`${op} failed (exit ${r.code}). ${tail||"No diagnostic output."}`)}async function probeDurationSec(ffprobe,input,signal){const r=await run(ffprobe,["-v","error","-show_entries","format=duration","-of","default=nokey=1:noprint_wrappers=1",input],signal);const v=Number(r.stdout.trim());if(Number.isFinite(v)&&v>0)return v;const r2=await run(ffprobe,["-v","error","-select_streams","a:0","-show_entries","stream=duration","-of","default=nokey=1:noprint_wrappers=1",input],signal);const v2=Number(r2.stdout.trim());return Number.isFinite(v2)&&v2>0?v2:0}async function probeBasic(ffprobe,input,signal){const r=await run(ffprobe,["-v","error","-show_entries","format=duration:stream=codec_type","-of","json",input],signal);let durationSec=0;let hasAudio=false;try{const j=JSON.parse(r.stdout);const d=Number(j.format?.duration);if(Number.isFinite(d)&&d>0)durationSec=d;hasAudio=(j.streams??[]).some(s=>s.codec_type==="audio")}catch{}return{durationSec,hasAudio}}async function probeMediaDurationSec(inputAbsPath,signal){const bins=resolveBins();if(!bins)return null;const d=await probeDurationSec(bins.ffprobe,inputAbsPath,signal);return d>0?d:null}async function extractFrameAt(inputAbsPath,atSec,outAbsPath,signal){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const at=Number.isFinite(atSec)&&atSec>0?atSec:0;const r=await run(bins.ffmpeg,["-y","-ss",String(at),"-i",inputAbsPath,"-frames:v","1","-update","1",outAbsPath],signal);if(r.code!==0){const f=ffmpegFailure("extract_frame",r);return{ok:false,errorCode:f.errorCode,message:f.message}}return{ok:true}}async function measureSilenceCoverage(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const noise=opts?.noiseDb??SILENCE_NOISE_DB;const minSec=opts?.minSilenceSec??SILENCE_MIN_SEC;const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-af",`silencedetect=noise=${noise}dB:d=${minSec}`,"-f","null","-"]),opts?.signal,{op:"silence_detect",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"silence detect aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"silence detect timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg silencedetect exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`silence detect failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:true,timing:parseSilenceDetect(r.stderr,dur)}}function runJumpCut(ffmpeg,inputAbsPath,kept,outputAbsPath,signal,progress){const{filter,maps}=buildKeepFilterComplex(kept);return run(ffmpeg,withFfmpegProgress(["-y","-i",inputAbsPath,"-filter_complex",filter,...maps,"-c:v","libx264","-preset","veryfast","-c:a","aac","-movflags","+faststart",outputAbsPath]),signal,progress)}async function detectSceneChanges(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const th=finiteNum(opts?.threshold);const threshold=th!==void 0&&th>=0&&th<=1?th:.4;const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-vf",`select='gt(scene,${threshold})',metadata=print`,"-an","-f","null","-"]),opts?.signal,{op:"scene_detect",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"scene detect aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"scene detect timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg scenedetect exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`scene detect failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:true,durationSec:dur,threshold,candidates:parseSceneChanges(`${r.stdout}+`)}catch{}}function withFfmpegProgress(args){return args.includes("-progress")?args:["-progress","pipe:2",...args]}function run(bin,args,signal,progress){return new Promise(resolve3=>{let child;try{child=(0,import_node_child_process.spawn)(bin,args,{...signal?{signal}:{}})}catch(err){resolve3({code:-1,stdout:"",stderr:err.message,timedOut:false,aborted:false});return}const out=[];const errChunks=[];let timedOut=false;const startedAtMs=Date.now();let lastProgressEmitMs=0;let progressFields={};let progressLineBuffer="";const heartbeat=progress?setInterval(()=>{emitRunProgress(progress,{status:"heartbeat",elapsed_sec:round2((Date.now()-startedAtMs)/1e3)})},progress.heartbeatMs??RUN_PROGRESS_HEARTBEAT_MS):null;heartbeat?.unref?.();const emitFfmpegProgress=(status,force=false)=>{if(!progress)return;const now=Date.now();if(!force&&now-lastProgressEmitMs<RUN_PROGRESS_MIN_EMIT_MS)return;lastProgressEmitMs=now;const processedSec=parseFfmpegProgressTimeSec(progressFields);const configuredDurationSec=progress.durationSec;const durationSec=typeof configuredDurationSec==="number"&&Number.isFinite(configuredDurationSec)&&configuredDurationSec>0?configuredDurationSec:null;emitRunProgress(progress,{status:status==="end"?"completed":"running",elapsed_sec:round2((now-startedAtMs)/1e3),...processedSec!==null?{processed_sec:round2(processedSec)}:{},...processedSec!==null&&durationSec?{percent:round2(clamp2(processedSec/durationSec*100,0,100))}:{}})};const ingestProgressChunk=text=>{if(!progress)return;progressLineBuffer+=text.replace(/\r/g,"\n");const lines=progressLineBuffer.split("\n");progressLineBuffer=lines.pop()??"";for(const line of lines){const m=line.trim().match(/^([A-Za-z0-9_]+)=(.*)$/);if(!m)continue;progressFields[m[1]]=m[2];if(m[1]==="progress"){emitFfmpegProgress(m[2],m[2]==="end");if(m[2]==="end")progressFields={}}}};const timer=setTimeout(()=>{timedOut=true;child.kill("SIGKILL")},FFMPEG_TIMEOUT_MS);let settled=false;const finish=result=>{if(settled)return;settled=true;clearTimeout(timer);if(heartbeat)clearInterval(heartbeat);if(progress&&result.code!==0){emitRunProgress(progress,{status:result.aborted?"aborted":result.timedOut?"timed_out":"failed",elapsed_sec:round2((Date.now()-startedAtMs)/1e3),code:result.code})}resolve3(result)};child.stdout?.on("data",c=>out.push(c.toString("utf8")));child.stderr?.on("data",c=>{const text=c.toString("utf8");errChunks.push(text);ingestProgressChunk(text)});child.stdin?.end();child.on("error",err=>{finish({code:-1,stdout:out.join(""),stderr:err.message,timedOut,aborted:!!signal?.aborted})});child.on("close",code=>{finish({code,stdout:out.join(""),stderr:errChunks.join(""),timedOut,aborted:!!signal?.aborted})})})}async function statSize(p){const st=await fs3.stat(p).catch(()=>null);return st&&st.isFile()?st.size:0}async function validateTrimOutput(ffprobe,outputAbsPath,signal){const bytes=await statSize(outputAbsPath);if(bytes<=0){return{ok:false,errorCode:"E_EDIT_EMPTY_OUTPUT",message:"trim produced an empty output file; check the requested start/duration."}}const durationSec=await probeDurationSec(ffprobe,outputAbsPath,signal);if(signal?.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"trim output validation aborted."};if(durationSec<MIN_TRIM_OUTPUT_SEC){return{ok:false,errorCode:"E_EDIT_EMPTY_OUTPUT",message:`trim produced a ${round2(durationSec)}s output, which is too short to use; check the requested start/duration.`}}return{ok:true,bytes,durationSec}}function fail(errorCode,message){return{ok:false,errorCode,message}}function ffmpegFailure(op,r){if(r.aborted)return fail("E_EDIT_ABORTED",`${op} aborted.`);if(r.timedOut)return fail("E_EDIT_TIMEOUT",`${op} timed out.`);const tail=r.stderr.trim().slice(-1200);log.warn(`ffmpeg ${op} exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return fail("E_EDIT_FAILED",`${op} failed (exit ${r.code}). ${tail||"No diagnostic output."}`)}async function measureLoudness(ffmpeg,ffprobe,inputAbsPath,signal){const durationSec=await probeDurationSec(ffprobe,inputAbsPath,signal);const r=await run(ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-af","ebur128=peak=true","-f","null","-"]),signal,{op:"loudness",phase:"analyze",durationSec});if(r.code!==0)return ffmpegFailure("loudness",r);const loudness=parseEbur128Summary(r.stderr);if(!loudness)return fail("E_EDIT_LOUDNESS_PARSE","Could not parse the ffmpeg ebur128 loudness summary.");return{ok:true,op:"loudness",loudness}}async function probeDurationSec(ffprobe,input,signal){const r=await run(ffprobe,["-v","error","-show_entries","format=duration","-of","default=nokey=1:noprint_wrappers=1",input],signal);const v=Number(r.stdout.trim());if(Number.isFinite(v)&&v>0)return v;const r2=await run(ffprobe,["-v","error","-select_streams","a:0","-show_entries","stream=duration","-of","default=nokey=1:noprint_wrappers=1",input],signal);const v2=Number(r2.stdout.trim());return Number.isFinite(v2)&&v2>0?v2:0}async function probeBasic(ffprobe,input,signal){const r=await run(ffprobe,["-v","error","-show_entries","format=duration:stream=codec_type","-of","json",input],signal);let durationSec=0;let hasAudio=false;try{const j=JSON.parse(r.stdout);const d=Number(j.format?.duration);if(Number.isFinite(d)&&d>0)durationSec=d;hasAudio=(j.streams??[]).some(s=>s.codec_type==="audio")}catch{}return{durationSec,hasAudio}}async function probeMediaDurationSec(inputAbsPath,signal){const bins=resolveBins();if(!bins)return null;const d=await probeDurationSec(bins.ffprobe,inputAbsPath,signal);return d>0?d:null}async function extractFrameAt(inputAbsPath,atSec,outAbsPath,signal){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const at=Number.isFinite(atSec)&&atSec>0?atSec:0;const r=await run(bins.ffmpeg,["-y","-ss",String(at),"-i",inputAbsPath,"-frames:v","1","-update","1",outAbsPath],signal);if(r.code!==0){const f=ffmpegFailure("extract_frame",r);return{ok:false,errorCode:f.errorCode,message:f.message}}return{ok:true}}async function measureSilenceCoverage(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const noise=opts?.noiseDb??SILENCE_NOISE_DB;const minSec=opts?.minSilenceSec??SILENCE_MIN_SEC;const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-af",`silencedetect=noise=${noise}dB:d=${minSec}`,"-f","null","-"]),opts?.signal,{op:"silence_detect",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"silence detect aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"silence detect timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg silencedetect exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`silence detect failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:true,timing:parseSilenceDetect(r.stderr,dur)}}function runJumpCut(ffmpeg,inputAbsPath,kept,outputAbsPath,signal,progress){const{filter,maps}=buildKeepFilterComplex(kept);return run(ffmpeg,withFfmpegProgress(["-y","-i",inputAbsPath,"-filter_complex",filter,...maps,"-c:v","libx264","-preset","veryfast","-c:a","aac","-movflags","+faststart",outputAbsPath]),signal,progress)}async function detectSceneChanges(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const th=finiteNum(opts?.threshold);const threshold=th!==void 0&&th>=0&&th<=1?th:.4;const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-vf",`select='gt(scene,${threshold})',metadata=print`,"-an","-f","null","-"]),opts?.signal,{op:"scene_detect",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"scene detect aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"scene detect timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg scenedetect exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`scene detect failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}return{ok:true,durationSec:dur,threshold,candidates:parseSceneChanges(`${r.stdout}${r.stderr}`)}}async function detectQuality(inputAbsPath,opts){const bins=resolveBins();if(!bins)return{ok:false,errorCode:"E_EDIT_FFMPEG_MISSING",message:"Bundled ffmpeg/ffprobe not found."};const fpsN=finiteNum(opts?.fps);const fps=fpsN!==void 0&&fpsN>0&&fpsN<=30?fpsN:3;const dur=await probeDurationSec(bins.ffprobe,inputAbsPath,opts?.signal);const vf=`fps=${fps},blackdetect=d=0.1:pix_th=0.10,freezedetect=n=0.003:d=0.5,blurdetect,signalstats,metadata=print`;const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",inputAbsPath,"-vf",vf,"-an","-f","null","-"]),opts?.signal,{op:"quality_scan",phase:"analyze",durationSec:dur});if(r.code!==0){if(r.aborted)return{ok:false,errorCode:"E_EDIT_ABORTED",message:"quality scan aborted."};if(r.timedOut)return{ok:false,errorCode:"E_EDIT_TIMEOUT",message:"quality scan timed out."};const tail=r.stderr.trim().slice(-800);log.warn(`ffmpeg quality scan exited ${r.code}: ${redactPaths(tail.slice(-300))}`);return{ok:false,errorCode:"E_EDIT_FAILED",message:`quality scan failed (exit ${r.code}). ${tail||"No diagnostic output."}`}}const logText=`${r.stdout}-${r.stderr}`;const report=summarizeQuality({durationSec:dur,frames:parseQualityFrames(logText),blackSpans:parseLabeledIntervals(logText,"black"),freezeSpans:parseLabeledIntervals(logText,"freeze"),...opts?.thresholds?{thresholds:opts.thresholds}:{}});return{ok:true,report}}async function editVideo(p){const bins=resolveBins();if(!bins)return fail("E_EDIT_FFMPEG_MISSING","Bundled ffmpeg/ffprobe not found.");const ensureOutDir=async out=>{await fs3.mkdir(path3.dirname(out),{recursive:true}).catch(()=>{})};if(p.op==="probe"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","probe requires input_path");const r=await run(bins.ffprobe,["-v","error","-print_format","json","-show_format","-show_streams",p.inputAbsPath],p.signal);if(r.code!==0)return ffmpegFailure("probe",r);try{return{ok:true,op:"probe",probe:JSON.parse(r.stdout)}}catch{return fail("E_EDIT_PROBE_PARSE","ffprobe returned unparseable JSON")}}if(p.op==="loudness"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","loudness requires input_path");const durationSec=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-hide_banner","-nostats","-i",p.inputAbsPath,"-af","ebur128=peak=true","-f","null","-"]),p.signal,{op:"loudness",phase:"analyze",durationSec});if(r.code!==0)return ffmpegFailure("loudness",r);const loudness=parseEbur128Summary(r.stderr);if(!loudness)return fail("E_EDIT_LOUDNESS_PARSE","Could not parse the ffmpeg ebur128 loudness summary.");return{ok:true,op:"loudness",loudness}}if(!p.outputAbsPath)return fail("E_EDIT_ARG",`${p.op} requires output_path`);await ensureOutDir(p.outputAbsPath);if(p.op==="trim"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","trim requires input_path");const start=finiteNum(p.start);const duration=finiteNum(p.duration);if(start===void 0||start<0)return fail("E_EDIT_ARG","trim requires a finite start >= 0 (seconds)");if(duration===void 0||duration<=0)return fail("E_EDIT_ARG","trim requires a finite duration > 0 (seconds)");const inputDurationSec=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal);const trimRangeError=validateTrimRequest(inputDurationSec,start,duration);if(trimRangeError)return trimRangeError;const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-ss",String(start),"-t",String(duration),"-c:v","libx264","-preset","veryfast","-c:a","aac","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"trim",phase:"edit",durationSec:duration});if(r.code!==0)return ffmpegFailure("trim",r);const checked=await validateTrimOutput(bins.ffprobe,p.outputAbsPath,p.signal);if(checked.ok===false)return fail(checked.errorCode,checked.message);return{ok:true,op:"trim",path:p.outputAbsPath,bytes:checked.bytes}}if(p.op==="concat"){const inputs=p.inputAbsPaths??[];if(inputs.length<2)return fail("E_EDIT_ARG","concat requires input_paths with at least 2 entries");const listPath=path3.join(os.tmpdir(),`orkas-concat-${(0,import_node_crypto.randomUUID)()}.txt`);const listBody=inputs.map(f=>`file '${f.replace(/'/g,"'\\''")}'`).join("\n");await fs3.writeFile(listPath,listBody,"utf8");try{const inputDurations=await mapWithConcurrencyLimit(inputs,MIX_COVERAGE_CONCURRENCY,input=>probeDurationSec(bins.ffprobe,input,p.signal));const concatDurationSec=inputDurations.every(d=>d>0)?inputDurations.reduce((sum,d)=>sum+d,0):null;const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-f","concat","-safe","0","-i",listPath,"-c:v","libx264","-preset","veryfast","-c:a","aac","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"concat",phase:"edit",durationSec:concatDurationSec});if(r.code!==0)return ffmpegFailure("concat",r);return{ok:true,op:"concat",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}finally{await fs3.rm(listPath,{force:true}).catch(()=>{})}}if(p.op==="burnsubs"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","burnsubs requires input_path");if(!p.subtitlesAbsPath)return fail("E_EDIT_ARG","burnsubs requires subtitles_path (.srt/.ass)");const subEsc=escapeFfmpegFilterValue(p.subtitlesAbsPath);const durationSec=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-vf",`subtitles=filename=${subEsc}`,"-c:v","libx264","-preset","veryfast","-c:a","copy","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"burnsubs",phase:"edit",durationSec});if(r.code!==0)return ffmpegFailure("burnsubs",r);return{ok:true,op:"burnsubs",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}if(p.op==="overlay"){if(!p.inputAbsPath||!p.overlayAbsPath)return fail("E_EDIT_ARG","overlay requires input_path (base) and overlay_path");const clampXY=v=>Math.round(Math.max(-1e5,Math.min(1e5,finiteNum(v)??0)));const x=clampXY(p.x);const y=clampXY(p.y);const durationSec=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-i",p.overlayAbsPath,"-filter_complex",`overlay=${x}:${y}`,"-c:v","libx264","-preset","veryfast","-c:a","copy","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"overlay",phase:"edit",durationSec});if(r.code!==0)return ffmpegFailure("overlay",r);return{ok:true,op:"overlay",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}if(p.op==="extract_frame"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","extract_frame requires input_path");const sf=finiteNum(p.start);const at=sf!==void 0&&sf>=0?sf:0;const r=await run(bins.ffmpeg,["-y","-ss",String(at),"-i",p.inputAbsPath,"-frames:v","1","-update","1",p.outputAbsPath],p.signal);if(r.code!==0)return ffmpegFailure("extract_frame",r);return{ok:true,op:"extract_frame",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}if(p.op==="trim_silence"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","trim_silence requires input_path");const noiseDb=finiteNum(p.noiseDb);const minSilenceSec=finiteNum(p.minSilenceSec);const padSec=finiteNum(p.padSec);const minKeepSec=finiteNum(p.minKeepSec);const meas=await measureSilenceCoverage(p.inputAbsPath,{...p.signal?{signal:p.signal}:{},...noiseDb!==void 0?{noiseDb}:{},...minSilenceSec!==void 0?{minSilenceSec}:{}});if(meas.ok===false)return fail(meas.errorCode,meas.message);const dur=meas.timing.durationSec;const kept=keepIntervalsFromRemovals(dur,meas.timing.silences,{...padSec!==void 0?{padSec}:{},...minSilenceSec!==void 0?{minRemoveSec:minSilenceSec}:{},...minKeepSec!==void 0?{minKeepSec}:{}});const removed=complementIntervals(kept,dur);if(!removed.length||!kept.length){return fail("E_EDIT_NO_CHANGE",`No silence \u2265 ${minSilenceSec??SILENCE_MIN_SEC}s found below ${noiseDb??SILENCE_NOISE_DB} dB \u2014 nothing to trim; use the original clip.`)}const cut=await runJumpCut(bins.ffmpeg,p.inputAbsPath,kept,p.outputAbsPath,p.signal,{op:"trim_silence",phase:"edit",durationSec:totalSpanSeconds(kept)});if(cut.code!==0)return ffmpegFailure("trim_silence",cut);const decision=decisionEvidence(removed,kept,`removed ${removed.length} silent span(s) below ${noiseDb??SILENCE_NOISE_DB} dB`);return{ok:true,op:"trim_silence",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),decision}}if(p.op==="remove_fillers"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","remove_fillers requires input_path");if(!p.transcriptAbsPath)return fail("E_EDIT_ARG","remove_fillers requires transcript_path (the analyze_media transcribe JSON with word timings)");let json;try{json=JSON.parse(await fs3.readFile(p.transcriptAbsPath,"utf8"))}catch(err){return fail("E_EDIT_TRANSCRIPT_PARSE",`could not read/parse transcript_path: ${err.message}`)}const words=normalizeTranscriptWords(json);if(!words.length)return fail("E_EDIT_NO_WORDS","transcript had no word-level timings \u2014 re-run analyze_media transcribe (--json) on this clip.");const padSec=finiteNum(p.padSec);const minKeepSec=finiteNum(p.minKeepSec);const removeSpans=fillerSpansFromWords(words,p.fillers&&p.fillers.length?p.fillers:DEFAULT_FILLERS,padSec!==void 0?{padSec}:{});if(!removeSpans.length)return fail("E_EDIT_NO_CHANGE","no filler words found \u2014 nothing to remove; use the original clip.");const dur=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal)||0;if(dur<=0)return fail("E_EDIT_FAILED","could not probe duration for filler removal.");const kept=keepIntervalsFromRemovals(dur,removeSpans,{padSec:0,minRemoveSec:0,...minKeepSec!==void 0?{minKeepSec}:{}});if(!kept.length)return fail("E_EDIT_NO_CHANGE","filler removal left nothing to keep.");const cut=await runJumpCut(bins.ffmpeg,p.inputAbsPath,kept,p.outputAbsPath,p.signal,{op:"remove_fillers",phase:"edit",durationSec:totalSpanSeconds(kept)});if(cut.code!==0)return ffmpegFailure("remove_fillers",cut);const removed=complementIntervals(kept,dur);const decision=decisionEvidence(removed,kept,`removed ${removeSpans.length} filler word(s)`);return{ok:true,op:"remove_fillers",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),decision}}if(p.op==="mix"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","mix requires input_path (the base video)");const segs=p.audioSegments&&p.audioSegments.length?p.audioSegments.filter(s=>s&&typeof s.audioAbsPath==="string"&&s.audioAbsPath).map(s=>({audioAbsPath:s.audioAbsPath,startSec:Math.max(0,finiteNum(s.startSec)??0)})):p.audioAbsPath?[{audioAbsPath:p.audioAbsPath,startSec:Math.max(0,finiteNum(p.start)??0)}]:[];if(!segs.length)return fail("E_EDIT_ARG","mix requires audio_path (the narration/music to add) or a non-empty audio_segments");const mode=p.onExistingAudio??"reject";const base=await probeBasic(bins.ffprobe,p.inputAbsPath,p.signal);if(base.hasAudio&&mode==="reject"){return fail("E_EDIT_BASE_HAS_AUDIO",`The base video already has an audio track, so mixing narration onto it would STACK a second voice (the "two voices" defect). Render the base SILENT first \u2014 for a compose segment, remove the narration <audio> from its index.html so render_composition produces no audio, then re-mix. If layering is intended (e.g. music under a talking-head's built-in lip-synced voice) pass on_existing_audio='mix'; to drop the base audio and keep only this narration pass on_existing_audio='replace'.`)}const sr=MIX_OUTPUT_SR;const ln=`loudnorm=I=${MIX_LOUDNORM.I}:TP=${MIX_LOUDNORM.TP}:LRA=${MIX_LOUDNORM.LRA}`;const filter=buildMixFilter({sr,segmentStartSec:segs.map(s=>s.startSec),baseHasAudio:base.hasAudio,mode:mode==="replace"?"replace":"mix",padWholeDurSec:base.durationSec>0?base.durationSec:null,loudnorm:ln});const inputArgs=["-y","-i",p.inputAbsPath];for(const s of segs)inputArgs.push("-i",s.audioAbsPath);const r=await run(bins.ffmpeg,withFfmpegProgress([...inputArgs,"-filter_complex",filter,"-map","0:v","-map","[aout]","-c:v","copy","-c:a","aac","-ar",String(sr),"-shortest","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"mix",phase:"edit",durationSec:base.durationSec});if(r.code!==0)return ffmpegFailure("mix",r);let coverage;const placedStarts=[];const placedEnds=[];const placedAudioEnds=[];const measurements=await mapWithConcurrencyLimit(segs,MIX_COVERAGE_CONCURRENCY,s=>measureSilenceCoverage(s.audioAbsPath,p.signal?{signal:p.signal}:{}));const measuredAll=measurements.every(meas=>meas.ok);if(measuredAll){for(let i=0;i<segs.length;i+=1){const s=segs[i];const meas=measurements[i];if(!meas.ok)continue;placedStarts.push(s.startSec+meas.timing.voicedStartSec);placedEnds.push(s.startSec+meas.timing.voicedEndSec);placedAudioEnds.push(s.startSec+meas.timing.durationSec)}}if(measuredAll&&placedEnds.length){coverage=assessVoiceoverCoverage({referenceDurationSec:base.durationSec,offsetSec:0,audioDurationSec:Math.max(...placedAudioEnds),voicedStartSec:Math.min(...placedStarts),voicedEndSec:Math.max(...placedEnds)})}return{ok:true,op:"mix",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),...coverage?{coverage}:{}}}return fail("E_EDIT_ARG",`unknown op: ${String(p.op)}`)}0&&(module.exports={assessVoiceoverCoverage,buildMixFilter,detectQuality,detectSceneChanges,editVideo,escapeFfmpegFilterValue,extractFrameAt,mapWithConcurrencyLimit,measureSilenceCoverage,parseEbur128Summary,parseFfmpegProgressTimeSec,parseSilenceDetect,probeMediaDurationSec,validateTrimRequest});+${r.stderr}`;const report=summarizeQuality({durationSec:dur,frames:parseQualityFrames(logText),blackSpans:parseLabeledIntervals(logText,"black"),freezeSpans:parseLabeledIntervals(logText,"freeze"),...opts?.thresholds?{thresholds:opts.thresholds}:{}});return{ok:true,report}}async function editVideo(p){const bins=resolveBins();if(!bins)return fail("E_EDIT_FFMPEG_MISSING","Bundled ffmpeg/ffprobe not found.");const ensureOutDir=async out=>{await fs3.mkdir(path3.dirname(out),{recursive:true}).catch(()=>{})};if(p.op==="probe"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","probe requires input_path");const r=await run(bins.ffprobe,["-v","error","-print_format","json","-show_format","-show_streams",p.inputAbsPath],p.signal);if(r.code!==0)return ffmpegFailure("probe",r);try{return{ok:true,op:"probe",probe:JSON.parse(r.stdout)}}catch{return fail("E_EDIT_PROBE_PARSE","ffprobe returned unparseable JSON")}}if(p.op==="loudness"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","loudness requires input_path");return measureLoudness(bins.ffmpeg,bins.ffprobe,p.inputAbsPath,p.signal)}if(!p.outputAbsPath)return fail("E_EDIT_ARG",`${p.op} requires output_path`);await ensureOutDir(p.outputAbsPath);if(p.op==="trim"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","trim requires input_path");const start=finiteNum(p.start);const duration=finiteNum(p.duration);if(start===void 0||start<0)return fail("E_EDIT_ARG","trim requires a finite start >= 0 (seconds)");if(duration===void 0||duration<=0)return fail("E_EDIT_ARG","trim requires a finite duration > 0 (seconds)");const inputDurationSec=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal);const trimRangeError=validateTrimRequest(inputDurationSec,start,duration);if(trimRangeError)return trimRangeError;const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-ss",String(start),"-t",String(duration),"-c:v","libx264","-preset","veryfast","-c:a","aac","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"trim",phase:"edit",durationSec:duration});if(r.code!==0)return ffmpegFailure("trim",r);const checked=await validateTrimOutput(bins.ffprobe,p.outputAbsPath,p.signal);if(checked.ok===false)return fail(checked.errorCode,checked.message);return{ok:true,op:"trim",path:p.outputAbsPath,bytes:checked.bytes}}if(p.op==="normalize_loudness"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","normalize_loudness requires input_path");const base=await probeBasic(bins.ffprobe,p.inputAbsPath,p.signal);if(!base.hasAudio)return fail("E_EDIT_NO_AUDIO","normalize_loudness requires an input with an audio stream.");const ln=`loudnorm=I=${MIX_LOUDNORM.I}:TP=${MIX_LOUDNORM.TP}:LRA=${MIX_LOUDNORM.LRA},aresample=${MIX_OUTPUT_SR}`;const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-map","0:v?","-map","0:a:0","-c:v","copy","-filter:a:0",ln,"-c:a","aac","-ar",String(MIX_OUTPUT_SR),"-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"normalize_loudness",phase:"edit",durationSec:base.durationSec});if(r.code!==0)return ffmpegFailure("normalize_loudness",r);const loudnessResult=await measureLoudness(bins.ffmpeg,bins.ffprobe,p.outputAbsPath,p.signal);if(loudnessResult.ok===false)return loudnessResult;return{ok:true,op:"normalize_loudness",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),loudness:loudnessResult.loudness}}if(p.op==="concat"){const inputs=p.inputAbsPaths??[];if(inputs.length<2)return fail("E_EDIT_ARG","concat requires input_paths with at least 2 entries");const listPath=path3.join(os.tmpdir(),`orkas-concat-${(0,import_node_crypto.randomUUID)()}.txt`);const listBody=inputs.map(f=>`file '${f.replace(/'/g,"'\\''")}'`).join("\n");await fs3.writeFile(listPath,listBody,"utf8");try{const inputDurations=await mapWithConcurrencyLimit(inputs,MIX_COVERAGE_CONCURRENCY,input=>probeDurationSec(bins.ffprobe,input,p.signal));const concatDurationSec=inputDurations.every(d=>d>0)?inputDurations.reduce((sum,d)=>sum+d,0):null;const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-f","concat","-safe","0","-i",listPath,"-c:v","libx264","-preset","veryfast","-c:a","aac","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"concat",phase:"edit",durationSec:concatDurationSec});if(r.code!==0)return ffmpegFailure("concat",r);return{ok:true,op:"concat",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}finally{await fs3.rm(listPath,{force:true}).catch(()=>{})}}if(p.op==="burnsubs"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","burnsubs requires input_path");if(!p.subtitlesAbsPath)return fail("E_EDIT_ARG","burnsubs requires subtitles_path (.srt/.ass)");const subEsc=escapeFfmpegFilterValue(p.subtitlesAbsPath);const durationSec=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-vf",`subtitles=filename=${subEsc}`,"-c:v","libx264","-preset","veryfast","-c:a","copy","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"burnsubs",phase:"edit",durationSec});if(r.code!==0)return ffmpegFailure("burnsubs",r);return{ok:true,op:"burnsubs",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}if(p.op==="overlay"){if(!p.inputAbsPath||!p.overlayAbsPath)return fail("E_EDIT_ARG","overlay requires input_path (base) and overlay_path");const clampXY=v=>Math.round(Math.max(-1e5,Math.min(1e5,finiteNum(v)??0)));const x=clampXY(p.x);const y=clampXY(p.y);const durationSec=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal);const r=await run(bins.ffmpeg,withFfmpegProgress(["-y","-i",p.inputAbsPath,"-i",p.overlayAbsPath,"-filter_complex",`overlay=${x}:${y}`,"-c:v","libx264","-preset","veryfast","-c:a","copy","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"overlay",phase:"edit",durationSec});if(r.code!==0)return ffmpegFailure("overlay",r);return{ok:true,op:"overlay",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}if(p.op==="extract_frame"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","extract_frame requires input_path");const sf=finiteNum(p.start);const at=sf!==void 0&&sf>=0?sf:0;const r=await run(bins.ffmpeg,["-y","-ss",String(at),"-i",p.inputAbsPath,"-frames:v","1","-update","1",p.outputAbsPath],p.signal);if(r.code!==0)return ffmpegFailure("extract_frame",r);return{ok:true,op:"extract_frame",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath)}}if(p.op==="trim_silence"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","trim_silence requires input_path");const noiseDb=finiteNum(p.noiseDb);const minSilenceSec=finiteNum(p.minSilenceSec);const padSec=finiteNum(p.padSec);const minKeepSec=finiteNum(p.minKeepSec);const meas=await measureSilenceCoverage(p.inputAbsPath,{...p.signal?{signal:p.signal}:{},...noiseDb!==void 0?{noiseDb}:{},...minSilenceSec!==void 0?{minSilenceSec}:{}});if(meas.ok===false)return fail(meas.errorCode,meas.message);const dur=meas.timing.durationSec;const kept=keepIntervalsFromRemovals(dur,meas.timing.silences,{...padSec!==void 0?{padSec}:{},...minSilenceSec!==void 0?{minRemoveSec:minSilenceSec}:{},...minKeepSec!==void 0?{minKeepSec}:{}});const removed=complementIntervals(kept,dur);if(!removed.length||!kept.length){return fail("E_EDIT_NO_CHANGE",`No silence \u2265 ${minSilenceSec??SILENCE_MIN_SEC}s found below ${noiseDb??SILENCE_NOISE_DB} dB \u2014 nothing to trim; use the original clip.`)}const cut=await runJumpCut(bins.ffmpeg,p.inputAbsPath,kept,p.outputAbsPath,p.signal,{op:"trim_silence",phase:"edit",durationSec:totalSpanSeconds(kept)});if(cut.code!==0)return ffmpegFailure("trim_silence",cut);const decision=decisionEvidence(removed,kept,`removed ${removed.length} silent span(s) below ${noiseDb??SILENCE_NOISE_DB} dB`);return{ok:true,op:"trim_silence",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),decision}}if(p.op==="remove_fillers"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","remove_fillers requires input_path");if(!p.transcriptAbsPath)return fail("E_EDIT_ARG","remove_fillers requires transcript_path (the analyze_media transcribe JSON with word timings)");let json;try{json=JSON.parse(await fs3.readFile(p.transcriptAbsPath,"utf8"))}catch(err){return fail("E_EDIT_TRANSCRIPT_PARSE",`could not read/parse transcript_path: ${err.message}`)}const words=normalizeTranscriptWords(json);if(!words.length)return fail("E_EDIT_NO_WORDS","transcript had no word-level timings \u2014 re-run analyze_media transcribe (--json) on this clip.");const padSec=finiteNum(p.padSec);const minKeepSec=finiteNum(p.minKeepSec);const removeSpans=fillerSpansFromWords(words,p.fillers&&p.fillers.length?p.fillers:DEFAULT_FILLERS,padSec!==void 0?{padSec}:{});if(!removeSpans.length)return fail("E_EDIT_NO_CHANGE","no filler words found \u2014 nothing to remove; use the original clip.");const dur=await probeDurationSec(bins.ffprobe,p.inputAbsPath,p.signal)||0;if(dur<=0)return fail("E_EDIT_FAILED","could not probe duration for filler removal.");const kept=keepIntervalsFromRemovals(dur,removeSpans,{padSec:0,minRemoveSec:0,...minKeepSec!==void 0?{minKeepSec}:{}});if(!kept.length)return fail("E_EDIT_NO_CHANGE","filler removal left nothing to keep.");const cut=await runJumpCut(bins.ffmpeg,p.inputAbsPath,kept,p.outputAbsPath,p.signal,{op:"remove_fillers",phase:"edit",durationSec:totalSpanSeconds(kept)});if(cut.code!==0)return ffmpegFailure("remove_fillers",cut);const removed=complementIntervals(kept,dur);const decision=decisionEvidence(removed,kept,`removed ${removeSpans.length} filler word(s)`);return{ok:true,op:"remove_fillers",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),decision}}if(p.op==="mix"){if(!p.inputAbsPath)return fail("E_EDIT_ARG","mix requires input_path (the base video)");const segs=p.audioSegments&&p.audioSegments.length?p.audioSegments.filter(s=>s&&typeof s.audioAbsPath==="string"&&s.audioAbsPath).map(s=>({audioAbsPath:s.audioAbsPath,startSec:Math.max(0,finiteNum(s.startSec)??0)})):p.audioAbsPath?[{audioAbsPath:p.audioAbsPath,startSec:Math.max(0,finiteNum(p.start)??0)}]:[];if(!segs.length)return fail("E_EDIT_ARG","mix requires audio_path (the narration/music to add) or a non-empty audio_segments");const mode=p.onExistingAudio??"reject";const base=await probeBasic(bins.ffprobe,p.inputAbsPath,p.signal);if(base.hasAudio&&mode==="reject"){return fail("E_EDIT_BASE_HAS_AUDIO",`The base video already has an audio track, so mixing narration onto it would STACK a second voice (the "two voices" defect). Render the base SILENT first \u2014 for a compose segment, remove the narration <audio> from its index.html so render_composition produces no audio, then re-mix. If layering is intended (e.g. music under a talking-head's built-in lip-synced voice) pass on_existing_audio='mix'; to drop the base audio and keep only this narration pass on_existing_audio='replace'.`)}const sr=MIX_OUTPUT_SR;const ln=`loudnorm=I=${MIX_LOUDNORM.I}:TP=${MIX_LOUDNORM.TP}:LRA=${MIX_LOUDNORM.LRA}`;const filter=buildMixFilter({sr,segmentStartSec:segs.map(s=>s.startSec),baseHasAudio:base.hasAudio,mode:mode==="replace"?"replace":"mix",padWholeDurSec:base.durationSec>0?base.durationSec:null,loudnorm:ln});const inputArgs=["-y","-i",p.inputAbsPath];for(const s of segs)inputArgs.push("-i",s.audioAbsPath);const r=await run(bins.ffmpeg,withFfmpegProgress([...inputArgs,"-filter_complex",filter,"-map","0:v","-map","[aout]","-c:v","copy","-c:a","aac","-ar",String(sr),"-shortest","-movflags","+faststart",p.outputAbsPath]),p.signal,{op:"mix",phase:"edit",durationSec:base.durationSec});if(r.code!==0)return ffmpegFailure("mix",r);let coverage;const placedStarts=[];const placedEnds=[];const placedAudioEnds=[];const measurements=await mapWithConcurrencyLimit(segs,MIX_COVERAGE_CONCURRENCY,s=>measureSilenceCoverage(s.audioAbsPath,p.signal?{signal:p.signal}:{}));const measuredAll=measurements.every(meas=>meas.ok);if(measuredAll){for(let i=0;i<segs.length;i+=1){const s=segs[i];const meas=measurements[i];if(!meas.ok)continue;placedStarts.push(s.startSec+meas.timing.voicedStartSec);placedEnds.push(s.startSec+meas.timing.voicedEndSec);placedAudioEnds.push(s.startSec+meas.timing.durationSec)}}if(measuredAll&&placedEnds.length){coverage=assessVoiceoverCoverage({referenceDurationSec:base.durationSec,offsetSec:0,audioDurationSec:Math.max(...placedAudioEnds),voicedStartSec:Math.min(...placedStarts),voicedEndSec:Math.max(...placedEnds)})}return{ok:true,op:"mix",path:p.outputAbsPath,bytes:await statSize(p.outputAbsPath),...coverage?{coverage}:{}}}return fail("E_EDIT_ARG",`unknown op: ${String(p.op)}`)}0&&(module.exports={assessVoiceoverCoverage,buildMixFilter,detectQuality,detectSceneChanges,editVideo,escapeFfmpegFilterValue,extractFrameAt,mapWithConcurrencyLimit,measureSilenceCoverage,parseEbur128Summary,parseFfmpegProgressTimeSec,parseSilenceDetect,probeMediaDurationSec,validateTrimRequest});diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-plan/SKILL.md b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-plan/SKILL.mdindex cfc7ec5e..1a36902e 100644--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-plan/SKILL.md+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/stage-plan/SKILL.md@@ -1,6 +1,7 @@---ownerAgent: 79df9cc89f5fname: stage-plan+min_app_version: "1.5.1"description_zh: 端到端视频编排的"摄入+计划"知识——先据实摄入用户素材,再把意图拆成一份跨模态 EDL(plan.json:剪辑/生成/合成/已提供 四类片段 + 旁白/音乐/字幕轨 + 交付承诺),用 stage-plan 的 video_plan 脚本校验后交 B 门审批;AUTO 端到端产线的核心。description_en: The "ingest + plan" knowledge for end-to-end video orchestration — ingest the user's material from evidence, then decompose intent into ONE cross-modal EDL (plan.json: edit / generate / compose / provided segments + narration/music/caption tracks + a delivery promise), validate it with the stage-plan video_plan script, and take it to gate B. Core of the AUTO end-to-end line.category: creation@@ -12,16 +13,21 @@ How to turn "here is my material + here's the video I want" into a single, inspe## How to call ingest scripts-Use `stage-edit` scripts for factual ingest before writing the plan:+Use `stage-edit` scripts for factual ingest before writing the plan, except transcription, which runs through the required built-in `video_studio` tool.```bash"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-edit edit_video -- --op probe --input raw/clip.mp4-"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-edit analyze_media -- --op transcribe --input raw/clip.mp4 --model large-v3"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-edit analyze_media -- --op ocr --input raw/screen-recording.mp4"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" stage-edit edit_video -- --op extract_frame --input raw/clip.mp4 --start 3 --output project/frames/clip-3s.png```-These are script calls, not direct tool calls; their JSON output is the evidence for `project/ingest.json`.+Call transcription directly as:++```json+{"op":"speech.transcribe","input_path":"raw/clip.mp4","transcript_path":"project/transcripts/clip.json","timestamps":"word"}+```++These script/tool calls return JSON. Their output is the evidence for `project/ingest.json`.## How to call the plan validator@@ -49,7 +55,7 @@ You cannot plan against material you have not looked at. For EVERY supplied clip1. **Probe** it (`stage-edit edit_video --op probe`) for real duration / resolution / fps / audio presence. A plan that cuts past the real duration breaks.2. **Read its content** the cheapest way that fits:- - spoken audio → `stage-edit analyze_media --op transcribe` (pass `--model large-v3` for non-English) → you now have timecoded words to cut on.+ - spoken audio → call `video_studio` `op: "speech.transcribe"` with `timestamps: "word"` → you now have timecoded words to cut on.- silent / screen-recording / slideshow → `stage-edit analyze_media --op ocr` → per-timecode on-screen text. The audio being empty does NOT mean the screen is.- need to judge what a moment LOOKS like (is the hero shot usable? is the product right-side up?) → read frames: `stage-edit edit_video --op extract_frame` then look at them. If you are multimodal you read them directly; if you cannot see images, say so and plan on probe/transcript/OCR evidence alone — mark those judgments unverified, do not invent them.3. Record what each input is good for in `project/ingest.json`: `{input_id, duration, has_audio, content_summary, quality_risks:[...], usable_for:[...], planning_implications:[...]}`. This is the factual basis the plan cites — segments reference `input_id`s from here. Rules:@@ -66,7 +72,7 @@ Pick ONE `delivery_promise.type` and make the whole plan keep it:- **compose_led** — designed HTML is the spine (explainer / data); footage/generation are accents.- **hybrid** — a deliberate mix (e.g. source hero + composed framing + generated opener).-Set `motion_min_ratio` to the minimum share of runtime that must be real motion rather than static cards — this is the anti-slideshow guard. If you cannot hit it from the available material, say so at gate A instead of quietly shipping a slideshow. If `source_required` is true, at least one PRIMARY segment must be real footage (`source: edit | provided`).+Set `motion_min_ratio` to the minimum share of runtime that must be real motion rather than static cards — this is the anti-slideshow guard. If you cannot hit it from the available material, say so at gate A instead of quietly shipping a slideshow. If `source_required` is true, at least one PRIMARY segment must be real footage (`source: edit | provided`) — the supplied footage must play in the rendered timeline, not merely appear as a still reference frame.## Step 3 — Decompose into a cross-modal EDL@@ -78,6 +84,8 @@ Write `project/plan.json`. Every segment declares HOW it is produced (`source`)Tracks are separate from the visual timeline: `tracks.narration` (a `voice` from the voice table + timed lines `{text, start_sec, target_sec}`; each line gets a `produced_path` once synthesized, so one line can be re-voiced alone), `tracks.music` (path + duck under narration), `tracks.captions` (`{ from?, style?, lines:[{text, start_sec, target_sec}] }` — captions live as DATA here, NOT burned into the picture, so a typo is a one-line edit re-burned at assemble). Put the billable-generation count in `cost_estimate` — gate C reads it.+Fit narration in the plan before any TTS call: use natural cadence (about 2.2-2.7 English words/sec or 4-5 Chinese chars/sec), shorten over-budget lines here, and do not rely on repeated synthesis to discover timing.+**Author plan.json in EXACTLY this shape (copy the field names — the `stage-plan video_plan --op validate` script rejects any other shape):**```jsondiff --git a/resources/builtin/marketplace/agents/bcfcb4921dce/agent.json b/resources/builtin/marketplace/agents/bcfcb4921dce/agent.jsonnew file mode 100644index 00000000..c69bda95--- /dev/null+++ b/resources/builtin/marketplace/agents/bcfcb4921dce/agent.json@@ -0,0 +1,83 @@+{+ "agent_id": "bcfcb4921dce",+ "version": "1.0.1",+ "name": "UIDesigner",+ "description_zh": "将产品目标、PRD、现有界面、截图、Figma/设计稿说明或品牌参考转成默认以 HTML 呈现的设计产物、设计稿来源交接、DESIGN.md 设计契约、按需中性参考包、设计系统、组件映射、可刷新 HTML 产物、前端实现、视觉审查和 craft 质量门槛;适合页面设计、dashboard、组件、响应式、A11y、设计系统、Figma/设计稿转 HTML、logo/字标/品牌视觉、live dashboard、视觉 polish、设计转代码和 UI review;触发词:UI设计、UX、界面设计、HTML设计稿、设计稿、Figma、设计契约、参考风格、设计系统、组件、logo、字标、品牌视觉、可刷新报告、实时看板、视觉优化、质量检查、反 AI 味、设计转代码、A11y、dashboard、页面改版、审美优化",+ "description_en": "Turns product goals, PRDs, existing screens, screenshots, Figma/design notes, or brand references into design deliverables that default to HTML, design-source handoffs, DESIGN.md-style design contracts, conditional neutral reference-pack choices, design systems, component mappings, refreshable HTML artifacts, frontend changes, visual review, and craft quality gates; useful for UI design, dashboards, components, responsive behavior, accessibility, Figma/design-to-HTML, design systems, live dashboards, design-to-code, and UI review.",+ "workflow": "You are UIDesigner, a product UI/UX and design-engineering agent. Your job is to produce usable interfaces, design systems, HTML-first design deliverables, and visual reviews that can move directly into implementation.\n\n### 0. Default output shape\n- Design deliverables default to HTML. Unless the user explicitly asks for another final format, create or modify an HTML artifact, HTML file, or HTML-rendered app screen.\n- This HTML default applies to designs, redesigns, mockups, UI concepts, pages, dashboards, component sets, design systems, logo/identity boards, Figma/screenshot-to-HTML work, visual audits, and live-ready reports.\n- Meta tasks are different: when the user asks to analyze this agent, list options, debug behavior, explain why a prior run failed, review prompts/skills, or propose a plan, answer in prose unless they ask for an artifact.\n- PNG, SVG, PDF, Markdown-only strategy, image-only output, or code-only patches are valid final formats only when explicitly requested or when the task is not a design artifact.\n- Images, screenshots, generated raster assets, SVGs, and rationale may appear inside the HTML, but must not replace the HTML deliverable.\n\n### 1. Route the UI job and load only needed skills\n- REFERENCE PACK RULE: ui-reference-packs is optional. Use it only when the user supplies style references, asks for a named visual direction, provides brand material, the product has no clear visual system, or a broad category could mislead the result and needs an explicit rejection. Prefer existing repo tokens, screenshot structure, and the design contract first.\n- DESIGN SOURCE / FIGMA: for Figma links/exports, design-tool screenshots, PDFs, JSON, design notes, existing HTML, or design-to-HTML fidelity, use ui-design-source first, then ui-design-contract; add ui-reference-packs only when the reference-pack rule triggers; then use ui-design-system, ui-controls-accessibility, ui-taste, ui-color, ui-html-renderer, and ui-craft-checks. Do not claim Figma import or frame inspection unless access or exports were actually inspected.\n- DESIGN BRIEF: use ui-design-contract, then ui-design-system, ui-controls-accessibility, ui-taste, ui-color, ui-html-renderer, and ui-craft-checks; add ui-reference-packs only when the reference-pack rule triggers.\n- IMPLEMENT: inspect the repo first. Use existing framework, components, tokens, CSS conventions, and icon modules; use ui-design-system, ui-controls-accessibility, ui-taste, ui-color, ui-html-renderer, and ui-craft-checks. Add ui-design-source and ui-design-contract when implementation is driven by Figma/design exports, screenshots, references, brand material, design notes, or unclear visual direction; add ui-reference-packs only when needed.\n- LIVE ARTIFACT: for live dashboards, refreshable reports, synced views, recurring updates, connector-backed data, or auditable data-backed HTML, use ui-live-artifact first, then ui-design-contract and the visual skills needed for quality, ui-html-renderer, and ui-craft-checks; ask whether it should be refreshable/live or static HTML when live intent is ambiguous.\n- REVIEW: use ui-design-review and ui-craft-checks, plus ui-taste, ui-controls-accessibility, and ui-color when needed. Report findings first; create an HTML review page only when the review itself is the deliverable and the user did not ask for text-only.\n- DESIGN SYSTEM: use ui-design-contract, ui-design-system, ui-color, ui-controls-accessibility, ui-html-renderer, and ui-craft-checks; add ui-design-source when derived from design exports, and ui-reference-packs only when a style benchmark is needed.\n- HANDOFF: use ui-design-source when a source exists, then ui-design-contract, ui-design-system, ui-controls-accessibility, ui-taste, ui-color, ui-html-renderer, and ui-craft-checks; add ui-reference-packs only when references or weak system direction make it useful.\n- SCREENSHOT / IMAGE REDESIGN: use ui-design-source for design-tool frames/exports, then ui-design-contract, visual skills, ui-html-renderer, and ui-craft-checks; add ui-reference-packs only for explicit restyle/reference needs. Treat the image as source of truth. Extract visible text, page type, layout regions, components, hierarchy, colors, and unknowns before rendering. If a later form answer conflicts with the screenshot, preserve the screenshot or ask one focused clarification.\n- LOGO / BRAND MARK: when UIDesigner is asked for a logo, icon, wordmark, brand mark, or visual identity, use ui-design-contract, ui-reference-packs, ui-taste, ui-color, ui-html-renderer, and ui-craft-checks. The deliverable is an HTML brand board or HTML design draft with marks, variants, tokens, usage examples, and rationale.\nIf the user explicitly asks for raw image generation or photo editing as the final format with no UI, brand-system, or HTML presentation, route to ImageCreator; if the user explicitly asks for video or motion content as the final format, route to VideoStudio; if it is a full production feature beyond UI, coordinate with ProductDeveloper.\n\n### 2. Gather design context\n- Create a compact Design Source Handoff when applicable, then a Design Contract Snapshot before rendering reference-heavy, screenshot-based, brand-led, or multi-screen work. Track observed/provided/inferred/unknown evidence plus keep/change/do-not-copy boundaries.\n- Inspect the current product, routes, components, CSS/tokens, UI framework, icon system, states, and responsive constraints before proposing a new style.\n- Prefer the product's existing design system and component patterns. External references translate style DNA only; they do not override source structure or local tokens.\n- For screenshots, Figma exports, PDFs, JSON, existing HTML, or brand references, extract structure, hierarchy, spacing, color roles, typography roles, component inventory, interaction states, visible copy, assets, fidelity mode, and accessibility constraints.\n- Preserve screenshot information architecture and visible content unless the user explicitly asks to change the product, page type, or workflow. Do not invent dashboards, tables, charts, metrics, sidebars, or operational data unless visible or requested.\n- When screenshot text or controls matter, use available OCR/image inspection. If confidence is low, label unknown regions or ask for context instead of filling gaps with a generic SaaS pattern.\n\n### 3. Make design decisions before editing\n- Use the Design Source Handoff and Design Contract Snapshot as source of truth. If a reference pack is selected, use it only for token roles, density, interaction attitude, and pattern boundaries.\n- State a compact UI direction: target user, primary workflow, information hierarchy, visual tone, layout model, component strategy, token strategy, accessibility risks, and responsive behavior.\n- Keep work tools utilitarian and scannable; use expressive visuals only when the domain calls for it.\n- For production UI, define empty, loading, error, disabled, selected, focus, hover, and mobile states when they matter.\n\n### 4. Implement or render\n- Render from the source, contract, local system, and any selected reference pack. Every major frame/screenshot/reference region must map to a visible HTML counterpart or an explicit removal/change rationale.\n- Do not use dashboard, kanban, pricing, mobile-frame, wireframe, or live-artifact patterns unless the user or source contract triggers them.\n- Build the actual usable experience as the first screen; do not turn app/tool requests into marketing pages.\n- Use stable layout dimensions and responsive constraints so dynamic text, hover states, and data changes do not shift or overlap UI.\n- Do not add dependencies for design convenience. If a library is already present, follow local usage patterns.\n- For live-ready artifacts, produce an HTML preview that works now, keep sample/normalized data separate when files are requested, represent refresh/error/stale states, and never persist secrets, raw provider responses, cookies, auth headers, or token-like fields.\n\n### 5. Validate visually\n- Run ui-craft-checks before final delivery for any non-trivial HTML artifact, implemented screen, review page, live-ready view, form, dashboard, or interactive surface. Fix P0 craft failures before final response.\n- When a runnable app or HTML artifact is available, use the Orkas embedded artifact preview, source/DOM inspection, existing screenshot evidence, or non-external viewport checks when available. Do not open the system browser by default; use an external browser only when the user explicitly asks for it or the target app workflow already requires it.\n- Verify HTML default delivery, source/design fidelity, state coverage, text fit, contrast, focus visibility, target sizes, interaction states, form behavior, responsive wrapping, live/security boundaries, anti-template tells, and absence of overlapping controls.\n- For design reviews, report evidence from the rendered UI or screenshots, not only abstract taste judgments.\n\n### 6. Deliver clearly\n- For design artifacts: put the HTML artifact/file path or implemented app screen first, then direction, tokens, component map, states, accessibility notes, review findings, and handoff details as relevant.\n- For implementation: summarize changed screens/files, design direction used, verification performed, and remaining product/design risks.\n- For reviews: lead with prioritized findings and concrete fixes; include an HTML review page or annotated artifact unless the user asked for text-only.\n- For ordinary delivery, report craft failures and verification performed; do not dump the full craft matrix unless the user asked for a review, handoff, or QA checklist.\n- Never claim a Figma import, design-source inspection, connector/live registration, external-browser validation, HTML rendering, or accessibility pass happened unless it actually did.",+ "created_at": "2026-07-08T00:00:00",+ "updated_at": "2026-07-08T19:20:00.000Z",+ "knowhow": [+ "Runs craft quality gates before delivery, covering HTML default, source/design fidelity, state coverage, accessibility, form validation, typography, motion, responsive behavior, live/security, and anti-template tells.",+ "Extracts Figma/design exports, screenshots, PDFs, JSON, design notes, and existing HTML into a Design Source Handoff with fidelity mode, frame map, components, tokens, assets, and unknowns before rendering.",+ "Plans live-ready HTML artifacts with safe data/provenance contracts, refresh/error/stale states, and static fallback when no connector/runtime is available.",+ "Selects optional neutral reference archetypes and pattern boundaries only when needed, improving visual specificity without accidentally applying dashboard, kanban, pricing, or mobile templates.",+ "Creates OpenDesign-inspired Design Contract Snapshots and DESIGN.md-style directions before rendering reference-heavy UI, so screenshots, brand material, and product constraints remain traceable.",+ "Turns product goals, PRDs, screenshots, Figma notes, and existing app context into UI direction, component plans, HTML design drafts, frontend implementation, and visual review.",+ "Keeps Better Design, UI Skills, Taste Skill, and Color Expert-inspired methods as separate private skills so detailed design knowledge stays routable.",+ "Prefers existing product components and tokens before introducing a new visual system.",+ "Validates rendered UI through embedded artifact preview, source/DOM inspection, screenshot evidence, or explicit external-browser checks only when requested."+ ],+ "standards": [+ "Non-trivial HTML artifacts, implemented screens, review pages, live-ready views, forms, dashboards, and interactive surfaces must pass P0 craft gates before final delivery or explicitly state unverified risks.",+ "Figma/design-source claims must be evidence-based: UIDesigner may only say frames, variables, or components were inspected when a connector, export, screenshot, or file was actually read.",+ "Live or refreshable artifacts must separate UI preview from normalized data/provenance, represent stale/loading/error states, and never persist secrets, credentials, auth headers, cookies, tokens, or raw provider responses.",+ "Reference packs are optional advisory style DNA, not templates: use them only when a reference/style gap exists, at most one primary pack plus one optional influence, and never let them override screenshot information architecture, explicit user constraints, or existing app tokens.",+ "When screenshots, references, brand material, or vague taste direction are provided, UIDesigner must create or consult a design contract before HTML rendering, separating observed/provided/inferred/unknown evidence and keep/change/do-not-copy boundaries.",+ "Every UI recommendation must connect to a user workflow, hierarchy, component behavior, accessibility outcome, or a concrete element visible in the provided screenshot/reference.",+ "All UIDesigner deliverables default to HTML, either as a self-contained artifact/file or as the implemented target app screen; use another final format only when the user explicitly asks for it. Image assets may be embedded but cannot be the only deliverable by default.",+ "Do not copy proprietary brand assets, logos, exact layouts, or protected content from references; adapt the design language only when appropriate.",+ "Production UI changes must account for responsive behavior, text fit, contrast, interaction states, and existing framework conventions.",+ "Design reviews must prioritize concrete, fixable issues over vague taste comments.",+ "Do not install dependencies, publish, or make broad refactors without explicit user approval."+ ],+ "category": "rnd",+ "icon": "palette",+ "color": "violet",+ "runtime": {+ "kind": "in_process"+ },+ "interactive": false,+ "output_format": "artifact",+ "skill_list": [+ "ui-design-source",+ "ui-live-artifact",+ "ui-design-contract",+ "ui-reference-packs",+ "ui-design-system",+ "ui-controls-accessibility",+ "ui-taste",+ "ui-color",+ "ui-html-renderer",+ "ui-craft-checks",+ "ui-design-review"+ ],+ "inputs": [+ {+ "id": "request",+ "label": "UI request",+ "type": "textarea",+ "required": true,+ "default": "",+ "description": "The UI, UX, design-system, visual review, or implementation task."+ },+ {+ "id": "repo_path",+ "label": "Local app path (optional)",+ "type": "directory",+ "required": false,+ "default": "",+ "description": "Optional local repository or app directory for implementation and visual verification."+ },+ {+ "id": "references",+ "label": "Design references",+ "type": "file",+ "required": false,+ "multiple": true,+ "default": [],+ "accept": "image/*,.pdf,.fig,.json,.md,.txt",+ "description": "Optional screenshots, exported design notes, brand material, or reference assets."+ }+ ]+}diff --git a/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-color/SKILL.md b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-color/SKILL.mdnew file mode 100644index 00000000..336ac3b5--- /dev/null+++ b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-color/SKILL.md@@ -0,0 +1,93 @@+---+ownerAgent: bcfcb4921dce+name: ui-color+description_zh: "构建和审查 UI 配色,覆盖 OKLCH/OKLAB、调色板、语义色、对比度、图表色、暗色模式和可访问性色彩规则。"+description_en: "Build and review UI color systems across OKLCH/OKLAB, palettes, semantic color, contrast, chart color, dark mode, and accessible color rules."+category: rnd+---++# ui-color++Use this skill when creating or reviewing palettes, contrast, semantic color, dark mode, or chart colors. It adapts Color Expert-style color reasoning into practical UI work.++## Color Roles First++Start with roles before choosing hues:++- `bg`: page background.+- `surface`: panels, rows, cards, inputs.+- `surface-raised`: dialogs, menus, popovers.+- `text`: primary content.+- `text-muted`: metadata and helper text.+- `border`: dividers, input outlines, table rules.+- `accent`: primary action, selection, active state.+- `focus`: visible keyboard focus.+- `danger`, `warning`, `success`, `info`: semantic states.+- `chart-*`: data series, separate from action colors.++Do not use the same accent for primary action, warning, and chart series.++## OKLCH And Perceptual Rules++When authoring new palettes:++- Prefer OKLCH/OKLAB reasoning for even lightness and chroma steps.+- Keep neutral surfaces low-chroma.+- Use accent chroma deliberately; high chroma should be rare in work tools.+- Build light and dark variants by role, not by automatic inversion.+- Keep semantic colors distinct in hue and lightness.++When the codebase uses hex, HSL, RGB, or CSS variables, implement in the local format while preserving the role logic.++## Contrast Rules++Check contrast for:++- Body text on page and panel backgrounds.+- Muted text on surfaces.+- Buttons in default, hover, pressed, and disabled states.+- Inputs, focus rings, and validation messages.+- Table row selection and hover.+- Status chips and alerts.+- Chart labels and legends.++Do not rely on color alone for state. Pair semantic colors with text, icon shape, position, or pattern.++## Palette Construction++For product UI:++- Use 1 primary accent.+- Add at most 1 secondary accent unless data visualization requires more.+- Keep neutral scale broad enough for hierarchy.+- Keep borders visible but quiet.+- Reserve saturated colors for action, selection, and status.++For dashboards:++- Separate categorical chart colors from UI actions.+- Avoid too many similar blues or purples.+- Make critical alerts readable in both color and text.++For brand/editorial pages:++- Color may be more expressive, but the product/place/object must stay inspectable.++## Dark Mode++Dark mode is not inverted light mode:++- Raise surfaces through lightness differences, not heavy shadows.+- Keep text contrast high without pure white everywhere.+- Lower accent chroma if it blooms.+- Re-check semantic colors; red and yellow often need separate dark-mode values.++## Review Output++When reporting color decisions:++- List role tokens.+- Explain accent and semantic usage.+- Note contrast risks.+- Note one-hue or over-saturation risks.+- State whether chart/data colors are separate from action colors.diff --git a/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-controls-accessibility/SKILL.md b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-controls-accessibility/SKILL.mdnew file mode 100644index 00000000..a7829e86--- /dev/null+++ b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-controls-accessibility/SKILL.md@@ -0,0 +1,97 @@+---+ownerAgent: bcfcb4921dce+name: ui-controls-accessibility+description_zh: "选择正确控件并检查可访问性,覆盖控件分类、状态覆盖、响应式、文本适配、键盘操作和 A11y 规则。"+description_en: "Choose the right controls and check accessibility across control taxonomy, states, responsive behavior, text fit, keyboard use, and A11y rules."+category: rnd+---++# ui-controls-accessibility++Use this skill when choosing controls, defining states, checking responsive behavior, or reviewing accessibility. It adapts UI Skills-style practical UI rules into implementation-ready design work.++## Control Taxonomy++Use familiar controls for the job:++- Button: clear command.+- Icon button: familiar compact command, with tooltip or accessible label.+- Toggle or checkbox: binary setting.+- Radio group: mutually exclusive choice where every option should be visible.+- Segmented control: small mode set that changes a view or filter.+- Select or combobox: larger option set.+- Menu: secondary commands.+- Tabs: peer views with persistent context.+- Slider: continuous numeric adjustment.+- Stepper or numeric input: precise numeric adjustment.+- Table or grid: comparison and repeated scanning.+- Drawer: secondary workflow while preserving main context.+- Modal: blocking decision or short focused task.+- Tooltip: explain an icon or concise unfamiliar label, not required content.++Do not style decorative pills as controls unless they have standard keyboard and state behavior.++## Required States++Represent states that a real product would need:++- Default, hover, active/pressed, focus-visible, disabled.+- Selected/current for tabs, nav, filters, rows, and options.+- Empty, loading, success, warning, error.+- Validation for form fields.+- Permission or unavailable state when actions are gated.+- Mobile collapsed state for navigation, filters, and dense tables.++Do not add every state to every component. Add the states the workflow can actually reach.++## Accessibility Checks++Minimum checks:++- Contrast: body text, muted text, controls, borders, focus rings, and semantic status.+- Keyboard: tab order, visible focus, Escape for popovers/modals, Enter/Space activation where expected.+- Labels: every input and icon-only action needs a visible label, aria-label, or clear surrounding context.+- Target size: small controls need enough clickable area.+- Text scaling: labels and buttons must fit with realistic localized text.+- Motion: avoid critical information that appears only through animation; respect reduced-motion where practical.+- Status: do not rely on color alone.++## Responsive Rules++Define stable responsive behavior:++- Navigation may collapse; primary action remains reachable.+- Tables switch to horizontal scroll, column priority, or list cards depending on data shape.+- Filters collapse into a drawer or toolbar menu.+- Two-pane layouts become stacked or detail-over-list.+- Fixed-format UI such as boards, grids, tiles, and toolbars need stable dimensions.+- Text must wrap or truncate intentionally; it must not overlap controls.++Do not scale font size with viewport width. Use explicit type roles and breakpoints.++## Form And Data Rules++Forms:++- Group related fields.+- Put helper/error text near the field.+- Show required/optional intent clearly.+- Use inline validation for recoverable errors.++Data:++- Align numbers for comparison.+- Keep row actions predictable.+- Use status chips sparingly and consistently.+- Provide sorting/filtering controls only when useful for the data size.++## Output Checklist++For every UI brief or implementation, include:++- Control choices and why.+- Key states represented.+- Keyboard/focus expectations.+- Mobile behavior.+- Text-fit and localization risk.+- Contrast or status-color notes.diff --git a/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-craft-checks/SKILL.md b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-craft-checks/SKILL.mdnew file mode 100644index 00000000..55b7225a--- /dev/null+++ b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-craft-checks/SKILL.md@@ -0,0 +1,98 @@+---+ownerAgent: bcfcb4921dce+name: ui-craft-checks+description_zh: "UIDesigner 的 HTML 设计质量门槛;在交付前或 review/polish 时检查可访问性、状态覆盖、表单验证、动效克制、排版层级、响应式/RTL、反 AI 模板味和截图/设计源保真。"+description_en: "UIDesigner's HTML craft quality gate; use before delivery or during review/polish to check accessibility, state coverage, form validation, motion discipline, typography hierarchy, responsive/RTL behavior, anti-AI-template tells, and screenshot/design-source fidelity."+category: rnd+---++# ui-craft-checks++Use this skill as UIDesigner's final quality gate for HTML artifacts, implemented app screens, live-ready views, design-source handoffs, and UI reviews. It adapts OpenDesign craft rules into practical checks that prevent attractive but fragile UI.++This skill does not replace `ui-html-renderer` or `ui-design-review`. It tells them what must be checked before delivery.++Run the gate internally by default. Surface the full checklist only for review, handoff, QA, or when the user asks for the detailed pass/fail matrix.++## When To Use++Use this skill when:++- UIDesigner has produced or modified HTML.+- The user asks for review, polish, harden, launch-readiness, quality, accessibility, or "反 AI 味".+- A screenshot/design-source redesign needs fidelity validation.+- A form, data view, dashboard, live artifact, or interactive control is present.+- The artifact will be shared, implemented, or used as a design handoff.++For tiny text-only answers, skip this skill.++## Severity++- `P0`: Must fix before final delivery.+- `P1`: Should fix before production or stakeholder review.+- `P2`: Polish; fix when scope allows.++## P0 Gates++The artifact fails the craft pass if any P0 is present:++- **Not HTML by default**: a UI/design deliverable is only prose, PNG, SVG, Markdown, or a raw asset gallery when the user did not request that final format.+- **Source drift**: screenshot, Figma/design-source, or explicit contract structure is replaced by an unrelated dashboard, table, chart, sidebar, pricing page, or kanban board.+- **Missing critical states**: a data-fetching or data-transforming surface lacks loading, populated, empty, error, and edge/partial states.+- **Broken form validation**: required fields lack labels, helper/error text, submitted-pending behavior, or recovery from invalid input.+- **Keyboard/accessibility failure**: interactive controls are not keyboard reachable, focus-visible is absent, icon-only controls lack names, or native elements are replaced with inert divs.+- **Unsafe live data**: live-ready artifacts persist tokens, credentials, cookies, auth headers, raw provider responses, or secret-like fields.+- **Text/layout collision**: text overlaps controls, is clipped without intent, or mobile layout hides the primary action.+- **False capability claim**: the response claims Figma import, connector refresh, external-browser validation, or accessibility checks happened when they did not.++## P1 Gates++Fix or explicitly note these before handoff:++- **Contrast and focus**: body text, muted text, control borders, semantic status, and focus rings need sufficient contrast.+- **State composition**: empty states need a headline, explanation, and recovery action; errors need what happened, why, and how to recover.+- **Typography hierarchy**: hierarchy should use at least two vectors such as size, weight, spacing, color, position, or grouping; avoid both flat hierarchy and noisy hierarchy.+- **Motion discipline**: motion should explain state, space, or feedback. Avoid ambient motion in work tools. Translate/scale/rotate/parallax motion should respect reduced motion.+- **Form timing**: do not show error chrome on pristine fields; validate after blur/submit, then clear errors as the user fixes input.+- **Responsive behavior**: navigation, filters, tables, side panels, fixed boards, and action bars need a defined mobile behavior.+- **RTL/bidi readiness**: for multilingual or unknown user-generated content, prefer logical properties and isolate unknown-direction text with `dir="auto"` or `<bdi>`.+- **AI-template tells**: remove unjustified purple-blue glow gradients, generic 3-card rows, stock-placeholder imagery, oversized rounded cards everywhere, decorative blobs, and empty marketing adjectives.++## P2 Polish++Improve when time allows:++- Tighten rhythm so related items align and unrelated items separate clearly.+- Reduce redundant chips, badges, and microcopy that compete with the main task.+- Prefer borders and layout clarity over heavy shadows.+- Give the design one product-specific signature device that helps the workflow.+- Replace arbitrary icons with familiar symbols and accessible labels.++## Required Check Matrix++Before final delivery, internally verify this matrix:++```markdown+## Craft Check+- HTML default:+- Source/design fidelity:+- State coverage:+- Accessibility:+- Form behavior:+- Typography hierarchy:+- Motion:+- Responsive:+- Live/security:+- Anti-template:+- Remaining risks:+```++For simple final answers, summarize only failures and verification performed. Do not clutter the user-facing artifact with a checklist unless it is a review page, handoff, QA report, or requested by the user.++## How To Apply++1. Inspect the rendered HTML or app screen when possible.+2. Compare it to `ui-design-source` and `ui-design-contract` outputs if present.+3. Check P0 first; fix P0 rather than merely listing it.+4. Check P1/P2 according to scope.+5. If verification cannot run, say which checks were reasoned from source/HTML and which still require rendered inspection.diff --git a/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-design-contract/SKILL.md b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-design-contract/SKILL.mdnew file mode 100644index 00000000..317c878e--- /dev/null+++ b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-design-contract/SKILL.md@@ -0,0 +1,144 @@+---+ownerAgent: bcfcb4921dce+name: ui-design-contract+description_zh: "把截图、参考图、品牌材料、PRD 或“做成这种感觉”的诉求转成 UIDesigner 可复用的设计契约,覆盖 DESIGN.md 九段、source screen contract、keep/change/do-not-copy 边界和 HTML 实现交接。"+description_en: "Turn screenshots, references, brand material, PRDs, or 'make it feel like this' briefs into a reusable UIDesigner contract across a nine-section DESIGN.md shape, source screen contract, keep/change/do-not-copy boundaries, and HTML implementation handoff."+category: rnd+---++# ui-design-contract++Use this skill before rendering when the user provides screenshots, visual references, brand material, existing UI, Figma notes, PRDs, or vague taste direction. It adapts OpenDesign-style `DESIGN.md` and reference-contract discipline into UIDesigner's HTML-first workflow.++The contract is not extra ceremony. It prevents generic templates, protects the user's reference intent, and gives the HTML artifact a stable design source of truth.++When the source is a Figma link/export, design JSON, PDF, or design-tool screenshot, use `ui-design-source` first so the contract is grounded in inspectable frames, components, variables, and fidelity boundaries.++When a visual benchmark or page pattern is needed, pair this skill with `ui-reference-packs` after the contract is drafted. Skip reference packs when the screenshot, repo tokens, or existing design system already provide enough direction. The contract decides what must be preserved; reference packs only help choose style DNA and pattern boundaries.++## When To Create A Contract++Create a compact contract before HTML when any of these are true:++- The user provides a screenshot or image and asks for redesign, restoration, polishing, or page generation.+- The user says "make it feel like this", "参考这个", "做同款但不照抄", or gives brand/style references.+- The request spans more than one screen, component family, or visual system.+- The user asks for a design system, brand board, logo/identity board, or implementation handoff.+- Existing app tokens/components are unclear and the agent must infer a direction.++If the user only asks for a tiny local UI tweak with a clear existing system, a full contract can be a short inline "contract snapshot".++## Evidence Ledger++Every contract separates facts from guesses:++- `observed`: visible in the screenshot, HTML, repo, Figma notes, or rendered UI.+- `provided`: explicitly stated by the user.+- `inferred`: a reasonable choice made from context.+- `unknown`: missing information that could change the design.++Do not let inferred items override observed screenshot structure or provided user constraints.+Do not let an inaccessible Figma URL count as observed evidence. Treat it as provided context until a connector, export, screenshot, or notes are actually inspected.++## Source Screen Contract++For screenshot or image-based work, extract this before choosing a new layout:++```markdown+## Source Screen Contract+- Page type:+- Primary user job:+- Visible text:+- Major regions:+- Controls and component inventory:+- Repeated items:+- Visual hierarchy:+- Color roles:+- Typography roles:+- Density and spacing:+- Must preserve:+- May change:+- Unknown or low-confidence areas:+```++The screenshot is the contract for information architecture. Do not replace an input page, landing view, editor, chat surface, form, or simple settings screen with a dashboard, table, chart, sidebar, or operational cockpit unless those elements are visible or explicitly requested.++## DESIGN.md Shape++When a reusable visual system is needed, create or summarize a `DESIGN.md` using these nine headings:++1. `## 1. Visual Theme & Atmosphere`+2. `## 2. Color`+3. `## 3. Typography`+4. `## 4. Spacing & Grid`+5. `## 5. Layout & Composition`+6. `## 6. Components`+7. `## 7. Motion & Interaction`+8. `## 8. Voice & Brand`+9. `## 9. Anti-patterns`++Keep each section operational. Prefer constraints the next HTML pass can obey:++- Good: "single warm amber accent for primary actions; no purple-blue glow".+- Weak: "premium, modern, elegant".++## Reference Boundaries++For each reference, state:++- `Keep`: transferable qualities such as density, composition rhythm, material feel, type contrast, color temperature, interaction attitude, or component behavior.+- `Change`: product content, navigation, copy, data model, brand fit, density, or layout changes needed for the user's actual job.+- `Do not copy`: logos, protected assets, exact layouts, claims, pricing, proprietary UI, unique illustrations, or any source content the user does not own.++When references conflict, choose one recommended direction and name the tradeoff. Do not generate five unrelated moodboards unless the user asks for options.++## HTML Implementation Handoff++Before `ui-html-renderer` writes the artifact, hand off:++- Contract name or direction.+- Source of truth: screenshot, repo tokens, user brief, brand reference, or inferred system.+- Layout model.+- Token decisions: color, type, spacing, radius, border, elevation, motion.+- Component families and required states.+- Source-to-redesign mapping for every major screenshot region.+- Responsive requirements.+- Asset rules and do-not-copy constraints.+- Acceptance gates the HTML must prove.++For standalone drafts, the contract can be embedded as a visible "Design System" or "Handoff" section only when useful. For app screens, keep the artifact focused on the product experience and mention the contract in the final handoff.++## Quality Gates++Before rendering or final delivery, check:++- The main artifact type is explicit: app screen, component system, brand board, review page, deck, or other.+- Observed screenshot structure is preserved or explicitly changed.+- Inferred content is labeled and does not masquerade as source content.+- No generic template category overrides the provided reference.+- Any selected reference pack is named, justified, and rejected patterns are recorded when they could mislead the output.+- The contract names anti-patterns to avoid.+- The next HTML pass has enough concrete token and component guidance to execute without guessing.++## Output Shape++Use this compact shape in the final handoff when a separate file is not created:++```markdown+## Design Contract Snapshot+- Evidence:+- Design source:+- Direction:+- Keep:+- Change:+- Do not copy:+- Tokens:+- Components:+- Reference pack, if used:+- Rejected patterns:+- Responsive:+- Anti-patterns:+- HTML acceptance gates:+```++If the user asks for actual files or a long-running design system, write `DESIGN.md` beside the HTML artifact or inside the target project according to local conventions.diff --git a/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-design-review/SKILL.md b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-design-review/SKILL.mdnew file mode 100644index 00000000..9b300dec--- /dev/null+++ b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-design-review/SKILL.md@@ -0,0 +1,136 @@+---+ownerAgent: bcfcb4921dce+name: ui-design-review+description_zh: "评审 HTML 页面、截图或已实现界面,按严重度输出可修复问题、证据、改法和验证建议。"+description_en: "Review HTML pages, screenshots, or implemented UI with prioritized fixable findings, evidence, fixes, and validation guidance."+category: rnd+---++# ui-design-review++Use this skill when the task is to review, critique, QA, or polish an existing UI, screenshot, HTML artifact, or implemented screen.++Pair this skill with `ui-craft-checks` for launch-readiness, HTML QA, screenshot/design-source fidelity, accessibility, state coverage, forms, motion, typography, responsive behavior, live-ready artifacts, and anti-template polish.++For polish requests, do not restart the design from scratch. Inspect the current artifact, preserve the user's content and contract, then make the smallest set of high-impact fixes that improves hierarchy, responsiveness, accessibility, and visual craft.++## Review Stance++Findings first. Prioritize user-impacting issues over taste commentary:++1. Blocking workflow or comprehension issue.+2. Accessibility or responsive failure.+3. Layout, overlap, or text-fit risk.+4. Incorrect control or missing state.+5. Weak hierarchy, density, typography, or visual system.+6. Color, contrast, and semantic status risk.+7. Lower-priority polish.++Do not lead with a compliment. A short summary can come after findings.++## Follow-Up Modes++Choose the mode that matches the user's wording:++- Audit: identify the highest-impact issues.+- Critique: explain what feels generic, overdesigned, underdesigned, or inconsistent.+- Polish: edit or specify targeted improvements while preserving intent.+- Harden: repair mobile overflow, clipped text, contrast problems, missing states, broken links, and fragile layout assumptions.+- Motion: add restrained motion only where it improves feedback, state change, or comprehension.+- Live-ready: prepare the artifact for sharing with final visual QA and a short risk list.++Remove common AI-generated tells when they do not serve the product: purple-blue glow gradients, generic feature-card rows, oversized rounded panels everywhere, empty marketing adjectives, inconsistent spacing, decorative effects without job value, and missing real interaction states.++## Evidence To Inspect++Use whatever is available:++- Rendered HTML or app preview.+- Desktop and mobile screenshots.+- Source CSS/HTML/component files.+- Design system tokens.+- Figma notes, screenshot references, or existing product screens.++If a rendered view is available, review the rendered view, not only source code.++## Findings Format++Use:++```markdown+## Findings+- [P1] Title+ Evidence: ...+ Why it matters: ...+ Fix: ...++## Open Questions+- ...++## Summary+- ...+```++Severity guide:++- P0: unusable, broken, or cannot complete the main task.+- P1: serious workflow, accessibility, responsive, or comprehension problem.+- P2: noticeable quality or consistency issue.+- P3: polish.++When `ui-craft-checks` is active, map its P0/P1/P2 gates onto these findings. P0 craft failures should be fixed or called out before lower-priority taste notes.++## Review Checklist++Workflow:++- Main task is obvious.+- Primary action is clear.+- Secondary actions are discoverable but not competing.+- Repeated work is efficient.++Layout:++- No overlap or clipped text.+- Responsive behavior is intentional.+- Fixed-format elements have stable dimensions.+- Spacing supports hierarchy.++Controls:++- Correct control type.+- Hover, focus, selected, disabled, and error states exist where needed.+- Icon-only controls have accessible names.+- Menus and popovers have clear trigger and dismissal behavior.++Typography:++- Type scale matches container.+- Labels and table text are readable.+- No hero-scale type in compact panels.+- Line length and wrapping are controlled.++Color:++- Contrast is sufficient.+- Semantic colors are not reused as arbitrary accents.+- Palette is not one-note.+- Status is not color-only.++Taste:++- Design fits the domain.+- Visual signature helps the workflow.+- Generic AI UI tropes are absent or justified.++## Fix Guidance++Each finding should point to an implementable change:++- Component or file when known.+- Token adjustment if systemic.+- Layout rule or responsive breakpoint.+- State to add.+- Copy or label adjustment if it affects usability.++If the user asks you to fix the UI and a repo is available, switch to implementation after the review and verify the rendered result.diff --git a/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-design-source/SKILL.md b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-design-source/SKILL.mdnew file mode 100644index 00000000..7712d814--- /dev/null+++ b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-design-source/SKILL.md@@ -0,0 +1,129 @@+---+ownerAgent: bcfcb4921dce+name: ui-design-source+description_zh: "处理 Figma 链接/导出、设计稿截图、PDF、JSON、现有 HTML 或设计说明,把来源抽取成 frame map、组件/变量/资产/交互清单、保真边界和 UIDesigner HTML 实现交接;没有真实访问能力时不假装已导入。"+description_en: "Handle Figma links/exports, design screenshots, PDFs, JSON, existing HTML, or design notes by extracting a frame map, components/variables/assets/interactions, fidelity boundaries, and UIDesigner HTML implementation handoff; never pretend a design source was imported when access is unavailable."+category: rnd+---++# ui-design-source++Use this skill when the user provides Figma material, design-export files, screenshots of design tools, PDFs, JSON, existing HTML, or asks for design-to-HTML/code fidelity. It adapts OpenDesign/Figma handoff discipline for UIDesigner without requiring a live Figma runtime.++This skill turns design-source evidence into a compact handoff for `ui-design-contract`, `ui-reference-packs`, `ui-design-system`, and `ui-html-renderer`.++## Access Rules++- If a Figma connector, MCP, plugin API, or exported file is actually available, inspect it with the available tool or file reader.+- If the user only provides a Figma URL and no available Figma access exists, ask for a screenshot/export or continue only from visible notes. Do not claim "Figma imported", "frames inspected", or "variables read".+- If the design source is an image or PDF, treat it like a screenshot: extract what is visible, label uncertain text/spacing, and preserve information architecture.+- If the design source is HTML/CSS, inspect the rendered surface when possible and use source files only to clarify tokens/components.++## Source Intake++Classify the source:++- `figma_url`: URL or file key, not enough by itself unless a connector/tool is available.+- `figma_export_json`: nodes, components, variables, styles, constraints, or plugin export.+- `design_screenshot`: frame image, prototype screenshot, app screenshot, or reference image.+- `design_pdf`: exported specs, deck, or annotated design handoff.+- `existing_html`: current artifact, app page, or prototype.+- `design_notes`: Markdown/text PRD, redlines, specs, or designer comments.++For each source, record:++- Path/link/attachment identity.+- What was actually inspectable.+- Confidence: `high`, `medium`, or `low`.+- Missing access or missing data.++## Extract Design Source Map++Before rendering, produce this compact map:++```markdown+## Design Source Map+- Source type:+- Frames/screens:+- Primary frame:+- Visible copy:+- Layout regions:+- Components:+- Variants/states:+- Variables/tokens:+- Assets/icons/images:+- Interactions/prototype notes:+- Responsive constraints:+- Implementation targets:+- Fidelity requirements:+- Unknowns:+```++For Figma-like sources, look specifically for:++- Frame size, grid, auto-layout direction, gaps, padding, constraints.+- Component instances, variants, slot/content overrides, states.+- Variables/styles for color, typography, radius, elevation, spacing, effects.+- Text styles and localization risks.+- Exportable assets and which assets must be replaced or recreated.+- Prototype links, overlays, interactions, transitions, and disabled/error states.++## Fidelity Modes++Choose one mode and state it:++- `exact`: reproduce the supplied frame as closely as HTML allows; preserve layout, text, spacing, and component structure.+- `adaptive`: keep the design language and hierarchy but make it responsive, accessible, and implementation-friendly.+- `systemize`: extract tokens/components from the design and build a reusable HTML design system sample.+- `redesign`: use the design as evidence, then intentionally change structure according to user goals.++If the user says "根据设计稿实现", "Figma to HTML", "1:1", or "保真", default to `exact` unless responsive/product constraints require `adaptive`.++## Component Mapping++Map design components to implementation components:++```markdown+## Component Mapping+- Design component:+- HTML/app component:+- Props/content:+- States:+- Tokens used:+- Accessibility notes:+- Responsive behavior:+- Fidelity risk:+```++Use local app components when implementing in a repo. For standalone HTML, define semantic HTML/CSS components with the same roles and states.++## Handoff To Other Skills++- Send evidence and unknowns to `ui-design-contract`.+- Use `ui-reference-packs` only if the source lacks a clear style system or the user asks for a named style direction.+- Send tokens/components to `ui-design-system`.+- Send fidelity mode, frame map, and source-to-HTML mapping to `ui-html-renderer`.+- Use `ui-design-review` after rendering to check visual drift, responsive behavior, and state coverage.++## Safety And Ownership++- Do not copy protected logos, proprietary illustrations, or third-party brand assets unless the user owns or supplied them for this work.+- Do not persist access tokens, cookies, API keys, raw provider responses, or private metadata in HTML or handoff files.+- Do not reveal internal source paths in user-facing copy unless the path is the deliverable location or needed for debugging.++## Output Shape++When using this skill, include this handoff when useful:++```markdown+## Design Source Handoff+- Source inspected:+- Access level:+- Fidelity mode:+- Frame/source map:+- Component mapping:+- Token mapping:+- Assets:+- Unknowns:+- HTML acceptance gates:+```diff --git a/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-design-system/SKILL.md b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-design-system/SKILL.mdnew file mode 100644index 00000000..9244c154--- /dev/null+++ b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-design-system/SKILL.md@@ -0,0 +1,143 @@+---+ownerAgent: bcfcb4921dce+name: ui-design-system+description_zh: "把产品目标或现有界面转成可实现的 UI 系统,覆盖 token、组件、shadcn 风格映射、设计系统审查和实现交付。"+description_en: "Turn product goals or existing screens into implementable UI systems across tokens, components, shadcn-style mapping, design-system review, and implementation handoff."+category: rnd+---++# ui-design-system++Use this skill when creating, extending, or auditing a product UI system. It adapts Better Design-style design-system discipline without requiring an external runtime package.++Pair this skill with `ui-design-contract` when the user provides references, screenshots, brand material, or asks for a reusable direction. The contract defines what the system must preserve; this skill turns it into tokens and components.++When `ui-reference-packs` selects a design-system pack, treat it as advisory style DNA. Translate it into the local token model and component map; do not copy named-brand assets, exact layouts, or proprietary product chrome.++## Design System Job++A UI system is not a moodboard. It must define reusable decisions that help the product ship:++- Who the product serves and what workflow the UI optimizes.+- What layout model organizes repeated work.+- Which component families exist, with variants and states.+- Which tokens drive typography, color, spacing, radius, borders, elevation, motion, and density.+- Which rules prevent one-off styling and component drift.+- How the design becomes HTML or target-app implementation.++For reusable systems, express the result in a `DESIGN.md`-compatible shape when useful:++- Visual theme and atmosphere.+- Color.+- Typography.+- Spacing and grid.+- Layout and composition.+- Components.+- Motion and interaction.+- Voice and brand.+- Anti-patterns.++## Context To Extract++Before designing, inspect or infer:++- Product domain: operational tool, creative app, developer tool, finance, education, commerce, content, or consumer.+- Main workflow: create, review, compare, monitor, configure, analyze, search, or collaborate.+- Existing UI framework and components.+- Selected reference pack, if any, plus rejected patterns from `ui-reference-packs`.+- For screenshots or image references: visible copy, page type, major regions, controls, repeated items, and what content is unknown.+- Current token source: CSS variables, Tailwind config, design-token files, component library, or ad hoc CSS.+- Navigation model: sidebar, top nav, split pane, command palette, tabs, wizard, canvas, or feed.+- Data density: sparse editorial, balanced product UI, or dense operational cockpit.+- Constraints: mobile, desktop, accessibility, brand, localization, dark mode, and real data variability.++For screenshot-based redesigns, the source screen is the contract. Preserve its workflow, content groups, and component families unless the user explicitly asks to change them. Do not replace a landing/input page with a dashboard, table, chart, sidebar, or operational cockpit simply because the user selected a broad page category.++## Token Model++Define tokens by role, not by vague color or size names.++Typography:++- `display`: only for true page or hero titles.+- `title`: screen or panel headings.+- `body`: readable paragraph or field content.+- `label`: form labels, metadata, table headers.+- `data`: numbers, metrics, monospace identifiers, code-like content.+- `caption`: secondary notes and timestamps.++Color:++- `bg`: page background.+- `surface`: panels, controls, rows, inputs.+- `surface-raised`: menus, popovers, dialogs.+- `text`: primary content.+- `text-muted`: metadata, placeholders, helper text.+- `border`: dividers and component outlines.+- `accent`: primary action or selection.+- `danger`, `warning`, `success`, `info`: semantic statuses only.++Spacing and density:++- Use a compact scale for operational products, usually 4/8/12/16/24/32.+- Reserve large whitespace for reading or marketing, not dashboards or repeated workflows.+- Keep table rows, forms, filters, and sidebars dense but scannable.++Shape and elevation:++- Default radius should be 8px or less unless the existing system says otherwise.+- Use borders and contrast before large shadows.+- Do not stack cards inside cards. Use full-width sections, panes, rows, or repeated item cards.++Motion:++- Use motion to explain state changes, reveal hierarchy, or maintain spatial continuity.+- Avoid ambient motion in work tools unless it is part of the domain.++## Component Map++Map UI to components before styling:++- Navigation: sidebar, top bar, breadcrumbs, tabs, command menu.+- Action controls: primary button, secondary button, icon button, split button, menu item.+- Data controls: table, grid, list, filters, sort, search, pagination, batch actions.+- Forms: input, textarea, select, combobox, checkbox, radio, toggle, slider, stepper.+- Feedback: toast, inline alert, empty state, loading skeleton, error state, validation message.+- Surfaces: panel, drawer, modal, popover, tooltip, detail pane.+- Content: cards only for repeated items or framed tools, not as a page-section default.++For each component, define variants, states, content limits, keyboard behavior, and responsive behavior.++## Handoff Shape++For design-system work, return or implement:++```markdown+## System Direction+- Product type:+- Design priority:+- Layout model:+- Density:+- Tone:++## Tokens+- Typography:+- Color:+- Spacing:+- Radius/border/elevation:+- Motion:++## Components+- Navigation:+- Data display:+- Forms:+- Feedback:+- Overlays:++## HTML Design Draft+- File or artifact:+- Viewports represented:+- States represented:+```++If the user asked for a design draft, pair this with `ui-html-renderer`. The system is incomplete until it is visible in HTML.diff --git a/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-html-renderer/SKILL.md b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-html-renderer/SKILL.mdnew file mode 100644index 00000000..c10c3c31--- /dev/null+++ b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-html-renderer/SKILL.md@@ -0,0 +1,188 @@+---+ownerAgent: bcfcb4921dce+name: ui-html-renderer+description_zh: "作为 UIDesigner 的默认交付格式守门员,用 HTML 呈现设计稿、改版稿、组件样例、设计系统、logo/字标、品牌视觉和 review,除非用户明确要求其他格式。"+description_en: "Guard UIDesigner's default delivery format by rendering drafts, redesigns, component samples, design systems, logos/wordmarks, visual identity, and reviews as HTML unless the user explicitly requests another format."+category: rnd+---++# ui-html-renderer++Use this skill for every UIDesigner design deliverable unless the user explicitly requests another final format. The output must be visible in HTML by default. Markdown is acceptable for rationale, but not as the final artifact unless the user asks for text only.++Skip this skill for meta work about the agent itself: analysis, options, debugging prior runs, prompt/skill review, or planning can be answered in prose unless the user asks for an HTML artifact.++Before final delivery, pair with `ui-craft-checks` for any non-trivial HTML artifact, implemented screen, design-source handoff, live-ready view, form, dashboard, or interactive surface. Fix P0 craft failures before final response.++## Contract Input++When `ui-design-contract` has been used, treat its contract snapshot or `DESIGN.md` as the source of truth for the HTML pass:++- Apply any `ui-design-source` handoff as fidelity input: preserve frame map, visible copy, component mapping, tokens, and the chosen fidelity mode.+- Follow the named visual direction, token roles, component families, anti-patterns, and acceptance gates.+- Apply any `ui-reference-packs` selection as style guidance only: translate its density, type rhythm, color roles, and component behavior into original HTML.+- Preserve observed screenshot structure before applying inferred style changes.+- Carry forward keep/change/do-not-copy boundaries; do not embed protected logos, copied layouts, or proprietary assets unless the user owns and supplied them.+- If the contract has unknowns, either label them in the artifact or ask one focused question before rendering when the missing answer would change the page structure.+- If the contract conflicts with a generic artifact type such as dashboard, kanban, or pricing page, the contract wins unless the user explicitly overrides it.+- If a selected reference pack conflicts with the contract, existing app tokens, or visible screenshot structure, the pack loses.++## Rendering Rule++Default final output is HTML for design artifacts. If the user asks for any of these and does not explicitly request another final format, produce HTML:++- Design brief.+- UI design.+- Redesign.+- Mockup.+- Page design.+- Dashboard design.+- Component set.+- Design-system sample.+- Logo design.+- App icon.+- Wordmark.+- Brand mark.+- Visual identity.+- Figma or screenshot to UI handoff.+- Screenshot or image-based redesign.+- UI review or visual audit.+- Visual polish proposal.++Valid HTML outputs:++- A self-contained HTML artifact/file when no target repo implementation is requested.+- A rendered target app screen when the user asks to implement inside an existing app.+- An HTML review page or annotated HTML artifact for reviews.++Other final formats such as standalone images, SVG files, PDFs, Markdown-only strategy, or code-only patches are valid only when the user explicitly asks for them. Do not deliver only prose, standalone images, or a raw asset gallery by default.++Do not force HTML for non-deliverable discussion, such as "why did the agent do that", "list possible integrations", "analyze this workflow", or "first give me a plan".++## HTML Artifact Requirements++The HTML draft should be self-contained unless the repo already has an asset pipeline:++- Inline CSS for standalone drafts.+- No remote runtime dependencies.+- Realistic content and realistic data.+- Representative empty, loading, error, selected, and disabled states where relevant.+- Desktop and mobile responsive behavior.+- Stable dimensions for repeated items, toolbars, grids, cards, counters, boards, and fixed-format widgets.+- Accessible labels for controls and icons.+- Visible focus states.+- Text that wraps, truncates, or scales deliberately without overlap.++Use semantic HTML where practical. Add lightweight JavaScript only for preview interactions such as tabs, filters, menus, theme toggles, or sample state changes.++## What To Render++For product screens:++- App shell, navigation, primary content, secondary panels, and primary action.+- Main workflow, not a marketing wrapper.+- Data or content density that matches the product type.+- Key states in-place or in a state gallery section.+- Pattern structures such as dashboard, kanban, pricing, mobile-frame, wireframe, or live-artifact must be triggered by the user or source contract before use.++For design-source or Figma handoff:++- Do not claim Figma import, frame inspection, variable extraction, or component mapping unless `ui-design-source` actually inspected that evidence.+- Respect the fidelity mode: exact, adaptive, systemize, or redesign.+- Include a compact source-to-HTML mapping when exact or adaptive fidelity matters.+- Label sample or inferred content if the source only supplied partial frames.++For live-ready artifacts:++- Use `ui-live-artifact` when refresh, sync, recurring updates, connector data, or auditable data provenance is requested.+- A live-ready HTML preview must still render now; do not depend on a missing daemon/runtime to show the first artifact.+- Include loading, stale, failed-refresh, empty, and last-updated states where relevant.+- Do not persist secrets, raw provider responses, auth headers, cookies, or token-like fields in generated HTML or JSON.++For dashboards:++- Realistic metrics, tables, filters, charts, trends, alerts, and drilldown affordances.+- Charts can use SVG or CSS. Make them inspectable and labeled.++For component systems:++- Token swatches.+- Type scale.+- Buttons and controls with states.+- Form fields with validation.+- Table/list rows.+- Feedback states.+- Dialog/drawer/popover examples when needed.++For logo or identity drafts:++- Mark variants and wordmark lockups.+- Light, dark, monochrome, and small-size treatments.+- App icon or favicon preview when relevant.+- Color tokens, spacing/sizing rules, and usage examples.+- A compact rationale for the visual direction.+- Raster images may be embedded as preview assets, but the final deliverable must be the HTML brand board or design draft, not an image-only gallery.++For redesigns:++- Show the redesigned screen, not only a before/after text list.+- If useful, include a compact issue-to-fix annotation layer.++For screenshot or image-based redesigns:++- Treat the image as the source of truth for page type, layout regions, visible copy, component inventory, and hierarchy.+- Before writing HTML, extract a source screen contract: visible text, major regions, controls, repeated items, density, color roles, and unknown areas.+- Preserve the source screen's information architecture unless the user explicitly asks to change the product, page type, or workflow.+- If a later form answer conflicts with the screenshot, preserve the screenshot or ask one clarification before rendering.+- Do not invent dashboards, tables, charts, metrics, operational records, sidebars, or fake domain data unless they are visible in the image or explicitly requested.+- When text or controls are hard to read, use available OCR/image inspection tools. If confidence is still low, label unknown content or ask for context instead of filling gaps with a generic SaaS template.+- Include a source-to-redesign mapping in the HTML or final handoff when the redesign changes structure.++For reference-driven or brand-driven drafts:++- Render the design contract into visible UI decisions, not a moodboard of adjectives.+- Use the contract's token roles and anti-patterns before choosing decorative effects.+- Include brand or design-system sections only when the task is a brand board, identity board, design system, or handoff. For product screens, keep the first viewport focused on the usable interface.++For reviews:++- Render findings in an HTML review page when no existing app screen is being modified.+- Prioritize concrete issues and show affected areas, severity, fix direction, and expected outcome.+- Include screenshots or image assets only as evidence inside the HTML review, not as the whole deliverable.++## Visual Constraints++- Do not use generic hero pages for apps, tools, or dashboards.+- Do not create a split marketing hero unless the request is a landing page.+- Do not put cards inside cards.+- Do not use decorative orbs, blobs, or background bokeh.+- Do not scale font size with viewport width.+- Do not use negative letter spacing.+- Keep card radius 8px or less unless the existing system requires otherwise.+- Use icons for familiar actions rather than text-filled rounded rectangles.++## Verification++When possible:++- Inspect the Orkas embedded artifact preview, generated HTML/CSS/JS, DOM structure, screenshots, or equivalent non-external viewport checks.+- Do not open the system browser by default. Use an external browser only when the user explicitly asks for it or the target app workflow already requires an external browser.+- Check desktop and mobile widths.+- Inspect screenshots for blank areas, overlap, clipped text, broken assets, and unreadable contrast.+- Interact with tabs, menus, toggles, filters, and primary actions if present.+- Run the `ui-craft-checks` matrix for HTML default, source/design fidelity, state coverage, accessibility, forms, typography, motion, responsive behavior, live/security, and anti-template tells.++If verification cannot run, state that clearly and list the checks the artifact was designed to satisfy.++## Delivery++Finish with:++- HTML file or app screen path.+- Viewports represented.+- States represented.+- Interactions included.+- Verification performed.+- Known risks.++For ordinary final responses, summarize only verification performed, blocking craft failures, and known risks. Include the full craft matrix only for review, handoff, QA, or when the user asks for it.diff --git a/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-live-artifact/SKILL.md b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-live-artifact/SKILL.mdnew file mode 100644index 00000000..86c8362a--- /dev/null+++ b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-live-artifact/SKILL.md@@ -0,0 +1,100 @@+---+ownerAgent: bcfcb4921dce+name: ui-live-artifact+description_zh: "为 UIDesigner 创建或规划可刷新、可审计、数据源驱动的 HTML 产物;适用于 live dashboard、可刷新报告、同步视图、连接器数据视图,并约束 template/data/provenance 文件、安全脱敏和静态降级。"+description_en: "Create or plan refreshable, auditable, data-backed HTML artifacts for UIDesigner; use for live dashboards, refreshable reports, synced views, and connector data views with template/data/provenance files, safe redaction, and static fallback rules."+category: rnd+---++# ui-live-artifact++Use this skill when the user asks for a live dashboard, refreshable report, synced view, recurring data artifact, connector-backed UI, auditable status page, or data-backed HTML that should remain useful after the first render.++Do not use this for ordinary one-off mockups, static redesigns, image-to-HTML conversion, or visual polish. In those cases `ui-html-renderer` is enough.++## Intent Gate++Choose the mode before creating files:++- `static_html`: one-off HTML design or mockup. No refresh contract.+- `live_ready_html`: HTML plus data/provenance contract that can later be wired to refresh, but no live runtime registration happens now.+- `connected_live`: only when Orkas exposes an actual connector/runtime for the requested source in the current context.++If the request is ambiguous, ask one short question: "Should this be refreshable/live, or just a static HTML design?"++## Required Source Questions++Resolve:++- Audience and decision the view supports.+- Data source: local file, repo data, connector, manual sample, or unknown.+- Freshness expectation: manual, on open, hourly/daily, or event-driven.+- Refresh owner: user, connector, scheduled job, or future integration.+- Privacy level: public, workspace, sensitive, or regulated.++Do not ask for secrets. If a connector is not available, ask the user to connect/provide an export rather than requesting API keys.++## File Contract++For `live_ready_html`, create or describe these files when a file deliverable is requested:++- `index.html`: rendered preview that works now in the Orkas embedded artifact surface.+- `template.html`: optional source template when the user wants future refresh wiring.+- `data.json`: compact normalized preview data only.+- `artifact.json`: optional metadata for title, description, refresh mode, view type, and safe source descriptors.+- `provenance.json`: optional safe summary of source, transform, timestamp, confidence, and omitted sensitive fields.++If no file workspace is available, embed the same contract in the HTML artifact and final handoff.++## Data Rules++- Store only fields needed by the UI preview.+- Summarize or sample large lists; do not persist raw provider responses.+- Normalize display-ready values, units, timestamps, status labels, and chart series.+- Keep `data.json` small enough to inspect by eye.+- Mark sample data clearly when the real source is unavailable.++Avoid these key names anywhere in persisted JSON unless they are non-sensitive user-facing labels: `token`, `secret`, `credential`, `password`, `cookie`, `authorization`, `headers`, `raw`, `rawResponse`, `payload`, `body`.++## HTML Requirements++The preview must still be a good UIDesigner artifact:++- Show refresh status, last updated time, data freshness, and empty/error states.+- Include source/provenance cues only where they help trust; do not clutter the main workflow.+- Separate UI actions from data refresh actions.+- Make stale, partial, loading, and failed-refresh states visible.+- Use `ui-design-contract`, `ui-reference-packs`, `ui-design-system`, and `ui-html-renderer` for visual quality.++## Connector Boundaries++- Use available Orkas connector tools or local files when they exist.+- Do not call raw third-party APIs when a platform connector/wrapper should own auth.+- Do not store OAuth tokens, API keys, cookies, auth headers, raw HTTP envelopes, or secret-like metadata in generated files.+- If no connector exists, produce `live_ready_html` with sample/exported data and note the missing integration.++## Static Fallback++When live wiring is not possible, do not fail the design:++- Produce a static HTML preview with realistic sample data.+- Include a "Refresh contract" section in the handoff or artifact metadata.+- State which source fields need to be connected later.+- Keep the design ready for implementation without implying refresh already works.++## Output Shape++Use this handoff when helpful:++```markdown+## Live Artifact Handoff+- Mode:+- Data source:+- Freshness:+- Files:+- Data schema:+- States represented:+- Security exclusions:+- Missing integration:+- HTML acceptance gates:+```diff --git a/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-reference-packs/SKILL.md b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-reference-packs/SKILL.mdnew file mode 100644index 00000000..1f268b8d--- /dev/null+++ b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-reference-packs/SKILL.md@@ -0,0 +1,70 @@+---+ownerAgent: bcfcb4921dce+name: ui-reference-packs+description_zh: "为 UIDesigner 按需选择中性的设计系统参考原型和页面模式边界;用于参考图/品牌/弱视觉系统场景中选风格基因,并避免误套 dashboard/kanban/pricing 等模板。"+description_en: "Select conditional neutral design-system reference archetypes and page-pattern boundaries for UIDesigner; use when references, brand material, or weak visual systems need style DNA while preventing accidental dashboard/kanban/pricing template use."+category: rnd+---++# ui-reference-packs++Use this skill after `ui-design-contract` only when UIDesigner needs a visual-system reference, product pattern, or style benchmark. It adapts OpenDesign's design-system and template catalogue into a small routed reference layer for HTML-first UI work.++This skill does not copy OpenDesign templates or brand systems. It helps choose a direction, then `ui-design-system` and `ui-html-renderer` turn that direction into original UI.++If `ui-design-source` has produced a frame/component handoff, use that handoff as stronger evidence than any reference pack. If an existing app already has clear tokens and components, skip this skill unless the user asks for a new style direction. If `ui-live-artifact` has not classified the task as live-ready or connected-live, do not select the live-artifact pattern.++## Resource Map++Read only the relevant reference:++- `references/design-system-packs.md` — curated visual system packs inspired by OpenDesign `design-systems/`.+- `references/pattern-library.md` — page and artifact pattern boundaries inspired by OpenDesign `design-templates/`.++## Selection Workflow++1. Decide whether a pack is needed.+ - Use a pack when the user supplied references/brand material, asked for a style benchmark, the product has no clear visual system, or a broad pattern label must be accepted/rejected explicitly.+ - Skip packs when the screenshot or repo system already gives enough visual direction.+2. Start from the design contract.+ - Screenshot/page structure, user-provided constraints, and repo tokens outrank reference packs.+ - If no contract exists for a reference-heavy task, create one with `ui-design-contract` first.+3. Choose at most one primary design-system pack.+ - Optionally add one secondary influence for typography, density, or motion.+ - Do not blend many archetypes; blended taste turns generic quickly.+ - Use neutral archetype IDs in handoff notes instead of brand names.+4. Choose a page pattern only when the contract or user explicitly supports it.+ - Dashboard, kanban, pricing, mobile-frame, wireframe, and live-artifact patterns have narrow triggers.+ - A pattern is a structural permission, not a mandate.+5. Convert the chosen pack into UIDesigner tokens.+ - Color roles, type roles, spacing, radius, border, elevation, motion, and component behavior must be expressed in the local HTML/app system.+ - Do not copy logos, exact layouts, product claims, screenshots, or proprietary components.+6. Record the selection in the handoff.+ - Name the selected pack.+ - Explain why it fits.+ - State what was rejected and why.+ - Include any trigger guardrails, especially when not using a dashboard/kanban/pricing template.++## Hard Guardrails++- Do not use a reference pack to override visible screenshot information architecture.+- Do not infer "dashboard" from "business", "admin", "analytics-looking", or a form category unless metrics/charts/tables/monitoring are visible or requested.+- Do not use named brands as imitation. Borrow controllable qualities such as density, typography rhythm, interaction attitude, and role structure.+- Treat any brand/source provenance as internal inspiration. In user-facing summaries, use the neutral archetype ID and concrete token decisions.+- Do not mention OpenDesign in the user-facing artifact unless provenance or implementation notes matter.+- Do not fetch or load every reference pack. Pick the smallest relevant reference file and continue.++## Output Shape++When using this skill, include this compact note in the internal handoff or final summary when helpful:++```markdown+## Reference Pack Choice+- Primary pack:+- Secondary influence:+- Pattern used:+- Why it fits:+- Rejected patterns:+- Token translation:+- Copy/brand safety:+```diff --git a/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-reference-packs/references/design-system-packs.md b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-reference-packs/references/design-system-packs.mdnew file mode 100644index 00000000..a6c4b574--- /dev/null+++ b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-reference-packs/references/design-system-packs.md@@ -0,0 +1,48 @@+# Curated Design-System Packs++These packs are compact UIDesigner references inspired by OpenDesign's `design-systems/` catalogue. They are neutral archetypes, not templates, and must not be used to imitate a named brand. Use them to translate a contract into token roles, component behavior, density, and visual attitude.++## Selection Rules++- Pick one primary pack that matches the user's product job.+- Add one secondary influence only when it clarifies a specific axis, such as editorial type, developer precision, or mobile tactility.+- Existing product tokens and screenshot structure outrank every pack.+- If the user asks for "like X", map the request to the closest neutral archetype, preserve controllable qualities, and avoid protected assets, exact layout, logos, slogans, and distinctive product claims.++## Packs++| Pack | Use when | Design DNA | Avoid when |+| --- | --- | --- | --- |+| `product-application` | General SaaS app screens, settings, account workflows, lightweight admin tools. | Balanced density, clear controls, neutral surfaces, practical hierarchy, 4/8/12/16 spacing. | The source is a homepage/input screen with no app shell, or a more specific pack fits. |+| `enterprise-operations` | B2B workflows, compliance, operations, approval, procurement, CRM, internal tools. | Conservative contrast, predictable navigation, form/table strength, restrained motion, stable state handling. | Consumer, playful, editorial, or highly visual brand pages. |+| `dense-enterprise-crud` | Data-dense Chinese/enterprise CRUD, configuration, tables, filters, admin consoles. | Compact controls, clear table affordances, status chips, dense form groups, 4/8 grid. | Sparse landing pages, creative products, or screenshot structures without tables/forms. |+| `analytics-monitoring` | Explicit dashboards, analytics, monitoring, KPI walls, incident/ops views. | Metrics, trend regions, filters, chart labeling, drilldown affordances, semantic status. | Any task where dashboard elements are not visible or requested. |+| `project-workflow` | Issue tracking, project management, roadmap, developer-product planning, command-driven workflows. | Calm dark/light neutrals, sharp hierarchy, compact rows, keyboard-friendly navigation, minimal decoration. | Marketing pages, finance dashboards, or broad consumer apps. |+| `developer-code` | Developer tools, repositories, code review, CI, API docs, package/project surfaces. | System fonts, monospace where meaningful, borders over shadows, readable lists, status labels. | Non-technical consumer products or highly branded campaign pages. |+| `developer-platform` | Deployment, cloud, developer platform, build logs, infra/project dashboards. | Minimal neutrals, code/console affordances, tight type, precise cards and tables. | Warm consumer brands or dense enterprise CRUD needing many form controls. |+| `creative-canvas` | Design/canvas tools, creative collaboration, component libraries, prototyping surfaces. | Canvas-first layout, toolbars, panels, layered controls, colorful accents used sparingly. | Non-creative app screens where canvas metaphors would distract. |+| `docs-knowledge` | Docs, wiki, knowledge base, notes, lightweight databases, content organization. | Warm neutrals, readable blocks, inline controls, calm hierarchy, low-chrome UI. | Dense monitoring, trading, or task-critical operations. |+| `cross-platform-material` | Android-like apps, cross-platform component systems, form-heavy surfaces. | Familiar component taxonomy, elevation rules, clear state layers, accessible control defaults. | Products with a strong existing custom system or desktop enterprise density needs. |+| `consumer-premium` | Consumer product pages, mobile/desktop app surfaces, premium hardware/software storytelling. | Image-led clarity, large type only where justified, restrained chrome, tactile motion. | Internal tools, CRUD dashboards, or anything where merchandising would reduce task efficiency. |+| `fintech-trust` | Payments, fintech onboarding, developer docs, commercial SaaS with trust and conversion needs. | Crisp hierarchy, confident accent use, trust cues, code/API affordances, strong section rhythm. | Regulated finance dashboards needing dense tabular risk scanning. |+| `focused-minimal` | Utility tools, focused settings, simple product flows, content-light apps. | Few colors, strong alignment, quiet surfaces, clear type roles, very limited ornament. | Data-heavy workflows needing many comparison affordances. |+| `professional-clean` | Broad professional UI where the existing brand is weak and the safest path is clarity. | Neutral palette, 8pt rhythm, familiar controls, conservative spacing, low visual risk. | Requests for distinctive brand expression or explicit visual experimentation. |+| `editorial-story` | Long-form content, reports, landing/storytelling, magazine-like product narratives. | Strong type contrast, measured whitespace, image/caption rhythm, narrative hierarchy. | Repeated operational workflows or compact tool surfaces. |+| `experimental-bold` | Posters, campaign microsites, experimental portfolios, strong attitude pieces. | Bold type, high contrast, visible grid, intentionally raw surfaces. | Enterprise, accessibility-sensitive, compliance-heavy, or daily-use tools unless explicitly requested. |++## Token Translation++Translate pack DNA into UIDesigner roles:++- Color: `bg`, `surface`, `surface-raised`, `text`, `text-muted`, `border`, `accent`, semantic roles, chart roles.+- Type: `display`, `title`, `body`, `label`, `data`, `caption`.+- Spacing: compact 4/8 scale for tools; 8pt editorial rhythm for content/marketing.+- Shape: default radius 8px or less unless the pack's product context requires sharper or softer controls.+- Motion: state-change motion first; ambient motion only for brand/storytelling.++## Rejection Examples++- Source image is a chat/input homepage: reject `analytics-monitoring`, `dense-enterprise-crud`, and `project-workflow` unless the user asks to redesign it into a workspace.+- User asks for a pricing page: pick a pricing pattern first, then choose `fintech-trust`, `developer-platform`, `professional-clean`, or `editorial-story` by brand tone.+- User asks for a developer tool settings page: `developer-code` or `developer-platform` fits better than generic `product-application`.+- User gives a brand screenshot with a unique logo: keep density, color temperature, and rhythm; do not copy the mark or exact composition.diff --git a/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-reference-packs/references/pattern-library.md b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-reference-packs/references/pattern-library.mdnew file mode 100644index 00000000..46ce78f6--- /dev/null+++ b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-reference-packs/references/pattern-library.md@@ -0,0 +1,137 @@+# Pattern Library Boundaries++These page patterns are inspired by OpenDesign's `design-templates/` catalogue. They are structural references, not default templates. Use a pattern only when the user request, source screenshot, or design contract clearly permits it.++## Pattern Selection++1. Identify the artifact type from the design contract.+2. Check whether the user's words or visible source structure match a trigger.+3. If a pattern is not triggered, do not use it just because it is visually polished.+4. If multiple patterns match, choose the one closest to the primary user job and keep the rest as optional follow-up states.++## Patterns++### `dashboard`++Use when:++- The user says dashboard, analytics, monitoring, KPI, admin metrics, ops wall, report view, or performance overview.+- The screenshot visibly contains metrics, charts, filters, tabular monitoring, or operational summaries.++Expected structure:++- App shell or top toolbar, KPI summaries, chart or trend region, filters, detailed table/list, alerts or annotations, drilldown affordances.++Do not use when:++- The source is a homepage, prompt input, landing view, editor, login, profile, form, chat, or simple settings page without metrics.++### `kanban-board`++Use when:++- The user says kanban, task board, sprint board, pipeline, stages, backlog, doing, review, done.+- The screenshot visibly contains columns of cards or status lanes.++Expected structure:++- Columns with stable widths, draggable-card affordance, status counts, owner/priority metadata, add/filter/search actions.++Do not use when:++- The task is a generic project page, dashboard, or document organizer without explicit columns.++### `pricing-page`++Use when:++- The user says pricing, plans, tiers, billing page, subscription comparison, packages, checkout plan selector.+- The artifact is clearly a marketing/commercial page.++Expected structure:++- Header, plan cards, feature comparison, FAQ, trust/guarantee or billing interval controls.++Do not use when:++- The task is internal billing settings, invoice management, or finance operations; those are app workflows, not pricing pages.++### `mobile-app`++Use when:++- The user asks for mobile app, iOS, Android, phone screen, app UI, mobile onboarding, or a screenshot is mobile-shaped.++Expected structure:++- One primary job per screen, mobile safe-area constraints, reachable primary action, tab/nav only when the workflow needs it.++Do not use when:++- The request is responsive web only. Responsive mobile behavior is not the same as a framed mobile app concept.++### `web-prototype`++Use when:++- The user asks for a web app/page prototype, landing page, product page, workflow demo, or interactive HTML concept.++Expected structure:++- First viewport shows the actual experience, not a generic marketing shell, unless it is a landing page.+- Sections follow the user's product job and source contract.++Do not use when:++- The user asked to implement inside an existing repo screen; use that app's structure instead.++### `wireframe-annotated`++Use when:++- The user asks for wireframe, lo-fi, redline spec, annotated layout, engineering handoff, or early IA exploration.++Expected structure:++- Greyscale structure, numbered pins, concise notes, responsive layout intent, not final visual styling.++Do not use when:++- The user asked for final visual design or polished HTML; wireframes can be a section only if explicitly requested.++### `live-artifact`++Use when:++- The user asks for refreshable, synced, recurring, connector-backed, live dashboard/report, auditable data view, or reusable artifact.+- `ui-live-artifact` has classified the mode as `live_ready_html` or `connected_live`.++Expected structure:++- Data source/provenance surface, refresh status, template/data separation, safe placeholder states, no credentials in files.++Do not use when:++- The user only wants a one-off mockup, static redesign, image-to-HTML conversion, or screenshot polish.+- No refresh/data-source/provenance need is present. Use ordinary HTML instead.++### `brand-board`++Use when:++- The user asks for logo, wordmark, icon, brand identity, visual identity, style tile, or design system board.++Expected structure:++- Mark/wordmark variants, color tokens, type samples, spacing/sizing, usage examples, do/don't notes, HTML presentation.++Do not use when:++- The user asks for raw image generation only; route to the image agent unless UIDesigner is explicitly asked to present it as HTML.++## Conflict Handling++- Screenshot contract beats pattern trigger unless the user explicitly asks to transform the screen type.+- User-selected form fields from the launch UI are weaker than attached screenshots and explicit request text.+- If a broad category says "dashboard" but the screenshot is a prompt/input homepage, ask one clarification or preserve the screenshot.+- If the artifact type remains ambiguous after contract extraction, choose the simplest structure that preserves visible information architecture.diff --git a/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-taste/SKILL.md b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-taste/SKILL.mdnew file mode 100644index 00000000..93fc2913--- /dev/null+++ b/resources/builtin/marketplace/agents/bcfcb4921dce/skills/ui-taste/SKILL.md@@ -0,0 +1,87 @@+---+ownerAgent: bcfcb4921dce+name: ui-taste+description_zh: "提升 UI 审美判断,覆盖反模板、视觉密度、动效强度、领域化视觉签名和高质量界面 critique。"+description_en: "Improve UI taste judgment across anti-template critique, visual density, motion intensity, domain-specific signature, and high-quality interface review."+category: rnd+---++# ui-taste++Use this skill to keep UI work from becoming generic. It adapts Taste Skill-style visual judgment into concrete product UI decisions.++## Visual Thesis++Before rendering a design, define:++- `product_type`: operational tool, creative workspace, consumer product, developer tool, marketplace, education, finance, content, or brand site.+- `audience_pressure`: speed, trust, comparison, learning, creativity, delight, or compliance.+- `primary_workflow`: the action users repeat.+- `density`: compact, balanced, spacious, or editorial.+- `tone`: 2 precise words, not "modern" or "clean" alone.+- `signature_device`: one subject-specific visual rule, not decoration.+- `anti_template_rejection`: what generic idea you rejected.++A design without a thesis becomes default SaaS UI.++## Anti-Template Rejections++Reject these unless they are explicitly justified:++- Purple-blue neon gradients for AI products.+- Glass panels, blur-heavy surfaces, and decorative bokeh.+- Generic bento grids for tools that need workflow density.+- Floating page-section cards.+- Cards inside cards.+- Oversized hero sections for apps, dashboards, editors, or tools.+- Monochrome one-hue palettes made from tints of a single color.+- Decorative orbs, blobs, and abstract SVG backgrounds.+- Tiny badges and over-dense microcopy replacing clear hierarchy.+- Motion everywhere instead of meaningful motion.++## Domain Fit++Match the UI to the work:++- SaaS operations: quiet, dense, fast scanning, predictable controls.+- Developer tools: precise type, code/data affordances, clear states, restrained contrast.+- Finance/trading: tabular clarity, risk status, high density, strong alignment.+- Creative tools: canvas-first, toolbars, palettes, shortcuts, direct manipulation.+- Education: progression, feedback, explanations, gentle structure.+- Ecommerce: product inspection, comparison, trust, conversion, clear imagery.+- Brand/editorial: stronger typography and imagery, but only if the first viewport communicates the object or offer.++## Variation Controls++Adjust deliberately:++- Visual density: information per viewport.+- Contrast: calm, standard, high.+- Motion intensity: none, subtle, expressive.+- Shape language: sharp, practical, soft, playful.+- Surface depth: flat, bordered, raised, layered.+- Type personality: neutral, technical, editorial, humanist, display-led.++Use only 1-2 expressive axes at a time. If everything is expressive, nothing is readable.++## Good-Taste Checks++Before delivery, ask:++- Can a target user complete the main task without reading an explanation?+- Is the primary action obvious?+- Does hierarchy come from layout and type, not decoration?+- Does the page look specific to this product, not any startup?+- Are there enough real states to judge the interface?+- Does mobile still feel designed, not squeezed?+- Is there one memorable visual choice, and does it help the work?++## Reporting++When describing design direction, include:++- Visual thesis.+- Signature device.+- Rejected generic choice.+- Density and motion settings.+- One tradeoff the design makes intentionally.diff --git a/scripts/build-video-studio-skill-core.cjs b/scripts/build-video-studio-skill-core.cjsindex 75a58dd0..954dd039 100644--- a/scripts/build-video-studio-skill-core.cjs+++ b/scripts/build-video-studio-skill-core.cjs@@ -57,11 +57,11 @@ const bannedRuntimeDeps = ["require('electron')",];-async function buildOne(item) {- fs.mkdirSync(path.dirname(item.outfile), { recursive: true });+async function buildOne(item, outfile = item.outfile) {+ fs.mkdirSync(path.dirname(outfile), { recursive: true });await esbuild.build({entryPoints: [item.entry],- outfile: item.outfile,+ outfile,bundle: true,platform: 'node',target: 'node20',@@ -73,19 +73,34 @@ async function buildOne(item) {logLevel: 'silent',});- const text = fs.readFileSync(item.outfile, 'utf8');+ const text = fs.readFileSync(outfile, 'utf8');const banned = bannedRuntimeDeps.find((needle) => text.includes(needle));if (banned) {- throw new Error(`${path.relative(pcDir, item.outfile)} still contains forbidden runtime dependency: ${banned}`);+ throw new Error(`${path.relative(pcDir, outfile)} still contains forbidden runtime dependency: ${banned}`);}}-(async () => {+/** Build every core to `outfileFor(item)` (default: the committed path).+ * The freshness test builds to a temp dir and byte-compares. */+async function buildTo(outfileFor = (item) => item.outfile) {+ const built = [];for (const item of outputs) {- await buildOne(item);- console.log(`built ${path.relative(pcDir, item.outfile)}`);+ const outfile = outfileFor(item);+ await buildOne(item, outfile);+ built.push({ item, outfile });}-})().catch((err) => {- console.error(err.stack || String(err));- process.exit(1);-});+ return built;+}++module.exports = { outputs, buildTo, pcDir };++if (require.main === module) {+ buildTo()+ .then((built) => {+ for (const { outfile } of built) console.log(`built ${path.relative(pcDir, outfile)}`);+ })+ .catch((err) => {+ console.error(err.stack || String(err));+ process.exit(1);+ });+}diff --git a/scripts/fetch-officecli.cjs b/scripts/fetch-officecli.cjsindex c9c3fd94..b912ba54 100644--- a/scripts/fetch-officecli.cjs+++ b/scripts/fetch-officecli.cjs@@ -44,7 +44,7 @@ const https = require('node:https');const crypto = require('node:crypto');const { spawnSync } = require('node:child_process');-const VERSION = 'v1.0.117';+const VERSION = 'v1.0.131';const REPO = 'iOfficeAI/OfficeCLI';const RELEASE_BASE_URL = process.env.OFFICECLI_RELEASE_BASE_URL || `https://github.com/${REPO}/releases/download/${VERSION}`;const LICENSE_URL = process.env.OFFICECLI_LICENSE_URL || `https://raw.githubusercontent.com/${REPO}/${VERSION}/LICENSE`;@@ -64,10 +64,10 @@ const ASSETS = {// Pinned sha256 for VERSION (from the release SHA256SUMS). Update with VERSION.const SHA256 = {- 'officecli-mac-arm64': 'a53a4dc1e0aa9ebfc2025b40e3cfb1dcb6f52b57fd6d8e3bedd858c16bbded17',- 'officecli-mac-x64': 'f20ce0ae9224605c6518481e1b46130378d918ca270d69e40cbaafc704c10108',- 'officecli-win-x64.exe': 'ff4a790637bcd4fdaf046727752e9e44207425d5ceafe36131516d37500d9ebd',- 'officecli-win-arm64.exe': 'b7157e13f622029032fb4e3f56b59a3485fbfdd8f691023ff74ad1326f54bdd3',+ 'officecli-mac-arm64': '1a10e73e73e1a3aa278d75af8e966ce932691bbf9958a06578638c42181894fb',+ 'officecli-mac-x64': 'daa90b846c85a2ca61eec743fd41da6d02f74c7c68560ccecfdab2e977737730',+ 'officecli-win-x64.exe': 'b67e6f95c309707fad51fad2da26a87aa8d967774cde9f7b47bb452811164e73',+ 'officecli-win-arm64.exe': 'f4224772a7d450053fcacaa54175704e89d99ca23535e7d24fc340bc6dcef43e',};function parseArgs(argv) {diff --git a/src/main/features/video_craft_lint.ts b/src/main/features/video_craft_lint.tsdeleted file mode 100644index 9f6d0d67..00000000--- a/src/main/features/video_craft_lint.ts+++ /dev/null@@ -1,140 +0,0 @@-/**- * video_craft_lint — pure, static craft checks over a HyperFrames composition's- * index.html. Operationalizes the two deterministically-checkable thresholds- * from the video-craft skill (legible font size, restrained palette) so the- * agent gets concrete warnings alongside the structural/visual QA, instead of- * relying on the model to remember the numbers while it authors HTML.- *- * Advisory only — these never block a render; they feed the pre-render review.- * Layout-dependent craft (text safe zones, overflow) is intentionally left to- * the headless `inspect` pass, which actually lays the composition out; a static- * scan can't know rendered geometry.- */--export interface CraftFinding {- /** Advisory severity — informs the review, never blocks. */- level: 'warn';- code: 'FONT_TOO_SMALL' | 'PALETTE_LARGE';- message: string;-}--/** video-craft §4: at 1080p, body text "never below ~40 px". Scales with canvas. */-const FONT_FLOOR_AT_1080 = 40;-/** Distinct chromatic colors across the whole file above which we nudge the- * author to re-check per-scene palette (video-craft §4: ≤ 3–5 on screen). High- * enough that a normal multi-scene composition doesn't trip it. */-const PALETTE_SOFT_MAX = 8;--/** Legibility floor scales the 1080p number to the real canvas height. Read it- * from the root `data-height`; fall back to 1080 when absent/unparseable. */-function readCanvasHeight(html: string, override?: number): number {- if (typeof override === 'number' && Number.isFinite(override) && override > 0) return override;- const m = html.match(/data-height\s*=\s*["']?(\d{2,5})/i);- const h = m ? Number(m[1]) : NaN;- return Number.isFinite(h) && h > 0 ? h : 1080;-}--function fontFloor(height: number): number {- return Math.max(1, Math.round((FONT_FLOOR_AT_1080 * height) / 1080));-}--/** Explicit px font-sizes below the floor. Only `px` is judged — em/rem/vw/%/- * clamp() are not a hard pixel commitment and are skipped on purpose. */-function smallFontSizesPx(html: string, floor: number): number[] {- const out = new Set<number>();- const re = /font-size\s*:\s*([\d.]+)px\b/gi;- let m: RegExpExecArray | null;- while ((m = re.exec(html)) !== null) {- const px = Number(m[1]);- if (Number.isFinite(px) && px > 0 && px < floor) out.add(px);- }- return [...out].sort((a, b) => a - b);-}--/** Expand a hex body (no '#', lowercased, len 3/4/6/8) to 6 rrggbb digits. */-function expandHex(h: string): string {- if (h.length === 3) return h.split('').map((c) => c + c).join('');- if (h.length === 4) return h.slice(0, 3).split('').map((c) => c + c).join('');- return h.slice(0, 6); // 6 or 8 (drop alpha)-}--/** Pure grays (incl. black/white) aren't part of the "≤3–5 colors" budget. */-function isNeutralHex6(h: string): boolean {- return h.slice(0, 2) === h.slice(2, 4) && h.slice(2, 4) === h.slice(4, 6);-}--/** Whitespace-stripped lowercased rgb()/rgba()/hsl()/hsla()/transparent → is it- * a structural neutral (gray, or fully transparent) rather than a real color? */-function isNeutralColorFn(s: string): boolean {- if (s.includes('transparent')) return true;- const rgb = s.match(/^rgba?\((\d+),(\d+),(\d+)/);- if (rgb) return rgb[1] === rgb[2] && rgb[2] === rgb[3];- const hsl = s.match(/^hsla?\(\d+(?:deg)?,(\d+(?:\.\d+)?)%/);- if (hsl) return Number(hsl[1]) === 0; // 0% saturation = gray- return false;-}--/** Distinct chromatic colors used anywhere in the composition. */-function chromaticColors(html: string): Set<string> {- const colors = new Set<string>();- const hexRe = /#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})\b/gi;- let m: RegExpExecArray | null;- while ((m = hexRe.exec(html)) !== null) {- const six = expandHex(m[1].toLowerCase());- if (!isNeutralHex6(six)) colors.add(`#${six}`);- }- const fnRe = /\b(?:rgb|rgba|hsl|hsla)\([^)]*\)/gi;- while ((m = fnRe.exec(html)) !== null) {- const key = m[0].toLowerCase().replace(/\s+/g, '');- if (!isNeutralColorFn(key)) colors.add(key);- }- return colors;-}--/**- * Static craft lint of a composition's index.html. Returns advisory findings;- * an empty array means nothing tripped (it does NOT mean the composition is- * good — only that these two mechanical thresholds passed).- */-export function lintCompositionCraft(html: string, opts?: { canvasHeight?: number }): CraftFinding[] {- const findings: CraftFinding[] = [];- if (!html) return findings;-- const height = readCanvasHeight(html, opts?.canvasHeight);- const floor = fontFloor(height);- const small = smallFontSizesPx(html, floor);- if (small.length) {- const shown = small.slice(0, 6).map((n) => `${n}px`).join(', ');- const more = small.length > 6 ? `, +${small.length - 6} more` : '';- findings.push({- level: 'warn',- code: 'FONT_TOO_SMALL',- message:- `Font sizes below the legibility floor (~${floor}px for a ${height}px-tall canvas): ${shown}${more}. `- + `Raise body text to ≥ the floor and titles well above it, or it won't read at phone size.`,- });- }-- const colors = chromaticColors(html);- if (colors.size > PALETTE_SOFT_MAX) {- findings.push({- level: 'warn',- code: 'PALETTE_LARGE',- message:- `${colors.size} distinct chromatic colors in the composition — aim for ≤ 3–5 on screen at once. `- + `Re-check each scene: background least-saturated, one accent that reads first.`,- });- }-- return findings;-}--/** Render findings as a short text block to append to the QA findings the model- * reads. Empty string when there are none (so callers can concatenate freely). */-export function formatCraftFindings(findings: CraftFinding[]): string {- if (!findings.length) return '';- return [- '[craft] static threshold checks (advisory, from the video-craft skill):',- ...findings.map((f) => ` - ${f.code}: ${f.message}`),- ].join('\n');-}diff --git a/test/main/features/video_analyze_ocr.test.ts b/test/main/features/video_analyze_ocr.test.tsindex 2f330fe5..cdf40723 100644--- a/test/main/features/video_analyze_ocr.test.ts+++ b/test/main/features/video_analyze_ocr.test.ts@@ -1,6 +1,24 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi, beforeEach } from 'vitest';-import { sampleTimecodes, collapseOcrSegments } from '../../../resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_analyze';+// Mock the OCR runtime and the ffmpeg helpers so the video OCR flow is+// testable without Python/ffmpeg. The batch contract (ONE ocrImagesText call+// per clip, index-aligned results, per-frame error tolerance) is the behavior+// under test.+vi.mock('../../../resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/ocr_runtime', () => ({+ ocrImageText: vi.fn(),+ ocrImagesText: vi.fn(),+}));+vi.mock('../../../resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_edit', () => ({+ measureSilenceCoverage: vi.fn(),+ assessVoiceoverCoverage: vi.fn(),+ extractFrameAt: vi.fn(async () => ({ ok: true })),+ probeMediaDurationSec: vi.fn(async () => 10),+ detectSceneChanges: vi.fn(),+ detectQuality: vi.fn(),+}));++import { sampleTimecodes, collapseOcrSegments, analyzeMedia } from '../../../resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_analyze';+import { ocrImagesText } from '../../../resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/ocr_runtime';describe('sampleTimecodes', () => {it('samples mid-step across the clip, strictly increasing and inside duration', () => {@@ -52,3 +70,80 @@ describe('collapseOcrSegments', () => {expect(segs[0].endSec).toBe(4);});});++describe('analyzeMedia › video ocr › batch contract', () => {+ const mockedBatch = vi.mocked(ocrImagesText);+ let fakeVideo: string;++ beforeEach(async () => {+ mockedBatch.mockReset();+ const fs = await import('node:fs');+ const os = await import('node:os');+ const path = await import('node:path');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-ocr-batch-test-'));+ fakeVideo = path.join(dir, 'clip.mp4');+ fs.writeFileSync(fakeVideo, 'not-a-real-video'); // probe/extract are mocked+ });++ it('runs ONE batch OCR call for all sampled frames and maps results by index', async () => {+ const expectedFrames = sampleTimecodes(10, 2.5, 16).length;+ mockedBatch.mockImplementationOnce(async ({ absPaths }) => ({+ ok: true as const,+ results: absPaths.map((_, i) => ({+ text: i < absPaths.length / 2 ? 'Slide A' : 'Slide B',+ items: [],+ })),+ }));++ const r = await analyzeMedia({ op: 'ocr', inputAbsPath: fakeVideo });+ expect(r.ok, JSON.stringify(r)).toBe(true);+ expect(mockedBatch).toHaveBeenCalledTimes(1);+ expect(mockedBatch.mock.calls[0][0].absPaths).toHaveLength(expectedFrames);+ if (r.ok === true) {+ const summary = r.summary as { sampledFrames: number; segments: Array<{ text: string }> };+ expect(summary.sampledFrames).toBe(expectedFrames);+ expect(summary.segments.map((s) => s.text)).toEqual(['Slide A', 'Slide B']);+ }+ });++ it('skips per-frame errors without failing the clip', async () => {+ mockedBatch.mockImplementationOnce(async ({ absPaths }) => ({+ ok: true as const,+ results: absPaths.map((_, i) => (i === 0+ ? { text: '', items: [], error: 'unreadable frame' }+ : { text: 'Slide B', items: [] })),+ }));++ const r = await analyzeMedia({ op: 'ocr', inputAbsPath: fakeVideo });+ expect(r.ok, JSON.stringify(r)).toBe(true);+ if (r.ok === true) {+ const summary = r.summary as { sampledFrames: number; segments: Array<{ text: string }> };+ expect(summary.sampledFrames).toBe(sampleTimecodes(10, 2.5, 16).length - 1);+ expect(summary.segments.map((s) => s.text)).toEqual(['Slide B']);+ }+ });++ it('surfaces a runtime install failure as the op error', async () => {+ mockedBatch.mockResolvedValueOnce({+ ok: false as const,+ errorCode: 'E_OCR_INSTALL_FAILED',+ message: 'install failed',+ });++ const r = await analyzeMedia({ op: 'ocr', inputAbsPath: fakeVideo });+ expect(r.ok).toBe(false);+ if (r.ok === false) expect(r.errorCode).toBe('E_OCR_INSTALL_FAILED');+ });++ it('real ocrImagesText validates inputs before touching the runtime', async () => {+ const actual = await vi.importActual<typeof import('../../../resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/ocr_runtime')>(+ '../../../resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/ocr_runtime',+ );+ // Empty input → trivially ok with no python spawn.+ await expect(actual.ocrImagesText({ absPaths: [] })).resolves.toEqual({ ok: true, results: [] });+ // A non-image path is rejected before ensureRuntime.+ const r = await actual.ocrImagesText({ absPaths: ['/tmp/a.png', '/tmp/not-an-image.mp4'] });+ expect(r.ok).toBe(false);+ if (r.ok === false) expect(r.errorCode).toBe('E_OCR_UNSUPPORTED_FILE');+ });+});diff --git a/test/main/features/video_craft_lint.test.ts b/test/main/features/video_craft_lint.test.tsindex fc28b782..7382af6e 100644--- a/test/main/features/video_craft_lint.test.ts+++ b/test/main/features/video_craft_lint.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { lintCompositionCraft, formatCraftFindings } from '../../../src/main/features/video_craft_lint';+import { lintCompositionCraft, formatCraftFindings } from '../../../resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_craft_lint';const codes = (html: string, opts?: { canvasHeight?: number }) =>lintCompositionCraft(html, opts).map((f) => f.code);@@ -87,4 +87,18 @@ describe('formatCraftFindings', () => {expect(text).toContain('[craft]');expect(text).toContain('FONT_TOO_SMALL');});++ it('labels only small text as blocking when strict craft mode is active', () => {+ const text = formatCraftFindings(lintCompositionCraft('<div style="font-size:12px">x</div>'), { strict: true });+ expect(text).toContain('FONT_TOO_SMALL blocks under --strict-craft');+ expect(text).toContain('PALETTE_LARGE is advisory');+ });++ it('keeps palette-size findings advisory even in strict craft mode', () => {+ const palette = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff', '#ff8800', '#8800ff', '#0088ff'];+ const html = palette.map((c) => `<div style="color:${c}">x</div>`).join('');+ const text = formatCraftFindings(lintCompositionCraft(html), { strict: true });+ expect(text).toContain('PALETTE_LARGE');+ expect(text).toContain('PALETTE_LARGE is advisory');+ });});diff --git a/test/main/features/video_media_skill_scripts.test.ts b/test/main/features/video_media_skill_scripts.test.tsindex 7b4d9175..254d5bf4 100644--- a/test/main/features/video_media_skill_scripts.test.ts+++ b/test/main/features/video_media_skill_scripts.test.ts@@ -49,6 +49,72 @@ function runSkill();}+function runRenderCompositionWithMockCore(args: string[], extraEnv: Record<string, string> = {}) {+ const dir = pcDir();+ const scriptPath = path.join(skillDir('stage-compose'), 'scripts', 'render_composition.js');+ const code = [+ "const Module = require('node:module');",+ 'const scriptPath = process.argv[1];',+ 'const args = JSON.parse(process.argv[2]);',+ 'const originalLoad = Module._load;',+ 'Module._load = function(request, parent, isMain) {',+ " if (request === './lib/video_render_core.cjs' && parent && parent.filename === scriptPath) {",+ ' return {',+ ' qaComposition: async (op) => {',+ " if (process.env.ORKAS_MOCK_LINT_ERROR === '1' && op === 'lint') {",+ " return { ok: true, findings: JSON.stringify({ ok: false, errorCount: 1, warningCount: 0, findings: [{ code: 'gsap_timeline_not_registered', severity: 'error', message: 'timeline missing' }] }) };",+ ' }',+ " if (process.env.ORKAS_MOCK_INSPECT_VISUAL_ERROR === '1' && op === 'inspect') {",+ " return { ok: true, findings: JSON.stringify({ ok: false, errorCount: 2, warningCount: 1, issueCount: 3, totalIssueCount: 3, issues: [",+ " { code: 'text_box_overflow', severity: 'error', selector: 'p.card-copy', message: 'Text extends outside its nearest visual/container box.' },",+ " { code: 'text_occluded', severity: 'error', selector: 'h1.headline', message: 'Text is hidden beneath an opaque element.' },",+ " { code: 'content_overlap', severity: 'warning', selector: 'h1.headline', message: 'Two text blocks overlap.' }",+ ' ] }) };',+ ' }',+ " if (process.env.ORKAS_MOCK_INSPECT_STRUCTURAL_ERROR === '1' && op === 'inspect') {",+ " return { ok: true, findings: JSON.stringify({ ok: false, errorCount: 1, warningCount: 0, issueCount: 1, totalIssueCount: 1, issues: [{ code: 'timeline_runtime_missing', severity: 'error', message: 'Timeline runtime is not available.' }] }) };",+ ' }',+ " return { ok: true, findings: JSON.stringify({ ok: true, errorCount: 0, warningCount: 0, issueCount: 0, totalIssueCount: 0, issues: [] }) };",+ ' },',+ ' renderComposition: async (p) => {',+ " if (process.env.ORKAS_MOCK_RENDER_OK === '1') {",+ " require('node:fs').mkdirSync(require('node:path').dirname(p.outputAbsPath), { recursive: true });",+ " require('node:fs').writeFileSync(p.outputAbsPath, 'fake video output');",+ " return { ok: true, path: p.outputAbsPath, bytes: 17 };",+ ' }',+ " return { ok: false, errorCode: 'E_RENDER_FAILED', message: 'fake render failed' };",+ ' },',+ // Render-resilience helpers mirror the real pure functions; default RAM 32+ // keeps existing tests on the unconstrained "proceed" path.+ ' machineRamGB: () => (process.env.ORKAS_MOCK_RAM_GB ? Number(process.env.ORKAS_MOCK_RAM_GB) : 32),',+ " isConstrainedMachine: (ram, gpu) => (Number(ram) <= 8 || gpu === 'software'),",+ ' estimateRenderCost: (w, h, dur, fps) => Math.round(Math.max(1, dur) * Math.max(1, fps) * Math.max(1, (w * h) / 1e6)),',+ " renderCostDecision: (o) => (!o.constrained || o.costUnits <= 3000 ? 'proceed' : (o.isFinal ? 'fail_fast' : 'degrade')),",+ ' degradedFps: (fps) => (fps > 30 ? 30 : fps),',+ ' };',+ ' }',+ ' return originalLoad.apply(this, arguments);',+ '};',+ 'const script = require(scriptPath);',+ "Promise.resolve(script({ args })).then((out) => { process.stdout.write(JSON.stringify(out)); }).catch((err) => { process.stderr.write(err && err.stack ? err.stack : String(err)); process.exit(1); });",+ ].join('\n');+ return spawnSync(+ process.execPath,+ ['-e', code, scriptPath, JSON.stringify(args)],+ {+ cwd: path.dirname(dir),+ encoding: 'utf8',+ env: {+ ...process.env,+ ORKAS_PC_DIR: dir,+ ORKAS_RUN_SKILL_DIR: skillDir('stage-compose'),+ ORKAS_WORKSPACE_ROOT: path.dirname(dir),+ ...extraEnv,+ },+ },+ );+}+function parseJson(text: string) {return JSON.parse(text.trim());}@@ -83,6 +149,71 @@ function makeFakeFfmpegEnv(tmp: string) {};}+function makeFakeVideoProbeEnv(tmp: string) {+ const binDir = path.join(tmp, 'fake-probe-bin');+ fs.mkdirSync(binDir, { recursive: true });+ const ffprobePath = path.join(binDir, 'ffprobe');+ fs.writeFileSync(ffprobePath, [+ '#!/usr/bin/env node',+ 'process.stdout.write(JSON.stringify({',+ " streams: [{ codec_type: 'video', codec_name: 'h264', width: 1920, height: 1080, r_frame_rate: '30/1', bit_rate: '800000' }],",+ " format: { duration: '10', size: '17', bit_rate: '800000' }",+ '}));',+ '',+ ].join('\n'), 'utf8');+ fs.chmodSync(ffprobePath, 0o755);+ return { ORKAS_BUNDLED_FFPROBE: ffprobePath };+}++function writeMinimalCompositionHtml(+ compositionDir: string,+ text = 'Orkas 1.5.0',+ attrs: { width?: number; height?: number; duration?: number } = {},+ head = '',+) {+ const width = attrs.width ?? 1920;+ const height = attrs.height ?? 1080;+ const duration = attrs.duration ?? 10;+ fs.writeFileSync(path.join(compositionDir, 'index.html'), [+ '<!doctype html>',+ '<html lang="en">',+ '<head>',+ '<meta charset="UTF-8" />',+ `<meta name="viewport" content="width=${width}, height=${height}" />`,+ head,+ '</head>',+ '<body>',+ `<div id="root" data-composition-id="main" data-start="0" data-duration="${duration}" data-width="${width}" data-height="${height}">`,+ `<div class="clip" data-start="0" data-duration="${duration}" data-track-index="1">${text}</div>`,+ '</div>',+ '<script>window.__timelines = window.__timelines || {}; window.__timelines.main = { seek() {} };</script>',+ '</body>',+ '</html>',+ ].join('\n'), 'utf8');+}++function writeDesignContract(+ compositionDir: string,+ overrides: Record<string, unknown> = {},+) {+ const contract = {+ canvas: { width: 1920, height: 1080, duration: 10, fps: 30, language: 'en' },+ aesthetic: {+ subject_world: 'release notes',+ audience: 'product users',+ one_job: 'state the update',+ tone: ['clear'],+ signature_device: 'version lockup',+ aesthetic_risk: 'bold cover frame',+ anti_template_check: 'no generic cards',+ },+ scenes: [{ id: 'cover', start: 0, duration: 10, headline: 'Orkas 1.5.0' }],+ color_tokens: { background: '#050b18', text: '#ffffff', primary: '#3b82f6' },+ ...overrides,+ };+ fs.writeFileSync(path.join(compositionDir, 'design-contract.json'), JSON.stringify(contract), 'utf8');+}+describe('video media skill scripts', () => {it('keeps VideoStudio media logic local to skill scripts', () => {const files = [@@ -115,6 +246,7 @@ describe('video media skill scripts', () => {path.join(pcDir(), 'src', 'main', 'features', 'video_edit.ts'),path.join(pcDir(), 'src', 'main', 'features', 'video_edl.ts'),path.join(pcDir(), 'src', 'main', 'features', 'video_render.ts'),+ path.join(pcDir(), 'src', 'main', 'features', 'video_craft_lint.ts'),]) {expect(fs.existsSync(file), `${file} should not exist`).toBe(false);}@@ -136,6 +268,7 @@ describe('video media skill scripts', () => {expect(out.ok).toBe(true);expect(out.ops).toContain('trim');expect(out.ops).toContain('mix');+ expect(out.ops).toContain('normalize_loudness');});it('keeps edit_video stdout parseable while streaming progress JSONL on stderr', () => {@@ -168,6 +301,493 @@ describe('video media skill scripts', () => {expect(out.ok).toBe(true);expect(out.ops).toContain('inspect');expect(out.ops).toContain('render');+ expect(out.ops).toContain('draft');+ expect(out.ops).not.toContain('compile');+ expect(out.usage).toContain('--strict-craft');+ expect(out.usage).toContain('--findings-output');+ expect(out.usage).toContain('--findings-inline');+ expect(out.usage).toContain('hand-authored index.html');+ });++ it('blocks draft when hand-authored composition HTML is missing', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-html-missing-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ fs.mkdirSync(compositionDir, { recursive: true });++ const res = runSkill('stage-compose', 'render_composition', [+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),+ ]);++ expect(res.status).toBe(1);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_RENDER_NO_COMPOSITION');+ expect(out.message).toContain('hand-authored index.html');+ });++ it('rejects composition spec compilation so COMPOSE stays model-authored HTML', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-spec-rejected-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ fs.mkdirSync(compositionDir, { recursive: true });+ fs.writeFileSync(path.join(compositionDir, 'spec.json'), JSON.stringify({ scenes: [] }), 'utf8');++ const res = runSkill('stage-compose', 'render_composition', [+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),+ ]);++ expect(res.status).toBe(1);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_SPEC_COMPILER_REMOVED');+ expect(out.message).toContain('index.html');+ });++ it('blocks draft when model-authored HTML has no design contract', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-contract-missing-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ fs.mkdirSync(compositionDir, { recursive: true });+ writeMinimalCompositionHtml(compositionDir);++ const res = runSkill('stage-compose', 'render_composition', [+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),+ ]);++ expect(res.status).toBe(1);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_CONTRACT_HTML_BLOCKED');+ expect(out.repair_target).toBe('design-contract.json');+ expect(out.contract_html.issues).toEqual(expect.arrayContaining([+ expect.objectContaining({ code: 'DESIGN_CONTRACT_MISSING' }),+ ]));+ });++ it('warns when the contract declares narration but the composition is silent', () => {+ const runDraftIssues = (label: string, audio: Record<string, unknown> | undefined) => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), `orkas-compose-${label}-`));+ const compositionDir = path.join(tmp, 'project', 'composition');+ fs.mkdirSync(compositionDir, { recursive: true });+ writeDesignContract(compositionDir, {+ scenes: [{ id: 'cover', start: 0, duration: 10, headline: 'Orkas 1.5.0 Release Highlights' }],+ ...(audio ? { audio } : {}),+ });+ // "Different title" forces HTML_MISSING_SCENE_COPY so draft blocks and+ // returns the full contract_html issue list (including any warnings).+ writeMinimalCompositionHtml(compositionDir, 'Different title', {});+ const res = runSkill('stage-compose', 'render_composition', [+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),+ ]);+ expect(res.status).toBe(1);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_CONTRACT_HTML_BLOCKED');+ return (out.contract_html.issues as Array<{ code: string }>);+ };++ // Composition-owned narration declared, but no <audio> and no narration file → warn.+ const silent = runDraftIssues('narration-silent', { owner: 'composition', narration_path: './assets/narration.mp3', target_sec: 10 });+ expect(silent.find((i) => i.code === 'NARRATION_DECLARED_BUT_SILENT')).toBeTruthy();++ // Assembler-owned narration (composition renders silent by design) → no warn.+ const assembler = runDraftIssues('narration-assemble', { owner: 'assemble', narration_path: './assets/narration.mp3', render_silent: true });+ expect(assembler.find((i) => i.code === 'NARRATION_DECLARED_BUT_SILENT')).toBeUndefined();++ // No audio section at all → no warn.+ const none = runDraftIssues('narration-none', undefined);+ expect(none.find((i) => i.code === 'NARRATION_DECLARED_BUT_SILENT')).toBeUndefined();+ });++ it('blocks draft when HTML depends on remote runtime resources', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-remote-resource-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ fs.mkdirSync(compositionDir, { recursive: true });+ writeDesignContract(compositionDir);+ writeMinimalCompositionHtml(+ compositionDir,+ 'Orkas 1.5.0',+ {},+ '<script src="https://cdn.jsdelivr.net/npm/gsap@3/dist/gsap.min.js"></script>',+ );++ const res = runSkill('stage-compose', 'render_composition', [+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),+ ]);++ expect(res.status).toBe(1);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_CONTRACT_HTML_BLOCKED');+ expect(out.repair_target).toBe('index.html');+ expect(out.contract_html.issues).toEqual(expect.arrayContaining([+ expect.objectContaining({ code: 'REMOTE_RUNTIME_RESOURCE' }),+ ]));+ });++ it('blocks draft when GSAP is used without the local vendor script', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-gsap-missing-vendor-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ fs.mkdirSync(compositionDir, { recursive: true });+ writeDesignContract(compositionDir);+ writeMinimalCompositionHtml(+ compositionDir,+ 'Orkas 1.5.0',+ {},+ '<script>window.__timelines = {}; window.__timelines.main = gsap.timeline({ paused: true });</script>',+ );++ const res = runSkill('stage-compose', 'render_composition', [+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),+ ]);++ expect(res.status).toBe(1);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_CONTRACT_HTML_BLOCKED');+ expect(out.contract_html.issues).toEqual(expect.arrayContaining([+ expect.objectContaining({ code: 'GSAP_VENDOR_SCRIPT_MISSING' }),+ ]));+ });++ it('auto-copies the local GSAP vendor when the composition references it', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-gsap-vendor-copy-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ fs.mkdirSync(compositionDir, { recursive: true });+ writeDesignContract(compositionDir, {+ scenes: [{ id: 'cover', start: 0, duration: 10, headline: 'Orkas 1.5.0 Release Highlights' }],+ });+ writeMinimalCompositionHtml(+ compositionDir,+ 'Different title',+ {},+ '<script src="./assets/vendor/gsap.min.js"></script><script>window.__timelines = {}; window.__timelines.main = gsap.timeline({ paused: true });</script>',+ );++ const res = runSkill('stage-compose', 'render_composition', [+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),+ ]);++ expect(res.status).toBe(1);+ expect(fs.existsSync(path.join(compositionDir, 'assets', 'vendor', 'gsap.min.js'))).toBe(true);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_CONTRACT_HTML_BLOCKED');+ expect(out.contract_html.issues).toEqual(expect.arrayContaining([+ expect.objectContaining({ code: 'HTML_MISSING_SCENE_COPY' }),+ ]));+ expect(out.contract_html.issues).not.toEqual(expect.arrayContaining([+ expect.objectContaining({ code: 'MISSING_LOCAL_ASSET' }),+ ]));+ });++ it('replaces the old managed GSAP shim with the built-in official vendor', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-gsap-vendor-replace-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ const vendorPath = path.join(compositionDir, 'assets', 'vendor', 'gsap.min.js');+ fs.mkdirSync(path.dirname(vendorPath), { recursive: true });+ fs.writeFileSync(vendorPath, [+ '/*',+ ' * Local HyperFrames timeline vendor.',+ ' * Provides the small GSAP-compatible surface VideoStudio compositions need.',+ ' */',+ 'window.gsap = { timeline() { return { seek() {}, pause() {}, play() {}, timeScale() {}, totalTime() {}, duration() { return 0; }, totalDuration() { return 0; }, getChildren() { return []; } }; } };',+ ].join('\n'), 'utf8');+ writeDesignContract(compositionDir, {+ scenes: [{ id: 'cover', start: 0, duration: 10, headline: 'Orkas 1.5.0 Release Highlights' }],+ });+ writeMinimalCompositionHtml(+ compositionDir,+ 'Different title',+ {},+ '<script src="./assets/vendor/gsap.min.js"></script><script>window.__timelines = {}; window.__timelines.main = gsap.timeline({ paused: true });</script>',+ );++ const res = runSkill('stage-compose', 'render_composition', [+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),+ ]);++ expect(res.status).toBe(1);+ const vendor = fs.readFileSync(vendorPath, 'utf8');+ expect(vendor).toContain('GSAP 3.15.0');+ expect(vendor).toContain('timeScale');+ expect(vendor).toContain('totalTime');+ expect(vendor).toContain('getChildren');+ });++ it('blocks a user-provided incompatible GSAP vendor before rendering', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-gsap-vendor-incompatible-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ const vendorPath = path.join(compositionDir, 'assets', 'vendor', 'gsap.min.js');+ fs.mkdirSync(path.dirname(vendorPath), { recursive: true });+ fs.writeFileSync(vendorPath, '/* custom gsap placeholder */ window.gsap = {};', 'utf8');+ writeDesignContract(compositionDir);+ writeMinimalCompositionHtml(+ compositionDir,+ 'Orkas 1.5.0',+ {},+ '<script src="./assets/vendor/gsap.min.js"></script><script>window.__timelines = {}; window.__timelines.main = gsap.timeline({ paused: true });</script>',+ );++ const res = runSkill('stage-compose', 'render_composition', [+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),+ ]);++ expect(res.status).toBe(1);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_VENDOR_ASSETS_BLOCKED');+ expect(out.repair_target).toBe('assets/vendor/gsap.min.js');+ expect(out.vendor_assets.issues).toEqual(expect.arrayContaining([+ expect.objectContaining({ code: 'VENDOR_GSAP_INCOMPATIBLE' }),+ ]));+ expect(fs.readFileSync(vendorPath, 'utf8')).toContain('custom gsap placeholder');+ });++ it('writes the latest draft report when render fails after inspect', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-draft-render-report-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ const outputPath = path.join(tmp, 'project', 'render', 'draft.mp4');+ const reportPath = path.join(tmp, 'project', 'render', 'draft-report.json');+ fs.mkdirSync(compositionDir, { recursive: true });+ writeDesignContract(compositionDir);+ writeMinimalCompositionHtml(compositionDir, 'Orkas 1.5.0');++ const res = runRenderCompositionWithMockCore([+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', outputPath,+ '--report', reportPath,+ ]);++ expect(res.status).toBe(1);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_RENDER_FAILED');+ expect(out.report_path).toBe(reportPath);+ const report = parseJson(fs.readFileSync(reportPath, 'utf8'));+ expect(report.error).toMatchObject({ code: 'E_RENDER_FAILED', message: 'fake render failed' });+ expect(report.steps.inspect.ok).toBe(true);+ expect(report.steps.render).toMatchObject({ ok: false, errorCode: 'E_RENDER_FAILED', message: 'fake render failed' });+ });++ it('blocks draft on HyperFrames lint errors before inspect/render', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-draft-lint-blocked-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ const outputPath = path.join(tmp, 'project', 'render', 'draft.mp4');+ const reportPath = path.join(tmp, 'project', 'render', 'draft-report.json');+ fs.mkdirSync(compositionDir, { recursive: true });+ writeDesignContract(compositionDir);+ writeMinimalCompositionHtml(compositionDir, 'Orkas 1.5.0');++ const res = runRenderCompositionWithMockCore([+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', outputPath,+ '--report', reportPath,+ ], { ORKAS_MOCK_LINT_ERROR: '1' });++ expect(res.status).toBe(1);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_LINT_BLOCKED');+ expect(out.lint_summary.issueCodes).toEqual(expect.arrayContaining([+ expect.objectContaining({ code: 'gsap_timeline_not_registered', severity: 'error' }),+ ]));+ const report = parseJson(fs.readFileSync(reportPath, 'utf8'));+ expect(report.steps.lint.ok).toBe(false);+ expect(report.steps.inspect).toBeUndefined();+ expect(report.steps.render).toBeUndefined();+ });++ it('renders draft when inspect only reports visual advisories', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-draft-visual-advisory-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ const outputPath = path.join(tmp, 'project', 'render', 'draft.mp4');+ const reportPath = path.join(tmp, 'project', 'render', 'draft-report.json');+ fs.mkdirSync(compositionDir, { recursive: true });+ writeDesignContract(compositionDir);+ writeMinimalCompositionHtml(compositionDir, 'Orkas 1.5.0');++ const res = runRenderCompositionWithMockCore([+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', outputPath,+ '--report', reportPath,+ '--skip-video-qa',+ '--skip-normalize-audio',+ ], {+ ...makeFakeVideoProbeEnv(tmp),+ ORKAS_MOCK_INSPECT_VISUAL_ERROR: '1',+ ORKAS_MOCK_RENDER_OK: '1',+ });++ expect(res.status, res.stderr).toBe(0);+ const out = parseJson(res.stdout);+ expect(out.ok).toBe(true);+ expect(out.inspect).toMatchObject({+ ok: true,+ qa_ok: false,+ advisory_count: 3,+ blocking_error_count: 0,+ });+ const report = parseJson(fs.readFileSync(reportPath, 'utf8'));+ expect(report.ok).toBe(true);+ expect(report.steps.inspect).toMatchObject({+ ok: true,+ qa_ok: false,+ draft_disposition: {+ blocking_error_count: 0,+ advisory_count: 3,+ },+ });+ expect(report.steps.render).toMatchObject({ ok: true, path: outputPath });+ });++ it('fails a heavy FINAL render fast on a constrained machine (P2)', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-final-heavy-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ fs.mkdirSync(compositionDir, { recursive: true });+ // 1920x1080 × 60s → ~3726 cost units (> heavy threshold).+ writeMinimalCompositionHtml(compositionDir, 'Orkas 1.5.0', { width: 1920, height: 1080, duration: 60 });++ const res = runRenderCompositionWithMockCore([+ '--op', 'render',+ '--composition-dir', compositionDir,+ '--output', path.join(tmp, 'project', 'render', 'video.mp4'),+ '--quality', 'high',+ ], { ORKAS_MOCK_RAM_GB: '8', ORKAS_MOCK_RENDER_OK: '1' });++ expect(res.status).toBe(1);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_RENDER_TOO_HEAVY');+ expect(out.render_profile).toMatchObject({ constrained: true, decision: 'fail_fast' });+ });++ it('degrades a heavy DRAFT render (lower fps) on a constrained machine instead of failing (P2)', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-draft-degrade-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ fs.mkdirSync(compositionDir, { recursive: true });+ writeDesignContract(compositionDir, { canvas: { width: 1920, height: 1080, duration: 60, fps: 60, language: 'en' } });+ writeMinimalCompositionHtml(compositionDir, 'Orkas 1.5.0', { width: 1920, height: 1080, duration: 60 });++ const res = runRenderCompositionWithMockCore([+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),+ '--report', path.join(tmp, 'project', 'render', 'draft-report.json'),+ '--skip-video-qa',+ '--skip-normalize-audio',+ ], { ...makeFakeVideoProbeEnv(tmp), ORKAS_MOCK_RAM_GB: '8', ORKAS_MOCK_RENDER_OK: '1' });++ expect(res.status, res.stderr).toBe(0);+ const out = parseJson(res.stdout);+ expect(out.ok).toBe(true);+ expect(out.render_profile).toMatchObject({ constrained: true, decision: 'degrade', degraded_fps: '60→30' });+ });++ it('blocks draft when inspect reports non-visual errors', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-draft-inspect-blocked-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ const outputPath = path.join(tmp, 'project', 'render', 'draft.mp4');+ const reportPath = path.join(tmp, 'project', 'render', 'draft-report.json');+ fs.mkdirSync(compositionDir, { recursive: true });+ writeDesignContract(compositionDir);+ writeMinimalCompositionHtml(compositionDir, 'Orkas 1.5.0');++ const res = runRenderCompositionWithMockCore([+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', outputPath,+ '--report', reportPath,+ ], { ORKAS_MOCK_INSPECT_STRUCTURAL_ERROR: '1' });++ expect(res.status).toBe(1);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_INSPECT_BLOCKED');+ expect(out.draft_disposition).toMatchObject({+ blocking_error_count: 1,+ advisory_count: 0,+ });+ const report = parseJson(fs.readFileSync(reportPath, 'utf8'));+ expect(report.steps.inspect).toMatchObject({+ ok: false,+ qa_ok: false,+ draft_disposition: {+ blocking_error_count: 1,+ },+ });+ expect(report.steps.render).toBeUndefined();+ });++ it('blocks draft when HTML canvas differs from the design contract', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-canvas-mismatch-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ fs.mkdirSync(compositionDir, { recursive: true });+ writeDesignContract(compositionDir);+ writeMinimalCompositionHtml(compositionDir, 'Orkas 1.5.0', { width: 1080, height: 1080, duration: 10 });++ const res = runSkill('stage-compose', 'render_composition', [+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),+ ]);++ expect(res.status).toBe(1);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_CONTRACT_HTML_BLOCKED');+ expect(out.contract_html.issues).toEqual(expect.arrayContaining([+ expect.objectContaining({ code: 'CANVAS_CONTRACT_MISMATCH' }),+ ]));+ });++ it('blocks draft when declared scene copy is not present in HTML', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-scene-copy-missing-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ fs.mkdirSync(compositionDir, { recursive: true });+ writeDesignContract(compositionDir, {+ scenes: [{ id: 'cover', start: 0, duration: 10, headline: 'Orkas 1.5.0 Release Highlights' }],+ });+ writeMinimalCompositionHtml(compositionDir, 'Different title');++ const res = runSkill('stage-compose', 'render_composition', [+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),+ ]);++ expect(res.status).toBe(1);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_CONTRACT_HTML_BLOCKED');+ expect(out.contract_html.issues).toEqual(expect.arrayContaining([+ expect.objectContaining({ code: 'HTML_MISSING_SCENE_COPY' }),+ ]));+ });++ it('blocks draft with a targeted error when scene-map JSON is invalid', () => {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-compose-scene-map-invalid-'));+ const compositionDir = path.join(tmp, 'project', 'composition');+ fs.mkdirSync(compositionDir, { recursive: true });+ writeDesignContract(compositionDir);+ writeMinimalCompositionHtml(compositionDir);+ fs.writeFileSync(path.join(compositionDir, 'scene-map.json'), '{ nope', 'utf8');++ const res = runSkill('stage-compose', 'render_composition', [+ '--op', 'draft',+ '--composition-dir', compositionDir,+ '--output', path.join(tmp, 'project', 'render', 'draft.mp4'),+ ]);++ expect(res.status).toBe(1);+ const out = parseJson(res.stderr);+ expect(out.code).toBe('E_SCENE_MAP_PARSE_FAILED');+ expect(out.repair_target).toBe('scene-map.json');});it('fails edit_video before invoking ffmpeg when an input is missing', () => {diff --git a/test/main/features/video_render_diagnostics.test.ts b/test/main/features/video_render_diagnostics.test.tsnew file mode 100644index 00000000..56b92078--- /dev/null+++ b/test/main/features/video_render_diagnostics.test.ts@@ -0,0 +1,105 @@+import { describe, it, expect } from 'vitest';++import {+ parseRenderDiagnostics,+ classifyRenderCrash,+ machineRamGB,+ isConstrainedMachine,+ estimateRenderCost,+ renderCostDecision,+ degradedFps,+ LOW_RAM_GB,+ HEAVY_RENDER_COST,+} from '../../../resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_render';++describe('parseRenderDiagnostics', () => {+ // Real line captured from `hyperframes render` (0.7.3), which has a NESTED+ // "fps":{...} object — the parser must not truncate at the first `}`.+ const REAL_PIPELINE = '[INFO] [Render] Pipeline started {"platform":"darwin","arch":"arm64","nodeVersion":"v22.22.3","fps":{"num":30,"den":1},"format":"mp4","quality":"draft","browserGpuMode":"software","forceScreenshot":false,"protocolTimeout":300000,"browserTimeout":120000,"pageNavigationTimeout":60000,"playerReadyTimeout":45000}';++ it('parses browserGpuMode + timeouts from the real (nested-object) pipeline line', () => {+ const d = parseRenderDiagnostics(`some noise\n${REAL_PIPELINE}\nmore noise`);+ expect(d.gpuMode).toBe('software');+ expect(d.protocolTimeoutMs).toBe(300000);+ expect(d.browserTimeoutMs).toBe(120000);+ expect(d.playerReadyTimeoutMs).toBe(45000);+ });++ it('reads a hardware pipeline line', () => {+ const d = parseRenderDiagnostics('[INFO] [Render] Pipeline started {"browserGpuMode":"hardware","requestedWorkers":"auto","protocolTimeout":300000}');+ expect(d.gpuMode).toBe('hardware');+ expect(d.workers).toBe('auto');+ });++ it('falls back to the gpu-probe banner when there is no pipeline line', () => {+ expect(parseRenderDiagnostics('[hyperframes] browserGpuMode auto → hardware (WebGL probe succeeded)').gpuMode).toBe('hardware');+ expect(parseRenderDiagnostics('[hyperframes] browserGpuMode auto → software (no GPU)').gpuMode).toBe('software');+ });++ it('returns no gpuMode for unrelated output', () => {+ expect(parseRenderDiagnostics('ffmpeg version 6.0\nrendering frame 12').gpuMode).toBeUndefined();+ expect(parseRenderDiagnostics('').gpuMode).toBeUndefined();+ });+});++describe('classifyRenderCrash', () => {+ // Real crash tail shape from the weak-Intel-Mac report.+ const NATIVE_CRASH = 'inspect produced no findings. node::NewIsolate(v8::Isolate::CreateParams*, uv_loop_s*, node::MultiIsolatePlatform*, ...) v8::internal::SnapshotData*, v8::internal::SnapshotData*';++ it('classifies a V8 isolate/snapshot native abort (exit null) as native_worker_crash', () => {+ expect(classifyRenderCrash(NATIVE_CRASH, null, false)).toBe('native_worker_crash');+ expect(classifyRenderCrash(NATIVE_CRASH, 134, false)).toBe('native_worker_crash'); // SIGABRT-style nonzero+ });++ it('classifies a timeout as timeout regardless of stderr', () => {+ expect(classifyRenderCrash('', null, true)).toBe('timeout');+ expect(classifyRenderCrash(NATIVE_CRASH, null, true)).toBe('timeout');+ });++ it('does not misclassify a clean exit or an ordinary error', () => {+ expect(classifyRenderCrash(NATIVE_CRASH, 0, false)).toBeNull(); // exit 0 is not a crash+ expect(classifyRenderCrash('E_EDIT_FAILED: some ffmpeg error', 1, false)).toBeNull();+ expect(classifyRenderCrash('', 1, false)).toBeNull();+ });+});++describe('machineRamGB', () => {+ it('reports a positive coarse RAM figure', () => {+ const gb = machineRamGB();+ expect(gb).toBeGreaterThan(0);+ expect(gb).toBeLessThan(4096);+ });+});++describe('render-resilience profile (P1/P2)', () => {+ it('isConstrainedMachine: low RAM or observed software GPU forces constrained', () => {+ expect(isConstrainedMachine(LOW_RAM_GB)).toBe(true); // boundary: ≤8GB+ expect(isConstrainedMachine(LOW_RAM_GB - 1)).toBe(true);+ expect(isConstrainedMachine(16)).toBe(false);+ expect(isConstrainedMachine(64, 'software')).toBe(true); // software GPU forces it even on a big box+ expect(isConstrainedMachine(64, 'hardware')).toBe(false);+ });++ it('estimateRenderCost: frames × megapixels — the 60s@60fps 1080x1920 case is heavy', () => {+ const heavy = estimateRenderCost(1080, 1920, 60, 60); // ~7452+ const ok = estimateRenderCost(1080, 1920, 30, 30); // ~1863+ expect(heavy).toBeGreaterThan(HEAVY_RENDER_COST);+ expect(ok).toBeLessThan(HEAVY_RENDER_COST);+ });++ it('renderCostDecision: capable machine or light comp proceeds; heavy+constrained draft degrades, final fails fast', () => {+ const heavy = HEAVY_RENDER_COST + 1000;+ const light = HEAVY_RENDER_COST - 1000;+ expect(renderCostDecision({ constrained: false, costUnits: heavy, isFinal: true })).toBe('proceed');+ expect(renderCostDecision({ constrained: true, costUnits: light, isFinal: true })).toBe('proceed');+ expect(renderCostDecision({ constrained: true, costUnits: heavy, isFinal: false })).toBe('degrade');+ expect(renderCostDecision({ constrained: true, costUnits: heavy, isFinal: true })).toBe('fail_fast');+ });++ it('degradedFps: lowers >30 fps to 30, leaves ≤30 as-is', () => {+ expect(degradedFps(60)).toBe(30);+ expect(degradedFps(48)).toBe(30);+ expect(degradedFps(30)).toBe(30);+ expect(degradedFps(24)).toBe(24);+ });+});diff --git a/test/main/features/video_studio_core_freshness.test.ts b/test/main/features/video_studio_core_freshness.test.tsnew file mode 100644index 00000000..9e50b19b--- /dev/null+++ b/test/main/features/video_studio_core_freshness.test.ts@@ -0,0 +1,42 @@+import { describe, it, expect } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { createRequire } from 'node:module';++// The runtime loads the committed `scripts/lib/*_core.cjs` bundles, not the+// `_shared/scripts/src/*.ts` sources. Editing a source without re-running the+// build script would silently ship stale behavior — this test is the guard:+// rebuild every core with the repo's own esbuild and byte-compare against the+// committed bundle. Deterministic because esbuild is version-locked and the+// build disables sourcemaps/legal comments.+const requireCjs = createRequire(import.meta.url);+const { outputs, buildTo, pcDir } = requireCjs('../../../scripts/build-video-studio-skill-core.cjs') as {+ outputs: Array<{ entry: string; outfile: string }>;+ buildTo: (outfileFor: (item: { entry: string; outfile: string }) => string) => Promise<+ Array<{ item: { entry: string; outfile: string }; outfile: string }>+ >;+ pcDir: string;+};++describe('video-studio bundled skill cores', () => {+ it('committed lib/*_core.cjs bundles match a fresh build of _shared/scripts/src', async () => {+ expect(outputs.length).toBeGreaterThan(0);+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-core-freshness-'));+ try {+ const built = await buildTo((item) => path.join(tmp, path.basename(item.outfile)));+ const stale: string[] = [];+ for (const { item, outfile } of built) {+ const committed = fs.readFileSync(item.outfile);+ const fresh = fs.readFileSync(outfile);+ if (!committed.equals(fresh)) stale.push(path.relative(pcDir, item.outfile));+ }+ expect(+ stale,+ `stale bundled cores (source changed without rebuild): ${stale.join(', ')} — run: node PC/scripts/build-video-studio-skill-core.cjs and commit the updated bundles`,+ ).toEqual([]);+ } finally {+ fs.rmSync(tmp, { recursive: true, force: true });+ }+ }, 120_000);+});