Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
refactor: isolate build execution and complete production workflow
kashorin870fc33bc49e
diff --git a/README.md b/README.mdindex fe22a186..85d2de87 100644--- a/README.md+++ b/README.md@@ -20,7 +20,7 @@<p align="center"><a href="https://github.com/hypit-ai/hypit/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/hypit-ai/hypit?style=flat-square&color=FFD700&logo=github&logoColor=white&label=Stars"></a>- <a href="./package.json"><img alt="Node 22.12+" src="https://img.shields.io/badge/Node.js-22.12%2B-5FA04E?style=flat-square&logo=nodedotjs&logoColor=white"></a>+ <a href="./package.json"><img alt="Node 22.15+" src="https://img.shields.io/badge/Node.js-22.15%2B-5FA04E?style=flat-square&logo=nodedotjs&logoColor=white"></a><a href="./package.json"><img alt="pnpm 10.33" src="https://img.shields.io/badge/pnpm-10.33-F69220?style=flat-square&logo=pnpm&logoColor=white"></a><a href="./package.json"><img alt="TypeScript 5.9" src="https://img.shields.io/badge/TypeScript-5.9-3178C6?style=flat-square&logo=typescript&logoColor=white"></a><a href="./LICENSE"><img alt="License" src="https://img.shields.io/badge/License-Apache--2.0%20with%20conditions-E3B341?style=flat-square"></a>diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 217e2059..03b3747e 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -20,7 +20,7 @@<p align="center"><a href="https://github.com/hypit-ai/hypit/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/hypit-ai/hypit?style=flat-square&color=FFD700&logo=github&logoColor=white&label=Stars"></a>- <a href="./package.json"><img alt="Node 22.12+" src="https://img.shields.io/badge/Node.js-22.12%2B-5FA04E?style=flat-square&logo=nodedotjs&logoColor=white"></a>+ <a href="./package.json"><img alt="Node 22.15+" src="https://img.shields.io/badge/Node.js-22.15%2B-5FA04E?style=flat-square&logo=nodedotjs&logoColor=white"></a><a href="./package.json"><img alt="pnpm 10.33" src="https://img.shields.io/badge/pnpm-10.33-F69220?style=flat-square&logo=pnpm&logoColor=white"></a><a href="./package.json"><img alt="TypeScript 5.9" src="https://img.shields.io/badge/TypeScript-5.9-3178C6?style=flat-square&logo=typescript&logoColor=white"></a><a href="./LICENSE"><img alt="License" src="https://img.shields.io/badge/License-Apache--2.0%20with%20conditions-E3B341?style=flat-square"></a>diff --git a/docs/guide/author-packages.md b/docs/guide/author-packages.mdindex 85ca51dd..70f667e9 100644--- a/docs/guide/author-packages.md+++ b/docs/guide/author-packages.md@@ -79,3 +79,15 @@ version, compile and pack its code and assets with `npm pack`, or publish underin npm or a private registry. For registry publication, remove `private: true` and supply the normalpackage metadata. Consumers install the selected version and commit their package-manager lockfile.A Hypit repository checkout or upstream pull request is not needed to use the component.++## See a complete production++The [complex spoken explainer](https://github.com/hypit-ai/hypit/tree/main/examples/complex-explainer)+combines presenter framing, independent captions, website demonstrations and coordinated animated+scenes in one finished work. Its project guide follows each decision to the Source, Recipe or package+that owns it. The example distinguishes a useful component boundary from the separate choices to+expose parameters or design for reuse. Accepted material is supplied separately, so its default Run+can open and render the composition without another generation request.++[Watch the finished film](https://storage.googleapis.com/hypit-public-assets/assets/examples/complex-explainer/v1/20260914/final.mp4)+or follow the example's download instructions to open its accepted material in Studio.diff --git a/docs/guide/conventions.md b/docs/guide/conventions.mdindex bf1e9dba..4abe76a8 100644--- a/docs/guide/conventions.md+++ b/docs/guide/conventions.md@@ -11,7 +11,7 @@ These conventions describe work inside the Hypit repository. Project extensions|---|---|---|| Package directory | kebab-case | `packages/speech-alignment/` || Package name | `@hypit/` scope | `@hypit/speech-alignment` |-| Provider package | `provider-` prefix | `@hypit/provider-kie` |+| Provider package | `provider-` prefix | `@studio/provider-images` || TypeScript file | kebab-case | `align.ts` || Exported type | PascalCase | `SpeechAlignment` || Exported function | camelCase | `createSpeechAlignment` |diff --git a/docs/guide/develop.md b/docs/guide/develop.mdindex 2143815d..338fd74b 100644--- a/docs/guide/develop.md+++ b/docs/guide/develop.md@@ -7,7 +7,7 @@ description: Getting started with Hypit development.| Tool | Version | Required for ||---|---|---|-| Node.js | 22.12+ | everything |+| Node.js | 22.15+ | everything || pnpm | 10.33.x | workspace management; selected by the root `packageManager` field || Python | 3.10–3.13 | local WhisperX and OpenCV Managed Programs || uv | latest | Python environment management |diff --git a/docs/guide/providers.md b/docs/guide/providers.mdindex 9e61c215..6a7fd35a 100644--- a/docs/guide/providers.md+++ b/docs/guide/providers.md@@ -8,6 +8,11 @@ A **Provider** knows how to fulfill that request through a particular service. Aconfigured instance of that Provider, with its service address, credential reference and capacity.The Runtime Profile binds the requested capability to an Endpoint.+Hypit's official Distribution includes local Providers and the HypiHub Provider. Other services+connect through packages owned by the production or their authors. The Agent can implement a new+service through the public SDK, just as it can create a visual component for a video.+[Service partners](./service-partners.md) introduces independent partners through that same path.+## Choose the change that matches the need| You want to… | Change |@@ -58,6 +63,10 @@ owns the handler interfaces, activation, resource declarations and pricing API.to JavaScript and install it in the project through its package manager. Configure its Endpointunder `endpoints` and select it in `bindings` in the [Runtime Profile](./runtime.md).+The [complete project Provider example](https://github.com/hypit-ai/hypit/tree/main/examples/provider-package)+demonstrates reference uploads, task receipts, collection and pricing using an illustrative API.+It also ships with the executable, so the Agent can adapt it without a repository checkout.+## Prices and permissionThe Provider declares local work without a Provider charge, or supplies its published pricing page.diff --git a/docs/guide/runtime.md b/docs/guide/runtime.mdindex f2cb7982..8c3f78fd 100644--- a/docs/guide/runtime.md+++ b/docs/guide/runtime.md@@ -224,7 +224,12 @@ therefore select separately, even when their Profiles declare equivalent externa`runtime up` asks npm to prepare the selected adapters' exact upstream packages in the sharedmachine home, prepares declared **local** Managed Programs, then starts the local Worker. It does notstart, restart, log into or probe remote Endpoints such as HypiHub. `runtime down` stops only the-local Worker; separately managed local Programs remain available until `programs down`.+local Worker and its execution processes; separately managed local Programs remain available until `programs down`.++Use `--endpoint <instance>` on `runtime up`, `programs up|status|down`, or `doctor` to operate on a+chosen service; repeat it for several services. Omitting it covers the whole Profile. Build planning+checks the Endpoints actually selected for that work. Optional upstream package versions have separate+installations, so preparing one version does not replace another; npm retains its shared download cache.`doctor` is the active read-only environment check. It resolves declared credentials and lets eachselected Endpoint verify its real environment; a remote Provider may therefore contact its bounded@@ -244,21 +249,25 @@ the exact `result` or `cleanup` step. After fixing the external problem, an operOperation values, working bytes and the exact Result Repository; it never loads or invokes a Produceror Endpoint. It idempotently writes the Result, removes the working directory, then atomically removesthe active SQLite aggregate. Only one Result writer may own that work at a time; this mutual--exclusion lease is not a phase and never changes the decision. A Worker restarted after a hard interruption-clears the abandoned lease and records attention, but performs no storage action automatically. Missing bytes-fail explicitly instead of being regenerated.+exclusion lease is not a phase and never changes the decision. After a hard interruption, the coordinator+clears abandoned Result-writer leases. An already decided Build whose Result writing was interrupted retains attention+for `result finish`; a Build that lost its executor is concluded and its available facts are written to+Result. Missing bytes fail explicitly instead of being regenerated.Reusing an earlier Result is an explicit Candidate in a new `.svrun`, not hidden Runtime behavior.-A running Worker loads installed Component packages as Builds first require them. A later Build may-name a new Component package without restarting the Worker; the Worker loads only packages it has-not already seen from that package's complete dependency closure. Loaded package code is not hot-reloaded, so editing a package or updating the Distribution still requires stopping an idle Worker-before the next Build.--The Worker records the normalized literal Runtime Profile, not a hash. A changed Profile is not-silently applied to a live Worker. SQLite separately pins credential and Endpoint selection while any-pending or active Build remains, so a restarted Worker cannot poll an old Operation handle through new-Endpoint config.+Each Build uses its own loaded project implementation and selected Provider configuration. Editing project components or changing Profile selections therefore applies to the next+Build while already started work keeps its loaded implementation. Managed Programs keep their own+lifetime, so a warm model remains available across Builds. Concurrent Builds share execution+infrastructure. Remote waiting does not reserve a whole-Build slot; declared resource limits apply+to the work using those resources.+The local Runtime can rotate execution processes as completed-work memory accumulates: existing Builds+finish in their current process while new Builds use another. Warm services stay available.++If an executor is lost, its affected attempts end with completed Outputs and available remote receipts;+it is not restarted with newly edited code. Continue through a new Build and explicit reuse. Files+read later by a component retain ordinary filesystem semantics. Distribution updates and changes to+the coordinator's inherited shell environment still require restarting that bootstrap process after+preserving active work.Runtime packages are trusted local deployment code. npm or pnpm owns their installed versions;Hypit only selects exact requirements and invokes npm at the explicit `runtime up`/`packages install`diff --git a/docs/guide/service-partners.md b/docs/guide/service-partners.mdnew file mode 100644index 00000000..e5b8ab3c--- /dev/null+++ b/docs/guide/service-partners.md@@ -0,0 +1,22 @@+---+title: Service partners+description: Independent service partners and how they connect to Hypit.+---++HypiHub is Hypit's recommended integrated hosted service for supported generation and WhisperX+work. Its Provider is maintained with Hypit. Local execution remains available through the local+Providers, and users can connect their own services through project Providers.++The services introduced below are independent partners. They have their own accounts, terms,+prices, model availability and APIs. A partnership is an introduction, not a shared HypiHub account+or an automatically installed integration. Choose a service for the work and connect its supported+capabilities through the ordinary [Model and Provider](./providers.md) extension path.++## Monid++[Monid](https://monid.ai) is a Hypit service partner.+[Its documentation](https://docs.monid.ai/) describes its available tools and access methods.+Check the capabilities, reference inputs and rates required by the production before choosing the+account. An installed compatible Provider can be reused; otherwise the Agent can implement the+needed API mapping in a project package.+diff --git a/docs/guide/testing.md b/docs/guide/testing.mdindex d79a8760..799ca517 100644--- a/docs/guide/testing.md+++ b/docs/guide/testing.md@@ -60,18 +60,10 @@ test("compiles the expected exports", async () => {### Provider tests-Test Endpoint implementations with real or simulated external services. Environment-gated: check-for required credentials or executables and skip when absent.--```typescript-test("generates a video", async (t) => {- if (!process.env.KIE_API_KEY) {- t.skip("KIE_API_KEY not set");- return;- }- // ... real API call-});-```+Exercise request mapping, media transport and task progression against a controlled service fixture.+The [project Provider example](https://github.com/hypit-ai/hypit/tree/main/examples/provider-package)+includes a lifecycle test that collects a returned image without spending on generation. Live calls+use the selected service and explicit spending scope; an available key alone does not authorize them.### Architecture boundariesdiff --git a/docs/quickstart.md b/docs/quickstart.mdindex 4fa75e38..2cd151ad 100644--- a/docs/quickstart.md+++ b/docs/quickstart.md@@ -46,11 +46,14 @@ project and explains the direction as the work develops.The Agent checks the relevant tools and services already available. For a spoken reference, WhisperXprovides the words and their timing so the Agent can relate the picture to what is being said.-If it is missing, the Agent can help prepare it locally or explain the hosted option.+If it needs preparation, the Agent explains the local effort and hosted option before you choose.+Cached weights can reduce setup time; they do not choose a service for you.[HypiHub](https://hypit.ai) offers hosted WhisperX and image, video and voice models through one-account. You can also use your own keys with supported Providers, and combine local and hosted-capabilities. The Agent explains what is needed and helps connect the services you choose.+account. You can also use your own keys through existing or project-written Providers, and combine+local and hosted capabilities. The Agent connects what the next part of the work needs, explains+progress and shows its reference understanding before developing the material plan. Generation+accounts can be chosen when that plan establishes the models you need.## 4. Agree on the cost and let production rundiff --git a/docs/quickstart/generation.md b/docs/quickstart/generation.mdindex 61d982bd..bfbd1667 100644--- a/docs/quickstart/generation.md+++ b/docs/quickstart/generation.md@@ -104,7 +104,7 @@ model-selected duration or an integer from 4 through 30 seconds:```svml<seedance:ReferenceVideo id="long-take" model="2.5"prompt={long-direction} duration="30" resolution="720p">- <seedance:Reference image={presenter-reference}/>+ <seedance:Reference image={presenter-reference} person-reference="true"/><seedance:Reference audio={presenter-voice}/></seedance:ReferenceVideo>```@@ -143,11 +143,21 @@ video and audio references within the model's declared limits.prompt={alice-direction}duration="5"generate-audio="true">- <seedance:Reference image={alice-reference}/>+ <seedance:Reference image={alice-reference} person-reference="true"/><seedance:Reference audio={alice-voice}/></seedance:ReferenceVideo>```+On an image or video reference, `person-reference="true"` declares a person/avatar in the supplied+material, including a generated human likeness. Use false for a reference without that content;+omission leaves the classification unspecified. Audio references do not use this visual flag.+Frame mode provides `first-frame-person-reference` and `last-frame-person-reference`. The selected+Provider carries this fact through the service's media preparation.++A video reference can guide dance, physical action or camera movement while images guide the new+appearance. Choose an excerpt that carries the intended motion within the selected model and+service's input-duration limits; the requested output duration is a separate choice.+The component does not know that this is a talking head. That meaning lives in the supplied Text.Common attributes are `id`, `model`, `prompt`, `duration`, `resolution`, `aspect-ratio` and@@ -163,14 +173,14 @@ edge. Extraction does not turn it into speech evidence or attach speaker meaning<seedance:ReferenceVideo id="follow-up" model="mini"prompt={follow-up-direction} duration="5" generate-audio="true">- <seedance:Reference image={presenter-reference}/>+ <seedance:Reference image={presenter-reference} person-reference="true"/><seedance:Reference audio={voice-from-opening.audio}/></seedance:ReferenceVideo>```The same media-operation package exposes `Transform` for ordered trim/retime and `ExtractFrame` for-first, last, indexed or timestamped still extraction. Local FFmpeg and AWS Lambda are interchangeable-Runtime Endpoints for these exact Needs; neither changes the author graph.+first, last, indexed or timestamped still extraction. Local FFmpeg implements these exact Needs. Another compatible Runtime Endpoint can be selected+without changing the author graph.## Seedance semantic Kits@@ -260,9 +270,9 @@ camera changes and performance in its authored action, in the exact order they s<seedance:ReferenceVideo id="interview-take" model="mini"prompt={interview-prompt} duration="8"resolution="720p" aspect-ratio="9:16" generate-audio="true">- <seedance:Reference image={interviewer-view}/>- <seedance:Reference image={guest-view}/>- <seedance:Reference image={shared-view}/>+ <seedance:Reference image={interviewer-view} person-reference="true"/>+ <seedance:Reference image={guest-view} person-reference="true"/>+ <seedance:Reference image={shared-view} person-reference="true"/><seedance:Reference audio={interviewer-voice}/><seedance:Reference audio={guest-voice}/></seedance:ReferenceVideo>@@ -298,7 +308,7 @@ module. The result enters Seedance through the same explicit `prompt` edge as anprompt={hook-prompt}duration="8"resolution="720p" aspect-ratio="9:16" generate-audio="true">- <seedance:Reference image={presenter-clean}/>+ <seedance:Reference image={presenter-clean} person-reference="true"/><seedance:Reference audio={presenter-voice}/></seedance:ReferenceVideo>```@@ -337,12 +347,12 @@ generation:<seedance:ReferenceVideo id="hook-take" model="mini" prompt={hook-prompt}duration="8" resolution="720p" aspect-ratio="9:16" generate-audio="true">- <seedance:Reference image={presenter-clean}/>+ <seedance:Reference image={presenter-clean} person-reference="true"/><seedance:Reference audio={presenter-voice}/></seedance:ReferenceVideo><seedance:ReferenceVideo id="meeting-take" model="mini" prompt={meeting-prompt}duration="6" resolution="720p" aspect-ratio="9:16" generate-audio="true">- <seedance:Reference image={presenter-alt}/>+ <seedance:Reference image={presenter-alt} person-reference="true"/><seedance:Reference audio={presenter-voice}/></seedance:ReferenceVideo>```diff --git a/docs/quickstart/images.md b/docs/quickstart/images.mdindex 59a52be1..d1a24c8c 100644--- a/docs/quickstart/images.md+++ b/docs/quickstart/images.md@@ -9,8 +9,7 @@ source of another operation.They all need an endpoint. `image-compose` and `image-transform` ask for the raster capability, which`@hypit/provider-image-opencv-local` answers by running OpenCV in a bounded Python process on-your own machine; `background-removal` asks for its own capability, which `@hypit/provider-kie`-answers remotely. Select the supporting Endpoint in your [Runtime Profile](/guide/runtime)+your own machine; `background-removal` asks for its own capability, which a selected project Provider implements. Select the supporting Endpoint in your [Runtime Profile](/guide/runtime)when using these operations.## Composing layersdiff --git a/docs/quickstart/run.md b/docs/quickstart/run.mdindex f97dd808..e967984d 100644--- a/docs/quickstart/run.md+++ b/docs/quickstart/run.md@@ -257,27 +257,16 @@ is a configuration starting point, not evidence that an account was chosen.After choosing a service, connect its credential:-| Variable | Provider/use |-|---|---|-| HypiHub OAuth | HypiHub paid generation, WhisperX alignment; run `hypit auth login hypihub.default --runtime hypit.runtime.json` |-| `KIE_API_KEY` | Explicit KIE Provider only |-| `MIMO_API_KEY` | Xiaomi MiMo Voice Design or Voice Clone, only when the official Endpoint is explicitly selected |--Run only the lines for the Endpoints in your Profile. In macOS/Linux shells:+For a chosen HypiHub account:```bash-read -r -s KIE_API_KEY-export KIE_API_KEY-read -r -s MIMO_API_KEY-export MIMO_API_KEY+hypit auth login hypihub.default```-In Windows PowerShell:--```powershell-$env:KIE_API_KEY = "your-key"-$env:MIMO_API_KEY = "your-key"-```+For another selected Endpoint, use its declared secure input, such as+`hypit auth login images.personal`. Its Provider describes the required credential and its Profile+selects the Store. A project Provider follows the same path. Environment-backed credentials are+set in the Worker environment according to that Provider's configuration.Keep credentials out of Author Source, Run Source, Runtime Profile source, and committed files.`doctor` validates required credential presence without printing secret values.@@ -414,8 +403,9 @@ A plain `status <build-id>` prints one snapshot. `status --watch` exits when theEach invocation creates a fresh Build id, even when the Author and Run Sources are unchanged. Thatis necessary for non-deterministic generation: cross-Build reuse belongs only to explicit Candidates-in a Run Source. While a Build is active, a Worker restart continues its accepted execution facts-and the same external task checkpoints; it never turns another invocation into that Build.+in a Run Source. Closing an observer leaves the Worker running. Losing a Build's execution context+ends that attempt; restarting the Worker does not resume it. Completed Outputs and recorded task+receipts remain available, and further execution uses a new Build with explicit reuse.### 5. Inspect and retrieve results@@ -461,7 +451,9 @@ hypit runtime logshypit runtime down```-`runtime down` stops the Worker from advancing Builds but leaves external programs running.-Use `programs down` only when those programs should also stop. Neither command cancels durable-Builds or remote Provider work. Starting the same Profile again continues its active Builds from-their already accepted execution facts.+`runtime down` stops the coordinator and its execution processes, leaving Managed Programs running.+Unfinished Builds whose execution contexts end cannot resume when the Worker starts again. Preserve+their completed Outputs and recorded receipts, then use a new Build for further work. Work that was+submitted but never started can still start. Use `programs down` when the separate Programs should+also stop. To cancel a selected Build's remote work, use `hypit cancel <build-id>` while its execution+context is available; stopping local processes does not itself cancel remote Provider tasks.diff --git a/docs/zh/guide/author-packages.md b/docs/zh/guide/author-packages.mdindex 3162dcd4..56090425 100644--- a/docs/zh/guide/author-packages.md+++ b/docs/zh/guide/author-packages.md@@ -45,3 +45,9 @@ preview Source 为作者提供可打开或渲染的小例子。查看能说明将它声明的元素与输出用于编排。`hypit vocabulary` 展示作者接口,`hypit check` 检查 Source 或 Run。组件 README 应包含可复制示例、输出、实用的创作选择和行为示意图。组件服务于当前作品时,就与项目一起保存。需要分享时,选择发布版本,编译并用 `npm pack` 打包代码和素材,或通过所有者自己的 scope 发布到 npm 或私有 Registry。发布到 Registry 时去掉 `private: true`,补充普通包元信息。使用者安装选定版本并提交包管理器 lockfile。使用组件不需要 Hypit 仓库 checkout,也不需要向主仓库提 PR。++## 阅读一个完整作品++[复杂口播示例](https://github.com/hypit-ai/hypit/tree/main/examples/complex-explainer) 将主持人变场、独立字幕、网页演示和多个协同动效场景组合成完整作品。项目说明把每种修改指向负责它的 Source、Recipe 或组件包。它区分了三件事:划分组件职责、开放有用参数、为真实需求设计复用。已接受素材单独提供,默认 Run 可以直接打开并渲染这份编排,无需重新请求生成。++可以直接[观看最终成片](https://storage.googleapis.com/hypit-public-assets/assets/examples/complex-explainer/v1/20260914/final.mp4),也可以按照示例中的下载说明取得素材包,在 Studio 中打开完整作品。diff --git a/docs/zh/guide/conventions.md b/docs/zh/guide/conventions.mdindex a5f4c0c7..7f9959b1 100644--- a/docs/zh/guide/conventions.md+++ b/docs/zh/guide/conventions.md@@ -11,7 +11,7 @@ description: 命名、模块边界、TypeScript 配置与 wire 数据。|---|---|---|| 包目录 | kebab-case | `packages/speech-alignment/` || 包名 | `@hypit/` scope | `@hypit/speech-alignment` |-| Provider 包 | `provider-` 前缀 | `@hypit/provider-kie` |+| Provider 包 | `provider-` 前缀 | `@studio/provider-images` || TypeScript 文件 | kebab-case | `align.ts` || 导出类型 | PascalCase | `SpeechAlignment` || 导出函数 | camelCase | `createSpeechAlignment` |diff --git a/docs/zh/guide/develop.md b/docs/zh/guide/develop.mdindex f98e0d74..e33b4b9f 100644--- a/docs/zh/guide/develop.md+++ b/docs/zh/guide/develop.md@@ -7,7 +7,7 @@ description: 开始 Hypit 开发工作。| 工具 | 版本 | 用于 ||---|---|---|-| Node.js | 22.12+ | 所有工作 |+| Node.js | 22.15+ | 所有工作 || pnpm | 10.33.x | workspace 管理;由根目录 `packageManager` 字段选择 || Python | 3.10–3.13 | 本地 WhisperX 与 OpenCV Managed Program || uv | latest | Python 环境管理 |diff --git a/docs/zh/guide/providers.md b/docs/zh/guide/providers.mdindex 862996b8..e2276f9a 100644--- a/docs/zh/guide/providers.md+++ b/docs/zh/guide/providers.md@@ -5,6 +5,8 @@ description: 选择账户、连接服务或添加模型,沿用同一套视频**Model** 定义要生成什么:输入、支持的参数和输出类型。**Provider** 知道如何通过某个服务完成这个请求。**Endpoint** 是配置好的 Provider 实例,包含服务地址、凭据引用和容量。Runtime Profile 将所需能力绑定到 Endpoint。+官方发行包含本地 Provider 和 HypiHub Provider。其他服务通过项目或作者自己的包接入;Agent 可以使用公开 SDK 编写所需接入,就像为视频创建视觉组件。[服务合作方介绍](../../guide/service-partners.md) 集中介绍独立合作服务,它们沿用同一套扩展方式。+## 根据需求选择修改位置| 你想做什么 | 修改哪里 |@@ -39,6 +41,8 @@ import type { AsyncEndpoint, CredentialRef, EndpointRequest } from "@hypit/hypit[Endpoint SDK](https://github.com/hypit-ai/hypit/blob/main/packages/endpoint-kit/README.md) 维护处理接口、activation、资源声明和价格 API。将包编译为 JavaScript,由项目包管理器安装。在 [Runtime Profile](./runtime.md) 的 `endpoints` 中配置实例,并通过 `bindings` 选择它。+[完整项目 Provider 示例](https://github.com/hypit-ai/hypit/tree/main/examples/provider-package) 使用示意 API 展示参考上传、任务回执、结果收集与价格读取。示例随执行包分发,Agent 无需仓库 checkout 就能读取和改写。+## 价格与授权Provider 可以声明本地执行没有 Provider 调用费用,或提供公开费率页面。它也可以使用 Endpoint 凭据读取当前费率,返回简洁摘要及原始价格材料。`hypit pricing <run>` 将费率与计划请求一起展示;未来素材的测量值在产物存在前仍是未知的。diff --git a/docs/zh/guide/runtime.md b/docs/zh/guide/runtime.mdindex f95078ae..d37416f2 100644--- a/docs/zh/guide/runtime.md+++ b/docs/zh/guide/runtime.md@@ -200,9 +200,13 @@ BYOK 或本地 Provider 时可以编辑 Profile 或选择另一份 Profile。`runtime up` 先让 npm 把所选 Adapter 的精确上游包准备到机器共享目录,再准备所选的**本地**Managed Program 并启动本地 Worker。它不会启动、重启、登录或探测 HypiHub 这类远程 Endpoint。-`runtime down` 只停止本地 Worker;由 Runtime 管理的本地 Program 会继续可用,直到显式运行+`runtime down` 停止本地 Worker 和它的执行进程;由 Runtime 管理的本地 Program 会继续可用,直到显式运行`programs down`。+`runtime up`、`programs up|status|down` 和 `doctor` 都可以用 `--endpoint <instance>` 只处理已选定的+服务;需要多个服务时可以重复这个参数。不传时处理整个 Profile。Build 规划则检查本次工作实际选中的+Endpoint。可选上游包按准确版本分别安装,准备一个版本不会替换另一个版本,npm 的下载缓存仍然共享。+`doctor` 才是主动但只读的环境检查。它解析已声明的凭据,并允许每个所选 Endpoint 检查真实环境;远程 Provider 因而可以访问一次有界的模型目录或能力接口。登录成功只证明凭据存在,doctor 成功才证明该账户此刻可以路由所选 Endpoint 声明的能力。普通 `check`、`plan` 和 Build 预检都不会运行这类@@ -217,18 +221,21 @@ Result 写入或活跃状态清理失败时,decision 保持不变,并记录只读取已保存的 Build facts、已结束 Operation 值、工作字节和固定 Result Repository,不加载或调用 Producer与 Endpoint。Result writer 核对并写入同一个 Result,再删除工作目录,最后原子删除整个 SQLite 活跃聚合。同一个 Build 同时只能被一个 Result writer 占用;这个互斥 lease 不是 phase,也不改变 decision。-进程若硬中断,下一 Worker 只撤销遗留 lease、记录 attention,不自动执行存储动作。工作字节丢失会明确失败,不补生成。+硬中断后,协调进程撤销遗留的 Result writer lease。已有终态、但 Result 写入中断的 Build 保留 attention,+由 `result finish` 收尾;丢失执行进程的活跃 Build 则结束这次尝试,将已有事实写入 Result。+工作字节丢失会明确失败,不补生成。已结束 Build 不恢复;复用以前的 Result 必须在新的 `.svrun` 中显式写 Candidate。-运行中的 Worker 会在 Build 第一次需要某个已安装 Component 包时加载它。后续 Build 可以在-不重启 Worker 的情况下新增 Component 包;Worker 会沿完整依赖闭包只加载尚未见过的部分。-已经加载的包代码不会热更新,因此修改包代码或更新 Distribution 后,仍需等 Worker 空闲再将-其停止,然后提交下一次 Build。+每次 Build 都使用独立加载的项目实现和选定的 Provider 配置。修改项目组件或+Profile 后,新的 Build 使用新实现,已经开始的工作继续使用它加载的实现。Managed Program 有独立+生命周期,本地模型可以继续保持就绪。并发 Build 共享执行基础设施,远程等待不占用整单执行名额;+具体工作的并发仍遵循其声明的资源额度。+本地 Runtime 可以在已完成工作的内存积累后轮换执行进程:已有 Build 留在原进程做完,新 Build 进入新进程,+已经就绪的常驻服务继续可用。-Worker 记录启动时规范化后的完整 Runtime Profile。Profile 在 Worker 存活期间改变时,`status` 会报告-配置已变化,`up` 会拒绝静默复用旧进程,Worker 也会停止;重新启动才会激活新环境。这里保存的是活动-进程配置文本,不是哈希,也不进入 Build Result。SQLite 另外只固定当前活跃执行使用的 credential 与-Endpoint 选择,避免新 Endpoint 配置轮询旧 handle。+执行进程丢失会结束它承载的活跃 Build,并保留已完成的产物和已有的远程回执,不会用修改后的代码重新运行+同一次 Build。继续制作时创建新 Build 并显式复用。组件后来主动读取的文件仍遵循正常文件语义。+更新 Distribution 或修改协调进程继承的环境变量,仍需先保留活跃工作,再重启这一启动进程。Runtime 包是本地可信部署代码,其安装版本由 npm 或 pnpm 管理。Hypit 只在显式 `runtime up` /`packages install` 边界选择精确依赖并调用 npm,不维护第二份包锁,也不会把元数据冒充成沙箱。diff --git a/docs/zh/quickstart.md b/docs/zh/quickstart.mdindex 15217f09..ec3fc9fb 100644--- a/docs/zh/quickstart.md+++ b/docs/zh/quickstart.md@@ -39,7 +39,9 @@ npx skills add hypit-ai/hypit -gAgent 会先检查相关工具与已有服务。对于有对白的参考视频,WhisperX 提供词语及其时间,帮助 Agent 把画面变化和说话内容联系起来。缺少时,Agent 可以协助在本机准备,也会说明托管选项。-[HypiHub](https://hypit.ai) 通过一个账户提供托管 WhisperX 和图片、视频、音色模型。你也可以通过支持的 Provider 使用自己的 Key,或组合本地与托管能力。Agent 会解释需要什么,再协助连接你选择的服务。+[HypiHub](https://hypit.ai) 通过一个账户提供托管 WhisperX 和图片、视频、音色模型。本地服务需要准备时,Agent 会先解释实际安装成本与托管选择,再由你选择;已有模型缓存可以减少准备时间,但不代替这个选择。++你也可以通过已有或项目编写的 Provider 使用自己的 Key,或组合本地与托管能力。Agent 根据下一步的工作连接所需能力,持续说明进展,并展示对参考视频的理解。等素材方案明确需要哪些模型时,再解决相应生成账户的选择。## 4. 确认费用,开始制作diff --git a/docs/zh/quickstart/generation.md b/docs/zh/quickstart/generation.mdindex 68c94dc3..e171990d 100644--- a/docs/zh/quickstart/generation.md+++ b/docs/zh/quickstart/generation.md@@ -93,7 +93,7 @@ Seedance 2.5 复用同样的 Surface,而不是由 Runtime 把别的模型偷```svml<seedance:ReferenceVideo id="long-take" model="2.5"prompt={long-direction} duration="30" resolution="720p">- <seedance:Reference image={presenter-reference}/>+ <seedance:Reference image={presenter-reference} person-reference="true"/><seedance:Reference audio={presenter-voice}/></seedance:ReferenceVideo>```@@ -128,11 +128,19 @@ Seedance 2.5 复用同样的 Surface,而不是由 Runtime 把别的模型偷prompt={alice-direction}duration="5"generate-audio="true">- <seedance:Reference image={alice-reference}/>+ <seedance:Reference image={alice-reference} person-reference="true"/><seedance:Reference audio={alice-voice}/></seedance:ReferenceVideo>```+图片或视频参考上的 `person-reference="true"` 声明素材中含有人物/数字人形象,AI 生成的人像也适用。+没有这类内容时可写 false;省略表示没有提供分类。音频参考不使用这个视觉标记。+首尾帧模式提供 `first-frame-person-reference` 和 `last-frame-person-reference`。+选定的 Provider 负责把这项事实交给服务的素材准备流程。++舞蹈、身体动作或运镜可以由参考视频提供运动依据,再用参考图指定新的形象与场景。+围绕需要保留的动作选取片段,并核对模型与服务的参考视频时长上限;它和要生成的视频时长是两回事。+这个低层组件并不知道它被用来做口播;用途只存在于传入的 Text 中。公共属性包括`id`、`model`、`prompt`、`duration`、`resolution`、`aspect-ratio`、`generate-audio`;`duration` 是模型范围内的整秒字面量,事先用 `hypit measure` 量好。@@ -145,13 +153,12 @@ Seedance 2.5 复用同样的 Surface,而不是由 Runtime 把别的模型偷<seedance:ReferenceVideo id="follow-up" model="mini"prompt={follow-up-direction} duration="5" generate-audio="true">- <seedance:Reference image={presenter-reference}/>+ <seedance:Reference image={presenter-reference} person-reference="true"/><seedance:Reference audio={voice-from-opening.audio}/></seedance:ReferenceVideo>```-同一个媒体操作包还提供 `Transform`(按顺序截取、变速)和 `ExtractFrame`(首帧、尾帧、指定帧或指定时间取图)。本地 FFmpeg 与 AWS Lambda 只是这些精确 Need 的可互换 Runtime-Endpoint,不会改变作者图。+同一个媒体操作包还提供 `Transform`(按顺序截取、变速)和 `ExtractFrame`(首帧、尾帧、指定帧或指定时间取图)。本地 FFmpeg 实现这些精确 Need;也可以选择其他兼容的 Runtime Endpoint,作者图保持不变。## Seedance 语义 Kit@@ -225,9 +232,9 @@ Source Closure 沿着这个显式包导入读取内容。如果共享措辞不<seedance:ReferenceVideo id="interview-take" model="mini"prompt={interview-prompt} duration="8"resolution="720p" aspect-ratio="9:16" generate-audio="true">- <seedance:Reference image={interviewer-view}/>- <seedance:Reference image={guest-view}/>- <seedance:Reference image={shared-view}/>+ <seedance:Reference image={interviewer-view} person-reference="true"/>+ <seedance:Reference image={guest-view} person-reference="true"/>+ <seedance:Reference image={shared-view} person-reference="true"/><seedance:Reference audio={interviewer-voice}/><seedance:Reference audio={guest-voice}/></seedance:ReferenceVideo>@@ -259,7 +266,7 @@ dialogue/action 由普通 Text 模块组装,结果再像其他生成任务一<seedance:ReferenceVideo id="hook-take" model="mini"prompt={hook-prompt} duration="8"resolution="720p" aspect-ratio="9:16" generate-audio="true">- <seedance:Reference image={presenter-clean}/>+ <seedance:Reference image={presenter-clean} person-reference="true"/><seedance:Reference audio={presenter-voice}/></seedance:ReferenceVideo>```@@ -296,12 +303,12 @@ dialogue/action 由普通 Text 模块组装,结果再像其他生成任务一<seedance:ReferenceVideo id="hook-take" model="mini" prompt={hook-prompt}duration="8" resolution="720p" aspect-ratio="9:16" generate-audio="true">- <seedance:Reference image={presenter-clean}/>+ <seedance:Reference image={presenter-clean} person-reference="true"/><seedance:Reference audio={presenter-voice}/></seedance:ReferenceVideo><seedance:ReferenceVideo id="meeting-take" model="mini" prompt={meeting-prompt}duration="6" resolution="720p" aspect-ratio="9:16" generate-audio="true">- <seedance:Reference image={presenter-alt}/>+ <seedance:Reference image={presenter-alt} person-reference="true"/><seedance:Reference audio={presenter-voice}/></seedance:ReferenceVideo>```diff --git a/docs/zh/quickstart/images.md b/docs/zh/quickstart/images.mdindex b7c5e793..7431cb39 100644--- a/docs/zh/quickstart/images.md+++ b/docs/zh/quickstart/images.md@@ -5,7 +5,7 @@ description: 在图片流向生成器或 Track 之前,对它做合成、校正有三个包接收一张图片、交还一张图片。它们都不产出 Track:每个输出都是一张可供下游引用的图片——作为 Seedance 的参考帧、作为 Media Item,或作为下一次操作的来源。-它们都需要 Endpoint。`image-compose` 与 `image-transform` 索取 raster 能力,由 `@hypit/provider-image-opencv-local` 在本机运行 OpenCV 来满足;`background-removal` 索取的是它自己声明的能力,由 `@hypit/provider-kie` 远程满足。使用这些操作时,在 [Runtime Profile](/zh/guide/runtime) 中选择支持它们的 Endpoint。+它们都需要 Endpoint。`image-compose` 与 `image-transform` 索取 raster 能力,由 `@hypit/provider-image-opencv-local` 在本机运行 OpenCV 来满足;`background-removal` 索取的是它自己声明的能力,由所选项目 Provider 实现。使用这些操作时,在 [Runtime Profile](/zh/guide/runtime) 中选择支持它们的 Endpoint。## 合成图层diff --git a/docs/zh/quickstart/run.md b/docs/zh/quickstart/run.mdindex 27e26fad..39cd7f52 100644--- a/docs/zh/quickstart/run.md+++ b/docs/zh/quickstart/run.md@@ -220,27 +220,15 @@ hypit auth status选择服务后,再连接其凭据:-| 变量 | Provider / 用途 |-|---|---|-| HypiHub OAuth | HypiHub 付费生成、WhisperX 对齐;运行 `hypit auth login hypihub.default --runtime hypit.runtime.json` 并在 https://hypit.ai 登录 |-| `KIE_API_KEY` | 仅在显式选择 KIE Provider 时使用 |-| `MIMO_API_KEY` | Xiaomi MiMo 音色设计或音色克隆;只有明确选择官方 Endpoint 时才需要 |--只执行 Profile 中所选 Endpoint 对应的行。在 macOS/Linux Shell 中:+已选择 HypiHub 账户时:```bash-read -r -s KIE_API_KEY-export KIE_API_KEY-read -r -s MIMO_API_KEY-export MIMO_API_KEY+hypit auth login hypihub.default```-在 Windows PowerShell 中:--```powershell-$env:KIE_API_KEY = "your-key"-$env:MIMO_API_KEY = "your-key"-```+其他所选 Endpoint 使用它声明的安全输入方式,例如 `hypit auth login images.personal`。+Provider 说明需要哪种凭据,Profile 选择存储方式;项目 Provider 沿用同一条路径。+如果使用环境变量存储,则按 Provider 的配置在 Worker 环境中设置。不要把凭据写进 Author Source、Run Source、Runtime Profile 源文件或提交内容。`doctor` 会验证所需凭据是否存在,但不会打印秘密值。@@ -389,9 +377,9 @@ hypit status <build-id> --watch| `--follow` | 将 Build 进度流式输出到终端 |每次执行都会创建新的 Build id,即使 Author Source 和 Run Source 完全没变。这是非确定性生成-所要求的边界:跨 Build 复用只能由 Run Source 里的显式 Candidate 决定。一次 Build 提交后-处于活跃状态时具有耐久性;Worker 重启会继续它已经接受的执行事实和同一外部任务,但不会让-另一次命令变成这个 Build。+所要求的边界:跨 Build 复用只能由 Run Source 里的显式 Candidate 决定。关闭观察终端不会停止+Worker;但 Build 一旦失去执行上下文,这次尝试就结束,重启 Worker 不会恢复它。已完成的+Output 和记录下来的任务凭据会保留;后续执行通过新 Build 显式复用已有工作。### 5. 检查并获取结果@@ -431,6 +419,8 @@ hypit runtime logshypit runtime down```-`runtime down` 只会让 Worker 停止领取新 Build,并保留外部程序;只有确实要停掉这些程序时-才执行 `programs down`。两条命令都不会取消耐久 Build 或远程 Provider 工作。再次启动同一-Profile 后,会从已经接受的执行事实继续推进其中的活跃 Build。+`runtime down` 停止协调器及其执行进程,保留独立的 Managed Program。未完成的 Build 一旦+失去执行上下文,就不会在 Worker 重启后恢复;保留其已完成 Output 和任务凭据,通过新 Build+继续制作。已提交但从未开始的 Build 仍可开始。只有确实要停掉独立程序时才执行 `programs down`。+要取消某个 Build 的远程工作,应在其执行上下文仍可用时调用 `hypit cancel <build-id>`;+停止本地进程本身不会取消远程 Provider 任务。diff --git a/examples/README.md b/examples/README.mdindex 64aacaf4..94f3305d 100644--- a/examples/README.md+++ b/examples/README.md@@ -1,15 +1,21 @@# Video examples-Each of the three formats has one complete generation entry, `reference.svml`, with an adjacent-`reference.svrun`. These Sources generate their main images, recurring voice references and video-Takes, then normalize media, align the Script and compose the finished video. They need no earlier-Build Result or manually supplied presenter, host or scene image.+These projects demonstrate different directing and composition decisions. Read the one closest to+the question, then trace its intent, component boundaries, semantic events and rendered behavior.+Adapt those relationships to a new work; its scene list and styling are choices for that production.-| Example | What its reference entry demonstrates |-| --- | --- |-| [Football ranking](ranking-football/README.md) | One generated goth host, eight generated comic B-roll images, real player icons, independent speaking Takes and a persistent tier board |-| [Podcast](podcast/README.md) | Related host views, a generated creatine product, holding views, a split opening and a three-scene lifestyle montage |-| [Street interview](interview/README.md) | A shared encounter and two derived close views, motivated cuts, coordinated Moment reveals, and a fresh-footage Caption tracking extension |+| Example | What to learn | Starting material |+| --- | --- | --- |+| [Football ranking](ranking-football/README.md) | Independent speaking Takes, a persistent tier board and timed reveals | Generate from `reference.svrun` |+| [Podcast](podcast/README.md) | Related host views, product references, motivated cuts and a lifestyle montage | Generate from `reference.svrun` |+| [Street interview](interview/README.md) | A shared encounter, derived close views, coordinated Moments and Caption tracking | Generate from `reference.svrun` |+| [Complex spoken explainer](complex-explainer/README.md) | Coordinated project scenes, moving presenter framing, independent Caption, semantic graphic events and Take-free intervals | Download its accepted media/Result bundle; render locally |++The three generation entries use `reference.svml` and an adjacent `reference.svrun`. They generate+their main images, recurring voice references and video Takes, then normalize media, align the Script+and compose the video. They need no earlier Build Result or manually supplied presenter, host or scene+image. The explainer instead opens a complete 137-second production with 17 accepted Takes, recorded+demonstrations, pixel graphics and sound; its default Run reuses the supplied material.Self-contained here means a project directory: SVML, its imported SVS/Kits and the selected localassets. The installed Hypit Distribution supplies the imported packages. A Runtime Profile and@@ -21,4 +27,6 @@ The other `swap-*` and nested projects preserve separate variations and reuse stall been rebuilt to the same generation standard as these three reference entries. A linked showcasevideo demonstrates the original production; a fresh generation is a new result and will differ.-`minimal-author-package/` demonstrates independent component packaging.+For focused package work, `minimal-author-package/` demonstrates independent component packaging;+[provider-package](provider-package/README.md) demonstrates connecting a chosen service through a+project Provider. Each package's public inputs and behavior belong with its implementation.diff --git a/examples/complex-explainer/.gitignore b/examples/complex-explainer/.gitignorenew file mode 100644index 00000000..aadbdada--- /dev/null+++ b/examples/complex-explainer/.gitignore@@ -0,0 +1,5 @@+node_modules/+.hypit/+productions/explainer/assets/+productions/explainer/output/+FEEDBACK.jsondiff --git a/examples/complex-explainer/README.md b/examples/complex-explainer/README.mdnew file mode 100644index 00000000..ae413851--- /dev/null+++ b/examples/complex-explainer/README.md@@ -0,0 +1,105 @@+# Complex spoken explainer++A complete Chinese explainer combining 17 accepted performances, website demonstrations and eight+project-owned animated scenes. Its 137-second Timeline includes an opening montage without speech,+full-frame and circular presenter views, a half-frame handoff, covered narration, and a silent ending.++The source is an editable production, not a general-purpose explainer template. It demonstrates how+to give each visual relationship an owner while exposing only the parameters the author actually needs.++[Watch the finished film](https://storage.googleapis.com/hypit-public-assets/assets/examples/complex-explainer/v1/20260914/final.mp4)+(137 seconds, approximately 42 MiB), or+[download the complete media archive](https://storage.googleapis.com/hypit-public-assets/assets/examples/complex-explainer/v1/20260914/media.tar.gz)+(approximately 455 MiB) to open the editable production below.++## Open the production++Use the Hypit checkout accompanying this example. The example has been validated against that+checkout; it does not claim compatibility with an older published Distribution. Install the+project-local packages from this directory:++```sh+npm ci --ignore-scripts+```++The code is stored in Git. Images, recordings, accepted Result resources and a finished video are+supplied separately in the media archive. Download and extract the archive **at this directory**:++```sh+mkdir -p .hypit+curl --fail --location 'https://storage.googleapis.com/hypit-public-assets/assets/examples/complex-explainer/v1/20260914/media.tar.gz' --output .hypit/media.tar.gz+tar -xzf .hypit/media.tar.gz+```++The archive contains source assets, one portable Result with 50 accepted Outputs and their resource+files, and the finished film. It preserves the resource bindings inside composite values. It contains+accepted material rather than generation history; private review notes, credentials and the original+reference creator's footage are excluded. Media is hosted on Google Cloud Storage and stays outside Git.+After extraction, `.hypit/media.tar.gz` can be removed to reclaim the archive's download space.++```sh+cd productions/explainer+hypit check runs/render.svrun+hypit plan runs/render.svrun --runtime ../../hypit.runtime.json+hypit studio --run runs/render.svrun --runtime ../../hypit.runtime.json+```++Open the printed **Comments** URL (`#comments`) to review the composition before export and leave+timestamped direction on the current picture. In the same session, switch to **Studio** to explore+the timeline and adjust exposed parameters. Browser review does not render a video file. Notes save to+this workspace's `FEEDBACK.json`; the Agent can read and resolve them while editing the owning Source+or scene code. Existing private review conversations are not included. The Inspector remains useful+for the selected Caption, Style and event choices without exposing every internal scene dimension.++The default Run explicitly selects 50 accepted Outputs from the bundled Result. Its remaining plan+contains only local visual rendering, audio mixing and muxing. The included Profile has no generation+account, credential store or transcription service. Material has already been normalized and given+its semantic timing; opening this example does not generate or transcribe it again.++Submit `runs/render.svrun` to render the complete film. `runs/export-parts.svrun` instead renders five+consecutive ranges for limited temporary disk space. Its local Profile requests eight rendering+workers and one render request at a time. The [production guide](productions/explainer/README.md)+explains joining exported parts. The archive also includes `productions/explainer/output/final.mp4`.++## Read the work by responsibility++| Question | Owner |+| --- | --- |+| What is said, and which words motivate a change? | [Script](productions/explainer/authors/script.svml) |+| Which raw resources, clock and canvas are used? | [Assets](productions/explainer/authors/assets.svml) |+| What directed the accepted performance? | [Direction](productions/explainer/authors/direction.svml), [performance Recipe](productions/explainer/recipes/performance.svs) |+| How are Takes, Uses, events and contributions assembled? | [Main Source](productions/explainer/authors/main.svml) |+| How does the Caption look? | [Composition Recipe](productions/explainer/recipes/composition.svs) |+| How does each coordinated scene behave? | [Web scenes](packages/web-scenes/README.md) |+| How do the presenter and opening graphics move? | [Opening system](packages/opening-system/README.md) |+| How are cue boundaries and one-line captions handled? | [Caption package](packages/single-line-captions/README.md) |+| Which existing material should a new Build use? | [Render Run](productions/explainer/runs/render.svrun) |++Generated and normalized Outputs remain in the entry Source where the Run can satisfy them explicitly.+Changing a cue break or graphic event does not require replacing the performance. A rewrite of the+spoken words is different: supply a new Take with timing for that Script and select it in the Run.+The retained generation declarations show the original direction but are not invoked by the default+Run. Configure an explicitly chosen Model/Provider path before requesting new material.++## What this example teaches++A coordinated editor scene can own its folder, pointer, preview and timeline without publishing a+control for every dimension. The presenter, Caption and countdown change for different reasons and+remain independent. Shared palette and typing helpers are ordinary code dependencies, not extra+Tracks. The scene's state is computed from frame time, making direct seeking and range rendering+possible. Script Moments locate spoken changes; authored durations shape how those changes unfold.++Read the [Treatment](productions/explainer/TREATMENT.md) and+[craft notes](productions/explainer/CRAFT-NOTES.md) for the practical reasoning. Components use public+Author Package and Companion interfaces; Studio and Core contain no dispatch for this example.++## Materials and editorial copy++The host image and voice are AI-generated. The competitor-case demonstrations were made by the+project owner. The phone's drinking callback uses a newly generated fictional illustration, not the+reference creator's footage. Website captures and product marks retain their sources; the diagrams,+repeated marks and token counters are authored illustrations rather than measured product tests.+See [asset provenance](productions/explainer/ASSET-PROVENANCE.md).++This is the owner's authored explainer, including its comparisons and rhetorical claims. The+reusable lesson is how the production is expressed, not a benchmark of other products.diff --git a/examples/complex-explainer/hypit.runtime.json b/examples/complex-explainer/hypit.runtime.jsonnew file mode 100644index 00000000..bc1d9194--- /dev/null+++ b/examples/complex-explainer/hypit.runtime.json@@ -0,0 +1,24 @@+{+ "format": "hypit.runtime-local@1",+ "dataRoot": ".hypit/execution",+ "endpoints": {+ "media.local": {+ "use": "@hypit/provider-media-local",+ "config": {+ "defaultConcurrency": 2+ }+ },+ "hyperframes.local": {+ "use": "@hypit/provider-hyperframes-local",+ "config": {+ "workers": 8,+ "defaultConcurrency": 1+ }+ }+ },+ "bindings": {+ "@hypit/render-hyperframes@1#render-visual": "hyperframes.local",+ "@hypit/media-pipeline@1#render-timeline-audio": "media.local",+ "@hypit/media-pipeline@1#mux-program-media": "media.local"+ }+}diff --git a/examples/complex-explainer/package-lock.json b/examples/complex-explainer/package-lock.jsonnew file mode 100644index 00000000..3d69bdbf--- /dev/null+++ b/examples/complex-explainer/package-lock.json@@ -0,0 +1,65 @@+{+ "name": "hypit-complex-explainer",+ "version": "0.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "hypit-complex-explainer",+ "version": "0.0.0",+ "dependencies": {+ "@explainer/launch-scenes": "file:packages/launch-scenes",+ "@explainer/opening-system": "file:packages/opening-system",+ "@explainer/single-line-captions": "file:packages/single-line-captions",+ "@explainer/visual-language": "file:packages/visual-language",+ "@explainer/web-scenes": "file:packages/web-scenes"+ }+ },+ "node_modules/@explainer/launch-scenes": {+ "resolved": "packages/launch-scenes",+ "link": true+ },+ "node_modules/@explainer/opening-system": {+ "resolved": "packages/opening-system",+ "link": true+ },+ "node_modules/@explainer/single-line-captions": {+ "resolved": "packages/single-line-captions",+ "link": true+ },+ "node_modules/@explainer/visual-language": {+ "resolved": "packages/visual-language",+ "link": true+ },+ "node_modules/@explainer/web-scenes": {+ "resolved": "packages/web-scenes",+ "link": true+ },+ "packages/launch-scenes": {+ "name": "@explainer/launch-scenes",+ "version": "0.0.0"+ },+ "packages/opening-system": {+ "name": "@explainer/opening-system",+ "version": "0.0.0",+ "dependencies": {+ "@explainer/visual-language": "file:../visual-language"+ }+ },+ "packages/single-line-captions": {+ "name": "@explainer/single-line-captions",+ "version": "0.0.0"+ },+ "packages/visual-language": {+ "name": "@explainer/visual-language",+ "version": "0.0.0"+ },+ "packages/web-scenes": {+ "name": "@explainer/web-scenes",+ "version": "0.0.0",+ "dependencies": {+ "@explainer/visual-language": "file:../visual-language"+ }+ }+ }+}diff --git a/examples/complex-explainer/package.json b/examples/complex-explainer/package.jsonnew file mode 100644index 00000000..67261f4e--- /dev/null+++ b/examples/complex-explainer/package.json@@ -0,0 +1,13 @@+{+ "name": "hypit-complex-explainer",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "dependencies": {+ "@explainer/opening-system": "file:packages/opening-system",+ "@explainer/launch-scenes": "file:packages/launch-scenes",+ "@explainer/web-scenes": "file:packages/web-scenes",+ "@explainer/single-line-captions": "file:packages/single-line-captions",+ "@explainer/visual-language": "file:packages/visual-language"+ }+}diff --git a/examples/complex-explainer/packages/launch-scenes/README.md b/examples/complex-explainer/packages/launch-scenes/README.mdnew file mode 100644index 00000000..05f79f44--- /dev/null+++ b/examples/complex-explainer/packages/launch-scenes/README.md@@ -0,0 +1,5 @@+# Montage poster++This project package supplies the current `PosterTitle` treatment: a pink headline with a dark offset outline and a cream subtitle label. Text, subtitle, vertical position, sizes, gap and drawing order are useful author choices. The supplied Timeline Window determines its presence; the font is an explicit asset.++The Companion exposes those same fields through standard Studio controls and temporal lineage. Rendering owns local HTML/CSS and produces a visual contribution only. Earlier metal-title and introductory scene studies remain in private history; the active introductory and comparison scenes belong to `web-scenes`.diff --git a/examples/complex-explainer/packages/launch-scenes/package.json b/examples/complex-explainer/packages/launch-scenes/package.jsonnew file mode 100644index 00000000..674bf3a1--- /dev/null+++ b/examples/complex-explainer/packages/launch-scenes/package.json@@ -0,0 +1,16 @@+{+ "name": "@explainer/launch-scenes",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "hypit": {+ "activation": "./src/activation.js"+ },+ "exports": {+ ".": "./src/render.js"+ },+ "files": [+ "src",+ "README.md"+ ]+}diff --git a/examples/complex-explainer/packages/launch-scenes/src/activation.js b/examples/complex-explainer/packages/launch-scenes/src/activation.jsnew file mode 100644index 00000000..be87acbc--- /dev/null+++ b/examples/complex-explainer/packages/launch-scenes/src/activation.js@@ -0,0 +1,360 @@+import { sceneCompanions } from "./studio.js";+import { createStudioTrackCompanionHostFacet } from "@hypit/hypit/studio-adapter";+import {+ assertAttributes,+ assertEmptyElement,+ textAttribute,+ canonicalize,+ sameType,+ sealGraphFragment,+ createMarkupSurfaceHostFacet,+} from "@hypit/hypit/author-kit";+import { compositionTypes } from "@hypit/hypit/composition";+import { mediaTypes } from "@hypit/hypit/media";+import { timelineTypes } from "@hypit/hypit/timeline";+import { spatialTypes } from "@hypit/hypit/spatial";+import { temporalTypes, assertTemporalInstantFor } from "@hypit/hypit/temporal";+import {+ resolveTemporalContext,+ createTemporalWindowProjection,+ createTemporalInstantProjection,+ temporalWindowAttributeNames,+ temporalWindowAttributeVocabulary,+ temporalContextAttributeVocabulary,+ temporalInstantAttributeNames,+ temporalInstantAttributeVocabulary,+} from "@hypit/hypit/temporal-markup";+import { renderPoster } from "./render.js";+const module = { name: "@explainer/launch-scenes", version: "1" },+ type = (name) => ({ module, name }),+ producer = (name) => ({ module, name }),+ port = (name, type) => ({ name, type });+const options = type("Options"),+ events = type("Events");+const common = [+ port("timeline", timelineTypes.track),+ port("canvas", spatialTypes.canvas),+ port("window", temporalTypes.window),+ port("font", mediaTypes.fontArtifact),+ port("options", options),+ port("events", events),+];+const tags = {+ PosterTitle: {+ name: "poster",+ render: renderPoster,+ assets: [],+ defaults: {+ text: "Hypit",+ subtitle: "",+ z: 45,+ y: 0.18,+ size: 180,+ "subtitle-size": 44,+ "subtitle-gap": 36,+ },+ },+};+const ins = (tag) => [...common, ...tags[tag].assets.map((n) => port(n, mediaTypes.blobArtifact))];+export const manifest = {+ format: "hypit.module@1",+ ...module,+ dependencies: [+ ...new Map(+ [+ compositionTypes.visualTrack,+ mediaTypes.fontArtifact,+ mediaTypes.blobArtifact,+ timelineTypes.track,+ spatialTypes.canvas,+ temporalTypes.window,+ temporalTypes.instant,+ ].map((t) => [t.module.name, { module: t.module }]),+ ).values(),+ ],+ types: [{ name: "Options" }, { name: "Events" }],+ capabilities: [],+ producers: [+ { name: "empty", inputs: [], outputs: [port("events", events)], needs: [] },+ {+ name: "append",+ inputs: [+ port("timeline", timelineTypes.track),+ port("events", events),+ port("options", options),+ port("at", temporalTypes.instant),+ ],+ outputs: [port("events", events)],+ needs: [],+ },+ ...Object.keys(tags).map((tag) => ({+ name: tags[tag].name,+ inputs: ins(tag),+ outputs: [port("track", compositionTypes.visualTrack)],+ needs: [],+ })),+ ],+};+const inline = (r) => {+ if (r?.value.kind !== "inline") throw Error("Expected inline scene value");+ return r.value.value;+ },+ value = (v) => ({ kind: "inline", value: canonicalize(v) }),+ out = (n, v) => ({ outputs: { [n]: value(v) }, needs: {} });+const component = {+ producers: [+ { producer: producer("empty"), handler: () => out("events", []) },+ {+ producer: producer("append"),+ handler: ({ inputs: i }) => {+ const o = inline(i.options),+ at = inline(i.at),+ list = inline(i.events);+ assertTemporalInstantFor(at, {+ subjectId: o.id,+ space: inline(i.timeline),+ });+ if (list.some((e) => e.name === o.name)) throw Error("Beat names must be unique");+ return out("events", [...list, { ...o, at }]);+ },+ },+ ...Object.keys(tags).map((tag) => ({+ producer: producer(tags[tag].name),+ handler: ({ inputs: i }) =>+ out(+ "track",+ tags[tag].render(+ inline(i.timeline),+ inline(i.canvas),+ inline(i.window),+ inline(i.font),+ inline(i.options),+ inline(i.events),+ Object.fromEntries(tags[tag].assets.map((n) => [n, i[n].value])),+ ),+ ),+ })),+ ],+};+function decode(tag) {+ return ({ element, resolveReference }) => {+ const spec = tags[tag];+ assertAttributes(element, [+ "id",+ "timeline",+ "canvas",+ "font",+ ...spec.assets,+ ...Object.keys(spec.defaults),+ ...temporalWindowAttributeNames,+ ]);+ const id = textAttribute(element, "id"),+ context = resolveTemporalContext({ element, resolveReference }),+ window = createTemporalWindowProjection({+ id: id + ".window",+ subjectId: id,+ element,+ ...context,+ resolveReference,+ });+ const ref = (el, n, t) => {+ const raw = el.attributes[n];+ if (typeof raw !== "object" || raw.kind !== "reference")+ throw Error(n + " must be a reference");+ const r = resolveReference(raw.path);+ if (!r || !sameType(r.type, t)) throw Error(n + " has wrong type");+ return r.ref;+ };+ const opts = { id };+ for (const [n, d] of Object.entries(spec.defaults)) {+ const v = element.attributes[n];+ if (v !== undefined && typeof v !== "string") throw Error(n + " must be literal");+ opts[n] = typeof d === "number" ? Number(v ?? d) : (v ?? d);+ }+ if (!Number.isSafeInteger(opts.z)) throw Error("z must be integer");+ const records = [+ ...window.records,+ {+ id: id + ".options",+ type: options,+ value: value(opts),+ range: element.range,+ },+ ],+ components = [...window.components],+ fragments = [...window.fragments];+ const inputs = ins(tag).filter((p) => p.name !== "events"),+ bindings = {+ timeline: context.timeline.ref,+ canvas: ref(element, "canvas", spatialTypes.canvas),+ window: window.ref,+ font: ref(element, "font", mediaTypes.fontArtifact),+ options: { kind: "record", id: id + ".options" },+ };+ for (const n of spec.assets) bindings[n] = ref(element, n, mediaTypes.blobArtifact);+ const input = (name) => ({ kind: "fragment-input", name }),+ op = (operation) => ({ kind: "fragment-operation", operation }),+ operations = [+ {+ id: "empty",+ producer: producer("empty"),+ inputs: {},+ result: { kind: "output", name: "events" },+ },+ ];+ let prev = "empty",+ count = 0;+ for (const ch of element.children) {+ if (ch.kind === "text") {+ if (ch.value.trim()) throw Error("Expected Beat");+ continue;+ }+ if (ch.name.split(":").at(-1) !== "Beat") throw Error("Expected Beat");+ assertAttributes(ch, ["name", ...temporalInstantAttributeNames]);+ assertEmptyElement(ch);+ const name = textAttribute(ch, "name"),+ key = "beat" + ++count,+ eid = id + "." + key,+ at = createTemporalInstantProjection({+ id: eid,+ subjectId: eid,+ element: ch,+ ...context,+ resolveReference,+ });+ records.push(...at.records, {+ id: eid + ".options",+ type: options,+ value: value({ id: eid, name }),+ range: ch.range,+ });+ components.push(...at.components);+ fragments.push(...at.fragments);+ inputs.push(port(key, options), port(key + "-at", temporalTypes.instant));+ bindings[key] = { kind: "record", id: eid + ".options" };+ bindings[key + "-at"] = at.ref;+ operations.push({+ id: key,+ producer: producer("append"),+ inputs: {+ timeline: input("timeline"),+ events: op(prev),+ options: input(key),+ at: input(key + "-at"),+ },+ result: { kind: "output", name: "events" },+ });+ prev = key;+ }+ operations.push({+ id: "render",+ producer: producer(spec.name),+ inputs: {+ ...Object.fromEntries(+ ins(tag)+ .filter((p) => p.name !== "events")+ .map((p) => [p.name, input(p.name)]),+ ),+ events: op(prev),+ },+ result: { kind: "output", name: "track" },+ });+ const fragment = sealGraphFragment({+ inputs,+ operations,+ exports: [+ {+ name: "track",+ type: compositionTypes.visualTrack,+ root: op("render"),+ },+ ],+ });+ return {+ records,+ fragments: [...fragments, fragment],+ components: [+ ...components,+ {+ id,+ fragment: fragment.id,+ inputs: bindings,+ outputs: { track: id + ".track" },+ range: element.range,+ },+ ],+ exports: [id + ".track"],+ };+ };+}+export const hypitPackage = {+ format: "hypit.node-package@1",+ modules: [{ manifest }],+ components: [component],+ hostFacets: [+ createStudioTrackCompanionHostFacet(sceneCompanions(module, tags)),+ ...Object.keys(tags).map((tag) =>+ createMarkupSurfaceHostFacet({+ module,+ declaration: {+ name: tags[tag].name,+ tag,+ mode: "structured",+ outputs: [+ options,+ events,+ compositionTypes.visualTrack,+ temporalTypes.window,+ temporalTypes.instant,+ temporalTypes.windowSpec,+ temporalTypes.instantSpec,+ ],+ vocabulary: {+ summary: "Project launch scene with phrase-driven visual beats.",+ attributes: [+ ...temporalContextAttributeVocabulary,+ ...temporalWindowAttributeVocabulary,+ ...["id", "canvas", "font", ...tags[tag].assets].map((name) => ({+ name,+ kind: "expression",+ required: true,+ summary: name,+ })),+ ...Object.keys(tags[tag].defaults).map((name) => ({+ name,+ kind: "literal",+ required: false,+ summary: name,+ })),+ ],+ children: [+ {+ tag: "Beat",+ cardinality: "many",+ summary: "Named event in the scene, projected from a Moment or authored time.",+ attributes: [+ {+ name: "name",+ kind: "literal",+ required: true,+ summary: "Behavioral event name",+ },+ ...temporalInstantAttributeVocabulary,+ ],+ },+ ],+ ports: [+ {+ name: "track",+ type: compositionTypes.visualTrack,+ summary: "Visual contribution",+ },+ ],+ },+ },+ handler: decode(tag),+ }),+ ),+ ],+};+export default hypitPackage;diff --git a/examples/complex-explainer/packages/launch-scenes/src/render.js b/examples/complex-explainer/packages/launch-scenes/src/render.jsnew file mode 100644index 00000000..265e59af--- /dev/null+++ b/examples/complex-explainer/packages/launch-scenes/src/render.js@@ -0,0 +1,69 @@+import { sealVisualTrack } from "@hypit/hypit/composition";+import { browserProgram } from "@hypit/hypit/hyperframes";+import { assertTemporalWindowFor } from "@hypit/hypit/temporal";+const sty = (o) => Object.entries(o).map(([name, value]) => ({ name, value }));+const esc = (s) =>+ String(s).replace(+ /[&<>"']/g,+ (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c],+ );+function seal(t, c, w, o, html, css, setup, data, children = []) {+ assertTemporalWindowFor(w, { subjectId: o.id, space: t });+ return sealVisualTrack({+ id: o.id,+ programSpaceId: t.id,+ visualIr: "hypit.visual-ir@1",+ presents: [+ {+ id: o.id,+ span: w.span,+ stacking: { order: o.z, tieBreak: o.id },+ elements: [+ {+ id: "scene",+ kind: "program",+ order: 0,+ program: browserProgram({+ html: html + '<div class="font-resource">{{font}}</div>',+ css:+ ":scope{pointer-events:none}.font-resource{position:absolute;width:1px;height:1px;opacity:0;overflow:hidden}" ++ css,+ setup:+ `const family=getComputedStyle(root.querySelector('.font-resource>*')).fontFamily;root.style.fontFamily=family;` ++ setup,+ data,+ }),+ style: sty({+ position: "absolute",+ inset: 0,+ width: c.widthPx + "px",+ height: c.heightPx + "px",+ }),+ },+ {+ id: "font",+ parent: "scene",+ kind: "text",+ order: 1,+ text: "Hypit 字",+ fonts: [data.font],+ style: sty({ "font-size": "12px" }),+ },+ ...children,+ ],+ },+ ],+ });+}+export function renderPoster(t, c, w, font, o) {+ return seal(+ t,+ c,+ w,+ o,+ `<div class="poster"><div class="poster-title">${esc(o.text)}</div><div class="poster-subtitle">${esc(o.subtitle)}</div></div>`,+ `.poster{position:absolute;left:5%;top:${o.y * 100}%;width:90%;text-align:center}.poster-title{font-size:${o.size}px;line-height:1.05;color:#ff79bc;-webkit-text-stroke:5px #2b1f30;paint-order:stroke fill;text-shadow:2px 2px #2b1f30,4px 4px #2b1f30,7px 8px #2b1f30;filter:drop-shadow(0 0 1px #ffe6f2)}.poster-subtitle{display:inline-block;margin-top:${o["subtitle-gap"]}px;padding:10px 26px 13px;font-size:${o["subtitle-size"]}px;line-height:1.2;color:#2b1f30;background:#fff0f7;border:3px solid #2b1f30;border-radius:6px;box-shadow:6px 7px 0 #fa67aa}`,+ "return frame=>{};",+ { font },+ );+}diff --git a/examples/complex-explainer/packages/launch-scenes/src/studio.js b/examples/complex-explainer/packages/launch-scenes/src/studio.jsnew file mode 100644index 00000000..fd266f97--- /dev/null+++ b/examples/complex-explainer/packages/launch-scenes/src/studio.js@@ -0,0 +1,63 @@+import { compositionTypes } from "@hypit/hypit/composition";+import { textLayer, temporalLineageFor } from "@hypit/hypit/studio-adapter";+const fields = {+ PosterTitle: [+ ["text", "Title", "text"],+ ["subtitle", "Subtitle", "text"],+ ["y", "Y", "number"],+ ["size", "Title size", "number"],+ ["subtitle-size", "Subtitle size", "number"],+ ["subtitle-gap", "Subtitle gap", "number"],+ ],+};+export function sceneCompanions(module, tags) {+ return Object.entries(tags).map(([tag, spec]) => {+ const inspector = [...fields[tag], ["z", "Drawing order", "number"]].map(+ ([binding, label, control]) => ({+ binding,+ label,+ control,+ domain: ["y", "z"].includes(binding) ? "where" : "how",+ section: { id: "title", label: "Title" },+ ...(binding === "y" ? { unit: "%", number: { scale: 100, step: 1 } } : {}),+ ...(["size", "subtitle-size", "subtitle-gap"].includes(binding)+ ? { unit: "px", number: { minimum: 0, step: 1 } }+ : {}),+ }),+ );+ return {+ id: spec.name,+ role: "track",+ output: {+ type: compositionTypes.visualTrack,+ surface: spec.name,+ modules: [module],+ },+ family: "launch-scenes",+ label: "Montage title",+ tone: "orange",+ icon: "text",+ lane: { heightPx: 44 },+ bindings: inspector.map((f) => ({+ name: f.binding,+ writable: true,+ fallback: spec.defaults[f.binding],+ })),+ inspector,+ project(context) {+ return context.generic().map((e) => ({+ ...e,+ temporal: temporalLineageFor(context, context.placement.id, "window"),+ display: {+ title: "Montage title",+ layers: [+ textLayer(+ context.placement?.attributes.text ?? context.placement?.attributes.title ?? tag,+ ),+ ],+ },+ }));+ },+ };+ });+}diff --git a/examples/complex-explainer/packages/opening-system/README.md b/examples/complex-explainer/packages/opening-system/README.mdnew file mode 100644index 00000000..07b0c302--- /dev/null+++ b/examples/complex-explainer/packages/opening-system/README.md@@ -0,0 +1,56 @@+# Opening system++Project components and Performance Styles for an explanation-led video. They share the film's Timeline and Canvas but own independent visual behavior. Connect each `.track` to Film explicitly. They produce no audio.++- **Title**: opening clock and a two-level headline in a pink window card. Existing presenter footage continues beneath it at its original brightness. Its outer Window ends on the authored “开始” Moment in this production. `seconds` is the promise printed on the title, not the estimated duration of the film.+- **Timer**: a persistent topic plaque, pennant and dot-matrix timer. Its Window's first frame starts the countdown; zero is followed by coral overtime counting upward. `title`, `subtitle`, `seconds`, `flag-color`, `x`, `y`, `width`, `flag-amplitude`, `flag-speed`, `entrance-frames` and `z` are author choices. It does not infer pauses from speech or stop when a Take is absent.+- **Flag**: an independent low-angle pixel flag. It uses the same deterministic pixel texture treatment as Timer, with its own Window, placement, dimensions and color. No relationship to the opposition boards is inferred. The current Source places it below captions during the first-road explanation. `flag-amplitude` and `flag-speed` keep the folds slow and the logo readable.+- **Stage**: independent images or normalized videos in a clear foreground viewport, with the same material enlarged, blurred and dimmed behind it. Each Item has its own projected Window. Foreground and background share exact video sampling. An image is held during its Window. Later declared Items paint above earlier ones if they overlap. Empty intervals stay empty. `fit="contain"` preserves the supplied screenshot; `cover` fills and crops. `x`, `y`, `width`, `height` are fractions of Canvas dimensions. `blur` is specified at a reference width of 1080 and scales with Canvas width. `brightness`, `zoom`, `radius` and `z` finish the treatment.++The visual components accept the shared temporal Window forms: `during`, `at` plus `for`, `until` plus `for`, and `start`/`end` with semantic references. Stage Items use the same forms. The Surface projects those values; drawing code consumes the resolved Windows. Literal time is useful for a rapid montage, while the complete montage can follow a Segment end.++```svml+<import as="gfx" from="@explainer/opening-system@1"/>+<gfx:Title id="opening-title" timeline={program.timeline} canvas={canvas} font={display-font}+ start="program.start" end="moment.cue" moment={story.moment.begin}+ title="Hypit" subtitle="一分钟了解" seconds="60"/>+<gfx:Timer id="series-timer" timeline={program.timeline} canvas={canvas} font={display-font} logo={flag-logo}+ start="moment.cue" end="program.end" moment={story.moment.begin} title="Hypit"/>+<gfx:Stage id="coverage" timeline={program.timeline} canvas={canvas} during={story.selection.example}>+ <gfx:Item id="demo" video={prepared-demo.media} during={story.selection.example}/>+</gfx:Stage>+```++`video` accepts SynchronizedMedia after normalization, not a raw video Blob. `source-start-frame` optionally selects its starting source frame; native playback preserves source frame rate. A requested Window longer than the remaining video produces an actionable error rather than hidden looping. A Stage only contributes picture: include wanted audio separately.++The current 1.5-second four-image montage uses 5 / 4 / 5 / 31 frames at 30fps, boundaries 0 / 5 / 9 / 14 / 45. The supplied images live in the production's assets, not in this package. The exact font is also supplied by Source.++`src/activation.js` owns Manifest, Surface and finite graph wiring. `src/render.js` owns visuals and frame-seekable browser programs. The package uses Hypit's public authoring and domain APIs; it changes no framework, Studio or Core code. `src/studio.js` contributes the public Studio Companion facet. Defaults live once in `src/definition.js`, shared by Surface decoding and the Inspector. Title, Timer and Veil expose their own text, position and appearance choices. Stage has a parent for shared framing and slow-push settings, with independently timed media Items in its attached lane. Pullback, PortraitInset and Reframe expose the referenced Style/Frame parameters through Performance Uses. The Inspector uses Studio’s standard controls and writes existing author attributes; no Studio or Core component dispatch is added.++The actual montage and semantic title/timer bindings live in `authors/main.svml`. Earlier component studies are archived privately.++The pennant and floor flag use a small Canvas raster with stepped diagonal folds and discrete shaded bands. `src/flag-cloth.js` retains its filename, but the current renderer uses no 3D engine or cloth simulation. Frame time determines the low-cadence movement, and nearest-neighbor scaling preserves the pixels. The supplied logo remains readable; amplitude and speed are author choices. The pennant paints in front of its backplate. Brand artwork is supplied by Source.++The current Title uses the shared pink window treatment described below; earlier luminous corner studies remain historical outputs.++Stage `push-rate` is the foreground scale increase per second, default zero. For example, `push-rate="0.025"` increases scale by 2.5% per second while the viewport stays fixed. Each Item starts at native scale; its own original Window determines animation age even when the Stage clips that Window. The production enables this on the four-image montage; short flashes therefore move slightly, while a longer hold develops a visible slow push.+++## Texture Veil++`gfx:Veil` contributes an independent patterned overlay. Source places it above the background picture and below the text, diagram, presenter window and chrome it wants to keep clear. It neither reads sibling tracks nor edits their media. Use the shared temporal attributes, `timeline`, `canvas`, and `z` (default 20). It needs no font or asset.++`pattern` selects `mesh`, `dots`, or `hatch`; `cell` sets motif size at 1080px Canvas width; `amount` sets motif opacity. `tint` and `shade` describe the translucent color wash independently. `fade-frames` shapes its short entrance/exit; zero gives an immediate boundary. The pattern remains stationary during the hold. The defaults are a starting treatment, not a requirement to apply the overlay to every picture.++Earlier texture studies are retained in private production history. The active Source shows the selected treatment.++### Opening pullback as a Performance Use++`<gfx:Pullback id="opening-pullback" scale="1.5"/>` defines a project-owned Performance Style. Apply it with `<performance:Use start="0f" end="1s" style={opening-pullback}/>` after the broad full-frame Use. Its original Use Window drives a quartic ease-out from 1.5× to 1×, centered at 50%/35%; Timeline footage keeps its source clock. At the end it meets ordinary full-frame geometry. Titles and other contributions stay independent. This changes framing, not playback speed or generated material.++## Portrait inset+`<gfx:PortraitInset id="host-small" frame={host-inset}/>` is a project Performance Style for a circular presenter viewport with a closer inner crop. It uses Timeline media/source spans, clips each interval, and presents the current visual source at its placed playback time. The external Frame controls position and size; this work uses 330px. An inner 1.23× magnification, anchored at 50%/28%, increases face presence independently from viewport size. Its vivid-pink rim, dark outline and solid offset shadow match the supplied pink interface reference. This is independent from full-frame and Reframe Uses.++The spoken opening Title is currently a pale-pink window card with a dark outline, a vivid-pink headline and a solid lower-right shadow. Timer plaque/readout follow the same palette while preserving the animated pixel flag and existing time behavior.++`performance-media.js` owns prepared Timeline media projection and sampling shared by Pullback, Reframe and PortraitInset. The private `@explainer/visual-language` dependency owns the current pink palette; each Style owns its framing behavior.diff --git a/examples/complex-explainer/packages/opening-system/package.json b/examples/complex-explainer/packages/opening-system/package.jsonnew file mode 100644index 00000000..67f14df5--- /dev/null+++ b/examples/complex-explainer/packages/opening-system/package.json@@ -0,0 +1,19 @@+{+ "name": "@explainer/opening-system",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "hypit": {+ "activation": "./src/activation.js"+ },+ "exports": {+ ".": "./src/render.js"+ },+ "files": [+ "src",+ "README.md"+ ],+ "dependencies": {+ "@explainer/visual-language": "file:../visual-language"+ }+}diff --git a/examples/complex-explainer/packages/opening-system/src/activation.js b/examples/complex-explainer/packages/opening-system/src/activation.jsnew file mode 100644index 00000000..b9ab4c0c--- /dev/null+++ b/examples/complex-explainer/packages/opening-system/src/activation.js@@ -0,0 +1,552 @@+import { installPortraitTransition } from "./portrait-transition.js";+import { installPortraitInset } from "./portrait-inset.js";+import { installReframe } from "./reframe.js";+import { installPullback } from "./pullback.js";+import {+ assertAttributes,+ assertEmptyElement,+ canonicalize,+ createMarkupSurfaceHostFacet,+ sameType,+ sealGraphFragment,+ textAttribute,+} from "@hypit/hypit/author-kit";+import { compositionTypes } from "@hypit/hypit/composition";+import { mediaTypes } from "@hypit/hypit/media";+import { timelineTypes } from "@hypit/hypit/timeline";+import { spatialTypes } from "@hypit/hypit/spatial";+import { temporalTypes } from "@hypit/hypit/temporal";+import {+ createTemporalWindowProjection,+ createTemporalInstantProjection,+ resolveTemporalContext,+ temporalWindowAttributeNames,+ temporalWindowAttributeVocabulary,+ temporalContextAttributeVocabulary,+} from "@hypit/hypit/temporal-markup";+import { renderTitle, renderTimer, renderFlag, renderStage, renderVeil } from "./render.js";+import { module, defaults } from "./definition.js";+import { studioFacet } from "./studio.js";+const type = (name) => ({ module, name });+const optionsType = type("Options"),+ itemsType = type("Items");+const producer = (name) => ({ module, name });+const port = (name, type) => ({ name, type });+const common = [+ port("timeline", timelineTypes.track),+ port("canvas", spatialTypes.canvas),+ port("window", temporalTypes.window),+ port("options", optionsType),+];+export const manifest = {+ format: "hypit.module@1",+ ...module,+ dependencies: [+ ...new Map(+ [+ compositionTypes.visualTrack,+ mediaTypes.fontArtifact,+ mediaTypes.synchronized,+ mediaTypes.blobArtifact,+ timelineTypes.track,+ spatialTypes.canvas,+ temporalTypes.window,+ ].map((t) => [t.module.name, { module: t.module }]),+ ).values(),+ ],+ types: [{ name: "Options" }, { name: "Items" }],+ capabilities: [],+ producers: [+ {+ name: "title",+ inputs: [...common, port("font", mediaTypes.fontArtifact), port("bounce", temporalTypes.instant)],+ outputs: [port("track", compositionTypes.visualTrack)],+ needs: [],+ },+ {+ name: "timer",+ inputs: [+ ...common,+ port("font", mediaTypes.fontArtifact),+ port("logo", mediaTypes.blobArtifact),+ port("stop", temporalTypes.instant),+ ],+ outputs: [port("track", compositionTypes.visualTrack)],+ needs: [],+ },+ { name: "flag", inputs: [...common, port("logo", mediaTypes.blobArtifact)], outputs: [port("track", compositionTypes.visualTrack)], needs: [] },+ {+ name: "veil",+ inputs: common,+ outputs: [port("track", compositionTypes.visualTrack)],+ needs: [],+ },+ {+ name: "empty",+ inputs: [],+ outputs: [port("items", itemsType)],+ needs: [],+ },+ ...["image", "video"].map((kind) => ({+ name: "append-" + kind,+ inputs: [+ port("items", itemsType),+ port("options", optionsType),+ port("window", temporalTypes.window),+ port(+ "asset",+ kind === "image" ? mediaTypes.blobArtifact : mediaTypes.synchronized,+ ),+ ],+ outputs: [port("items", itemsType)],+ needs: [],+ })),+ {+ name: "stage",+ inputs: [...common, port("items", itemsType)],+ outputs: [port("track", compositionTypes.visualTrack)],+ needs: [],+ },+ ],+};+const inline = (r) => {+ if (r?.value.kind !== "inline")+ throw Error("Opening-system expects inline domain values.");+ return r.value.value;+};+const val = (v) => ({ kind: "inline", value: canonicalize(v) });+const output = (name, v) => ({ outputs: { [name]: val(v) }, needs: {} });+const component = {+ producers: [+ { producer: producer("flag"), handler: ({inputs: i}) => output("track", renderFlag(inline(i.timeline), inline(i.canvas), inline(i.window), inline(i.options), i.logo.value)) },+ ...[+ ["title", renderTitle],+ ["timer", renderTimer],+ ].map(([name, fn]) => ({+ producer: producer(name),+ handler: ({ inputs: i }) =>+ output(+ "track",+ fn(+ inline(i.timeline),+ inline(i.canvas),+ inline(i.window),+ inline(i.font),+ inline(i.options),+ name === "title" ? inline(i.bounce) : i.logo?.value,+ name === "timer" ? inline(i.stop) : undefined,+ ),+ ),+ })),+ {+ producer: producer("veil"),+ handler: ({ inputs: i }) =>+ output(+ "track",+ renderVeil(+ inline(i.timeline),+ inline(i.canvas),+ inline(i.window),+ inline(i.options),+ ),+ ),+ },+ { producer: producer("empty"), handler: () => output("items", []) },+ ...["image", "video"].map((kind) => ({+ producer: producer("append-" + kind),+ handler: ({ inputs: i }) =>+ output("items", [+ ...inline(i.items),+ {+ ...inline(i.options),+ window: inline(i.window),+ [kind === "image" ? "image" : "media"]:+ kind === "image" ? i.asset.value : inline(i.asset),+ },+ ]),+ })),+ {+ producer: producer("stage"),+ handler: ({ inputs: i }) =>+ output(+ "track",+ renderStage(+ inline(i.timeline),+ inline(i.canvas),+ inline(i.window),+ inline(i.items),+ inline(i.options),+ ),+ ),+ },+ ],+};+const camel = (s) => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());+function decode(kind) {+ return ({ element, resolveReference }) => {+ const values = defaults[kind];+ assertAttributes(element, [+ "id",+ "timeline",+ "canvas",+ ...(kind === "Title" ? ["bounce-at"] : []),+ ...(kind === "Timer" ? ["stop-at"] : []),+ ...(["Title", "Timer"].includes(kind) ? ["font"] : []),+ ...(["Timer", "Flag"].includes(kind) ? ["logo"] : []),+ ...Object.keys(values),+ ...temporalWindowAttributeNames,+ ]);+ const id = textAttribute(element, "id"),+ context = resolveTemporalContext({ element, resolveReference });+ const win = createTemporalWindowProjection({+ id: id + ".window",+ subjectId: id,+ element,+ ...context,+ resolveReference,+ });+ const ref = (el, name, t) => {+ const raw = el.attributes[name];+ if (typeof raw !== "object" || raw.kind !== "reference")+ throw Error(name + " must be a reference");+ const found = resolveReference(raw.path);+ if (!found || !sameType(found.type, t))+ throw Error(name + " has the wrong type");+ return found.ref;+ };+ const o = { id };+ for (const [name, d] of Object.entries(values)) {+ const raw = element.attributes[name];+ if (raw !== undefined && typeof raw !== "string")+ throw Error(name + " must be literal");+ const v = typeof d === "number" ? Number(raw ?? d) : (raw ?? d);+ if (typeof v === "number" && !Number.isFinite(v))+ throw Error(name + " must be finite");+ o[camel(name)] = v;+ }+ if (!Number.isSafeInteger(o.z)) throw Error("z must be an integer");+ if (+ kind === "Stage" &&+ (!["contain", "cover"].includes(o.fit) ||+ o.width <= 0 ||+ o.height <= 0 ||+ o.brightness < 0 ||+ o.blur < 0 ||+ o.pushRate < 0)+ )+ throw Error(+ "Stage needs positive dimensions, contain/cover fit, and nonnegative background values.",+ );+ if (+ ["Title", "Timer"].includes(kind) &&+ (!Number.isSafeInteger(o.seconds) || o.seconds < 0)+ )+ throw Error("seconds must be a nonnegative integer");+ if (+ kind === "Timer" &&+ (!Number.isSafeInteger(o.entranceFrames) || o.entranceFrames < 1)+ )+ throw Error("entrance-frames must be positive");+ if (+ kind === "Veil" &&+ (!["mesh", "dots", "hatch"].includes(o.pattern) ||+ o.cell <= 0 ||+ o.amount < 0 ||+ o.amount > 1 ||+ o.shade < 0 ||+ o.shade > 1 ||+ !Number.isSafeInteger(o.fadeFrames) ||+ o.fadeFrames < 0)+ )+ throw Error(+ "Veil needs mesh/dots/hatch, positive cell size, opacity from zero to one, and a nonnegative fade frame count",+ );+ const records = [+ ...win.records,+ {+ id: id + ".options",+ type: optionsType,+ value: val(o),+ range: element.range,+ },+ ],+ components = [...win.components],+ fragments = [...win.fragments];+ const inputs = [...common],+ bindings = {+ timeline: context.timeline.ref,+ canvas: ref(element, "canvas", spatialTypes.canvas),+ window: win.ref,+ options: { kind: "record", id: id + ".options" },+ };+ if (kind === "Title") {+ const bounce = createTemporalInstantProjection({+ id: id + ".bounce", subjectId: id + ".bounce",+ element: { ...element, attributes: { at: element.attributes["bounce-at"] ?? "program.start" } },+ ...context, resolveReference,+ });+ records.push(...bounce.records); components.push(...bounce.components); fragments.push(...bounce.fragments);+ inputs.push(port("bounce", temporalTypes.instant)); bindings.bounce = bounce.ref;+ }+ if (kind === "Timer") {+ const stop = createTemporalInstantProjection({id:id+".stop",subjectId:id+".stop",element:{...element,attributes:{at:element.attributes["stop-at"]??"program.end"}},...context,resolveReference});+ records.push(...stop.records);components.push(...stop.components);fragments.push(...stop.fragments);+ inputs.push(port("stop",temporalTypes.instant));bindings.stop=stop.ref;+ }+ const input = (name) => ({ kind: "fragment-input", name }),+ operation = (name) => ({ kind: "fragment-operation", operation: name });+ const operations = [];+ if (kind === "Stage") {+ operations.push({+ id: "empty",+ producer: producer("empty"),+ inputs: {},+ result: { kind: "output", name: "items" },+ });+ let previous = "empty",+ n = 0;+ for (const child of element.children) {+ if (child.kind === "text") {+ if (child.value.trim()) throw Error("Stage accepts Item children");+ continue;+ }+ if (child.name.split(":").at(-1) !== "Item")+ throw Error("Stage accepts Item children");+ assertAttributes(child, [+ "id",+ "image",+ "video",+ "source-start-frame",+ ...temporalWindowAttributeNames,+ ]);+ assertEmptyElement(child);+ const cid = textAttribute(child, "id"),+ isImage = child.attributes.image !== undefined;+ if (isImage === (child.attributes.video !== undefined))+ throw Error("Item needs exactly one image or normalized video");+ const iw = createTemporalWindowProjection({+ id: `${id}.${cid}.window`,+ subjectId: cid,+ element: child,+ ...context,+ resolveReference,+ });+ records.push(...iw.records);+ components.push(...iw.components);+ fragments.push(...iw.fragments);+ const key = "item" + ++n,+ optsId = id + "." + key,+ sourceStart = Number(child.attributes["source-start-frame"] ?? 0);+ if (!Number.isSafeInteger(sourceStart) || sourceStart < 0)+ throw Error("source-start-frame must be nonnegative integer");+ records.push({+ id: optsId,+ type: optionsType,+ value: val({ id: cid, sourceStart }),+ range: child.range,+ });+ for (const [suffix, t, r] of [+ ["options", optionsType, { kind: "record", id: optsId }],+ ["window", temporalTypes.window, iw.ref],+ [+ "asset",+ isImage ? mediaTypes.blobArtifact : mediaTypes.synchronized,+ ref(+ child,+ isImage ? "image" : "video",+ isImage ? mediaTypes.blobArtifact : mediaTypes.synchronized,+ ),+ ],+ ]) {+ inputs.push(port(key + "-" + suffix, t));+ bindings[key + "-" + suffix] = r;+ }+ operations.push({+ id: key,+ producer: producer(isImage ? "append-image" : "append-video"),+ inputs: {+ items: operation(previous),+ options: input(key + "-options"),+ window: input(key + "-window"),+ asset: input(key + "-asset"),+ },+ result: { kind: "output", name: "items" },+ });+ previous = key;+ }+ if (!n) throw Error("Stage needs Item children");+ operations.push({+ id: "render",+ producer: producer("stage"),+ inputs: {+ ...Object.fromEntries(common.map((p) => [p.name, input(p.name)])),+ items: operation(previous),+ },+ result: { kind: "output", name: "track" },+ });+ } else {+ assertEmptyElement(element);+ if (["Title", "Timer"].includes(kind)) {+ inputs.push(port("font", mediaTypes.fontArtifact));+ bindings.font = ref(element, "font", mediaTypes.fontArtifact);+ }+ if (["Timer", "Flag"].includes(kind)) {+ inputs.push(port("logo", mediaTypes.blobArtifact));+ bindings.logo = ref(element, "logo", mediaTypes.blobArtifact);+ }+ operations.push({+ id: "render",+ producer: producer(kind.toLowerCase()),+ inputs: Object.fromEntries(inputs.map((p) => [p.name, input(p.name)])),+ result: { kind: "output", name: "track" },+ });+ }+ const fragment = sealGraphFragment({+ inputs,+ operations,+ exports: [+ {+ name: "track",+ type: compositionTypes.visualTrack,+ root: operation("render"),+ },+ ],+ });+ return {+ records,+ fragments: [...fragments, fragment],+ components: [+ ...components,+ {+ id,+ fragment: fragment.id,+ inputs: bindings,+ outputs: { track: id + ".track" },+ range: element.range,+ },+ ],+ exports: [id + ".track"],+ };+ };+}+const declarations = Object.keys(defaults).map((tag) => ({+ name: tag.toLowerCase(),+ tag,+ mode: "structured",+ outputs: [+ optionsType,+ itemsType,+ compositionTypes.visualTrack,+ timelineTypes.track,+ temporalTypes.window,+ temporalTypes.instant,+ temporalTypes.windowSpec,+ temporalTypes.instantSpec,+ ],+ vocabulary: {+ summary: {+ Flag: "An independent foreshortened cloth flag beneath the composition.",+ Veil: "An independent patterned veil placed above footage and below foreground graphics.",+ Title:+ "Transparent opening clock and two-level headline in a pink window card.",+ Timer:+ "Persistent topic plaque with a countdown that turns coral and counts overtime.",+ Stage:+ "Clear foreground media with the same moving picture enlarged, blurred and dimmed behind it.",+ }[tag],+ attributes: [+ ...(tag === "Title" ? [{ name: "bounce-at", kind: "expression", required: false, summary: "Moment or time when the title jumps." }] : []),+ ...(tag === "Timer" ? [{name:"stop-at",kind:"expression",required:false,summary:"Freeze the overtime display and flash on this instant."}] : []),+ ...temporalContextAttributeVocabulary,+ ...temporalWindowAttributeVocabulary,+ ...[+ "id",+ "canvas",+ ...(["Title", "Timer"].includes(tag) ? ["font"] : []),+ ...(["Timer", "Flag"].includes(tag) ? ["logo"] : []),+ ].map((name) => ({+ name,+ kind: "expression",+ required: true,+ summary: name,+ })),+ ...Object.keys(defaults[tag]).map((name) => ({+ name,+ kind: "literal",+ required: false,+ summary: `${name}; default ${defaults[tag][name]}`,+ })),+ ],+ children:+ tag === "Stage"+ ? [+ {+ tag: "Item",+ cardinality: "many",+ summary:+ "Image or normalized video, in its own projected Window. Later items paint above earlier items.",+ attributes: [+ {+ name: "id",+ kind: "identifier",+ required: true,+ summary: "Item identity",+ },+ {+ name: "image",+ kind: "expression",+ required: false,+ summary: "Image artifact",+ },+ {+ name: "video",+ kind: "expression",+ required: false,+ summary: "Normalized moving media",+ },+ {+ name: "source-start-frame",+ kind: "literal",+ required: false,+ summary: "First source frame, default zero",+ },+ ...temporalWindowAttributeVocabulary,+ ],+ },+ ]+ : [],+ ports: [+ {+ name: "track",+ type: compositionTypes.visualTrack,+ summary: "Visual contribution, explicitly connected to Film",+ },+ ],+ },+}));+const pullback = installPullback(module, manifest, component, optionsType);+const fadeOut = installPullback(module, manifest, component, optionsType, "fade-out");+const reframe = installReframe(module, manifest, component);+const portraitTransition = installPortraitTransition(module, manifest, component);+const portraitInset = installPortraitInset(module, manifest, component);+export const hypitPackage = {+ format: "hypit.node-package@1",+ modules: [{ manifest }],+ components: [component],+ hostFacets: [+ ...declarations.map((declaration) =>+ createMarkupSurfaceHostFacet({+ module,+ declaration,+ handler: decode(declaration.tag),+ }),+ ),+ pullback,+ fadeOut,+ reframe,+ portraitTransition,+ portraitInset,+ studioFacet,+ ],+};+export default hypitPackage;diff --git a/examples/complex-explainer/packages/opening-system/src/definition.js b/examples/complex-explainer/packages/opening-system/src/definition.jsnew file mode 100644index 00000000..2dfadab1--- /dev/null+++ b/examples/complex-explainer/packages/opening-system/src/definition.js@@ -0,0 +1,50 @@+export const module = { name: "@explainer/opening-system", version: "1" };+export const defaults = {+ Veil: {+ z: 20,+ pattern: "mesh",+ cell: 12,+ amount: 0.26,+ shade: 0.48,+ tint: "#0c101b",+ "fade-frames": 6,+ },+ Title: {+ z: 40,+ title: "Hypit",+ subtitle: "一分钟了解",+ seconds: 60,+ color: "#e0f5ff",+ "timer-y": 0.175,+ "title-y": 0.53,+ "title-size": 0.19,+ },+ Timer: {+ z: 80,+ title: "Hypit",+ subtitle: "VIDEO FRAMEWORK",+ seconds: 60,+ x: 0,+ y: 0.13,+ width: 0.28,+ accent: "#386f7e",+ "flag-color": "#c92f4d",+ "flag-amplitude": 0.06,+ "flag-speed": 0.25,+ "entrance-frames": 7,+ },+ Flag: { z: 35, x: 0.17, y: 0.81, width: 0.66, height: 0.17, "flag-color": "#fa67aa", "flag-amplitude": 0.04, "flag-speed": 0.25 },+ Stage: {+ z: 10,+ x: 0,+ y: 0.263,+ width: 1,+ height: 0.463,+ fit: "contain",+ blur: 32,+ brightness: 0.32,+ zoom: 1.13,+ radius: 0,+ "push-rate": 0,+ },+};diff --git a/examples/complex-explainer/packages/opening-system/src/flag-cloth.js b/examples/complex-explainer/packages/opening-system/src/flag-cloth.jsnew file mode 100644index 00000000..227926d9--- /dev/null+++ b/examples/complex-explainer/packages/opening-system/src/flag-cloth.js@@ -0,0 +1,45 @@+// Shared pixel-art flag: a small texture, stepped folds and two authored views.+// Every frame is determined by its time; no simulation history is needed.+export const flagSetup = String.raw`+const flagCanvas=root.querySelector('.flag-canvas'), ctx=flagCanvas.getContext('2d');+flagCanvas.width=256;flagCanvas.height=160;ctx.imageSmoothingEnabled=false;+const logo=root.querySelector('.logo-resource img');+const texture=document.createElement('canvas');texture.width=128;texture.height=52;+const tc=texture.getContext('2d');tc.imageSmoothingEnabled=false;+const flagRaster=document.createElement('canvas');flagRaster.width=256;flagRaster.height=160;+const cc=flagRaster.getContext('2d');cc.imageSmoothingEnabled=false;+const mask=document.createElement('canvas');mask.width=256;mask.height=160;+const mc=mask.getContext('2d');let pixels=null;+function prepareTexture(){+ if(!logo?.complete||!logo.naturalWidth)return false;+ tc.fillStyle=data.flagColor;tc.fillRect(0,0,128,52);+ const lw=110,lh=Math.round(lw*logo.naturalHeight/logo.naturalWidth);+ tc.drawImage(logo,9,Math.round((52-lh)/2),lw,lh);+ // A few stitched pixels frame the logo without covering its lettering.+ tc.fillStyle='#ffe8f4';for(let x=4;x<124;x+=5){tc.fillRect(x,2,2,1);tc.fillRect(x,49,2,1);}+ pixels=tc.getImageData(0,0,128,52).data;return true;+}+function drawFlag(frame){+ if(!pixels&&!prepareTexture())return;+ const floor=data.flagPose==='floor',t=Math.floor(frame/data.fps*12)/12;+ const phase=t*data.flagSpeed*Math.PI*2,amp=Math.min(7,data.flagAmplitude*60);+ cc.clearRect(0,0,256,160);ctx.clearRect(0,0,256,160);+ for(let y=0;y<52;y++)for(let x=0;x<128;x++){+ const u=x/127,v=y/51,p=7*u-2*v-phase;+ const wave=Math.sin(p)+.2*Math.sin(p*1.8+.7);+ const dy=Math.round(amp*wave*(floor?1:Math.pow(u,.75)));+ const width=floor?142+v*65:190;+ const px=Math.round((floor?128-width/2-5*v:37)+u*width);+ const py=Math.round((floor?58+v*40:35+v*73+u*9)+dy);+ const band=Math.cos(p-0.45),shade=band>.5?1.1:band<-.55?.76:band<-.05?.9:1;+ const i=(y*128+x)*4;+ cc.fillStyle='rgb('+Math.min(255,Math.round(pixels[i]*shade))+','+Math.min(255,Math.round(pixels[i+1]*shade))+','+Math.min(255,Math.round(pixels[i+2]*shade))+')';+ cc.fillRect(px,py,Math.ceil(width/127)+1,floor?2:3);+ }+ mc.clearRect(0,0,256,160);mc.drawImage(flagRaster,0,0);mc.globalCompositeOperation='source-in';mc.fillStyle='#42263e';mc.fillRect(0,0,256,160);mc.globalCompositeOperation='source-over';+ if(!floor){ctx.fillStyle='#281d2d';ctx.fillRect(32,22,4,121);ctx.fillRect(30,18,8,6);ctx.fillStyle='#ffe6b3';ctx.fillRect(31,18,5,4);ctx.fillStyle='#faafd1';ctx.fillRect(33,25,1,113);}+ ctx.drawImage(mask,3,4);+ for(const [x,y] of [[-1,0],[1,0],[0,-1],[0,1]])ctx.drawImage(mask,x,y);+ ctx.drawImage(flagRaster,0,0);+}+`;diff --git a/examples/complex-explainer/packages/opening-system/src/performance-media.js b/examples/complex-explainer/packages/opening-system/src/performance-media.jsnew file mode 100644index 00000000..aa30cbbb--- /dev/null+++ b/examples/complex-explainer/packages/opening-system/src/performance-media.js@@ -0,0 +1,37 @@+import { projectTimelineMedia } from "@hypit/hypit/timeline";+export function performanceMedia(timeline, window, parent = "scene") {+ const clips = projectTimelineMedia(timeline, window.span).filter(+ (clip) => clip.media.visual,+ );+ const children = clips.map((clip, index) => ({+ id: "clip" + index,+ parent,+ kind: "video",+ order: index + 1,+ muted: true,+ artifact: clip.media.visual.artifact,+ style: Object.entries({+ position: "absolute",+ inset: 0,+ width: "100%",+ height: "100%",+ "object-fit": "cover",+ }).map(([name, value]) => ({ name, value })),+ sampling: {+ sourceFrameRate: clip.media.timeline.frameRate,+ sourceFrameCount: clip.media.timeline.frameCount,+ segments: [+ {+ target: {+ startFrame: clip.span.startFrame - window.span.startFrame,+ endFrameExclusive:+ clip.span.endFrameExclusive - window.span.startFrame,+ },+ sourceFrame: { numerator: clip.source.startFrame, denominator: 1 },+ rate: { numerator: 1, denominator: 1 },+ },+ ],+ },+ }));+ return { clips, children };+}diff --git a/examples/complex-explainer/packages/opening-system/src/portrait-inset.js b/examples/complex-explainer/packages/opening-system/src/portrait-inset.jsnew file mode 100644index 00000000..c3451699--- /dev/null+++ b/examples/complex-explainer/packages/opening-system/src/portrait-inset.js@@ -0,0 +1,167 @@+import { palette } from "@explainer/visual-language";+import { performanceMedia } from "./performance-media.js";+import {+ assertAttributes,+ assertEmptyElement,+ textAttribute,+ canonicalize,+ sealGraphFragment,+ createMarkupSurfaceHostFacet,+ sameType,+} from "@hypit/hypit/author-kit";+import { performanceStyle, performanceTypes } from "@hypit/hypit/performance";+import { sealVisualTrack, compositionTypes } from "@hypit/hypit/composition";+import { timelineTypes } from "@hypit/hypit/timeline";+import { spatialTypes } from "@hypit/hypit/spatial";+import { temporalTypes } from "@hypit/hypit/temporal";+import { browserProgram } from "@hypit/hypit/hyperframes";+const styles = (o) =>+ Object.entries(o).map(([name, value]) => ({ name, value }));+export function installPortraitInset(module, manifest, component) {+ const inputs = [+ { name: "timeline", type: timelineTypes.track },+ { name: "canvas", type: spatialTypes.canvas },+ { name: "window", type: temporalTypes.window },+ { name: "frame", type: spatialTypes.frame },+ ],+ producer = { module, name: "portrait-inset" };+ manifest.producers.push({+ name: "portrait-inset",+ inputs,+ outputs: [{ name: "visual", type: compositionTypes.visualTrack }],+ needs: [],+ });+ const fragment = sealGraphFragment({+ inputs,+ operations: [+ {+ id: "render",+ producer,+ inputs: Object.fromEntries(+ inputs.map((p) => [p.name, { kind: "fragment-input", name: p.name }]),+ ),+ result: { kind: "output", name: "visual" },+ },+ ],+ exports: [+ {+ name: "visual",+ type: compositionTypes.visualTrack,+ root: { kind: "fragment-operation", operation: "render" },+ },+ ],+ });+ component.producers.push({+ producer,+ handler: ({ inputs }) => {+ const { timeline, canvas, window, frame } = Object.fromEntries(+ Object.entries(inputs).map(([k, r]) => [k, r.value.value]),+ ),+ { clips, children } = performanceMedia(timeline, window);+ const program = browserProgram({+ html:+ '<div class="viewport"><div class="inner">' ++ children.map((v) => "{{" + v.id + "}}").join("") ++ "</div></div>",+ css: `.viewport{position:absolute;overflow:hidden;border-radius:50%;border:4px solid ${palette.ink};box-shadow:0 0 0 5px #fa81b8,7px 9px 0 5px ${palette.ink}}.inner{position:absolute;inset:0;transform:scale(1.23);transform-origin:50% 28%}.inner>*{object-position:50% 28%!important}`,+ data: {+ frame,+ spans: clips.map((c) => ({+ start: c.span.startFrame - window.span.startFrame,+ end: c.span.endFrameExclusive - window.span.startFrame,+ })),+ },+ setup: `const view=root.querySelector('.viewport'),a=data.frame;Object.assign(view.style,{left:a.xPx+'px',top:a.yPx+'px',width:a.widthPx+'px',height:a.heightPx+'px'});const vs=[...root.querySelectorAll('video')];return f=>vs.forEach((v,i)=>v.style.visibility=f>=data.spans[i].start&&f<data.spans[i].end?'inherit':'hidden');`,+ });+ const id = window.subjectId,+ visual = sealVisualTrack({+ id,+ programSpaceId: timeline.id,+ visualIr: "hypit.visual-ir@1",+ presents: children.length+ ? [+ {+ id,+ span: window.span,+ stacking: { order: 60, tieBreak: id },+ elements: [+ {+ id: "scene",+ kind: "program",+ order: 0,+ program,+ style: styles({+ position: "absolute",+ inset: 0,+ width: canvas.widthPx + "px",+ height: canvas.heightPx + "px",+ }),+ },+ ...children,+ ],+ },+ ]+ : [],+ });+ return {+ outputs: { visual: { kind: "inline", value: canonicalize(visual) } },+ needs: {},+ };+ },+ });+ return createMarkupSurfaceHostFacet({+ module,+ declaration: {+ name: "portrait-inset",+ tag: "PortraitInset",+ mode: "structured",+ outputs: [performanceTypes.style],+ vocabulary: {+ summary: "Round speaking portrait with a tighter inner crop.",+ attributes: [+ {+ name: "id",+ kind: "identifier",+ required: true,+ summary: "Style identity",+ },+ ...["frame"].map((name) => ({+ name,+ kind: "reference",+ required: true,+ accepts: [spatialTypes.frame],+ summary: "Portrait viewport",+ })),+ ],+ },+ },+ handler: ({ element, resolveReference }) => {+ assertAttributes(element, ["id", "frame"]);+ assertEmptyElement(element);+ const bindings = {};+ for (const n of ["frame"]) {+ const a = element.attributes[n];+ if (a?.kind !== "reference") throw Error(n + " needs Frame");+ const r = resolveReference(a.path);+ if (!r || !sameType(r.type, spatialTypes.frame))+ throw Error(n + " needs Frame");+ bindings[n] = r;+ }+ return {+ records: [+ {+ id: textAttribute(element, "id"),+ type: performanceTypes.style,+ value: {+ kind: "inline",+ value: canonicalize(performanceStyle(fragment, bindings)),+ },+ range: element.range,+ },+ ],+ components: [],+ fragments: [],+ };+ },+ });+}diff --git a/examples/complex-explainer/packages/opening-system/src/portrait-transition.js b/examples/complex-explainer/packages/opening-system/src/portrait-transition.jsnew file mode 100644index 00000000..41a1b687--- /dev/null+++ b/examples/complex-explainer/packages/opening-system/src/portrait-transition.js@@ -0,0 +1,174 @@+import { palette } from "@explainer/visual-language";+import { performanceMedia } from "./performance-media.js";+import {+ assertAttributes,+ assertEmptyElement,+ textAttribute,+ canonicalize,+ sealGraphFragment,+ createMarkupSurfaceHostFacet,+ sameType,+} from "@hypit/hypit/author-kit";+import { performanceStyle, performanceTypes } from "@hypit/hypit/performance";+import { sealVisualTrack, compositionTypes } from "@hypit/hypit/composition";+import { timelineTypes } from "@hypit/hypit/timeline";+import { spatialTypes } from "@hypit/hypit/spatial";+import { temporalTypes } from "@hypit/hypit/temporal";+import { browserProgram } from "@hypit/hypit/hyperframes";+const styles = (o) =>+ Object.entries(o).map(([name, value]) => ({ name, value }));+export function installPortraitTransition(module, manifest, component) {+ const inputs = [+ { name: "timeline", type: timelineTypes.track },+ { name: "canvas", type: spatialTypes.canvas },+ { name: "window", type: temporalTypes.window },+ { name: "from", type: spatialTypes.frame },+ { name: "to", type: spatialTypes.frame },+ ],+ producer = { module, name: "portrait-transition" };+ manifest.producers.push({+ name: "portrait-transition",+ inputs,+ outputs: [{ name: "visual", type: compositionTypes.visualTrack }],+ needs: [],+ });+ const fragment = sealGraphFragment({+ inputs,+ operations: [+ {+ id: "render",+ producer,+ inputs: Object.fromEntries(+ inputs.map((p) => [p.name, { kind: "fragment-input", name: p.name }]),+ ),+ result: { kind: "output", name: "visual" },+ },+ ],+ exports: [+ {+ name: "visual",+ type: compositionTypes.visualTrack,+ root: { kind: "fragment-operation", operation: "render" },+ },+ ],+ });+ component.producers.push({+ producer,+ handler: ({ inputs }) => {+ const { timeline, canvas, window, from, to } = Object.fromEntries(+ Object.entries(inputs).map(([k, r]) => [k, r.value.value]),+ ),+ { clips, children } = performanceMedia(timeline, window);+ const program = browserProgram({+ html:+ '<div class="viewport"><div class="inner">' ++ children.map((v) => "{{" + v.id + "}}").join("") ++ "</div></div>",+ css: `.viewport{position:absolute;overflow:hidden}.inner{position:absolute;inset:0;transform-origin:50% 28%}` ,+ data: {+ from,+ to,+ ink: palette.ink,+ spans: clips.map(c=>({start:c.span.startFrame-window.span.startFrame,end:c.span.endFrameExclusive-window.span.startFrame})),+ duration: window.span.endFrameExclusive - window.span.startFrame,+ },+ setup: `const view=root.querySelector('.viewport'),inner=root.querySelector('.inner'),videos=[...inner.querySelectorAll('video')];return f=>{+ const p=Math.max(0,Math.min(1,f/Math.max(1,data.duration-1))),q=p*p*p*(p*(p*6-15)+10),a=data.from,b=data.to;+ Object.assign(view.style,{left:(a.xPx+(b.xPx-a.xPx)*q)+'px',top:(a.yPx+(b.yPx-a.yPx)*q)+'px',width:(a.widthPx+(b.widthPx-a.widthPx)*q)+'px',height:(a.heightPx+(b.heightPx-a.heightPx)*q)+'px',borderRadius:(50*q)+'%',border:(4*q)+'px solid '+data.ink,boxShadow:q===0?'none':'0 0 0 '+(5*q)+'px #fa81b8,'+(7*q)+'px '+(9*q)+'px 0 '+(5*q)+'px '+data.ink});+ inner.style.transform='scale('+(1+.23*q)+')';+ videos.forEach((v,i)=>{v.style.setProperty('object-position','50% '+(50-22*q)+'%','important');v.style.visibility=f>=data.spans[i].start&&f<data.spans[i].end?'inherit':'hidden'});+};`,+ });+ const id = window.subjectId,+ visual = sealVisualTrack({+ id,+ programSpaceId: timeline.id,+ visualIr: "hypit.visual-ir@1",+ presents: children.length+ ? [+ {+ id,+ span: window.span,+ stacking: { order: 60, tieBreak: id },+ elements: [+ {+ id: "scene",+ kind: "program",+ order: 0,+ program,+ style: styles({+ position: "absolute",+ inset: 0,+ width: canvas.widthPx + "px",+ height: canvas.heightPx + "px",+ }),+ },+ ...children,+ ],+ },+ ]+ : [],+ });+ return {+ outputs: { visual: { kind: "inline", value: canonicalize(visual) } },+ needs: {},+ };+ },+ });+ return createMarkupSurfaceHostFacet({+ module,+ declaration: {+ name: "portrait-transition",+ tag: "PortraitTransition",+ mode: "structured",+ outputs: [performanceTypes.style],+ vocabulary: {+ summary:+ "A continuous full-frame performance move into the project's circular presenter inset.",+ attributes: [+ {+ name: "id",+ kind: "identifier",+ required: true,+ summary: "Style identity",+ },+ ...["from", "to"].map((name) => ({+ name,+ kind: "reference",+ required: true,+ accepts: [spatialTypes.frame],+ summary: "Endpoint frame",+ })),+ ],+ },+ },+ handler: ({ element, resolveReference }) => {+ assertAttributes(element, ["id", "from", "to"]);+ assertEmptyElement(element);+ const bindings = {};+ for (const n of ["from", "to"]) {+ const a = element.attributes[n];+ if (a?.kind !== "reference") throw Error(n + " needs Frame");+ const r = resolveReference(a.path);+ if (!r || !sameType(r.type, spatialTypes.frame))+ throw Error(n + " needs Frame");+ bindings[n] = r;+ }+ return {+ records: [+ {+ id: textAttribute(element, "id"),+ type: performanceTypes.style,+ value: {+ kind: "inline",+ value: canonicalize(performanceStyle(fragment, bindings)),+ },+ range: element.range,+ },+ ],+ components: [],+ fragments: [],+ };+ },+ });+}diff --git a/examples/complex-explainer/packages/opening-system/src/pullback.js b/examples/complex-explainer/packages/opening-system/src/pullback.jsnew file mode 100644index 00000000..9d8d3dba--- /dev/null+++ b/examples/complex-explainer/packages/opening-system/src/pullback.js@@ -0,0 +1,184 @@+import { performanceMedia } from "./performance-media.js";+import {+ assertAttributes,+ assertEmptyElement,+ textAttribute,+ canonicalize,+ sealGraphFragment,+ createMarkupSurfaceHostFacet,+} from "@hypit/hypit/author-kit";+import {+ performanceStyle,+ performanceTypes,+ performanceModuleRef,+} from "@hypit/hypit/performance";+import { sealVisualTrack, compositionTypes } from "@hypit/hypit/composition";+import { timelineTypes } from "@hypit/hypit/timeline";+import { spatialTypes } from "@hypit/hypit/spatial";+import { temporalTypes } from "@hypit/hypit/temporal";+import { browserProgram } from "@hypit/hypit/hyperframes";+const styles = (o) =>+ Object.entries(o).map(([name, value]) => ({ name, value }));+// A local Use owns the pullback's clock; media continues at its placed source time.+export function installPullback(module, manifest, component, optionsType, mode="pullback") {+ const isFade=mode==="fade-out",tag=isFade?"FadeOut":"Pullback";+ const inputs = [+ { name: "timeline", type: timelineTypes.track },+ { name: "canvas", type: spatialTypes.canvas },+ { name: "window", type: temporalTypes.window },+ { name: "options", type: optionsType },+ ];+ const producer = { module, name: mode };+ if (!manifest.dependencies.some(d=>d.module.name===performanceModuleRef.name)) manifest.dependencies.push({ module: performanceModuleRef });+ manifest.producers.push({+ name: mode,+ inputs,+ outputs: [{ name: "visual", type: compositionTypes.visualTrack }],+ needs: [],+ });+ const fragment = sealGraphFragment({+ inputs,+ operations: [+ {+ id: "render",+ producer,+ inputs: Object.fromEntries(+ inputs.map((p) => [p.name, { kind: "fragment-input", name: p.name }]),+ ),+ result: { kind: "output", name: "visual" },+ },+ ],+ exports: [+ {+ name: "visual",+ type: compositionTypes.visualTrack,+ root: { kind: "fragment-operation", operation: "render" },+ },+ ],+ });+ component.producers.push({+ producer,+ handler: ({ inputs }) => {+ const { timeline, canvas, window, options } = Object.fromEntries(+ Object.entries(inputs).map(([k, r]) => {+ if (r.value.kind !== "inline")+ throw Error("Pullback needs inline inputs");+ return [k, r.value.value];+ }),+ );+ const { clips, children } = performanceMedia(timeline, window);+ const duration = window.span.endFrameExclusive - window.span.startFrame;+ const program = browserProgram({+ html:+ '<div class="picture">' ++ children.map((c) => "{{" + c.id + "}}").join("") ++ "</div>",+ css: (isFade?":scope{background:#fce5ee}":"")+":scope{overflow:hidden}.picture{position:absolute;inset:0;transform-origin:50% 35%}",+ data: {+ scale: options.scale,+ fade: isFade,+ duration,+ spans: clips.map((c) => ({+ start: c.span.startFrame - window.span.startFrame,+ end: c.span.endFrameExclusive - window.span.startFrame,+ })),+ },+ setup: `const picture=root.querySelector('.picture'),videos=[...picture.querySelectorAll('video')];return frame=>{const p=Math.max(0,Math.min(1,frame/Math.max(1,data.duration-1))),scale=1+(data.scale-1)*Math.pow(1-p,4);picture.style.transform='scale('+scale+')';picture.style.opacity=data.fade?String(1-p*p*(3-2*p)):'1';videos.forEach((v,i)=>v.style.visibility=frame>=data.spans[i].start&&frame<data.spans[i].end?'inherit':'hidden');};`,+ });+ const id = window.subjectId,+ visual = sealVisualTrack({+ id,+ programSpaceId: timeline.id,+ visualIr: "hypit.visual-ir@1",+ presents: children.length+ ? [+ {+ id,+ span: window.span,+ stacking: { order: 0, tieBreak: id },+ elements: [+ {+ id: "scene",+ kind: "program",+ order: 0,+ program,+ style: styles({+ position: "absolute",+ inset: 0,+ width: canvas.widthPx + "px",+ height: canvas.heightPx + "px",+ }),+ },+ ...children,+ ],+ },+ ]+ : [],+ });+ return {+ outputs: { visual: { kind: "inline", value: canonicalize(visual) } },+ needs: {},+ };+ },+ });+ return createMarkupSurfaceHostFacet({+ module,+ declaration: {+ name: mode,+ tag,+ mode: "structured",+ outputs: [performanceTypes.style, optionsType],+ vocabulary: {+ summary:+ isFade?"Fade placed footage to transparent across this Use.":"Fast-to-slow pullback of placed footage, settling at ordinary full-frame geometry.",+ attributes: [+ {+ name: "id",+ kind: "identifier",+ required: true,+ summary: "Style identity",+ },+ ...(!isFade?[{+ name: "scale",+ kind: "literal",+ required: false,+ summary: "Initial magnification; defaults to 1.5",+ }]:[]),+ ],+ },+ },+ handler: ({ element }) => {+ assertAttributes(element, isFade?["id"]:["id", "scale"]);+ assertEmptyElement(element);+ const id = textAttribute(element, "id"),+ scale = isFade?1:Number(element.attributes.scale ?? 1.5);+ if (!Number.isFinite(scale) || scale < 1)+ throw Error("Pullback scale must be at least 1");+ const options = {+ type: optionsType,+ ref: { kind: "record", id: id + ".options" },+ };+ return {+ records: [+ {+ id: id + ".options",+ type: optionsType,+ value: { kind: "inline", value: canonicalize({ scale }) },+ range: element.range,+ },+ {+ id,+ type: performanceTypes.style,+ value: {+ kind: "inline",+ value: canonicalize(performanceStyle(fragment, { options })),+ },+ range: element.range,+ },+ ],+ components: [],+ fragments: [],+ };+ },+ });+}diff --git a/examples/complex-explainer/packages/opening-system/src/reframe.js b/examples/complex-explainer/packages/opening-system/src/reframe.jsnew file mode 100644index 00000000..c6bac29e--- /dev/null+++ b/examples/complex-explainer/packages/opening-system/src/reframe.js@@ -0,0 +1,166 @@+import { performanceMedia } from "./performance-media.js";+import {+ assertAttributes,+ assertEmptyElement,+ textAttribute,+ canonicalize,+ sealGraphFragment,+ createMarkupSurfaceHostFacet,+ sameType,+} from "@hypit/hypit/author-kit";+import { performanceStyle, performanceTypes } from "@hypit/hypit/performance";+import { sealVisualTrack, compositionTypes } from "@hypit/hypit/composition";+import { timelineTypes } from "@hypit/hypit/timeline";+import { spatialTypes } from "@hypit/hypit/spatial";+import { temporalTypes } from "@hypit/hypit/temporal";+import { browserProgram } from "@hypit/hypit/hyperframes";+const styles = (o) =>+ Object.entries(o).map(([name, value]) => ({ name, value }));+export function installReframe(module, manifest, component) {+ const inputs = [+ { name: "timeline", type: timelineTypes.track },+ { name: "canvas", type: spatialTypes.canvas },+ { name: "window", type: temporalTypes.window },+ { name: "from", type: spatialTypes.frame },+ { name: "to", type: spatialTypes.frame },+ ],+ producer = { module, name: "reframe" };+ manifest.producers.push({+ name: "reframe",+ inputs,+ outputs: [{ name: "visual", type: compositionTypes.visualTrack }],+ needs: [],+ });+ const fragment = sealGraphFragment({+ inputs,+ operations: [+ {+ id: "render",+ producer,+ inputs: Object.fromEntries(+ inputs.map((p) => [p.name, { kind: "fragment-input", name: p.name }]),+ ),+ result: { kind: "output", name: "visual" },+ },+ ],+ exports: [+ {+ name: "visual",+ type: compositionTypes.visualTrack,+ root: { kind: "fragment-operation", operation: "render" },+ },+ ],+ });+ component.producers.push({+ producer,+ handler: ({ inputs }) => {+ const { timeline, canvas, window, from, to } = Object.fromEntries(+ Object.entries(inputs).map(([k, r]) => [k, r.value.value]),+ ),+ { clips, children } = performanceMedia(timeline, window);+ const program = browserProgram({+ html:+ '<div class="viewport">' ++ children.map((v) => "{{" + v.id + "}}").join("") ++ "</div>",+ css: ".viewport{position:absolute;overflow:hidden}.viewport>*{object-position:50% 30%!important}",+ data: {+ from,+ to,+ duration: window.span.endFrameExclusive - window.span.startFrame,+ },+ setup: `const view=root.querySelector('.viewport');return f=>{const p=Math.max(0,Math.min(1,f/Math.max(1,data.duration-1))),q=p*p*(3-2*p),a=data.from,b=data.to;Object.assign(view.style,{left:(a.xPx+(b.xPx-a.xPx)*q)+'px',top:(a.yPx+(b.yPx-a.yPx)*q)+'px',width:(a.widthPx+(b.widthPx-a.widthPx)*q)+'px',height:(a.heightPx+(b.heightPx-a.heightPx)*q)+'px'});};`,+ });+ const id = window.subjectId,+ visual = sealVisualTrack({+ id,+ programSpaceId: timeline.id,+ visualIr: "hypit.visual-ir@1",+ presents: children.length+ ? [+ {+ id,+ span: window.span,+ stacking: { order: 60, tieBreak: id },+ elements: [+ {+ id: "scene",+ kind: "program",+ order: 0,+ program,+ style: styles({+ position: "absolute",+ inset: 0,+ width: canvas.widthPx + "px",+ height: canvas.heightPx + "px",+ }),+ },+ ...children,+ ],+ },+ ]+ : [],+ });+ return {+ outputs: { visual: { kind: "inline", value: canonicalize(visual) } },+ needs: {},+ };+ },+ });+ return createMarkupSurfaceHostFacet({+ module,+ declaration: {+ name: "reframe",+ tag: "Reframe",+ mode: "structured",+ outputs: [performanceTypes.style],+ vocabulary: {+ summary:+ "Continuous prepared-performance viewport change between two Frames.",+ attributes: [+ {+ name: "id",+ kind: "identifier",+ required: true,+ summary: "Style identity",+ },+ ...["from", "to"].map((name) => ({+ name,+ kind: "reference",+ required: true,+ accepts: [spatialTypes.frame],+ summary: "Endpoint frame",+ })),+ ],+ },+ },+ handler: ({ element, resolveReference }) => {+ assertAttributes(element, ["id", "from", "to"]);+ assertEmptyElement(element);+ const bindings = {};+ for (const n of ["from", "to"]) {+ const a = element.attributes[n];+ if (a?.kind !== "reference") throw Error(n + " needs Frame");+ const r = resolveReference(a.path);+ if (!r || !sameType(r.type, spatialTypes.frame))+ throw Error(n + " needs Frame");+ bindings[n] = r;+ }+ return {+ records: [+ {+ id: textAttribute(element, "id"),+ type: performanceTypes.style,+ value: {+ kind: "inline",+ value: canonicalize(performanceStyle(fragment, bindings)),+ },+ range: element.range,+ },+ ],+ components: [],+ fragments: [],+ };+ },+ });+}diff --git a/examples/complex-explainer/packages/opening-system/src/render.js b/examples/complex-explainer/packages/opening-system/src/render.jsnew file mode 100644index 00000000..43f5e07b--- /dev/null+++ b/examples/complex-explainer/packages/opening-system/src/render.js@@ -0,0 +1,326 @@+import { palette } from "@explainer/visual-language";+import { flagSetup } from "./flag-cloth.js";+import { sealVisualTrack } from "@hypit/hypit/composition";+import { browserProgram } from "@hypit/hypit/hyperframes";+import { assertTemporalWindowFor } from "@hypit/hypit/temporal";++const digits = {+ 0: ["11111", "10001", "10001", "10001", "10001", "10001", "11111"],+ 1: ["00100", "01100", "00100", "00100", "00100", "00100", "11111"],+ 2: ["11111", "00001", "00001", "11111", "10000", "10000", "11111"],+ 3: ["11111", "00001", "00001", "01111", "00001", "00001", "11111"],+ 4: ["10001", "10001", "10001", "11111", "00001", "00001", "00001"],+ 5: ["11111", "10000", "10000", "11111", "00001", "00001", "11111"],+ 6: ["11111", "10000", "10000", "11111", "10001", "10001", "11111"],+ 7: ["11111", "00001", "00010", "00100", "01000", "01000", "01000"],+ 8: ["11111", "10001", "10001", "11111", "10001", "10001", "11111"],+ 9: ["11111", "10001", "10001", "11111", "00001", "00001", "11111"],+ ":": ["0", "0", "1", "0", "1", "0", "0"],+};+const dotSvg = `<svg class="clock" viewBox="0 0 25 7" aria-label="Timer"></svg>`;+const dotSetup = `const patterns=data.digits, clock=root.querySelector('.clock');let previous='';+const showClock=(seconds)=>{const n=Math.max(0,Math.floor(Math.abs(seconds))),str=Math.floor(n/60)+':'+String(n%60).padStart(2,'0');if(str===previous)return;previous=str;let x=0,html='';for(const ch of str){const p=patterns[ch];for(let y=0;y<7;y++)for(let c=0;c<p[y].length;c++)if(p[y][c]==='1')html+='<rect x="'+(x+c)+'" y="'+y+'" width=".79" height=".79" rx=".035"/>';x+=p[0].length+1;}clock.setAttribute('viewBox','0 0 '+(x-1)+' 7');clock.innerHTML=html;};`;+const style = (obj) =>+ Object.entries(obj).map(([name, value]) => ({ name, value }));+function text(id, parent, value, font, size, color) {+ return {+ id,+ parent,+ kind: "text",+ order: id === "title" ? 1 : 2,+ text: value,+ fonts: [font],+ style: style({+ "font-size": size + "px",+ "line-height": 1.2,+ color,+ "white-space": "nowrap",+ }),+ };+}+function track(timeline, canvas, window, o, program, children = [], presents) {+ assertTemporalWindowFor(window, { subjectId: o.id, space: timeline });+ return sealVisualTrack({+ id: o.id,+ programSpaceId: timeline.id,+ visualIr: "hypit.visual-ir@1",+ presents: presents ?? [+ {+ id: o.id,+ span: window.span,+ stacking: { order: o.z, tieBreak: o.id },+ elements: [+ {+ id: "scene",+ kind: "program",+ order: 0,+ program,+ style: style({+ position: "absolute",+ inset: 0,+ width: canvas.widthPx + "px",+ height: canvas.heightPx + "px",+ }),+ },+ ...children,+ ],+ },+ ],+ });+}+export function renderTitle(timeline, canvas, window, font, o, bounce) {+ const w = canvas.widthPx;+ const letters = Array.from(o.title);+ return track(+ timeline,+ canvas,+ window,+ o,+ browserProgram({+ html: `+<div class="time">${dotSvg}</div+><div class="titlebox"+ ><div class="titlebar"><i></i><i></i><i></i><span>HYPIT.EXE</span><b>×</b></div+ ><canvas class="pixel-world" width="216" height="116"></canvas><div class="eyebrow">{{subtitle}}</div><div class="headline">${letters.map((_, i) => `<span class="title-letter">{{letter-${i}}}</span>`).join("")}</div+ ><svg class="spark" viewBox="0 0 7 7">+ <path+ d="M3 0h1v2h1v1h2v1H5v1H4v2H3V5H2V4H0V3h2V2h1Z"+ fill="${palette.pink}"+ stroke="${palette.ink}"+ stroke-width=".2"+ /></svg><div class="pixel-trim"><i></i><i></i><i></i><i></i></div><span class="window-grip">▰▰▰</span>+></div>+`,+ css: `:scope{pointer-events:none;color:${palette.ink}}.time{position:absolute;left:32%;top:${o.timerY * 100}%;width:36%;color:#ffe6f4;filter:drop-shadow(3px 4px 0 ${palette.ink}) drop-shadow(0 0 5px #fff1fa) drop-shadow(0 0 17px #ff58b4)}.clock{width:100%;fill:currentColor;overflow:visible;stroke:#73314f;stroke-width:.10;paint-order:stroke fill}.titlebox{position:absolute;left:10%;top:${o.titleY * 100}%;width:80%;height:27%;background:#fff3f9;border:5px solid ${palette.ink};border-radius:16px;box-shadow:13px 15px 0 ${palette.ink}}.titlebar{height:46px;display:flex;align-items:center;gap:9px;padding:0 16px;border-bottom:4px solid ${palette.ink};background:#f9a4cc;border-radius:11px 11px 0 0;font:20px Menlo,monospace}.titlebar i{width:13px;height:13px;background:#fdf4fa;border:2px solid ${palette.ink}}.titlebar i:nth-child(2){background:#b7dfc8}.titlebar i:nth-child(3){background:#d4baf6}.titlebar span{margin-left:12px}.titlebar b{margin-left:auto;font-size:32px}.pixel-world{position:absolute;left:0;top:50px;width:100%;height:calc(100% - 50px);border-radius:0 0 10px 10px;image-rendering:pixelated}.eyebrow{position:absolute;top:20%;left:0;width:100%;display:flex;justify-content:center}.eyebrow>*{color:${palette.ink}!important;-webkit-text-stroke:0!important}.headline{position:absolute;top:39%;left:0;width:100%;display:flex;justify-content:center}.title-letter{display:inline-block;will-change:transform}.title-letter>*{color:${palette.pink}!important;-webkit-text-stroke:3px ${palette.ink};paint-order:stroke fill;filter:drop-shadow(6px 6px 0 ${palette.ink})}.spark{position:absolute;width:54px;height:54px;right:35px;bottom:40px;image-rendering:pixelated}.pixel-trim{position:absolute;left:30px;bottom:35px;display:flex;gap:9px}.pixel-trim i{width:12px;height:12px;border:2px solid ${palette.ink};background:#f8a1cb}.pixel-trim i:nth-child(2){background:#cbb6ed}.pixel-trim i:nth-child(3){background:#bde3c7}.window-grip{position:absolute;right:12px;bottom:6px;font:11px monospace;letter-spacing:2px;color:#b687a2}`,+ data: { digits, seconds: o.seconds, fps: timeline.frameRate.numerator / timeline.frameRate.denominator, bounce: bounce.frame - window.span.startFrame },+ setup: dotSetup + `showClock(data.seconds);+const world=root.querySelector('.pixel-world').getContext('2d'),letters=[...root.querySelectorAll('.title-letter')];+world.imageSmoothingEnabled=false;+return frame=>{+ const t=frame/data.fps;+ world.fillStyle='#fff3f9';world.fillRect(0,0,216,116);+ // The road recedes to a clear central horizon; scenery stays at its sides.+ world.fillStyle='#f1d7ea';for(let i=0;i<5;i++){const x=9+i*48;world.fillRect(x,8+(i%2)*6,18,3);world.fillRect(x+4,5+(i%2)*6,9,3);}+ // Elevated valley walls flank a low clear center behind the title.+ for(let side of [-1,1])for(let x=0;x<72;x+=3){const k=x/72,high=56+Math.floor(k*k*47),px=side<0?x:213-x;world.fillStyle='#d7cee9';world.fillRect(px,high,3,116-high);world.fillStyle='#d7b6e4';world.fillRect(px,high+6,3,110-high);}+ const horizon=99;+ for(let y=horizon;y<116;y++){+ const depth=(y-horizon)/(116-horizon),half=5+depth*70;+ world.fillStyle='#d7dfbd';world.fillRect(0,y,216,1);+ world.fillStyle='#d9b6d7';world.fillRect(Math.floor(108-half),y,Math.ceil(half*2),1);+ world.fillStyle='#fff0f7';world.fillRect(Math.floor(108-half),y,Math.max(1,depth*3),1);world.fillRect(Math.floor(108+half),y,Math.max(1,depth*3),1);+ const stripe=((1/Math.max(.02,depth)-t*2.3)%2+2)%2;+ if(stripe<.85){world.fillStyle='#fff5fc';world.fillRect(Math.floor(108-depth*2),y,Math.max(1,depth*4),1);}+ }+ for(let i=0;i<7;i++){+ const p=((i/7+t*.22)%1),d=p*p,y=horizon+d*17,size=2+d*10;+ for(const side of [-1,1]){const x=108+side*(70+d*45);world.fillStyle='#bd8dad';world.fillRect(Math.floor(x-size*.15),Math.floor(y-size*.7),Math.max(1,size*.3),Math.ceil(size*.7));world.fillStyle=i%2?'#f5a4c9':'#b7cda9';world.fillRect(Math.floor(x-size*.6),Math.floor(y-size*1.7),Math.ceil(size*1.2),Math.ceil(size));world.fillRect(Math.floor(x-size*.3),Math.floor(y-size*2),Math.ceil(size*.6),Math.ceil(size*.3));}+ }+ letters.forEach((letter,i)=>{+ const age=(frame-data.bounce)/data.fps-i*.085,q=age/.42;+ const jump=q>=0&&q<1?Math.sin(q*Math.PI):0;+ letter.style.transform='translateY('+(-26*jump)+'px) rotate('+(-4*jump)+'deg) scale('+(1+.055*jump)+')';+ });+};`,+ }),+ [+ ...letters.map((letter, i) => ({ ...text(`letter-${i}`, "scene", letter, font, w * o.titleSize, o.color), order: 3 + i })),+ text("subtitle", "scene", o.subtitle, font, w * 0.078, `${palette.ink}`),+ ],+ );+}++export function renderTimer(timeline, canvas, window, font, o, logo, stop) {+ const fps = timeline.frameRate.numerator / timeline.frameRate.denominator;+ return track(+ timeline,+ canvas,+ window,+ o,+ browserProgram({+ html: `+<div class="badge"+ ><div class="pennant"><canvas class="flag-canvas"></canvas></div><div class="backplate"></div+ ><div class="plaque"><svg class="plaque-outline" viewBox="0 0 300 115" preserveAspectRatio="none"><path d="M-3 2H276L298 113H-3Z" fill="${palette.pink}" stroke="${palette.ink}" stroke-width="4" stroke-linejoin="round"/></svg><div class="topic">{{title}}</div><div class="sub">{{subtitle}}</div></div+ ><div class="readout">${dotSvg}</div></div+><div class="logo-resource">{{flag-logo}}</div>+`,+ css: `:scope{pointer-events:none}.badge{position:absolute;left:${o.x * 100}%;top:${o.y * 100}%;width:${o.width * 100}%;height:10.6%;color:#edf6ff;filter:drop-shadow(0 3px 3px #0007)}.backplate{position:absolute;z-index:0;left:-4%;top:-13%;width:80%;height:110%;border:3px solid ${palette.ink};border-radius:2px 5px 12px 2px;transform:skewX(10deg);background:#fff0f7;box-shadow:5px 6px 0 ${palette.ink}}.plaque{position:absolute;z-index:2;inset:0 0 43%;overflow:visible}.plaque-outline{position:absolute;inset:0;width:100%;height:100%;overflow:visible;filter:drop-shadow(5px 6px 0 ${palette.ink})}.topic{position:absolute;top:12%;left:8%;width:78%;display:flex;justify-content:center}.sub{position:absolute;top:73%;left:8%;width:78%;display:flex;justify-content:center;opacity:.64;letter-spacing:.06em}.readout{position:absolute;z-index:3;top:67%;left:26%;width:45%;filter:none}.clock{width:100%;fill:currentColor;overflow:visible}.pennant{position:absolute;z-index:1;bottom:89%;left:19%;height:76%;width:69%}.flag-canvas{display:block;width:100%;height:100%;image-rendering:pixelated}.logo-resource{position:absolute;opacity:0;width:1px;height:1px;pointer-events:none}`,+ data: {+ digits,+ seconds: o.seconds,+ fps,+ entrance: o.entranceFrames,+ stop: stop.frame-window.span.startFrame,+ flagAmplitude: o.flagAmplitude,+ flagSpeed: o.flagSpeed,+ flagColor: o.flagColor,+ },+ setup:+ dotSetup ++ flagSetup ++ `const badge=root.querySelector('.badge'),readout=root.querySelector('.readout');return frame=>{const p=Math.max(0,Math.min(1,frame/data.entrance)),e=1-Math.pow(1-p,3);badge.style.transform='translateX('+(-125*(1-e))+'%)';const held=frame>=data.stop,remain=data.seconds-Math.floor(Math.min(frame,data.stop,2*data.seconds*data.fps)/data.fps);showClock(held?data.seconds:remain);readout.style.color=held?'#e83f5f':remain<0?'#df3685':'${palette.ink}';const q=Math.max(0,Math.min(1,(frame-data.stop)/18)),flash=held?Math.sin(q*Math.PI):0;readout.style.filter='drop-shadow(0 0 '+(flash*22)+'px #ff2452)';badge.style.filter='drop-shadow(0 0 '+(flash*22)+'px #ff3e66)';drawFlag(frame);};`,+ }),+ [+ text(+ "title",+ "scene",+ o.title,+ font,+ canvas.widthPx * o.width * 0.16,+ `${palette.ink}`,+ ),+ text(+ "subtitle",+ "scene",+ o.subtitle,+ font,+ canvas.widthPx * o.width * 0.067,+ `${palette.ink}`,+ ),+ {+ id: "flag-logo",+ parent: "scene",+ kind: "image",+ order: 3,+ artifact: logo,+ style: [],+ },+ ],+ );+}+export function renderStage(timeline, canvas, window, items, o) {+ const presents = [];+ for (const [index, item] of items.entries()) {+ const start = Math.max(window.span.startFrame, item.window.span.startFrame),+ end = Math.min(+ window.span.endFrameExclusive,+ item.window.span.endFrameExclusive,+ );+ if (end <= start) continue;+ const w = canvas.widthPx,+ h = canvas.heightPx;+ const artifact = item.media?.visual?.artifact ?? item.image;+ if (!artifact) throw Error("Stage video needs prepared visual media.");+ let sampling;+ if (item.media) {+ const sourceRate = item.media.timeline.frameRate,+ rate = {+ numerator: sourceRate.numerator * timeline.frameRate.denominator,+ denominator: sourceRate.denominator * timeline.frameRate.numerator,+ };+ const offset =+ item.sourceStart ++ ((start - item.window.span.startFrame) * rate.numerator) /+ rate.denominator;+ const last =+ offset + ((end - start - 1) * rate.numerator) / rate.denominator;+ if (last >= item.media.timeline.frameCount)+ throw Error(+ "Stage window exceeds the supplied video. Shorten its window or supply longer media.",+ );+ sampling = {+ sourceFrameRate: sourceRate,+ sourceFrameCount: item.media.timeline.frameCount,+ segments: [+ {+ target: { startFrame: 0, endFrameExclusive: end - start },+ sourceFrame: {+ numerator: Math.round(offset * rate.denominator),+ denominator: rate.denominator,+ },+ rate,+ },+ ],+ };+ }+ const children = ["back", "front"].map((id, i) => ({+ id,+ parent: "scene",+ order: i + 1,+ kind: item.media ? "video" : "image",+ artifact,+ muted: true,+ ...(sampling ? { sampling } : {}),+ style: style({+ position: "absolute",+ inset: 0,+ width: "100%",+ height: "100%",+ "object-fit": i === 0 ? "cover" : o.fit,+ }),+ }));+ const program = browserProgram({+ html: `+<div class="back">{{back}}</div><div class="shade"></div+><div class="front"+ ><div class="aperture"><div class="content">{{front}}</div></div></div+>+`,+ css: `:scope{background:#070a10;overflow:hidden}.back{position:absolute;inset:-8%;filter:blur(${(o.blur * w) / 1080}px) brightness(${o.brightness});transform:scale(${o.zoom})}.shade{position:absolute;inset:0;background:linear-gradient(180deg,#0001 0%,transparent 40%,#000a 86%,#000d 100%)}.front{position:absolute;left:${o.x * 100}%;top:${o.y * 100}%;width:${o.width * 100}%;height:${o.height * 100}%;overflow:hidden;border-radius:${o.radius}px;filter:drop-shadow(0 9px 20px #0004)}.aperture{position:absolute;inset:0;overflow:hidden}.content{position:absolute;inset:0;transform-origin:center}`,+ data: {+ fit: o.fit,+ rate: o.pushRate,+ fps: timeline.frameRate.numerator / timeline.frameRate.denominator,+ offset: start - item.window.span.startFrame,+ },+ setup: `const content=root.querySelector('.content'),front=root.querySelector('.front'),aperture=root.querySelector('.aperture'),media=content.querySelector('img,video');return frame=>{if(data.fit==='contain'){const w=media?.naturalWidth||media?.videoWidth,h=media?.naturalHeight||media?.videoHeight;if(w&&h){const scale=Math.min(front.clientWidth/w,front.clientHeight/h);aperture.style.inset='auto';aperture.style.width=w*scale+'px';aperture.style.height=h*scale+'px';aperture.style.left=(front.clientWidth-w*scale)/2+'px';aperture.style.top=(front.clientHeight-h*scale)/2+'px';}}content.style.transform='scale('+(1+(frame+data.offset)/data.fps*data.rate)+')';};`,+ });+ presents.push({+ id: `${o.id}.${item.id}`,+ subjectId: item.id,+ span: { startFrame: start, endFrameExclusive: end },+ stacking: { order: o.z, tieBreak: String(index).padStart(6, "0") },+ elements: [+ {+ id: "scene",+ kind: "program",+ order: 0,+ program,+ style: style({+ position: "absolute",+ inset: 0,+ width: w + "px",+ height: h + "px",+ }),+ },+ ...children,+ ],+ });+ }+ return track(timeline, canvas, window, o, undefined, [], presents);+}++// An independent screen texture: the author's stack places it above picture and below graphics.+export function renderVeil(timeline, canvas, window, o) {+ const cell = (o.cell * canvas.widthPx) / 1080;+ const patterns = {+ mesh: `repeating-conic-gradient(from 45deg,rgba(255,255,255,.52) 0% 25%,rgba(0,0,0,.55) 0% 50%)`,+ dots: `radial-gradient(circle,rgba(0,0,0,.8) 0 22%,transparent 26%)`,+ hatch: `repeating-linear-gradient(-45deg,rgba(255,255,255,.35) 0 1px,transparent 1px ${cell}px)`,+ };+ return track(+ timeline,+ canvas,+ window,+ o,+ browserProgram({+ html: '<div class="wash"></div><div class="pattern"></div>',+ css: `:scope{pointer-events:none}.wash,.pattern{position:absolute;inset:0}.wash{background:${o.tint};opacity:${o.shade}}.pattern{background-image:${patterns[o.pattern]};background-size:${cell}px ${cell}px;opacity:${o.amount}}`,+ data: {+ length: window.span.endFrameExclusive - window.span.startFrame,+ fade: o.fadeFrames,+ },+ setup: `return frame=>{const f=data.fade;root.style.opacity=String(f?Math.max(0,Math.min(1,frame/f,(data.length-1-frame)/f)):1);};`,+ }),+ );+}++export function renderFlag(timeline, canvas, window, o, logo) {+ return track(timeline, canvas, window, o, browserProgram({+ html: '<div class="floor-cloth"><canvas class="flag-canvas"></canvas></div><div class="logo-resource">{{flag-logo}}</div>',+ css: `:scope{pointer-events:none}.floor-cloth{position:absolute;left:${o.x*100}%;top:${o.y*100}%;width:${o.width*100}%;height:${o.height*100}%;filter:none}.flag-canvas{display:block;width:100%;height:100%;image-rendering:pixelated}.logo-resource{position:absolute;opacity:0;width:1px;height:1px}`,+ data: {fps:timeline.frameRate.numerator/timeline.frameRate.denominator,flagPose:'floor',flagColor:o.flagColor,flagAmplitude:o.flagAmplitude,flagSpeed:o.flagSpeed},+ setup: flagSetup+`const cloth=root.querySelector('.floor-cloth');return frame=>{cloth.style.opacity=Math.min(1,frame/12);drawFlag(frame);};`+ }), [{id:'flag-logo',parent:'scene',kind:'image',order:1,artifact:logo,style:[]}]);+}diff --git a/examples/complex-explainer/packages/opening-system/src/studio.js b/examples/complex-explainer/packages/opening-system/src/studio.jsnew file mode 100644index 00000000..529f2b78--- /dev/null+++ b/examples/complex-explainer/packages/opening-system/src/studio.js@@ -0,0 +1,260 @@+import { compositionTypes } from "@hypit/hypit/composition";+import {+ createStudioCompanionHostFacet,+ textLayer,+ temporalLineageFor,+} from "@hypit/hypit/studio-adapter";+import { module, defaults } from "./definition.js";++const section = (id, label) => ({ id, label });+const field = (binding, label, domain, group, control, more = {}) => ({+ binding,+ label,+ domain,+ section: section(group, group),+ control,+ ...more,+});+const number = (binding, label, domain = "how", more = {}) =>+ field(+ binding,+ label,+ domain,+ domain === "where" ? "Placement" : "Appearance",+ "number",+ more,+ );+const percent = (binding, label, domain = "where") =>+ number(binding, label, domain, {+ unit: "%",+ number: { scale: 100, step: 1 },+ });+const text = (binding, label) => field(binding, label, "how", "Text", "text");+const z = number("z", "Drawing order", "where", { number: { step: 1 } });+const layouts = {+ Title: [+ text("title", "Title"),+ text("subtitle", "Subtitle"),+ number("seconds", "Promised duration", "how", {+ unit: "s",+ number: { minimum: 0, step: 1 },+ }),+ percent("timer-y", "Clock Y"),+ percent("title-y", "Title Y"),+ percent("title-size", "Title size", "how"),+ field("color", "Title color", "how", "Appearance", "color"),+ z,+ ],+ Timer: [+ text("title", "Title"),+ text("subtitle", "Subtitle"),+ number("seconds", "Countdown", "how", {+ unit: "s",+ number: { minimum: 0, step: 1 },+ }),+ percent("x", "X"),+ percent("y", "Y"),+ percent("width", "Width"),+ field("flag-color", "Flag color", "how", "Flag", "color"),+ field("flag-amplitude", "Wave amplitude", "how", "Flag", "number", {+ unit: "%",+ number: { scale: 100, minimum: 0, step: 0.5 },+ }),+ field("flag-speed", "Wave speed", "how", "Flag", "number", {+ unit: "cycles/s",+ number: { minimum: 0, step: 0.05 },+ }),+ z,+ ],+ Flag: [percent("x", "X"), percent("y", "Y"), percent("width", "Width"), percent("height", "Height"), field("flag-color", "Cloth color", "how", "Flag", "color"), z],+ Stage: [+ percent("x", "X"),+ percent("y", "Y"),+ percent("width", "Width"),+ percent("height", "Height"),+ field("fit", "Image fit", "how", "Appearance", "select", {+ options: ["contain", "cover"],+ }),+ percent("push-rate", "Slow push per second", "how"),+ number("blur", "Background blur", "how", {+ unit: "px",+ number: { minimum: 0, step: 1 },+ }),+ percent("brightness", "Background brightness", "how"),+ number("zoom", "Background scale", "how", {+ unit: "×",+ number: { minimum: 0, step: 0.05 },+ }),+ number("radius", "Corner radius", "how", {+ unit: "px",+ number: { minimum: 0, step: 1 },+ }),+ z,+ ],+ Veil: [+ field("pattern", "Pattern", "how", "Appearance", "select", {+ options: ["mesh", "dots", "hatch"],+ }),+ number("cell", "Pattern size", "how", {+ unit: "px",+ number: { minimum: 1, step: 1 },+ }),+ percent("amount", "Pattern opacity", "how"),+ percent("shade", "Wash opacity", "how"),+ field("tint", "Wash color", "how", "Appearance", "color"),+ z,+ ],+};+const names = {+ Flag: ["Floor flag", "Foreshortened cloth"],+ Title: ["Opening title", "Clock and headline"],+ Timer: ["Countdown", "Cloth flag and countdown"],+ Stage: ["Material stage", "Foreground media with enlarged backdrop"],+ Veil: ["Texture veil", "Patterned overlay"],+};+const tracks = Object.entries(layouts).map(([kind, inspector]) => ({+ id: kind.toLowerCase(),+ role: "track",+ output: {+ type: compositionTypes.visualTrack,+ surface: kind.toLowerCase(),+ modules: [module],+ },+ family: "opening-system",+ label: names[kind][0],+ icon: kind === "Stage" ? "video" : "component",+ tone: kind === "Stage" ? "blue" : "magenta",+ lane: { heightPx: 48 },+ bindings: inspector.map((f) => ({+ name: f.binding,+ writable: true,+ fallback: defaults[kind][f.binding],+ })),+ inspector,+ ...(kind === "Stage"+ ? {+ attachments: [+ {+ id: "items",+ family: "stage-items",+ label: "Media",+ tone: "blue-muted",+ icon: "video",+ facet: "visual",+ lane: { heightPx: 40 },+ },+ ],+ project(context) {+ const children = context+ .generic()+ .map((e) => ({+ ...e,+ lane: "items",+ temporal: temporalLineageFor(context, e.authoredId, "window"),+ }));+ if (!context.placement || !children.length) return children;+ const temporal = temporalLineageFor(+ context,+ context.placement.id,+ "window",+ );+ const span = temporal?.projection;+ return [+ {+ id: context.track.outputRef + ":stage",+ authoredId: context.placement.id,+ elementRange: context.placement.range,+ display: {+ title: names[kind][0],+ layers: [textLayer(names[kind][1])],+ },+ startFrame:+ span?.startFrame ??+ Math.min(...children.map((e) => e.startFrame)),+ endFrameExclusive:+ span?.endFrameExclusive ??+ Math.max(...children.map((e) => e.endFrameExclusive)),+ stackOrder: 0,+ renderIds: [],+ ...(temporal ? { temporal } : {}),+ presentation: { entity: "material-stage", chrome: "standard" },+ },+ ...children,+ ];+ },+ }+ : {+ project(context) {+ return context+ .generic()+ .map((e) => ({+ ...e,+ temporal: temporalLineageFor(+ context,+ context.placement.id,+ "window",+ ),+ display: {+ title: names[kind][0],+ layers: [textLayer(names[kind][1])],+ },+ }));+ },+ }),+}));+const frameNames = [+ "left",+ "top",+ "right",+ "bottom",+ "x",+ "y",+ "width",+ "height",+];+function frames(names) {+ return {+ bindings: names.map((name) => ({+ name,+ referenced: frameNames.map((name) => ({ name, writable: true })),+ })),+ inspector: names.flatMap((name) =>+ frameNames.map((f) => ({+ binding: name + "." + f,+ label: f,+ domain: "where",+ page: { id: name, label: name },+ section: { id: "frame", label: "Frame" },+ control: "number",+ number: { suffixes: ["%", "px"], step: 1 },+ })),+ ),+ };+}+const parameters = [+ {+ id: "pullback",+ match: { module, surface: "pullback" },+ bindings: [{ name: "scale", writable: true, fallback: 1.5 }],+ inspector: [+ number("scale", "Initial magnification", "how", {+ unit: "×",+ number: { minimum: 1, step: 0.05 },+ }),+ ],+ },+ {+ id: "portrait-inset",+ match: { module, surface: "portrait-inset" },+ ...frames(["frame"]),+ },+ {+ id: "reframe",+ match: { module, surface: "reframe" },+ ...frames(["from", "to"]),+ },+];+export const studioFacet = createStudioCompanionHostFacet({+ tracks,+ parameters,+});diff --git a/examples/complex-explainer/packages/single-line-captions/README.md b/examples/complex-explainer/packages/single-line-captions/README.mdnew file mode 100644index 00000000..41bf10c0--- /dev/null+++ b/examples/complex-explainer/packages/single-line-captions/README.md@@ -0,0 +1,7 @@+# Single shared caption row++Uses the public fine-caption renderer and author surface. Incoming cues take the shared row, clipping only visible spans. Semantic timings stay unchanged. This is the project’s single-host presentation choice.++## Studio++The project Track reuses the standard Fine Caption Companion with its Module identity. Cues display their actual content and numbering, and Uses keep the normal style band and recipe parameters. Only visibility scheduling differs from Fine Caption; cue identities, style projection and author editing follow the existing public implementation.diff --git a/examples/complex-explainer/packages/single-line-captions/package.json b/examples/complex-explainer/packages/single-line-captions/package.jsonnew file mode 100644index 00000000..34b023dd--- /dev/null+++ b/examples/complex-explainer/packages/single-line-captions/package.json@@ -0,0 +1,9 @@+{+ "name": "@explainer/single-line-captions",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "hypit": {+ "activation": "./src/activation.js"+ }+}\ No newline at end of filediff --git a/examples/complex-explainer/packages/single-line-captions/src/activation.js b/examples/complex-explainer/packages/single-line-captions/src/activation.jsnew file mode 100644index 00000000..33e937a1--- /dev/null+++ b/examples/complex-explainer/packages/single-line-captions/src/activation.js@@ -0,0 +1,140 @@+import { captionFineStudioTrackCompanions } from "@hypit/caption-fine-studio";+import { createStudioTrackCompanionHostFacet } from "@hypit/hypit/studio-adapter";+import {+ createMarkupSurfaceHostFacet,+ sealGraphFragment,+ canonicalize,+} from "@hypit/hypit/author-kit";+import {+ captionFineManifest,+ captionFineModuleRef,+ captionFineProducers,+ captionFineMarkupSurfaces,+ decodeFineCaptionTrackSurface,+ scheduleFineCaption,+ assertFineCaptionSchedule,+} from "@hypit/caption-fine";+const module = { name: "@explainer/single-line-captions", version: "1" },+ producer = { module, name: "schedule" };+const manifest = {+ format: "hypit.module@1",+ ...module,+ dependencies: [+ ...captionFineManifest.dependencies,+ { module: captionFineModuleRef },+ ],+ types: [],+ capabilities: [],+ producers: [+ {+ ...captionFineManifest.producers.find(+ (p) => p.name === captionFineProducers.schedule.name,+ ),+ name: producer.name,+ },+ ],+};+const inline = (r) => r.value.value;+export function singleLineSchedule(caption, program, document) {+ const schedule = scheduleFineCaption(caption, program, document);+ const cues = [...schedule.cues].sort(+ (a, b) => a.visibleStartFrame - b.visibleStartFrame,+ );+ // This production has one shared subtitle row. A new cue takes that row.+ // Only visibility is clipped; accepted semantic word times remain intact.+ const result = {+ ...schedule,+ cues: cues+ .map((cue, i) => {+ const next = cues[i + 1]?.visibleStartFrame ?? Infinity;+ return {+ ...cue,+ visibility: cue.visibility+ .map((s) => ({+ ...s,+ endFrameExclusive: Math.min(s.endFrameExclusive, next),+ }))+ .filter((s) => s.startFrame < s.endFrameExclusive),+ };+ })+ .filter((c) => c.visibility.length),+ };+ assertFineCaptionSchedule(result);+ return result;+}+const handler = (ctx) => {+ const result = decodeFineCaptionTrackSurface(ctx),+ ids = new Map();+ const fragments = result.fragments.map((f) => {+ if (+ !f.operations.some(+ (op) =>+ op.producer.module.name === captionFineModuleRef.name &&+ op.producer.name === captionFineProducers.schedule.name,+ )+ )+ return f;+ const replacement = sealGraphFragment({+ inputs: f.inputs,+ operations: f.operations.map((op) =>+ op.producer.module.name === captionFineModuleRef.name &&+ op.producer.name === captionFineProducers.schedule.name+ ? { ...op, producer }+ : op,+ ),+ exports: f.exports,+ });+ ids.set(f.id, replacement.id);+ return replacement;+ });+ return {+ ...result,+ fragments,+ components: result.components.map((c) => ({+ ...c,+ fragment: ids.get(c.fragment) ?? c.fragment,+ })),+ };+};+export const hypitPackage = {+ format: "hypit.node-package@1",+ modules: [{ manifest }],+ components: [+ {+ producers: [+ {+ producer,+ handler: ({ inputs: i }) => ({+ outputs: {+ schedule: {+ kind: "inline",+ value: canonicalize(+ singleLineSchedule(+ inline(i.caption),+ inline(i.program),+ inline(i.document),+ ),+ ),+ },+ },+ needs: {},+ }),+ },+ ],+ },+ ],+ hostFacets: [+ createStudioTrackCompanionHostFacet(+ captionFineStudioTrackCompanions.map((companion) => ({+ ...companion,+ output: { ...companion.output, modules: [module] },+ })),+ ),+ createMarkupSurfaceHostFacet({+ module,+ declaration: captionFineMarkupSurfaces.find((s) => s.name === "track"),+ handler,+ }),+ ],+};+export default hypitPackage;diff --git a/examples/complex-explainer/packages/visual-language/package.json b/examples/complex-explainer/packages/visual-language/package.jsonnew file mode 100644index 00000000..8fc15078--- /dev/null+++ b/examples/complex-explainer/packages/visual-language/package.json@@ -0,0 +1,9 @@+{+ "name": "@explainer/visual-language",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.js"+ }+}diff --git a/examples/complex-explainer/packages/visual-language/src/index.js b/examples/complex-explainer/packages/visual-language/src/index.jsnew file mode 100644index 00000000..04cd5a98--- /dev/null+++ b/examples/complex-explainer/packages/visual-language/src/index.js@@ -0,0 +1,15 @@+export const palette = Object.freeze({+ ink: "#281d2d",+ paper: "#fce5ee",+ pink: "#fa67aa",+ pinkSoft: "#f7c9df",+ cream: "#fff8fc",+ mint: "#b6e2c9",+ lilac: "#e1cef8",+});+export const paletteCss =+ ":scope{" ++ Object.entries(palette)+ .map(([name, value]) => "--" + name + ":" + value)+ .join(";") ++ "}";diff --git a/examples/complex-explainer/packages/web-scenes/README.md b/examples/complex-explainer/packages/web-scenes/README.mdnew file mode 100644index 00000000..73177364--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/README.md@@ -0,0 +1,36 @@+# Coordinated explainer scenes++Eight project-owned scenes combine accepted media with frame-addressable HTML animation. A scene owns the objects that respond to one another; independent presenter framing, Caption, countdown and sound stay outside it. Fixed local geometry is appropriate for this one-off design.++## Scene map++| Surface | Source folder | What belongs together |+| --- | --- | --- |+| Introduction | `src/scenes/introduction/` | Website/code demonstrations, app icons and paired example cards |+| Comparison | `src/scenes/comparison/` | Two product demonstrations and their visual comparison |+| Road | `src/scenes/editor-route/` | Opposing route cards, folder, pointer, editor, rejected drag and terminal |+| CodeJourney | `src/scenes/code-route/` | Code, copied implementations and time-editing demonstration |+| ComponentWorkshop | `src/scenes/components/` | Reused structures and changing media inputs |+| SemanticWorkshop | `src/scenes/semantic-time/` | Visible words and the graphic events attached to them |+| DeliveryWorkshop | `src/scenes/delivery/` | Result library, phone feeds and the drinking callback |+| Outro | `src/scenes/outro/` | GitHub demonstration, install sequence, portraits and closing card |++Each folder owns `index.js` (content and resource slots), `styles.js` (appearance) and `animation.js` (frame-to-state behavior). The editor route additionally separates the appearances of its stage, editor, material and output demonstrations.++## Inputs and time++Each Surface receives Timeline, Canvas, font, a temporal Window, its explicit assets and named `Beat` children. The Source attaches those events to Script Moments or authored time. The Surface uses the public temporal projection helpers; local animation reads the resulting event frames. Seek any frame directly: pointer paths, springs, typing and transitions derive state from time.++Prepared video inputs are SynchronizedMedia. Image inputs are Blob artifacts. `DeliveryWorkshop.reference` is the fictional drinking illustration; it is deliberately an image, without fabricating a silent Take or video. Media entries explicitly choose native playback, holding the last frame or looping where the scene needs it.++Shared ordinary modules under `src/shared/` own browser-program assembly and media sampling, visual primitives, the route cards, terminal behavior and editor artwork. `@explainer/visual-language` supplies common palette and motion helpers. These code dependencies are not automatically separate Film Tracks.++## Companion and sound++`src/studio.js` declares scene identity, concise descriptions, temporal lineage and drawing-order controls through Hypit's public Companion facet. Studio does not know these scene names. Detailed design remains in the package instead of exposing every internal dimension.++All outputs are visual contributions. Music and pixel effects are explicit Audio Tracks in the main Source; these scenes neither play hidden audio nor infer routing.++## What the demonstrations mean++Website and template-library passages use supplied recordings. The competitor-case clips were made by the project owner. Repeated marks, token counters, the editor and its failed drag are authored illustrations, not measurements or recordings proving product behavior. The complete argument remains this production's editorial copy. See the production's asset provenance notes.diff --git a/examples/complex-explainer/packages/web-scenes/package.json b/examples/complex-explainer/packages/web-scenes/package.jsonnew file mode 100644index 00000000..af37d59b--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/package.json@@ -0,0 +1,15 @@+{+ "name": "@explainer/web-scenes",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "hypit": {+ "activation": "./src/activation.js"+ },+ "exports": {+ ".": "./src/render.js"+ },+ "dependencies": {+ "@explainer/visual-language": "file:../visual-language"+ }+}diff --git a/examples/complex-explainer/packages/web-scenes/src/activation.js b/examples/complex-explainer/packages/web-scenes/src/activation.jsnew file mode 100644index 00000000..8785c9e9--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/activation.js@@ -0,0 +1,483 @@+import { renderComponentWorkshop } from "./scenes/components/index.js";+import { renderSemanticWorkshop } from "./scenes/semantic-time/index.js";+import { renderDeliveryWorkshop } from "./scenes/delivery/index.js";+import { renderCodeJourney } from "./scenes/code-route/index.js";+import { renderOutro } from "./scenes/outro/index.js";+import { sceneCompanions } from "./studio.js";+import { createStudioTrackCompanionHostFacet } from "@hypit/hypit/studio-adapter";+import { renderRoad } from "./scenes/editor-route/index.js";+import {+ assertAttributes,+ assertEmptyElement,+ textAttribute,+ canonicalize,+ sameType,+ sealGraphFragment,+ createMarkupSurfaceHostFacet,+} from "@hypit/hypit/author-kit";+import { compositionTypes } from "@hypit/hypit/composition";+import { mediaTypes } from "@hypit/hypit/media";+import { timelineTypes } from "@hypit/hypit/timeline";+import { spatialTypes } from "@hypit/hypit/spatial";+import { temporalTypes, assertTemporalInstantFor } from "@hypit/hypit/temporal";+import {+ resolveTemporalContext,+ createTemporalWindowProjection,+ createTemporalInstantProjection,+ temporalWindowAttributeNames,+ temporalWindowAttributeVocabulary,+ temporalContextAttributeVocabulary,+ temporalInstantAttributeNames,+ temporalInstantAttributeVocabulary,+} from "@hypit/hypit/temporal-markup";+import { renderIntro, renderComparison } from "./render.js";+const module = { name: "@explainer/web-scenes", version: "1" },+ type = (name) => ({ module, name }),+ producer = (name) => ({ module, name }),+ port = (name, type) => ({ name, type });+const options = type("Options"),+ events = type("Events");+const common = [+ port("timeline", timelineTypes.track),+ port("canvas", spatialTypes.canvas),+ port("window", temporalTypes.window),+ port("font", mediaTypes.fontArtifact),+ port("options", options),+ port("events", events),+];+const tags = {+ ComponentWorkshop: {+ name: "component-workshop",+ render: renderComponentWorkshop,+ assets: ["v0", "v1", "v2", "v3", "v4", "v5"],+ defaults: { z: 10 },+ },+ SemanticWorkshop: {+ name: "semantic-workshop",+ render: renderSemanticWorkshop,+ assets: ["creatify", "higgsfield"],+ defaults: { z: 10 },+ },+ DeliveryWorkshop: {+ name: "delivery-workshop",+ render: renderDeliveryWorkshop,+ assets: ["film", "clone", "water", "reference", "host", "thumb1", "thumb2", "thumb3"],+ defaults: { z: 10 },+ },+ CodeJourney: {+ name: "code-journey",+ render: renderCodeJourney,+ assets: ["codex", "remotion", "hyperframes", "ranking", "podcast", "interview", "target"],+ defaults: { z: 10 },+ },+ Outro: {+ name: "outro",+ render: renderOutro,+ assets: [+ "page",+ "codex",+ "portraits-0",+ "portraits-1",+ "portraits-2",+ "portraits-3",+ "portraits-4",+ ],+ defaults: { z: 10 },+ },+ Road: {+ name: "road",+ render: renderRoad,+ assets: [+ "page",+ "sample",+ "codex",+ "capcut",+ "premiere",+ "resolve",+ "logo",+ "portrait",+ "thumb-a",+ "thumb-b",+ "thumb-c",+ "thumb-d",+ "thumb-e",+ "thumb-f",+ "thumb-g",+ ],+ defaults: { z: 10 },+ },+ Introduction: {+ name: "intro",+ render: renderIntro,+ assets: [+ "page",+ "code",+ "readme",+ "codex",+ "claude",+ "reference-ranking",+ "reference-podcast",+ "reference-interview",+ "hypit-ranking",+ "hypit-podcast",+ "hypit-interview",+ ],+ defaults: { z: 10 },+ },+ Comparison: {+ name: "comparison",+ render: renderComparison,+ assets: [+ "left",+ "right",+ "price-a",+ "price-b",+ "templates-a",+ "templates-b",+ "case-a",+ "case-b",+ "logo-a",+ "logo-b",+ ],+ defaults: { z: 10 },+ },+};+const images = new Set([+ "creatify",+ "higgsfield",+ "host",+ "reference",+ "thumb1",+ "thumb2",+ "thumb3",+ "remotion",+ "hyperframes",+ "portraits-0",+ "portraits-1",+ "portraits-2",+ "portraits-3",+ "portraits-4",+ "codex",+ "claude",+ "logo-a",+ "logo-b",+ "capcut",+ "premiere",+ "resolve",+ "logo",+ "portrait",+ "thumb-a",+ "thumb-b",+ "thumb-c",+ "thumb-d",+ "thumb-e",+ "thumb-f",+ "thumb-g",+]);+const assetType = (n) => (images.has(n) ? mediaTypes.blobArtifact : mediaTypes.synchronized);+const ins = (tag) => [...common, ...tags[tag].assets.map((n) => port(n, assetType(n)))];+export const manifest = {+ format: "hypit.module@1",+ ...module,+ dependencies: [+ ...new Map(+ [+ compositionTypes.visualTrack,+ mediaTypes.blobArtifact,+ mediaTypes.fontArtifact,+ mediaTypes.synchronized,+ timelineTypes.track,+ spatialTypes.canvas,+ temporalTypes.window,+ temporalTypes.instant,+ ].map((t) => [t.module.name, { module: t.module }]),+ ).values(),+ ],+ types: [{ name: "Options" }, { name: "Events" }],+ capabilities: [],+ producers: [+ { name: "empty", inputs: [], outputs: [port("events", events)], needs: [] },+ {+ name: "append",+ inputs: [+ port("timeline", timelineTypes.track),+ port("events", events),+ port("options", options),+ port("at", temporalTypes.instant),+ ],+ outputs: [port("events", events)],+ needs: [],+ },+ ...Object.keys(tags).map((tag) => ({+ name: tags[tag].name,+ inputs: ins(tag),+ outputs: [port("track", compositionTypes.visualTrack)],+ needs: [],+ })),+ ],+};+const inline = (r) => {+ if (r?.value.kind !== "inline") throw Error("Expected inline scene value");+ return r.value.value;+ },+ value = (v) => ({ kind: "inline", value: canonicalize(v) }),+ out = (n, v) => ({ outputs: { [n]: value(v) }, needs: {} });+const component = {+ producers: [+ { producer: producer("empty"), handler: () => out("events", []) },+ {+ producer: producer("append"),+ handler: ({ inputs: i }) => {+ const o = inline(i.options),+ at = inline(i.at),+ list = inline(i.events);+ assertTemporalInstantFor(at, {+ subjectId: o.id,+ space: inline(i.timeline),+ });+ if (list.some((e) => e.name === o.name)) throw Error("Beat names must be unique");+ return out("events", [...list, { ...o, at }]);+ },+ },+ ...Object.keys(tags).map((tag) => ({+ producer: producer(tags[tag].name),+ handler: ({ inputs: i }) =>+ out(+ "track",+ tags[tag].render(+ inline(i.timeline),+ inline(i.canvas),+ inline(i.window),+ inline(i.font),+ inline(i.options),+ inline(i.events),+ Object.fromEntries(+ tags[tag].assets.map((n) => [n, images.has(n) ? i[n].value : inline(i[n])]),+ ),+ ),+ ),+ })),+ ],+};+function decode(tag) {+ return ({ element, resolveReference }) => {+ const spec = tags[tag];+ assertAttributes(element, [+ "id",+ "timeline",+ "canvas",+ "font",+ ...spec.assets,+ ...Object.keys(spec.defaults),+ ...temporalWindowAttributeNames,+ ]);+ const id = textAttribute(element, "id"),+ context = resolveTemporalContext({ element, resolveReference }),+ window = createTemporalWindowProjection({+ id: id + ".window",+ subjectId: id,+ element,+ ...context,+ resolveReference,+ });+ const ref = (el, n, t) => {+ const raw = el.attributes[n];+ if (typeof raw !== "object" || raw.kind !== "reference")+ throw Error(n + " must be a reference");+ const r = resolveReference(raw.path);+ if (!r || !sameType(r.type, t)) throw Error(n + " has wrong type");+ return r.ref;+ };+ const opts = { id };+ for (const [n, d] of Object.entries(spec.defaults)) {+ const v = element.attributes[n];+ if (v !== undefined && typeof v !== "string") throw Error(n + " must be literal");+ opts[n] = typeof d === "number" ? Number(v ?? d) : (v ?? d);+ }+ if (!Number.isSafeInteger(opts.z)) throw Error("z must be integer");+ const records = [+ ...window.records,+ {+ id: id + ".options",+ type: options,+ value: value(opts),+ range: element.range,+ },+ ],+ components = [...window.components],+ fragments = [...window.fragments];+ const inputs = ins(tag).filter((p) => p.name !== "events"),+ bindings = {+ timeline: context.timeline.ref,+ canvas: ref(element, "canvas", spatialTypes.canvas),+ window: window.ref,+ font: ref(element, "font", mediaTypes.fontArtifact),+ options: { kind: "record", id: id + ".options" },+ };+ for (const n of spec.assets) bindings[n] = ref(element, n, assetType(n));+ const input = (name) => ({ kind: "fragment-input", name }),+ op = (operation) => ({ kind: "fragment-operation", operation }),+ operations = [+ {+ id: "empty",+ producer: producer("empty"),+ inputs: {},+ result: { kind: "output", name: "events" },+ },+ ];+ let prev = "empty",+ count = 0;+ for (const ch of element.children) {+ if (ch.kind === "text") {+ if (ch.value.trim()) throw Error("Expected Beat");+ continue;+ }+ if (ch.name.split(":").at(-1) !== "Beat") throw Error("Expected Beat");+ assertAttributes(ch, ["name", ...temporalInstantAttributeNames]);+ assertEmptyElement(ch);+ const name = textAttribute(ch, "name"),+ key = "beat" + ++count,+ eid = id + "." + key,+ at = createTemporalInstantProjection({+ id: eid,+ subjectId: eid,+ element: ch,+ ...context,+ resolveReference,+ });+ records.push(...at.records, {+ id: eid + ".options",+ type: options,+ value: value({ id: eid, name }),+ range: ch.range,+ });+ components.push(...at.components);+ fragments.push(...at.fragments);+ inputs.push(port(key, options), port(key + "-at", temporalTypes.instant));+ bindings[key] = { kind: "record", id: eid + ".options" };+ bindings[key + "-at"] = at.ref;+ operations.push({+ id: key,+ producer: producer("append"),+ inputs: {+ timeline: input("timeline"),+ events: op(prev),+ options: input(key),+ at: input(key + "-at"),+ },+ result: { kind: "output", name: "events" },+ });+ prev = key;+ }+ operations.push({+ id: "render",+ producer: producer(spec.name),+ inputs: {+ ...Object.fromEntries(+ ins(tag)+ .filter((p) => p.name !== "events")+ .map((p) => [p.name, input(p.name)]),+ ),+ events: op(prev),+ },+ result: { kind: "output", name: "track" },+ });+ const fragment = sealGraphFragment({+ inputs,+ operations,+ exports: [+ {+ name: "track",+ type: compositionTypes.visualTrack,+ root: op("render"),+ },+ ],+ });+ return {+ records,+ fragments: [...fragments, fragment],+ components: [+ ...components,+ {+ id,+ fragment: fragment.id,+ inputs: bindings,+ outputs: { track: id + ".track" },+ range: element.range,+ },+ ],+ exports: [id + ".track"],+ };+ };+}+export const hypitPackage = {+ format: "hypit.node-package@1",+ modules: [{ manifest }],+ components: [component],+ hostFacets: [+ createStudioTrackCompanionHostFacet(sceneCompanions(module, tags)),+ ...Object.keys(tags).map((tag) =>+ createMarkupSurfaceHostFacet({+ module,+ declaration: {+ name: tags[tag].name,+ tag,+ mode: "structured",+ outputs: [+ options,+ events,+ compositionTypes.visualTrack,+ temporalTypes.window,+ temporalTypes.instant,+ temporalTypes.windowSpec,+ temporalTypes.instantSpec,+ ],+ vocabulary: {+ summary: "Project launch scene with phrase-driven visual beats.",+ attributes: [+ ...temporalContextAttributeVocabulary,+ ...temporalWindowAttributeVocabulary,+ ...["id", "canvas", "font", ...tags[tag].assets].map((name) => ({+ name,+ kind: "expression",+ required: true,+ summary: name,+ })),+ ...Object.keys(tags[tag].defaults).map((name) => ({+ name,+ kind: "literal",+ required: false,+ summary: name,+ })),+ ],+ children: [+ {+ tag: "Beat",+ cardinality: "many",+ summary: "Named event in the scene, projected from a Moment or authored time.",+ attributes: [+ {+ name: "name",+ kind: "literal",+ required: true,+ summary: "Behavioral event name",+ },+ ...temporalInstantAttributeVocabulary,+ ],+ },+ ],+ ports: [+ {+ name: "track",+ type: compositionTypes.visualTrack,+ summary: "Visual contribution",+ },+ ],+ },+ },+ handler: decode(tag),+ }),+ ),+ ],+};+export default hypitPackage;diff --git a/examples/complex-explainer/packages/web-scenes/src/render.js b/examples/complex-explainer/packages/web-scenes/src/render.jsnew file mode 100644index 00000000..07385ea7--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/render.js@@ -0,0 +1,3 @@+export { scene } from "./shared/scene.js";+export { renderIntro } from "./scenes/introduction/index.js";+export { renderComparison } from "./scenes/comparison/index.js";diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/code-route/animation.js b/examples/complex-explainer/packages/web-scenes/src/scenes/code-route/animation.jsnew file mode 100644index 00000000..eb0a2634--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/code-route/animation.js@@ -0,0 +1,31 @@+export const codeJourneyAnimation = `const $=s=>root.querySelector(s),$$=s=>[...root.querySelectorAll(s)];+const pop=x=>{x=clamp(x);return 1+2.70158*Math.pow(x-1,3)+1.70158*Math.pow(x-1,2)},smooth=x=>{x=clamp(x);return x*x*(3-2*x)},mix=(a,z,q)=>a+(z-a)*q;+const set=(el,a)=>{el.style.opacity=String(clamp(a));el.style.visibility=a>0?'inherit':'hidden'};+const panes=$$('.code-lines');for(const pane of panes){for(let i=0;i<31;i++){const line=document.createElement('div');line.className='code-line';const no=document.createElement('span');no.className='line-no';const text=document.createElement('span');text.className='line-text';line.append(no,text);pane.append(line)}}+const paintCode=(pane,characters,offset=0)=>{[...pane.children].forEach((row,i)=>{const n=i+offset,text=data.codeSamples[n%data.codeSamples.length];row.children[0].textContent=String(n+1);row.children[1].textContent=text.slice(0,Math.max(0,Math.floor(characters-i*62)));})};+const origins=[260,290,300],targets=[400,540,680],stamp=['1.36s','2.84s','0.72s'];+return frame=>{const f=frame,b=data.beats,water=fade(f,b.water,b.resume,6),solution=ease((f-b.solution)/18),resumed=ease((f-b.resume)/12);+ set($('.code-ground'),f<b.water?1:resumed);set($('.routes'),f<b.water?1:resumed);$('.routes').style.transform='translateY('+mix(400,385,solution)+'px) scale('+mix(.5,.7,solution)+')';+ const routeFaces=$$('.route-face'),handoff=smooth(f/20);routeFaces[0].style.background='rgb('+Math.round(mix(238,249,handoff))+','+Math.round(mix(113,188,handoff))+','+Math.round(mix(171,218,handoff))+')';routeFaces[1].style.background='rgb('+Math.round(mix(215,189,handoff))+','+Math.round(mix(190,118,handoff))+','+Math.round(mix(241,231,handoff))+')';+ routeFaces.forEach(el=>el.style.boxShadow="12px 14px 0 #382535");+ if(solution>0){routeFaces[0].style.background='#f99ac7';routeFaces[1].style.background='#c89ae9';const glow=Math.sin(clamp((f-b.keep)/18)*Math.PI)*16;routeFaces.forEach(el=>el.style.boxShadow='12px 14px 0 #382535,0 0 '+glow+'px #fff6bd')}+ const ide=1-ease((f-b.play)/10),tools=fade(f,b.remotion,b.play+7,8),play=fade(f,b.play,b.once+8,8),once=fade(f,b.once,b.variant+8,8),variant=fade(f,b.variant,b.copy+8,8),duplicate=fade(f,b.copy,b.time+8,8),retime=fade(f,b.time,b.water,8);+ set($('.code-ide'),ide*(1-tools*.48));$('.code-ide').style.transform='translateY('+((1-pop(f/14))*65)+'px)';paintCode($('.live-code'),170+f*15,Math.max(0,Math.floor((f-65)/15)));+ set($('.tool-icons'),tools);for(const [sel,at] of [['.remotion-tool',b.remotion],['.hyperframes-tool',b.hyperframes],['.html-tool',b.html]]){const el=$(sel),q=pop((f-at)/13);set(el,ease((f-at)/8));el.style.transform='translateY('+((1-q)*80)+'px) scale('+q+')'}+ set($('.motion-browser'),play);$('.motion-browser').style.transform='translateY('+((1-pop((f-b.play)/13))*75)+'px)';const pt=Math.max(0,f-b.play)/data.fps;+ $$('.toy').forEach((el,i)=>{const phase=pt*3.5+i*2.1,x=i===0?365+Math.sin(phase)*125:385+Math.cos(phase)*285,y=i===0?180+Math.cos(phase)*70:185+Math.sin(phase)*155;el.style.transform='translate('+x+'px,'+y+'px) rotate('+Math.sin(phase)*18+'deg) scale('+(1+.08*Math.sin(phase*1.5))+')'});+ $$('.pixel-spark').forEach((el,i)=>{const p=(pt*.55+i*.113)%1;el.style.left=(80+i*104)+'px';el.style.top=(70+p*470)+'px';el.style.transform='rotate('+Math.round(pt*6+i)*90+'deg) scale('+(Math.sin(p*Math.PI)*.8)+')';el.style.background=i%2?'#bf9fdd':'#f08abc'});+ set($('.once-stage'),once);const cycle=Math.max(1,(b.variant-b.once)/3),elapsed=Math.max(0,f-b.once),change=Math.min(2,Math.floor(elapsed/cycle));$$('.switch-shot').forEach((el,i)=>set(el,i===change?1:0));paintCode($('.reset-code'),200+Math.pow((elapsed%cycle)/cycle,.45)*2000,change*310);$('.rewrite-code').style.transform='translateY('+Math.sin((elapsed%cycle)/cycle*Math.PI)*-5+'px)';+ set($('.variant-stage'),variant);const vq=pop((f-b.variant)/14);$('.proposed-card').style.transform='translateX('+((1-vq)*100)+'px)';$('.proposed-card').style.borderColor=f%25<15?'#a957a7':'#d8acd5';+ set($('.duplicate-stage'),duplicate);paintCode($('.source-lines'),9999,2040+Math.max(0,Math.floor((f-b.copy)/5)));const dc=Math.max(0,f-b.copy)*22;paintCode($('.destination-lines'),dc%1750,Math.floor(dc/1750)*25);$('.code-transfer').style.transform='none';+ const burning=ease((f-b.tokens)/10);set($('.token-meter'),burning);$('.token-meter b').textContent=Math.round(12500+clamp((f-b.tokens)/Math.max(1,b.time-b.tokens))*337500).toLocaleString('en-US');$('.pixel-fire').style.transform='scale('+(1+Math.round(Math.sin(f*.9)*2)*.055)+') rotate('+Math.round(Math.sin(f*.4))*4+'deg)';+ set($('.retiming-stage'),retime);$$('.timing-row').forEach((row,i)=>{const rq=ease((f-b.time-i*4)/9);row.style.transform='translateX('+((1-rq)*80)+'px)';const body=row.querySelector('.row-script');set(body,ease((f-b.different-i*3)/9));const eq=ease((f-b.match-i*4)/9),slot=Math.max(1,(b.water-b.retime-5)/3),fix=clamp((f-b.retime-i*slot)/(slot*.8)),x=mix(origins[i],targets[i],smooth(fix));const chip=row.querySelector('.effect-chip');set(chip,eq);chip.style.left=x+'px';chip.style.transform='scale('+(.7+.3*pop((f-b.match-i*4)/12))+')';const tint=smooth(fix);chip.style.background='rgb('+Math.round(mix(207,197,tint))+','+Math.round(mix(184,223,tint))+','+Math.round(mix(237,191,tint))+')';row.querySelector('.effect-time').textContent=fix>=1?stamp[i]:fix>0?mix(parseFloat(stamp[i])*.35,parseFloat(stamp[i]),smooth(fix)).toFixed(2)+'s':'--.--s';const link=row.querySelector('.row-connector');set(link,eq);link.style.left=(x+56)+'px';});+ const pointer=$('.code-pointer');let px=820,py=465,pa=0,click=0;+ if(f<b.play){pa=1;const q=smooth((f-20)/16);px=mix(800,330,q);py=mix(1070,620,q);click=f>34&&f<45?1-(f-34)/11:0;}+ else if(f>=b.copy&&f<b.tokens){pa=1;const q=smooth((f-b.copy)/20);px=mix(350,790,q);py=mix(940,1070,q);click=f>b.copy+18&&f<b.copy+29?1-(f-b.copy-18)/11:0;}+ else if(f>=b.retime&&f<b.water){pa=1;const slot=Math.max(1,(b.water-b.retime-5)/3),i=Math.min(2,Math.floor((f-b.retime)/slot)),q=smooth(clamp((f-b.retime-i*slot)/(slot*.8)));px=42+mix(origins[i],targets[i],q)+65;py=465+i*254+166;click=0;}+ set(pointer,pa);pointer.style.transform='translate('+px+'px,'+py+'px)';set($('.code-click'),click);$('.code-click').style.transform='scale('+(1+(1-click)*1.4)+')';+ set($('.water-label'),water);$('.water-label').style.transform='translateY('+((1-pop((f-b.water)/12))*55)+'px)';$('.water-label i').style.opacity=String(.55+.45*Math.sin(f*.13)**2);+ set($('.synthesis-mark'),solution);$('.synthesis-mark').style.transform='translateY('+((1-pop((f-b.solution)/19))*80)+'px)';$('.synthesis-ring').style.backgroundPosition=(40+35*Math.sin(f*.035))+'% 0';$('.join-lines path').style.strokeDashoffset=String(1000*(1-ease((f-b.solution-8)/20)));+ const k=clamp((f-b.keep)/Math.max(12,b.drop-b.keep-4));$$('.kept-parts>div').forEach((el,i)=>{const q=smooth(clamp((k-i*.08)/.82)),x=mix(i?775:140,460,q),y=mix(1170,760,q)-Math.sin(q*Math.PI)*110;set(el,ease((f-b.parts-i*3)/8)*(1-ease((q-.85)/.15)));el.style.transform='translate('+x+'px,'+y+'px) scale('+(1-q*.5)+')';});const drop=clamp((f-b.drop)/Math.max(24,data.duration-b.drop));set($('.discarded'),f>=b.drop?1-ease((drop-.65)/.35):0);$$('.discarded span').forEach((el,i)=>{const age=f-b.drop-i*6,q=smooth(clamp((age-13)/Math.max(20,data.duration-b.drop-25)));set(el,ease(age/8)*(1-ease((q-.7)/.3)));el.style.transform='translate('+((i-1)*q*230)+'px,'+(q*q*670)+'px) rotate('+((i-1)*q*65)+'deg) scale('+(1-q*.3)+')';});+};`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/code-route/index.js b/examples/complex-explainer/packages/web-scenes/src/scenes/code-route/index.jsnew file mode 100644index 00000000..27cf73ab--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/code-route/index.js@@ -0,0 +1,232 @@+import { hypitWordmark, hypitSymbol } from "../../shared/brand-marks.js";+import { scene } from "../../shared/scene.js";+import { routeCardsHtml, routeCardsCss } from "../../shared/route-cards.js";+import { codeJourneyCss, synthesisDetailsCss } from "./styles.js";+import { codeJourneyAnimation } from "./animation.js";+import { requireBeats } from "../../shared/beats.js";+const htmlIcon = `<svg viewBox="0 0 100 110"><path fill="#e66a36" d="M5 5H95L87 94L50 105L13 94Z"/><path fill="#f68c51" d="M50 13H86L79 88L50 97Z"/><path fill="#fff3e9" d="M24 24H77L76 36H38L39 47H75L71 78L50 85L28 78L26 62H39L40 69L50 72L60 69L62 58H27Z"/></svg>`;+const pointer = `<svg viewBox="0 0 60 76"><path d="M6 4L51 37L30 42L21 67Z" fill="#fff6fc" stroke="#382535" stroke-width="4" stroke-linejoin="round"/><path d="M14 18L32 36L25 39L21 47Z" fill="#f48abc"/></svg>`;+const bar = (name) =>+ `<div class="code-bar"><i></i><i></i><i></i><span>${name}</span><b>×</b></div>`;+const codeSamples = [+ 'const scene = document.querySelector(".scene");',+ "const timeline = createTimeline({ fps: 30 });",+ 'const title = scene.querySelector(".title");',+ "function update(frame) {",+ " const progress = easeOut(frame / 24);",+ " title.style.transform = translate(0, progress);",+ " picture.style.opacity = progress;",+ " board.reveal({ row: 1, at: 2.40 });",+ " return { x: frame * 4, scale: 1.05 };",+ "}",+ "window.update = update;",+ "const clip = { start: 0, end: 128 };",+ "const spring = { stiffness: 120, damping: 12 };",+ "layout.place(card, { x: 480, y: 720 });",+ 'caption.setText("Make it yours.");',+ "animate(logo, { rotate: 12, duration: 18 });",+];+const wave = (row) =>+ Array.from(+ { length: 62 },+ (_, i) =>+ `<i style="height:${6 + Math.abs(Math.sin(i * (1.17 + row * 0.19)) * Math.cos(i * 0.41 + row)) * 38}px"></i>`,+ ).join("");+export function renderCodeJourney(t, c, w, font, o, events, m) {+ const names = [+ "remotion",+ "hyperframes",+ "html",+ "play",+ "once",+ "variant",+ "copy",+ "duplicate",+ "tokens",+ "time",+ "different",+ "match",+ "retime",+ "water",+ "resume",+ "solution",+ "keep",+ "drop",+ ];+ requireBeats(events, names);+ const b = Object.fromEntries(events.map((e) => [e.name, e.at.frame - w.span.startFrame]));+ const entries = {+ codex: { image: m.codex },+ remotion: { image: m.remotion },+ hyperframes: { image: m.hyperframes },+ "play-remotion": { image: m.remotion },+ "play-hyperframes": { image: m.hyperframes },+ };+ for (const [i, key] of ["ranking", "podcast", "interview"].entries()) {+ entries["switch-" + i] = { media: m[key], start: b.once, end: b.variant + 8 };+ entries["row-" + i] = { media: m[key], start: b.time, end: b.water };+ }+ entries["original"] = { media: m.ranking, start: b.variant, end: b.copy + 9 };+ entries["proposed"] = { media: m.target, start: b.variant, end: b.copy + 9 };+ const html = `+<div class="code-ground"></div>${routeCardsHtml}+<div class="code-ide code-window"+ >${bar("scene.html")}<div class="ide-body"+ ><aside><b>▧</b><b>⌕</b><b>⑂</b><b>▣</b><b>⚙</b></aside+ ><nav+ >EXPLORER<br /><br />▾ src<br /> scene.html<br /> motion.js<br /> styles.css<br /><br />▾+ assets<br /> host.mp4<br /> logo.svg</nav+ ><div class="ide-code"+ ><div class="file-tab">scene.html <span>×</span></div+ ><div class="code-lines live-code"></div></div></div+ ><div class="ide-status">● main <span>UTF-8 HTML 30fps</span></div></div+>+<div class="tool-icons"+ ><div class="tool remotion-tool">{{remotion}}</div+ ><div class="tool hyperframes-tool">{{hyperframes}}</div+ ><div class="tool html-tool">${htmlIcon}</div></div+>+<div class="motion-browser code-window"+ >${bar("localhost:3000")}<div class="playground"+ ><div class="play-grid"></div><div class="play-blob blob-0"></div+ ><div class="play-blob blob-1"></div><div class="toy toy-0">${hypitSymbol}</div+ ><div class="toy toy-1">{{play-remotion}}</div+ ><div class="toy toy-2">{{play-hyperframes}}</div>${Array.from({ length: 9 }, (_, i) => `<i class="pixel-spark spark-${i}"></i>`).join("")}</div+ ></div+>+<div class="once-stage"+ ><div class="switch-video code-window">${bar("video.mp4")}${[0, 1, 2].map((i) => `<div class="switch-shot shot-${i}">{{switch-${i}}}</div>`).join("")}</div+ ><div class="rewrite-code code-window"+ >${bar("scene.html")}<div class="code-lines reset-code"></div><div class="rewrite-caret"></div></div+></div>+<div class="variant-stage"+ ><div class="variant-card original-card">{{original}}</div+ ><div class="variant-arrow"+ ><svg viewBox="0 0 100 64">+ <path+ d="M8 22H56V6H68V18H80V30H92V42H80V54H68V62H56V46H8Z"+ fill="#382535"+ transform="translate(3 2)"+ />+ <path+ d="M4 18H52V2H64V14H76V26H88V38H76V50H64V58H52V42H4Z"+ fill="#f38fbd"+ stroke="#382535"+ stroke-width="3"+ />+ <path d="M12 25H56V16L72 30H12Z" fill="#ffdae9" /></svg></div+ ><div class="variant-card proposed-card">{{proposed}}<div class="wanted-outline"></div></div+></div>+<div class="duplicate-stage"+ ><div class="code-window source-code"+ >${bar("original.html")}<div class="code-lines source-lines"></div></div+ ><div class="code-transfer"+ ><svg viewBox="0 0 100 64">+ <path+ d="M8 22H56V6H68V18H80V30H92V42H80V54H68V62H56V46H8Z"+ fill="#382535"+ transform="translate(3 2)"+ />+ <path+ d="M4 18H52V2H64V14H76V26H88V38H76V50H64V58H52V42H4Z"+ fill="#f38fbd"+ stroke="#382535"+ stroke-width="3"+ />+ <path d="M12 25H56V16L72 30H12Z" fill="#ffdae9" /></svg></div+ ><div class="code-window destination-code"+ >${bar("new-video.html")}<div class="code-lines destination-lines"></div></div+ ><div class="token-meter"+ ><span>TOKENS</span><b>0</b+ ><svg class="pixel-fire" viewBox="0 0 12 16">+ <path d="M5 0H8V4H10V7H12V13H10V16H2V14H0V8H2V10H4V6H5Z" fill="#e34f82" />+ <path d="M6 7H8V11H10V14H8V16H4V14H3V11H5Z" fill="#ffd571" /></svg></div+></div>+<div class="retiming-stage">${[0, 1, 2].map((i) => `<div class="timing-row row-${i}"><div class="row-video">{{row-${i}}}</div><div class="row-script"><p>${["第一名,是属于我们的。", "今天我们来聊一聊这个话题。", "你会选择哪一个?"][i]}</p><div class="row-wave">${wave(i)}</div><div class="row-ruler"><i></i><i></i><i></i><i></i><i></i></div></div><div class="effect-chip effect-${i}"><span>${["#1", "▧", "ABC"][i]}</span><code class="effect-time">--.--s</code></div><div class="row-connector"></div></div>`).join("")}</div>+<div class="code-pointer"+ >${pointer}<div class="code-pointer-badge">{{codex}}</div><i class="code-click"></i+></div>+<div class="water-label"><span>✦</span> 战略性喝水 <span>✦</span><i>▰ ▰ ▰</i></div>+<div class="synthesis-mark"+ ><div class="synthesis-ring">${hypitSymbol}<b>Hypit</b></div+ ><svg class="join-lines" viewBox="0 0 800 240">+ <path+ d="M400 0V90Q400 120 370 120H130Q100 120 100 150V230M400 90Q400 120 430 120H670Q700 120 700 150V230"+ /></svg+></div>+<div class="kept-parts"+ ><div+ ><svg viewBox="0 0 90 65">+ <rect+ x="4"+ y="4"+ width="82"+ height="55"+ rx="3"+ fill="#ffd0e3"+ stroke="#382535"+ stroke-width="4"+ />+ <path d="M4 18H86M32 18V59" stroke="#382535" stroke-width="3" />+ <rect+ x="40"+ y="25"+ width="36"+ height="24"+ fill="#b2dacc"+ stroke="#382535"+ stroke-width="3"+ /></svg+ ><b>画布布局</b></div+ ><div+ ><svg viewBox="0 0 90 65">+ <path+ d="M30 13L10 32L30 51M60 13L80 32L60 51M51 7L39 57"+ fill="none"+ stroke="#382535"+ stroke-width="7"+ /></svg+ ><b>代码动效</b></div+ ></div+><div class="discarded"+ ><span+ ><svg viewBox="0 0 90 65">+ <path+ d="M30 13L10 32L30 51M60 13L80 32L60 51M51 7L39 57"+ fill="none"+ stroke="#382535"+ stroke-width="7"+ /></svg+ >重复代码</span+ ><span+ ><svg viewBox="0 0 90 65">+ <rect x="4" y="4" width="82" height="55" fill="#d4c4ef" stroke="#382535" stroke-width="4" />+ <path d="M13 22H70M13 33H57M13 44H76" stroke="#79598d" stroke-width="4" />+ <path d="M66 6V58" stroke="#e25781" stroke-width="4" /></svg+ >重抄时间点</span+ ><span+ ><svg viewBox="0 0 90 65">+ <path+ d="M20 48H75V58H20ZM13 32H68V45H13ZM23 14H78V28H23Z"+ fill="#f5cb70"+ stroke="#382535"+ stroke-width="4"+ />+ <path d="M31 17V26M43 17V26M55 17V26" stroke="#ae773d" stroke-width="3" /></svg+ >Token 开销</span+ ></div+>`;+ return scene(+ t,+ c,+ w,+ font,+ o,+ html,+ routeCardsCss + codeJourneyCss + synthesisDetailsCss,+ codeJourneyAnimation,+ events,+ entries,+ { codeSamples, duration: w.span.endFrameExclusive - w.span.startFrame },+ );+}diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/code-route/styles.js b/examples/complex-explainer/packages/web-scenes/src/scenes/code-route/styles.jsnew file mode 100644index 00000000..1e300d17--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/code-route/styles.js@@ -0,0 +1,14 @@+export const codeJourneyCss = `:scope{background:transparent!important;--ink:#382535;--lilac:#d5bcf0;color:var(--ink);font-family:Menlo,monospace!important}.backdrop,.backdrop-wash{display:none}.code-ground{position:absolute;inset:0;background-color:#fce5ee;background-image:radial-gradient(#f2bdcf 1.8px,transparent 1.8px);background-size:30px 30px}.routes{transform:translateY(400px) scale(.5)}.route-editor .route-face{background:#f9bcda}.route-code .route-face{background:#c794ee}.route{transform:rotateY(16deg)}.route-code{transform:rotateY(-16deg)}+.code-window{background:#fff2f8;border:4px solid var(--ink);border-radius:10px;box-shadow:10px 12px 0 var(--ink);overflow:hidden}.code-bar{height:53px;display:flex;align-items:center;gap:10px;padding:0 17px;border-bottom:3px solid var(--ink);background:#f3a9cd;font:23px Menlo,monospace}.code-bar i{width:12px;height:12px;background:#fff4fa;border:2px solid var(--ink)}.code-bar i:nth-child(2){background:#c6dfb7}.code-bar i:nth-child(3){background:#cbb4e9}.code-bar span{margin-left:20px}.code-bar b{margin-left:auto;font-size:29px}+.code-ide{position:absolute;left:35px;top:550px;width:1010px;height:640px}.ide-body{display:flex;height:548px}.ide-body aside{width:54px;flex:none;background:#eacde0;border-right:2px solid #bc92ac;display:flex;align-items:center;flex-direction:column;gap:32px;padding-top:18px;font:32px monospace}.ide-body nav{flex:none;width:175px;padding:23px 12px;font:19px/1.6 Menlo,monospace;white-space:nowrap;background:#f5dce9;border-right:2px solid #e1b5cf}.ide-code{flex:1;overflow:hidden}.file-tab{height:43px;padding:10px 15px;font:20px Menlo,monospace;background:#fff6fa;border-bottom:2px solid #eac9dd}.file-tab span{float:right}.ide-status{height:35px;background:#ed99c3;padding:3px 14px;font:19px Menlo,monospace}.ide-status span{float:right}.code-lines{font:20px/1.5 Menlo,monospace;padding:10px 15px;overflow:hidden;height:100%;white-space:pre}.code-line{height:30px;display:flex;gap:14px}.line-no{color:#bb8ba7;min-width:40px;text-align:right}.line-text{color:#854364}.code-line:nth-child(3n) .line-text{color:#5c5399}.code-line:nth-child(4n) .line-text{color:#56806d}+.tool-icons{position:absolute;left:70px;top:765px;width:940px;height:390px;z-index:5}.tool{position:absolute;width:245px;height:245px;filter:drop-shadow(0 0 18px #c2a7f8)}.tool>*{width:100%!important;height:100%!important;object-fit:contain!important}.remotion-tool{left:20px;filter:drop-shadow(0 0 20px #73bcff)}.hyperframes-tool{right:20px;filter:drop-shadow(0 0 20px #78edba)}.html-tool{left:315px;top:-35px;width:310px;height:340px;filter:drop-shadow(0 0 23px #ffd4a3)}+.motion-browser{position:absolute;left:35px;top:550px;width:1010px;height:630px}.playground{position:relative;height:573px;background:#fff1d9;overflow:hidden}.play-grid{position:absolute;inset:0;background-image:linear-gradient(#dfb4cc55 2px,transparent 2px),linear-gradient(90deg,#dfb4cc55 2px,transparent 2px);background-size:50px 50px;transform:perspective(800px) rotateX(18deg) scale(1.2)}.play-blob{position:absolute;width:360px;height:260px;border-radius:45%;background:#f7b4d5;filter:blur(2px)}.blob-0{left:40px;top:40px}.blob-1{right:10px;bottom:0;background:#c8b8eb}.toy{position:absolute;left:0;top:0;width:180px;height:180px;padding:22px;background:#fff8fc;border:4px solid var(--ink);border-radius:25px;box-shadow:8px 10px 0 #382535}.toy>*{width:100%!important;height:100%!important;object-fit:contain!important}.toy-0{background:#fff8fc;width:225px;height:225px;z-index:2}.pixel-spark{position:absolute;width:13px;height:13px;background:#e85b9e;box-shadow:13px 0 #e85b9e,0 13px #e85b9e}+.once-stage,.variant-stage,.duplicate-stage{position:absolute;left:40px;top:560px;width:1000px;height:640px}.switch-video{position:absolute;width:395px;height:630px;left:0}.switch-shot{position:absolute;top:53px;bottom:0;width:100%;overflow:hidden}.switch-shot>*{object-fit:cover!important;width:100%!important;height:100%!important}.rewrite-code{position:absolute;right:0;width:560px;height:630px}.reset-code{font-size:18px}.variant-card{position:absolute;top:0;width:410px;height:630px;background:#fff1f8;border:5px solid var(--ink);border-radius:10px;overflow:hidden;box-shadow:10px 12px 0 var(--ink)}.variant-card>*{width:100%!important;height:100%!important;object-fit:cover!important}.original-card{left:0}.proposed-card{right:0;border:6px dashed #ae69b0;box-shadow:none;background:#f6dce9}.proposed-card>video{opacity:.35;filter:saturate(.4)}.variant-arrow{position:absolute;left:432.5px;top:270px;width:135px;height:90px;color:#994979}+.source-code,.destination-code{position:absolute;top:0;width:450px;height:610px}.source-code{left:0}.destination-code{right:0}.duplicate-stage .code-lines{font-size:17px;line-height:1.5}.duplicate-stage .code-line{height:25px}.duplicate-stage .line-no{min-width:36px}.code-transfer{position:absolute;left:460px;top:269px;width:80px;height:72px}.token-meter{position:absolute;left:175px;top:470px;width:640px;height:140px;display:flex;align-items:center;gap:22px;padding:10px 28px;background:#ffcadf;border:5px solid var(--ink);box-shadow:10px 12px 0 var(--ink);z-index:5;font:25px Menlo,monospace}.token-meter b{font-size:69px;color:#d44784;text-shadow:3px 4px #fff3d7}.pixel-fire{margin-left:auto;width:66px;height:85px;image-rendering:pixelated}+.retiming-stage{position:absolute;left:42px;top:465px;width:996px;height:750px;transform:scale(1);transform-origin:top center}.timing-row{position:absolute;left:0;width:996px;height:230px;border:4px solid var(--ink);border-radius:9px;background:#fff2f8;box-shadow:8px 9px 0 #382535}.row-0{top:0}.row-1{top:254px}.row-2{top:508px}.row-video{position:absolute;left:14px;top:12px;width:127px;height:198px;border:3px solid var(--ink);overflow:hidden;border-radius:4px}.row-video>*{width:100%!important;height:100%!important;object-fit:cover!important}.row-script{position:absolute;left:172px;top:18px;width:780px}.row-script p{font:29px/1.5 sans-serif;margin:5px 0 10px;white-space:nowrap}.row-wave{height:55px;display:flex;align-items:center;gap:7px;width:735px;overflow:hidden}.row-wave i{display:block;width:5px;flex:none;background:#ca76a6}.row-ruler{position:absolute;top:155px;left:0;width:770px;height:2px;border-bottom:2px solid #c99ab5;display:flex;justify-content:space-between}.row-ruler i{height:8px;border-left:2px solid #c99ab5}.effect-chip{position:absolute;top:141px;width:137px;height:68px;border:3px solid var(--ink);background:#cdb8ef;display:flex;align-items:center;justify-content:center;gap:8px;box-shadow:4px 5px 0 #382535;font:28px monospace;z-index:2}.effect-chip code{font:20px monospace}.row-connector{position:absolute;top:128px;height:16px;border-left:3px dashed #cb5093}+.code-pointer{position:absolute;left:0;top:0;width:70px;height:90px;z-index:40;filter:drop-shadow(4px 5px 0 #38253533)}.code-pointer>svg{width:100%;height:100%}.code-pointer-badge{position:absolute;left:37px;top:45px;width:46px;height:46px;background:#fff4fa;border:3px solid var(--ink);border-radius:50%;padding:8px}.code-pointer-badge>*{width:100%!important;height:100%!important;object-fit:contain!important}.code-click{position:absolute;top:-15px;left:-15px;width:44px;height:44px;border:5px solid #ef63a4;border-radius:50%}+.water-label{position:absolute;top:1470px;left:270px;width:540px;text-align:center;padding:19px 20px;background:#ffe6f2;border:4px solid var(--ink);border-radius:7px;box-shadow:9px 10px 0 var(--ink);font:46px sans-serif}.water-label span{color:#e867a3}.water-label i{display:block;font:20px monospace;letter-spacing:8px;margin-top:10px;color:#e867a3}+.synthesis-mark{position:absolute;left:140px;top:650px;width:800px;height:610px;z-index:29}.synthesis-ring{position:relative;margin:auto;width:360px;height:290px;background:linear-gradient(120deg,#f9d36b 0%,#ffeeb2 35%,#fff9e1 48%,#f5c661 65%,#ffe49b 100%);background-size:240% 100%;border:5px solid var(--ink);border-radius:7px;box-shadow:11px 13px 0 var(--ink);z-index:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px}.synthesis-ring svg{width:155px;height:135px}.synthesis-ring b{font:bold 58px Menlo,monospace;color:#382535}.synthesis-ring:after{content:"";position:absolute;left:20px;right:20px;bottom:13px;height:4px;background:#382535}.join-lines{position:absolute;left:0;top:295px;width:800px;height:240px;overflow:visible}.join-lines path{fill:none;stroke:#c99a44;stroke-width:12;stroke-linecap:square;stroke-dasharray:1000;stroke-dashoffset:1000}.discarded{position:absolute;inset:0;z-index:35}.discarded span{position:absolute;top:1000px;width:168px;height:112px;background:#fff0d7;border:4px solid var(--ink);padding:12px;font:22px Menlo,monospace;color:#69334a;box-shadow:6px 7px 0 var(--ink);text-align:center}.discarded svg{width:68px;height:54px;display:block;margin:0 auto 5px}.discarded span:nth-child(1){left:160px!important}.discarded span:nth-child(2){left:460px!important}.discarded span:nth-child(3){left:760px!important}.discarded span:nth-child(1){left:150px}.discarded span:nth-child(2){left:470px}.discarded span:nth-child(3){left:790px}+`;++export const synthesisDetailsCss = `.variant-arrow svg,.code-transfer svg{width:100%;height:100%;overflow:visible}.kept-parts{position:absolute;inset:0;z-index:40;pointer-events:none}.kept-parts>div{position:absolute;left:0;top:0;width:160px;height:124px;padding:9px;background:#fff8e7;border:4px solid #382535;border-radius:5px;box-shadow:6px 7px 0 #382535;text-align:center;transform-origin:center}.kept-parts svg{width:85px;height:65px}.kept-parts b{display:block;font:25px sans-serif}.effect-1 span{display:block;width:27px;height:27px;background:linear-gradient(135deg,#f8c58d 48%,#9dbfa2 49%);border:2px solid #382535;font-size:0}.effect-1 span:after{content:"";display:block;width:6px;height:6px;background:#fff0bd;margin:3px}`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/comparison/animation.js b/examples/complex-explainer/packages/web-scenes/src/scenes/comparison/animation.jsnew file mode 100644index 00000000..be5e9ecb--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/comparison/animation.js@@ -0,0 +1,87 @@+export const comparison_animation = `const phases = [...root.querySelectorAll("[data-p]")],+ h = root.querySelector(".heading b"),+ sub = root.querySelector(".heading small"),+ stage = root.querySelector(".stage");+return (frame) => {+ paintBackdrop(frame);+ const b = data.beats,+ p =+ frame >= b.cases+ ? "case"+ : frame >= b.templates+ ? "templates"+ : frame >= b.monthly+ ? "price"+ : frame >= b.other+ ? "home-b"+ : "home-a";+ const windows = {+ "home-a": [0, b.other + 12],+ "home-b": [b.other, b.monthly + 12],+ price: [b.monthly, b.templates + 12],+ templates: [b.templates, b.cases + 12],+ case: [b.cases, data.count],+ };+ phases.forEach((el) => {+ const [start, end] = windows[el.dataset.p],+ q = ease((frame - start) / 12),+ leaving = clamp((frame - (end - 12)) / 12);+ el.style.opacity = String(fade(frame, start, end, 12));+ if (el.dataset.p.startsWith("home"))+ el.style.transform =+ "translateX(" ++ ((el.dataset.p === "home-a" ? -1 : 1) * (1 - q) * 85 - leaving * 60) ++ "px) scale(" ++ (1.035 - q * 0.035) ++ ")";+ else {+ el.querySelectorAll(".panel").forEach(+ (panel, i) =>+ (panel.style.transform =+ "translateX(" ++ (i === 0 ? 1 : -1) * (1 - q) * 150 ++ "px) translateY(" ++ (1 - q) * 35 ++ "px) scale(" ++ (1.045 - q * 0.045) ++ ")"),+ );+ }+ });+ h.textContent =+ p === "home-a"+ ? "Creatify"+ : p === "home-b"+ ? "Higgsfield"+ : p === "price"+ ? "月付方案"+ : p === "templates"+ ? "模板选择"+ : frame >= b.watermark+ ? "水印"+ : "案例对比";+ h.style.fontSize = p === "home-b" ? "74px" : "84px";+ sub.textContent = p.startsWith("home")+ ? "视频生成平台"+ : p === "price"+ ? "Creatify + Higgsfield"+ : p === "templates"+ ? "两家的模板界面"+ : frame >= b.watermark+ ? "品牌标识示意"+ : "提供的生成案例";+ const pair = !p.startsWith("home"),+ price = p === "price";+ root.querySelectorAll(".brand-label").forEach((el) => {+ el.style.opacity = String(fade(frame, b.monthly, b.templates, 7));+ el.style.top = "1200px";+ el.querySelector("span").style.display = price ? "block" : "none";+ });+ stage.style.height = "770px";+ root.querySelectorAll(".stamp").forEach((el) => {+ const q = ease((frame - b.watermark - Number(el.dataset.i) * 1.3) / 5);+ el.style.opacity = String(q * 0.7);+ el.style.transform = "rotate(-18deg) scale(" + (1.25 - q * 0.25) + ")";+ });+};+`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/comparison/index.js b/examples/complex-explainer/packages/web-scenes/src/scenes/comparison/index.jsnew file mode 100644index 00000000..2f129a79--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/comparison/index.js@@ -0,0 +1,47 @@+import { comparison_styles } from "./styles.js";+import { comparison_animation } from "./animation.js";+import { scene } from "../../shared/scene.js";+import { requireBeats } from "../../shared/beats.js";+export function renderComparison(t, c, w, font, o, events, m) {+ requireBeats(events, ["other", "monthly", "templates", "cases", "watermark"]);+ const b = Object.fromEntries(events.map((e) => [e.name, e.at.frame - w.span.startFrame])),+ count = w.span.endFrameExclusive - w.span.startFrame;+ const entries = {};+ for (const [id, media, start, end] of [+ ["home-a", m.left, 0, b.monthly],+ ["home-b", m.right, b.other, b.monthly],+ ["price-a", m["price-a"], b.monthly, b.templates],+ ["price-b", m["price-b"], b.monthly, b.templates],+ ["templates-a", m["templates-a"], b.templates, b.cases],+ ["templates-b", m["templates-b"], b.templates, b.cases],+ ["case-a", m["case-a"], b.cases, count],+ ["case-b", m["case-b"], b.cases, count],+ ])+ entries[id] = {+ media,+ start,+ end: Math.min(count, end + 12),+ backdrop: id.startsWith("home") ? {} : { left: id.endsWith("-a") ? 0 : 50, width: 50 },+ };+ let stamps = "";+ for (const side of ["a", "b"])+ for (let i = 0; i < 12; i++) {+ const id = "stamp-" + side + i;+ entries[id] = { image: m["logo-" + side] };+ stamps += `<div class="stamp stamp-${side}" data-i="${i}" style="left:${(side === "a" ? 0 : 50) + (i % 3) * 16.66}%;top:${Math.floor(i / 3) * 23}%">{{${id}}}</div>`;+ }+ const pair = (name) =>+ `<div class="phase pair" data-p="${name}"><div class="panel panel-a">{{${name}-a}}</div><div class="panel panel-b">{{${name}-b}}</div></div>`;+ return scene(+ t,+ c,+ w,+ font,+ o,+ `<div class="mesh"></div><div class="heading"><b>Creatify</b><small>视频生成平台</small></div><div class="stage"><div class="phase" data-p="home-a"><div class="screen">{{home-a}}</div></div><div class="phase" data-p="home-b"><div class="screen">{{home-b}}</div></div>${pair("price")}${pair("templates")}${pair("case")}<div class="stamps">${stamps}</div></div><div class="brand-label label-a">Creatify<span>$39/月</span></div><div class="brand-label label-b">Higgsfield<span>$59/月</span></div>`,+ comparison_styles,+ comparison_animation,+ events,+ entries,+ );+}diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/comparison/styles.js b/examples/complex-explainer/packages/web-scenes/src/scenes/comparison/styles.jsnew file mode 100644index 00000000..79879dc5--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/comparison/styles.js@@ -0,0 +1,88 @@+export const comparison_styles = `.heading b {+ font-size: 80px;+}+.panel {+ position: absolute;+ top: 0;+ width: 50%;+ height: 100%;+ background: transparent;+ overflow: hidden;+}+.panel-a {+ left: 0;+}+.panel-b {+ right: 0;+}+.panel > * {+ object-fit: cover !important;+ object-position: center top !important;+}+.phase[data-p="case"] .panel {+ background: none;+ border: 0;+ box-shadow: none;+}+.phase[data-p="case"] .panel-a > * {+ object-position: center top !important;+}+.phase[data-p="case"] .panel-b > * {+ object-position: center top !important;+}+.phase[data-p="price"] {+ height: 610px;+}+.phase[data-p="templates"] .panel > * {+ object-fit: cover !important;+}+.phase[data-p="price"] .panel > * {+ object-fit: cover !important;+ object-position: 50% 0 !important;+}+.brand-label {+ position: absolute;+ top: 1370px;+ width: 49%;+ text-align: center;+ font-size: 58px;+ color: #fff2f9;+ -webkit-text-stroke: 2px #281d2d;+ paint-order: stroke fill;+ text-shadow: 5px 6px 0 #281d2d;+ opacity: 0;+}+.label-a {+ left: 0;+}+.label-b {+ right: 0;+}+.brand-label span {+ display: block;+ font: bold 56px/1.2 Menlo, "Courier New", monospace;+ color: #e96aa3;+ -webkit-text-stroke: 2px #281d2d;+ paint-order: stroke fill;+ text-shadow: 3px 4px 0 #281d2d;+ margin-top: 26px;+}+.stamps {+ position: absolute;+ inset: 0;+ overflow: hidden;+}+.stamp {+ position: absolute;+ width: 16.2%;+ height: 21%;+ display: flex;+ align-items: center;+ opacity: 0;+ filter: drop-shadow(0 2px 2px #000);+ transform: rotate(-18deg);+}+.stamp > * {+ object-fit: contain !important;+}+`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/components/animation.js b/examples/complex-explainer/packages/web-scenes/src/scenes/components/animation.jsnew file mode 100644index 00000000..49ce082d--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/components/animation.js@@ -0,0 +1,101 @@+import { portraitMotion } from "../../shared/studio-art.js";+// This scene owns its fixed design. External events arrive as projected frames.+export const animation = `+return (f) => {+ const b = data.beats,+ zoom = smooth((f - b.all) / 20),+ lib = smooth((f - b.library) / 22),+ reuse = smooth((f - b.reuse) / 22),+ variants = ease((f - b.variants) / 10),+ boxStart = ease((f - b.caption) / 20);+ show($(".component-editor"), 1 - zoom);+ show($(".hero-person"), (1 - boxStart * 0.8) * (1 - lib));+ move(+ $(".hero-person"),+ mix(410, 320, zoom),+ mix(735, 650, zoom),+ mix(0.6, 1.18, zoom),+ );+ show($(".component-library"), lib * (1 - reuse));+ show($(".new-creators"), reuse * (1 - variants));+ show($(".tile-world"), 1 - variants);+ animateTiles(f); ${portraitMotion}+ const times = [b.caption, b.ranking, b.chart, b.card],+ offsets = [+ [25, 430, 0.64],+ [12, 205, 0.4],+ [220, 110, 0.28],+ [180, 340, 0.36],+ ],+ land = [+ [78, 980, 0.6],+ [400, 810, 0.42],+ [810, 825, 0.34],+ [730, 1100, 0.48],+ ];+ $$(".effect-tile").forEach((el, i) => {+ const boxed = smooth((f - times[i]) / 15),+ hs = mix(0.6, 1.18, zoom),+ hx = mix(410, 320, zoom),+ hy = mix(735, 650, zoom);+ let x = hx + offsets[i][0] * hs,+ y = hy + offsets[i][1] * hs,+ s = offsets[i][2] * hs;+ x = mix(x, 100 + (i % 2) * 475, boxed);+ y =+ mix(y, 715 + Math.floor(i / 2) * 320, boxed) -+ Math.sin(boxed * Math.PI) * 40;+ s = mix(s, 0.9, boxed);+ x = mix(x, 255 + (i % 2) * 305, lib);+ y = mix(y, 810 + Math.floor(i / 2) * 260, lib);+ s = mix(s, 0.61, lib);+ const q = smooth((f - b.reuse - i * 3) / 20);+ x = mix(x, land[i][0], q);+ y = mix(y, land[i][1], q) - Math.sin(q * Math.PI) * 95;+ s = mix(s, land[i][2], q);+ move(el, x, y, s);+ show(el, 1);+ const shell = boxed * (1 - reuse);+ el.style.background = "rgba(255,248,234," + shell + ")";+ el.style.borderColor = "rgba(130,82,125," + shell + ")";+ el.style.boxShadow = "8px 9px rgba(56,37,53," + shell + ")";+ show(el.querySelector(".tile-cap"), shell);+ show(+ el.querySelector(".tile-corners"),+ Math.sin(clamp((f - times[i]) / 24) * Math.PI),+ );+ });+ const ghost = fade(f, 4, b.all, 7),+ g = smooth((f - 10) / 22);+ show($(".copy-ghost"), ghost);+ move(+ $(".copy-ghost"),+ mix(435, 310, g),+ mix(900, 1250, g),+ mix(0.65, 1, g),+ );+ show($(".work-pointer"), ghost);+ move($(".work-pointer"), mix(545, 445, g), mix(935, 1280, g));+ $(".hs-playhead").style.left = 220 + f * 1.4 + "px";+ $$(".new-creator").forEach(+ (el, i) =>+ (el.style.transform =+ "translateY(" + (1 - pop((f - b.reuse - i * 2) / 17)) * 90 + "px)"),+ );+ show($(".variant-trio"), variants);+ $$(".trio-card").forEach((el, i) => {+ const q = pop((f - [b.word, b.picture, b.color][i]) / 11),+ swap = smooth((f - b.swap - i * 2) / 13);+ el.style.transform =+ "translateY(" ++ (1 - q) * 100 ++ "px) rotateY(" ++ Math.sin(swap * Math.PI) * -15 ++ "deg) scale(" ++ (0.85 + 0.15 * q) ++ ")";+ show(el, ease((f - [b.word, b.picture, b.color][i]) / 8));+ show(el.querySelector(".trio-first"), 1 - swap);+ show(el.querySelector(".trio-next"), swap);+ });+};`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/components/index.js b/examples/complex-explainer/packages/web-scenes/src/scenes/components/index.jsnew file mode 100644index 00000000..2da48f4b--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/components/index.js@@ -0,0 +1,51 @@+import { css } from "./styles.js";+import { animation } from "./animation.js";+import { hypitSymbol } from "../../shared/brand-marks.js";+import { scene } from "../../shared/scene.js";+import { pointer, tiles, workCss, workSetup } from "../../shared/workshop-language.js";+import {+ studioBar,+ inspector,+ librarySide,+ miniTimeline,+ faceless,+ studioCss,+ portraitMotion,+} from "../../shared/studio-art.js";+export function renderComponentWorkshop(t, c, w, font, o, events, m) {+ const b = Object.fromEntries(events.map((e) => [e.name, e.at.frame - w.span.startFrame]));+ const entries = {};+ for (let i = 0; i < 6; i++)+ entries["v" + i] = {+ media: m["v" + i],+ start: i < 3 ? b.variants : b.swap,+ end: w.span.endFrameExclusive - w.span.startFrame,+ };+ const html = `+<div class="work-ground"></div+><div class="component-editor hs-window"+ >${studioBar()}${librarySide()}<div class="hs-preview-label hs-tab">Preview</div+ ><div class="hs-preview-matte"></div>${inspector()}${miniTimeline()}</div+><div class="hero-person">${faceless(0)}</div><div class="tile-world">${tiles()}</div+><div class="copy-ghost"+ ><span class="drag-rank">#1</span><span class="drag-logo">${hypitSymbol}</span><b>Hypit</b+ ><div class="drag-bars"><i></i><i></i><i></i></div></div+><div class="component-library"+ ><div class="library-tab"></> 组件库</div+ ><div class="library-rim"><i></i><i></i><i></i><b>4 COMPONENTS</b></div+ ><div class="library-slots"><i></i><i></i><i></i><i></i></div></div+><div class="new-creators">${[0, 1, 2].map((i) => `<div class="new-creator creator-${i}">${faceless(i)}</div>`).join("")}</div+><div class="variant-trio">${[0, 1, 2].map((i) => `<div class="trio-card card-${i}"><div class="trio-first">{{v${i}}}</div><div class="trio-next">{{v${i + 3}}}</div></div>`).join("")}</div>${pointer}`;+ return scene(+ t,+ c,+ w,+ font,+ o,+ html,+ workCss + studioCss + css,+ workSetup + animation,+ events,+ entries,+ );+}diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/components/styles.js b/examples/complex-explainer/packages/web-scenes/src/scenes/components/styles.jsnew file mode 100644index 00000000..a40497a0--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/components/styles.js@@ -0,0 +1,197 @@+// This scene owns its fixed design. External events arrive as projected frames.+export const css = `+.component-editor {+ top: 650px;+ height: 750px;+}+.hero-person {+ position: absolute;+ left: 0;+ top: 0;+ width: 360px;+ height: 640px;+ border: 3px solid #775169;+ box-shadow: 7px 9px #ad819b55;+ overflow: hidden;+ transform-origin: 0 0;+}+.tile-world {+ position: absolute;+ inset: 0;+ z-index: 10;+ pointer-events: none;+}+.effect-tile {+ transition: none;+}+.copy-ghost {+ position: absolute;+ left: 0;+ top: 0;+ width: 205px;+ height: 84px;+ background: #fff0c5f0;+ border: 3px solid #9f6289;+ color: #67405e;+ font: 27px monospace;+ padding: 10px;+ z-index: 20;+ box-shadow: 5px 7px #bc8aaa88;+ border-radius: 5px;+ display: flex;+ align-items: flex-start;+ gap: 8px;+ transform-origin: 0 0;+}+.drag-rank {+ font-weight: bold;+ color: #a77138;+}+.drag-logo {+ width: 35px;+ height: 35px;+}+.drag-logo svg {+ width: 100%;+ height: 100%;+}+.copy-ghost > b {+ font-size: 25px;+}+.drag-bars {+ position: absolute;+ left: 13px;+ right: 13px;+ bottom: 10px;+ display: flex;+ gap: 7px;+}+.drag-bars i {+ display: block;+ width: 45%;+ height: 10px;+ background: #d5aedf;+ border: 1px solid #9f719f;+}+.drag-bars i:nth-child(2) {+ width: 25%;+ background: #efadca;+}+.drag-bars i:nth-child(3) {+ width: 15%;+ background: #f0ce89;+}+.component-library {+ position: absolute;+ left: 210px;+ top: 700px;+ width: 660px;+ height: 640px;+ border: 5px solid #583954;+ background: #edbcd3;+ border-radius: 12px;+ box-shadow: 13px 15px #583954;+}+.library-tab {+ position: absolute;+ left: -5px;+ top: -62px;+ width: 320px;+ height: 62px;+ border: 5px solid #583954;+ border-bottom: none;+ border-radius: 10px 10px 0 0;+ background: #f6d3e1;+ padding: 12px 22px;+ font: 30px sans-serif;+}+.library-rim {+ display: flex;+ align-items: center;+ gap: 12px;+ height: 60px;+ padding: 12px 24px;+ background: #f6d3e1;+ border-bottom: 3px solid #b885a6;+}+.library-rim i {+ width: 14px;+ height: 14px;+ border: 2px solid #9e668c;+ background: #fff0d3;+}+.library-rim b {+ margin-left: auto;+ font: 18px monospace;+ color: #a26b8c;+}+.library-slots {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 35px;+ padding: 33px 27px;+}+.library-slots i {+ height: 223px;+ border: 3px dashed #be91aa;+ border-radius: 8px;+ background: #fff0f6;+}+.new-creator {+ position: absolute;+ top: 740px;+ width: 300px;+ height: 534px;+ border: 4px solid #583954;+ border-radius: 10px;+ box-shadow: 9px 11px #583954;+ overflow: hidden;+}+.creator-0 {+ left: 60px;+}+.creator-1 {+ left: 390px;+}+.creator-2 {+ left: 720px;+}+.variant-trio {+ position: absolute;+ left: 25px;+ top: 755px;+ width: 1030px;+ height: 600px;+ perspective: 1500px;+}+.trio-card {+ position: absolute;+ top: 0;+ width: 330px;+ height: 586.6667px;+ border: 4px solid #583954;+ border-radius: 10px;+ overflow: hidden;+ box-shadow: 9px 12px #583954;+ background: #fff3fa;+ transform-origin: center;+}+.trio-card > div {+ position: absolute;+ inset: 0;+}+.trio-card video {+ width: 100% !important;+ height: 100% !important;+ object-fit: cover !important;+}+.card-0 {+ left: 0;+}+.card-1 {+ left: 350px;+}+.card-2 {+ left: 700px;+}+`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/delivery/animation.js b/examples/complex-explainer/packages/web-scenes/src/scenes/delivery/animation.jsnew file mode 100644index 00000000..8557c757--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/delivery/animation.js@@ -0,0 +1,83 @@+// This scene owns its fixed design. External events arrive as projected frames.+export const animation = `+return (f) => {+ const b = data.beats,+ asset = ease((f - b.assets) / 13),+ publish = smooth((f - b.upload) / 17),+ compare = smooth((f - b.compare) / 20),+ meta = smooth((f - b.meta) / 17),+ guess = smooth((f - b.guess) / 20);+ show($(".delivery-studio"), 1 - publish);+ $(".delivery-studio").style.transform =+ "scale(" + (1 + 0.025 * asset) + ")";+ $$(".asset-thumb").forEach((el, i) => {+ const ready = ease((f - b.assets - i * 7) / 9);+ show(el.querySelector(".asset-picture"), ready);+ show(el.querySelector(".pixel-loading"), 1 - ready);+ el.querySelectorAll(".pixel-loading i").forEach(+ (dot, j) =>+ (dot.style.opacity = ((Math.floor(f / 3) + j) % 9) / 10 + 0.1),+ );+ el.querySelector(".asset-progress i").style.width =+ clamp((f + 15 - i * 4) / Math.max(1, b.assets + i * 7 + 8)) * 100 + "%";+ });+ show($(".studio-film"), ease((f - b.assets - 21) / 12));+ $(".hs-playhead").style.left = 210 + f * 1.7 + "px";+ const left = $(".phone-left"),+ right = $(".phone-right");+ show(left, publish);+ move(+ left,+ mix(391, mix(330, 70, compare), publish),+ mix(760, 665, publish),+ mix(0.6, 1, publish),+ );+ show(right, compare);+ move(right, 590 + (1 - compare) * 420, 665, 1);+ show($(".work-pointer"), 0);+ $(".post-film").style.transform = "translateY(" + -meta * 100 + "%)";+ $(".post-water").style.transform = "translateY(" + (1 - meta) * 100 + "%)";+ show($(".post-water"), meta);+ $(".post-clone").style.transform = "translateY(" + -guess * 100 + "%)";+ $(".post-reference").style.transform =+ "translateY(" + (1 - guess) * 100 + "%)";+ show($(".post-reference"), guess);+ show($(".phone-question"), guess);+ show($(".phone-brand"), meta);+ $(".phone-brand").style.transform =+ "scale(" ++ (1 + 0.12 * Math.sin(clamp((f - b.brand) / 17) * Math.PI)) ++ ")";+ const growth = ease((f - b.upload) / 40);+ $$(".heart-total").forEach(+ (el) =>+ (el.textContent = Math.floor(120 + growth * 89880).toLocaleString(+ "en-US",+ )),+ );+ $$(".comment-total").forEach(+ (el) =>+ (el.textContent = Math.floor(24 + growth * 2310).toLocaleString(+ "en-US",+ )),+ );+ $$(".share-total").forEach(+ (el) =>+ (el.textContent = Math.floor(18 + growth * 8740).toLocaleString(+ "en-US",+ )),+ );+ show($(".floating-hearts"), publish * (1 - compare));+ $$(".floating-hearts i").forEach((el, i) => {+ const q = ((Math.max(0, f - b.upload) + i * 6) % 43) / 43;+ el.style.transform =+ "translate(" ++ -20 * Math.sin(q * 6 + i) ++ "px," ++ (550 - q * 390) ++ "px) scale(" ++ (0.5 + 0.7 * Math.sin(q * Math.PI)) ++ ")";+ show(el, Math.sin(q * Math.PI));+ });+};`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/delivery/index.js b/examples/complex-explainer/packages/web-scenes/src/scenes/delivery/index.jsnew file mode 100644index 00000000..b840a604--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/delivery/index.js@@ -0,0 +1,62 @@+import { css } from "./styles.js";+import { animation } from "./animation.js";+import { scene } from "../../shared/scene.js";+import { pointer, workCss, workSetup } from "../../shared/workshop-language.js";+import { studioBar, inspector, miniTimeline, studioCss } from "../../shared/studio-art.js";+import { hypitSymbol } from "../../shared/brand-marks.js";+const social = () =>+ `<div class="phone-social"><div class="avatar-dot">${hypitSymbol}</div><b>♥<small class="heart-total">120</small></b><b>▣<small class="comment-total">24</small></b><b>➦<small class="share-total">18</small></b></div>`;+export function renderDeliveryWorkshop(t, c, w, font, o, events, m) {+ const b = Object.fromEntries(events.map((e) => [e.name, e.at.frame - w.span.startFrame])),+ end = w.span.endFrameExclusive - w.span.startFrame;+ const entries = {+ preview: { media: m.film, start: 0, end: b.upload + 20 },+ phoneFilm: { media: m.film, start: 0, end, holdLast: true },+ phoneClone: { media: m.clone, start: b.compare, end, holdLast: true },+ ourWater: { media: m.water, start: b.meta, end, holdLast: true },+ theirWater: { image: m.reference },+ host: { image: m.host },+ thumb1: { image: m.thumb1 },+ thumb2: { image: m.thumb2 },+ thumb3: { image: m.thumb3 },+ };+ const html = `+<div class="work-ground"></div+><div class="delivery-studio hs-window"+ >${studioBar()}<div class="delivery-assets hs-library"+ ><div class="hs-tab">Results ▦</div><div class="asset-grid">${["host", "thumb1", "thumb2", "thumb3"].map((n, i) => `<div class="asset-thumb asset-${i}"><div class="asset-picture">{{${n}}}</div><div class="pixel-loading">${Array.from({ length: 9 }, (_, j) => `<i style="--j:${j}"></i>`).join("")}</div><div class="asset-progress"><i></i></div><span>${["HOST", "Hypit", "Creatify", "Higgsfield"][i]}</span></div>`).join("")}</div></div+ ><div class="hs-preview-label hs-tab">Preview</div+ ><div class="hs-preview-matte"></div>${inspector()}<div class="studio-film">{{preview}}</div+ >${miniTimeline()}</div+><div class="phone phone-left"+ ><div class="phone-camera"></div+ ><div class="phone-screen"+ ><div class="phone-post post-film">{{phoneFilm}}</div+ ><div class="phone-post post-water">{{ourWater}}</div+ ><div class="phone-brand">${hypitSymbol}<b>Hypit</b></div+ >${social()}<div class="phone-bottom">@hypit ♫ original sound</div+ ><div class="floating-hearts">${Array.from({ length: 8 }, () => "<i>♥</i>").join("")}</div></div+ ><div class="phone-home"></div></div+><div class="phone phone-right"+ ><div class="phone-camera"></div+ ><div class="phone-screen"+ ><div class="phone-post post-clone">{{phoneClone}}</div+ ><div class="phone-post post-reference">{{theirWater}}</div>${social()}<div+ class="phone-bottom"+ >For You Following</div+ ><div class="phone-question">?</div></div+ ><div class="phone-home"></div></div+>${pointer}`;+ return scene(+ t,+ c,+ w,+ font,+ o,+ html,+ workCss + studioCss + css,+ workSetup + animation,+ events,+ entries,+ );+}diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/delivery/styles.js b/examples/complex-explainer/packages/web-scenes/src/scenes/delivery/styles.jsnew file mode 100644index 00000000..f0b872c5--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/delivery/styles.js@@ -0,0 +1,258 @@+// This scene owns its fixed design. External events arrive as projected frames.+export const css = `+.delivery-studio {+ top: 670px;+ height: 750px;+ transform-origin: 50% 50%;+}+.asset-grid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 20px 12px;+ padding: 24px 12px;+}+.asset-thumb {+ height: 170px;+ position: relative;+ text-align: center;+}+.asset-picture {+ height: 125px;+}+.asset-picture img {+ height: 100% !important;+ width: 100% !important;+ object-fit: contain !important;+}+.asset-thumb > span {+ display: block;+ font: 15px monospace;+ margin-top: 10px;+}+.pixel-loading {+ position: absolute;+ top: 29px;+ left: 28px;+ display: grid;+ grid-template-columns: repeat(3, 12px);+ gap: 7px;+}+.pixel-loading i {+ width: 12px;+ height: 12px;+ background: #d084b6;+}+.asset-progress {+ height: 5px;+ margin: 6px 8px;+ background: #e1cad9;+}+.asset-progress i {+ height: 100%;+ display: block;+ background: #b478a5;+}+.studio-film {+ position: absolute;+ left: 391px;+ top: 90px;+ width: 252px;+ height: 448px;+ overflow: hidden;+ border: 3px solid #95708b;+}+.studio-film > * {+ width: 100% !important;+ height: 100% !important;+ object-fit: cover !important;+}+.phone {+ position: absolute;+ left: 0;+ top: 0;+ width: 420px;+ height: 875px;+ background: linear-gradient(+ 115deg,+ #e9e5e7 0%,+ #a9a4ab 18%,+ #ddd9df 48%,+ #8a858e 80%,+ #ddd8df 100%+ );+ border: 2px solid #77717b;+ border-radius: 65px;+ box-shadow:+ inset 0 0 0 3px #eeeaf0,+ inset 0 0 0 8px #171619,+ 10px 15px 0 #58395424,+ 0 18px 35px #38253526;+ transform-origin: top left;+ overflow: visible;+ box-sizing: border-box;+}+.phone-camera {+ position: absolute;+ top: 26px;+ left: 150px;+ width: 120px;+ height: 33px;+ background: #070709;+ border-radius: 22px;+ z-index: 12;+ box-shadow: inset 0 1px 1px #ffffff13;+}+.phone-camera:after {+ content: "";+ position: absolute;+ right: 10px;+ top: 10px;+ width: 12px;+ height: 12px;+ border-radius: 50%;+ background: radial-gradient(+ circle at 40% 35%,+ #24374d,+ #0b1020 45%,+ #09090c 70%+ );+ border: 1px solid #1d1c25;+}+.phone:before,+.phone:after {+ content: "";+ position: absolute;+ width: 4px;+ background: linear-gradient(90deg, #8c8791, #dcd8df, #8c8791);+ border-radius: 2px;+}+.phone:before {+ left: -5px;+ top: 160px;+ height: 57px;+ box-shadow: 0 73px #aaa4ad;+}+.phone:after {+ right: -5px;+ top: 208px;+ height: 95px;+}+.phone-screen {+ position: absolute;+ left: 10px;+ right: 10px;+ top: 10px;+ bottom: 10px;+ border-radius: 54px;+ background: #18121b;+ overflow: hidden;+}+.phone-post {+ position: absolute;+ inset: 0;+}+.phone-post video,+.phone-post img {+ position: absolute;+ inset: 0;+ width: 100% !important;+ height: 100% !important;+ object-fit: cover !important;+ object-position: center top !important;+}+.phone-home {+ position: absolute;+ bottom: 23px;+ left: 140px;+ width: 140px;+ height: 5px;+ background: #fffafc;+ border-radius: 4px;+ z-index: 12;+ box-shadow: 0 1px 3px #0005;+}+.phone-social {+ position: absolute;+ right: 13px;+ bottom: 62px;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 19px;+ color: #fff8f8;+ text-align: center;+ filter: drop-shadow(2px 3px #382535);+ z-index: 5;+}+.phone-social > b {+ font: 39px sans-serif;+ line-height: 1;+}+.phone-social small {+ display: block;+ font: 17px monospace;+ margin-top: 5px;+}+.avatar-dot {+ border: 2px solid #fff;+ width: 40px;+ height: 40px;+ border-radius: 50%;+ padding: 6px;+ background: #fff4fa;+}+.avatar-dot svg {+ width: 100%;+ height: 100%;+}+.phone-bottom {+ position: absolute;+ bottom: 39px;+ left: 12px;+ font: 15px monospace;+ color: #fff;+ text-shadow: 2px 2px #382535;+ z-index: 5;+}+.phone-brand {+ position: absolute;+ left: 14px;+ top: 61px;+ height: 42px;+ background: #ffdf99;+ border: 2px solid #774e56;+ padding: 5px 12px;+ display: flex;+ align-items: center;+ gap: 8px;+ color: #503740;+ font: 22px monospace;+ z-index: 4;+}+.phone-brand svg {+ width: 30px;+ height: 25px;+}+.floating-hearts {+ position: absolute;+ inset: 0;+ pointer-events: none;+ z-index: 4;+}+.floating-hearts i {+ position: absolute;+ right: 35px;+ top: 0;+ font: 34px sans-serif;+ color: #ff77ac;+ text-shadow: 2px 3px #824663;+}+.phone-question {+ position: absolute;+ left: 165px;+ top: 145px;+ color: #fff0cf;+ font: bold 85px monospace;+ text-shadow: 5px 6px #614953;+}+`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/animation.js b/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/animation.jsnew file mode 100644index 00000000..83d31ee5--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/animation.js@@ -0,0 +1,355 @@+export const road_animation = `const single = new Map(),+ multiple = new Map();+const $ = (s) => {+ if (!single.has(s)) single.set(s, root.querySelector(s));+ return single.get(s);+};+const $$ = (s) => {+ if (!multiple.has(s)) multiple.set(s, [...root.querySelectorAll(s)]);+ return multiple.get(s);+};+const tech = $(".technical"),+ ctx = $(".field").getContext("2d"),+ routes = $(".routes"),+ cards = $$(".route"),+ heading = $(".road-heading"),+ editor = $(".editor"),+ timeline = $(".timeline"),+ folder = $(".folder"),+ pointer = $(".pointer"),+ generated = $(".generated"),+ sample = $(".sample");+const diamonds = $$(".diamond");+const lerp = (a, b, p) => a + (b - a) * p,+ smooth = (p) => {+ p = clamp(p);+ return p * p * (3 - 2 * p);+ },+ out = (p) => 1 - Math.pow(1 - clamp(p), 3),+ pop = (p) => {+ p = clamp(p);+ return 1 + 2.70158 * Math.pow(p - 1, 3) + 1.70158 * Math.pow(p - 1, 2);+ },+ visible = (el, a) => {+ el.style.opacity = String(clamp(a));+ el.style.visibility = a > 0 ? "inherit" : "hidden";+ };+const paintField = (f) => {+ ctx.fillStyle = data.palette.paper;+ ctx.fillRect(0, 0, 135, 240);+ ctx.fillStyle = "#f8d3e3";+ for (let y = 2; y < 240; y += 8)+ for (let x = 2; x < 135; x += 8) ctx.fillRect(x, y, 1, 1);+ const cross = (x, y, c) => {+ ctx.fillStyle = c;+ ctx.fillRect(x + 1, y, 1, 5);+ ctx.fillRect(x - 1, y + 2, 5, 1);+ };+ cross(16, 76, "#f591bd");+ cross(119, 183, "#c7afe5");+ cross(23, 207, "#b9d7c6");+};+const travel = (f, a, z, x0, y0, x1, y1, arc = 0) => {+ const p = smooth((f - a) / Math.max(1, z - a));+ return [lerp(x0, x1, p), lerp(y0, y1, p) - Math.sin(p * Math.PI) * arc];+};+paintField(0);+return (frame) => {+ const f = frame,+ b = data.beats;+ visible(tech, out((f - b.overview) / 12));+ visible(+ $(".homepage"),+ out((f - b.half) / 10) * (1 - out((f - b.overview) / 10)),+ );+ $(".homepage").style.transform =+ "translateY(" + (1 - out((f - b.half) / 14)) * 180 + "px)";+ const enter = out((f - b.overview) / 16),+ dock = smooth((f - b.editor) / 19),+ rscale = lerp(1, 0.5, dock);+ visible(routes, enter);+ routes.style.transform =+ "translateY(" + lerp(0, 400, dock) + "px) scale(" + rscale + ")";+ cards.forEach((el, i) => {+ const reveal = out((f - b.overview - i * 4) / 14),+ yaw = (i === 0 ? 18 : -18) + Math.sin(f * 0.01 + i) * 0.6;+ el.style.transform =+ "translateX(" ++ (i === 0 ? -1 : 1) * (1 - reveal) * 180 ++ "px) rotateY(" ++ yaw ++ "deg) translateZ(" ++ Math.sin(f * 0.02 + i) * 8 ++ "px) scale(" + (1 + .105 * Math.pow(Math.max(0, Math.sin((f-b.overview)/30*5-i*Math.PI)), 2) * (1-dock) * reveal) + ")";+ el.style.opacity = String(reveal * (i === 1 ? 1 - dock * 0.04 : 1));+ });+ const sweepAge=Math.max(0,f-b.editor-22)%141,sweepQ=sweepAge/24;+ const sweep=$('.selection-sweep');sweep.style.opacity=String(dock*(sweepAge<24?.46*Math.sin(sweepQ*Math.PI):0));sweep.style.transform='translateX('+(-130+sweepQ*680)+'px)';+ const mix=(a,z,p)=>'rgb('+a.map((v,i)=>Math.round(lerp(v,z[i],p))).join(',')+')';+ cards[0].querySelector('.route-face').style.background='linear-gradient(145deg,'+mix([255,190,218],[255,126,185],dock)+','+mix([245,139,190],[232,61,137],dock)+')';+ cards[1].querySelector('.route-face').style.background='linear-gradient(145deg,#d9c5fc,#b8a0e5)';+ visible(heading, enter * (1 - out((f - b.editor) / 9)));+ const demoOn = out((f - b.operate) / 12),+ icons = out((f - b.capcut) / 6) * (1 - out((f - b.assets) / 9)),+ assets = out((f - b.assets) / 10) * (1 - out((f - b.drag + 7) / 17)),+ keyMode = out((f - b.keys) / 10) * (1 - out((f - b.tokens) / 8));+ const editorOn = demoOn * (1 - out((f - b.number) / 7)) + keyMode;+ visible(editor, editorOn);+ const ordinary = 1 - keyMode,+ zoomCanvas = out((f - b.place) / 12) * (1 - out((f - b.number) / 7));+ editor.style.transform =+ "translateY(" ++ ((1 - demoOn) * 80 - zoomCanvas * 35) ++ "px) rotateX(" ++ ordinary * (1 - out((f - b.drag) / 12)) * 7 ++ "deg) rotateY(" ++ -ordinary * (1 - out((f - b.drag) / 12)) * 5 ++ "deg) scale(" ++ (1 + zoomCanvas * 0.1) ++ ")";+ editor.style.transformOrigin = "50% " + (zoomCanvas ? "28%" : "50%");+ visible($(".editor-top"), 1);+ visible($(".editor-bar"), 1);+ timeline.style.transform = "none";+ visible($(".editor-veil"), icons * 0.87 + assets * 0.7);+ visible($(".brands"), icons);+ ["capcut", "premiere", "resolve"].forEach((n) => {+ const el = $(".brand." + n),+ p = pop((f - b[n]) / 9),+ group = out((f - b.same) / 13);+ visible(el, out((f - b[n]) / 5));+ el.style.transform =+ "translateY(" ++ ((1 - out((f - b[n]) / 10)) * 90 - group * 20) ++ "px) rotateY(" ++ (1 - out((f - b[n]) / 10)) * -30 ++ "deg) scale(" ++ Math.max(0.05, p) * (1 + group * 0.14) ++ ")";+ });+ visible($(".brand-equality"), out((f - b.same) / 9));+ visible(folder, assets);+ folder.style.transform =+ "translateY(" ++ (1 - out((f - b.assets) / 10)) * 90 ++ "px) rotateX(" ++ lerp(18, 3, out((f - b.assets) / 15)) ++ "deg)";+ $$(".asset").forEach((el, i) => {+ const p = pop((f - b.assets - i * 3) / 9);+ visible(el, out((f - b.assets - i * 3) / 5));+ el.style.transform =+ "translateY(" ++ (1 - out((f - b.assets - i * 3) / 9)) * 55 ++ "px) scale(" ++ Math.max(0.05, p) ++ ")";+ });+ const dragged = out((f - b.drag) / 25);+ $$(".clip").forEach((el, i) => {+ const p = f < b.assets ? 1 : out((f - b.drag - i * 6 - 16) / 5);+ visible(el, p);+ el.style.transform = "scaleX(" + Math.max(0.01, p) + ")";+ });+ $$(".picture").forEach((el, i) => {+ const p =+ f < b.assets ? (i === 0 ? 1 : 0) : out((f - b.drag - i * 6 - 14) / 7);+ visible(el, p);+ el.style.filter =+ f >= b.fail && f < b.number && i === 1+ ? "drop-shadow(0 0 12px #e83f5f)"+ : "";+ });+ for (let i = 0; i < 2; i++) {+ const el = $(".d" + i),+ a = b.drag + i * 16,+ z = a + 19,+ q = clamp((f - a) / 19),+ pos = travel(f, a, z, 150 + i * 190, 175, 95 + i * 185, 412 + i * 50, 90);+ visible(el, f >= a && f < z ? 1 : 0);+ el.style.left = pos[0] + "px";+ el.style.top = pos[1] + "px";+ el.style.transform =+ "scale(" ++ lerp(1, 0.4, q) ++ ") rotate(" ++ Math.sin(q * Math.PI) * -8 ++ "deg)";+ }+ const failed = clamp((f - b.fail) / Math.max(1, b.number - b.fail)),+ path = $(".failed-path");+ visible(path, 0);+ const release = 0.49,+ pull =+ failed < release+ ? smooth(failed / release)+ : Math.exp((-7 * (failed - release)) / (1 - release)) *+ Math.cos((11 * (failed - release)) / (1 - release));+ const dx = 195 * pull,+ dy = -65 * pull,+ grab = $(".p1");+ grab.style.transform =+ "translate(" ++ dx ++ "px," ++ dy ++ "px) rotate(" ++ (-7 + pull * 13) ++ "deg) scale(" ++ (1 + Math.abs(pull) * 0.055) ++ ")";+ grab.style.outline = failed > 0 && failed < 1 ? "3px solid #ffbb91" : "none";+ grab.style.boxShadow =+ failed >= release && failed < 0.72+ ? "7px 7px 0 #ed6554"+ : "5px 5px 0 #251921";+ const examples = out((f - b.number) / 7) * (1 - out((f - b.keys) / 7));+ visible($(".motion-examples"), examples);+ $(".number-example>b").style.transform =+ "scale(" + Math.max(0.01, pop((f - b.number) / 11)) + ")";+ const ip = pop((f - b.image) / 22), flightPath = out((f - b.image) / 18);+ visible($(".image-example"), out((f - b.image) / 5));+ $(".flying-logo").style.transform =+ "translate(" ++ -330 * (1 - ip) ++ "px," ++ (170 * (1 - flightPath) - Math.sin(flightPath * Math.PI) * 85) ++ "px) rotate(" ++ -25 * (1 - ip) ++ "deg) scale(" ++ (0.6 + 0.4 * ip) ++ ")";+ const arrival=clamp((f-b.image-9)/24);+ $(".logo-burst").style.opacity=String(Math.sin(arrival*Math.PI));+ $(".logo-burst").style.transform="scale("+(.78+out(arrival)*.4)+")";+ visible(+ $(".pulse-ring"),+ Math.sin(clamp((f - b.number) / 18) * Math.PI) * 0.6,+ );+ $(".pulse-ring").style.transform =+ "scale(" + (1 + clamp((f - b.number) / 18) * 0.8) + ")";+ visible($(".keys"), keyMode);+ visible($(".key-label"), keyMode);+ const keyProgress = clamp((f - b.keys) / Math.max(1, b.tokens - b.keys - 6));+ $$(".diamond").forEach((el, i) => {+ const p = out((keyProgress * 25 - i - 0.7) / 0.3);+ visible(el, p);+ el.style.transform = "scale(" + (0.6 + 0.4 * p) + ")";+ });+ const cost = out((f - b.tokens) / 6) * (1 - out((f - b.generated) / 7));+ visible($(".terminal-cost"), cost);+ const cp = clamp((f - b.tokens) / Math.max(1, b.generated - b.tokens));+ const end = 1100 + Math.floor(cp * (data.code.length - 1100)),+ pre = $(".terminal-cost pre");+ paintTerminal(pre, data.code, end);+ $(".token-meter b").textContent = Math.floor(+ 248630 * Math.pow(cp, 1.6),+ ).toLocaleString("en-US");+ visible(generated, out((f - b.generated) / 9)*clamp((data.count-f)/8));+ const g = out((f - b.generated) / 14),+ focus = smooth((f - b.unstable) / 12),+ fan = out((f - b.styles) / 9);+ sample.style.transform =+ "translateY(" ++ (1 - g) * 80 ++ "px) scale(" ++ (1.5 - 0.5 * g) * (1 + 0.28 * focus) * (1 - 0.36 * fan) ++ ")";+ sample.style.filter = "brightness(" + (1 - fan * 0.35) + ")";+ visible($(".sample-label"), 1 - focus);+ $$(".variant").forEach((el, i) => {+ const prep = out((f - b.unstable) / 8),+ p = out((f - b.styles - i * 2) / 8);+ visible(el, prep * 0.09 + p * 0.91);+ el.style.transform =+ "rotateY(" ++ (i === 1 ? -1 : 1) * (1 - p) * 42 ++ "deg) translateZ(" ++ p * 30 ++ "px) scale(" ++ (0.82 + 0.18 * p) ++ ")";+ });+ $$(".connectors path").forEach((el, i) => {+ const p = out((f - b.styles - i * 2) / 7);+ el.style.strokeDashoffset = String(500 * (1 - p));+ el.style.opacity = String(p);+ });+ visible($(".lock"), out((f - b.styles) / 6));+ let point = [460, 440],+ click = 0,+ show = 0;+ if (f >= b.operate && f < b.capcut) {+ const t = f - b.operate,+ k = Math.floor(t / 15),+ p = clamp((t % 15) / 10),+ targets = [+ [130, 420],+ [490, 470],+ [330, 590],+ [790, 425],+ [620, 490],+ ],+ a = targets[k % 5],+ z = targets[(k + 1) % 5];+ point = travel(p, 0, 1, ...a, ...z, 30);+ click = Math.max(0, 1 - (t % 15) / 5);+ show = 1;+ } else if (f >= b.drag && f < b.place) {+ const i = f - b.drag < 16 ? 0 : 1,+ a = b.drag + i * 16;+ point = travel(+ f,+ a,+ a + 19,+ 160 + i * 190,+ 185,+ 110 + i * 185,+ 430 + i * 50,+ 90,+ );+ show = 1;+ click = f > a + 17 ? 1 - clamp((f - a - 17) / 6) : 0;+ } else if (f >= b.place && f < b.fail) {+ point = travel(f, b.place, b.fail, 360, 180, 530, 155, 25);+ show = 1;+ } else if (f >= b.fail && f < b.number) {+ const sc = 1 + zoomCanvas * 0.1;+ point = [+ 510 + (260 + dx - 510) * sc,+ 174 + (140 + dy - 174) * sc - zoomCanvas * 35,+ ];+ show = 1;+ click = failed < 0.49 ? 1 : Math.max(0, 1 - (failed - 0.49) * 6);+ } else if (f >= b.keys && f < b.tokens) {+ const n = Math.min(24, Math.floor(keyProgress * 25)),+ phase = (keyProgress * 25) % 1,+ prev = Math.max(0, n - 1),+ dest = (i) => [+ timeline.offsetLeft + diamonds[i].offsetLeft,+ timeline.offsetTop + diamonds[i].offsetTop,+ ];+ const a = dest(prev),+ z = dest(n),+ q = smooth(clamp(phase / 0.7));+ point = [+ lerp(a[0], z[0], q),+ lerp(a[1], z[1], q) - Math.sin(q * Math.PI) * 15,+ ];+ show = 1;+ click = phase > 0.7 ? Math.sin(((phase - 0.7) / 0.3) * Math.PI) : 0;+ }+ pointer.style.transform =+ "translate(" ++ point[0] ++ "px," ++ point[1] ++ "px) scale(" ++ (1 - click * 0.1) ++ ")";+ visible(pointer, show);+ visible($(".click-ring"), click * 0.8);+ $(".click-ring").style.transform = "scale(" + (1 + (1 - click) * 1.3) + ")";+ $(".playhead").style.left = 65 + ((f * 0.9) % 850) + "px";+};+`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/editor-styles.js b/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/editor-styles.jsnew file mode 100644index 00000000..8b55a652--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/editor-styles.js@@ -0,0 +1,428 @@+// Final pink treatment; layout and paint for the editor part of the scene.+export const editorStyles = `.editor {+ position: absolute;+ inset: 0;+ transform-origin: center center;+ background: #fff7fb;+ border: 4px solid var(--ink);+ border-radius: 12px;+ box-shadow: 10px 12px 0 var(--ink);+ overflow: hidden;+}+.editor-bar {+ height: 42px;+ display: flex;+ gap: 9px;+ align-items: center;+ padding: 0 18px;+ background: var(--pinkSoft);+ border-bottom: 3px solid var(--ink);+}+.editor-bar i {+ background: #e46876;+ border-radius: 2px;+ border: 1px solid var(--ink);+ width: 12px;+ height: 12px;+}+.editor-bar i:nth-child(2) {+ background: #e8bd73;+}+.editor-bar i:nth-child(3) {+ background: #71bf98;+}+.editor-bar b {+ margin-left: 20px;+ font: 16px monospace;+ letter-spacing: 3px;+ color: var(--ink);+ font-weight: 700;+}+.editor-bar span {+ margin-left: auto;+ font: 17px monospace;+ color: var(--ink);+ font-weight: 700;+}+.editor-top {+ display: flex;+ padding: 12px;+ gap: 12px;+ height: 310px;+}+.library {+ width: 150px;+ padding: 12px;+ background: #fce5ef;+ color: #402b40;+ border: 2px solid #edc5d8;+}+.library small {+ font: 12px monospace;+ letter-spacing: 2px;+ color: #574158;+ font-weight: 700;+}+.properties small {+ font: 12px monospace;+ letter-spacing: 2px;+ color: #574158;+ font-weight: 700;+}+.library-grid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 8px;+ margin-top: 12px;+}+.library-grid i {+ display: grid;+ place-items: center;+ font: 25px monospace;+ color: #b2d7ea;+ height: 76px;+ background: #fff9fc;+ border: 2px solid var(--ink);+ border-radius: 5px;+ box-shadow: 3px 3px 0 var(--ink);+ overflow: hidden;+}+.preview {+ position: relative;+ width: 620px;+ overflow: hidden;+ background: #f4ecf3;+}+.preview-grid {+ position: absolute;+ inset: 0;+ background: repeating-conic-gradient(#ddcfdf60 0 25%, transparent 0 50%);+ background-size: 24px 24px;+}+.picture {+ position: absolute;+ overflow: hidden;+ border: 3px solid var(--ink);+ box-shadow: 5px 5px 0 var(--ink);+}+.picture > * {+ object-fit: contain !important;+}+.p0 {+ left: 204px;+ top: 12px;+ width: 140px;+ height: 248px;+}+.p1 {+ left: 22px;+ top: 58px;+ width: 174px;+ height: 121px;+ transform: rotate(-7deg);+}+.p2 {+ right: 56px;+ top: 32px;+ width: 112px;+ height: 199px;+ transform: rotate(7deg);+}+.preview-label {+ position: absolute;+ left: 15px;+ bottom: 10px;+ font: 11px monospace;+ letter-spacing: 3px;+ color: #795870;+}+.properties {+ width: 160px;+ padding: 12px;+ font: 12px monospace;+ background: #fce5ef;+ color: #402b40;+ border: 2px solid #edc5d8;+}+.properties p {+ display: flex;+ justify-content: space-between;+ margin: 12px 0;+}+.properties i {+ font-style: normal;+ padding: 4px 8px;+ background: #fff9fc;+ border: 1px solid #ccabc1;+ min-width: 45px;+ text-align: center;+}+.properties > div {+ height: 45px;+ border-top: 1px solid #56677944;+ margin-top: 25px;+}+.timeline {+ position: absolute;+ left: 16px;+ right: 16px;+ bottom: 17px;+ height: 235px;+ transform-origin: center center;+ background: #fff7fb;+ border: 2px solid var(--ink);+}+.ticks {+ height: 31px;+ display: flex;+ justify-content: space-around;+ font: 12px monospace;+ border-bottom: 1px solid #8395a93d;+ align-items: center;+ color: #684b64;+ border-bottom-color: #d7b8cc;+}+.lane-lines {+ position: absolute;+ inset: 32px 0 0;+ background: repeating-linear-gradient(+ 180deg,+ transparent 0 53px,+ #d8bfd23d 53px 54px+ );+}+.clip {+ position: absolute;+ height: 44px;+ overflow: hidden;+ display: flex;+ align-items: center;+ gap: 6px;+ background: #f8a0c8;+ border: 2px solid var(--ink);+ border-radius: 4px;+}+.clip > div {+ height: 100%;+ width: 45px;+}+.clip > div > * {+ object-fit: contain !important;+}+.clip b {+ font: 11px monospace;+ color: var(--ink);+ font-weight: bold;+}+.clip-1 {+ background: #d0b6f2;+ border-color: var(--ink);+}+.clip-3 {+ background: #d0b6f2;+ border-color: var(--ink);+}+.audio {+ position: absolute;+ left: 65px;+ right: 25px;+ top: 153px;+ height: 34px;+ display: flex;+ align-items: center;+ justify-content: space-around;+ background: #b2dfc6;+ border: 2px solid var(--ink);+}+.audio i {+ display: block;+ width: 4px;+ background: #537e64;+}+.caption-blocks {+ position: absolute;+ left: 70px;+ top: 198px;+ display: flex;+ gap: 9px;+}+.caption-blocks i {+ display: block;+ width: 200px;+ padding: 3px 8px;+ font: 13px sans-serif;+ font-style: normal;+ background: #f4dca8;+ color: #483627;+ border-radius: 2px;+ border: 1px solid #715b44;+}+.playhead {+ position: absolute;+ top: 0;+ bottom: 0;+ width: 2px;+ background: #b92768;+ box-shadow: none;+}+.playhead:before {+ content: "";+ position: absolute;+ left: -5px;+ top: 0;+ border-left: 6px solid transparent;+ border-right: 6px solid transparent;+ border-top: 9px solid #f0d8aa;+ border-top-color: #b92768;+}+.editor-veil {+ position: absolute;+ inset: 0;+ background: repeating-conic-gradient(#000a 0 25%, #0006 0 50%);+ background-size: 5px 5px;+ opacity: 0;+}+.failed-path {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ opacity: 0;+ filter: drop-shadow(0 0 6px #e83f5f);+}+.keys {+ position: absolute;+ inset: 0;+ opacity: 0;+}+.diamond {+ position: absolute;+ clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);+ opacity: 0;+ background: #f5529a;+ filter: drop-shadow(1px 1px 0 var(--ink));+ width: 14px;+ height: 25px;+}+.key-label {+ position: absolute;+ top: 15px;+ left: 0;+ width: 100%;+ text-align: center;+ opacity: 0;+ display: none;+}+.key-label small {+ display: block;+ font: 18px monospace;+ letter-spacing: 6px;+ color: #c7b5ae;+ margin-bottom: 15px;+}+.key-label b {+ font-size: 68px;+ color: #ff869c;+ text-shadow: 0 0 24px #df4c7977;+}+.pointer {+ position: absolute;+ left: 0;+ top: 0;+ width: 70px;+ height: 90px;+ z-index: 20;+ opacity: 0;+ transform-origin: 8px 6px;+ filter: drop-shadow(4px 5px 0 var(--ink));+}+.pointer > svg {+ width: 70px;+ height: 90px;+}+.pointer-badge {+ position: absolute;+ left: 45px;+ top: 65px;+ width: 44px;+ height: 44px;+ border-radius: 50%;+ overflow: hidden;+ background: #f5f8fb;+ border: 3px solid var(--ink);+ box-shadow: 3px 3px 0 var(--ink);+}+.click-ring {+ position: absolute;+ left: -17px;+ top: -17px;+ width: 50px;+ height: 50px;+ border: 2px solid #89e9f4;+ border-radius: 50%;+ opacity: 0;+ border-color: #ed438f;+}+.library-grid i > * {+ object-fit: contain !important;+}+.library-wave {+ height: 39px;+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-top: 17px;+ background: var(--mint);+ border: 2px solid var(--ink);+ padding: 3px;+}+.library-wave i {+ width: 3px;+ background: #375442;+}+.properties > div.control-stack {+ height: auto;+ border: 0;+ margin-top: 18px;+ display: grid;+ gap: 14px;+}+.control-stack > b {+ display: block;+ height: 5px;+ background: #c4a8bb;+ position: relative;+}+.control-stack i {+ position: absolute;+ top: -5px;+ left: 35%;+ height: 15px;+ width: 12px;+ min-width: 0;+ padding: 0;+ background: var(--pink);+ border: 2px solid var(--ink);+ border-radius: 2px;+}+.control-stack > b:nth-child(2) i {+ left: 65%;+}+.control-stack > b:nth-child(3) i {+ left: 45%;+}+.properties > div.align-tools {+ height: 32px;+ display: flex;+ gap: 8px;+ margin-top: 23px;+ border: 0;+}+.align-tools b {+ flex: 1;+ border: 2px solid var(--ink);+ background: #fff9fc;+ display: grid;+ place-items: center;+ box-shadow: 2px 2px 0 var(--ink);+}`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/index.js b/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/index.jsnew file mode 100644index 00000000..d54a6d0f--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/index.js@@ -0,0 +1,177 @@+import { routeCardsHtml } from "../../shared/route-cards.js";+import { palette, paletteCss } from "@explainer/visual-language";+import { road_styles } from "./styles.js";+import { road_animation } from "./animation.js";+import { scene } from "../../shared/scene.js";+const arrow = `<svg viewBox="0 0 90 105"><defs><linearGradient id="pointer-metal" x2="1" y2="1"><stop stop-color="#fff"/><stop offset=".5" stop-color="#b6d9ed"/><stop offset="1" stop-color="#53677d"/></linearGradient></defs><path d="M8 6L77 53L47 59L34 89L8 6Z" fill="url(#pointer-metal)" stroke="#f9feff" stroke-width="3"/><path d="M15 17L58 50L39 52L33 70Z" fill="#152c3d"/></svg>`;+const wave = (n = 72) =>+ Array.from(+ { length: n },+ (_, i) =>+ `<i style="height:${10 + Math.abs(Math.sin(i * 1.53) * Math.cos(i * 0.41)) * 30}px"></i>`,+ ).join("");+const ruler = Array.from(+ { length: 21 },+ (_, i) => `<span>${String(i).padStart(2, "0")}</span>`,+).join("");+const codeLines = Array.from(+ { length: 40 },+ (_, i) =>+ `keyframe(${(i * 0.07).toFixed(2)}, { x: ${Math.round(Math.sin(i * 0.2) * 210)}, y: ${Math.round(Math.cos(i * 0.3) * 90)}, scale: ${(1 + i * 0.014).toFixed(3)}, easing: "bezier" });`,+).join("\n");+export function renderRoad(t, c, w, font, o, events, m) {+ const b = Object.fromEntries(events.map((e) => [e.name, e.at.frame - w.span.startFrame])),+ count = w.span.endFrameExclusive - w.span.startFrame;+ const entries = {+ page: { media: m.page, start: b.half, end: b.overview + 12 },+ sample: { media: m.sample, start: b.generated, end: count },+ pointerlogo: { image: m.codex },+ "icon-capcut": { image: m.capcut },+ "icon-premiere": { image: m.premiere },+ "icon-resolve": { image: m.resolve },+ "flying-logo": { image: m.logo },+ };+ // These are the actual shots already used in this film, collected as stills for the editor demonstration.+ const gallery = [+ m.portrait,+ m["thumb-a"],+ m["thumb-b"],+ m["thumb-c"],+ m["thumb-d"],+ m["thumb-e"],+ m["thumb-f"],+ m["thumb-g"],+ ];+ for (let i = 0; i < 4; i++) entries["library" + i] = { image: gallery[[2, 3, 4, 5][i]] };+ for (let i = 0; i < 8; i++) entries["asset" + i] = { image: gallery[i] };+ for (let i = 0; i < 5; i++) entries["strip" + i] = { image: gallery[[0, 2, 3, 4, 6][i]] };+ for (let i = 0; i < 3; i++) entries["canvas" + i] = { image: gallery[[0, 6, 3][i]] };+ for (let i = 0; i < 2; i++) entries["drag" + i] = { image: gallery[[6, 3][i]] };+ const folder = Array.from(+ { length: 8 },+ (_, i) =>+ `<div class="asset" data-i="${i}"><div>{{asset${i}}}</div><small>${["HOST", "RANKING", "PODCAST", "INTERVIEW", "ORIGINAL", "ORIGINAL", "WEBSITE", "CODE"][i]} ${String(i + 1).padStart(2, "0")}</small></div>`,+ ).join("");+ const strips = Array.from(+ { length: 5 },+ (_, i) =>+ `<div class="clip clip-${i}" style="left:${70 + i * 151}px;width:${i % 2 ? 125 : 145}px;top:${i % 2 ? 100 : 45}px"><div>{{strip${i}}}</div><b>${i % 2 ? "VIDEO" : "IMAGE"}</b></div>`,+ ).join("");+ const diamonds = Array.from(+ { length: 25 },+ (_, i) =>+ `<i class="diamond" data-i="${i}" style="left:${65 + (i / 24) ** 1.15 * 850}px;top:${i % 3 === 0 ? 78 : 146}px"></i>`,+ ).join("");+ const variants = `<div class="variant v0"><b>1<span>Hypit</span></b><b>2<span>Creator</span></b><b>3<span>Studio</span></b></div><div class="variant v1"><div class="podiums"><b>2</b><b>1</b><b>3</b></div><strong>Hypit</strong></div><div class="variant v2"><strong>ABC</strong><p>Make it <em>yours.</em></p></div>`;+ const html = `+<div class="technical"+ ><canvas class="field" width="135" height="240"></canvas><div class="weave"></div+ ><div class="horizon"></div+></div>+<div class="homepage">{{page}}</div>+<div class="road-heading"></div>+${routeCardsHtml}+<div class="demo">+ <div class="editor"+ ><div class="editor-bar"><i></i><i></i><i></i><b>main.svml</b><span>00:00:06:12</span></div+ ><div class="editor-top"+ ><div class="library"+ ><small>MEDIA</small+ ><div class="library-grid"+ ><i>{{library0}}</i><i>{{library1}}</i><i>{{library2}}</i><i>{{library3}}</i></div+ ><div class="library-wave"+ ><i style="height: 8px"></i><i style="height: 21px"></i><i style="height: 34px"></i+ ><i style="height: 19px"></i><i style="height: 32px"></i><i style="height: 17px"></i+ ><i style="height: 30px"></i><i style="height: 15px"></i><i style="height: 28px"></i+ ><i style="height: 13px"></i><i style="height: 26px"></i><i style="height: 11px"></i+ ><i style="height: 24px"></i><i style="height: 9px"></i><i style="height: 22px"></i+ ><i style="height: 35px"></i></div></div+ ><div class="preview"+ ><div class="preview-grid"></div><div class="picture p0">{{canvas0}}</div+ ><div class="picture p1">{{canvas1}}</div><div class="picture p2">{{canvas2}}</div+ ><svg class="failed-path" viewBox="0 0 550 250">+ <path+ d="M90 180Q270 10 480 100"+ fill="none"+ stroke="#e83f5f"+ stroke-width="4"+ stroke-dasharray="9 8"+ />+ <path d="M470 82L490 100L466 115" fill="none" stroke="#e83f5f" stroke-width="4" /></svg+ ><div class="preview-label">COMPOSITION</div></div+ ><div class="properties"+ ><small>TRANSFORM</small><p>X <i>540</i></p+ ><p>Y <i>960</i></p+ ><p>Scale <i>100%</i></p+ ><div class="control-stack"+ ><b><i></i></b><b><i></i></b><b><i></i></b></div+ ><div class="align-tools"><b>↤</b><b>↔</b><b>↦</b></div></div+ ></div+ ><div class="timeline"+ ><div class="ticks">${ruler}</div><div class="lane-lines"></div>${strips}<div+ class="audio"+ >${wave()}</div+ ><div class="caption-blocks"><i>剪辑软件</i><i>素材生成</i><i>画布与时间轴</i></div+ ><div class="playhead"></div><div class="keys">${diamonds}</div></div+ ><div class="editor-veil"></div+ ></div>+ <div class="brands"+ ><div class="brand capcut">{{icon-capcut}}</div+ ><div class="brand premiere">{{icon-premiere}}</div+ ><div class="brand resolve">{{icon-resolve}}</div><div class="brand-equality"></div+ ></div>+ <div class="folder"+ ><div class="folder-tab">ASSETS</div+ ><div class="folder-face"+ ><div class="folder-label"></div><div class="assets">${folder}</div></div+ ></div+ >+ <div class="drag-tile d0">{{drag0}}</div><div class="drag-tile d1">{{drag1}}</div>+ <div class="motion-examples"+ ><div class="number-example"+ ><b>Hypit <em>#1</em></b+ ><div class="pulse-ring"></div></div+ ><div class="image-example"+ ><div class="flying-logo">{{flying-logo}}</div+ ><div class="logo-burst" aria-hidden="true"><i></i><i></i><i></i><i></i></div></div+ ></div>+ <div class="key-label"></div>+ <div class="terminal-cost"+ ><div class="terminal-top"><i></i><i></i><i></i><span>motion.js</span></div+ ><pre></pre><div class="token-meter"><small>TOKENS</small><b>0</b><span>↑</span></div></div+ >+ <div class="generated"+ ><div class="sample">{{sample}}</div><div class="sample-label"></div+ ><svg class="connectors" viewBox="0 0 1020 650">+ <path d="M465 245L375 140L240 110" />+ <path d="M555 270L680 225L810 225" />+ <path d="M465 410L370 530L210 530" /></svg+ >${variants}<div class="lock"+ ><svg viewBox="0 0 40 45">+ <path d="M10 20V13a10 10 0 0 1 20 0v7" fill="none" stroke="currentColor" stroke-width="3" />+ <rect+ x="6"+ y="19"+ width="28"+ height="23"+ rx="4"+ fill="#162032"+ stroke="currentColor"+ stroke-width="2"+ />+ <circle cx="20" cy="29" r="3" fill="currentColor" />+ <path d="M20 30v6" stroke="currentColor" stroke-width="2" /></svg></div+ ></div>+ <div class="pointer"+ ><div class="click-ring"></div>${arrow}<div class="pointer-badge"+ >{{pointerlogo}}</div+ ></div+ >+</div>`;+ const css = road_styles;+ return scene(t, c, w, font, o, html, paletteCss + css, roadSetup, events, entries, {+ code: codeLines,+ palette,+ });+}+const roadSetup = road_animation;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/materials-styles.js b/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/materials-styles.jsnew file mode 100644index 00000000..a1a8fa91--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/materials-styles.js@@ -0,0 +1,187 @@+// Final pink treatment; layout and paint for the materials part of the scene.+export const materialsStyles = `.folder {+ position: absolute;+ left: 60px;+ top: 40px;+ width: 900px;+ transform-style: preserve-3d;+ transform-origin: center bottom;+ height: 530px;+}+.folder-tab {+ position: absolute;+ left: 25px;+ top: -22px;+ width: 240px;+ height: 64px;+ padding: 12px 35px;+ font: 22px monospace;+ letter-spacing: 5px;+ background: var(--pink);+ border: 3px solid var(--ink);+ border-bottom: 0;+ border-radius: 8px 12px 0 0;+ color: var(--ink);+ box-shadow: 5px 0 0 var(--ink);+}+.folder-face {+ position: absolute;+ inset: 20px 0 0;+ background: #ffe9f2;+ border: 4px solid var(--ink);+ border-radius: 10px;+ box-shadow: 10px 12px 0 var(--ink);+ padding: 25px 28px;+}+.folder-label {+ align-items: center;+ justify-content: space-between;+ display: none;+}+.folder-label b {+ font-size: 36px;+}+.folder-label small {+ font: 15px monospace;+ color: #9ab0b8;+ letter-spacing: 3px;+}+.assets {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ margin-top: 0;+ gap: 20px;+ height: 100%;+ grid-template-rows: 1fr 1fr;+}+.asset {+ opacity: 0;+ height: auto;+ min-height: 0;+ display: flex;+ flex-direction: column;+}+.asset > div {+ overflow: hidden;+ height: auto;+ flex: 1;+ min-height: 0;+ border-radius: 6px;+ border: 3px solid var(--ink);+ box-shadow: 4px 4px 0 var(--ink);+}+.asset > div > * {+ object-fit: cover !important;+}+.asset small {+ font: 12px monospace;+ letter-spacing: 2px;+ display: block;+ color: #5b3652;+ font-weight: bold;+ margin-top: 10px;+}+.drag-tile {+ position: absolute;+ width: 140px;+ height: 140px;+ overflow: hidden;+ opacity: 0;+ z-index: 6;+ border: 3px solid var(--ink);+ border-radius: 6px;+ box-shadow: 7px 7px 0 var(--ink);+}+.drag-tile > * {+ object-fit: cover !important;+}+.motion-examples {+ position: absolute;+ inset: 70px 0 0;+ display: flex;+ gap: 30px;+}+.number-example {+ position: relative;+ width: 495px;+ height: 390px;+ overflow: hidden;+ background: var(--cream);+ border: 4px solid var(--ink);+ border-radius: 10px;+ box-shadow: 9px 10px 0 var(--ink);+}+.image-example {+ position: relative;+ width: 495px;+ height: 390px;+ overflow: hidden;+ background: var(--cream);+ border: 4px solid var(--ink);+ border-radius: 10px;+ box-shadow: 9px 10px 0 var(--ink);+}+.motion-examples small {+ position: absolute;+ top: 25px;+ left: 30px;+ font: 17px monospace;+ color: #8cbac9;+ letter-spacing: 4px;+ display: none;+}+.number-example > b {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ justify-content: center;+ align-items: center;+ font-size: 64px;+ line-height: 1.1;+ font-family: Menlo, monospace;+ color: var(--ink);+}+.number-example em {+ font-style: normal;+ font-size: 145px;+ color: #f466aa;+ text-shadow: 5px 5px 0 var(--ink);+}+.flying-logo {+ position: absolute;+ left: 78px;+ top: 144px;+ width: 330px;+ height: 101px;+ filter: drop-shadow(4px 5px 0 #f59bca);+}++++.logo-burst {position:absolute;left:62px;top:101px;width:365px;height:188px;pointer-events:none;opacity:0}+.logo-burst i {position:absolute;width:24px;height:24px;border:0 solid var(--pink);filter:drop-shadow(3px 3px 0 var(--ink))}+.logo-burst i:nth-child(1){left:0;top:0;border-left-width:6px;border-top-width:6px}+.logo-burst i:nth-child(2){right:0;top:0;border-right-width:6px;border-top-width:6px;border-color:var(--lilac)}+.logo-burst i:nth-child(3){left:0;bottom:0;border-left-width:6px;border-bottom-width:6px;border-color:var(--lilac)}+.logo-burst i:nth-child(4){right:0;bottom:0;border-right-width:6px;border-bottom-width:6px}+.image-example svg {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+}+.pulse-ring {+ position: absolute;+ left: 125px;+ top: 100px;+ width: 250px;+ height: 250px;+ border: 1px solid #e83f5f;+ border-radius: 50%;+ opacity: 0;+ border-color: #f46bac;+}+.image-example svg path {+ stroke: #f46bac;+}`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/output-styles.js b/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/output-styles.jsnew file mode 100644index 00000000..d9a71f2f--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/output-styles.js@@ -0,0 +1,233 @@+// Final pink treatment; layout and paint for the output part of the scene.+export const outputStyles = `.terminal-top i {+ background: #e46876;+ border-radius: 2px;+ border: 1px solid var(--ink);+ width: 12px;+ height: 12px;+}+.terminal-top i:nth-child(2) {+ background: #e8bd73;+}+.terminal-top i:nth-child(3) {+ background: #71bf98;+}+.terminal-cost {+ position: absolute;+ inset: 0;+ overflow: hidden;+ background: var(--cream);+ border: 4px solid var(--ink);+ border-radius: 12px;+ box-shadow: 10px 12px 0 var(--ink);+}+.terminal-top {+ height: 48px;+ display: flex;+ align-items: center;+ padding: 0 20px;+ gap: 9px;+ background: var(--pinkSoft);+ border-bottom: 3px solid var(--ink);+}+.terminal-top span {+ margin-left: 30px;+ font: 18px monospace;+ letter-spacing: 3px;+ color: var(--ink);+ font-weight: 700;+}+.token-meter {+ position: absolute;+ display: flex;+ gap: 20px;+ bottom: 0;+ left: 0;+ right: 0;+ height: 130px;+ padding: 15px 28px;+ background: var(--pinkSoft);+ border-top: 3px solid var(--ink);+ align-items: center;+}+.token-meter small {+ font: 20px monospace;+ letter-spacing: 5px;+ color: var(--ink);+}+.token-meter b {+ font: bold 98px monospace;+ font-size: 86px;+ color: #e13e8c;+ text-shadow: 2px 3px 0 #fffbfd;+}+.token-meter span {+ font: 72px monospace;+ color: var(--ink);+}+.generated {+ position: absolute;+ inset: 0;+ perspective: 1500px;+}+.sample {+ position: absolute;+ left: 270px;+ top: -30px;+ width: 480px;+ height: 650px;+ border: 5px solid var(--ink);+ border-radius: 10px;+ background: var(--cream);+ box-shadow: 11px 13px 0 var(--ink);+ overflow: hidden;+ transform-origin: 50% 70%;+}+.sample > * {+ object-fit: cover !important;+ object-position: 50% 70% !important;+}+.sample-label {+ position: absolute;+ left: 330px;+ top: 5px;+ font: 15px monospace;+ color: #e6edf5;+ letter-spacing: 3px;+ background: #0008;+ padding: 8px 14px;+ display: none;+}+.variant {+ position: absolute;+ width: 240px;+ height: 215px;+ padding: 16px;+ transform-origin: center center;+ background: #fff7fc;+ border: 4px solid var(--ink);+ border-radius: 10px;+ box-shadow: 7px 8px 0 var(--ink);+}+.v0 {+ left: 0;+ top: 0;+ --accent: #f466aa;+}+.v1 {+ right: 0;+ top: 140px;+ --accent: #c5a3ed;+}+.v2 {+ left: 0;+ bottom: 0;+ --accent: #9fd9b8;+}+.variant small {+ font: 12px monospace;+ letter-spacing: 2px;+ color: var(--accent);+ display: none;+}+.v0 > b {+ display: block;+ font: bold 31px/1.4 monospace;+ color: #df4b95;+}+.v0 b span {+ font: 20px sans-serif;+ margin-left: 15px;+ font-family: monospace;+ color: var(--ink);+}+.podiums {+ display: flex;+ align-items: end;+ height: 105px;+ gap: 10px;+ justify-content: center;+ margin-top: 15px;+}+.podiums b {+ width: 48px;+ height: 65px;+ display: grid;+ place-items: center;+ font: 32px monospace;+ background: #e3d4f8;+ color: var(--ink);+ border: 2px solid var(--ink);+}+.podiums b:nth-child(2) {+ height: 100px;+ background: #bd93e8;+}+.v1 strong {+ font: 21px sans-serif;+ display: block;+ text-align: center;+ margin-top: 8px;+ font-family: monospace;+ color: var(--ink);+}+.v2 strong {+ font: bold 70px sans-serif;+ display: block;+ color: #438368;+ font-family: monospace;+}+.v2 p {+ font: 21px sans-serif;+ margin-top: 15px;+ font-family: monospace;+ color: var(--ink);+}+.v2 em {+ font-style: normal;+ padding: 5px;+ background: #bee7d0;+}+.connectors {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ overflow: visible;+}+.connectors path {+ fill: none;+ stroke-dasharray: 500;+ stroke: var(--ink);+ stroke-width: 4;+ filter: none;+}+.lock svg {+ width: 36px;+ height: 43px;+}+.lock {+ position: absolute;+ left: 475px;+ top: 280px;+ font: 40px monospace;+ opacity: 0;+ text-shadow: none;+ color: #f66dab;+}+.terminal-cost pre {+ font: 22px/1.45 Menlo,+ monospace;+ color: #58405c;+ white-space: pre;+ height: 400px;+ margin: 12px 0 0;+ padding: 8px 24px;+ mask-image: none;+ overflow: hidden;+ border-left: 8px solid var(--pinkSoft);+}+.lock rect {+ fill: #fff4fa;+ stroke: var(--ink);+}`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/stage-styles.js b/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/stage-styles.jsnew file mode 100644index 00000000..7e879cc2--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/stage-styles.js@@ -0,0 +1,128 @@+import { routeCardsCss } from "../../shared/route-cards.js";+// Final pink treatment; layout and paint for the stage part of the scene.+export const stageStyles = `:scope {+ background: transparent !important;+ font-family: Menlo, "Courier New", monospace !important;+ color: var(--ink);+}+.backdrop {+ display: none;+}+.backdrop-wash {+ display: none;+}+.technical {+ position: absolute;+ inset: 0;+ opacity: 0;+ background: var(--paper);+}+.field {+ width: 100%;+ height: 100%;+ image-rendering: pixelated;+ opacity: 1;+}+.weave {+ position: absolute;+ inset: 0;+ background: repeating-conic-gradient(+ from 45deg,+ #0009 0 25%,+ #a6c4d00c 0 50%+ );+ background-size: 6px 6px;+ display: none;+}+.horizon {+ position: absolute;+ inset: 0;+ background: linear-gradient(+ 180deg,+ #02071280,+ transparent 45%,+ #050914dd 87%+ );+ display: none;+}+.homepage {+ position: absolute;+ left: 0;+ top: 922px;+ width: 1080px;+ height: 998px;+ overflow: hidden;+ opacity: 0;+}+.homepage > * {+ object-fit: cover !important;+ object-position: center top !important;+}+.road-heading {+ position: absolute;+ top: 365px;+ left: 300px;+ width: 450px;+ text-align: center;+ opacity: 0;+ display: none;+}+.road-heading small {+ display: block;+ color: #bfd9e2;+ letter-spacing: 8px;+ font: 23px monospace;+ margin-bottom: 20px;+}+.road-heading b {+ font-size: 86px;+ color: #f6e2bf;+ text-shadow: 0 2px 1px #684931,+ 0 0 20px #f2c99166;+}+${routeCardsCss}+.demo {+ position: absolute;+ left: 30px;+ top: 565px;+ width: 1020px;+ height: 620px;+ perspective: 1700px;+ z-index: 10;+}+.brands {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: space-around;+ perspective: 900px;+}+.brand {+ width: 230px;+ height: 230px;+ opacity: 0;+}+.brand > * {+ object-fit: contain !important;+}+.capcut {+ filter: drop-shadow(0 0 5px #e6fcff) drop-shadow(0 0 35px #b5d2eccc);+}+.premiere {+ filter: drop-shadow(0 0 7px #d6bfff) drop-shadow(0 0 40px #9a52fccc);+}+.resolve {+ filter: drop-shadow(0 0 8px #e3e9f2) drop-shadow(0 0 38px #87a9d2aa);+}+.brand-equality {+ position: absolute;+ bottom: 45px;+ width: 100%;+ text-align: center;+ font-size: 53px;+ letter-spacing: 8px;+ color: #e7eef3;+ opacity: 0;+ display: none;+}`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/styles.js b/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/styles.jsnew file mode 100644index 00000000..cb75544e--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/editor-route/styles.js@@ -0,0 +1,6 @@+import { stageStyles } from "./stage-styles.js";+import { editorStyles } from "./editor-styles.js";+import { materialsStyles } from "./materials-styles.js";+import { outputStyles } from "./output-styles.js";++export const road_styles = [stageStyles, editorStyles, materialsStyles, outputStyles].join("\n");diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/introduction/animation.js b/examples/complex-explainer/packages/web-scenes/src/scenes/introduction/animation.jsnew file mode 100644index 00000000..7664a56f--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/introduction/animation.js@@ -0,0 +1,97 @@+export const intro_animation = `const phases = [...root.querySelectorAll("[data-p]")],+ h = root.querySelector(".heading b"),+ sub = root.querySelector(".heading small");+return (frame) => {+ paintBackdrop(frame);+ const b = data.beats,+ p =+ frame >= b.examples+ ? 4+ : frame >= b.thirty+ ? 3+ : frame >= b.install+ ? 2+ : frame >= b.language+ ? 1+ : 0;+ const starts = [0, b.language, b.install, b.thirty, b.examples],+ ends = [+ b.language + 12,+ b.install + 12,+ b.thirty + 12,+ b.examples + 12,+ data.count,+ ];+ phases.forEach((el) => {+ const i = Number(el.dataset.p);+ el.style.opacity = String(fade(frame, starts[i], ends[i], 8));+ if (i < 4)+ el.style.transform =+ "translateY(" + (1 - ease((frame - starts[i]) / 10)) * 25 + "px)";+ });+ const titles = [+ ["Hypit", "开源视频复刻框架"],+ ["SVML", "视频领域语言"],+ ["Hypit Skill", "Codex + Claude"],+ ["30 min", "从参考到成片"],+ [+ frame >= b.face ? "你的版本" : "爆款原片",+ frame >= b.face ? "换脸 · 换产品" : "Ranking · Podcast · Interview",+ ],+ ];+ h.textContent = titles[p][0];+ h.style.fontSize = p === 2 ? "77px" : p === 4 ? "84px" : "100px";+ sub.textContent = titles[p][1];+ for (const name of ["codex", "claude"]) {+ const q = ease((frame - b[name]) / 7),+ el = root.querySelector(".app-" + name);+ el.style.opacity = String(q);+ el.style.transform =+ "translateY(" + (1 - q) * 55 + "px) scale(" + (0.65 + q * 0.35) + ")";+ }+ const typed = Math.floor(+ clamp((frame - b.thirty) / Math.max(1, b.examples - b.thirty)) *+ data.terminal.length,+ );+ paintTerminal(root.querySelector("pre"), data.terminal, typed);+ root.querySelectorAll(".card").forEach((el, i) => {+ const q = ease((frame - b.examples - i * 4) / 12),+ x = (i === 0 ? -430 : i === 1 ? 430 : 0) * (1 - q),+ y = (i === 2 ? 160 : 45) * (1 - q),+ raw = clamp((frame - b.face - i * 2) / 16),+ flip = ease(raw),+ hit = Math.sin(Math.PI * raw);+ el.style.opacity = String(q);+ el.style.transform =+ "translate3d(" ++ x ++ "px," ++ (y - hit * 22) ++ "px," ++ hit * 90 ++ "px) rotateY(" ++ (i === 0 ? 28 : i === 1 ? -28 : 0) * (1 - q) ++ "deg) rotate(" ++ (i === 0 ? -2 : i === 1 ? 2 : 0) * q * (1 - flip) ++ "deg) scale(" ++ (1 + hit * 0.045) ++ ")";+ const target = el.querySelector(".target"),+ original = el.querySelector(".original");+ target.style.opacity = String(clamp((flip - 0.3) / 0.3));+ target.style.transform =+ "perspective(900px) rotateY(" ++ 90 * (1 - flip) ++ "deg) scale(" ++ (1.09 - flip * 0.09) ++ ")";+ original.style.opacity = String(1 - clamp((flip - 0.3) / 0.3));+ original.style.transform =+ "perspective(900px) rotateY(" + -90 * flip + "deg)";+ const sweep = el.querySelector(".swap-sweep");+ sweep.style.opacity = String(hit * 0.8);+ sweep.style.transform = "translateX(" + (-110 + raw * 220) + "%)";+ el.style.boxShadow = "0 20px 40px #0009,0 0 " + hit * 32 + "px #ed557f99";+ });+};+`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/introduction/index.js b/examples/complex-explainer/packages/web-scenes/src/scenes/introduction/index.jsnew file mode 100644index 00000000..b5e01403--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/introduction/index.js@@ -0,0 +1,94 @@+import { intro_styles } from "./styles.js";+import { intro_animation } from "./animation.js";+import { scene } from "../../shared/scene.js";+import { requireBeats } from "../../shared/beats.js";+export function renderIntro(t, c, w, font, o, events, m) {+ requireBeats(events, [+ "language",+ "install",+ "codex",+ "claude",+ "thirty",+ "examples",+ "face",+ "product",+ ]);+ const b = Object.fromEntries(events.map((e) => [e.name, e.at.frame - w.span.startFrame])),+ count = w.span.endFrameExclusive - w.span.startFrame;+ const video = (media, start, end) => ({+ media,+ start,+ end: Math.min(count, end + 12),+ backdrop: {},+ });+ const entries = {+ page: video(m.page, 0, b.language),+ code: video(m.code, b.language, b.install),+ readme: video(m.readme, b.install, b.thirty),+ codex: { image: m.codex },+ claude: { image: m.claude },+ };+ for (const [n, i] of [+ ["ranking", 0],+ ["podcast", 1],+ ["interview", 2],+ ]) {+ entries["ref-" + n] = video(m["reference-" + n], b.examples, count);+ entries["own-" + n] = video(m["hypit-" + n], b.face, count);+ entries["ref-" + n].backdrop = n === "interview" ? {} : false;+ entries["own-" + n].backdrop = n === "interview" ? {} : false;+ if (n === "interview") entries["ref-" + n].end = b.face + 18;+ }+ const cards = ["ranking", "podcast", "interview"]+ .map(+ (n, i) =>+ `<div class="card card-${i}"><div class="original">{{ref-${n}}}</div><div class="target">{{own-${n}}}</div><div class="swap-sweep"></div></div>`,+ )+ .join("");+ const terminal = `+<time:Timeline id="program" clock="{clock}">+ <time:Take source="{host.take}" />+</time:Timeline>++<performance:Track timeline="{program.timeline}">+ <performance:Use style="{portrait}" />+</performance:Track>++<ranking:Board timeline="{program.timeline}">+ <ranking:Reveal at="{story.moment.first}" image="{product}" tier="S" />+</ranking:Board>++<caption:Track timeline="{program.timeline}" document="{story.caption}">+ <caption:Use style="{headline}" />+</caption:Track>++<film:Film timeline="{program.timeline}">+ <film:Track source="{presenter.visual}" />+ <film:Track source="{board.track}" />+</film:Film>`;+ return scene(+ t,+ c,+ w,+ font,+ o,+ `+<div class="mesh"></div><div class="heading"><b>Hypit</b><small>开源视频复刻框架</small></div+><div class="stage"+ ><div class="phase" data-p="0"><div class="screen">{{page}}</div></div+ ><div class="phase" data-p="1"><div class="screen">{{code}}</div></div+ ><div class="phase" data-p="2"+ ><div class="screen">{{readme}}</div><div class="app app-codex">{{codex}}</div+ ><div class="app app-claude">{{claude}}</div></div+ ><div class="phase terminal" data-p="3"+ ><div class="terminal-bar"><i></i><i></i><i></i><span>main.svml</span></div+ ><pre></pre><div class="cursor"></div></div+ ><div class="phase gallery" data-p="4">${cards}</div></div+>`,+ intro_styles,+ intro_animation,+ events,+ entries,+ { terminal },+ );+}diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/introduction/styles.js b/examples/complex-explainer/packages/web-scenes/src/scenes/introduction/styles.jsnew file mode 100644index 00000000..1a762139--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/introduction/styles.js@@ -0,0 +1,136 @@+export const intro_styles = `.phase.gallery {+ overflow: visible;+}+.card {+ position: absolute;+ overflow: hidden;+ border: 0;+ border-radius: 0;+ background: transparent;+}+.card-0 {+ left: 0;+ top: 75px;+ width: 362px;+ height: 645px;+ z-index: 1;+ transform-origin: left center;+}+.card-1 {+ right: 0;+ top: 75px;+ width: 362px;+ height: 645px;+ z-index: 1;+ transform-origin: right center;+}+.card-2 {+ left: 319px;+ top: 0;+ width: 442px;+ height: 786px;+ z-index: 2;+}+.original,+.target {+ position: absolute;+ inset: 0;+}+.original > *,+.target > * {+ object-fit: cover !important;+}+.target {+ opacity: 0;+}+.app {+ position: absolute;+ top: 330px;+ width: 255px;+ height: 255px;+ opacity: 0;+ filter: drop-shadow(0 12px 20px #0008);+}+.app-codex {+ left: 170px;+ filter: drop-shadow(0 0 8px #effcff) drop-shadow(0 0 32px #bbddff99);+}+.app-claude {+ right: 170px;+ filter: drop-shadow(0 0 8px #ffb89b) drop-shadow(0 0 32px #df775eaa);+}+.original,+.target {+ backface-visibility: hidden;+ transform-origin: center center;+}+.swap-sweep {+ position: absolute;+ inset: -10% -20%;+ background: linear-gradient(+ 110deg,+ transparent 35%,+ #fff5dcaa 48%,+ #e83f5fcc 51%,+ transparent 65%+ );+ opacity: 0;+ pointer-events: none;+ mix-blend-mode: screen;+}+.gallery {+ perspective: 1800px;+}+.card {+ will-change: transform;+ isolation: isolate;+}+.terminal {+ background: #fff0f7;+ border: 0;+}+.terminal-bar {+ height: 65px;+ border-bottom: 4px solid #392738;+ display: flex;+ align-items: center;+ padding: 0 25px;+ gap: 14px;+ background: #f8add0;+}+.terminal-bar i {+ width: 16px;+ height: 16px;+ background: #ef73ae;+ border-radius: 2px;+}+.terminal-bar i:nth-child(2) {+ background: #e7c574;+}+.terminal-bar i:nth-child(3) {+ background: #80ba91;+}+.terminal-bar span {+ font: 28px monospace;+ color: #392738;+ margin-left: 230px;+}+.terminal pre {+ font:+ 29px/1.55 Menlo,+ monospace;+ color: #68394f;+ white-space: pre-wrap;+ margin: 28px 35px;+ max-height: 650px;+ overflow: hidden;+}+.cursor {+ position: absolute;+ right: 40px;+ bottom: 35px;+ width: 15px;+ height: 30px;+ background: #d95791;+}+`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/outro/animation.js b/examples/complex-explainer/packages/web-scenes/src/scenes/outro/animation.jsnew file mode 100644index 00000000..1ec25f19--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/outro/animation.js@@ -0,0 +1,122 @@+// This scene owns its fixed design. External events arrive as projected frames.+export const animation = `+const $ = (s) => root.querySelector(s),+ columns = [...root.querySelectorAll(".portrait-column")];+const pop = (x) => {+ x = clamp(x);+ return 1 + 2.70158 * Math.pow(x - 1, 3) + 1.70158 * Math.pow(x - 1, 2);+};+const set = (el, a) => {+ el.style.opacity = String(clamp(a));+ el.style.visibility = a > 0 ? "inherit" : "hidden";+};+return (frame) => {+ const b = data.beats,+ f = frame;+ const tq = fade(f, b.overtime, b.github, 6);+ set($(".tears"), tq);+ [...root.querySelectorAll(".tear")].forEach((el, i) => {+ const age = Math.max(0, f - b.overtime),+ x = (i ? 594 : 443) + Math.sin(age * 0.025) * 2,+ y = 813 + Math.sin(age * 0.07) * 3;+ el.style.transform =+ "translate(" ++ x ++ "px," ++ y ++ "px) scaleY(" ++ (0.35 + 0.65 * ease(age / 9)) ++ ")";+ el.querySelector(".tear-drop").style.transform =+ "translateY(" + Math.floor(((age * 2 + i * 9) % 32) / 8) * 8 + "px)";+ });+ const github = fade(f, b.github, b.copy + 8, 8),+ copy = fade(f, b.copy, b.install + 7, 7),+ install = fade(f, b.install, b.gift + 8, 8),+ gift = fade(f, b.gift, b.bye + 9, 9),+ bye = ease((f - b.bye) / 12);+ paintBackdrop(f);+ set($(".backdrop"), github);+ set($(".outro-ground"), Math.max(copy, install, gift, f >= b.end ? 1 : 0));+ set($(".outro-page"), github);+ $(".outro-page").style.transform =+ "translateY(" ++ ((1 - ease((f - b.github) / 10)) * 65 - Math.max(0, f - b.github) * 0.8) ++ "px)";+ set($(".copy-panel"), copy);+ $(".copy-panel").style.transform =+ "translateY(" + (1 - pop((f - b.copy) / 12)) * 75 + "px)";+ const cq = clamp((f - b.copy) / Math.max(1, b.install - b.copy)),+ clicked = cq > 0.64;+ $(".copy-button").style.background = clicked ? "#bcdac3" : "#f8bbda";+ $(".copy-button span").textContent = clicked ? "Copied" : "Copy";+ $(".copy-button").style.transform =+ clicked && cq < 0.82 ? "translate(3px,3px)" : "none";+ $(".copy-highlight").style.opacity = clicked ? ".75" : "0";+ const pointer = $(".outro-pointer");+ set(pointer, copy);+ pointer.style.transform =+ "translate(" ++ (650 + 295 * ease(cq / 0.65)) ++ "px," ++ (1245 - 260 * ease(cq / 0.65)) ++ "px)";+ const ring = $(".click-ring"),+ rq = clamp((cq - 0.64) / 0.3);+ ring.style.opacity = String(clicked ? 1 - rq : 0);+ ring.style.transform = "scale(" + (1 + rq * 1.4) + ")";+ set($(".install-panel"), install);+ $(".install-panel").style.transform =+ "translateY(" + (1 - pop((f - b.install) / 13)) * 75 + "px)";+ const iq = clamp((f - b.install) / Math.max(1, b.gift - b.install));+ $(".installed-command").textContent = iq > 0.12 ? data.command : "";+ $(".caret").style.opacity = iq < 0.2 ? "1" : "0";+ const lines = [+ "◇ Fetching hypit-ai/hypit",+ "◇ Found skill: hypit",+ "◇ Installing to coding agents",+ "◆ Installation complete",+ ];+ $(".install-lines").textContent = lines+ .slice(0, Math.min(4, Math.floor(Math.max(0, iq - 0.18) * 5.2)))+ .join("\\n");+ $(".install-progress i").style.width =+ clamp((iq - 0.18) / 0.75) * 100 + "%";+ set($(".portrait-waterfall"), gift);+ const gq = clamp((f - b.gift) / Math.max(1, b.bye - b.gift));+ columns.forEach((col, i) => {+ const h = col.querySelector("img")?.naturalHeight || col.scrollHeight,+ travel = Math.max(+ 0,+ h * (218 / (col.querySelector("img")?.naturalWidth || 218)) - 1560,+ ),+ speed = 0.34 + gq * 0.08;+ col.style.transform =+ "translateY(" + -travel * (i % 2 ? 1 - speed : speed) + "px)";+ });+ const final = ease((f - (b.end - 12)) / 30);+ set($(".farewell-logo"), final);+ const tagline = "Clone any viral video with AI agents.";+ const typed = Math.floor(clamp((f - b.end - 8) / 35) * tagline.length);+ [...root.querySelectorAll(".pixel-letter")].forEach(+ (el, i) => (el.style.visibility = i < typed ? "inherit" : "hidden"),+ );+ $(".farewell-logo").style.transform =+ "translateY(" ++ (1 - final) * 45 ++ "px) scale(" ++ (0.94 + 0.06 * final) ++ ")";+ set($(".star-card"), bye);+ $(".star-card").style.transform =+ "translateY(" ++ ((1 - pop((f - b.bye) / 15)) * 90 + final * 150) ++ "px) scale(" ++ (1 + 0.012 * Math.sin(Math.max(0, f - b.bye) * 0.09)) ++ ")";+ [...root.querySelectorAll(".star")].forEach(+ (s, i) =>+ (s.style.transform =+ "rotate(" + Math.sin((f - b.bye) * 0.08 + i * Math.PI) * 10 + "deg)"),+ );+};`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/outro/index.js b/examples/complex-explainer/packages/web-scenes/src/scenes/outro/index.jsnew file mode 100644index 00000000..2fce3b79--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/outro/index.js@@ -0,0 +1,68 @@+import { css } from "./styles.js";+import { animation } from "./animation.js";+import { pixelType } from "../../shared/pixel-type.js";+import { hypitWordmark } from "../../shared/brand-marks.js";+import { scene } from "../../shared/scene.js";+import { requireBeats } from "../../shared/beats.js";+const github = `+<svg viewBox="0 0 24 24" fill="currentColor">+ <path+ d="M12 .8a11.2 11.2 0 0 0-3.54 21.83c.56.1.77-.24.77-.54v-2.1c-3.13.68-3.79-1.33-3.79-1.33-.51-1.3-1.25-1.64-1.25-1.64-1.02-.7.08-.69.08-.69 1.13.08 1.72 1.16 1.72 1.16 1.01 1.72 2.65 1.22 3.3.94.1-.73.4-1.22.71-1.5-2.5-.28-5.13-1.25-5.13-5.57 0-1.23.44-2.24 1.16-3.02-.12-.28-.5-1.43.11-2.99 0 0 .95-.3 3.08 1.16a10.68 10.68 0 0 1 5.6 0c2.14-1.46 3.08-1.16 3.08-1.16.62 1.56.23 2.71.11 2.99.73.78 1.16 1.79 1.16 3.02 0 4.33-2.63 5.28-5.14 5.56.4.35.76 1.03.76 2.08v3.09c0 .3.2.65.78.54A11.2 11.2 0 0 0 12 .8Z"+ />+</svg>`;+const cursor = `<svg viewBox="0 0 54 66"><path d="M5 3L46 33L28 37L20 58Z" fill="#fff7fc" stroke="#382535" stroke-width="4" stroke-linejoin="round"/><path d="M12 15L29 32L22 34L19 41Z" fill="#f57ab4"/></svg>`;+const copy = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="8" y="8" width="12" height="13" rx="2"/><path d="M15 8V3H3v13h5"/></svg>`;+export function renderOutro(t, c, w, font, o, events, m) {+ requireBeats(events, ["overtime", "github", "copy", "install", "gift", "bye", "end"]);+ const b = Object.fromEntries(events.map((e) => [e.name, e.at.frame - w.span.startFrame]));+ const entries = {+ codex: { image: m.codex },+ page: { media: m.page, start: b.github, end: b.copy + 8, backdrop: {} },+ };+ for (let i = 0; i < 5; i++) entries["portraits-" + i] = { image: m["portraits-" + i] };+ const html = `+<div class="outro-ground"></div+><svg class="tears" viewBox="0 0 1080 1920">+ <defs>+ <linearGradient id="tear-color" x2="1" y2="0">+ <stop stop-color="#d0faff" />+ <stop offset=".5" stop-color="#70d9f3" />+ <stop offset="1" stop-color="#b4f1ff" />+ </linearGradient>+ </defs>+ ${[0, 1].map((i) => `<g class="tear tear-${i}"><path class="tear-stream" d="M-16 0H16V24H8V48H16V80H8V112H-8V88H-16V56H-8V32H-16Z" fill="#93e6ff" stroke="#397792" stroke-width="4" stroke-linejoin="miter"/><path d="M-8 8H0V24H-8ZM0 40H8V56H0ZM-8 72H0V88H-8Z" fill="#effcff"/><path class="tear-drop" d="M-8 128H8V136H16V152H8V160H-8V152H-16V136H-8Z" fill="#93e6ff" stroke="#397792" stroke-width="4"/><path class="tear-chip" d="M-26 170H-14V182H-26Z M18 190H30V202H18Z" fill="#a7ecff" stroke="#397792" stroke-width="3"/></g>`).join("")}</svg+><div class="outro-page">{{page}}</div>+<div class="copy-panel"+ ><div class="outro-bar"><i></i><i></i><i></i><span>INSTALL SKILL</span><b>×</b></div+ ><div class="copy-body"+ ><span class="prompt-sign">$</span><code>npx skills add hypit-ai/hypit -g</code+ ><div class="copy-button">${copy}<span>Copy</span></div></div+ ><div class="copy-highlight"></div+></div>+<div class="install-panel"+ ><div class="outro-bar"><i></i><i></i><i></i><span>TERMINAL</span><b>×</b></div+ ><div class="install-body"+ ><p><span>$ </span><code class="installed-command"></code><b class="caret">▌</b></p+ ><div class="install-lines"></div><div class="install-progress"><i></i></div></div+></div>+<div class="outro-pointer"+ >${cursor}<div class="pointer-badge">{{codex}}</div><div class="click-ring"></div+></div>+<div class="portrait-waterfall">${Array.from({ length: 5 }, (_, i) => `<div class="portrait-column column-${i}">{{portraits-${i}}}</div>`).join("")}</div>+<div class="farewell-logo"+ >${hypitWordmark}<div class="farewell-tagline"+ ><div class="tagline-line">${pixelType("Clone any viral video")}</div+ ><div class="tagline-line">${pixelType("with AI agents.")}</div></div+ ></div+><div class="star-card"+ ><div class="star-top"+ ><span class="github-icon">${github}</span><span>hypit-ai/hypit</span></div+ ><div class="star-bottom"+ ><span class="star left">★</span><span>Star us on GitHub!</span+ ><span class="star right">★</span></div+ ></div+>`;+ return scene(t, c, w, font, o, html, css, animation, events, entries, {+ command: "npx skills add hypit-ai/hypit -g",+ });+}diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/outro/styles.js b/examples/complex-explainer/packages/web-scenes/src/scenes/outro/styles.jsnew file mode 100644index 00000000..53c8ee0b--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/outro/styles.js@@ -0,0 +1,319 @@+// This scene owns its fixed design. External events arrive as projected frames.+export const css = `+:scope {+ background: transparent;+ color: #382535;+}+.backdrop {+ display: block;+ opacity: 0;+}+.backdrop-wash {+ display: none;+}+.outro-ground {+ position: absolute;+ inset: 0;+ background: #fce5ee;+ background-image: radial-gradient(#efb9d0 1.5px, transparent 1.5px);+ background-size: 24px 24px;+ opacity: 0;+}+.outro-page {+ position: absolute;+ left: 0;+ top: 530px;+ width: 1080px;+ height: 910px;+ overflow: hidden;+}+.outro-page > * {+ object-fit: cover !important;+ object-position: center top !important;+}+.copy-panel,+.install-panel {+ position: absolute;+ left: 55px;+ top: 820px;+ width: 970px;+ background: #fff2f9;+ border: 5px solid #382535;+ border-radius: 9px;+ box-shadow: 12px 14px 0 #382535;+ overflow: hidden;+ transform-origin: center;+}+.outro-bar {+ height: 60px;+ background: #f6a6ce;+ border-bottom: 4px solid #382535;+ display: flex;+ align-items: center;+ gap: 13px;+ padding: 0 24px;+ font:+ 24px Menlo,+ monospace;+}+.outro-bar i {+ display: block;+ width: 16px;+ height: 16px;+ background: #fff4fa;+ border: 2px solid #382535;+}+.outro-bar i:nth-child(2) {+ background: #c7dfbc;+}+.outro-bar i:nth-child(3) {+ background: #cdbbe9;+}+.outro-bar span {+ margin-left: 15px;+}+.outro-bar b {+ margin-left: auto;+ font-size: 35px;+}+.copy-body {+ height: 235px;+ display: flex;+ align-items: center;+ padding: 0 26px;+ gap: 12px;+ font:+ 36px Menlo,+ monospace;+ position: relative;+ z-index: 1;+}+.prompt-sign {+ color: #d9468e;+}+.copy-button {+ margin-left: auto;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 8px;+ font:+ 18px Menlo,+ monospace;+ background: #f8bbda;+ border: 3px solid #382535;+ border-radius: 4px;+ padding: 14px 17px;+ box-shadow: 5px 5px 0 #382535;+}+.copy-button svg {+ width: 34px;+ height: 34px;+}+.copy-highlight {+ position: absolute;+ left: 65px;+ right: 130px;+ top: 155px;+ height: 43px;+ background: #f7bbda;+ opacity: 0;+}+.install-panel {+ top: 740px;+ min-height: 455px;+}+.install-body {+ padding: 25px 27px;+ font:+ 32px/1.65 Menlo,+ monospace;+}+.install-body p {+ margin: 0 0 35px;+ white-space: nowrap;+}+.install-body p span {+ color: #cf4286;+}+.install-lines {+ color: #714358;+ white-space: pre-line;+}+.install-progress {+ margin-top: 35px;+ height: 16px;+ background: #f2d3e3;+ border: 2px solid #382535;+}+.install-progress i {+ display: block;+ height: 100%;+ width: 0;+ background: repeating-linear-gradient(+ 90deg,+ #e95b9d 0 20px,+ #f49cc6 20px 25px+ );+}+.outro-pointer {+ position: absolute;+ left: 0;+ top: 0;+ width: 68px;+ height: 85px;+ filter: drop-shadow(4px 5px 0 #38253533);+ z-index: 4;+}+.outro-pointer > svg {+ width: 100%;+ height: 100%;+}+.pointer-badge {+ position: absolute;+ left: 39px;+ top: 43px;+ width: 40px;+ height: 40px;+ background: #fff4f9;+ border: 3px solid #382535;+ border-radius: 50%;+ padding: 7px;+}+.pointer-badge > * {+ width: 100% !important;+ height: 100% !important;+ object-fit: contain !important;+}+.click-ring {+ position: absolute;+ left: -18px;+ top: -18px;+ border: 5px solid #ed64a4;+ width: 44px;+ height: 44px;+ border-radius: 50%;+ opacity: 0;+}+.portrait-waterfall {+ position: absolute;+ inset: 100px -35px 70px;+ display: flex;+ gap: 14px;+ overflow: hidden;+ mask-image: linear-gradient(transparent, #000 8%, #000 92%, transparent);+ transform: rotate(-3deg) scale(1.06);+}+.portrait-column {+ position: relative;+ width: 218px;+ flex: none;+ will-change: transform;+}+.portrait-column > * {+ width: 100% !important;+ height: auto !important;+ max-height: none !important;+ object-fit: contain !important;+ border-radius: 5px;+ box-shadow: 5px 6px 0 #382535;+}+.star-card {+ position: absolute;+ left: 78px;+ top: 1090px;+ width: 924px;+ border: 5px solid #382535;+ border-radius: 9px;+ background: #fff2f9;+ box-shadow: 12px 14px 0 #382535;+ transform-origin: center;+}+.star-top {+ display: flex;+ justify-content: center;+ align-items: center;+ gap: 27px;+ padding: 28px 20px 25px;+ font:+ bold 56px Menlo,+ monospace;+}+.github-icon {+ width: 70px;+ height: 70px;+ display: block;+}+.github-icon svg {+ width: 100%;+ height: 100%;+}+.star-bottom {+ background: #f59ac6;+ border-top: 4px solid #382535;+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 25px;+ padding: 23px 12px;+ font:+ bold 44px Menlo,+ monospace;+}+.star {+ font-size: 56px;+ color: #fff6bd;+ -webkit-text-stroke: 2px #382535;+ paint-order: stroke fill;+ text-shadow: 3px 4px 0 #382535;+}+.tears {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ z-index: 8;+ pointer-events: none;+}+.tear {+ transform-origin: 0 0;+}+.farewell-logo {+ position: absolute;+ left: 200px;+ top: 735px;+ width: 680px;+ height: 270px;+ filter: drop-shadow(5px 7px 0 #fff7fc);+ z-index: 2;+}+.farewell-logo svg {+ width: 100%;+ height: 100%;+}+.farewell-tagline {+ position: absolute;+ top: 300px;+ left: -120px;+ right: -120px;+ text-align: center;+ font:+ 30px Menlo,+ monospace;+ color: #613443;+ letter-spacing: -1px;+ text-shadow: 2px 2px #fff7ed;+ white-space: nowrap;+ height: 150px;+}+.tagline-line {+ height: 73px;+ text-align: center;+}+.farewell-tagline .tagline-line svg {+ width: auto;+ height: 48px;+ max-width: 100%;+ filter: drop-shadow(2px 3px #fff8ef);+}+`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/semantic-time/animation.js b/examples/complex-explainer/packages/web-scenes/src/scenes/semantic-time/animation.jsnew file mode 100644index 00000000..9de080d5--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/semantic-time/animation.js@@ -0,0 +1,125 @@+import { portraitMotion } from "../../shared/studio-art.js";+// This scene owns its fixed design. External events arrive as projected frames.+export const animation = `+const codePane = $(".script-source pre"),+ sourceLines = codePane.innerHTML.split("<br>");+codePane.innerHTML = sourceLines+ .map(+ (line, i) =>+ '<div class="source-line" data-line="' ++ i ++ '"><i class="source-line-no">' ++ String(i + 1).padStart(2, "0") ++ '</i><span class="source-line-body">' ++ (line || " ") ++ "</span></div>",+ )+ .join("");+return (f) => {+ const b = data.beats,+ match = ease((f - b.bind) / 10),+ expand = smooth((f - b.bind) / 13),+ examples = fade(f, b.examples, b["rewrite-scene"] + 6, 6),+ rewrite = fade(f, b["rewrite-scene"], b.syntax + 8, 6),+ syntax = ease((f - b.syntax) / 10),+ changed = smooth((f - b.rewrite) / 8),+ voiced = smooth((f - b.voice) / 8),+ adapt = smooth((f - b.adapt) / 24);+ show($(".semantic-studio"), 1 - ease((f - b.examples) / 10));+ show($(".semantic-board"), 1 - syntax);+ show($(".semantic-preview"), 0);+ show($(".semantic-examples"), examples);+ show($(".rewrite-sheet"), rewrite);+ show($(".script-source"), syntax);+ $(".script-source").style.transform =+ "translateY(" + (1 - pop((f - b.syntax) / 13)) * 35 + "px)";+ $$(".source-line").forEach((el, i) => {+ const q = ease((f - b.syntax - i * 1.3) / 7);+ el.style.opacity = String(q);+ el.style.transform = "translateX(" + (1 - q) * 16 + "px)";+ });+ $$(".script-source em").forEach((el, i) => {+ const q = Math.sin(clamp((f - b.syntax - 8 - i * 3) / 17) * Math.PI);+ el.style.boxShadow = "0 0 " + q * 12 + "px #ef91b8";+ el.style.background = "rgba(244,164,202," + (0.4 + 0.5 * q) + ")";+ }); ${portraitMotion}+ const examplePos = ease((f - b.examples) / 18),+ baseTop = mix(1174, 980, expand),+ baseScale = mix(0.58, 1, expand),+ boardTop = mix(mix(baseTop, 1160, examplePos), 1080, changed),+ boardScale = mix(mix(baseScale, 0.66, examplePos), 0.85, changed);+ $(".semantic-board").style.top = boardTop + "px";+ const scaleX = mix(1, 0.75, examplePos * (1 - changed));+ $(".semantic-board").style.transform =+ "scale(" + scaleX + "," + boardScale + ")";+ const updated = f >= b.voice;+ show($(".bank-original"), updated ? 0 : 1);+ show($(".bank-revised"), updated ? 1 : 0);+ const left = updated ? 115 : 155,+ steps = [125, 253, 386, 215, 386],+ phase =+ clamp((f - b.bind - 13) / Math.max(1, b.examples - b.bind - 20)) * 4,+ i = Math.min(3, Math.floor(phase)),+ edge = mix(steps[i], steps[i + 1], smooth((phase - i) / 0.55)),+ width = updated ? 451 : edge;+ const sel = $(".selected-words"),+ effect = $(".effect-window");+ sel.style.left = left + "px";+ sel.style.width = width + "px";+ effect.style.left = 130 + left + "px";+ effect.style.width = width + "px";+ show(effect, match);+ show(sel, match);+ const pulse = Math.sin(clamp((f - b.adapt) / 22) * Math.PI);+ effect.style.boxShadow = "0 0 " + pulse * 15 + "px #d789ba";+ effect.style.background =+ "rgb(" ++ Math.round(237 + 10 * pulse) ++ "," ++ Math.round(173 + 25 * pulse) ++ "," ++ Math.round(208 + 17 * pulse) ++ ")";+ $(".semantic-moment").style.left = left + width + "px";+ $(".semantic-playhead").style.left = 150 + ((f * 0.85) % 700) + "px";+ const pointer = $(".work-pointer"),+ drag = smooth((f - b.bind - 10) / 8);+ show(pointer, match * (1 - ease((f - b.examples) / 6)));+ move(+ pointer,+ mix(530, 35 + 505 + (130 + left + width - 505) * scaleX, drag),+ mix(boardTop - 3, boardTop + 285 * boardScale, drag),+ );+ const reveal = clamp((f - b.rank) / 17);+ $(".rank-front").style.transform =+ "rotateX(" + -180 * smooth(reveal) + "deg)";+ $(".rank-back").style.transform =+ "rotateX(" + (180 - 180 * smooth(reveal)) + "deg)";+ const fly = pop((f - b.product) / 19);+ show($(".flying-brand"), ease((f - b.product) / 8));+ $(".flying-brand").style.transform =+ "translate(" ++ (1 - fly) * -380 ++ "px," ++ (1 - fly) * -210 ++ "px) rotate(" ++ (1 - fly) * -35 ++ "deg) scale(" ++ (0.5 + 0.5 * fly) ++ ")";+ show($(".pixel-stars"), Math.sin(clamp((f - b.product) / 28) * Math.PI));+ show($(".rewrite-old"), 1 - changed);+ show($(".rewrite-new"), changed);+ $$(".voice-shape i").forEach((el, i) => {+ const old =+ (0.12 + 0.88 * Math.abs(Math.sin(i * 0.13) * Math.cos(i * 0.39))) *+ (10 + 68 * Math.abs(Math.sin(i * 2.17))),+ next =+ (0.08 ++ 0.92 * Math.abs(Math.cos(i * 0.09 + 1) * Math.sin(i * 0.31 + 2))) *+ (9 + 72 * Math.abs(Math.cos(i * 1.79)));+ el.style.height = mix(old, next, voiced) + "px";+ el.style.background = voiced > 0.5 ? "#9a72bc" : "#c074a5";+ });+ $(".voice-chip").style.background = voiced > 0.5 ? "#e5d0f4" : "#f3d6e6";+};`;diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/semantic-time/index.js b/examples/complex-explainer/packages/web-scenes/src/scenes/semantic-time/index.jsnew file mode 100644index 00000000..166abb46--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/semantic-time/index.js@@ -0,0 +1,67 @@+import { css } from "./styles.js";+import { animation } from "./animation.js";+import { scene } from "../../shared/scene.js";+import { bar, pointer, workCss, workSetup } from "../../shared/workshop-language.js";+import {+ studioBar,+ inspector,+ librarySide,+ faceless,+ studioCss,+ portraitMotion,+} from "../../shared/studio-art.js";+import { hypitSymbol } from "../../shared/brand-marks.js";+const wordBank = (name, words, widths) =>+ `<div class="word-bank bank-${name}">${words.map((word, i) => `<span class="word" style="width:${widths[i]}px">${word}</span>`).join("")}</div>`;+const line = (cls, label, body) =>+ `<div class="semantic-row ${cls}"><b>${label}</b><div class="semantic-row-body">${body}</div></div>`;+export function renderSemanticWorkshop(t, c, w, font, o, events, m) {+ const html = `+<div class="work-ground"></div+><div class="semantic-studio hs-window"+ >${studioBar()}${librarySide()}<div class="hs-preview-label hs-tab">Preview</div+ ><div class="hs-preview-matte"></div>${inspector()}<div class="semantic-person"+ >${faceless(1)}<div class="mini-result">#1 Hypit</div></div+ ></div+><div class="semantic-board work-window"+ >${bar("Hypit · Timeline")}${line("seconds", "TIME", "<span>0s</span><span>1s</span><span>2s</span><span>3s</span><span>4s</span><span>5s</span>")}${line("segments", "SEGMENT", "<i>HOST · introduction</i>")}${line("words", "WORDS", wordBank("original", ["榜单", "在", "第一名", "翻开", ",", "产品图", "在", "Hypit", "飞进来"], [82, 45, 125, 82, 30, 125, 45, 98, 124]) + wordBank("revised", ["今天的", "第一名", "揭晓", ",", "它就是", "Hypit", "。", "一起", "看看"], [95, 100, 100, 24, 100, 95, 24, 65, 120]))}${line("anchors", "ANCHORS", '<i class="selected-words">@reveal</i><i class="semantic-moment"></i>')}<div+ class="effect-lane"+ ><b>MG</b><div class="effect-window"><span>榜单揭晓</span><i></i></div></div+ ><div class="semantic-playhead"></div><div class="hs-handle"></div+></div>+<div class="semantic-preview work-window"+ >${bar("Preview")}<div class="preview-rank"><b>#1</b><span>Hypit</span>${hypitSymbol}</div+ ><div class="preview-tiles"><i></i><i></i><i></i></div+></div>+<div class="semantic-examples"+ ><div class="rank-example"+ ><div class="rank-heading">AI VIDEO TOOLS</div+ ><div class="rank-slot first"+ ><div class="rank-front">01 ?</div+ ><div class="rank-back">01 <span>${hypitSymbol}</span><b>Hypit</b></div></div+ ><div class="rank-slot"+ ><span class="rank-number">02</span><span class="rank-icon">{{creatify}}</span+ ><b>Creatify</b></div+ ><div class="rank-slot"+ ><span class="rank-number">03</span><span class="rank-icon">{{higgsfield}}</span+ ><b>Higgsfield</b></div+ ></div+ ><div class="sentence-example"+ ><div class="blank-brand"></div><div class="claim">is the <b>#1</b><br />AI video tool</div+ ><div class="flying-brand">${hypitSymbol}</div><div class="pixel-stars">✦ ✧ ✦</div></div+ ></div+>+<div class="rewrite-sheet work-window"+ >${bar("Script + Voice")}<div class="rewrite-old"+ >榜单在 <b>第一名</b> 翻开,<br />产品图在 <b>Hypit</b> 飞进来。</div+ ><div class="rewrite-new">今天的 <b>第一名</b> 揭晓,<br />它就是 <b>Hypit</b>。一起看看!</div+ ><div class="voice-shape">${Array.from({ length: 85 }, (_, i) => `<i style="--i:${i}"></i>`).join("")}</div><div class="voice-chip">♫ 新的配音</div></div+>+<div class="script-source work-window"+ >${bar("main.svml")}<pre><span><script id="story"></span><br> <intro><br> <HOST> 今天的 <em>@winner</em> 第一名<em>@/winner</em>,<br> 就是 <em>@product!</em> Hypit。<br> </intro><br><span></script></span><br><br><span><media:Track</span> timeline={program.timeline}<br> canvas={canvas}<span>></span><br> <span><media:Item</span> media={product.media}<br> frame={layout.product}<br> at=<em>{story.moment.product}</em> for="2s"<br> appearance={styles.product}<span>/></span><br><span></media:Track></span></pre></div+>${pointer}`;+ return scene(t, c, w, font, o, html, workCss + studioCss + css, workSetup + animation, events, {+ creatify: { image: m.creatify },+ higgsfield: { image: m.higgsfield },+ });+}diff --git a/examples/complex-explainer/packages/web-scenes/src/scenes/semantic-time/styles.js b/examples/complex-explainer/packages/web-scenes/src/scenes/semantic-time/styles.jsnew file mode 100644index 00000000..26b26a12--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/scenes/semantic-time/styles.js@@ -0,0 +1,393 @@+// This scene owns its fixed design. External events arrive as projected frames.+export const css = `+.semantic-studio {+ top: 650px;+ height: 750px;+}+.semantic-person {+ position: absolute;+ left: 405px;+ top: 94px;+ width: 240px;+ height: 420px;+ border: 3px solid #a87a9a;+ overflow: hidden;+}+.mini-result {+ position: absolute;+ left: 25px;+ bottom: 70px;+ background: #ffe1a4;+ border: 3px solid #9c7293;+ padding: 10px;+ font: bold 26px monospace;+}+.semantic-board {+ top: 1120px;+ height: 388px;+ overflow: visible;+ transform-origin: top center;+ z-index: 3;+}+.semantic-row {+ height: 52px;+ display: flex;+ border-bottom: 2px solid #dabccc;+ font: 20px monospace;+}+.semantic-row > b {+ width: 130px;+ flex: none;+ font:+ 17px Menlo,+ monospace;+ padding: 15px 10px;+ color: #85516d;+ border-right: 2px solid #dabccc;+}+.semantic-row-body {+ position: relative;+ width: 850px;+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 0 12px;+}+.seconds {+ height: 43px;+}+.seconds .semantic-row-body {+ justify-content: space-between;+ font: 16px monospace;+}+.segments i {+ width: 100%;+ height: 33px;+ padding: 4px 10px;+ background: #dfbeed;+ border: 2px solid #927094;+ border-radius: 3px;+ font: 19px monospace;+}+.word-bank {+ position: absolute;+ left: 12px;+ top: 0;+ height: 100%;+ display: flex;+ align-items: center;+ gap: 8px;+}+.words .word {+ white-space: nowrap;+ font: 23px sans-serif;+ display: flex;+ align-items: center;+ justify-content: center;+ height: 41px;+ flex: none;+ padding: 0;+ background: #fee6b6;+ border: 2px solid #b59868;+ border-radius: 3px;+}+.selected-words {+ position: absolute;+ top: 7px;+ height: 35px;+ background: #dcb8eb;+ border: 2px solid #8d669c;+ border-radius: 4px;+ padding: 4px 8px;+ font: 20px monospace;+}+.semantic-moment {+ position: absolute;+ width: 12px;+ height: 29px;+ background: #e76c89;+ clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);+ top: 10px;+}+.effect-lane {+ height: 68px;+ position: relative;+ display: flex;+}+.effect-lane > b {+ width: 130px;+ padding: 15px 12px;+ font: 19px monospace;+}+.effect-window {+ position: absolute;+ top: 10px;+ height: 47px;+ background: #edadd0;+ border: 3px solid #8b5176;+ border-radius: 4px;+ font: 21px sans-serif;+ padding: 8px 12px;+}+.effect-window i {+ position: absolute;+ right: 0;+ top: 0;+ bottom: 0;+ width: 11px;+ background: #bf70a0;+ border-left: 2px solid #8b5176;+}+.semantic-playhead {+ position: absolute;+ top: 96px;+ height: 265px;+ border-left: 3px solid #e76888;+ pointer-events: none;+}+.semantic-preview {+ top: 510px;+ height: 350px;+}+.preview-rank {+ position: absolute;+ left: 220px;+ top: 100px;+ width: 540px;+ height: 170px;+ background: #ffde95;+ border: 4px solid #382535;+ box-shadow: 8px 10px #382535;+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 28px;+ font: bold 53px monospace;+ transform-origin: center;+}+.preview-rank svg {+ height: 105px;+ width: 115px;+}+.preview-tiles {+ position: absolute;+ left: 100px;+ bottom: 25px;+ display: flex;+ gap: 17px;+}+.preview-tiles i {+ width: 170px;+ height: 25px;+ background: #ead5f0;+ border: 2px solid #c59dbd;+}+.semantic-examples {+ position: absolute;+ left: 35px;+ top: 710px;+ width: 1010px;+ height: 565px;+}+.rank-example {+ position: absolute;+ left: 0;+ width: 480px;+ height: 400px;+ background: #fff3e1;+ border: 4px solid #382535;+ box-shadow: 9px 11px #382535;+ border-radius: 7px;+ padding: 16px;+}+.rank-heading {+ font: bold 25px monospace;+ margin-bottom: 15px;+ letter-spacing: 2px;+}+.rank-slot {+ height: 91px;+ margin: 12px 0;+ background: #f5c8df;+ border: 3px solid #382535;+ padding: 12px 14px;+ font: 29px monospace;+ display: flex;+ align-items: center;+ gap: 12px;+}+.rank-slot b {+ font-size: 27px;+}+.rank-number {+ width: 40px;+ flex: none;+}+.rank-icon {+ width: 53px;+ height: 53px;+ flex: none;+ display: flex;+ align-items: center;+ justify-content: center;+}+.rank-icon > * {+ width: 100% !important;+ height: 100% !important;+ object-fit: contain !important;+}+.rank-slot.first {+ position: relative;+ background: #ffdc91;+ padding: 0;+ perspective: 700px;+}+.rank-front,+.rank-back {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ padding: 12px 16px;+ gap: 20px;+ backface-visibility: hidden;+ transform-origin: center;+}+.rank-back {+ background: #ffdc91;+}+.rank-back span {+ width: 66px;+ height: 63px;+}+.rank-back svg {+ width: 100%;+ height: 100%;+}+.sentence-example {+ position: absolute;+ right: 0;+ top: 0;+ width: 480px;+ height: 400px;+ background: #dfcef0;+ border: 4px solid #382535;+ box-shadow: 9px 11px #382535;+ border-radius: 7px;+ text-align: center;+ padding-top: 45px;+ overflow: visible;+}+.blank-brand {+ height: 119px;+ width: 140px;+ border-bottom: 5px dashed #957caa;+ margin: 0 auto 32px;+}+.claim {+ font:+ bold 31px/1.65 Menlo,+ monospace;+}+.claim b {+ background: #ffdea0;+ padding: 5px 8px;+}+.flying-brand {+ position: absolute;+ left: 167px;+ top: 45px;+ width: 140px;+ height: 124px;+}+.flying-brand svg {+ width: 100%;+ height: 100%;+}+.pixel-stars {+ position: absolute;+ inset: 25px 0 auto;+ color: #e5a83b;+ font: 34px monospace;+ letter-spacing: 35px;+}+.rewrite-sheet {+ top: 685px;+ height: 330px;+}+.rewrite-old,+.rewrite-new {+ position: absolute;+ top: 80px;+ left: 30px;+ font: 34px/1.6 sans-serif;+}+.rewrite-old b,+.rewrite-new b {+ background: #f4d899;+ border-bottom: 3px solid #ca9e53;+}+.voice-shape {+ position: absolute;+ left: 33px;+ right: 200px;+ bottom: 25px;+ height: 75px;+ display: flex;+ gap: 4px;+ align-items: center;+}+.voice-shape i {+ width: 5px;+ background: #c074a5;+ flex: none;+}+.voice-chip {+ position: absolute;+ right: 20px;+ bottom: 32px;+ font: 22px sans-serif;+ padding: 12px;+ background: #d5b9ed;+ border: 2px solid #382535;+}+.script-source {+ top: 665px;+ height: 765px;+}+.script-source pre {+ font:+ 27px/1.55 Menlo,+ monospace;+ padding: 30px 20px;+ white-space: pre-wrap;+ margin: 0;+}+.source-line {+ position: relative;+ display: flex;+ min-height: 42px;+}+.source-line-no {+ font: 18px/42px monospace;+ color: #c4a3b9;+ width: 36px;+ flex: none;+ border-right: 1px solid #e6cbdb;+ margin-right: 12px;+ font-style: normal;+}+.source-line-body {+ white-space: pre;+ color: #58405b;+}+.script-source span {+ color: #976ea7;+}+.script-source em {+ font-style: normal;+ background: #f7cdda;+ color: #bc3b77;+ padding: 4px;+}+`;diff --git a/examples/complex-explainer/packages/web-scenes/src/shared/beats.js b/examples/complex-explainer/packages/web-scenes/src/shared/beats.jsnew file mode 100644index 00000000..e55ca8c2--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/shared/beats.js@@ -0,0 +1,3 @@+export const requireBeats = (events, names) => {+ for (const n of names) if (!events.some((e) => e.name === n)) throw Error("Missing Beat " + n);+};diff --git a/examples/complex-explainer/packages/web-scenes/src/shared/brand-marks.js b/examples/complex-explainer/packages/web-scenes/src/shared/brand-marks.jsnew file mode 100644index 00000000..ee2830db--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/shared/brand-marks.js@@ -0,0 +1,5 @@+// Exact paths from assets/brand/hypit-logo-original.svg, with a coral fill.+export const hypitWordmark =+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="54.9 186.2 732.1 222.8" fill="#e85b75" aria-hidden="true"><path d="M303.78,277.82c-5.98-8.63-15.83-13.77-26.32-13.77h-93.41c-12.28,0-24.92,7.44-29.6,18.8l-28.26,75.82c-4.6,11.25-4.54,24.05,2.22,34.16,6.79,10.15,19.36,16.15,31.57,16.15h85.98c14.12,0,26.9-8.88,31.84-22.1l29.69-79.57c3.67-9.84,2.29-20.86-3.69-29.48v-.02h-.02ZM252.02,377.25c-.94,2.52-3.39,4.22-6.08,4.22h-83.45c-4.34,0-6.68-2.8-7.49-3.99s-2.5-4.43-.84-8.44l23.85-66.24c2.29-6.35,8.08-10.87,14.82-11.22.33-.02.67-.02,1.02-.02h75.41s12.51,1.42,9.29,14.61l-26.53,71.09h0ZM106.85,361.73s-22.36-11.59-17.66-32.66l29.67-82.23c4.78-13.25,17.36-22.09,31.45-22.09h95.02c6.25,0,12.1,3.03,15.71,8.14l13.89,19.68h-112.97c-8.7,0-16.49,5.41-19.52,13.57l-35.59,95.6h0ZM73.3,323.27s-22.37-11.59-17.66-32.66l29.67-82.23c4.79-13.25,17.37-22.09,31.45-22.09h89.91c6.25,0,12.1,3.03,15.71,8.14l13.89,19.68h-107.84c-8.7,0-16.49,5.41-19.52,13.57l-35.59,95.6h-.02Z" fill="#e85b75" /><rect x="692.47" y="276.19" width="19.22" height="90.09" rx="4.12" ry="4.12" fill="#e85b75" /><path d="M462.31,293.32c-4.51-11.11-12.93-15.68-28.26-17.66-15.52-2-31.17,1.58-36.41,2.96v-38.42c0-2.22-1.8-4.02-4.02-4.02h-11.19c-2.22,0-4.02,1.8-4.02,4.02v123.26c0,2.22,1.8,4.02,4.02,4.02h11.19c2.22,0,4.02-1.8,4.02-4.02v-66.25c3.68-1.46,16.84-6.13,30.89-4.57,12.12,1.35,15.81,10.13,16.92,14.75.32,1.33.47,2.68.47,4.03v53.36c0,1.49,1.2,2.68,2.68,2.68h13.65c1.49,0,2.68-1.2,2.68-2.68v-57.38c0-4.82-.82-9.63-2.63-14.09h.01Z" fill="#e85b75" /><path d="M568.55,346.34v-67.42c0-1.57-1.27-2.85-2.85-2.85h-14.66c-1.57,0-2.85,1.27-2.85,2.85v64.51c0,.58-.19,1.16-.58,1.6-1.62,1.88-7.33,6.23-25.19,5.92-2.22.05-6.37-.58-8.51-1.13-14.03-3.61-12.62-17.41-12.62-33.16v-37.73c0-1.57-1.27-2.85-2.85-2.85h-13.68c-1.57,0-2.85,1.27-2.85,2.85v57.63s-2.72,24.49,25.91,30.92c0,0,3.11.67,7.45,1.01h-.02s.13,0,.38.03c.07,0,.15,0,.23.02.19.02.42.02.69.04.25.02.51.02.77.04,2.94.14,8.59.25,14.08-.44h-.05c6.97-.77,13.42-2.51,17.37-5.02,0,0-1.77,20.45-18.82,23.73-9.86,1.13-24.24-.46-31.62-1.65-2.22-.36-4.33,1.06-4.84,3.24l-2.55,10.92c-.49,2.08.99,4.09,3.1,4.28,7.44.63,23.6,1.84,34.54,1.37,14.62-.61,26.8-6.24,34.06-21.17,7.26-14.93,5.93-37.54,5.93-37.54h.03Z" fill="#e85b75" /><path d="M674.19,297.63c-8.46-21.2-28.09-21.76-37.64-22.58-7.78-.66-37.08.93-47.69,1.54-2.17.13-3.86,1.92-3.86,4.1v119.88c0,1.74,1.41,3.14,3.14,3.14h14.17c1.74,0,3.14-1.41,3.14-3.14v-34.16c45.01,4.23,52.91-1.5,60.82-8.86,8.8-8.2,15.13-37.91,7.91-59.92h.01ZM656.46,330.82c-.27,4.64-1.91,18-19.5,19.22-17.59,1.23-31.5-2.32-31.5-2.32v-54.21c4.62-.18,16.65-.61,25.09-.61,10.64,0,15.27,1.5,21.82,8.32s4.37,24.96,4.09,29.59h0Z" fill="#e85b75" /><circle cx="703.1" cy="250.37" r="14.18" fill="#e85b75" /><path d="M784.34,292.92c1.41,0,2.56-1.15,2.56-2.56v-11.6c0-1.41-1.15-2.56-2.56-2.56h-27.3v-19.11c0-1.32-1.07-2.38-2.38-2.38h-14.87c-1.32,0-2.38,1.07-2.38,2.38v19.11h-10.74c-1.41,0-2.56,1.15-2.56,2.56v11.6c0,1.41,1.15,2.56,2.56,2.56h10.74v48.61c0,14.46,11.72,26.19,26.19,26.19h19.46c2.13,0,3.86-1.73,3.86-3.86v-9.69c0-2.13-1.73-3.86-3.86-3.86h-13.53c-6.9,0-12.48-5.59-12.48-12.48v-44.92h27.3-.01Z" fill="#e85b75" /></svg>';+export const hypitSymbol =+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="54.9 186.2 265 222.8" fill="#e85b75" aria-hidden="true"><path d="M303.78,277.82c-5.98-8.63-15.83-13.77-26.32-13.77h-93.41c-12.28,0-24.92,7.44-29.6,18.8l-28.26,75.82c-4.6,11.25-4.54,24.05,2.22,34.16,6.79,10.15,19.36,16.15,31.57,16.15h85.98c14.12,0,26.9-8.88,31.84-22.1l29.69-79.57c3.67-9.84,2.29-20.86-3.69-29.48v-.02h-.02ZM252.02,377.25c-.94,2.52-3.39,4.22-6.08,4.22h-83.45c-4.34,0-6.68-2.8-7.49-3.99s-2.5-4.43-.84-8.44l23.85-66.24c2.29-6.35,8.08-10.87,14.82-11.22.33-.02.67-.02,1.02-.02h75.41s12.51,1.42,9.29,14.61l-26.53,71.09h0ZM106.85,361.73s-22.36-11.59-17.66-32.66l29.67-82.23c4.78-13.25,17.36-22.09,31.45-22.09h95.02c6.25,0,12.1,3.03,15.71,8.14l13.89,19.68h-112.97c-8.7,0-16.49,5.41-19.52,13.57l-35.59,95.6h0ZM73.3,323.27s-22.37-11.59-17.66-32.66l29.67-82.23c4.79-13.25,17.37-22.09,31.45-22.09h89.91c6.25,0,12.1,3.03,15.71,8.14l13.89,19.68h-107.84c-8.7,0-16.49,5.41-19.52,13.57l-35.59,95.6h-.02Z" fill="#e85b75" /></svg>';diff --git a/examples/complex-explainer/packages/web-scenes/src/shared/pixel-type.js b/examples/complex-explainer/packages/web-scenes/src/shared/pixel-type.jsnew file mode 100644index 00000000..049580ca--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/shared/pixel-type.js@@ -0,0 +1,45 @@+// Small project-owned bitmap lettering for the closing card.+const glyphs = {+ C: ["01110", "10001", "10000", "10000", "10000", "10001", "01110"],+ A: ["01110", "10001", "10001", "11111", "10001", "10001", "10001"],+ I: ["111", "010", "010", "010", "010", "010", "111"],+ a: ["00000", "00000", "01110", "00001", "01111", "10001", "01111"],+ b: ["10000", "10000", "10110", "11001", "10001", "10001", "11110"],+ c: ["00000", "00000", "01110", "10001", "10000", "10001", "01110"],+ d: ["00001", "00001", "01101", "10011", "10001", "10001", "01111"],+ e: ["00000", "00000", "01110", "10001", "11111", "10000", "01110"],+ f: ["00110", "01001", "01000", "11100", "01000", "01000", "01000"],+ g: ["00000", "01111", "10001", "10001", "01111", "00001", "01110"],+ h: ["10000", "10000", "10110", "11001", "10001", "10001", "10001"],+ i: ["1", "0", "1", "1", "1", "1", "1"],+ l: ["10", "10", "10", "10", "10", "10", "01"],+ n: ["00000", "00000", "10110", "11001", "10001", "10001", "10001"],+ o: ["00000", "00000", "01110", "10001", "10001", "10001", "01110"],+ r: ["00000", "00000", "10110", "11001", "10000", "10000", "10000"],+ s: ["00000", "00000", "01111", "10000", "01110", "00001", "11110"],+ t: ["0100", "0100", "1111", "0100", "0100", "0101", "0010"],+ v: ["00000", "00000", "10001", "10001", "10001", "01010", "00100"],+ w: ["00000", "00000", "10001", "10001", "10101", "10101", "01010"],+ y: ["00000", "00000", "10001", "10001", "01111", "00001", "01110"],+ ".": ["0", "0", "0", "0", "0", "1", "1"],+ " ": ["000", "000", "000", "000", "000", "000", "000"],+};+export function pixelType(text) {+ let x = 0;+ const letters = [...text]+ .map((letter, index) => {+ const rows = glyphs[letter];+ if (!rows) throw Error("Missing closing-card glyph: " + letter);+ const rects = rows+ .flatMap((row, y) =>+ [...row].flatMap((bit, i) =>+ bit === "1" ? `<rect x="${x + i}" y="${y}" width="1" height="1"/>` : [],+ ),+ )+ .join("");+ x += rows[0].length + 1;+ return `<g class="pixel-letter" data-letter="${index}">${rects}</g>`;+ })+ .join("");+ return `<svg viewBox="0 0 ${x - 1} 7" role="img" aria-label="${text}" shape-rendering="crispEdges" fill="currentColor">${letters}</svg>`;+}diff --git a/examples/complex-explainer/packages/web-scenes/src/shared/route-cards.js b/examples/complex-explainer/packages/web-scenes/src/shared/route-cards.jsnew file mode 100644index 00000000..8a54c648--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/shared/route-cards.js@@ -0,0 +1,105 @@+export const routeCardsHtml = `+<div class="routes"+ ><div class="route route-editor"+ ><div class="route-face"+ ><div class="selection-sweep" aria-hidden="true"></div+ ><svg class="route-icon" viewBox="0 0 180 90">+ <g fill="none" stroke="currentColor" stroke-width="3">+ <rect x="4" y="4" width="172" height="82" rx="4" />+ <path d="M4 27H176M25 27V86" />+ <path d="M38 43H105M60 58H150M38 74H122" stroke-width="9" />+ <path d="M117 21V83" stroke="#e83f5f" stroke-width="2" />+ </g></svg+ ><b>剪辑软件</b><div class="route-line"></div></div></div+ ><div class="versus"><span>VS</span></div+ ><div class="route route-code"+ ><div class="route-face"+ ><div class="braces"></></div><b>代码</b><div class="route-line"></div></div></div+></div>`;+export const routeCardsCss = `.routes {+ position: absolute;+ left: 50px;+ top: 710px;+ width: 980px;+ height: 390px;+ transform-style: preserve-3d;+ perspective: 1600px;+ transform-origin: center center;+ z-index: 30;+}+.route {+ position: absolute;+ width: 420px;+ height: 350px;+ transform-style: preserve-3d;+}+.route-editor {+ left: 0;+ --rim: #2b1f30;+}+.route-code {+ right: 0;+ --rim: #2b1f30;+}+.route-face {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ border: 5px solid var(--ink);+ border-radius: 14px;+ background: var(--lilac);+ box-shadow: 12px 14px 0 var(--ink);+}+.route-editor .route-face{overflow:hidden}+.selection-sweep{position:absolute;inset:-15% auto -15% 0;width:110px;pointer-events:none;background:repeating-linear-gradient(0deg,#fff5db99 0 12px,transparent 12px 18px);clip-path:polygon(0 0,65% 0,65% 12%,80% 12%,80% 35%,100% 35%,100% 65%,80% 65%,80% 85%,65% 85%,65% 100%,0 100%);opacity:0}+.route-code .route-face {+ border: 5px solid var(--ink);+ border-radius: 14px;+ background: var(--lilac);+ box-shadow: 12px 14px 0 var(--ink);+}+.route small {+ font: 21px monospace;+ letter-spacing: 5px;+ color: var(--rim);+ position: absolute;+ top: 28px;+}+.route b {+ margin-top: 15px;+ font-family: monospace;+ font-weight: 900;+ font-size: 65px;+ text-shadow: none;+ color: var(--ink);+}+.route-icon {+ width: 185px;+ height: 93px;+ margin-top: 15px;+ color: var(--ink);+}+.braces {+ font: 100px/1.1 monospace;+ margin-top: 15px;+ color: var(--ink);+}+.route-line {+ position: absolute;+ bottom: 20px;+ width: 80%;+ background: var(--ink);+ height: 3px;+}+.versus {+ position:absolute;left:420px;top:0;width:140px;height:350px;+ display:grid;place-items:center;z-index:2;color:var(--ink);+}+.versus span{display:grid;place-items:center;width:96px;height:86px;font:900 38px/1 Menlo,monospace;letter-spacing:-3px;background:#fff5db;border:4px solid var(--ink);border-radius:8px;box-shadow:5px 6px 0 var(--ink);transform:rotate(-3deg)}+.versus::before,.versus::after{content:"";position:absolute;top:164px;border-top:10px solid transparent;border-bottom:10px solid transparent}+.versus::before{left:0;border-left:14px solid var(--ink)}+.versus::after{right:0;border-right:14px solid var(--ink)}+`;diff --git a/examples/complex-explainer/packages/web-scenes/src/shared/scene-styles.js b/examples/complex-explainer/packages/web-scenes/src/shared/scene-styles.jsnew file mode 100644index 00000000..cba05662--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/shared/scene-styles.js@@ -0,0 +1,112 @@+export const scene_styles = `:scope {+ pointer-events: none;+ color: #fff1d2;+ overflow: hidden;+ background: #fce5ee;+}+.backdrop {+ position: absolute;+ inset: -12%;+ filter: blur(24px) brightness(0.32);+ transform: scale(1.12);+ overflow: hidden;+}+.backdrop-pane {+ position: absolute;+ top: 0;+ bottom: 0;+ opacity: 0;+ overflow: hidden;+}+.backdrop-pane > * {+ object-fit: cover !important;+}+.backdrop-wash {+ position: absolute;+ inset: 0;+ background: linear-gradient(+ 180deg,+ #6d375625 0%,+ #6d375615 50%,+ #47253bc9 100%+ );+}+.font-resource {+ position: absolute;+ width: 1px;+ height: 1px;+ opacity: 0;+ overflow: hidden;+}+.heading {+ display: none;+ position: absolute;+ left: 27%;+ top: 18.8%;+ width: 44%;+ text-align: center;+ z-index: 4;+}+.heading b {+ display: block;+ font-size: 100px;+ line-height: 1.1;+ background: linear-gradient(+ 175deg,+ #fff8dd 3%,+ #d4b088 37%,+ #fff1c7 49%,+ #755041 52%,+ #d7b68a 86%,+ #fff0cf+ );+ background-clip: text;+ -webkit-background-clip: text;+ -webkit-text-fill-color: transparent;+ -webkit-text-stroke: 1px #e9c9a4;+ filter: drop-shadow(0 3px 1px #35211a) drop-shadow(0 0 12px #dfae6440);+}+.heading small {+ display: block;+ font-size: 31px;+ letter-spacing: 2px;+ margin-top: 30px;+ color: #ecd9b6;+}+.stage {+ position: absolute;+ left: 0;+ right: 0;+ top: 565px;+ height: 770px;+}+.phase {+ position: absolute;+ inset: 0;+ opacity: 0;+ overflow: hidden;+}+.screen {+ position: absolute;+ inset: 0;+ background: transparent;+ overflow: hidden;+}+.screen > * {+ object-fit: cover !important;+}+.line {+ position: absolute;+ left: 0;+ right: 0;+ height: 1px;+ background: linear-gradient(90deg, #deb79c11, #e5c292aa, #deb79c11);+}+.mesh {+ position: absolute;+ inset: 0;+ background: repeating-conic-gradient(#fff 0 25%, transparent 0 50%);+ background-size: 8px 8px;+ opacity: 0.018;+}+`;diff --git a/examples/complex-explainer/packages/web-scenes/src/shared/scene.js b/examples/complex-explainer/packages/web-scenes/src/shared/scene.jsnew file mode 100644index 00000000..115ca505--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/shared/scene.js@@ -0,0 +1,165 @@+import { terminalSetup } from "./terminal.js";+import { scene_styles } from "./scene-styles.js";+import { sealVisualTrack } from "@hypit/hypit/composition";+import { browserProgram } from "@hypit/hypit/hyperframes";+import { assertTemporalWindowFor } from "@hypit/hypit/temporal";+const styles = (o) => Object.entries(o).map(([name, value]) => ({ name, value }));+export function scene(t, c, w, font, o, html, css, setup, events, entries, extra = {}) {+ assertTemporalWindowFor(w, { subjectId: o.id, space: t });+ const beats = Object.fromEntries(events.map((e) => [e.name, e.at.frame - w.span.startFrame]));+ const count = w.span.endFrameExclusive - w.span.startFrame;+ const backgrounds = [];+ entries = { ...entries };+ for (const [id, v] of Object.entries(entries)) {+ if (!v.media || !v.backdrop) continue;+ const key = "backdrop-" + id;+ entries[key] = { ...v, backdrop: false };+ backgrounds.push({+ id: key,+ start: v.start ?? 0,+ end: v.end ?? count,+ left: v.backdrop.left ?? 0,+ width: v.backdrop.width ?? 100,+ });+ }+ const backHtml =+ '<div class="backdrop">' ++ backgrounds+ .map(+ (v) =>+ `<div class="backdrop-pane" data-back="${v.id}" style="left:${v.left}%;width:${v.width}%">{{${v.id}}}</div>`,+ )+ .join("") ++ '</div><div class="backdrop-wash"></div>';+ const children = Object.entries(entries).map(([id, v], n) => {+ const shared = {+ id,+ parent: "scene",+ order: n + 2,+ style: styles({ width: "100%", height: "100%", "object-fit": "contain" }),+ };+ if (v.image) return { ...shared, kind: "image", artifact: v.image };+ const m = v.media,+ src = m.timeline.frameRate,+ start = Math.max(0, v.start ?? 0),+ end = Math.min(count, v.end ?? count);+ if (!m.visual) throw Error(id + " requires prepared picture");+ const rate = {+ numerator: src.numerator * t.frameRate.denominator * (v.rate?.numerator ?? 1),+ denominator: src.denominator * t.frameRate.numerator * (v.rate?.denominator ?? 1),+ };+ if (+ !v.loop &&+ !v.holdLast &&+ ((end - start - 1) * rate.numerator) / rate.denominator >= m.timeline.frameCount+ )+ throw Error(id + " source is too short");+ return {+ ...shared,+ kind: "video",+ artifact: m.visual.artifact,+ muted: true,+ sampling: {+ sourceFrameRate: src,+ sourceFrameCount: m.timeline.frameCount,+ segments: v.holdLast+ ? (() => {+ const played = Math.min(+ end - start,+ Math.ceil((m.timeline.frameCount * rate.denominator) / rate.numerator),+ ),+ segments = [+ {+ target: { startFrame: start, endFrameExclusive: start + played },+ sourceFrame: { numerator: 0, denominator: 1 },+ rate,+ },+ ];+ if (start + played < end)+ segments.push({+ target: { startFrame: start + played, endFrameExclusive: end },+ sourceFrame: { numerator: m.timeline.frameCount - 1, denominator: 1 },+ rate: { numerator: 0, denominator: 1 },+ });+ return segments;+ })()+ : v.loop+ ? Array.from(+ {+ length: Math.ceil(+ (end - start) /+ Math.floor((m.timeline.frameCount * rate.denominator) / rate.numerator),+ ),+ },+ (_, i) => {+ const n = Math.floor((m.timeline.frameCount * rate.denominator) / rate.numerator),+ a = start + i * n;+ return {+ target: { startFrame: a, endFrameExclusive: Math.min(end, a + n) },+ sourceFrame: { numerator: 0, denominator: 1 },+ rate,+ };+ },+ )+ : [+ {+ target: { startFrame: start, endFrameExclusive: end },+ sourceFrame: { numerator: 0, denominator: 1 },+ rate,+ },+ ],+ },+ };+ });+ return sealVisualTrack({+ id: o.id,+ programSpaceId: t.id,+ visualIr: "hypit.visual-ir@1",+ presents: [+ {+ id: o.id,+ span: w.span,+ stacking: { order: o.z, tieBreak: o.id },+ elements: [+ {+ id: "scene",+ kind: "program",+ order: 0,+ program: browserProgram({+ html: backHtml + html + '<div class="font-resource">{{font}}</div>',+ css: base + css,+ data: {+ beats,+ fps: t.frameRate.numerator / t.frameRate.denominator,+ count,+ backgrounds,+ ...extra,+ },+ setup:+ terminalSetup ++ `root.style.fontFamily=getComputedStyle(root.querySelector('.font-resource>*')).fontFamily;const clamp=x=>Math.max(0,Math.min(1,x)),ease=x=>1-Math.pow(1-clamp(x),3);const fade=(f,a,z,n=10)=>(a===0?1:ease((f-a)/n))*(z>=data.count?1:clamp((z-f)/n));const paintBackdrop=f=>{for(const b of data.backgrounds){root.querySelector('[data-back="'+b.id+'"]').style.opacity=String(fade(f,b.start,b.end,12));}};` ++ setup,+ }),+ style: styles({+ position: "absolute",+ inset: 0,+ width: c.widthPx + "px",+ height: c.heightPx + "px",+ }),+ },+ {+ id: "font",+ parent: "scene",+ kind: "text",+ order: 1,+ text: "Hypit 字",+ fonts: [font],+ style: styles({ "font-size": "12px" }),+ },+ ...children,+ ],+ },+ ],+ });+}+const base = scene_styles;diff --git a/examples/complex-explainer/packages/web-scenes/src/shared/studio-art.js b/examples/complex-explainer/packages/web-scenes/src/shared/studio-art.jsnew file mode 100644index 00000000..b65af344--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/shared/studio-art.js@@ -0,0 +1,462 @@+import { hypitSymbol } from "./brand-marks.js";+export const studioBar = () =>+ `<div class="hs-bar"><div class="hs-brand">${hypitSymbol}<b>Hypit</b></div><span>Studio</span><span>main.svml</span><i>◧</i><i>◇</i><i>×</i></div>`;+export const inspector = () =>+ `<aside class="hs-inspector"><div class="hs-tab">Where When How</div><div class="hs-inspect-body"><b>Transform</b><div class="hs-fields"><span>X 50</span><span>Y 50</span><span>W 100</span><span>H 100</span></div><b>Appearance</b><div class="hs-swatches"><i></i><i></i><i></i><i></i></div><div class="hs-slider"><i></i></div><div class="hs-slider short"><i></i></div><b>Typography</b><div class="hs-select">Mono ⌄</div><div class="hs-align">≡ ≡ ≡</div></div></aside>`;+export const librarySide = () =>+ `<aside class="hs-library"><div class="hs-tab">Components ▦</div><div class="hs-library-grid">${["CC", "▤", "▥", "◇"].map((v, i) => `<div><b>${v}</b><span>${["Caption", "Ranking", "Chart", "Card"][i]}</span></div>`).join("")}</div><div class="hs-mini-code"><Film><br> <Track /><br> <Track /><br></Film></div></aside>`;+export const miniTimeline = () =>+ `<div class="hs-timeline"><div class="hs-tab">Timeline <span>00:00 00:05 00:10</span></div>${["Performance", "Caption", "MG"].map((v, i) => `<div class="hs-lane"><b>${v}</b><div><i class="hs-clip clip-${i}"></i><i class="hs-clip small clip-${i}"></i></div></div>`).join("")}<div class="hs-playhead"></div></div>`;+export function faceless(index = 0) {+ const cloth = ["#fff8ef", "#f7c7d9", "#d9cef2"][index],+ shade = ["#e4dce5", "#df9eba", "#b8a5d7"][index],+ navy = ["#35384f", "#69445b", "#4a4169"][index];+ return `+<svg class="faceless" viewBox="0 0 360 640">+ <rect width="360" height="640" fill="${["#eddae1", "#f0dfe5", "#e6ddf0"][index]}" />+ <path+ d="M0 85H75V107H0M280 60H360V82H280M0 530H80V547H0"+ stroke="#fff9ed"+ stroke-width="8"+ opacity=".75"+ />+ <path+ d="M311 497V285M311 355Q275 322 278 296M312 394Q346 347 347 325"+ fill="none"+ stroke="#b49ab7"+ stroke-width="8"+ />+ <rect x="283" y="471" width="61" height="77" rx="5" fill="#bea1b6" />+ <g class="faceless-person">+ <path+ d="M90 303Q61 218 103 135Q124 98 183 98Q250 98 265 158Q285 229 264 322L284 460Q256 482 231 448H104Q69 468 65 416Z"+ fill="#342d36"+ stroke="#4d3944"+ stroke-width="4"+ />+ <path+ d="M43 640L51 373Q58 321 129 311L232 311Q300 320 307 373L324 640"+ fill="${cloth}"+ stroke="#806b80"+ stroke-width="3"+ />+ <path+ d="M63 378Q47 466 42 558L62 640H119L109 433M262 378L288 548L269 640H324"+ fill="${shade}"+ opacity=".52"+ />+ <path d="M151 273V324L181 352L212 324V273" fill="#f4cbb8" />+ <path+ d="M147 320L181 379L217 320L251 331L236 438L181 414L126 438L105 331Z"+ fill="${navy}"+ stroke="#615365"+ stroke-width="2"+ />+ <path+ d="M111 336L133 426L180 402L229 426L245 336"+ fill="none"+ stroke="${cloth}"+ stroke-width="6"+ />+ <path d="M144 331L180 394L217 332L210 432L180 481L150 432Z" fill="#f4cbb8" />+ <path+ d="M139 439L153 640M222 439L210 640"+ fill="none"+ stroke="${navy}"+ stroke-width="8"+ />+ <path+ d="M58 340L113 326L121 347L68 364Z M249 328L304 343L294 366L240 349Z"+ fill="${navy}"+ stroke="#534957"+ stroke-width="2"+ />+ <path+ d="M72 337L81 359M87 333L96 355M102 329L110 350M253 332L245 352M269 336L261 357M284 340L276 361"+ stroke="#dfc27a"+ stroke-width="6"+ />+ <ellipse cx="181" cy="221" rx="63" ry="86" fill="#f4cbb8" />+ <path+ d="M109 189Q107 135 147 125L205 126Q244 137 254 191Q220 181 211 156Q192 183 140 191L119 234Z"+ fill="#342d36"+ />+ <path+ d="M120 187Q95 283 115 383Q123 426 99 475Q142 491 147 448Q150 420 137 389Q112 324 137 261Z"+ fill="#3a3038"+ />+ <path+ d="M111 274Q102 360 127 411Q139 454 114 467"+ fill="none"+ stroke="#5c454e"+ stroke-width="5"+ />+ <path d="M240 180Q273 242 250 321L269 389Q243 409 230 388L225 285Z" fill="#332d35" />+ <path+ d="M82 149Q63 117 94 91Q102 69 137 74Q170 47 207 66Q240 64 258 84Q294 91 283 130L275 159Z"+ fill="${cloth}"+ stroke="#786a79"+ stroke-width="3"+ />+ <path+ d="M89 127Q180 108 275 136L272 165Q175 143 90 164Z"+ fill="${navy}"+ stroke="#282b3b"+ stroke-width="3"+ />+ <path d="M93 151Q183 129 271 155" fill="none" stroke="#e6cb85" stroke-width="6" />+ <path+ d="M90 164Q172 129 270 165L252 181Q178 158 112 182Z"+ fill="#303346"+ stroke="#73677a"+ stroke-width="3"+ />+ <g+ transform="translate(182 96)"+ fill="none"+ stroke="#dec274"+ stroke-width="5"+ stroke-linecap="round"+ stroke-linejoin="round"+ >+ <circle cy="-11" r="6" />+ <path d="M0-5V21M-12 3H12M-23 10Q-22 26 0 28Q22 26 23 10M-23 10L-25 19M23 10L25 19" />+ </g>+ <path d="M244 261V285" stroke="#eee7df" stroke-width="3" />+ <path d="M244 279L250 287L244 295L238 287Z" fill="#fff9df" stroke="#b9a7a9" stroke-width="2" />+ <circle cx="230" cy="388" r="5" fill="#dfc17d" />+ <circle cx="225" cy="404" r="5" fill="#dfc17d" />+ <path d="M87 552H271L299 640H58Z" fill="${cloth}" stroke="#b6a7b9" stroke-width="2" />+ <path+ d="M114 558L97 640M148 558L142 640M188 558L195 640M226 558L249 640"+ stroke="${shade}"+ stroke-width="5"+ />+ <g transform="rotate(6 178 420)">+ <rect x="164" y="357" width="27" height="188" rx="7" fill="#303038" />+ <rect+ x="145"+ y="302"+ width="65"+ height="94"+ rx="29"+ fill="#272933"+ stroke="#59505b"+ stroke-width="2"+ />+ <text+ x="177"+ y="353"+ text-anchor="middle"+ font-size="13"+ font-family="monospace"+ fill="#fff7f1"+ font-weight="bold"+ >+ HYPIT+ </text>+ <path+ d="M160 416Q155 392 166 389L187 389Q202 394 201 410L196 451L173 476L156 453Z"+ fill="#f4cbb8"+ stroke="#c19e91"+ stroke-width="2"+ />+ <path+ d="M167 403L191 407M166 414L191 417M167 425L188 427"+ stroke="#d5ac9c"+ stroke-width="2"+ />+ </g>+ <g class="faceless-hand">+ <path+ d="M282 548L260 485L255 450L243 424Q240 412 247 410L263 431L265 392Q271 381 277 395L279 426L285 404Q290 396 294 404L294 434Q309 446 306 464L299 489L313 540Z"+ fill="#f4cbb8"+ stroke="#c09b91"+ stroke-width="2"+ />+ <path d="M269 430L281 448M294 434L291 455" fill="none" stroke="#d3aa9b" stroke-width="2" />+ </g>+ </g>+</svg>`;+}+export const studioCss = `+.hs-window {+ position: absolute;+ left: 35px;+ top: 650px;+ width: 1010px;+ height: 750px;+ background: #f8e8f0;+ border: 4px solid #39283a;+ border-radius: 9px;+ box-shadow: 11px 13px #39283a;+ overflow: hidden;+}+.hs-bar {+ height: 52px;+ display: flex;+ align-items: center;+ gap: 28px;+ border-bottom: 3px solid #39283a;+ background: #f1a8ca;+ padding: 0 16px;+ font:+ 21px Menlo,+ monospace;+}+.hs-brand {+ display: flex;+ align-items: center;+ gap: 8px;+}+.hs-brand svg {+ width: 30px;+ height: 30px;+}+.hs-bar > span:nth-of-type(1) {+ background: #fff0f7;+ border: 2px solid #9b668b;+ padding: 4px 10px;+ border-radius: 4px;+}+.hs-bar > span:nth-of-type(2) {+ color: #754e6b;+ font-size: 18px;+}+.hs-bar > i:first-of-type {+ margin-left: auto;+}+.hs-bar > i {+ font-style: normal;+}+.hs-tab {+ height: 37px;+ padding: 8px 12px;+ background: #ecd6e4;+ border-bottom: 2px solid #b99bae;+ font:+ 17px Menlo,+ monospace;+ color: #69475e;+}+.hs-library {+ position: absolute;+ top: 52px;+ bottom: 226px;+ width: 250px;+ background: #f9edf4;+ border-right: 2px solid #b99bae;+}+.hs-library-grid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 15px;+ padding: 18px 14px;+}+.hs-library-grid > div {+ text-align: center;+ font: 15px monospace;+}+.hs-library-grid b {+ height: 60px;+ display: flex;+ align-items: center;+ justify-content: center;+ background: #ecd8f3;+ border: 2px solid #a078a2;+ box-shadow: 3px 4px #d0b2c9;+ font-size: 32px;+ color: #8a628e;+}+.hs-library-grid span {+ display: block;+ margin-top: 9px;+}+.hs-mini-code {+ margin: 18px;+ color: #b18aa9;+ font: 19px/1.65 monospace;+}+.hs-inspector {+ position: absolute;+ right: 0;+ top: 52px;+ bottom: 226px;+ width: 240px;+ background: #f9edf4;+ border-left: 2px solid #b99bae;+}+.hs-inspect-body {+ padding: 18px 14px;+ font: 16px monospace;+}+.hs-inspect-body > b {+ display: block;+ margin: 8px 0 16px;+ color: #755a70;+}+.hs-fields {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 9px;+ margin-bottom: 22px;+}+.hs-fields span,+.hs-select {+ padding: 8px;+ background: #f0e0ec;+ border: 1px solid #c5a8bc;+ border-radius: 3px;+}+.hs-swatches {+ display: flex;+ gap: 10px;+ margin: 12px 0;+}+.hs-swatches i {+ width: 29px;+ height: 29px;+ background: #e797be;+ border: 2px solid #9a6d8a;+}+.hs-swatches i:nth-child(2) {+ background: #cab0e8;+}+.hs-swatches i:nth-child(3) {+ background: #f2d097;+}+.hs-swatches i:nth-child(4) {+ background: #fff3e7;+}+.hs-slider {+ height: 4px;+ background: #c4a2ba;+ margin: 24px 4px;+ position: relative;+}+.hs-slider i {+ position: absolute;+ left: 65%;+ top: -6px;+ width: 15px;+ height: 15px;+ background: #fff4ef;+ border: 2px solid #a86c98;+ border-radius: 3px;+}+.hs-slider.short i {+ left: 30%;+}+.hs-align {+ margin: 20px 0;+}+.hs-preview-label {+ position: absolute;+ left: 250px;+ right: 240px;+ top: 52px;+}+.hs-preview-matte {+ position: absolute;+ left: 250px;+ right: 240px;+ top: 89px;+ bottom: 226px;+ background: #e5cede;+ background-image: radial-gradient(#ba93b0 1px, transparent 1px);+ background-size: 16px 16px;+}+.hs-timeline {+ position: absolute;+ left: 0;+ right: 0;+ bottom: 0;+ height: 226px;+ border-top: 3px solid #98738f;+ background: #f8eaf3;+}+.hs-timeline .hs-tab span {+ margin-left: 110px;+}+.hs-lane {+ display: flex;+ align-items: center;+ height: 51px;+ border-bottom: 1px solid #e1c9da;+ font: 17px monospace;+}+.hs-lane > b {+ width: 155px;+ padding: 0 13px;+ color: #805b75;+}+.hs-lane > div {+ display: flex;+ gap: 7px;+ width: 800px;+}+.hs-clip {+ display: block;+ width: 470px;+ height: 32px;+ border: 2px solid #94749c;+ background: #d8c0ed;+ border-radius: 3px;+}+.hs-clip.small {+ width: 165px;+}+.hs-clip.clip-1 {+ background: #e8c680;+ border-color: #b39b60;+ width: 280px;+}+.hs-clip.clip-2 {+ background: #f3b7d6;+ border-color: #b884a9;+ width: 330px;+}+.hs-playhead {+ position: absolute;+ left: 300px;+ top: 38px;+ bottom: 0;+ border-left: 3px solid #e85f89;+}+.faceless {+ width: 100%;+ height: 100%;+ display: block;+}+.faceless-hand {+ transform-origin: 285px 500px;+}+.hs-handle {+ height: 14px;+ position: absolute;+ left: 0;+ right: 0;+ top: -8px;+ cursor: ns-resize;+}+.hs-handle:after {+ content: "";+ position: absolute;+ width: 90px;+ height: 5px;+ border-radius: 3px;+ background: #a5819c;+ left: 45%;+ top: 4px;+}+`;+export const portraitMotion = `+$$(".faceless-person").forEach(+ (el, i) =>+ (el.style.transform =+ "translateY(" + Math.sin(f * 0.045 + i) * 2 + "px)"),+);+$$(".faceless-hand").forEach(+ (el, i) =>+ (el.style.transform = "rotate(" + Math.sin(f * 0.08 + i) * 7 + "deg)"),+);`;diff --git a/examples/complex-explainer/packages/web-scenes/src/shared/terminal.js b/examples/complex-explainer/packages/web-scenes/src/shared/terminal.jsnew file mode 100644index 00000000..ddc54016--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/shared/terminal.js@@ -0,0 +1,6 @@+export const terminalSetup = `+function paintTerminal(pre, text, characters) {+ const content = text.slice(0, Math.max(0, Math.floor(characters)));+ if (pre.textContent !== content) pre.textContent = content;+ pre.scrollTop = pre.scrollHeight;+}`;diff --git a/examples/complex-explainer/packages/web-scenes/src/shared/workshop-language.js b/examples/complex-explainer/packages/web-scenes/src/shared/workshop-language.jsnew file mode 100644index 00000000..88ce9931--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/shared/workshop-language.js@@ -0,0 +1,288 @@+import { hypitSymbol } from "./brand-marks.js";+export const bar = (label) =>+ `<div class="work-bar"><i></i><i></i><i></i><span>${label}</span><b>×</b></div>`;+export const pointer = `<div class="work-pointer"><svg viewBox="0 0 60 76"><path d="M6 4L51 37L30 42L21 67Z" fill="#fff8ef" stroke="#382535" stroke-width="4"/><path d="M14 18L32 36L25 39L21 47Z" fill="#f39cbd"/></svg><div>${hypitSymbol}</div></div>`;+export const tiles = () =>+ ["字幕", "榜单", "图表", "卡片"]+ .map(+ (name, i) =>+ `+<div class="effect-tile effect-tile-${i}"+ ><div class="tile-cap">${name}<span></></span></div+ ><div class="tile-art">${+ [+ '<div class="demo-caption"><span>MAKE</span><span>IT</span><span>YOURS</span></div>',+ '<div class="demo-ranking"><i>01 <b>Hypit</b></i><i>02 <b>Creatify</b></i><i>03 <b>Higgsfield</b></i></div>',+ '<div class="demo-chart"><i></i><i></i><i></i><i></i><i></i></div>',+ '<div class="demo-card"><span>★</span><b>HELLO!</b><i>MAKE SOMETHING GREAT</i></div>',+ ][i]+ }</div><div class="tile-corners"></div+></div>`,+ )+ .join("");+export const workCss = `+:scope {+ background: transparent;+ color: #382535;+ font-family: Menlo, monospace !important;+}+.backdrop,+.backdrop-wash {+ display: none;+}+.work-ground {+ position: absolute;+ inset: 0;+ background-color: #fce5ee;+ background-image: radial-gradient(#efb8cf 1.6px, transparent 1.6px);+ background-size: 28px 28px;+}+.work-window {+ position: absolute;+ left: 35px;+ top: 540px;+ width: 1010px;+ background: #fff4fa;+ border: 4px solid #382535;+ border-radius: 9px;+ box-shadow: 11px 13px 0 #382535;+ overflow: hidden;+}+.work-bar {+ height: 52px;+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 0 17px;+ background: #f5acd0;+ border-bottom: 3px solid #382535;+ font:+ 22px Menlo,+ monospace;+}+.work-bar i {+ height: 12px;+ width: 12px;+ border: 2px solid #382535;+ background: #fff5df;+}+.work-bar i:nth-child(2) {+ background: #cbb3ed;+}+.work-bar i:nth-child(3) {+ background: #eaca7a;+}+.work-bar span {+ margin-left: 18px;+}+.work-bar b {+ margin-left: auto;+}+.work-pointer {+ position: absolute;+ left: 0;+ top: 0;+ width: 65px;+ height: 82px;+ z-index: 60;+ filter: drop-shadow(3px 4px #38253533);+}+.work-pointer > svg {+ width: 100%;+ height: 100%;+}+.work-pointer > div {+ position: absolute;+ left: 37px;+ top: 45px;+ width: 44px;+ height: 44px;+ border: 3px solid #382535;+ border-radius: 50%;+ background: #fff7ec;+ padding: 6px;+}+.work-pointer > div svg {+ width: 100%;+ height: 100%;+}+.effect-tile {+ position: absolute;+ width: 415px;+ height: 270px;+ border: 4px solid #382535;+ border-radius: 8px;+ box-shadow: 8px 9px 0 #382535;+ background: #fff8ea;+ transform-origin: top left;+ overflow: hidden;+}+.tile-cap {+ height: 42px;+ background: #e8d9f4;+ border-bottom: 3px solid #382535;+ padding: 6px 15px;+ font: 23px sans-serif;+ opacity: 0;+}+.tile-cap span {+ float: right;+ font: bold 24px monospace;+}+.tile-art {+ position: absolute;+ inset: 47px 12px 12px;+ display: flex;+ align-items: center;+ justify-content: center;+}+.tile-corners {+ position: absolute;+ inset: 5px;+ border: 3px dashed #b363a0;+ pointer-events: none;+ opacity: 0;+}+.demo-caption {+ display: flex;+ gap: 8px;+ transform: rotate(-5deg);+ font:+ bold 33px Menlo,+ monospace;+}+.demo-caption span {+ padding: 10px 6px;+ border-radius: 3px;+ color: #382535;+ text-shadow: 2px 2px #fff;+}+.demo-ranking {+ width: 88%;+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.demo-ranking i {+ display: block;+ background: #f6cee3;+ border: 2px solid #382535;+ padding: 7px 12px;+ font: 19px monospace;+}+.demo-ranking i:first-child {+ background: #ffdfa1;+}+.demo-ranking b {+ margin-left: 18px;+}+.demo-chart {+ display: flex;+ align-items: flex-end;+ gap: 20px;+ height: 150px;+ border-bottom: 3px solid #382535;+ width: 85%;+ justify-content: center;+}+.demo-chart i {+ display: block;+ width: 42px;+ height: 130px;+ background: #c5a0e9;+ border: 3px solid #382535;+ transform-origin: bottom;+}+.demo-chart i:nth-child(2n) {+ background: #f18ebc;+}+.demo-card {+ width: 260px;+ height: 155px;+ background: #ffbbd8;+ border: 4px solid #382535;+ box-shadow: 8px 9px #382535;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ transform: rotate(5deg);+}+.demo-card span {+ color: #fff1ab;+ font: 48px monospace;+ text-shadow: 3px 4px #382535;+}+.demo-card b {+ font: bold 28px monospace;+}+.demo-card i {+ font: 11px monospace;+}+.work-media {+ position: absolute;+ overflow: hidden;+}+.work-media > * {+ width: 100% !important;+ height: 100% !important;+ object-fit: cover !important;+}+.pixel-tag {+ background: #fff4d7;+ border: 3px solid #382535;+ box-shadow: 5px 6px #382535;+ padding: 10px 18px;+ font:+ 26px Menlo,+ monospace;+}+`;+export const workSetup = `+const $ = (s) => root.querySelector(s),+ $$ = (s) => [...root.querySelectorAll(s)],+ mix = (a, z, q) => a + (z - a) * q,+ smooth = (x) => {+ x = clamp(x);+ return x * x * (3 - 2 * x);+ },+ pop = (x) => {+ x = clamp(x);+ return 1 + 2.70158 * (x - 1) ** 3 + 1.70158 * (x - 1) ** 2;+ },+ show = (el, a) => {+ el.style.opacity = String(clamp(a));+ el.style.visibility = a > 0 ? "inherit" : "hidden";+ },+ move = (el, x, y, s = 1) =>+ (el.style.transform =+ "translate(" + x + "px," + y + "px) scale(" + s + ")");+const animateTiles = (f) => {+ $$(".demo-caption span").forEach((e, i) => {+ e.style.background =+ Math.floor(f / 12) % 3 === i ? "#f394c2" : "transparent";+ e.style.transform =+ "translateY(" + -4 * Math.max(0, Math.sin(f * 0.12 - i)) + "px)";+ });+ $$(".demo-ranking i").forEach(+ (e, i) =>+ (e.style.transform =+ "translateX(" + Math.sin(f * 0.05 + i) * 4 + "px)"),+ );+ $$(".demo-chart i").forEach(+ (e, i) =>+ (e.style.transform =+ "scaleY(" ++ (0.4 + 0.6 * (0.5 + 0.5 * Math.sin(f * 0.065 + i))) ++ ")"),+ );+ $$(".demo-card").forEach(+ (e) =>+ (e.style.transform =+ "rotate(" ++ Math.sin(f * 0.05) * 7 ++ "deg) translateY(" ++ Math.sin(f * 0.08) * 6 ++ "px)"),+ );+};`;diff --git a/examples/complex-explainer/packages/web-scenes/src/studio.js b/examples/complex-explainer/packages/web-scenes/src/studio.jsnew file mode 100644index 00000000..60c3bc1c--- /dev/null+++ b/examples/complex-explainer/packages/web-scenes/src/studio.js@@ -0,0 +1,61 @@+import { compositionTypes } from "@hypit/hypit/composition";+import { textLayer, temporalLineageFor } from "@hypit/hypit/studio-adapter";+const scenes = {+ ComponentWorkshop: ["Components in use", "Motion → components → library → another video"],+ SemanticWorkshop: ["Words drive motion", "Selection → reveal → revised words → following motion"],+ DeliveryWorkshop: ["From assets to a film", "Assets → result → sharing → reference callback"],+ CodeJourney: ["The coding route", "IDE → motion → rewrites → timing → Hypit"],+ Outro: ["Get Hypit", "GitHub → copy → install → characters → star"],+ Road: ["The editing route", "Editor → materials → motion → keyframes → generated sample"],+ Introduction: [+ "Introducing Hypit",+ "Homepage → code → installation → reference and replacement examples",+ ],+ Comparison: ["Competing tools", "Homepages → prices → templates → results → watermarks"],+};+export function sceneCompanions(module, tags) {+ return Object.entries(tags).map(([tag, spec]) => ({+ id: spec.name,+ role: "track",+ output: {+ type: compositionTypes.visualTrack,+ surface: spec.name,+ modules: [module],+ },+ family: "explainer-scenes",+ label: scenes[tag][0],+ tone: "violet",+ icon: "component",+ lane: { heightPx: 52 },+ bindings: [{ name: "z", writable: true, fallback: spec.defaults.z }],+ inspector: [+ {+ binding: "z",+ label: "Drawing order",+ domain: "where",+ section: { id: "stack", label: "Stacking" },+ control: "number",+ number: { step: 1 },+ },+ ],+ project(context) {+ return context.generic().map((e) => ({+ ...e,+ temporal: temporalLineageFor(context, context.placement.id, "window"),+ display: {+ title: scenes[tag][0],+ layers: [textLayer(scenes[tag][1])],+ },+ inspector: [+ {+ id: "sequence",+ label: "Sequence",+ domain: "how",+ section: { id: "scene", label: "Scene" },+ value: scenes[tag][1],+ },+ ],+ }));+ },+ }));+}diff --git a/examples/complex-explainer/productions/explainer/ASSET-PROVENANCE.md b/examples/complex-explainer/productions/explainer/ASSET-PROVENANCE.mdnew file mode 100644index 00000000..1c379a8c--- /dev/null+++ b/examples/complex-explainer/productions/explainer/ASSET-PROVENANCE.md@@ -0,0 +1,19 @@+# Asset provenance++The project owner confirmed the following for this production:++- The two competitor-case clips are demonstrations made by the project owner, not official samples supplied by those companies.+- The host image and voice are AI-generated material supplied or commissioned for this project.+- The drinking callback in the right-hand phone is a newly generated illustration of a fictional character. It replaces the reference creator’s live-action drinking clip in the active composition.++The original reference footage and earlier exports remain in private project history for study. They are not part of the intended public example media bundle. Other website captures, product marks and reference examples retain their actual sources; these categories should not be described collectively as AI-generated.++## Drinking illustration++File: `assets/final-half/drinking-illustration.png`++Created with the built-in image generation tool on 2026-09-14. Prompt: see `assets/final-half/drinking-illustration.prompt.txt`.++## Portrait waterfall++The branded bird portrait was replaced with an owner-supplied ordinary pigeon portrait. The replacement is incorporated in `assets/characters/portraits-0.webp`; the original character collection is not included in this example.diff --git a/examples/complex-explainer/productions/explainer/BRIEF.md b/examples/complex-explainer/productions/explainer/BRIEF.mdnew file mode 100644index 00000000..85fe8ab2--- /dev/null+++ b/examples/complex-explainer/productions/explainer/BRIEF.md@@ -0,0 +1,9 @@+# Hypit explainer++Produce a lively Chinese explanation of Hypit, using the reference’s alternating presenter and MG structure with the owner’s supplied AI presenter and voice. The accepted direction is pink retro pixel graphics, actual website demonstrations, clear comparisons and expressive full-frame moments.++The completed composition is 1080 × 1920, 30 fps, 4,112 frames (137.067 seconds). Seventeen prepared Takes supply the performance and its semantic anchors. An opening 1.5-second gap carries the four-image montage; a two-second tail carries the closing graphic without a fabricated Take.++This production is being organized as a complex spoken-video example. Preserve the accepted visual direction while making the Sources, project components and explicit material reuse understandable. Separate independent behavior; expose parameters only for actual author choices.++The owner confirmed the competitor-case demonstrations are their own work and the host image/voice are AI-generated. Replace the reference creator’s drinking footage with the fictional drinking illustration. See [asset provenance](ASSET-PROVENANCE.md).diff --git a/examples/complex-explainer/productions/explainer/CRAFT-NOTES.md b/examples/complex-explainer/productions/explainer/CRAFT-NOTES.mdnew file mode 100644index 00000000..22373fb3--- /dev/null+++ b/examples/complex-explainer/productions/explainer/CRAFT-NOTES.md@@ -0,0 +1,33 @@+# Lessons from the explainer++## Organize responsibility before exposing controls++A component is a useful owner of related behavior. Parameterization is a separate choice about what the author should vary; cross-project reuse is another choice about a demonstrated future need. The editor demonstration is one coherent scene because its folder, pointer and timeline respond to each other. Its exact pixel dimensions can remain internal. The background, Caption and presenter have independent reasons to change and deserve independent ownership.++## Give changes meaningful event names++The Script identifies the phrase that motivates a change. A scene receives events such as “install”, “examples” or “guess”; its code turns those events into local motion. Direct time and frame counts remain useful for transition duration, silent endings and fast montages. This lets timing move with accepted performance without rewriting every animation timestamp.++## Material quality starts in direction++Voice reference, Script and Action establish the intended performance. Useful direction describes an attitude the audience can hear and see, supported by a few decisive expressions or gestures. A generated actor’s request should describe the actual performance; a metaphor about graphics flying into frame belongs in component direction. Composition review then improves framing, Caption, coverage and event timing around accepted materials.++## Preserve complete visual systems when changing style++Removing redundant text does not remove the need for visual detail. When the treatment changed to pink retro graphics, folder contents, editor controls and terminal activity still had to fill their roles. A shared palette made coherent updates possible; local scene code retained the details that explained each idea.++## Write motion that can be sought directly++A pointer follows an eased path; a rejected drag shares the picture’s spring displacement; typing derives its visible tail from time. None requires playback of all preceding frames. This makes exact-frame review and range rendering normal operations. A low-resolution Canvas flag was a better match for the chosen pixel language than preserving an elaborate cloth simulation.++## Use Studio to discuss intentions++Many valuable comments describe a new visual idea, not a number a user can edit. Time-stamped comments kept that discussion attached to the picture. Companions expose only useful identifiers, timing and directing controls, through Studio’s common interfaces. A coordinated scene does not need controls for every internal measurement.++## Preserve accepted outputs and readable authoring++Run Candidates express which existing material to carry forward. Build execution handles the remaining work. Keep explicit output boundaries where the Run needs to select them; separate Script and direction without hiding those boundaries. Archive obsolete experiments so the active entry is evident. Keep CSS and frame programs readable rather than compressing a complete scene into a single enormous string.++## Export for the machine actually available++The full film temporarily exceeded local disk capacity while lossless frames accumulated. Consecutive range renders bounded temporary storage; eight workers handled each range and the output parts were joined. This is a production workaround for this machine, not a requirement for every video or a new rendering abstraction.diff --git a/examples/complex-explainer/productions/explainer/README.md b/examples/complex-explainer/productions/explainer/README.mdnew file mode 100644index 00000000..e2d312c2--- /dev/null+++ b/examples/complex-explainer/productions/explainer/README.md@@ -0,0 +1,47 @@+# Complex spoken explainer++A 137-second Chinese explainer built from 17 accepted Takes, recorded demonstrations, project-owned MG, independent Caption and sound. The example demonstrates useful component boundaries without turning every design constant into a public parameter.++## Start here++From this production directory:++```sh+hypit check runs/render.svrun+hypit plan runs/render.svrun+hypit studio --run runs/render.svrun+```++The current production Run explicitly selects accepted Outputs. Read the plan before submitting a Build: composition edits should retain that selected material. The included local-only Profile is sufficient for opening and rendering this accepted work.++## Where an edit belongs++| Edit | Owner |+| --- | --- |+| Spoken words, cue breaks, Moments and Selections | `authors/script.svml` |+| Input images, recordings, fonts and clock/canvas | `authors/assets.svml` |+| Performance prompt and selected speaker Kit | `authors/direction.svml`, `recipes/performance.svs` |+| Material outputs, Take placement, Uses, scene events and Film | `authors/main.svml` |+| Caption appearance and ordinary presentation | `recipes/composition.svs` |+| A coordinated visual behavior | The owning project package under `../../packages/` |+| Which accepted output is used | `runs/render.svrun` |++Generated-material and normalization outputs remain explicit in the entry Source so the Run can satisfy them by name. Imported files own Script, raw resources and direction; moving an output into a private imported graph would remove that entry’s reuse boundary.++## Components++`opening-system` owns opening graphics, flags, stage and presenter framing Styles. `web-scenes` owns eight coordinated demonstrations. `single-line-captions` presents Script cues through Caption’s semantics and public Companion interfaces. `launch-scenes` supplies the montage poster. `visual-language` is an ordinary shared palette/helper dependency. Each package README explains its inputs and ownership.++## Export++`runs/render.svrun` targets the complete film. `runs/export-parts.svrun` targets five consecutive ranges for machines with limited temporary disk. Each Build is a fresh execution attempt; the Run carries accepted material. The local profile currently requests eight rendering workers.++After exporting the five named Outputs with `hypit get`, join their video streams without re-encoding:++```sh+python3 scripts/assemble-final-export.py part-1.mp4 part-2.mp4 part-3.mp4 part-4.mp4 part-5.mp4 --output final.mp4+```++The helper derives each part’s length from its encoded video, removes each AAC part’s encoder delay before joining sound, and encodes one final audio stream. Parts must be consecutive, ordered and made with the same video settings.++Read [Treatment](TREATMENT.md), [craft notes](CRAFT-NOTES.md) and [asset provenance](ASSET-PROVENANCE.md). Private exploration and old outputs are preserved in history, outside the portable example.diff --git a/examples/complex-explainer/productions/explainer/TREATMENT.md b/examples/complex-explainer/productions/explainer/TREATMENT.mdnew file mode 100644index 00000000..d0b19356--- /dev/null+++ b/examples/complex-explainer/productions/explainer/TREATMENT.md@@ -0,0 +1,28 @@+# Treatment++A quick, playful presenter leads an argument from two costly production approaches to Hypit’s composition and semantic timing. The picture demonstrates each claim through changing objects, not a succession of explanatory title cards.++## Picture and performance++The presenter usually occupies a circular inset, with full-frame opening, transition and closing passages. Performance Uses move the same playing footage between full, upper-half and inset framing. The drinking break returns to the inset on “我们继续”. A covered passage keeps its spoken material and timing while MG leads the picture.++The visual language is pale pink and cream, vivid pink accents, dark offset shadows, stepped pixel flags and a persistent countdown. Caption remains an independent, readable single-line contribution. The montage’s fourth picture holds under the title “复刻任何爆款视频”.++## Scene responsibilities++- Introduction: homepage, source/video demonstration, installation, paired reference and adapted examples.+- Comparison: supplied website captures, pricing and template pages, owner-made case demonstrations and illustrative repeated marks.+- Editor route: one coordinated editor owns folder, pointer, material drops, rejected drag, keyframes and terminal cost.+- Code route: authored code and copied timing show why a one-off implementation is expensive to revise.+- Components: demonstrations of reused visual structures with changed inputs.+- Semantic time: visible words and events show semantic attachment.+- Delivery: editor results become two phone feeds; the final drinking callback uses an anonymous illustration.+- Outro: GitHub page, copy/install gesture, portrait collection and the final star card.++Each scene owns its local HTML, styling and frame-addressable motion. Shared palette, pointer, route cards and typing helpers are ordinary code dependencies. They do not need separate Tracks merely because code is reused. Independent opening graphics, presenter, Caption, music and effects remain separate Film contributions.++## Time and sound++Script Moments drive spoken changes; local durations define how a transition unfolds. Montage flashes and the silent ending use authored frame ranges. Each scene derives state from the current frame, allowing direct seeking and range rendering. Music is low beneath voice; eight synthesized pixel effects accent selected movements. Scene packages output picture only; the Audio Track owns those effect placements.++See [project guide](README.md) for authoring entry points and [craft notes](CRAFT-NOTES.md) for the lessons from this production.diff --git a/examples/complex-explainer/productions/explainer/authors/assets.svml b/examples/complex-explainer/productions/explainer/authors/assets.svmlnew file mode 100644index 00000000..b331ffcc--- /dev/null+++ b/examples/complex-explainer/productions/explainer/authors/assets.svml@@ -0,0 +1,75 @@+<?svml using="@hypit/markup@1"?>+<svml>+ <import as="asset" from="@hypit/media@1"/>+ <import as="time" from="@hypit/timeline-author@1"/>+ <import as="spatial" from="@hypit/spatial@1"/>+ <asset:Image id="road-logo" src="../assets/brand/hypit-logo-ink.png"/>+ <asset:Image id="gallery-ranking" src="../assets/editor-gallery/ranking.jpg"/>+ <asset:Image id="gallery-podcast" src="../assets/editor-gallery/podcast.jpg"/>+ <asset:Image id="gallery-interview" src="../assets/editor-gallery/interview.jpg"/>+ <asset:Image id="gallery-original-ranking" src="../assets/editor-gallery/original-ranking.jpg"/>+ <asset:Image id="gallery-original-interview" src="../assets/editor-gallery/original-interview.jpg"/>+ <asset:Image id="gallery-homepage" src="../assets/editor-gallery/homepage.jpg"/>+ <asset:Image id="gallery-code" src="../assets/editor-gallery/code.jpg"/>+ <asset:Image id="flag-logo" src="../assets/brand/hypit-logo-white.png"/>+ <asset:Font id="display-font" src="../assets/fonts/smiley-sans/SmileySans-Oblique.ttf" weight="400" style="oblique"/>+ <spatial:Canvas id="canvas" width="1080" height="1920"/>+ <asset:Image id="montage-1" src="../assets/montage/01.png"/>+ <asset:Image id="montage-2" src="../assets/montage/02.png"/>+ <asset:Image id="montage-3" src="../assets/montage/03.png"/>+ <asset:Image id="montage-4" src="../assets/montage/04.png"/>+ <asset:Image id="portraits-0" src="../assets/characters/portraits-0.webp"/>+ <asset:Image id="portraits-1" src="../assets/characters/portraits-1.webp"/>+ <asset:Image id="portraits-2" src="../assets/characters/portraits-2.webp"/>+ <asset:Image id="portraits-3" src="../assets/characters/portraits-3.webp"/>+ <asset:Image id="portraits-4" src="../assets/characters/portraits-4.webp"/>+ <asset:Image id="icon-remotion" src="../assets/brand/icon-remotion.png"/>+ <asset:Image id="icon-hyperframes" src="../assets/brand/icon-hyperframes.png"/>+ <time:Clock id="clock" frame-rate="30"/>+ <asset:Image id="presenter-reference" src="../assets/presenter-a464d354ce0d.png"/>+ <asset:Audio id="voice-reference" src="../assets/audio/voice-20260914-9.85s.mp3"/>+ <asset:Audio id="bgm-source" src="../assets/audio/bgm.m4a"/>+ <asset:Video id="web-hypit" src="../assets/web/hypit-introduction-30fps.mp4"/>+ <asset:Video id="web-creatify" src="../assets/web/creatify-scroll-30fps.mp4"/>+ <asset:Video id="web-higgsfield" src="../assets/web/higgsfield-clean-v2-30fps.mp4"/>+ <asset:Video id="code-demo" src="../assets/examples/source-and-video.mp4"/>+ <asset:Video id="readme-demo" src="../assets/web/readme-ready.mp4"/>+ <asset:Video id="price-creatify" src="../assets/web/creatify-price-ready.mp4"/>+ <asset:Video id="price-higgsfield" src="../assets/web/higgsfield-price-ready.mp4"/>+ <asset:Video id="templates-creatify" src="../assets/web/creatify-templates-scrolling.mp4"/>+ <asset:Video id="templates-higgsfield" src="../assets/web/higgsfield-templates-scrolling.mp4"/>+ <asset:Video id="case-creatify" src="../assets/competitors/creatify-example.mp4"/>+ <asset:Video id="case-higgsfield" src="../assets/competitors/higgsfield-example.mp4"/>+ <asset:Video id="reference-ranking" src="../assets/examples/reference-ranking.mp4"/>+ <asset:Video id="reference-podcast" src="../assets/examples/reference-podcast.mp4"/>+ <asset:Video id="reference-interview" src="../assets/examples/reference-interview.mp4"/>+ <asset:Video id="hypit-ranking" src="../assets/examples/ranking-hypit-final.mp4"/>+ <asset:Video id="hypit-podcast" src="../assets/examples/podcast-hypit-final.mp4"/>+ <asset:Video id="hypit-interview" src="../assets/examples/interview-hypit-final.mp4"/>+ <asset:Image id="icon-capcut" src="../assets/brand/capcut.png"/>+ <asset:Image id="icon-premiere" src="../assets/brand/premiere.png"/>+ <asset:Image id="icon-resolve" src="../assets/brand/resolve.png"/>+ <asset:Image id="icon-codex" src="../assets/brand/codex-app.png"/>+ <asset:Image id="icon-claude" src="../assets/brand/claude-app.png"/>+ <asset:Image id="logo-creatify" src="../assets/brand/creatify-mark.png"/>+ <asset:Image id="logo-higgsfield" src="../assets/brand/higgsfield-mark.png"/>+ <asset:Video id="ranking-clone" src="../assets/final-half/ranking-clone.mp4"/>+ <asset:Video id="swap-virtual" src="../assets/final-half/swap-virtual.mp4"/>+ <asset:Video id="swap-language" src="../assets/final-half/swap-language.mp4"/>+ <asset:Video id="swap-topic" src="../assets/final-half/swap-topic.mp4"/>+ <asset:Video id="swap-product" src="../assets/final-half/swap-product.mp4"/>+ <asset:Video id="swap-vehicle" src="../assets/final-half/swap-vehicle.mp4"/>+ <asset:Image id="reference-drink-illustration" src="../assets/final-half/drinking-illustration.png"/>+ <asset:Image id="ranking-host" src="../assets/final-half/host.png"/>+ <asset:Image id="ranking-icon" src="../assets/final-half/hypit.jpg"/>+ <asset:Image id="ranking-creatify" src="../assets/final-half/creatify.png"/>+ <asset:Image id="ranking-higgsfield" src="../assets/final-half/higgsfield.png"/>+ <asset:Audio id="sfx-tap" src="../assets/audio/pixel-sfx/tap.wav"/>+ <asset:Audio id="sfx-pop" src="../assets/audio/pixel-sfx/pop.wav"/>+ <asset:Audio id="sfx-swipe" src="../assets/audio/pixel-sfx/swipe.wav"/>+ <asset:Audio id="sfx-land" src="../assets/audio/pixel-sfx/land.wav"/>+ <asset:Audio id="sfx-reject" src="../assets/audio/pixel-sfx/reject.wav"/>+ <asset:Audio id="sfx-ticks" src="../assets/audio/pixel-sfx/ticks.wav"/>+ <asset:Audio id="sfx-spark" src="../assets/audio/pixel-sfx/spark.wav"/>+ <asset:Audio id="sfx-finish" src="../assets/audio/pixel-sfx/finish.wav"/>+</svml>diff --git a/examples/complex-explainer/productions/explainer/authors/direction.svml b/examples/complex-explainer/productions/explainer/authors/direction.svmlnew file mode 100644index 00000000..4fc74995--- /dev/null+++ b/examples/complex-explainer/productions/explainer/authors/direction.svml@@ -0,0 +1,131 @@+<?svml using="@hypit/markup@1"?>+<svml>+ <import as="copy" source="./script.svml"/>+ <import as="text" from="@hypit/text@1"/>+ <import as="speaker-kit" source="@hypit/seedance-kits/speaker"/>+ <import as="settings" source="../recipes/performance.svs"/>++ <text:Value id="opening-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. She excitedly shares a discovery with bright, quick confidence. On “一分钟”, she lifts her free index finger beside her face with raised eyebrows and a buoyant vocal accent, then lowers it into lively hand beats during the introduction. As she says the complete project name “high pit”, her smile widens. On “开始咯!”, she keeps looking into the lens, leans slightly forward and opens her free palm toward the camera in one inviting forward push, stopping short of covering the lens. The camera stays fixed.</text:Value>++<text:Render id="opening-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Param name="composition-stability" value="soft-locked"/>+ <text:Set name="dialogue" text={copy.story.segment.opening.dialogue}/>+ <text:Set name="action" text={opening-action}/>+ </text:Render>++<text:Value id="introduction-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. She has found something useful and cannot wait to show a friend how easy it is. Her explanation flows quickly, with a pleased, confident smile. On “只要半小时”, her eyebrows rise and the free hand gives one emphatic downward beat; “半小时” carries the surprise. On “你自己的脸和产品”, she opens her palm toward the viewer and gives “你自己的” an inviting emphasis, making the benefit feel personal.</text:Value>++<text:Render id="introduction-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Set name="dialogue" text={copy.story.segment.introduction.dialogue}/>+ <text:Set name="action" text={introduction-action}/>+ </text:Render>++<text:Value id="competitors-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. She challenges an overpriced offer with amused disbelief, looking to the viewer to share the judgment. On “收你几十美元”, her brows rise and her free palm turns upward in a questioning gesture, with an incredulous accent on “几十美元”. Her expression tightens at “只能照着模板做”. The final “还会给你打他们家的水印哦” lands with a small disbelieving head shake and a wry, pointed smile; the complaint becomes sharper as she speaks.</text:Value>++<text:Render id="competitors-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Set name="dialogue" text={copy.story.segment.competitors.dialogue}/>+ <text:Set name="action" text={competitors-action}/>+ </text:Render>++<text:Value id="two-roads-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. She draws the viewer closer to explain something she has figured out, with eager confidence and direct eye contact. On “那接下来”, she leans slightly toward the camera and brings her free palm forward in a quick inviting gesture. Give “我给你拆解” a purposeful, confident emphasis. She straightens while clearly articulating the complete phrase “Hypit 的底层逻辑”, then relaxes into an amused, knowing smile on “说白了”. A short sideways sweep of the open hand accompanies “两条路嘛”, which ends in an assured falling cadence. The gestures flow with the six-second explanation.</text:Value>++<text:Render id="two-roads-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Set name="dialogue" text={copy.story.segment.two-roads.dialogue}/>+ <text:Set name="action" text={two-roads-action}/>+ </text:Render>++<text:Value id="editor-road-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. She briskly walks a friend through a familiar routine, confident that they will recognize it. Give “第一条路” a clear accented entrance. On “别看有那么多种”, her eyebrows lift with a lightly amused expression; on “但逻辑都是一样的”, she gives one knowing nod with a lightly amused smile. Her free hand moves from an open presenting gesture on “素材生成好” into two purposeful placement beats through “贴到时间轴和画布上”.</text:Value>++<text:Render id="editor-road-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Set name="dialogue" text={copy.story.segment.editor-road.dialogue}/>+ <text:Set name="action" text={editor-road-action}/>+ </text:Render>++<text:Value id="keyframe-cost-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. Her initial concession turns into increasingly incredulous criticism. On “虽然贴的还可以”, she gives a brief conceding nod; at “但做动效就不行咯”, her brow tightens, her head gives a short decisive shake, and her voice becomes pointed. The ordinary wishes for a number and a picture are spoken with easy expectation. On “二十几个时间点” and “几十万的token”, her eyebrows lift in disbelief and her free hand opens in exasperation. Finish “而且还改不了样式” with a firm downward vocal landing and one decisive palm-down beat. Keep the explanation quick and connected as the frustration grows.</text:Value>++<text:Render id="keyframe-cost-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Set name="dialogue" text={copy.story.segment.keyframe-cost.dialogue}/>+ <text:Set name="action" text={keyframe-cost-action}/>+ </text:Render>++<text:Value id="code-road-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. She brightens as she introduces a genuinely exciting alternative. “第二条路” gets a fresh, clear vocal lift and a more upright posture. She names the tools with easy familiarity, then opens her free arm outward on “动效想怎么做怎么做”, with widened eyes and an enthusiastic smile that makes the freedom feel appealing.</text:Value>++<text:Render id="code-road-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Set name="dialogue" text={copy.story.segment.code-road.dialogue}/>+ <text:Set name="action" text={code-road-action}/>+ </text:Render>++<text:Value id="reuse-cost-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. The promising option has a catch, and she is incredulous that so much work must be repeated. On “只能用一次了”, she raises her free index finger with a disbelieving eyebrow lift and gives “一次” pointed stress. The description of copying flows quickly with mounting frustration; “原封不动抄一遍” gets a short head shake. The final “又会” is audibly exasperated, ending with a questioning open palm at the token cost.</text:Value>++<text:Render id="reuse-cost-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Set name="dialogue" text={copy.story.segment.reuse-cost.dialogue}/>+ <text:Set name="action" text={reuse-cost-action}/>+ </text:Render>++<text:Value id="timing-cost-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. She insists that the next problem is the one the viewer really needs to understand. On “更要命的是”, she leans slightly forward, narrows her eyes in focused concern and gives the phrase a firm accent. She explains the different words and voice tracks in quick connected phrasing. At “每次” and “重新”, her free hand gives two distinct emphatic beats, finishing the repeated timing work with an incredulous head shake.</text:Value>++<text:Render id="timing-cost-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Set name="dialogue" text={copy.story.segment.timing-cost.dialogue}/>+ <text:Set name="action" text={timing-cost-action}/>+ </text:Render>++<text:Value id="water-break-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. A compact continuous four-second shot: she briefly covers her mouth with her free hand and coughs once, then immediately looks and reaches beyond the right edge of the picture to bring in a sealed-lid straw cup. The cup has a coral-red lid, a white body and a drinking straw. She takes one quick sip, lowers the cup below her mouth, returns her gaze to the lens and smiles warmly as she says the short closing dialogue, “我们继续”. The smile and brisk, upbeat delivery show that she is ready to carry on. Her microphone hand lowers the microphone slightly for the cough and sip, then brings it back toward her mouth for the words; her free hand keeps the cup after the sip. The reach is toward screen-right, the viewer's right. The actions connect immediately, leaving the end of the four seconds for the complete spoken phrase. Include the brief cough and sip sounds with her speech. The camera stays fixed.</text:Value>++<text:Render id="water-break-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Param name="edit-rhythm" value="continuous-take"/>+ <text:Param name="performance" value="reactive-playful"/>+ <text:Param name="gesture" value="natural"/>+ <text:Set name="dialogue" text={copy.story.segment.water-break.dialogue}/>+ <text:Set name="action" text={water-break-action}/>+ </text:Render>++<text:Value id="synthesis-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. She is delighted to announce the solution after all that frustration. “而 Hypit” arrives with a confident smile and a fresh lift in her voice. On “最值钱的东西都留下了”, she draws her open hand toward herself with a pleased nod. On “最烧钱的东西都扔掉了”, the same hand makes a brisk outward dismissive sweep and the sentence lands decisively. The contrasting gestures follow her conviction about keeping what matters and discarding waste.</text:Value>++<text:Render id="synthesis-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Set name="dialogue" text={copy.story.segment.synthesis.dialogue}/>+ <text:Set name="action" text={synthesis-action}/>+ </text:Render>++<text:Value id="components-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. She enjoys explaining a practical shortcut that makes the viewer's work easier. On “只需要写一次”, she lifts her free index finger and gives “一次” a confident, satisfied accent. Her delivery becomes rhythmically nimble through “换文案、换图、换颜色”, with a flowing sequence of open-hand beats. On “一行代码都不用重写了”, she gives a small assured head shake and a delighted smile, landing the promise clearly.</text:Value>++<text:Render id="components-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Set name="dialogue" text={copy.story.segment.components.dialogue}/>+ <text:Set name="action" text={components-action}/>+ </text:Render>++<text:Value id="semantic-time-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. She shares the central insight with focused enthusiasm, looking straight at the viewer. “把稿子当做时间线” gets a confident nod. On “不是绑定在秒上”, her free palm turns outward with a brief head shake; on “绑定在说的话上”, it turns toward the viewer as her expression brightens. Stress “秒” and “说的话” through distinct accents and an assured final cadence while keeping the Mandarin tones clear.</text:Value>++<text:Render id="semantic-time-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Set name="dialogue" text={copy.story.segment.semantic-time.dialogue}/>+ <text:Set name="action" text={semantic-time-action}/>+ </text:Render>++<text:Value id="semantic-demo-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. She makes the idea tangible with the pleasure of showing that it really works. Give “第一名” a crisp accent accompanied by a small upward hand beat, and the later product name a second distinct beat. She becomes visibly pleased as she explains that the words and voice can change: raised brows, a warm smile, and confident flowing delivery. Finish “一个时间点都不用改了” with a small decisive head shake and a satisfied downward vocal landing.</text:Value>++<text:Render id="semantic-demo-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Set name="dialogue" text={copy.story.segment.semantic-demo.dialogue}/>+ <text:Set name="action" text={semantic-demo-action}/>+ </text:Render>++<text:Value id="result-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. She confidently gathers the payoff for the viewer, with energized, persuasive delivery. On “素材生成完就能直接拿到成片”, she opens her free palm forward with a pleased nod. Give “连一秒钟” a pointed, delighted emphasis; then broaden the smile and land “完全一模一样” firmly, keeping the conclusion quick and assured.</text:Value>++<text:Render id="result-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Set name="dialogue" text={copy.story.segment.result.dialogue}/>+ <text:Set name="action" text={result-action}/>+ </text:Render>++<text:Value id="reference-reveal-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. She reveals her own example with pleased, slightly mischievous pride. On “这条视频”, she gives a small open-handed gesture toward herself, then looks directly into the lens. As she asks “你们猜得出”, she leans a little closer and lifts her eyebrows with a teasing smile. The final question has a curious, inviting lift, as though she is genuinely waiting for the viewer's guess.</text:Value>++<text:Render id="reference-reveal-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Set name="dialogue" text={copy.story.segment.reference-reveal.dialogue}/>+ <text:Set name="action" text={reference-reveal-action}/>+ </text:Render>++<text:Value id="closing-action">HOST is the woman in @image1, with the Mandarin voice identity of @audio1. Keep the handheld microphone in the same hand and use the free hand for gestures. She realizes she has run long, then quickly turns that embarrassment into an affectionate, lively farewell. From the very first frame, her head is already tilted down and her gaze is on the phone already held in her free hand. She begins “哎呀” while still looking down at that phone, eyebrows lifting in amused surprise. Through “说好一分钟的,怎么超时这么久了”, she lifts her eyes back to the camera and lowers the phone. She immediately returns to the lens with a slightly sheepish grin and gives the search and installation invitation in brisk, friendly Mandarin. “免费领取” and “一百个” carry delighted emphasis with an inviting open palm toward the viewer. On “我们下期见”, her smile broadens; while saying the final “拜拜”, she extends her free hand toward the camera and fully covers the lens just as the words finish. End with the lens covered. The camera itself stays fixed.</text:Value>++<text:Render id="closing-prompt" template={speaker-kit.speaker-v1} recipe={settings.speaker.host}>+ <text:Param name="composition-stability" value="soft-locked"/>+ <text:Set name="dialogue" text={copy.story.segment.closing.dialogue}/>+ <text:Set name="action" text={closing-action}/>+ </text:Render>+</svml>diff --git a/examples/complex-explainer/productions/explainer/authors/main.svml b/examples/complex-explainer/productions/explainer/authors/main.svmlnew file mode 100644index 00000000..123bd3fe--- /dev/null+++ b/examples/complex-explainer/productions/explainer/authors/main.svml@@ -0,0 +1,416 @@+<?svml using="@hypit/markup@1"?>+<svml>+ <import as="copy" source="./script.svml"/>+ <import as="assets" source="./assets.svml"/>+ <import as="direction" source="./direction.svml"/>+ <import as="seedance" from="@hypit/seedance@1"/>+ <import as="pipeline" from="@hypit/media-pipeline@1"/>+ <import as="whisperx" from="@hypit/whisperx@1"/>+ <import as="time" from="@hypit/timeline-author@1"/>+ <import as="webscene" from="@explainer/web-scenes@1"/>+ <import as="launch" from="@explainer/launch-scenes@1"/>+ <import as="performance" from="@hypit/performance@1"/>+ <import as="sound" from="@hypit/sound@1"/>+ <import as="audio" from="@hypit/audio-track@1"/>+ <import as="caption" from="@hypit/caption@1"/>+ <import as="linecaption" from="@explainer/single-line-captions@1"/>+ <import as="caption-fine" from="@hypit/caption-fine@1"/>+ <import as="film" from="@hypit/film@1"/>+ <import as="render" from="@hypit/render-hyperframes@1"/>+ <import as="look" source="../recipes/composition.svs"/>+ <import as="gfx" from="@explainer/opening-system@1"/>+ <import as="spatial" from="@hypit/spatial@1"/>++ <!-- Prepared material outputs: explicit Run reuse boundaries -->+ <pipeline:Normalize id="bgm-media" source={assets.bgm-source} clock={assets.clock} video="none" audio="default" span-authority="audio"/>+ <pipeline:Normalize id="web-hypit-media" source={assets.web-hypit} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="web-creatify-media" source={assets.web-creatify} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="web-higgsfield-media" source={assets.web-higgsfield} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <seedance:ReferenceVideo id="opening-generation" model="mini" prompt={direction.opening-prompt} duration="5" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="opening-media" source={opening-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="opening" narrative={copy.story} segment={copy.story.segment.opening} media={opening-media.media} language="zh"/>+ <seedance:ReferenceVideo id="introduction-generation" model="mini" prompt={direction.introduction-prompt} duration="11" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="introduction-media" source={introduction-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="introduction" narrative={copy.story} segment={copy.story.segment.introduction} media={introduction-media.media} language="zh"/>+ <seedance:ReferenceVideo id="competitors-generation" model="mini" prompt={direction.competitors-prompt} duration="8" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="competitors-media" source={competitors-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="competitors" narrative={copy.story} segment={copy.story.segment.competitors} media={competitors-media.media} language="zh"/>+ <seedance:ReferenceVideo id="two-roads-generation" model="mini" prompt={direction.two-roads-prompt} duration="6" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="two-roads-media" source={two-roads-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="two-roads" narrative={copy.story} segment={copy.story.segment.two-roads} media={two-roads-media.media} language="zh"/>+ <seedance:ReferenceVideo id="editor-road-generation" model="mini" prompt={direction.editor-road-prompt} duration="8" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="editor-road-media" source={editor-road-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="editor-road" narrative={copy.story} segment={copy.story.segment.editor-road} media={editor-road-media.media} language="zh"/>+ <seedance:ReferenceVideo id="keyframe-cost-generation" model="mini" prompt={direction.keyframe-cost-prompt} duration="13" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="keyframe-cost-media" source={keyframe-cost-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="keyframe-cost" narrative={copy.story} segment={copy.story.segment.keyframe-cost} media={keyframe-cost-media.media} language="zh"/>+ <seedance:ReferenceVideo id="code-road-generation" model="mini" prompt={direction.code-road-prompt} duration="6" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="code-road-media" source={code-road-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="code-road" narrative={copy.story} segment={copy.story.segment.code-road} media={code-road-media.media} language="zh"/>+ <seedance:ReferenceVideo id="reuse-cost-generation" model="mini" prompt={direction.reuse-cost-prompt} duration="8" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="reuse-cost-media" source={reuse-cost-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="reuse-cost" narrative={copy.story} segment={copy.story.segment.reuse-cost} media={reuse-cost-media.media} language="zh"/>+ <seedance:ReferenceVideo id="timing-cost-generation" model="mini" prompt={direction.timing-cost-prompt} duration="8" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="timing-cost-media" source={timing-cost-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="timing-cost" narrative={copy.story} segment={copy.story.segment.timing-cost} media={timing-cost-media.media} language="zh"/>+ <seedance:ReferenceVideo id="water-break-generation" model="mini" prompt={direction.water-break-prompt} duration="4" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="water-break-media" source={water-break-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="water-break" narrative={copy.story} segment={copy.story.segment.water-break} media={water-break-media.media} language="zh"/>+ <seedance:ReferenceVideo id="synthesis-generation" model="mini" prompt={direction.synthesis-prompt} duration="5" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="synthesis-media" source={synthesis-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="synthesis" narrative={copy.story} segment={copy.story.segment.synthesis} media={synthesis-media.media} language="zh"/>+ <seedance:ReferenceVideo id="components-generation" model="mini" prompt={direction.components-prompt} duration="12" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="components-media" source={components-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="components" narrative={copy.story} segment={copy.story.segment.components} media={components-media.media} language="zh"/>+ <seedance:ReferenceVideo id="semantic-time-generation" model="mini" prompt={direction.semantic-time-prompt} duration="5" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="semantic-time-media" source={semantic-time-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="semantic-time" narrative={copy.story} segment={copy.story.segment.semantic-time} media={semantic-time-media.media} language="zh"/>+ <seedance:ReferenceVideo id="semantic-demo-generation" model="mini" prompt={direction.semantic-demo-prompt} duration="10" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="semantic-demo-media" source={semantic-demo-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="semantic-demo" narrative={copy.story} segment={copy.story.segment.semantic-demo} media={semantic-demo-media.media} language="zh"/>+ <seedance:ReferenceVideo id="result-generation" model="mini" prompt={direction.result-prompt} duration="8" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="result-media" source={result-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="result" narrative={copy.story} segment={copy.story.segment.result} media={result-media.media} language="zh"/>+ <seedance:ReferenceVideo id="reference-reveal-generation" model="mini" prompt={direction.reference-reveal-prompt} duration="5" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="reference-reveal-media" source={reference-reveal-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="reference-reveal" narrative={copy.story} segment={copy.story.segment.reference-reveal} media={reference-reveal-media.media} language="zh"/>+ <seedance:ReferenceVideo id="closing-generation" model="mini" prompt={direction.closing-prompt} duration="11" resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={assets.presenter-reference} person-reference="true"/>+ <seedance:Reference audio={assets.voice-reference}/>+ </seedance:ReferenceVideo>+ <pipeline:Normalize id="closing-media" source={closing-generation.video} clock={assets.clock} video="primary-moving" audio="default" span-authority="video"/>+ <whisperx:SemanticTake id="closing" narrative={copy.story} segment={copy.story.segment.closing} media={closing-media.media} language="zh"/>+ <pipeline:Normalize id="code-demo-media" source={assets.code-demo} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="readme-demo-media" source={assets.readme-demo} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="price-creatify-media" source={assets.price-creatify} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="price-higgsfield-media" source={assets.price-higgsfield} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="templates-creatify-media" source={assets.templates-creatify} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="templates-higgsfield-media" source={assets.templates-higgsfield} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="case-creatify-media" source={assets.case-creatify} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="case-higgsfield-media" source={assets.case-higgsfield} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="reference-ranking-media" source={assets.reference-ranking} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="reference-podcast-media" source={assets.reference-podcast} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="reference-interview-media" source={assets.reference-interview} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="hypit-ranking-media" source={assets.hypit-ranking} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="hypit-podcast-media" source={assets.hypit-podcast} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="hypit-interview-media" source={assets.hypit-interview} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>++ <!-- One Timeline: placed Takes, opening gap and silent ending -->+ <time:Timeline id="program" clock={assets.clock} end="content.end+2s">+ <time:Take source={opening.take}/>+ <time:Take source={introduction.take} at="previous.end+1.5s"/>+ <time:Take source={competitors.take}/>+ <time:Take source={two-roads.take}/>+ <time:Take source={editor-road.take}/>+ <time:Take source={keyframe-cost.take}/>+ <time:Take source={code-road.take}/>+ <time:Take source={reuse-cost.take}/>+ <time:Take source={timing-cost.take}/>+ <time:Take source={water-break.take}/>+ <time:Take source={synthesis.take}/>+ <time:Take source={components.take}/>+ <time:Take source={semantic-time.take}/>+ <time:Take source={semantic-demo.take}/>+ <time:Take source={result.take}/>+ <time:Take source={reference-reveal.take}/>+ <time:Take source={closing.take}/>+ </time:Timeline>+ <pipeline:Normalize id="ranking-clone-media" source={assets.ranking-clone} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="swap-virtual-media" source={assets.swap-virtual} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="swap-language-media" source={assets.swap-language} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="swap-topic-media" source={assets.swap-topic} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="swap-product-media" source={assets.swap-product} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>+ <pipeline:Normalize id="swap-vehicle-media" source={assets.swap-vehicle} clock={assets.clock} video="primary-moving" audio="none" span-authority="video"/>++ <!-- Opening chrome and independent montage -->+ <gfx:Title id="opening-title" timeline={program.timeline} canvas={assets.canvas} font={assets.display-font} start="program.start" end="moment.cue" moment={copy.story.moment.begin} bounce-at={copy.story.moment.opening-brand} color="#fa67aa" title-y="0.58" title="Hypit" subtitle="一分钟了解" seconds="60"/>+ <gfx:Flag id="road-flag" x="0.035" width="0.93" height="0.21" y="0.752" timeline={program.timeline} canvas={assets.canvas} logo={assets.flag-logo} start="moment.cue" moment={copy.story.moment.road-overview} end-source={copy.story.segment.timing-cost} end="segment.end"/>+ <gfx:Flag id="closing-road-flag" x="0.035" width="0.93" height="0.21" y="0.752" timeline={program.timeline} canvas={assets.canvas} logo={assets.flag-logo} start-source={copy.story.segment.synthesis} start="segment.start" end-source={copy.story.segment.closing} end="segment.start"/>+ <gfx:Timer flag-amplitude="0.06" logo={assets.flag-logo} id="series-timer" timeline={program.timeline} canvas={assets.canvas} font={assets.display-font} start="moment.cue" end="program.end" moment={copy.story.moment.begin} stop-at={copy.story.moment.outro-overtime} flag-color="#fa67aa" title="Hypit" subtitle="VIDEO FRAMEWORK" seconds="60"/>+ <gfx:Stage id="opening-montage" push-rate="0.025" timeline={program.timeline} canvas={assets.canvas} start="segment.end" end="segment.end+1.5s" segment={copy.story.segment.opening}>+ <gfx:Item id="image-1" image={assets.montage-1} segment={copy.story.segment.opening} start="segment.end+0f" end="segment.end+5f"/>+ <gfx:Item id="image-2" image={assets.montage-2} segment={copy.story.segment.opening} start="segment.end+5f" end="segment.end+9f"/>+ <gfx:Item id="image-3" image={assets.montage-3} segment={copy.story.segment.opening} start="segment.end+9f" end="segment.end+14f"/>+ <gfx:Item id="image-4" image={assets.montage-4} segment={copy.story.segment.opening} start="segment.end+14f" end="segment.end+45f"/>+ </gfx:Stage>++ <!-- Presenter presentation: Uses select framing without changing playback -->+ <spatial:Frame id="full-frame" within={assets.canvas} left="0%" top="0%" right="100%" bottom="100%"/>+ <spatial:AnchoredFrame id="host-inset" within={assets.canvas} x="93%" y="13.5%" width="330px" height="330px" anchor="top-right"/>+ <performance:Style id="host-hidden" frame={full-frame} appearance={look.media.hidden}/>+ <performance:Style id="host-full" frame={full-frame} appearance={look.media.full}/>+ <gfx:PortraitInset id="host-small" frame={host-inset}/>+ <gfx:Pullback id="opening-pullback" scale="1.5"/>+ <gfx:FadeOut id="host-fade"/>+ <spatial:Frame id="upper-frame" within={assets.canvas} left="0%" top="0%" right="100%" bottom="48%"/>+ <performance:Style id="host-upper" frame={upper-frame} appearance={look.media.upper}/>+ <gfx:Reframe id="host-rise" from={full-frame} to={upper-frame}/>+ <gfx:PortraitTransition id="host-resume" from={full-frame} to={host-inset}/>+ <performance:Track id="presenter" timeline={program.timeline} canvas={assets.canvas}>+ <performance:Use style={host-small} segment={copy.story.segment.introduction} start="segment.start" end="program.end"/>+ <performance:Use during={copy.story.segment.opening} style={host-full}/>+ <performance:Use start="0f" end="1s" style={opening-pullback}/>+ <performance:Use during={copy.story.segment.two-roads} style={host-full}/>+ <performance:Use segment={copy.story.segment.two-roads} start="segment.start" end="segment.start+1s" style={opening-pullback}/>+ <performance:Use start-source={copy.story.moment.road-half} start="moment.cue" end-source={copy.story.moment.road-overview} end="moment.cue" style={host-upper}/>+ <performance:Use at={copy.story.moment.road-half} for="14f" style={host-rise}/>+ <performance:Use segment={copy.story.segment.two-roads} moment={copy.story.moment.road-overview} start="moment.cue" end="segment.end" style={host-small}/>+ <performance:Use during={copy.story.segment.water-break} style={host-full}/>+ <performance:Use moment={copy.story.moment.resume} start="moment.cue" end="program.end" style={host-small}/>+ <performance:Use at={copy.story.moment.resume} for="18f" style={host-resume}/>+ <performance:Use during={copy.story.segment.closing} style={host-full}/>+ <performance:Use segment={copy.story.segment.closing} start="segment.start" end="segment.start+1s" style={opening-pullback}/>+ <performance:Use start-source={copy.story.moment.outro-github} start="moment.cue" end-source={copy.story.moment.outro-bye} end="moment.cue" style={host-small}/>+ <performance:Use during={copy.story.segment.timing-cost} style={host-hidden}/>+ <performance:Use start-source={copy.story.moment.result-guess} start="moment.cue" end-source={copy.story.segment.reference-reveal} end="segment.end" style={host-hidden}/>+ <performance:Use segment={copy.story.segment.closing} start="segment.end-12f" end="segment.end" style={host-fade}/>+ <performance:Use segment={copy.story.segment.closing} start="segment.end" end="program.end" style={host-hidden}/>+ </performance:Track>+ <sound:Style id="normal-voice"/>++ <!-- Voice, music and independently authored effects -->+ <sound:Track id="voice" timeline={program.timeline}>+ <sound:Use style={normal-voice}/>+ </sound:Track>+ <audio:Track id="music" timeline={program.timeline}>+ <audio:Item id="bgm" source={bgm-media.media} during="program" playback="once" gain="0.09" fade-in="6f" fade-out="2s"/>+ </audio:Track>+ <pipeline:Normalize id="sfx-tap-media" source={assets.sfx-tap} clock={assets.clock} video="none" audio="default" span-authority="audio"/>+ <pipeline:Normalize id="sfx-pop-media" source={assets.sfx-pop} clock={assets.clock} video="none" audio="default" span-authority="audio"/>+ <pipeline:Normalize id="sfx-swipe-media" source={assets.sfx-swipe} clock={assets.clock} video="none" audio="default" span-authority="audio"/>+ <pipeline:Normalize id="sfx-land-media" source={assets.sfx-land} clock={assets.clock} video="none" audio="default" span-authority="audio"/>+ <pipeline:Normalize id="sfx-reject-media" source={assets.sfx-reject} clock={assets.clock} video="none" audio="default" span-authority="audio"/>+ <pipeline:Normalize id="sfx-ticks-media" source={assets.sfx-ticks} clock={assets.clock} video="none" audio="default" span-authority="audio"/>+ <pipeline:Normalize id="sfx-spark-media" source={assets.sfx-spark} clock={assets.clock} video="none" audio="default" span-authority="audio"/>+ <pipeline:Normalize id="sfx-finish-media" source={assets.sfx-finish} clock={assets.clock} video="none" audio="default" span-authority="audio"/>+ <audio:Track id="pixel-effects" timeline={program.timeline}>+ <audio:Item id="sfx-intro-codex" source={sfx-pop-media.media} at={copy.story.moment.intro-codex} for="0.24s" playback="once" gain="0.16" fade-out="1f"/>+ <audio:Item id="sfx-intro-claude" source={sfx-pop-media.media} at={copy.story.moment.intro-claude} for="0.24s" playback="once" gain="0.16" fade-out="1f"/>+ <audio:Item id="sfx-intro-examples" source={sfx-swipe-media.media} at={copy.story.moment.intro-examples} for="0.36s" playback="once" gain="0.2" fade-out="1f"/>+ <audio:Item id="sfx-intro-face" source={sfx-spark-media.media} at={copy.story.moment.intro-face} for="0.48s" playback="once" gain="0.13" fade-out="1f"/>+ <audio:Item id="sfx-competitor-monthly" source={sfx-tap-media.media} at={copy.story.moment.competitor-monthly} for="0.12s" playback="once" gain="0.16" fade-out="1f"/>+ <audio:Item id="sfx-competitor-watermark" source={sfx-ticks-media.media} at={copy.story.moment.competitor-watermark} for="0.65s" playback="once" gain="0.13" fade-out="1f"/>+ <audio:Item id="sfx-roads" source={sfx-land-media.media} at={copy.story.moment.roads} for="0.26s" playback="once" gain="0.22" fade-out="1f"/>+ <audio:Item id="sfx-road-assets" source={sfx-pop-media.media} at={copy.story.moment.road-assets} for="0.24s" playback="once" gain="0.15" fade-out="1f"/>+ <audio:Item id="sfx-road-drag" source={sfx-tap-media.media} at={copy.story.moment.road-drag} for="0.12s" playback="once" gain="0.13" fade-out="1f"/>+ <audio:Item id="sfx-road-fail" source={sfx-reject-media.media} at={copy.story.moment.road-fail} for="0.4s" playback="once" gain="0.19" fade-out="1f"/>+ <audio:Item id="sfx-road-number" source={sfx-pop-media.media} at={copy.story.moment.road-number} for="0.24s" playback="once" gain="0.2" fade-out="1f"/>+ <audio:Item id="sfx-road-image" source={sfx-swipe-media.media} at={copy.story.moment.road-image} for="0.36s" playback="once" gain="0.18" fade-out="1f"/>+ <audio:Item id="sfx-road-keys" source={sfx-ticks-media.media} at={copy.story.moment.road-keys} for="0.65s" playback="once" gain="0.13" fade-out="1f"/>+ <audio:Item id="sfx-road-tokens" source={sfx-ticks-media.media} at={copy.story.moment.road-tokens} for="0.65s" playback="once" gain="0.12" fade-out="1f"/>+ <audio:Item id="sfx-code-play" source={sfx-pop-media.media} at={copy.story.moment.code-play} for="0.24s" playback="once" gain="0.16" fade-out="1f"/>+ <audio:Item id="sfx-code-duplicate" source={sfx-ticks-media.media} at={copy.story.moment.code-duplicate} for="0.65s" playback="once" gain="0.12" fade-out="1f"/>+ <audio:Item id="sfx-solution-keep" source={sfx-spark-media.media} at={copy.story.moment.solution-keep} for="0.48s" playback="once" gain="0.19" fade-out="1f"/>+ <audio:Item id="sfx-solution-drop" source={sfx-swipe-media.media} at={copy.story.moment.solution-drop} for="0.36s" playback="once" gain="0.18" fade-out="1f"/>+ <audio:Item id="sfx-part-caption" source={sfx-tap-media.media} at={copy.story.moment.part-caption} for="0.12s" playback="once" gain="0.13" fade-out="1f"/>+ <audio:Item id="sfx-part-ranking" source={sfx-tap-media.media} at={copy.story.moment.part-ranking} for="0.12s" playback="once" gain="0.13" fade-out="1f"/>+ <audio:Item id="sfx-part-chart" source={sfx-tap-media.media} at={copy.story.moment.part-chart} for="0.12s" playback="once" gain="0.13" fade-out="1f"/>+ <audio:Item id="sfx-part-card" source={sfx-tap-media.media} at={copy.story.moment.part-card} for="0.12s" playback="once" gain="0.13" fade-out="1f"/>+ <audio:Item id="sfx-parts-library" source={sfx-land-media.media} at={copy.story.moment.parts-library} for="0.26s" playback="once" gain="0.18" fade-out="1f"/>+ <audio:Item id="sfx-parts-reuse" source={sfx-spark-media.media} at={copy.story.moment.parts-reuse} for="0.48s" playback="once" gain="0.14" fade-out="1f"/>+ <audio:Item id="sfx-parts-swap" source={sfx-swipe-media.media} at={copy.story.moment.parts-swap} for="0.36s" playback="once" gain="0.19" fade-out="1f"/>+ <audio:Item id="sfx-rank-reveal" source={sfx-land-media.media} at={copy.story.moment.rank-reveal} for="0.26s" playback="once" gain="0.2" fade-out="1f"/>+ <audio:Item id="sfx-product-reveal" source={sfx-pop-media.media} at={copy.story.moment.product-reveal} for="0.24s" playback="once" gain="0.2" fade-out="1f"/>+ <audio:Item id="sfx-sem-voice" source={sfx-tap-media.media} at={copy.story.moment.sem-voice} for="0.12s" playback="once" gain="0.13" fade-out="1f"/>+ <audio:Item id="sfx-sem-adapt" source={sfx-spark-media.media} at={copy.story.moment.sem-adapt} for="0.48s" playback="once" gain="0.14" fade-out="1f"/>+ <audio:Item id="sfx-result-assets" source={sfx-finish-media.media} at={copy.story.moment.result-assets} for="0.72s" playback="once" gain="0.16" fade-out="1f"/>+ <audio:Item id="sfx-result-meta" source={sfx-swipe-media.media} at={copy.story.moment.result-meta} for="0.36s" playback="once" gain="0.17" fade-out="1f"/>+ <audio:Item id="sfx-outro-install" source={sfx-tap-media.media} at={copy.story.moment.outro-install} for="0.12s" playback="once" gain="0.15" fade-out="1f"/>+ <audio:Item id="sfx-outro-gift" source={sfx-spark-media.media} at={copy.story.moment.outro-gift} for="0.48s" playback="once" gain="0.18" fade-out="1f"/>+ <audio:Item id="sfx-outro-bye" source={sfx-finish-media.media} at={copy.story.moment.outro-bye} for="0.72s" playback="once" gain="0.18" fade-out="1f"/>+ <audio:Item id="sfx-montage-1" source={sfx-tap-media.media} segment={copy.story.segment.opening} start="segment.end+0f" end="segment.end+4f" playback="once" gain="0.21"/>+ <audio:Item id="sfx-montage-2" source={sfx-tap-media.media} segment={copy.story.segment.opening} start="segment.end+5f" end="segment.end+9f" playback="once" gain="0.21"/>+ <audio:Item id="sfx-montage-3" source={sfx-tap-media.media} segment={copy.story.segment.opening} start="segment.end+9f" end="segment.end+13f" playback="once" gain="0.21"/>+ <audio:Item id="sfx-montage-4" source={sfx-spark-media.media} segment={copy.story.segment.opening} start="segment.end+14f" end="segment.end+28f" playback="once" gain="0.27"/>+ </audio:Track>++ <!-- Caption: Script text, authored cues and presentation -->+ <caption:Hidden id="hidden-captions"/>+ <caption-fine:Style id="caption-base" recipe={look.caption.primary} font={assets.display-font}/>+ <linecaption:Track id="captions" timeline={program.timeline} document={copy.story.caption}>+ <linecaption:Use style={caption-base}/>+ <linecaption:Use during={copy.story.segment.opening} style={hidden-captions}/>+ </linecaption:Track>+ <launch:PosterTitle id="montage-label" timeline={program.timeline} canvas={assets.canvas} font={assets.display-font} segment={copy.story.segment.opening} start="segment.end+14f" end="segment.end+45f" text="Hypit" subtitle="复刻任何爆款视频" y="0.165" size="180" subtitle-size="46" subtitle-gap="35"/>++ <!-- Coordinated scenes: supplied media plus semantic events -->+ <webscene:Introduction id="intro-scene" timeline={program.timeline} canvas={assets.canvas} font={assets.display-font} during={copy.story.segment.introduction} page={web-hypit-media.media} code={code-demo-media.media} readme={readme-demo-media.media} codex={assets.icon-codex} claude={assets.icon-claude} reference-ranking={reference-ranking-media.media} reference-podcast={reference-podcast-media.media} reference-interview={reference-interview-media.media} hypit-ranking={hypit-ranking-media.media} hypit-podcast={hypit-podcast-media.media} hypit-interview={hypit-interview-media.media}>+ <webscene:Beat name="language" at={copy.story.moment.intro-language}/>+ <webscene:Beat name="install" at={copy.story.moment.intro-install}/>+ <webscene:Beat name="codex" at={copy.story.moment.intro-codex}/>+ <webscene:Beat name="claude" at={copy.story.moment.intro-claude}/>+ <webscene:Beat name="examples" at={copy.story.moment.intro-examples}/>+ <webscene:Beat name="thirty" at={copy.story.moment.intro-thirty}/>+ <webscene:Beat name="face" at={copy.story.moment.intro-face}/>+ <webscene:Beat name="product" at={copy.story.moment.intro-product}/>+ </webscene:Introduction>+ <webscene:Comparison id="competitor-scene" timeline={program.timeline} canvas={assets.canvas} font={assets.display-font} during={copy.story.segment.competitors} left={web-creatify-media.media} right={web-higgsfield-media.media} price-a={price-creatify-media.media} price-b={price-higgsfield-media.media} templates-a={templates-creatify-media.media} templates-b={templates-higgsfield-media.media} case-a={case-creatify-media.media} case-b={case-higgsfield-media.media} logo-a={assets.logo-creatify} logo-b={assets.logo-higgsfield}>+ <webscene:Beat name="other" at={copy.story.moment.competitor-other}/>+ <webscene:Beat name="monthly" at={copy.story.moment.competitor-monthly}/>+ <webscene:Beat name="templates" at={copy.story.moment.competitor-templates}/>+ <webscene:Beat name="cases" at={copy.story.moment.competitor-cases}/>+ <webscene:Beat name="watermark" at={copy.story.moment.competitor-watermark}/>+ </webscene:Comparison>+ <webscene:Road id="editor-journey" timeline={program.timeline} canvas={assets.canvas} font={assets.display-font} start-source={copy.story.segment.two-roads} start="segment.start" end-source={copy.story.segment.keyframe-cost} end="segment.end" page={web-hypit-media.media} sample={case-higgsfield-media.media} codex={assets.icon-codex} capcut={assets.icon-capcut} premiere={assets.icon-premiere} resolve={assets.icon-resolve} logo={assets.road-logo} portrait={assets.presenter-reference} thumb-a={assets.gallery-ranking} thumb-b={assets.gallery-podcast} thumb-c={assets.gallery-interview} thumb-d={assets.gallery-original-ranking} thumb-e={assets.gallery-original-interview} thumb-f={assets.gallery-homepage} thumb-g={assets.gallery-code}>+ <webscene:Beat name="half" at={copy.story.moment.road-half}/>+ <webscene:Beat name="overview" at={copy.story.moment.road-overview}/>+ <webscene:Beat name="editor" at={copy.story.moment.road-editor}/>+ <webscene:Beat name="operate" at={copy.story.moment.road-operate}/>+ <webscene:Beat name="capcut" at={copy.story.moment.road-capcut}/>+ <webscene:Beat name="premiere" at={copy.story.moment.road-premiere}/>+ <webscene:Beat name="resolve" at={copy.story.moment.road-resolve}/>+ <webscene:Beat name="same" at={copy.story.moment.road-same}/>+ <webscene:Beat name="assets" at={copy.story.moment.road-assets}/>+ <webscene:Beat name="drag" at={copy.story.moment.road-drag}/>+ <webscene:Beat name="place" at={copy.story.moment.road-place}/>+ <webscene:Beat name="fail" at={copy.story.moment.road-fail}/>+ <webscene:Beat name="number" at={copy.story.moment.road-number}/>+ <webscene:Beat name="image" at={copy.story.moment.road-image}/>+ <webscene:Beat name="keys" at={copy.story.moment.road-keys}/>+ <webscene:Beat name="tokens" at={copy.story.moment.road-tokens}/>+ <webscene:Beat name="generated" at={copy.story.moment.road-generated}/>+ <webscene:Beat name="unstable" at={copy.story.moment.road-unstable}/>+ <webscene:Beat name="styles" at={copy.story.moment.road-styles}/>+ </webscene:Road>+ <webscene:CodeJourney id="code-journey" timeline={program.timeline} canvas={assets.canvas} font={assets.display-font} start-source={copy.story.segment.code-road} start="segment.start" end-source={copy.story.segment.synthesis} end="segment.end" codex={assets.icon-codex} remotion={assets.icon-remotion} hyperframes={assets.icon-hyperframes} ranking={reference-ranking-media.media} podcast={reference-podcast-media.media} interview={reference-interview-media.media} target={hypit-ranking-media.media}>+ <webscene:Beat name="remotion" at={copy.story.moment.code-remotion}/>+ <webscene:Beat name="hyperframes" at={copy.story.moment.code-hyperframes}/>+ <webscene:Beat name="html" at={copy.story.moment.code-html}/>+ <webscene:Beat name="play" at={copy.story.moment.code-play}/>+ <webscene:Beat name="once" at={copy.story.moment.code-once}/>+ <webscene:Beat name="variant" at={copy.story.moment.code-variant}/>+ <webscene:Beat name="copy" at={copy.story.moment.code-copy}/>+ <webscene:Beat name="duplicate" at={copy.story.moment.code-duplicate}/>+ <webscene:Beat name="tokens" at={copy.story.moment.code-tokens}/>+ <webscene:Beat name="time" at={copy.story.moment.code-time}/>+ <webscene:Beat name="different" at={copy.story.moment.code-different}/>+ <webscene:Beat name="match" at={copy.story.moment.code-match}/>+ <webscene:Beat name="retime" at={copy.story.moment.code-retime}/>+ <webscene:Beat name="water" at={copy.story.segment.water-break} boundary="start"/>+ <webscene:Beat name="resume" at={copy.story.moment.resume}/>+ <webscene:Beat name="solution" at={copy.story.moment.solution}/>+ <webscene:Beat name="parts" at={copy.story.moment.solution-roads}/>+ <webscene:Beat name="keep" at={copy.story.moment.solution-keep}/>+ <webscene:Beat name="drop" at={copy.story.moment.solution-drop}/>+ </webscene:CodeJourney>+ <webscene:ComponentWorkshop id="component-workshop" timeline={program.timeline} canvas={assets.canvas} font={assets.display-font} during={copy.story.segment.components} v0={ranking-clone-media.media} v1={swap-virtual-media.media} v2={swap-language-media.media} v3={swap-topic-media.media} v4={swap-product-media.media} v5={swap-vehicle-media.media}>+ <webscene:Beat name="all" at={copy.story.moment.parts-all}/>+ <webscene:Beat name="caption" at={copy.story.moment.part-caption}/>+ <webscene:Beat name="ranking" at={copy.story.moment.part-ranking}/>+ <webscene:Beat name="chart" at={copy.story.moment.part-chart}/>+ <webscene:Beat name="card" at={copy.story.moment.part-card}/>+ <webscene:Beat name="library" at={copy.story.moment.parts-library}/>+ <webscene:Beat name="reuse" at={copy.story.moment.parts-reuse}/>+ <webscene:Beat name="variants" at={copy.story.moment.parts-word}/>+ <webscene:Beat name="word" at={copy.story.moment.parts-word}/>+ <webscene:Beat name="picture" at={copy.story.moment.parts-picture}/>+ <webscene:Beat name="color" at={copy.story.moment.parts-color}/>+ <webscene:Beat name="swap" at={copy.story.moment.parts-swap}/>+ </webscene:ComponentWorkshop>+ <webscene:SemanticWorkshop id="semantic-workshop" timeline={program.timeline} canvas={assets.canvas} font={assets.display-font} creatify={assets.ranking-creatify} higgsfield={assets.ranking-higgsfield} start-source={copy.story.segment.semantic-time} start="segment.start" end-source={copy.story.segment.semantic-demo} end="segment.end">+ <webscene:Beat name="bind" at={copy.story.moment.sem-bind}/>+ <webscene:Beat name="examples" at={copy.story.moment.sem-examples}/>+ <webscene:Beat name="rank" at={copy.story.moment.rank-reveal}/>+ <webscene:Beat name="product" at={copy.story.moment.product-reveal}/>+ <webscene:Beat name="rewrite-scene" at={copy.story.moment.sem-rewrite-scene}/>+ <webscene:Beat name="rewrite" at={copy.story.moment.sem-rewrite}/>+ <webscene:Beat name="voice" at={copy.story.moment.sem-voice}/>+ <webscene:Beat name="adapt" at={copy.story.moment.sem-adapt}/>+ <webscene:Beat name="syntax" at={copy.story.moment.sem-syntax}/>+ </webscene:SemanticWorkshop>+ <webscene:DeliveryWorkshop id="delivery-workshop" timeline={program.timeline} canvas={assets.canvas} font={assets.display-font} start-source={copy.story.segment.result} start="segment.start" end-source={copy.story.segment.reference-reveal} end="segment.end" film={hypit-ranking-media.media} clone={ranking-clone-media.media} water={water-break-media.media} reference={assets.reference-drink-illustration} host={assets.ranking-host} thumb1={assets.ranking-icon} thumb2={assets.ranking-creatify} thumb3={assets.ranking-higgsfield}>+ <webscene:Beat name="assets" at={copy.story.moment.result-assets}/>+ <webscene:Beat name="upload" at={copy.story.moment.result-upload}/>+ <webscene:Beat name="compare" at={copy.story.moment.result-compare}/>+ <webscene:Beat name="meta" at={copy.story.moment.result-meta}/>+ <webscene:Beat name="brand" at={copy.story.moment.result-brand}/>+ <webscene:Beat name="guess" at={copy.story.moment.result-guess}/>+ </webscene:DeliveryWorkshop>+ <webscene:Outro id="outro-scene" timeline={program.timeline} canvas={assets.canvas} font={assets.display-font} segment={copy.story.segment.closing} start="segment.start" end="program.end" page={readme-demo-media.media} codex={assets.icon-codex} portraits-0={assets.portraits-0} portraits-1={assets.portraits-1} portraits-2={assets.portraits-2} portraits-3={assets.portraits-3} portraits-4={assets.portraits-4}>+ <webscene:Beat name="overtime" at={copy.story.moment.outro-overtime}/>+ <webscene:Beat name="github" at={copy.story.moment.outro-github}/>+ <webscene:Beat name="copy" at={copy.story.moment.outro-copy}/>+ <webscene:Beat name="install" at={copy.story.moment.outro-install}/>+ <webscene:Beat name="gift" at={copy.story.moment.outro-gift}/>+ <webscene:Beat name="bye" at={copy.story.moment.outro-bye}/>+ <webscene:Beat name="end" at={copy.story.segment.closing} boundary="end"/>+ </webscene:Outro>++ <!-- Final assembly: contributions and render targets -->+ <film:Film id="main" canvas={assets.canvas} timeline={program.timeline} appearance={look.film.main}>+ <film:Track source={presenter.visual}/>+ <film:Track source={voice.audio}/>+ <film:Track source={music.audio}/>+ <film:Track source={pixel-effects.audio}/>+ <film:Track source={captions.track}/>+ <film:Track source={opening-title.track}/>+ <film:Track source={series-timer.track}/>+ <film:Track source={road-flag.track}/>+ <film:Track source={closing-road-flag.track}/>+ <film:Track source={opening-montage.track}/>+ <film:Track source={montage-label.track}/>+ <film:Track source={intro-scene.track}/>+ <film:Track source={competitor-scene.track}/>+ <film:Track source={editor-journey.track}/>+ <film:Track source={code-journey.track}/>+ <film:Track source={component-workshop.track}/>+ <film:Track source={semantic-workshop.track}/>+ <film:Track source={delivery-workshop.track}/>+ <film:Track source={outro-scene.track}/>+ </film:Film>+ <render:Video id="complete-film" composition={main.composition} timeline={program.timeline}/>+ <!-- Consecutive export ranges for limited temporary disk space. -->+ <render:Video id="export-part-1" composition={main.composition} timeline={program.timeline} start-frame="0" end-frame-exclusive="900"/>+ <render:Video id="export-part-2" composition={main.composition} timeline={program.timeline} start-frame="900" end-frame-exclusive="1800"/>+ <render:Video id="export-part-3" composition={main.composition} timeline={program.timeline} start-frame="1800" end-frame-exclusive="2700"/>+ <render:Video id="export-part-4" composition={main.composition} timeline={program.timeline} start-frame="2700" end-frame-exclusive="3600"/>+ <render:Video id="export-part-5" composition={main.composition} timeline={program.timeline} start-frame="3600" end-frame-exclusive="4112"/>+</svml>diff --git a/examples/complex-explainer/productions/explainer/authors/script.svml b/examples/complex-explainer/productions/explainer/authors/script.svmlnew file mode 100644index 00000000..f156839d--- /dev/null+++ b/examples/complex-explainer/productions/explainer/authors/script.svml@@ -0,0 +1,58 @@+<?svml using="@hypit/markup@1"?>+<svml>+ <import from="@hypit/script@1"/>++ <script id="story">+ <opening>+ <HOST> 一分钟带你了解最近超火的 || 开源视频复刻项目 @opening-brand! high pit。 || @begin! 开始咯!+ </opening>+ <introduction>+ <HOST> Hypit是一个开源视频复刻框架, || @intro-language! 自创了一套视频领域语言。 || @intro-install! 把hypit skill装进你的 || @intro-codex! codex或者@intro-claude! <claude|cloud>, || @intro-thirty! 只要半小时就能拿到 || @intro-examples! 你想复刻的任何爆款视频, || 并且还换@intro-face! 上了你自己的脸 || 和@intro-product! 产品。+ </introduction>+ <competitors>+ <HOST> 隔壁的 Creatify和@competitor-other! Higgsfield, || 一个月要@competitor-monthly! 收你几十美元 || @competitor-templates! 但只能照着模板做, || @competitor-cases! 不仅复刻不了爆款, || @competitor-watermark! 还会给你打他们家的水印哦。+ </competitors>+ <two-roads>+ <HOST> 那接下来我给你拆解 || @road-half! Hypit 的底层逻辑。 || @road-overview! 说白了, || 现在用 AI 做视频就@roads! 两条路嘛。+ </two-roads>+ <editor-road>+ <HOST> @road-editor! 第一条路是 || @road-operate! 让 AI 操作剪辑软件。 || @road-capcut! 别看有@road-premiere! 那么@road-resolve! 多种, || @road-same! 但逻辑都是一样的: || @road-assets! AI 先帮你把素材生成好, || @road-drag! 再一个个去贴到 || 时间轴和画布上。+ </editor-road>+ <keyframe-cost>+ <HOST> @road-place! 虽然贴的还可以, || @road-fail! 但做动效就不行咯。 || 想让@road-number! 一个数字弹出来、 || 或者@road-image! 一张图飞进来, || @road-keys! 要么让 AI 在时间轴上 || 标出二十几个时间点, || @road-tokens! 烧掉几十万的token, || @road-generated! 要么用seedance直出, || @road-unstable! 不仅效果不稳定, || @road-styles! 而且还改不了样式。+ </keyframe-cost>+ <code-road>+ <HOST> @code-start! 第二条路是让 AI 去写代码。 || @code-remotion! Remotion和@code-hyperframes! Hyperframes, || 本质都是写@code-html! html, || @code-play! 动效想怎么做怎么做。+ </code-road>+ <reuse-cost>+ <HOST> @code-once! 但代价是每条视频只能用一次了! || @code-variant! 下次想做个差不多的, || @code-copy! 得让 AI 把几千行的html || @code-duplicate! 原封不动抄一遍, || @code-tokens! 又会烧掉几十万的token;+ </reuse-cost>+ <timing-cost>+ <HOST> @code-time! 而且更要命的是, || @code-different! 每条素材的稿子和配音都不一样, || @code-match! 为了让动效对上口播的时间, || @code-retime! 每次 AI 都得重新抄一遍时间点。+ </timing-cost>+ <water-break>+ <HOST> @resume! 我们继续。+ </water-break>+ <synthesis>+ <HOST> @solution! 而 Hypit 是把 @solution-roads! 这两条路上 || @solution-keep! 最值钱的东西都留下了, || @solution-drop! 最烧钱的东西都扔掉了!+ </synthesis>+ <components>+ <HOST> 画布上呢, || 它把动效给组件化了: || @parts-all! 所有值得变成组件的东西, || 无论是@component-list @part-caption! 字幕、@part-ranking! 榜单、@part-chart! 图表、@part-card! 卡片 @/component-list, || @parts-library! AI 都只需要写一次, || @parts-reuse! 之后每条视频都能拿来复用, || 你想@parts-word! 换文案、@parts-picture! 换图、@parts-color! 换颜色, || @parts-swap! 一行代码都不用重写了!+ </components>+ <semantic-time>+ <HOST> 时间上呢, || 它是把稿子当做时间线的: || @sem-bind! 动效不是绑定在秒上, || 而是绑定在说的话上。+ </semantic-time>+ <semantic-demo>+ <HOST> @sem-examples! 比如榜单在“@rank-reveal! 第一名”这个词上翻开, || 产品图在说“@product-reveal! hypit”这时候飞进来。 || @sem-rewrite-scene! 就算是重写 @sem-rewrite! 稿子、@sem-voice! 换掉了配音, || @sem-adapt! 动效依然都会精准出现, || @sem-syntax! 一个时间点都不用改了!+ </semantic-demo>+ <result>+ <HOST> 所以用 Hypit 来做视频, || @result-assets! 素材生成完就能直接拿到成片, || @result-upload! 连一秒钟的剪辑都不需要, || @result-compare! 而且跟原来那条爆款的效果 || 完全一模一样!+ </result>+ <reference-reveal>+ <HOST> @result-meta! 这条视频就是用 @result-brand! Hypit || 复刻的一条爆款, || @result-guess! 你们猜得出原博主是哪位吗?+ </reference-reveal>+ <closing>+ <HOST> 哎呀说好一分钟的 || @outro-overtime! 怎么超时这么久了。 || @outro-github! <Github|Git Hub> 搜索 Hypit, || @outro-copy! 一键复制skill || @outro-install! 装进你的 coding agent; || @outro-gift! 还能免费领取 || 一百个口播数字人哦! || @outro-bye! 我们下期见, || 拜拜~+ </closing>+ </script>+</svml>diff --git a/examples/complex-explainer/productions/explainer/recipes/composition.svs b/examples/complex-explainer/productions/explainer/recipes/composition.svsnew file mode 100644index 00000000..1756e889--- /dev/null+++ b/examples/complex-explainer/productions/explainer/recipes/composition.svs@@ -0,0 +1,21 @@+<?svml using="@hypit/svs@1"?>+<sheet version="1">+ film.main { background: #090f1b; }+ media.hidden { stack-order: 0; fit: cover; opacity: 0; }+ media.full { stack-order: 0; fit: cover; clip: frame; }+ media.upper { stack-order: 60; fit: cover; frame-y: 0.3; content-y: 0.3; clip: frame; }+ caption.primary {+ stack-order: 70; x: 0.5; y: 0.79; width: 0.90; height: 0.13;+ anchor-x: center; anchor-y: bottom; align: center; block-align: end; inline-size: fixed;+ wrap: word; size: 68; line-height: 1.1; fill: #EDE7DE; stroke-color: #10121e; stroke-width: 6;+ shadow-color: #2b1f30;+ shadow-opacity: 1;+ shadow-x: 4;+ shadow-y: 5;+ shadow-blur: 0;+ shadow-spread: 1;+ background: #00000000; padding: "0"; radius: 0;+ karaoke: off; cue-enter: fade; cue-enter-frames: 2; cue-enter-start-scale: 0.94;+ cue-exit: none; lead-frames: 0; tail-frames: 0; handoff: cut;+ }+</sheet>diff --git a/examples/complex-explainer/productions/explainer/recipes/performance.svs b/examples/complex-explainer/productions/explainer/recipes/performance.svsnew file mode 100644index 00000000..b11c2ae7--- /dev/null+++ b/examples/complex-explainer/productions/explainer/recipes/performance.svs@@ -0,0 +1,10 @@+<?svml using="@hypit/svs@1"?>+<sheet version="1">+ speaker.host {+ composition-stability: soft-locked;+ camera-motion: none;+ edit-rhythm: pause-trim-jump-cuts;+ performance: high-energy-ugc;+ gesture: expressive;+ }+</sheet>diff --git a/examples/complex-explainer/productions/explainer/runs/export-parts.svrun b/examples/complex-explainer/productions/explainer/runs/export-parts.svrunnew file mode 100644index 00000000..74f590a7--- /dev/null+++ b/examples/complex-explainer/productions/explainer/runs/export-parts.svrun@@ -0,0 +1,109 @@+<?svml using="@hypit/run-markup@1"?>+<svrun version="1">+ <author source="../authors/main.svml"/>+ <target output="export-part-1.video"/>+ <target output="export-part-2.video"/>+ <target output="export-part-3.video"/>+ <target output="export-part-4.video"/>+ <target output="export-part-5.video"/>+ <build-record id="opening-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="opening.take"/>+ <satisfy output="opening.take" candidate="opening-kept"/>+ <build-record id="introduction-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="introduction.take"/>+ <satisfy output="introduction.take" candidate="introduction-kept"/>+ <build-record id="competitors-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="competitors.take"/>+ <satisfy output="competitors.take" candidate="competitors-kept"/>+ <build-record id="two-roads-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="two-roads.take"/>+ <satisfy output="two-roads.take" candidate="two-roads-kept"/>+ <build-record id="editor-road-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="editor-road.take"/>+ <satisfy output="editor-road.take" candidate="editor-road-kept"/>+ <build-record id="keyframe-cost-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="keyframe-cost.take"/>+ <satisfy output="keyframe-cost.take" candidate="keyframe-cost-kept"/>+ <build-record id="code-road-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="code-road.take"/>+ <satisfy output="code-road.take" candidate="code-road-kept"/>+ <build-record id="reuse-cost-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="reuse-cost.take"/>+ <satisfy output="reuse-cost.take" candidate="reuse-cost-kept"/>+ <build-record id="timing-cost-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="timing-cost.take"/>+ <satisfy output="timing-cost.take" candidate="timing-cost-kept"/>+ <build-record id="water-break-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="water-break.take"/>+ <satisfy output="water-break.take" candidate="water-break-kept"/>+ <build-record id="synthesis-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="synthesis.take"/>+ <satisfy output="synthesis.take" candidate="synthesis-kept"/>+ <build-record id="components-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="components.take"/>+ <satisfy output="components.take" candidate="components-kept"/>+ <build-record id="semantic-time-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="semantic-time.take"/>+ <satisfy output="semantic-time.take" candidate="semantic-time-kept"/>+ <build-record id="semantic-demo-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="semantic-demo.take"/>+ <satisfy output="semantic-demo.take" candidate="semantic-demo-kept"/>+ <build-record id="result-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="result.take"/>+ <satisfy output="result.take" candidate="result-kept"/>+ <build-record id="reference-reveal-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="reference-reveal.take"/>+ <satisfy output="reference-reveal.take" candidate="reference-reveal-kept"/>+ <build-record id="closing-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="closing.take"/>+ <satisfy output="closing.take" candidate="closing-kept"/>+ <build-record id="prepared-0" build="bld_20260914T043459227Z_E0B178D4A9" output="bgm-media.media"/>+ <satisfy output="bgm-media.media" candidate="prepared-0"/>+ <build-record id="prepared-1" build="bld_20260914T043459227Z_E0B178D4A9" output="case-creatify-media.media"/>+ <satisfy output="case-creatify-media.media" candidate="prepared-1"/>+ <build-record id="prepared-2" build="bld_20260914T043459227Z_E0B178D4A9" output="case-higgsfield-media.media"/>+ <satisfy output="case-higgsfield-media.media" candidate="prepared-2"/>+ <build-record id="prepared-4" build="bld_20260914T043459227Z_E0B178D4A9" output="code-demo-media.media"/>+ <satisfy output="code-demo-media.media" candidate="prepared-4"/>+ <build-record id="prepared-27" build="bld_20260914T043459227Z_E0B178D4A9" output="price-creatify-media.media"/>+ <satisfy output="price-creatify-media.media" candidate="prepared-27"/>+ <build-record id="prepared-34" build="bld_20260914T043459227Z_E0B178D4A9" output="price-higgsfield-media.media"/>+ <satisfy output="price-higgsfield-media.media" candidate="prepared-34"/>+ <build-record id="prepared-37" build="bld_20260914T043459227Z_E0B178D4A9" output="readme-demo-media.media"/>+ <satisfy output="readme-demo-media.media" candidate="prepared-37"/>+ <build-record id="prepared-38" build="bld_20260914T043459227Z_E0B178D4A9" output="reference-podcast-media.media"/>+ <satisfy output="reference-podcast-media.media" candidate="prepared-38"/>+ <build-record id="prepared-39" build="bld_20260914T043459227Z_E0B178D4A9" output="reference-ranking-media.media"/>+ <satisfy output="reference-ranking-media.media" candidate="prepared-39"/>+ <build-record id="prepared-40" build="bld_20260914T043459227Z_E0B178D4A9" output="reference-interview-media.media"/>+ <satisfy output="reference-interview-media.media" candidate="prepared-40"/>+ <build-record id="prepared-43" build="bld_20260914T043459227Z_E0B178D4A9" output="web-creatify-media.media"/>+ <satisfy output="web-creatify-media.media" candidate="prepared-43"/>+ <build-record id="prepared-44" build="bld_20260914T043459227Z_E0B178D4A9" output="web-higgsfield-media.media"/>+ <satisfy output="web-higgsfield-media.media" candidate="prepared-44"/>+ <build-record id="prepared-46" build="bld_20260914T043459227Z_E0B178D4A9" output="web-hypit-media.media"/>+ <satisfy output="web-hypit-media.media" candidate="prepared-46"/>+ <build-record id="revision5-0" build="bld_20260914T043459227Z_E0B178D4A9" output="hypit-ranking-media.media"/>+ <satisfy output="hypit-ranking-media.media" candidate="revision5-0"/>+ <build-record id="revision5-1" build="bld_20260914T043459227Z_E0B178D4A9" output="hypit-podcast-media.media"/>+ <satisfy output="hypit-podcast-media.media" candidate="revision5-1"/>+ <build-record id="revision5-2" build="bld_20260914T043459227Z_E0B178D4A9" output="hypit-interview-media.media"/>+ <satisfy output="hypit-interview-media.media" candidate="revision5-2"/>+ <build-record id="revision5-3" build="bld_20260914T043459227Z_E0B178D4A9" output="templates-creatify-media.media"/>+ <satisfy output="templates-creatify-media.media" candidate="revision5-3"/>+ <build-record id="revision5-4" build="bld_20260914T043459227Z_E0B178D4A9" output="templates-higgsfield-media.media"/>+ <satisfy output="templates-higgsfield-media.media" candidate="revision5-4"/>+ <build-record id="last-half-ranking-clone" build="bld_20260914T043459227Z_E0B178D4A9" output="ranking-clone-media.media"/>+ <satisfy output="ranking-clone-media.media" candidate="last-half-ranking-clone"/>+ <build-record id="last-half-swap-virtual" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-virtual-media.media"/>+ <satisfy output="swap-virtual-media.media" candidate="last-half-swap-virtual"/>+ <build-record id="last-half-swap-language" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-language-media.media"/>+ <satisfy output="swap-language-media.media" candidate="last-half-swap-language"/>+ <build-record id="last-half-swap-topic" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-topic-media.media"/>+ <satisfy output="swap-topic-media.media" candidate="last-half-swap-topic"/>+ <build-record id="last-half-swap-product" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-product-media.media"/>+ <satisfy output="swap-product-media.media" candidate="last-half-swap-product"/>+ <build-record id="last-half-swap-vehicle" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-vehicle-media.media"/>+ <satisfy output="swap-vehicle-media.media" candidate="last-half-swap-vehicle"/>+ <build-record id="water-picture-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="water-break-media.media"/>+ <satisfy output="water-break-media.media" candidate="water-picture-kept"/>+ <build-record id="pixel-sfx-tap" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-tap-media.media"/>+ <satisfy output="sfx-tap-media.media" candidate="pixel-sfx-tap"/>+ <build-record id="pixel-sfx-pop" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-pop-media.media"/>+ <satisfy output="sfx-pop-media.media" candidate="pixel-sfx-pop"/>+ <build-record id="pixel-sfx-swipe" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-swipe-media.media"/>+ <satisfy output="sfx-swipe-media.media" candidate="pixel-sfx-swipe"/>+ <build-record id="pixel-sfx-land" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-land-media.media"/>+ <satisfy output="sfx-land-media.media" candidate="pixel-sfx-land"/>+ <build-record id="pixel-sfx-reject" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-reject-media.media"/>+ <satisfy output="sfx-reject-media.media" candidate="pixel-sfx-reject"/>+ <build-record id="pixel-sfx-ticks" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-ticks-media.media"/>+ <satisfy output="sfx-ticks-media.media" candidate="pixel-sfx-ticks"/>+ <build-record id="pixel-sfx-spark" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-spark-media.media"/>+ <satisfy output="sfx-spark-media.media" candidate="pixel-sfx-spark"/>+ <build-record id="pixel-sfx-finish" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-finish-media.media"/>+ <satisfy output="sfx-finish-media.media" candidate="pixel-sfx-finish"/>+</svrun>diff --git a/examples/complex-explainer/productions/explainer/runs/prepare-example.svrun b/examples/complex-explainer/productions/explainer/runs/prepare-example.svrunnew file mode 100644index 00000000..0b2cd66c--- /dev/null+++ b/examples/complex-explainer/productions/explainer/runs/prepare-example.svrun@@ -0,0 +1,154 @@+<?svml using="@hypit/run-markup@1"?>+<svrun version="1">+ <author source="../authors/main.svml"/>+ <target output="opening.take"/>+ <target output="introduction.take"/>+ <target output="competitors.take"/>+ <target output="two-roads.take"/>+ <target output="editor-road.take"/>+ <target output="keyframe-cost.take"/>+ <target output="code-road.take"/>+ <target output="reuse-cost.take"/>+ <target output="timing-cost.take"/>+ <target output="water-break.take"/>+ <target output="synthesis.take"/>+ <target output="components.take"/>+ <target output="semantic-time.take"/>+ <target output="semantic-demo.take"/>+ <target output="result.take"/>+ <target output="reference-reveal.take"/>+ <target output="closing.take"/>+ <target output="bgm-media.media"/>+ <target output="case-creatify-media.media"/>+ <target output="case-higgsfield-media.media"/>+ <target output="code-demo-media.media"/>+ <target output="price-creatify-media.media"/>+ <target output="price-higgsfield-media.media"/>+ <target output="readme-demo-media.media"/>+ <target output="reference-podcast-media.media"/>+ <target output="reference-ranking-media.media"/>+ <target output="reference-interview-media.media"/>+ <target output="web-creatify-media.media"/>+ <target output="web-higgsfield-media.media"/>+ <target output="web-hypit-media.media"/>+ <target output="hypit-ranking-media.media"/>+ <target output="hypit-podcast-media.media"/>+ <target output="hypit-interview-media.media"/>+ <target output="templates-creatify-media.media"/>+ <target output="templates-higgsfield-media.media"/>+ <target output="ranking-clone-media.media"/>+ <target output="swap-virtual-media.media"/>+ <target output="swap-language-media.media"/>+ <target output="swap-topic-media.media"/>+ <target output="swap-product-media.media"/>+ <target output="swap-vehicle-media.media"/>+ <target output="water-break-media.media"/>+ <target output="sfx-tap-media.media"/>+ <target output="sfx-pop-media.media"/>+ <target output="sfx-swipe-media.media"/>+ <target output="sfx-land-media.media"/>+ <target output="sfx-reject-media.media"/>+ <target output="sfx-ticks-media.media"/>+ <target output="sfx-spark-media.media"/>+ <target output="sfx-finish-media.media"/>+ <build-record id="opening-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="opening.take"/>+ <satisfy output="opening.take" candidate="opening-kept"/>+ <build-record id="introduction-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="introduction.take"/>+ <satisfy output="introduction.take" candidate="introduction-kept"/>+ <build-record id="competitors-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="competitors.take"/>+ <satisfy output="competitors.take" candidate="competitors-kept"/>+ <build-record id="two-roads-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="two-roads.take"/>+ <satisfy output="two-roads.take" candidate="two-roads-kept"/>+ <build-record id="editor-road-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="editor-road.take"/>+ <satisfy output="editor-road.take" candidate="editor-road-kept"/>+ <build-record id="keyframe-cost-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="keyframe-cost.take"/>+ <satisfy output="keyframe-cost.take" candidate="keyframe-cost-kept"/>+ <build-record id="code-road-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="code-road.take"/>+ <satisfy output="code-road.take" candidate="code-road-kept"/>+ <build-record id="reuse-cost-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="reuse-cost.take"/>+ <satisfy output="reuse-cost.take" candidate="reuse-cost-kept"/>+ <build-record id="timing-cost-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="timing-cost.take"/>+ <satisfy output="timing-cost.take" candidate="timing-cost-kept"/>+ <build-record id="water-break-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="water-break.take"/>+ <satisfy output="water-break.take" candidate="water-break-kept"/>+ <build-record id="synthesis-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="synthesis.take"/>+ <satisfy output="synthesis.take" candidate="synthesis-kept"/>+ <build-record id="components-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="components.take"/>+ <satisfy output="components.take" candidate="components-kept"/>+ <build-record id="semantic-time-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="semantic-time.take"/>+ <satisfy output="semantic-time.take" candidate="semantic-time-kept"/>+ <build-record id="semantic-demo-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="semantic-demo.take"/>+ <satisfy output="semantic-demo.take" candidate="semantic-demo-kept"/>+ <build-record id="result-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="result.take"/>+ <satisfy output="result.take" candidate="result-kept"/>+ <build-record id="reference-reveal-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="reference-reveal.take"/>+ <satisfy output="reference-reveal.take" candidate="reference-reveal-kept"/>+ <build-record id="closing-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="closing.take"/>+ <satisfy output="closing.take" candidate="closing-kept"/>+ <build-record id="prepared-0" build="bld_20260914T043459227Z_E0B178D4A9" output="bgm-media.media"/>+ <satisfy output="bgm-media.media" candidate="prepared-0"/>+ <build-record id="prepared-1" build="bld_20260914T043459227Z_E0B178D4A9" output="case-creatify-media.media"/>+ <satisfy output="case-creatify-media.media" candidate="prepared-1"/>+ <build-record id="prepared-2" build="bld_20260914T043459227Z_E0B178D4A9" output="case-higgsfield-media.media"/>+ <satisfy output="case-higgsfield-media.media" candidate="prepared-2"/>+ <build-record id="prepared-4" build="bld_20260914T043459227Z_E0B178D4A9" output="code-demo-media.media"/>+ <satisfy output="code-demo-media.media" candidate="prepared-4"/>+ <build-record id="prepared-27" build="bld_20260914T043459227Z_E0B178D4A9" output="price-creatify-media.media"/>+ <satisfy output="price-creatify-media.media" candidate="prepared-27"/>+ <build-record id="prepared-34" build="bld_20260914T043459227Z_E0B178D4A9" output="price-higgsfield-media.media"/>+ <satisfy output="price-higgsfield-media.media" candidate="prepared-34"/>+ <build-record id="prepared-37" build="bld_20260914T043459227Z_E0B178D4A9" output="readme-demo-media.media"/>+ <satisfy output="readme-demo-media.media" candidate="prepared-37"/>+ <build-record id="prepared-38" build="bld_20260914T043459227Z_E0B178D4A9" output="reference-podcast-media.media"/>+ <satisfy output="reference-podcast-media.media" candidate="prepared-38"/>+ <build-record id="prepared-39" build="bld_20260914T043459227Z_E0B178D4A9" output="reference-ranking-media.media"/>+ <satisfy output="reference-ranking-media.media" candidate="prepared-39"/>+ <build-record id="prepared-40" build="bld_20260914T043459227Z_E0B178D4A9" output="reference-interview-media.media"/>+ <satisfy output="reference-interview-media.media" candidate="prepared-40"/>+ <build-record id="prepared-43" build="bld_20260914T043459227Z_E0B178D4A9" output="web-creatify-media.media"/>+ <satisfy output="web-creatify-media.media" candidate="prepared-43"/>+ <build-record id="prepared-44" build="bld_20260914T043459227Z_E0B178D4A9" output="web-higgsfield-media.media"/>+ <satisfy output="web-higgsfield-media.media" candidate="prepared-44"/>+ <build-record id="prepared-46" build="bld_20260914T043459227Z_E0B178D4A9" output="web-hypit-media.media"/>+ <satisfy output="web-hypit-media.media" candidate="prepared-46"/>+ <build-record id="revision5-0" build="bld_20260914T043459227Z_E0B178D4A9" output="hypit-ranking-media.media"/>+ <satisfy output="hypit-ranking-media.media" candidate="revision5-0"/>+ <build-record id="revision5-1" build="bld_20260914T043459227Z_E0B178D4A9" output="hypit-podcast-media.media"/>+ <satisfy output="hypit-podcast-media.media" candidate="revision5-1"/>+ <build-record id="revision5-2" build="bld_20260914T043459227Z_E0B178D4A9" output="hypit-interview-media.media"/>+ <satisfy output="hypit-interview-media.media" candidate="revision5-2"/>+ <build-record id="revision5-3" build="bld_20260914T043459227Z_E0B178D4A9" output="templates-creatify-media.media"/>+ <satisfy output="templates-creatify-media.media" candidate="revision5-3"/>+ <build-record id="revision5-4" build="bld_20260914T043459227Z_E0B178D4A9" output="templates-higgsfield-media.media"/>+ <satisfy output="templates-higgsfield-media.media" candidate="revision5-4"/>+ <build-record id="last-half-ranking-clone" build="bld_20260914T043459227Z_E0B178D4A9" output="ranking-clone-media.media"/>+ <satisfy output="ranking-clone-media.media" candidate="last-half-ranking-clone"/>+ <build-record id="last-half-swap-virtual" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-virtual-media.media"/>+ <satisfy output="swap-virtual-media.media" candidate="last-half-swap-virtual"/>+ <build-record id="last-half-swap-language" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-language-media.media"/>+ <satisfy output="swap-language-media.media" candidate="last-half-swap-language"/>+ <build-record id="last-half-swap-topic" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-topic-media.media"/>+ <satisfy output="swap-topic-media.media" candidate="last-half-swap-topic"/>+ <build-record id="last-half-swap-product" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-product-media.media"/>+ <satisfy output="swap-product-media.media" candidate="last-half-swap-product"/>+ <build-record id="last-half-swap-vehicle" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-vehicle-media.media"/>+ <satisfy output="swap-vehicle-media.media" candidate="last-half-swap-vehicle"/>+ <build-record id="water-picture-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="water-break-media.media"/>+ <satisfy output="water-break-media.media" candidate="water-picture-kept"/>+ <build-record id="pixel-sfx-tap" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-tap-media.media"/>+ <satisfy output="sfx-tap-media.media" candidate="pixel-sfx-tap"/>+ <build-record id="pixel-sfx-pop" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-pop-media.media"/>+ <satisfy output="sfx-pop-media.media" candidate="pixel-sfx-pop"/>+ <build-record id="pixel-sfx-swipe" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-swipe-media.media"/>+ <satisfy output="sfx-swipe-media.media" candidate="pixel-sfx-swipe"/>+ <build-record id="pixel-sfx-land" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-land-media.media"/>+ <satisfy output="sfx-land-media.media" candidate="pixel-sfx-land"/>+ <build-record id="pixel-sfx-reject" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-reject-media.media"/>+ <satisfy output="sfx-reject-media.media" candidate="pixel-sfx-reject"/>+ <build-record id="pixel-sfx-ticks" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-ticks-media.media"/>+ <satisfy output="sfx-ticks-media.media" candidate="pixel-sfx-ticks"/>+ <build-record id="pixel-sfx-spark" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-spark-media.media"/>+ <satisfy output="sfx-spark-media.media" candidate="pixel-sfx-spark"/>+ <build-record id="pixel-sfx-finish" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-finish-media.media"/>+ <satisfy output="sfx-finish-media.media" candidate="pixel-sfx-finish"/>+</svrun>diff --git a/examples/complex-explainer/productions/explainer/runs/render.svrun b/examples/complex-explainer/productions/explainer/runs/render.svrunnew file mode 100644index 00000000..1c9614d8--- /dev/null+++ b/examples/complex-explainer/productions/explainer/runs/render.svrun@@ -0,0 +1,105 @@+<?svml using="@hypit/run-markup@1"?>+<svrun version="1">+ <author source="../authors/main.svml"/>+ <target output="complete-film.video"/>+ <build-record id="opening-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="opening.take"/>+ <satisfy output="opening.take" candidate="opening-kept"/>+ <build-record id="introduction-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="introduction.take"/>+ <satisfy output="introduction.take" candidate="introduction-kept"/>+ <build-record id="competitors-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="competitors.take"/>+ <satisfy output="competitors.take" candidate="competitors-kept"/>+ <build-record id="two-roads-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="two-roads.take"/>+ <satisfy output="two-roads.take" candidate="two-roads-kept"/>+ <build-record id="editor-road-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="editor-road.take"/>+ <satisfy output="editor-road.take" candidate="editor-road-kept"/>+ <build-record id="keyframe-cost-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="keyframe-cost.take"/>+ <satisfy output="keyframe-cost.take" candidate="keyframe-cost-kept"/>+ <build-record id="code-road-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="code-road.take"/>+ <satisfy output="code-road.take" candidate="code-road-kept"/>+ <build-record id="reuse-cost-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="reuse-cost.take"/>+ <satisfy output="reuse-cost.take" candidate="reuse-cost-kept"/>+ <build-record id="timing-cost-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="timing-cost.take"/>+ <satisfy output="timing-cost.take" candidate="timing-cost-kept"/>+ <build-record id="water-break-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="water-break.take"/>+ <satisfy output="water-break.take" candidate="water-break-kept"/>+ <build-record id="synthesis-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="synthesis.take"/>+ <satisfy output="synthesis.take" candidate="synthesis-kept"/>+ <build-record id="components-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="components.take"/>+ <satisfy output="components.take" candidate="components-kept"/>+ <build-record id="semantic-time-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="semantic-time.take"/>+ <satisfy output="semantic-time.take" candidate="semantic-time-kept"/>+ <build-record id="semantic-demo-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="semantic-demo.take"/>+ <satisfy output="semantic-demo.take" candidate="semantic-demo-kept"/>+ <build-record id="result-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="result.take"/>+ <satisfy output="result.take" candidate="result-kept"/>+ <build-record id="reference-reveal-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="reference-reveal.take"/>+ <satisfy output="reference-reveal.take" candidate="reference-reveal-kept"/>+ <build-record id="closing-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="closing.take"/>+ <satisfy output="closing.take" candidate="closing-kept"/>+ <build-record id="prepared-0" build="bld_20260914T043459227Z_E0B178D4A9" output="bgm-media.media"/>+ <satisfy output="bgm-media.media" candidate="prepared-0"/>+ <build-record id="prepared-1" build="bld_20260914T043459227Z_E0B178D4A9" output="case-creatify-media.media"/>+ <satisfy output="case-creatify-media.media" candidate="prepared-1"/>+ <build-record id="prepared-2" build="bld_20260914T043459227Z_E0B178D4A9" output="case-higgsfield-media.media"/>+ <satisfy output="case-higgsfield-media.media" candidate="prepared-2"/>+ <build-record id="prepared-4" build="bld_20260914T043459227Z_E0B178D4A9" output="code-demo-media.media"/>+ <satisfy output="code-demo-media.media" candidate="prepared-4"/>+ <build-record id="prepared-27" build="bld_20260914T043459227Z_E0B178D4A9" output="price-creatify-media.media"/>+ <satisfy output="price-creatify-media.media" candidate="prepared-27"/>+ <build-record id="prepared-34" build="bld_20260914T043459227Z_E0B178D4A9" output="price-higgsfield-media.media"/>+ <satisfy output="price-higgsfield-media.media" candidate="prepared-34"/>+ <build-record id="prepared-37" build="bld_20260914T043459227Z_E0B178D4A9" output="readme-demo-media.media"/>+ <satisfy output="readme-demo-media.media" candidate="prepared-37"/>+ <build-record id="prepared-38" build="bld_20260914T043459227Z_E0B178D4A9" output="reference-podcast-media.media"/>+ <satisfy output="reference-podcast-media.media" candidate="prepared-38"/>+ <build-record id="prepared-39" build="bld_20260914T043459227Z_E0B178D4A9" output="reference-ranking-media.media"/>+ <satisfy output="reference-ranking-media.media" candidate="prepared-39"/>+ <build-record id="prepared-40" build="bld_20260914T043459227Z_E0B178D4A9" output="reference-interview-media.media"/>+ <satisfy output="reference-interview-media.media" candidate="prepared-40"/>+ <build-record id="prepared-43" build="bld_20260914T043459227Z_E0B178D4A9" output="web-creatify-media.media"/>+ <satisfy output="web-creatify-media.media" candidate="prepared-43"/>+ <build-record id="prepared-44" build="bld_20260914T043459227Z_E0B178D4A9" output="web-higgsfield-media.media"/>+ <satisfy output="web-higgsfield-media.media" candidate="prepared-44"/>+ <build-record id="prepared-46" build="bld_20260914T043459227Z_E0B178D4A9" output="web-hypit-media.media"/>+ <satisfy output="web-hypit-media.media" candidate="prepared-46"/>+ <build-record id="revision5-0" build="bld_20260914T043459227Z_E0B178D4A9" output="hypit-ranking-media.media"/>+ <satisfy output="hypit-ranking-media.media" candidate="revision5-0"/>+ <build-record id="revision5-1" build="bld_20260914T043459227Z_E0B178D4A9" output="hypit-podcast-media.media"/>+ <satisfy output="hypit-podcast-media.media" candidate="revision5-1"/>+ <build-record id="revision5-2" build="bld_20260914T043459227Z_E0B178D4A9" output="hypit-interview-media.media"/>+ <satisfy output="hypit-interview-media.media" candidate="revision5-2"/>+ <build-record id="revision5-3" build="bld_20260914T043459227Z_E0B178D4A9" output="templates-creatify-media.media"/>+ <satisfy output="templates-creatify-media.media" candidate="revision5-3"/>+ <build-record id="revision5-4" build="bld_20260914T043459227Z_E0B178D4A9" output="templates-higgsfield-media.media"/>+ <satisfy output="templates-higgsfield-media.media" candidate="revision5-4"/>+ <build-record id="last-half-ranking-clone" build="bld_20260914T043459227Z_E0B178D4A9" output="ranking-clone-media.media"/>+ <satisfy output="ranking-clone-media.media" candidate="last-half-ranking-clone"/>+ <build-record id="last-half-swap-virtual" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-virtual-media.media"/>+ <satisfy output="swap-virtual-media.media" candidate="last-half-swap-virtual"/>+ <build-record id="last-half-swap-language" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-language-media.media"/>+ <satisfy output="swap-language-media.media" candidate="last-half-swap-language"/>+ <build-record id="last-half-swap-topic" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-topic-media.media"/>+ <satisfy output="swap-topic-media.media" candidate="last-half-swap-topic"/>+ <build-record id="last-half-swap-product" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-product-media.media"/>+ <satisfy output="swap-product-media.media" candidate="last-half-swap-product"/>+ <build-record id="last-half-swap-vehicle" build="bld_20260914T043459227Z_E0B178D4A9" output="swap-vehicle-media.media"/>+ <satisfy output="swap-vehicle-media.media" candidate="last-half-swap-vehicle"/>+ <build-record id="water-picture-kept" build="bld_20260914T043459227Z_E0B178D4A9" output="water-break-media.media"/>+ <satisfy output="water-break-media.media" candidate="water-picture-kept"/>+ <build-record id="pixel-sfx-tap" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-tap-media.media"/>+ <satisfy output="sfx-tap-media.media" candidate="pixel-sfx-tap"/>+ <build-record id="pixel-sfx-pop" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-pop-media.media"/>+ <satisfy output="sfx-pop-media.media" candidate="pixel-sfx-pop"/>+ <build-record id="pixel-sfx-swipe" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-swipe-media.media"/>+ <satisfy output="sfx-swipe-media.media" candidate="pixel-sfx-swipe"/>+ <build-record id="pixel-sfx-land" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-land-media.media"/>+ <satisfy output="sfx-land-media.media" candidate="pixel-sfx-land"/>+ <build-record id="pixel-sfx-reject" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-reject-media.media"/>+ <satisfy output="sfx-reject-media.media" candidate="pixel-sfx-reject"/>+ <build-record id="pixel-sfx-ticks" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-ticks-media.media"/>+ <satisfy output="sfx-ticks-media.media" candidate="pixel-sfx-ticks"/>+ <build-record id="pixel-sfx-spark" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-spark-media.media"/>+ <satisfy output="sfx-spark-media.media" candidate="pixel-sfx-spark"/>+ <build-record id="pixel-sfx-finish" build="bld_20260914T043459227Z_E0B178D4A9" output="sfx-finish-media.media"/>+ <satisfy output="sfx-finish-media.media" candidate="pixel-sfx-finish"/>+</svrun>diff --git a/examples/complex-explainer/productions/explainer/scripts/assemble-final-export.py b/examples/complex-explainer/productions/explainer/scripts/assemble-final-export.pynew file mode 100644index 00000000..c70e07b7--- /dev/null+++ b/examples/complex-explainer/productions/explainer/scripts/assemble-final-export.py@@ -0,0 +1,54 @@+"""Join already-rendered consecutive ranges; preserve video and rebuild one audio stream."""+import argparse+import json+from pathlib import Path+import subprocess+import tempfile+from fractions import Fraction+++def run(args):+ subprocess.run(args, check=True)+++def duration(path):+ info = json.loads(subprocess.check_output([+ 'ffprobe', '-v', 'error', '-select_streams', 'v:0',+ '-show_entries', 'stream=nb_frames,r_frame_rate', '-of', 'json', str(path)+ ]))['streams'][0]+ return int(info['nb_frames']) / Fraction(info['r_frame_rate'])+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('parts', nargs='+', type=Path, help='Consecutive rendered parts in playback order')+ parser.add_argument('--output', required=True, type=Path)+ args = parser.parse_args()+ parts = [p.resolve(strict=True) for p in args.parts]+ lengths = [duration(p) for p in parts]+ args.output.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(prefix='explainer-join-') as temp:+ temp = Path(temp)+ listing = temp / 'concat.txt'+ listing.write_text(''.join(+ "file '" + str(p).replace("'", "'\\''") + f"'\nduration {float(d):.9f}\n"+ for p, d in zip(parts, lengths)+ ))+ picture = temp / 'picture.mp4'+ run(['ffmpeg', '-v', 'error', '-y', '-f', 'concat', '-safe', '0', '-i', str(listing),+ '-map', '0:v:0', '-an', '-c:v', 'copy', str(picture)])+ command = ['ffmpeg', '-v', 'error', '-y', '-i', str(picture)]+ for p in parts:+ command += ['-i', str(p)]+ # Decode each part separately so each AAC encoder delay is removed before concatenation.+ filters = ';'.join(+ f'[{i}:a:0]atrim=duration={float(d):.9f},asetpts=PTS-STARTPTS[a{i}]'+ for i, d in enumerate(lengths, 1)+ ) + ';' + ''.join(f'[a{i}]' for i in range(1, len(parts) + 1)) + f'concat=n={len(parts)}:v=0:a=1[a]'+ run(command + ['-filter_complex', filters, '-map', '0:v:0', '-map', '[a]',+ '-c:v', 'copy', '-c:a', 'aac', '-b:a', '256k', '-movflags', '+faststart', str(args.output)])+ print(args.output.resolve())+++if __name__ == '__main__':+ main()diff --git a/examples/provider-package/README.md b/examples/provider-package/README.mdnew file mode 100644index 00000000..0d61a35d--- /dev/null+++ b/examples/provider-package/README.md@@ -0,0 +1,78 @@+# A project-owned Provider++This complete package demonstrates an asynchronous image service through the public Hypit SDK.+The service protocol below is **illustrative**, not a live vendor API. Replace its mapping and+transport with the selected service's documented operations. The lifecycle test exercises the+example without a paid request. Implement the capabilities needed by the production; a service's+entire catalogue is not required.++## Follow one request++The existing GPT Image 2 Model produces `@hypit/gpt-image@1#gpt-image-2` with a generated image-set+result. This Provider supports 1K at three ratios, with optional reference images. It reports its+smaller support range without changing the Model. The Profile selects this implementation; the+Source's prompt, references and model remain ordinary generation inputs.++The example service uses Bearer authentication for these API operations:++| Operation | Example protocol |+| --- | --- |+| Upload reference | `POST /uploads`, image bytes and media Content-Type → `{ "url": "https://…" }` |+| Submit generation | `POST /tasks`, `{ "model": "gpt-image-2", "input": { "prompt": "…", "ratio": "9:16", "size": "1K", "references": [] } }` → `{ "id": "task-123" }` |+| Poll task | `GET /tasks/task-123` → `state`: `queued`, `running`, `failed`, or `succeeded`; success includes a signed image `url` |+| Read rates | `GET /rates?model=gpt-image-2` → service-owned fields and a `description` stating rates, units and conditions |+| Collect result | GET the signed image URL without the account key |++`start` records the received task ID through `checkpoint` before returning it. Runtime owns polling,+capacity and durable operation state. `poll` returns `ready` for completed remote work; `collect`+stores the image through `context.resources` and returns the Model's declared value. The Provider+chooses neither a Result folder nor a project media path. A failed call ends the attempt while the+received task ID remains evidence. This service defines no cancellation endpoint, so the package+does not claim remote cancellation.++`pricing` identifies the service page. `readPricing` maps the current request to its service rate+source and preserves the response with a concise description. It reads no graph and invents no+future media duration. Rates and credentials do not supply spending permission.++## Make it a package in the production++Copy `packages/provider-images` into the video's `packages/`. Choose your own package name and change+`providerModule.name` with it. Implement the actual service protocol, including its request limits,+upload/download limits and any OAuth or cancellation behavior it really offers. Configure the+selected service address; `images.example` is a placeholder that cannot generate media.++Use the active `@hypit/hypit` version as a development dependency. Build and install with the+project's package manager. In this repository the example uses `workspace:*` for that dependency;+replace it with your selected release when copying it out. The `@hypit/driver-node` and+`@hypit/gpt-image` development dependencies serve the repository test only and can be removed from+the copied package. For example:++```bash+cd packages/provider-images+npm install+npm run build+cd ../..+npm install ./packages/provider-images+```++The package ships JavaScript. Its `hypit.activation` exports a Profile-selected Runtime facet;+installation alone activates nothing. The active Distribution resolves public SDK imports when+loading project packages. Keep the chosen package version and lockfile with the project.++Merge the endpoint, credential store and binding from `hypit.runtime.json` into the project's+chosen Profile. Preserve its other services and resolve bindings explicitly. Once the user chooses+that account, `hypit auth login images.personal` securely enters the key into its declared store.+`plan` checks the requested parameters; `pricing` supplies the service's rates. Submitting a real+generation follows the agreed production scope and spending authority.++## Owners++- `src/provider.ts`: exact capability, mapping, service support, task lifecycle, pricing and capacity.+- `src/activation.ts`: configuration and package activation through the Runtime SDK.+- Model: author inputs and result meaning. No service URL or account is placed in it.+- Runtime: durable execution, scheduling, credentials supplied to declared slots, and Results.++The Endpoint SDK README owns the precise handler fields; the Runtime SDK README owns activation.+Both are included in the installed Distribution. A new service may need a small immediate handler,+a different upload protocol, or an asynchronous implementation like this one. Those are Provider+decisions within the same public boundary.diff --git a/examples/provider-package/hypit.runtime.json b/examples/provider-package/hypit.runtime.jsonnew file mode 100644index 00000000..4f3b877c--- /dev/null+++ b/examples/provider-package/hypit.runtime.json@@ -0,0 +1,12 @@+{+ "format": "hypit.runtime-local@1",+ "dataRoot": ".hypit/execution",+ "credentials": { "os": { "use": "@hypit/credential-store-os" } },+ "endpoints": {+ "images.personal": {+ "use": "@example/provider-images",+ "config": { "baseUrl": "https://images.example", "apiKey": { "store": "os", "key": "images.personal" } }+ }+ },+ "bindings": { "@hypit/gpt-image@1#gpt-image-2": "images.personal" }+}diff --git a/examples/provider-package/packages/provider-images/package.json b/examples/provider-package/packages/provider-images/package.jsonnew file mode 100644index 00000000..cccd4a03--- /dev/null+++ b/examples/provider-package/packages/provider-images/package.json@@ -0,0 +1,11 @@+{+ "name": "@example/provider-images",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "hypit": { "activation": "./dist/activation.js" },+ "exports": { ".": "./dist/provider.js" },+ "files": ["dist"],+ "scripts": { "build": "tsc -p tsconfig.json" },+ "devDependencies": { "@hypit/hypit": "workspace:*", "typescript": "5.9.3", "@hypit/driver-node": "workspace:*", "@hypit/gpt-image": "workspace:*" }+}diff --git a/examples/provider-package/packages/provider-images/src/activation.ts b/examples/provider-package/packages/provider-images/src/activation.tsnew file mode 100644index 00000000..29ec58ab--- /dev/null+++ b/examples/provider-package/packages/provider-images/src/activation.ts@@ -0,0 +1,24 @@+import {+ createRuntimeEndpointAdapterFacet, runtimeConfigCredentialRef, runtimeConfigExact,+ runtimeConfigObject, runtimeConfigPositiveInteger, runtimeConfigString,+} from "@hypit/hypit/runtime-kit";+import { createImageProvider, providerModule } from "./provider.js";++export default {+ format: "hypit.node-package@1" as const,+ hostFacets: [createRuntimeEndpointAdapterFacet({+ use: providerModule.name,+ activate(context) {+ const config = runtimeConfigObject(context.config, "Image service");+ runtimeConfigExact(config, ["baseUrl", "apiKey", "concurrency", "pollIntervalMs"], "Image service");+ const baseUrl = runtimeConfigString(config.baseUrl, "Image service baseUrl");+ const apiKey = runtimeConfigCredentialRef(config.apiKey, "Image service apiKey");+ if (!baseUrl || !apiKey || !context.pool) throw new Error("Image service requires baseUrl, apiKey and pool");+ return { endpoint: createImageProvider({+ instance: context.instance, pool: context.pool, baseUrl, apiKey,+ concurrency: runtimeConfigPositiveInteger(config.concurrency, "concurrency") ?? 1,+ pollIntervalMs: runtimeConfigPositiveInteger(config.pollIntervalMs, "pollIntervalMs") ?? 2_000,+ }) };+ },+ })],+};diff --git a/examples/provider-package/packages/provider-images/src/provider.ts b/examples/provider-package/packages/provider-images/src/provider.tsnew file mode 100644index 00000000..47827300--- /dev/null+++ b/examples/provider-package/packages/provider-images/src/provider.ts@@ -0,0 +1,122 @@+import { canonicalize, defineEndpointPackage, wakeAfter } from "@hypit/hypit/endpoint-kit";+import type { AsyncEndpoint, CredentialRef, EndpointRequest } from "@hypit/hypit/endpoint-kit";+import { compileWireRequest, generationTypes, sealGeneratedImageSet } from "@hypit/hypit/generation";+import type { GenerationRequest, GenerationWireMapping } from "@hypit/hypit/generation";++export const providerModule = { name: "@example/provider-images", version: "1" } as const;+export const capability = { module: { name: "@hypit/gpt-image", version: "1" }, name: "gpt-image-2" } as const;++// This example service implements only this subset of the model. Its API is described in README.+const mapping: GenerationWireMapping = {+ capability, result: "image", routes: [{ model: "gpt-image-2" }],+ fields: {+ prompt: { as: "value", field: "prompt" },+ aspectRatio: { as: "value", field: "ratio" },+ resolution: { as: "value", field: "size" },+ images: { as: "urlArray", field: "references" },+ },+};++function object(value: unknown): Record<string, unknown> {+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("Expected service object");+ return value as Record<string, unknown>;+}+function text(value: unknown): string {+ if (typeof value !== "string" || value.length === 0) throw new Error("Expected nonempty service text");+ return value;+}+function address(value: string): string {+ const url = new URL(value);+ if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname))) {+ throw new Error("Service URLs require HTTPS or loopback HTTP");+ }+ return url.href;+}++function support(request: EndpointRequest) {+ const ports = (request.constraints as unknown as GenerationRequest).ports;+ const unsupported = ports.resolution?.[0] !== "1K"+ || !["1:1", "9:16", "16:9"].includes(String(ports.aspectRatio?.[0]))+ || Object.keys(ports).some((port) => !(port in mapping.fields))+ || request.pendingInputs?.some((slot) => !(slot.input in mapping.fields));+ return unsupported+ ? { status: "unsupported" as const, reason: "This service offers 1K at 1:1, 9:16 or 16:9, without background control" }+ : { status: "supported" as const };+}++export function createImageProvider(options: {+ instance: string; pool: string; baseUrl: string; apiKey: CredentialRef;+ concurrency?: number; pollIntervalMs?: number; fetch?: typeof globalThis.fetch;+}) {+ const base = address(options.baseUrl).replace(/\/$/u, "");+ const fetcher = options.fetch ?? globalThis.fetch;+ const interval = options.pollIntervalMs ?? 2_000;+ const key = (credentials: Readonly<Record<string, { secret: string }>>) => text(credentials.apiKey?.secret);+ async function json(path: string, secret: string, init: RequestInit = {}) {+ const response = await fetcher(`${base}${path}`, {+ ...init, headers: { ...init.headers, authorization: `Bearer ${secret}` },+ signal: AbortSignal.timeout(30_000),+ });+ if (!response.ok) throw new Error(`Image service ${path} returned HTTP ${response.status}`);+ return object(await response.json());+ }+ const endpoint: AsyncEndpoint = {+ async start(context) {+ const supported = support(context.need);+ if (supported.status === "unsupported") throw new Error(supported.reason);+ const secret = key(context.credentials);+ const request = await compileWireRequest(mapping, context.need.constraints as unknown as GenerationRequest,+ async (artifact) => {+ const bytes = await context.resources.get(artifact.resource);+ if (bytes === undefined) throw new Error("Reference image is unavailable");+ const upload = await json("/uploads", secret, {+ method: "POST", headers: { "content-type": artifact.mediaType }, body: new Blob([new Uint8Array(bytes)]),+ });+ return address(text(upload.url));+ });+ const task = await json("/tasks", secret, {+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(request),+ });+ const id = text(task.id), handle = { id }, receipt = { id };+ await context.checkpoint?.({ handle, receipt });+ return { ...wakeAfter(handle, interval), receipt };+ },+ async poll(context) {+ const id = text(object(context.handle).id);+ const task = await json(`/tasks/${encodeURIComponent(id)}`, key(context.credentials));+ if (task.state === "queued" || task.state === "running") {+ return wakeAfter({ id }, interval, Date.now(), { phase: task.state });+ }+ if (task.state === "failed") return {+ status: "failed", failure: { code: "IMAGE_SERVICE_FAILED", message: "Image service task failed" },+ };+ if (task.state !== "succeeded") throw new Error("Image service returned an unknown task state");+ return { status: "ready", handle: { id, url: address(text(task.url)) } };+ },+ async collect(context) {+ // The service returns a signed asset URL; account credentials go only to its API.+ const url = address(text(object(context.handle).url));+ const response = await fetcher(url, { signal: AbortSignal.timeout(60_000) });+ if (!response.ok) throw new Error(`Image download returned HTTP ${response.status}`);+ const mediaType = response.headers.get("content-type")?.split(";")[0]?.trim();+ if (!mediaType?.startsWith("image/")) throw new Error("Image service returned a non-image result");+ const artifact = await context.resources.put(new Uint8Array(await response.arrayBuffer()), mediaType);+ return { status: "completed", result: { value: {+ kind: "inline", value: canonicalize(sealGeneratedImageSet({ images: [artifact] })),+ } } };+ },+ };+ return defineEndpointPackage({+ module: providerModule, facet: "images", instance: options.instance, pool: options.pool,+ credentials: { apiKey: options.apiKey }, credentialInputs: { apiKey: { label: "Image service API key" } },+ defaultConcurrency: options.concurrency ?? 1,+ actionLimits: { submit: { concurrency: 1 }, poll: { concurrency: 4 }, collect: { concurrency: 1 } },+ pricing: { kind: "page", url: `${base}/pricing` },+ async readPricing(context) {+ const source = `${base}/rates?model=gpt-image-2`;+ const rates = await json("/rates?model=gpt-image-2", key(await context.credentials()));+ return [{ source, data: canonicalize(rates), summary: text(rates.description) }];+ },+ capabilities: [{ capability, returns: generationTypes.imageSet, lifecycle: "asynchronous", supports: support, endpoint }],+ });+}diff --git a/examples/provider-package/packages/provider-images/test/provider.test.ts b/examples/provider-package/packages/provider-images/test/provider.test.tsnew file mode 100644index 00000000..e59f9227--- /dev/null+++ b/examples/provider-package/packages/provider-images/test/provider.test.ts@@ -0,0 +1,70 @@+import assert from "node:assert/strict";+import test from "node:test";+import { EndpointRegistry, MemoryResourceStore } from "@hypit/driver-node";+import { sealGptImage2Request } from "@hypit/gpt-image";+import type { BlobRef, EndpointStartContext } from "@hypit/hypit/endpoint-kit";+import { canonicalize } from "@hypit/hypit/endpoint-kit";+import { generationTypes } from "@hypit/hypit/generation";+import { capability, createImageProvider } from "../src/provider.js";++test("project Provider maps a reference, retains its receipt and collects through the public resource port", async () => {+ const resources = new MemoryResourceStore();+ const source = await resources.put(new Uint8Array([1, 2, 3]), "image/png");+ const calls: string[] = [];+ let checkpoint: unknown;+ const provider = createImageProvider({+ instance: "images.personal", pool: "images.personal", baseUrl: "https://images.example",+ apiKey: { store: "os", key: "images.personal" }, pollIntervalMs: 0,+ fetch: async (input, init) => {+ const url = new URL(String(input)); calls.push(url.pathname);+ if (url.hostname === "assets.example") {+ assert.equal(init?.headers, undefined);+ return new Response(new Uint8Array([4, 5, 6]), { headers: { "content-type": "image/webp" } });+ }+ assert.equal((init?.headers as Record<string, string>).authorization, "Bearer test-key");+ if (url.pathname === "/rates") return Response.json({ description: "$0.05 per 1K image", unit: "image", usd: 0.05 });+ if (url.pathname === "/uploads") {+ assert.deepEqual(new Uint8Array(await (init?.body as Blob).arrayBuffer()), new Uint8Array([1, 2, 3]));+ return Response.json({ url: "https://assets.example/reference.png" });+ }+ if (url.pathname === "/tasks") {+ assert.deepEqual(JSON.parse(String(init?.body)), {+ model: "gpt-image-2", input: { prompt: "A portrait", ratio: "9:16", size: "1K", references: ["https://assets.example/reference.png"] },+ });+ return Response.json({ id: "received-task" });+ }+ if (url.pathname === "/tasks/received-task") {+ assert.deepEqual(checkpoint, { handle: { id: "received-task" }, receipt: { id: "received-task" } });+ return Response.json({ state: "succeeded", url: "https://assets.example/output.webp" });+ }+ throw new Error(`Unexpected path ${url.pathname}`);+ },+ });+ const constraints = canonicalize(sealGptImage2Request({+ prompt: ["A portrait"], aspectRatio: ["9:16"], resolution: ["1K"], images: [{ role: "image", artifact: source }],+ }));+ const need = { id: "need:example", capability, returns: generationTypes.imageSet, constraints, result: "record:example" } as const;+ const registry = new EndpointRegistry(); await provider.install(registry);+ const resolution = registry.resolve(need);+ assert.equal(resolution.status, "resolved");+ assert.equal(resolution.registration.kind, "asynchronous");+ const endpoint = resolution.registration.endpoint;+ const context: EndpointStartContext = {+ need, command: { kind: "fulfill-need", id: "command:example", need }, operation: "operation:example",+ resources, credentials: { apiKey: { secret: "test-key" } },+ checkpoint: async (value) => { checkpoint = value; },+ };+ const pricing = await provider.readPricing!({ request: need, credentials: async () => context.credentials });+ assert.equal(pricing[0]?.summary, "$0.05 per 1K image");+ const start = await endpoint.start(context); assert.equal(start.status, "pending");+ const ready = await endpoint.poll({ ...context, handle: start.handle }); assert.equal(ready.status, "ready");+ const collected = await endpoint.collect!({ ...context, handle: ready.handle }); assert.equal(collected.status, "completed");+ assert.equal(collected.result.value.kind, "inline");+ const images = (collected.result.value.value as unknown as { images: BlobRef[] }).images;+ assert.equal(images[0]?.mediaType, "image/webp");+ assert.deepEqual(await resources.get(images[0]!.resource), new Uint8Array([4, 5, 6]));+ assert.deepEqual(calls, ["/rates", "/uploads", "/tasks", "/tasks/received-task", "/output.webp"]);+ assert.equal(provider.offers[0]!.supports!({ ...need, constraints: canonicalize(sealGptImage2Request({+ prompt: ["A portrait"], aspectRatio: ["9:16"], resolution: ["2K"],+ })) }).status, "unsupported");+});diff --git a/examples/provider-package/packages/provider-images/tsconfig.json b/examples/provider-package/packages/provider-images/tsconfig.jsonnew file mode 100644index 00000000..741d98f2--- /dev/null+++ b/examples/provider-package/packages/provider-images/tsconfig.json@@ -0,0 +1,9 @@+{+ "compilerOptions": {+ "target": "ES2023", "module": "NodeNext", "moduleResolution": "NodeNext",+ "lib": ["ES2023", "DOM"], "strict": true, "noUncheckedIndexedAccess": true,+ "exactOptionalPropertyTypes": true, "verbatimModuleSyntax": true,+ "declaration": true, "rootDir": "src", "outDir": "dist", "skipLibCheck": true+ },+ "include": ["src/**/*.ts"]+}diff --git a/examples/ranking-football/README.md b/examples/ranking-football/README.mdindex af664623..a2109ff2 100644--- a/examples/ranking-football/README.md+++ b/examples/ranking-football/README.md@@ -24,6 +24,10 @@ parody UI. It does not automatically inherit the host's iPhone capture paragraph## Work with the example+The example Profiles use local media/rendering and HypiHub for hosted capabilities. They illustrate+execution choices; connect the intended account or select project Providers before paid work.+Existing production projects can retain their own Providers independently of these example defaults.+With a configured Runtime and installed Distribution, run from this directory:```bashdiff --git a/examples/ranking-football/reference-banana-from-swap/hypit.runtime.json b/examples/ranking-football/reference-banana-from-swap/hypit.runtime.jsonindex 581b0c04..e9ad64ae 100644--- a/examples/ranking-football/reference-banana-from-swap/hypit.runtime.json+++ b/examples/ranking-football/reference-banana-from-swap/hypit.runtime.json@@ -4,22 +4,9 @@"credentials": {"os": {"use": "@hypit/credential-store-os"- },- "env": {- "use": "@hypit/credential-store-env"}},"endpoints": {- "kie.default": {- "use": "@hypit/provider-kie",- "config": {- "apiKey": {- "store": "env",- "key": "KIE_API_KEY"- },- "defaultConcurrency": 10- }- },"media.local": {"use": "@hypit/provider-media-local","config": {@@ -39,6 +26,15 @@"quality": "standard","defaultConcurrency": 1}+ },+ "hypihub.default": {+ "use": "@hypit/provider-hypihub",+ "config": {+ "apiKey": {+ "store": "os",+ "key": "hypihub.default"+ }+ }}}}diff --git a/examples/ranking-football/reference-banana/hypit.runtime.json b/examples/ranking-football/reference-banana/hypit.runtime.jsonindex a2b83a11..e9ad64ae 100644--- a/examples/ranking-football/reference-banana/hypit.runtime.json+++ b/examples/ranking-football/reference-banana/hypit.runtime.json@@ -7,16 +7,6 @@}},"endpoints": {- "kie.default": {- "use": "@hypit/provider-kie",- "config": {- "apiKey": {- "store": "os",- "key": "KIE_API_KEY"- },- "defaultConcurrency": 10- }- },"media.local": {"use": "@hypit/provider-media-local","config": {@@ -36,6 +26,15 @@"quality": "standard","defaultConcurrency": 1}+ },+ "hypihub.default": {+ "use": "@hypit/provider-hypihub",+ "config": {+ "apiKey": {+ "store": "os",+ "key": "hypihub.default"+ }+ }}}}diff --git a/examples/ranking-football/swap-effect-banana-reference-sync/hypit.runtime.json b/examples/ranking-football/swap-effect-banana-reference-sync/hypit.runtime.jsonindex 581b0c04..e9ad64ae 100644--- a/examples/ranking-football/swap-effect-banana-reference-sync/hypit.runtime.json+++ b/examples/ranking-football/swap-effect-banana-reference-sync/hypit.runtime.json@@ -4,22 +4,9 @@"credentials": {"os": {"use": "@hypit/credential-store-os"- },- "env": {- "use": "@hypit/credential-store-env"}},"endpoints": {- "kie.default": {- "use": "@hypit/provider-kie",- "config": {- "apiKey": {- "store": "env",- "key": "KIE_API_KEY"- },- "defaultConcurrency": 10- }- },"media.local": {"use": "@hypit/provider-media-local","config": {@@ -39,6 +26,15 @@"quality": "standard","defaultConcurrency": 1}+ },+ "hypihub.default": {+ "use": "@hypit/provider-hypihub",+ "config": {+ "apiKey": {+ "store": "os",+ "key": "hypihub.default"+ }+ }}}}diff --git a/examples/ranking-football/swap-effect-banana/hypit.runtime.json b/examples/ranking-football/swap-effect-banana/hypit.runtime.jsonindex 581b0c04..e9ad64ae 100644--- a/examples/ranking-football/swap-effect-banana/hypit.runtime.json+++ b/examples/ranking-football/swap-effect-banana/hypit.runtime.json@@ -4,22 +4,9 @@"credentials": {"os": {"use": "@hypit/credential-store-os"- },- "env": {- "use": "@hypit/credential-store-env"}},"endpoints": {- "kie.default": {- "use": "@hypit/provider-kie",- "config": {- "apiKey": {- "store": "env",- "key": "KIE_API_KEY"- },- "defaultConcurrency": 10- }- },"media.local": {"use": "@hypit/provider-media-local","config": {@@ -39,6 +26,15 @@"quality": "standard","defaultConcurrency": 1}+ },+ "hypihub.default": {+ "use": "@hypit/provider-hypihub",+ "config": {+ "apiKey": {+ "store": "os",+ "key": "hypihub.default"+ }+ }}}}diff --git a/package.json b/package.jsonindex b0e31e3e..23bb9501 100644--- a/package.json+++ b/package.json@@ -157,7 +157,12 @@"examples/semantic-composition/*.svml","examples/semantic-composition/*.svrun","examples/semantic-composition/*.svs",- "examples/semantic-composition/hypit.runtime.json"+ "examples/semantic-composition/hypit.runtime.json",+ "examples/provider-package/README.md",+ "examples/provider-package/packages/*/package.json",+ "examples/provider-package/packages/*/tsconfig.json",+ "examples/provider-package/packages/*/src/**/*",+ "examples/provider-package/hypit.runtime.json"],"scripts": {"pack:distribution": "node scripts/pack-distribution.mjs",@@ -174,7 +179,7 @@"prepack": "npm run build:public-types"},"engines": {- "node": ">=22.12.0"+ "node": ">=22.15.0"},"devDependencies": {"@hypit/artifact": "workspace:*",@@ -219,17 +224,14 @@"@hypit/narrative": "workspace:*","@hypit/performance": "workspace:*","@hypit/performance-studio": "workspace:*",- "@hypit/sound-studio": "workspace:*","@hypit/program-space": "workspace:*",+ "@hypit/project-context-node": "workspace:*","@hypit/protocol": "workspace:*",- "@hypit/provider-hyperframes-aws-lambda": "workspace:*","@hypit/provider-hyperframes-local": "workspace:*","@hypit/provider-hypihub": "workspace:*","@hypit/provider-image-opencv-local": "workspace:*",- "@hypit/provider-kie": "workspace:*","@hypit/provider-media-local": "workspace:*","@hypit/provider-whisperx-local": "workspace:*",- "@hypit/provider-xiaomi-mimo": "workspace:*","@hypit/ranking": "workspace:*","@hypit/ranking-studio": "workspace:*","@hypit/raster": "workspace:*",@@ -248,6 +250,7 @@"@hypit/seedance-kits": "workspace:*","@hypit/seedream": "workspace:*","@hypit/sound": "workspace:*",+ "@hypit/sound-studio": "workspace:*","@hypit/spatial": "workspace:*","@hypit/speech": "workspace:*","@hypit/speech-alignment": "workspace:*",@@ -278,6 +281,7 @@"cmu-pronouncing-dictionary": "3.0.0","tsx": "4.21.0","typescript": "5.9.3",- "vite": "8.2.2"+ "vite": "8.2.2",+ "cjs-module-lexer": "2.2.1"}}diff --git a/packages/background-removal/README.md b/packages/background-removal/README.mdindex 15708ce9..3b78ebcc 100644--- a/packages/background-removal/README.md+++ b/packages/background-removal/README.md@@ -12,13 +12,10 @@ Use it for a product, portrait or graphic that will be composited over another pimage Output. `{cutout.image}` publishes one image BlobArtifact with transparency. Keep its actualdimensions when placing it in Media Track, or use Image Compose when a flattened still is wanted.-The package declares the visual operation; the selected Endpoint implements it. The existing-`@hypit/provider-kie` route uses-[KIE Recraft Remove Background](https://docs.kie.ai/market/recraft/remove-background), sending-`model: "recraft/remove-background"` and `input.image`. It follows the ordinary submit, poll and-collect lifecycle and expects one image result. Another Provider can fulfill the same capability-without changing the Source. This operation therefore needs no separate Recraft-specific author-Model to use the existing KIE implementation.+The package declares the visual operation; a project Provider implements the capability+`@hypit/background-removal@1#remove-background`, accepting `{ source: BlobRef }` and returning one+image BlobRef with transparency. The Provider owns its service's request mapping and task lifecycle.+A service-specific author Model is unnecessary when the operation has this same meaning.For a moving portrait, [Volcengine Matting](../volcengine-matting/README.md) provides`<matte:Portrait source={performance.video}/>` through HypiHub. Normalize its processed videodiff --git a/packages/build-result-s3/src/repository.ts b/packages/build-result-s3/src/repository.tsindex 27af802b..17d7aa80 100644--- a/packages/build-result-s3/src/repository.ts+++ b/packages/build-result-s3/src/repository.ts@@ -1,3 +1,4 @@+import { preserveExecutionLog } from "@hypit/build-result";import type {BuildResultFileRef,ExternalFileAccess,@@ -120,10 +121,13 @@ class S3BuildResultWriter implements BuildResultWriter {await this.#repository.deleteWriter(this.#build);return manifest;}+ const executionLog = await preserveExecutionLog(input.executionLog,+ async (path, chunks, mediaType) => await this.#repository.writeFile(this.#build, path, chunks, mediaType));const now = Date.now();const updated: BuildResultManifest = {...manifest,outcome: input.outcome,+ ...(executionLog === undefined ? {} : { executionLog }),...(input.operations === undefined ? {} : { operations: input.operations }),finishedAt: manifest.finishedAt ?? now,...(input.failure === undefined ? {} : { failure: input.failure }),diff --git a/packages/build-result-s3/test/repository.test.ts b/packages/build-result-s3/test/repository.test.tsindex 12bac9e8..8831fab3 100644--- a/packages/build-result-s3/test/repository.test.ts+++ b/packages/build-result-s3/test/repository.test.ts@@ -491,3 +491,41 @@ test("S3 Composite values retain external and prior-Result Resource references",for await (const chunk of (await repository.openFile(reusedId, externalRef, { start: 1, endExclusive: 3 }))!) selected.push(chunk);assert.deepEqual(Buffer.concat(selected), Buffer.from([5, 6]));});++test("S3 preserves execution evidence before terminal publication and does not repeat it on finish", async () => {+ const client = new MemoryS3();+ const repository = new S3BuildResultRepository({ bucket: "unused", prefix: "project", client });+ const id = "bld_20260913T130000000Z_0000000001";+ const writer = await repository.create({ id, source: { path: "main.svml" }, targets: [], publishedOutputs: [] });+ const text = '{"format":"hypit.execution-log@1","message":"renderer stopped"}\n';+ const manifest = await writer.finish({ outcome: "cancelled", executionLog: (async function* () { yield Buffer.from(text); })() });+ assert.ok(manifest.executionLog);+ assert.deepEqual(manifest.outputs, {});+ assert.equal(manifest.executionLog.size, Buffer.byteLength(text));+ assert.ok(client.writes.at(-2)?.endsWith("execution.jsonl"));+ assert.ok(client.writes.at(-1)?.endsWith("result.json"));+ const reopened = await repository.read(id);+ const stream = await repository.openFile(id, reopened!.executionLog!);+ let read = "";+ for await (const chunk of stream!) read += Buffer.from(chunk).toString();+ assert.equal(read, text);+ const count = client.writes.length;+ await writer.finish({ outcome: "cancelled" });+ assert.equal(client.writes.length, count);+});++test("failed log archival keeps the Result open and finishing again performs only storage", async () => {+ const client = new MemoryS3();+ const repository = new S3BuildResultRepository({ bucket: "unused", prefix: "project", client });+ const id = "bld_20260913T130000000Z_0000000002";+ const writer = await repository.create({ id, source: { path: "main.svml" }, targets: [], publishedOutputs: [] });+ await assert.rejects(writer.finish({ outcome: "failed", failure: "render stopped", executionLog: (async function* () {+ yield Buffer.from('first record\n'); throw new Error("log read failed");+ })() }), /log read failed/);+ assert.equal((await repository.read(id))!.outcome, undefined);+ const result = await writer.finish({ outcome: "failed", failure: "render stopped", executionLog: (async function* () {+ yield Buffer.from('complete record\n');+ })() });+ assert.equal(result.outcome, "failed");+ assert.ok(result.executionLog);+});diff --git a/packages/build-result/README.md b/packages/build-result/README.mdindex c4fd9e22..2c305c29 100644--- a/packages/build-result/README.md+++ b/packages/build-result/README.md@@ -56,3 +56,14 @@ It is presentation text only: Output names, forwarding and file ownership do not`updatePresentation` accepts `outputDisplayNames`, keyed by exact public Output name. Eachnonempty string sets that Output’s `displayName`; null removes it. Like title and note editing,this applies to finished Results and preserves all values, file references and Output identifiers.++## Execution evidence++A finished manifest may contain `executionLog`, an ordinary Result file reference separate from+`outputs`. `BuildResultWriter.finish({ executionLog, outcome, ... })` accepts a byte stream. Repositories+preserve it as `execution.jsonl` before the terminal manifest is published. The filesystem and S3+implementations use the same interface. Repeating an already completed finish does not rewrite it.++This file describes how the Build ran; it is neither an authored Output nor a gallery asset. Consumers+read it with `openFile(build, manifest.executionLog)`. Its absence means no log was recorded, including+Results made before logging was available; readers do not reconstruct history from other projects.diff --git a/packages/build-result/src/decode.ts b/packages/build-result/src/decode.tsindex d5690630..4e86d510 100644--- a/packages/build-result/src/decode.ts+++ b/packages/build-result/src/decode.ts@@ -202,6 +202,7 @@ export function decodeBuildResultManifest(throw new Error(`${subject} must be either unfinished or have both outcome and finishedAt`);}const failure = optionalString(item.failure, `${subject}.failure`);+ if (item.executionLog !== undefined) assertBuildResultFileRef(item.executionLog, `${subject}.executionLog`);return {format: "hypit.build-result@1",id,@@ -215,6 +216,7 @@ export function decodeBuildResultManifest(...(outcome === undefined ? {} : { outcome }),...(failure === undefined ? {} : { failure }),outputs: outputs(item.outputs, `${subject}.outputs`),+ ...(item.executionLog === undefined ? {} : { executionLog: item.executionLog }),...(item.operations === undefined ? {} : { operations: operationReceipts(item.operations, `${subject}.operations`) }),};}diff --git a/packages/build-result/src/execution-log.ts b/packages/build-result/src/execution-log.tsnew file mode 100644index 00000000..bf83b34f--- /dev/null+++ b/packages/build-result/src/execution-log.ts@@ -0,0 +1,17 @@+import type { BuildResultFileRef } from "./types.js";++/** Execution evidence is a Result file, not an authored Output or generated asset. */+export async function preserveExecutionLog(+ chunks: AsyncIterable<Uint8Array> | undefined,+ write: (path: string, chunks: AsyncIterable<Uint8Array>, mediaType: string) => Promise<void>,+): Promise<BuildResultFileRef | undefined> {+ if (chunks === undefined) return undefined;+ let size = 0;+ const counted = (async function* () {+ for await (const chunk of chunks) { size += chunk.byteLength; yield chunk; }+ })();+ const path = "execution.jsonl";+ const mediaType = "application/x-ndjson";+ await write(path, counted, mediaType);+ return { kind: "build-file", path, size, mediaType };+}diff --git a/packages/build-result/src/index.ts b/packages/build-result/src/index.tsindex 8ce9d898..7b322415 100644--- a/packages/build-result/src/index.ts+++ b/packages/build-result/src/index.ts@@ -26,3 +26,4 @@ export type * from "./writer.js";export { currentFileReference, fileReferenceIdentity, ownedFileReference, localExternalFiles } from "./file-reference.js";export type { ExternalFileAccess } from "./file-reference.js";+export { preserveExecutionLog } from "./execution-log.js";diff --git a/packages/build-result/src/store.ts b/packages/build-result/src/store.tsindex c6fe96c1..1e0a1b4f 100644--- a/packages/build-result/src/store.ts+++ b/packages/build-result/src/store.ts@@ -1,3 +1,4 @@+import { preserveExecutionLog } from "./execution-log.js";import { currentFileReference, localExternalFiles } from "./file-reference.js";import type { ExternalFileAccess } from "./file-reference.js";import { randomUUID } from "node:crypto";@@ -134,12 +135,21 @@ async function copyArtifactAtomic(await mkdir(dirname(destination), { recursive: true });const input = await source.open(artifact);if (input === undefined) throw new Error(`Build resource ${artifact.resource} is unavailable`);+ await writeStreamAtomic(destination, input);+}++async function writeStreamAtomic(destination: string, input: AsyncIterable<Uint8Array>): Promise<void> {+ await mkdir(dirname(destination), { recursive: true });const temporary = `${destination}.part-${randomUUID()}`;const output = await open(temporary, "wx");try {for await (const value of input) {const chunk = Uint8Array.from(value);- await output.write(chunk);+ let offset = 0;+ while (offset < chunk.byteLength) {+ const { bytesWritten } = await output.write(chunk, offset, chunk.byteLength - offset);+ offset += bytesWritten;+ }}await output.close();await replaceFile(temporary, destination);@@ -442,10 +452,13 @@ export class FileBuildResult {await rm(join(this.directory, writerStateName), { force: true });return manifest;}+ const executionLog = await preserveExecutionLog(input.executionLog,+ async (path, chunks) => await writeStreamAtomic(join(this.directory, path), chunks));const now = Date.now();const updated: BuildResultManifest = {...manifest,outcome: input.outcome,+ ...(executionLog === undefined ? {} : { executionLog }),...(input.operations === undefined ? {} : { operations: input.operations }),finishedAt: manifest.finishedAt ?? now,...(input.failure === undefined ? {} : { failure: input.failure }),diff --git a/packages/build-result/src/types.ts b/packages/build-result/src/types.tsindex 9d01ed1a..0c1b857d 100644--- a/packages/build-result/src/types.ts+++ b/packages/build-result/src/types.ts@@ -206,6 +206,7 @@ export type BuildResultManifest = {readonly failure?: string;readonly outputs: Readonly<Record<string, BuildResultOutput>>;readonly operations?: readonly BuildResultOperation[];+ readonly executionLog?: BuildResultFileRef;};export type FinishedBuildResultManifest = BuildResultManifest & {@@ -294,6 +295,8 @@ export type BuildResultSync = {};export type BuildResultFinish = {+ /** Closed execution evidence; Repository stores it before publishing the terminal manifest. */+ readonly executionLog?: AsyncIterable<Uint8Array>;readonly operations?: readonly BuildResultOperation[];readonly outcome: BuildResultOutcome;readonly failure?: string;diff --git a/packages/caption-fine/src/render.ts b/packages/caption-fine/src/render.tsindex ea1414b2..02ce6f02 100644--- a/packages/caption-fine/src/render.ts+++ b/packages/caption-fine/src/render.ts@@ -788,8 +788,8 @@ function cueElements(const next = atoms[prefixIndex + 1];const nextStart = next === undefined ? durationFrames : atomFrames.get(next.id)?.start;if (nextStart === undefined) throw new Error("Fine Caption is missing timing for the next Atom");- // A no-break timeline inside an atom keeps its words on one row; the boundaries between atoms- // take an ordinary timeline. Both are spaced only where the surfaces meeting there call for one.+ // A no-break space inside an atom keeps its words on one row; the boundaries between atoms+ // take an ordinary space. Both are spaced only where the surfaces meeting there call for one.const prefixText = joinSurfaces(atoms.slice(0, prefixIndex + 1).map((prefixAtom, index) => {for (const wordId of prefixAtom.wordIds) {@@ -1078,7 +1078,7 @@ export function renderFineCaption(assertProgramSpaceIdentity(timeline);if (schedule.spaceId !== timeline.id || schedule.narrativeId !== document.narrativeId) {- throw new Error("Fine Caption inputs belong to different ProgramSpaces or Narratives");+ throw new Error("Fine Caption inputs belong to different Timelines or Narratives");}const styles = new Map(program.styles.map((style) => [style.id, style]));const wordText = new Map(document.words.map((word) => [word.id, word.text]));diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 4555dc86..6bb05699 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -11,9 +11,37 @@ Source imports decide which language and component packages give the source meanProfile separately selects Credential Stores and Endpoints allowed to execute work. The CLI does notinvent targets, candidates or Provider choices.-Human output is compact by default. `--json` emits a command-specific view rather than raw compiler,-Runtime or Repository objects. `--verbose` adds operational detail; it never turns the command into-an internal state dump.+Human and JSON output answer the same command-specific question. `--json` changes encoding;+`--verbose` expands scope. Compiler, Runtime and Repository objects are not default reports.++| Command | Default scope | Explicit detail |+| --- | --- | --- |+| `check` | Validation, targets and counts | `--verbose`: exported names/types and historical references |+| `plan` | Targets, demanded requests, Endpoint selection and diagnostics | `--verbose`: Run choices, graph step count and unreached declarations |+| `pricing` | Requests that may incur a Provider charge and their rate material | `--verbose`: declared no-charge requests and original documents |+| `status`, `activity` | Current work, Provider-reported phases and failures | `--verbose`: individual operations; activity also includes capacity reservations |+| `inspect` | Targets and explicitly highlighted Outputs, outcome and failure evidence | `--output <name>` selects one Output; `--verbose` browses all available Outputs and receipts |+| `doctor`, `programs` | Complete diagnostics; program discovery or the unmet result of an explicit lifecycle action | `--verbose`: successful lifecycle details; `--limit` bounds the healthy program list |++Run choices count explicit Candidate selections, which can supply existing work or execute an+alternative producer. They are not a count of reused files. Result output counts describe all+available named Outputs, including forwarded ones; they are not a count of newly generated assets.+`history <output>` lists Builds containing that name, including reuse, rather than deduplicating+generation events or guessing whether mutable external files still contain the same bytes.+`inspect` chooses names before resolving references, so an unrelated Output cannot delay or break+inspection of a target. It reports the number of other Outputs without reading their descriptions.++`plan` retains every target, demanded request and preflight diagnostic in both encodings. `--limit`+bounds expanded detail, not the work inventory before grouping. `inspect` likewise keeps its default+target/highlight selection intact; `--limit` bounds the broader `--verbose` list, with an omitted count.+No-charge classification continues to belong to the selected Endpoint's pricing declaration.++Build follow and status include Provider-reported local Command activity as well as asynchronous+Operations. Follow coalesces counters into readable updates and continues to distinguish execution+from Result saving. Status groups identical active Operations and retains failures by default;+completed receipts are detail. Activity reports the phases that trigger its updates and ignores+changes confined to Builds outside the displayed page. Providers own the phase vocabulary; the CLI+does not interpret model or renderer names.## Project and Runtime context@@ -24,7 +52,8 @@ directory, including when `--workspace` is supplied.Runtime-aware commands use an explicit `--runtime` for that invocation, or read exactly the resolvedproject's `.hypit/runtime` pointer. `runtime use` writes the pointer; a Profile filename by itself does-not select it. Project selection is also available on `paths`, `doctor`, execution status/control,+not select it. The pointer is a file, separate from the Profile's `dataRoot`; a directory at that+path is reported explicitly and preserved. Project selection is also available on `paths`, `doctor`, execution status/control,Runtime operations, `programs` and `auth`. Machine-wide `packages` operations have no project selector.`paths` shows the effective locations and whether the Profile came from a command argument, a project@@ -46,6 +75,9 @@ settings without searching arbitrary records for a request-shaped object. When amade by an earlier Build step, that direct graph edge stays symbolic until the file exists; the restof the request is still shown. A complete request is resolved through the same Endpoint Registry asthe Build, including the Endpoint's `supports` check.+Each component's planned-Need presentation owns its useful request fields. An empty presentation+means the summary is unavailable, not that the request has no parameters. Structured render inputs+are summarized by their owning packages; the CLI does not traverse upstream graphs to invent them.`pricing <run>` uses that selected Runtime to read Provider-owned rate material. The default reportsummarizes requests whose resolved Endpoint explicitly declares `pricing.kind: "local"` as having no@@ -74,3 +106,24 @@ machine-view union. `main.ts` resolves project and selected Runtime context sepasyntax, then routes these command groups. Result commands do not consult or construct a Runtime,and the generic CLI cannot silently choose a Result Repository or a Provider-specific loginflow.++## Execution logs++`hypit logs <build-id> [--workspace <project>] [--runtime <profile>] [--lines <count>]` reads Build+execution phases and Provider diagnostics. It reads a finished Result directly, without opening the+Runtime; an active Build is read through Runtime control. The selected Repository handles file access.+`--lines` limits the tail and the report states the omitted count; JSON carries records plus that count.+`inspect` exposes an available log separately from authored Outputs. `hypit runtime logs` reads the+Worker process log instead, for Runtime startup or process-level failures.++Project context resolution is owned by [`@hypit/project-context-node`](../project-context-node/README.md).+CLI, Studio and creation tools call that same package; the CLI is not another environment owner.++`doctor`, `programs up|status|down`, and `runtime up` accept repeated `--endpoint <instance>` values.+The same Endpoint scope reaches package preparation and Program operations. Omission means the whole+Profile. Build preflight instead uses the Endpoints resolved for that Build's concrete requests.+An unrelated offered capability does not add another credential or Program requirement.++Upstream package installation reports an `install.log` path at preparation time. Exact package+releases coexist below the machine home, each with npm's own package.json and lockfile. `paths` shows+the home; `packages status <name@version>` checks the requested release rather than a mutable latest copy.diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex fb0d3002..10b6d058 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -16,6 +16,7 @@"@hypit/driver-node": "workspace:*","@hypit/elaborator": "workspace:*","@hypit/package-loader-node": "workspace:*",+ "@hypit/project-context-node": "workspace:*","@hypit/protocol": "workspace:*","@hypit/run": "workspace:*","@hypit/runtime": "workspace:*",diff --git a/packages/cli/src/arguments.ts b/packages/cli/src/arguments.tsindex a6f9a648..9ecf86f6 100644--- a/packages/cli/src/arguments.ts+++ b/packages/cli/src/arguments.ts@@ -18,6 +18,7 @@ type RawOptions = {readonly presentation: CliOutputOptions;readonly workspaceRoot?: string;readonly assetRoots: readonly string[];+ readonly endpoints: readonly string[];readonly packageRoot?: string;readonly runtimeProfile?: string;readonly follow: boolean;@@ -36,6 +37,7 @@ type RawOptions = {readonly watch: boolean;readonly readyFile?: string;readonly workerOwner?: string;+ readonly executionRoot?: string;readonly reason?: string;readonly slot?: string;readonly credentialFile?: string;@@ -155,6 +157,12 @@ export function parseCommand(argv: readonly string[]): CliCommand {...optionalProject(options),};}+ case "logs": {+ const [build, rest] = requiredPositional(tail, "logs requires one Build id");+ const options = commandOptions(command, rest, "--runtime", "--workspace", "--lines");+ return { command, build, lines: options.lines, presentation: options.presentation,+ ...optionalProject(options), ...optionalRuntime(options) };+ }case "status": {const [build, rest] = requiredPositional(tail, "status requires one Build id");const options = commandOptions(command, rest, "--runtime", "--workspace", "--watch", "--max-wait-ms", "--limit");@@ -205,12 +213,13 @@ export function parseCommand(argv: readonly string[]): CliCommand {case "auth": return parseAuthCommand(tail);case "doctor": {const [profile, rest] = optionalPositional(tail);- const options = commandOptions(command, rest, "--workspace", "--runtime", "--limit");+ const options = commandOptions(command, rest, "--workspace", "--runtime", "--limit", "--endpoint");if (profile !== undefined && options.runtimeProfile !== undefined) {throw new Error("doctor accepts the Runtime Profile either positionally or with --runtime, not both");}return {command,+ ...(options.endpoints.length === 0 ? {} : { endpoints: options.endpoints }),presentation: options.presentation,limit: options.limit,...optionalProject(options),@@ -223,7 +232,7 @@ export function parseCommand(argv: readonly string[]): CliCommand {}case "_worker": {const [profile, rest] = requiredPositional(tail, "internal Worker launch is incomplete");- const options = commandOptions(command, rest, "--ready-file", "--worker-owner", "--package-root");+ const options = commandOptions(command, rest, "--ready-file", "--worker-owner", "--package-root", "--execution-root");if (options.readyFile === undefined || options.workerOwner === undefined) {throw new Error("internal Worker launch is incomplete");}@@ -232,6 +241,7 @@ export function parseCommand(argv: readonly string[]): CliCommand {profile,readyFile: options.readyFile,workerOwner: options.workerOwner,+ ...(options.executionRoot === undefined ? {} : { executionRoot: options.executionRoot }),presentation: options.presentation,...optionalPackageRoot(options),};@@ -305,7 +315,7 @@ function parseRuntimeCommand(tail: readonly string[]): RuntimeSelectionCommand |}const [profile, rest] = optionalPositional(values);const allowed = action === "up" || action === "down"- ? ["--runtime", "--max-wait-ms"] as const+ ? action === "up" ? ["--runtime", "--max-wait-ms", "--endpoint"] as const : ["--runtime", "--max-wait-ms"] as const: action === "status"? ["--runtime", "--limit"] as const: ["--runtime", "--lines"] as const;@@ -320,7 +330,7 @@ function parseRuntimeCommand(tail: readonly string[]): RuntimeSelectionCommand |...optionalProject(options),};if (action === "up" || action === "down") {- return { ...common, action, ...(options.maxWaitMs === undefined ? {} : { maxWaitMs: options.maxWaitMs }) };+ return { ...common, action, ...(action === "up" && options.endpoints.length > 0 ? { endpoints: options.endpoints } : {}), ...(options.maxWaitMs === undefined ? {} : { maxWaitMs: options.maxWaitMs }) };}if (action === "status") return { ...common, action, limit: options.limit };return { ...common, action, lines: options.lines };@@ -333,7 +343,7 @@ function parseProgramsCommand(tail: readonly string[]): ProgramsCommand {}const [profile, rest] = optionalPositional(values);const options = commandOptions(`programs ${action}`, rest,- "--runtime", "--workspace", "--limit", "--max-wait-ms");+ "--runtime", "--workspace", "--limit", "--max-wait-ms", "--endpoint");if (action !== "up" && options.maxWaitMs !== undefined) {throw new Error("--max-wait-ms applies to programs up");}@@ -341,6 +351,7 @@ function parseProgramsCommand(tail: readonly string[]): ProgramsCommand {const runtime = runtimeOption(profile ?? options.runtimeProfile);const common = {command: "programs" as const,+ ...(options.endpoints.length === 0 ? {} : { endpoints: options.endpoints }),action,presentation: options.presentation,limit: options.limit,@@ -403,6 +414,7 @@ function parseOptions(values: readonly string[]): RawOptions {let runtimeProfile: string | undefined;let follow = false;let maxWaitMs: number | undefined;+ const endpoints: string[] = [];let outputName: string | undefined;let title: string | undefined;let note: string | undefined;@@ -421,6 +433,7 @@ function parseOptions(values: readonly string[]): RawOptions {let watch = false;let readyFile: string | undefined;let workerOwner: string | undefined;+ let executionRoot: string | undefined;let reason: string | undefined;let slot: string | undefined;let credentialFile: string | undefined;@@ -429,7 +442,7 @@ function parseOptions(values: readonly string[]): RawOptions {for (let index = 0; index < values.length; index += 1) {const item = values[index]!;if (!item.startsWith("--")) throw new Error(`unexpected positional argument ${item}`);- const repeatable = [+ const repeatable = item === "--endpoint" || ["--json", "--jsonl", "--watch", "--verbose", "--debug","--no-color", "--follow", "--asset-root", "--highlight",].includes(item);@@ -450,6 +463,7 @@ function parseOptions(values: readonly string[]): RawOptions {index += 1;continue;}+ if (item === "--endpoint") { endpoints.push(optionValue(values, index, "--endpoint requires an Endpoint name")); index += 1; continue; }if (item === "--workspace") {workspaceRoot = resolve(optionValue(values, index, "--workspace requires a directory")); index += 1; continue;}@@ -506,6 +520,9 @@ function parseOptions(values: readonly string[]): RawOptions {if (item === "--worker-owner") {workerOwner = optionValue(values, index, "--worker-owner requires an identity"); index += 1; continue;}+ if (item === "--execution-root") {+ executionRoot = resolve(optionValue(values, index, "--execution-root requires a path")); index += 1; continue;+ }if (item === "--reason") {reason = optionValue(values, index, "--reason requires text"); index += 1; continue;}@@ -527,6 +544,7 @@ function parseOptions(values: readonly string[]): RawOptions {presentation: { json: json || jsonl, ...(jsonl ? { jsonl: true } : {}), color, verbose },assetRoots,follow,+ endpoints,highlightedOutputs,clearTitle,clearNote,@@ -546,6 +564,7 @@ function parseOptions(values: readonly string[]): RawOptions {...(destination === undefined ? {} : { destination }),...(readyFile === undefined ? {} : { readyFile }),...(workerOwner === undefined ? {} : { workerOwner }),+ ...(executionRoot === undefined ? {} : { executionRoot }),...(reason === undefined ? {} : { reason }),...(slot === undefined ? {} : { slot }),...(credentialFile === undefined ? {} : { credentialFile }),diff --git a/packages/cli/src/build-planning.ts b/packages/cli/src/build-planning.tsindex 6fada047..70e5938d 100644--- a/packages/cli/src/build-planning.ts+++ b/packages/cli/src/build-planning.ts@@ -421,9 +421,10 @@ export function assertPlannedRequests(}}-export async function preflightPlan(host: NodeRuntimeHost, state: BuildState) {+export async function preflightPlan(host: NodeRuntimeHost, state: BuildState, providers: readonly PlanProviderView[]) {const capabilities = demandedCapabilities(state);- const result = await host.preflight({ capabilities });+ const endpoints = [...new Set(providers.flatMap((item) => item.status === "resolved" && item.endpoint !== undefined ? [item.endpoint] : []))];+ const result = await host.preflight({ endpoints });return {ok: !result.diagnostics.some((item) => item.severity === "error"),capabilities: capabilities.map(capabilityName),diff --git a/packages/cli/src/command.ts b/packages/cli/src/command.tsindex 813606de..37bcdafd 100644--- a/packages/cli/src/command.ts+++ b/packages/cli/src/command.ts@@ -72,6 +72,7 @@ export type ProjectResultCommand =});export type ExecutionCommand =+ | (CommandBase & RuntimeOption & { readonly command: "logs"; readonly build: string; readonly lines: number })| (CommandBase & RuntimeOption & {readonly command: "status";readonly build: string;@@ -115,6 +116,7 @@ export type RuntimeOperationCommand =| (CommandBase & RuntimeOption & {readonly command: "runtime";readonly action: "up";+ readonly endpoints?: readonly string[];readonly maxWaitMs?: number;})| (CommandBase & RuntimeOption & {@@ -136,12 +138,14 @@ export type RuntimeOperationCommand =export type ProgramsCommand =| (CommandBase & RuntimeOption & {readonly command: "programs";+ readonly endpoints?: readonly string[];readonly action: "up";readonly maxWaitMs?: number;readonly limit: number;})| (CommandBase & RuntimeOption & {readonly command: "programs";+ readonly endpoints?: readonly string[];readonly action: "down" | "status";readonly limit: number;});@@ -182,6 +186,7 @@ export type EnvironmentCommand =})| (CommandBase & ProjectOption & RuntimeOption & {readonly command: "doctor";+ readonly endpoints?: readonly string[];readonly limit: number;});@@ -190,6 +195,7 @@ export type WorkerCommand = CommandBase & {readonly profile: string;readonly readyFile: string;readonly workerOwner: string;+ readonly executionRoot?: string;readonly packageRoot?: string;};diff --git a/packages/cli/src/commands/environment.ts b/packages/cli/src/commands/environment.tsindex d4c8ffae..c723906f 100644--- a/packages/cli/src/commands/environment.ts+++ b/packages/cli/src/commands/environment.ts@@ -73,8 +73,8 @@ export async function runEnvironmentCommand(input: {};const reportPackageProgress = args.presentation.json? undefined- : (event: { readonly specifier: string; readonly phase: "checking" | "installing" | "ready" }): void => {- if (event.phase === "installing") io.write(` · Installing ${event.specifier}\n`);+ : (event: { readonly specifier: string; readonly phase: "checking" | "installing" | "ready"; readonly logPath?: string }): void => {+ if (event.phase === "installing") io.write(` · Installing ${event.specifier}${event.logPath === undefined ? "" : ` · log ${event.logPath}`}\n`);};const reportCredentialProgress = args.presentation.json? io.writeProgress@@ -126,10 +126,13 @@ export async function runEnvironmentCommand(input: {action: args.action,package: args.package,ready,+ ...(reports[0] === undefined ? {} : { installation: reports[0].root }),+ ...(reports[0]?.logPath === undefined ? {} : { logPath: reports[0].logPath }),}, args.action === "install" ? "Machine package is ready" : "Machine package status",ready ? "success" : "warning", [["Package", args.package],["Ready", String(ready)],+ ...(args.presentation.verbose && reports[0] !== undefined ? [["Installation", reports[0].root] as const] : []),]);if (!ready) io.setExitCode?.(1);return;@@ -138,7 +141,7 @@ export async function runEnvironmentCommand(input: {if (args.command === "doctor") {const profile = runtimeProfile === undefined ? undefined : resolve(runtimeProfile);const [runtimeResult, projectResult] = await Promise.all([- profile === undefined ? undefined : (await runtimeHost(profile)).doctor(),+ profile === undefined ? undefined : (await runtimeHost(profile)).doctor(args.endpoints === undefined ? {} : { endpoints: args.endpoints }),distribution.diagnoseProjectResults(projectRoot, {packageRoot: await packageRootForProject(),...(distribution.packageRoot === undefined@@ -155,8 +158,7 @@ export async function runEnvironmentCommand(input: {...(runtimeSelectionFile === undefined ? {} : { selectionFile: runtimeSelectionFile }),...(profile === undefined ? {} : { profile }),diagnosticCount: diagnostics.length,- diagnostics: diagnostics.slice(0, args.limit),- ...(diagnostics.length <= args.limit ? {} : { omittedDiagnostics: diagnostics.length - args.limit }),+ diagnostics,};writeCliOutput(io, args.presentation, { kind: "doctor", machine });if (!machine.ok) io.setExitCode?.(1);@@ -168,21 +170,27 @@ export async function runEnvironmentCommand(input: {const profile = resolve(runtimeProfile);const host = await runtimeHost(profile);if (args.action === "up") {- await host.prepare(reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress });+ await host.prepare({ ...(args.endpoints === undefined ? {} : { endpoints: args.endpoints }), ...(reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress }) });}const controller = await runtimeController(profile);const result = args.action === "up"? await controller.programs.up({+ ...(args.endpoints === undefined ? {} : { endpoints: args.endpoints }),...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),...(reportProgramProgress === undefined ? {} : { onProgress: reportProgramProgress }),}): args.action === "down"- ? await controller.programs.down()- : await controller.programs.report();+ ? await controller.programs.down(args.endpoints === undefined ? {} : { endpoints: args.endpoints })+ : await controller.programs.report(args.endpoints === undefined ? {} : { endpoints: args.endpoints });const ready = result.programs.every((item) => item.state.state === "ready");const desiredState = args.action === "down" ? !result.programs.some((item) => item.state.state === "ready") : ready;const lifecycleOk = args.action === "status" || desiredState;- const shownPrograms = result.programs.filter((item) => args.presentation.verbose || item.state.state !== "ready").slice(0, args.limit);+ const needsAttention = (item: typeof result.programs[number]) => args.action === "down"+ ? item.state.state === "ready" : item.state.state !== "ready";+ const relevant = result.programs.filter((item) => args.presentation.verbose || args.action === "status" || needsAttention(item));+ const urgent = relevant.filter(needsAttention);+ const shownPrograms = [...urgent, ...relevant.filter((item) => !needsAttention(item)).slice(0, Math.max(0, args.limit - urgent.length))];+ const omittedPrograms = relevant.length - shownPrograms.length;const title = args.action === "up"? desiredState ? "External programs ready" : "External programs need attention": args.action === "down"@@ -192,15 +200,17 @@ export async function runEnvironmentCommand(input: {format: "hypit.cli-programs@1",action: args.action,ready,- programs: result.programs.slice(0, args.limit).map(programRecord),- ...(result.programs.length <= args.limit ? {} : { omittedPrograms: result.programs.length - args.limit }),+ programCount: result.programs.length,+ readyCount: result.programs.filter((item) => item.state.state === "ready").length,+ programs: shownPrograms.map(programRecord),+ ...(omittedPrograms === 0 ? {} : { omittedPrograms }),}, title,args.action === "status" ? ready ? "success" : "info" : lifecycleOk ? "success" : "warning", [...(!args.presentation.verbose && lifecycleOk && args.action !== "status" ? [] : [["Programs", String(result.programs.length)] as const,["Ready", String(result.programs.filter((item) => item.state.state === "ready").length)] as const,]),- ], shownPrograms.map(programDescription));+ ], shownPrograms.map(programDescription).concat(omittedPrograms === 0 ? [] : [`${omittedPrograms} more programs · use --limit <count>`]));if (!lifecycleOk) io.setExitCode?.(1);return;}@@ -213,11 +223,12 @@ export async function runEnvironmentCommand(input: {const packageRoot = await packageRootForProject();const host = await runtimeHost(profile, packageRoot);const prepared = await host.prepare(- reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress },+ { ...(args.endpoints === undefined ? {} : { endpoints: args.endpoints }), ...(reportPackageProgress === undefined ? {} : { onProgress: reportPackageProgress }) },);- const validated = await host.createRuntime();+ const validated = await host.createRuntime(args.endpoints === undefined ? {} : { endpoints: args.endpoints });await validated.close();const external = await controller.programs.up({+ ...(args.endpoints === undefined ? {} : { endpoints: args.endpoints }),...(args.maxWaitMs === undefined ? {} : { maxWaitMs: args.maxWaitMs }),...(reportProgramProgress === undefined ? {} : { onProgress: reportProgramProgress }),});@@ -234,7 +245,7 @@ export async function runEnvironmentCommand(input: {programs: {total: external.programs.length,ready: external.programs.filter((item) => item.state.state === "ready").length,- items: external.programs.map(programRecord),+ items: external.programs.filter((item) => args.presentation.verbose || item.state.state !== "ready").map(programRecord),},}, ok ? "Local Runtime ready" : "Local Runtime needs attention", ok ? "success" : "warning", [...(!args.presentation.verbose && ok ? [] : [@@ -300,13 +311,12 @@ export async function runEnvironmentCommand(input: {attention,worker: {state: worker.state,- ...(worker.configuration === undefined ? {} : { configuration: worker.configuration }),},builds: counts,programs: {total: external.programs.length,ready: external.programs.length - unavailable.length,- unavailable: unavailable.slice(0, args.limit).map((item) => ({ id: item.id, state: item.state.state })),+ unavailable: unavailable.map(programRecord),},capacity: {active: activity.capacity.length,@@ -326,7 +336,7 @@ export async function runEnvironmentCommand(input: {["Capacity in use", String(activity.capacity.length)] as const,] : []),], [- ...unavailable.slice(0, args.limit).map((item) => `${item.id}: ${item.state.state}`),+ ...unavailable.map(programDescription),]);} finally {if (runtime !== undefined) await runtime.close();diff --git a/packages/cli/src/commands/execution.ts b/packages/cli/src/commands/execution.tsindex 84c18ab5..13e17146 100644--- a/packages/cli/src/commands/execution.ts+++ b/packages/cli/src/commands/execution.ts@@ -1,12 +1,14 @@+import { readExecutionLog } from "@hypit/runtime";import type { BuildResultManifest, BuildResultRepository } from "@hypit/build-result";import type { NodeRuntimeHost } from "@hypit/runtime-host-node";import type { CliCommand, ExecutionCommand } from "../command.js";-import { activityObservationKey, buildProgressLines, observeBuildView } from "../observation.js";+import { activityObservationKey, buildProgressLines, buildProgressView, observeBuildView } from "../observation.js";import type { CliIo } from "../output.js";import type { CliRuntimeController } from "../runtime-port.js";import { formatOperationProgress } from "../runtime-view.js";import { buildStatusView } from "../view.js";+import type { CliBuildStatusView } from "../view.js";import type { OperationalWriter } from "./types.js";type OpenProjectResults = () => Promise<{@@ -14,8 +16,21 @@ type OpenProjectResults = () => Promise<{close(): void | Promise<void>;}>;+function statusDetailLines(build: CliBuildStatusView | null): string[] {+ return [+ ...(build?.failure === undefined ? [] : [`Reason ${build.failure}`]),+ ...(build?.commands ?? []).map((command) => `${command.endpoint}: ${formatOperationProgress(command.progress)}`),+ ...(build?.operations ?? []).map((operation) => {+ const label = `${operation.endpoint}${operation.receipt === undefined ? "" : ` · task ${operation.receipt.id}`}`;+ const detail = operation.failure !== undefined ? `${operation.failure.code} — ${operation.failure.message}`+ : operation.progress === undefined ? operation.state : formatOperationProgress(operation.progress);+ return `${label}: ${detail}${operation.count === undefined ? "" : ` ×${operation.count}`}`;+ }),+ ];+}+export function isExecutionCommand(args: CliCommand): args is ExecutionCommand {- return args.command === "status" || args.command === "cancel" || args.command === "activity"+ return args.command === "logs" || args.command === "status" || args.command === "cancel" || args.command === "activity"|| (args.command === "result" && (args.action === "finish" || args.action === "discard"));}@@ -23,6 +38,7 @@ export function isExecutionCommand(args: CliCommand): args is ExecutionCommand {export async function runExecutionCommand(input: {readonly args: ExecutionCommand;readonly runtimeProfile: string | undefined;+ readonly resolveProjectRuntime?: () => Promise<string | undefined>;readonly io: CliIo;readonly runtimeHost: (profile: string) => Promise<NodeRuntimeHost>;readonly runtimeController: (profile: string) => Promise<CliRuntimeController>;@@ -30,6 +46,53 @@ export async function runExecutionCommand(input: {readonly write: OperationalWriter;}): Promise<void> {const { args, runtimeProfile, io, runtimeHost, runtimeController, openProjectResults, write } = input;+ if (args.command === "logs") {+ const opened = await openProjectResults();+ let source: "runtime" | "result" | "unavailable" = "unavailable";+ let view: import("@hypit/runtime").ExecutionLogView | undefined;+ let finished = false;+ try {+ const result = await opened.repository.read(args.build);+ finished = result?.outcome !== undefined;+ if (result?.executionLog !== undefined) {+ const chunks = await opened.repository.openFile(args.build, result.executionLog);+ if (chunks === undefined) throw new Error(`Build ${args.build} execution log file is unavailable`);+ view = await readExecutionLog(chunks, args.lines);+ source = "result";+ }+ } finally { await opened.close(); }+ const activeProfile = !finished && view === undefined+ ? runtimeProfile ?? await input.resolveProjectRuntime?.() : undefined;+ if (activeProfile !== undefined) {+ const control = await (await runtimeHost(activeProfile)).openControl({ readOnly: true });+ try { view = await control.logs?.(args.build, args.lines); }+ finally { await control.close(); }+ if (view !== undefined) source = "runtime";+ // Result finishing can move the log between the first read and the active read.+ if (view === undefined) {+ const completed = await openProjectResults();+ try {+ const result = await completed.repository.read(args.build);+ if (result?.executionLog !== undefined) {+ const chunks = await completed.repository.openFile(args.build, result.executionLog);+ if (chunks !== undefined) { view = await readExecutionLog(chunks, args.lines); source = "result"; }+ }+ } finally { await completed.close(); }+ }+ }+ const records = view?.records ?? [];+ const omitted = (view?.total ?? 0) - records.length;+ write({ format: "hypit.cli-logs@1", build: args.build, source, records, omittedRecords: omitted },+ view === undefined ? "No execution log recorded" : "Build execution log", "info",+ [["Build", args.build], ["Source", source]], [+ ...(omitted > 0 ? [`Showing last ${records.length} records; ${omitted} earlier records omitted. Use --lines to read more.`] : []),+ ...records.map((record) => `${new Date(record.time).toISOString()} ${record.endpoint} ${record.command} ${+ record.kind === "phase" ? record.phase : record.kind === "diagnostic" || record.kind === "failed"+ ? `${record.kind}: ${record.message}` : record.kind}`),+ ]);+ return;+ }+if (args.command === "status" && runtimeProfile === undefined) {const openedResults = await openProjectResults();let result;@@ -42,7 +105,7 @@ export async function runExecutionCommand(input: {throw new Error(`Build ${args.build} has no finished Result; select its Runtime to observe active execution`);}const finished = result?.outcome !== undefined;- const build = result === undefined ? null : buildStatusView({ id: result.id, result });+ const build = result === undefined ? null : buildStatusView({ id: result.id, result, verbose: args.presentation.verbose });const outcome = result?.outcome;write({ format: "hypit.cli-status@1", build }, result === undefined? "Build Result not found"@@ -56,11 +119,12 @@ export async function runExecutionCommand(input: {...(build?.title === undefined ? [] : [["Title", build.title] as const]),...(outcome === undefined ? [] : [["Outcome", outcome] as const]),...(!finished && result !== undefined ? [["Result", "open"] as const] : []),- ...(build?.result.outputCount === undefined ? [] : [["Outputs", String(build.result.outputCount)] as const]),- ], !finished && result !== undefined- ? ["Select the Runtime to inspect active work."]- : []);- if (result === undefined || !finished) io.setExitCode?.(1);+ ...(build?.targets?.length ? [["Targets", build.targets.join(", ")] as const] : []),+ ], [+ ...statusDetailLines(build),+ ...(!finished && result !== undefined ? ["Select the Runtime to inspect active work."] : []),+ ]);+ if (result === undefined || !finished || outcome === "failed") io.setExitCode?.(1);return;}@@ -98,11 +162,12 @@ export async function runExecutionCommand(input: {return {id: item.id,work: status.work,- ...(item.outcome === undefined ? {} : { outcome: item.outcome }),+ phases: buildProgressView(item).phases,...(status.attention === undefined ? {} : { attention: status.attention }),};});- const currentView = activityObservationKey(worker.state, activity.builds);+ const currentView = JSON.stringify([activity.builds.length,+ activityObservationKey(worker.state, activity.builds.slice(0, args.limit))]);if (args.watch && currentView === previous) return;previous = currentView;const value = {@@ -111,7 +176,7 @@ export async function runExecutionCommand(input: {worker: worker.state,builds,...(activity.builds.length <= args.limit ? {} : { omittedBuilds: activity.builds.length - args.limit }),- capacity: activity.capacity,+ ...(args.presentation.verbose ? { capacity: activity.capacity } : {}),};const buildLines = activity.builds.slice(0, args.limit).map((item) => {const requestProgress = item.requests === undefined || item.requests.total === 0@@ -119,20 +184,16 @@ export async function runExecutionCommand(input: {: ` · ${item.requests.completed}/${item.requests.total} steps`;return `${item.id}: ${buildStatusView({ id: item.id, runtime: item }).work.state}`+ requestProgress+ + Object.entries(buildProgressView(item).phases).map(([phase, count]) => ` · ${count} ${phase}`).join("")+ `${item.stop?.cause === "execution-failed" ? " · stopping after failure" : item.cancellationRequested ? " · cancelling" : ""}`+ `${item.issue === undefined ? "" : ` · ${item.issue.message}`}`;});- const activeOperations = activity.builds.flatMap((item) => item.operations)- .filter((item) => item.status === "pending");const operationLines = args.presentation.verbose- ? activity.builds.flatMap((build) => build.operations.filter((item) => item.status === "pending")- .map((item) => `${build.id} · ${item.endpoint}: ${item.progress === undefined- ? item.status- : formatOperationProgress(item.progress)}`)).slice(0, args.limit)+ ? activity.builds.slice(0, args.limit).flatMap((build) => buildProgressView(build).details+ .map((detail) => `${build.id} · ${detail}`)): [];write(value, "Runtime activity", activity.builds.length === 0 ? "success" : "info", [["Active Builds", String(activity.builds.length)],- ["Active Operations", String(activeOperations.length)],["Worker", worker.state],], [...buildLines,@@ -187,7 +248,6 @@ export async function runExecutionCommand(input: {...(result === undefined ? {} : { result }),...(resultReadError === undefined ? {} : { resultReadError }),verbose: args.presentation.verbose,- operationLimit: args.limit,});const attention = build?.attention;const humanTitle = !found@@ -226,14 +286,9 @@ export async function runExecutionCommand(input: {["Result", "saving"] as const,] : resultOutcome !== undefined ? [["Outcome", resultOutcome] as const,- ...(build?.result.outputCount === undefined- ? [] : [["Outputs", String(build.result.outputCount)] as const]),] : [["State", build?.work.state ?? "unknown"] as const]),- ], (build?.operations ?? []).map((operation) => operation.failure !== undefined- ? `${operation.endpoint}${operation.receipt === undefined ? "" : ` · task ${operation.receipt.id}`}: ${operation.failure.code} — ${operation.failure.message}`- : operation.progress === undefined- ? `${operation.endpoint}${operation.receipt === undefined ? "" : ` · task ${operation.receipt.id}`}: ${operation.state}`- : `${operation.endpoint}${operation.receipt === undefined ? "" : ` · task ${operation.receipt.id}`}: ${formatOperationProgress(operation.progress)}`)+ ...(build?.targets?.length ? [["Targets", build.targets.join(", ")] as const] : []),+ ], statusDetailLines(build).concat(attention === undefined ? [] : [`Attention ${attention.message}`,...(attention.action === undefined ? [] : [`Action ${attention.action}`]),diff --git a/packages/cli/src/commands/results.ts b/packages/cli/src/commands/results.tsindex 14bd728d..52cd60d0 100644--- a/packages/cli/src/commands/results.ts+++ b/packages/cli/src/commands/results.ts@@ -100,13 +100,8 @@ export async function runProjectResultCommand(input: {projectRoot,...(args.outputName === undefined ? {} : { output: args.outputName }),limit: args.limit,+ verbose: args.presentation.verbose,});- const focusedOutputs = args.outputName === undefined- ? build.outputs.filter((item) => item.target || item.highlighted)- : build.outputs;- const visibleOutputs = args.presentation.verbose ? build.outputs : focusedOutputs;- const outputCount = build.outputs.length + (build.omittedOutputs ?? 0);- const hiddenOutputCount = args.outputName === undefined ? outputCount - focusedOutputs.length : 0;write({ format: "hypit.cli-inspect@1", build }, "Build Result",manifest.outcome === "failed" ? "error": manifest.outcome === "cancelled" ? "warning"@@ -117,23 +112,24 @@ export async function runProjectResultCommand(input: {["Outcome", build.outcome],...(args.outputName === undefined ? [["Targets", String(build.targetCount)] as const,- ["Outputs", String(outputCount)] as const,+ ["Available Outputs", String(build.outputCount)] as const,] : []),], [...(build.failure === undefined ? [] : [`Reason ${build.failure}`]),+ ...(build.executionLog === undefined ? [] : [`Execution log hypit logs ${build.id}`]),...(build.operations ?? []).map((operation) =>`${operation.endpoint}: ${operation.status}${operation.receipt === undefined ? "" : ` · task ${operation.receipt.id}`}`+ (operation.failure === undefined ? "" : ` · ${operation.failure.code}: ${operation.failure.message}`)),...(build.omittedOperations === undefined ? [] : [`${build.omittedOperations} more execution receipts · use --limit <count>`]),...(build.note === undefined ? [] : [`Note ${build.note}`]),- ...visibleOutputs.map((item) => `${item.highlighted ? "★" : item.target ? "Target" : "Output"} ${item.name}`+ ...build.outputs.map((item) => `${item.highlighted ? "★" : item.target ? "Target" : "Output"} ${item.name}`+ (!args.presentation.verbose ? "" : ` · ${item.type} · ${item.kind}`+ `${item.mediaType === undefined ? "" : ` · ${item.mediaType}`}`+ `${item.size === undefined ? "" : ` · ${item.size} bytes`}`)),- ...(!args.presentation.verbose && hiddenOutputCount > 0 ? [- `${hiddenOutputCount} other Output${hiddenOutputCount === 1 ? "" : "s"} · use --verbose or --output <name>`,+ ...(args.outputName === undefined && (build.otherOutputCount ?? 0) > 0 ? [+ `${build.otherOutputCount} other Outputs · use --verbose or --output <name>`,] : []),- ...(args.presentation.verbose && build.omittedOutputs !== undefined ? [+ ...(build.omittedOutputs !== undefined ? [`${build.omittedOutputs} more Outputs · use --limit <count> or --output <name>`,] : []),]);diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex f79c6909..9b39e90b 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -4,8 +4,8 @@ export { loadDiscoveredSourcePackages } from "./source-packages.js";export { collectRunFrontends, loadRunFile, resolveBuildResultValue } from "./run-file.js";export type { LoadedRunFile } from "./run-file.js";export { hypitHostStateRoot, hypitProjectStateRoot } from "./paths.js";-export { resolvePackageRoot, resolveProjectRoot } from "./project-context.js";-export { findRuntimeProfile } from "./runtime-selection.js";+export { resolvePackageRoot, resolveProjectRoot } from "@hypit/project-context-node";+export { findRuntimeProfile } from "@hypit/project-context-node";export { renderCliError, writeCliHelp, writeCliOutput } from "./output.js";export type {CliColorMode,diff --git a/packages/cli/src/machine-view.ts b/packages/cli/src/machine-view.tsindex 371c37c4..20a39134 100644--- a/packages/cli/src/machine-view.ts+++ b/packages/cli/src/machine-view.ts@@ -13,11 +13,12 @@ type ProgramStateView = {type AttentionView = { readonly message: string; readonly action?: string };export type OperationalMachineView =+ | { readonly format: "hypit.cli-logs@1"; readonly build: string; readonly source: "runtime" | "result" | "unavailable"; readonly records: readonly import("@hypit/runtime").ExecutionLogRecord[]; readonly omittedRecords: number }| { readonly format: "hypit.cli-runtime-init@1"; readonly profile: string; readonly project: string; readonly selected: true }| { readonly format: "hypit.cli-runtime-selection@1"; readonly selected: boolean; readonly removed?: boolean; readonly profile?: string; readonly project?: string }| { readonly format: "hypit.cli-paths@1"; readonly project: string; readonly projectState: string; readonly profileSource: "argument" | "project" | "none"; readonly selectionFile: string; readonly profile?: string; readonly runtimeData?: string; readonly hostState: string; readonly machinePackages: string; readonly distribution?: string }| { readonly format: "hypit.cli-package@1"; readonly action: "install" | "status"; readonly package: string; readonly ready: boolean }- | { readonly format: "hypit.cli-programs@1"; readonly action: "up" | "down" | "status"; readonly ready: boolean; readonly programs: readonly ProgramStateView[]; readonly omittedPrograms?: number }+ | { readonly format: "hypit.cli-programs@1"; readonly action: "up" | "down" | "status"; readonly ready: boolean; readonly programCount: number; readonly readyCount: number; readonly programs: readonly ProgramStateView[]; readonly omittedPrograms?: number }| { readonly format: "hypit.cli-runtime-up@1"; readonly ready: boolean; readonly worker: string; readonly preparedPackages: number; readonly programs: { readonly total: number; readonly ready: number; readonly items: readonly ProgramStateView[] } }| { readonly format: "hypit.cli-runtime-logs@1"; readonly lines: readonly string[]; readonly totalLines: number; readonly omittedLines: number; readonly path?: string }| { readonly format: "hypit.cli-runtime-down@1"; readonly worker: string }@@ -30,7 +31,7 @@ export type OperationalMachineView =| { readonly format: "hypit.cli-result-edit@1"; readonly build: string; readonly title: string | null; readonly note: string | null; readonly highlightedOutputCount: number; readonly highlightedOutputs: readonly string[]; readonly omittedHighlightedOutputs?: number }| { readonly format: "hypit.cli-get@1"; readonly build: string; readonly output: string; readonly type: string; readonly kind: "scalar" | "resource" | "composite"; readonly path: string }| { readonly format: "hypit.cli-status@1"; readonly build: CliBuildStatusView | null }- | { readonly format: "hypit.cli-activity@1"; readonly at: number; readonly worker: string; readonly builds: readonly { readonly id: string; readonly work: CliBuildStatusView["work"]; readonly outcome?: string; readonly attention?: AttentionView }[]; readonly omittedBuilds?: number; readonly capacity: readonly import("@hypit/runtime").CapacityReservation[] }+ | { readonly format: "hypit.cli-activity@1"; readonly at: number; readonly worker: string; readonly builds: readonly { readonly id: string; readonly work: CliBuildStatusView["work"]; readonly phases: Readonly<Record<string, number>>; readonly attention?: AttentionView }[]; readonly omittedBuilds?: number; readonly capacity?: readonly import("@hypit/runtime").CapacityReservation[] }| { readonly format: "hypit.cli-result-discard@1"; readonly build: string; readonly discarded: boolean }| { readonly format: "hypit.cli-result-finish@1"; readonly build: string; readonly found?: false; readonly outcome?: string; readonly attention?: AttentionView }| { readonly format: "hypit.cli-cancel@1"; readonly requested: boolean; readonly build: CliBuildStatusView | null }diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.tsindex 27485d71..28b1abd5 100644--- a/packages/cli/src/main.ts+++ b/packages/cli/src/main.ts@@ -13,7 +13,7 @@ import type {CliRuntime,CliRuntimeController,} from "./runtime-port.js";-import { createPricingOutput, writeCliHelp, writeCliOutput } from "./output.js";+import { createPlanOutput, createPricingOutput, writeCliHelp, writeCliOutput } from "./output.js";import type { CliIo, CliMachineView } from "./output.js";import { parseCommand } from "./arguments.js";import type { CliCommand, RuntimeOption } from "./command.js";@@ -23,13 +23,13 @@ import { isProjectResultCommand, runProjectResultCommand } from "./commands/resuimport { isEnvironmentCommand, runEnvironmentCommand } from "./commands/environment.js";import { isExecutionCommand, runExecutionCommand } from "./commands/execution.js";import { inlineValuePreview } from "./runtime-view.js";-import { resolvePackageRoot, resolveProjectRoot } from "./project-context.js";+import { resolvePackageRoot, resolveProjectRoot } from "@hypit/project-context-node";import { loadDiscoveredSourcePackages } from "./source-packages.js";import {clearRuntimeProfile,findRuntimeProfile,selectRuntimeProfile,-} from "./runtime-selection.js";+} from "@hypit/project-context-node";import {buildStatusView,cliTypeName,@@ -40,8 +40,8 @@ function createPublicBuildId(now = Date.now()): string {return orderedBuildId(now, randomBytes(5).toString("hex").toUpperCase());}-async function loadRuntime(host: NodeRuntimeHost): Promise<CliRuntime> {- return await host.createRuntime();+async function loadRuntime(host: NodeRuntimeHost, endpoints: readonly string[]): Promise<CliRuntime> {+ return await host.createRuntime({ endpoints });}function commandWorkspaceRoot(command: CliCommand): string | undefined {@@ -116,7 +116,8 @@ export async function runCli(await (await runtimeHost(args.profile,args.packageRoot ?? await packageRootForProject(),- )).runWorker(args.readyFile, args.workerOwner);+ )).runWorker(args.readyFile, args.workerOwner,+ args.executionRoot === undefined ? undefined : { dataRoot: args.executionRoot });return;}if (args.command === "runtime" && args.action === "init") {@@ -180,7 +181,7 @@ export async function runCli(let runtimeSelectionFile: string | undefined;const runtimeWasExplicit = runtimeProfile !== undefined;let runtimeNeedsHint = runtimeWasExplicit;- if (acceptsRuntimeContext(args) && runtimeProfile === undefined) {+ if (acceptsRuntimeContext(args) && runtimeProfile === undefined && args.command !== "logs") {const selected = await findRuntimeProfile(await commandProjectRoot());if (selected !== undefined) {runtimeProfile = selected.profile;@@ -231,6 +232,7 @@ export async function runCli(runtimeHost,runtimeController,openProjectResults: projectResults,+ resolveProjectRuntime: async () => (await findRuntimeProfile(await commandProjectRoot()))?.profile,write: writeOperational,});return;@@ -289,17 +291,18 @@ export async function runCli(author: projectPath(loaded.authorSource, effectiveWorkspaceRoot),frontend: sourceHeader.using,targetCount: loaded.document.targets.length,- targets: loaded.document.targets.slice(0, args.limit).map((item) => item.output),+ targets: loaded.document.targets.map((item) => item.output),candidates: loaded.document.candidates.length,satisfactions: loaded.document.satisfactions.length,- unresolvedHistoricalOutputs: loaded.unresolvedHistoricalOutputs.slice(0, args.limit).map((item) => ({+ historicalOutputCount: loaded.unresolvedHistoricalOutputs.length,+ ...(args.presentation.verbose ? { unresolvedHistoricalOutputs: loaded.unresolvedHistoricalOutputs.slice(0, args.limit).map((item) => ({candidate: item.id,build: item.build,output: item.output,})),...(loaded.unresolvedHistoricalOutputs.length <= args.limit ? {} : {omittedHistoricalOutputs: loaded.unresolvedHistoricalOutputs.length - args.limit,- }),+ }) } : {}),} as const;writeCliOutput(io, args.presentation, {kind: "check-run",@@ -324,9 +327,10 @@ export async function runCli(assets: result.attachments.length,modules: modules.length,outputCount: outputs.length,- outputs: outputs.slice(0, args.limit).map((item) => ({ name: item.name, type: cliTypeName(item.type) })),- ...(outputs.length <= args.limit ? {} : { omittedOutputs: outputs.length - args.limit }),- ...(args.presentation.verbose ? { details: {+ ...(args.presentation.verbose ? {+ outputs: outputs.slice(0, args.limit).map((item) => ({ name: item.name, type: cliTypeName(item.type) })),+ ...(outputs.length <= args.limit ? {} : { omittedOutputs: outputs.length - args.limit }),+ details: {modules: modules.slice(0, args.limit),values: values.slice(0, args.limit).map((item) => ({ name: item.name, type: cliTypeName(item.type) })),} } : {}),@@ -402,7 +406,7 @@ export async function runCli(const evaluated = await evaluatePlanNeeds(result.definition, packageContributions);const providers = await describePlanProviders(host, evaluated.state, evaluated);assertPlannedRequests(evaluated.state, evaluated, providers);- const preflight = await preflightPlan(host, evaluated.state);+ const preflight = await preflightPlan(host, evaluated.state, providers);// Build is an execution boundary, not a provisioning command. The cheap// preflight must already be clean; `runtime up` is the explicit place for// installing or starting declared programs.@@ -415,7 +419,8 @@ export async function runCli(const detail = error instanceof Error ? error.message : String(error);throw new Error(`Runtime Worker could not start; no Build was queued: ${detail}`);}- runtime = await loadRuntime(await runtimeHost(runtimeProfile));+ runtime = await loadRuntime(await runtimeHost(runtimeProfile, sourcePackageRoot),+ [...new Set(providers.flatMap((item) => item.status === "resolved" && item.endpoint !== undefined ? [item.endpoint] : []))]);let built = await runtime.build(request);const requestCount = result.definition.plan.steps.reduce((total, step) => total + Object.keys(step.needs).length,@@ -488,7 +493,6 @@ export async function runCli(...(activeView === undefined ? {} : { runtime: activeView }),...(finishedResult === undefined ? {} : { result: finishedResult }),verbose: args.presentation.verbose,- operationLimit: args.limit,});const machine = {format: "hypit.cli-build@1" as const,@@ -590,8 +594,8 @@ export async function runCli(});return;}- const preflight = planHost === undefined ? undefined : await preflightPlan(planHost, evaluated.state);const providers = planHost === undefined ? undefined : await describePlanProviders(planHost, evaluated.state, evaluated);+ const preflight = planHost === undefined ? undefined : await preflightPlan(planHost, evaluated.state, providers ?? []);const needs = describePlanNeeds(evaluated.state, evaluated, providers ?? []);const outputNames = Object.fromEntries(result.compilation.author.exports.flatMap((item) =>item.ref.kind === "logical-output" ? [[item.ref.id, item.name]] : []));@@ -600,8 +604,10 @@ export async function runCli(const candidate = loaded.run.satisfactionNames[selection.output];return output === undefined || candidate === undefined ? [] : [{ output, candidate }];});- const allUnreached = unreachedGenerations(result.compilation.author.graph, result.state, outputNames)- .map((item) => ({ output: item.name, operation: item.producer }));+ const allUnreached = args.presentation.verbose+ ? unreachedGenerations(result.compilation.author.graph, result.state, outputNames)+ .map((item) => ({ output: item.name, operation: item.producer }))+ : [];const targets = loaded.run.document.targets.map((item) => item.output);const unsupportedRequestCount = providers?.filter((item) => item.status === "unsupported").length ?? 0;const unresolvedRequestCount = providers?.filter((item) => item.status === "unresolved" || item.status === "ambiguous").length ?? 0;@@ -610,45 +616,31 @@ export async function runCli(const requestIssueCount = needs.filter((item) => item.issue !== undefined).length;writeCliOutput(io, args.presentation, {kind: "plan",- machine: {+ machine: createPlanOutput({format: "hypit.cli-plan@1",ok: (preflight?.ok ?? true) && unresolvedRequestCount === 0&& unsupportedRequestCount === 0 && requestIssueCount === 0,run: projectPath(loaded.path, effectiveWorkspaceRoot),targetCount: targets.length,- targets: targets.slice(0, args.limit),+ targets,steps: result.definition.plan.steps.length,requestCount: needs.length,requestIssueCount,...(providerRequestCount === undefined ? {} : { providerRequestCount }),...(providers === undefined ? {} : { localRequestCount, unresolvedRequestCount, unsupportedRequestCount }),choiceCount: allChoices.length,- choices: allChoices.slice(0, args.limit),- ...(allChoices.length <= args.limit ? {} : { omittedChoices: allChoices.length - args.limit }),- ...(allUnreached.length === 0 ? {} : { unreached: allUnreached.slice(0, args.limit) }),- ...(allUnreached.length <= args.limit ? {} : { omittedUnreached: allUnreached.length - args.limit }),- ...(providers === undefined ? {} : {- providers: providers.slice(0, Math.max(args.limit, 50)),- ...(providers.length <= Math.max(args.limit, 50)- ? {}- : { omittedProviders: providers.length - Math.max(args.limit, 50) }),- }),- needs: needs.slice(0, Math.max(args.limit, 50)),- ...(needs.length <= Math.max(args.limit, 50) ? {} : { omittedNeeds: needs.length - Math.max(args.limit, 50) }),+ choices: allChoices,+ unreached: allUnreached,+ ...(providers === undefined ? {} : { providers }),+ needs,...(preflight === undefined ? {} : { preflight: {ok: preflight.ok,capabilityCount: preflight.capabilities.length,- capabilities: preflight.capabilities.slice(0, args.limit),- ...(preflight.capabilities.length <= args.limit- ? {}- : { omittedCapabilities: preflight.capabilities.length - args.limit }),+ capabilities: preflight.capabilities,diagnosticCount: preflight.diagnostics.length,- diagnostics: preflight.diagnostics.slice(0, args.limit),- ...(preflight.diagnostics.length <= args.limit- ? {}- : { omittedDiagnostics: preflight.diagnostics.length - args.limit }),+ diagnostics: preflight.diagnostics,} }),- },+ }, { verbose: args.presentation.verbose, limit: args.limit }),});if ((preflight !== undefined && !preflight.ok) || unresolvedRequestCount > 0|| unsupportedRequestCount > 0 || requestIssueCount > 0) io.setExitCode?.(1);diff --git a/packages/cli/src/observation.ts b/packages/cli/src/observation.tsindex 2eef47cb..8f160454 100644--- a/packages/cli/src/observation.ts+++ b/packages/cli/src/observation.ts@@ -5,7 +5,8 @@ import { formatOperationProgress } from "./runtime-view.js";const FIRST_HEARTBEAT_MS = 30_000;const LATER_HEARTBEAT_MS = 60_000;-const MIN_PROGRESS_INTERVAL_MS = 1_000;+// Coalesce live counters into readable terminal updates; persistence can advance more often.+const MIN_PROGRESS_INTERVAL_MS = 5_000;export type BuildProgressView = {readonly build: string;@@ -22,6 +23,10 @@ function progressPhases(view: CliBuildView): Readonly<Record<string, number>> {const phase = operation.progress?.phase ?? "in progress";phases.set(phase, (phases.get(phase) ?? 0) + 1);}+ for (const command of view.commands ?? []) {+ const label = formatOperationProgress(command.progress);+ phases.set(label, (phases.get(label) ?? 0) + 1);+ }return Object.fromEntries([...phases].sort(([left], [right]) => left.localeCompare(right)));}@@ -41,6 +46,7 @@ export function buildProgressView(view: CliBuildView, now = Date.now()): BuildPrphases: progressPhases(view),elapsedMs: Math.max(0, now - view.createdAt),details: [+ ...(view.commands ?? []).map((item) => `${item.endpoint}: ${formatOperationProgress(item.progress)}`),...(view.stop === undefined ? [] : [view.stop.cause === "execution-failed"? `Build stopping after failure${view.stop.reason === undefined ? "" : `: ${view.stop.reason}`}`: `Build cancelling${view.stop.reason === undefined ? "" : `: ${view.stop.reason}`}`]),diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.tsindex b555b58d..09fa52d4 100644--- a/packages/cli/src/output.ts+++ b/packages/cli/src/output.ts@@ -60,7 +60,7 @@ export type AuthorCheckOutput = {readonly assets: number;readonly modules: number;readonly outputCount: number;- readonly outputs: readonly {+ readonly outputs?: readonly {readonly name: string;readonly type: string;}[];@@ -82,6 +82,7 @@ export type RunCheckOutput = {readonly targets: readonly string[];readonly candidates: number;readonly satisfactions: number;+ readonly historicalOutputCount?: number;readonly steps?: number;readonly unresolvedHistoricalOutputs?: readonly {readonly candidate: string;@@ -94,7 +95,7 @@ export type RunCheckOutput = {export type PlanPreflight = {readonly ok: boolean;readonly capabilityCount: number;- readonly capabilities: readonly string[];+ readonly capabilities?: readonly string[];readonly omittedCapabilities?: number;readonly diagnosticCount: number;readonly diagnostics: readonly CliDiagnostic[];@@ -119,7 +120,7 @@ export type PlanOutput = {readonly run: string;readonly targetCount: number;readonly targets: readonly string[];- readonly steps: number;+ readonly steps?: number;readonly requestCount: number;readonly requestIssueCount: number;/** Present when a Runtime Profile was selected. */@@ -128,19 +129,45 @@ export type PlanOutput = {readonly unresolvedRequestCount?: number;readonly unsupportedRequestCount?: number;readonly choiceCount: number;- readonly choices: readonly { readonly output: string; readonly candidate: string }[];+ readonly choices?: readonly { readonly output: string; readonly candidate: string }[];readonly omittedChoices?: number;readonly unreached?: readonly { readonly output: string; readonly operation: string }[];readonly omittedUnreached?: number;/** Present only when a Runtime Profile was selected; the Endpoint and price page behind each capability. */readonly providers?: readonly PlanProvider[];- readonly omittedProviders?: number;/** Every external request the Build will make, in step order, with its parameters when known. */readonly needs?: readonly PlanNeed[];- readonly omittedNeeds?: number;readonly preflight?: PlanPreflight;};+/** Output scope is independent of encoding. Limits apply to expanded detail, not demanded work. */+export function createPlanOutput(plan: PlanOutput, options: { readonly verbose: boolean; readonly limit: number }): PlanOutput {+ const { steps, choices = [], unreached = [], preflight, ...summary } = plan;+ const limit = options.limit;+ return {+ ...summary,+ ...(options.verbose ? {+ steps,+ choices: choices.slice(0, limit),+ ...(choices.length <= limit ? {} : { omittedChoices: choices.length - limit }),+ unreached: unreached.slice(0, limit),+ ...(unreached.length <= limit ? {} : { omittedUnreached: unreached.length - limit }),+ } : {}),+ ...(preflight === undefined ? {} : { preflight: {+ ok: preflight.ok,+ capabilityCount: preflight.capabilityCount,+ diagnosticCount: preflight.diagnosticCount,+ diagnostics: preflight.diagnostics,+ ...(options.verbose ? {+ capabilities: preflight.capabilities?.slice(0, limit) ?? [],+ ...((preflight.capabilities?.length ?? 0) <= limit ? {} : {+ omittedCapabilities: preflight.capabilities!.length - limit,+ }),+ } : {}),+ } }),+ };+}+export type PricingEntry = PlanProvider & {readonly pricingDocuments?: readonly PricingDocument[];readonly pricingError?: string;@@ -310,7 +337,7 @@ function renderAuthorCheck(verbose: boolean,): string {const lines = [heading("success", "Source is valid", io, colors), ""];- const readable = view.machine.outputs;+ const readable = view.machine.outputs ?? [];lines.push(...facts([["Source", shortPath(view.machine.source)],["Outputs", String(view.machine.outputCount)],@@ -350,8 +377,7 @@ function renderRunCheck(verbose: boolean,): string {const lines = [heading("success", "Run source is valid", io, colors), ""];- const reuse = (view.machine.unresolvedHistoricalOutputs?.length ?? 0)- + (view.machine.omittedHistoricalOutputs ?? 0);+ const reuse = view.machine.historicalOutputCount ?? 0;const targetSummary = view.machine.targets.length === 0? String(view.machine.targetCount): view.machine.targets.join(", ")@@ -433,7 +459,7 @@ function needSummaryText(needs: readonly PlanNeed[]): string {const pendingCount = first.pending.length;if (pendingCount > 0) parts.push(`${pendingCount === 1 ? "input" : `${pendingCount} inputs`} produced during Build`);if (first.issue !== undefined) parts.push(`could not inspect: ${first.issue}`);- return parts.length === 0 ? "no parameters" : parts.join(" · ");+ return parts.length === 0 ? "request summary unavailable" : parts.join(" · ");}/** One line per distinct request shape, counted; the step names when only one request has that shape. */@@ -489,6 +515,7 @@ function renderPlan(["Run", shortPath(view.machine.run)],["Targets", targetSummary],["Requests", String(view.machine.requestCount)],+ ...(view.machine.choiceCount === 0 ? [] : [["Run choices", String(view.machine.choiceCount)] as const]),...(view.machine.requestIssueCount === 0 ? [] : [["Request issues", String(view.machine.requestIssueCount)] as const]),...((view.machine.providerRequestCount ?? 0) === 0 ? [] : [["Provider requests", String(view.machine.providerRequestCount)] as const]),...((view.machine.localRequestCount ?? 0) === 0 ? [] : [["Local requests", String(view.machine.localRequestCount)] as const]),@@ -497,7 +524,7 @@ function renderPlan(...(view.machine.preflight === undefined ? [] : [["Preflight", view.machine.preflight.ok ? "ready" : "needs attention",] as const]),- ...(verbose ? [["Steps", String(view.machine.steps)] as const] : []),+ ...(!verbose || view.machine.steps === undefined ? [] : [["Steps", String(view.machine.steps)] as const]),], colors));if (view.machine.providers !== undefined) {if (view.machine.providers.length > 0) lines.push("", colors.strong("Providers and price pages"));@@ -531,9 +558,6 @@ function renderPlan(const requests = new Set(group.map((provider) => provider.request));lines.push(...groupedNeedLines((view.machine.needs ?? []).filter((need) => requests.has(need.request)), colors, verbose));}- if ((view.machine.omittedProviders ?? 0) > 0) {- lines.push(` ${colors.dim(`${view.machine.omittedProviders} more requests · use --limit <count>`)}`);- }} else if (view.machine.requestCount > 0) {const byCapability = new Map<string, PlanNeed[]>();for (const need of view.machine.needs ?? []) {@@ -559,9 +583,9 @@ function renderPlan(}if (view.machine.preflight !== undefined&& (view.machine.preflight.diagnostics.length > 0- || (verbose && view.machine.preflight.capabilities.length > 0))) {+ || (verbose && (view.machine.preflight.capabilities?.length ?? 0) > 0))) {lines.push("", colors.strong("Runtime preflight"));- if (verbose) for (const capability of view.machine.preflight.capabilities) lines.push(` ${colors.accent(capability)}`);+ if (verbose) for (const capability of view.machine.preflight.capabilities ?? []) lines.push(` ${colors.accent(capability)}`);if (verbose && (view.machine.preflight.omittedCapabilities ?? 0) > 0) {lines.push(` ${colors.dim(`${view.machine.preflight.omittedCapabilities} more capabilities · use --limit <count>`)}`);}@@ -578,9 +602,9 @@ function renderPlan(lines.push(` ${colors.dim(`${capabilityCount} demanded Endpoint ${capabilityCount === 1 ? "capability" : "capabilities"} checked.`)}`);}}- if (view.machine.choices.length > 0) {+ if (verbose && (view.machine.choices?.length ?? 0) > 0) {lines.push("", colors.strong("Run choices"));- for (const selection of view.machine.choices) {+ for (const selection of view.machine.choices ?? []) {const status = colors.success(glyph(io, "✓", "+"));lines.push(` ${status} ${colors.accent(selection.output)} ← ${selection.candidate}`);}@@ -774,23 +798,27 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undeficolors.dim("Validate one self-described Author Source or Run Source without executing it."),""," hypit check <source> [--workspace <workspace>] [--asset-root <directory>]",+ " --verbose lists exported names/types and historical references.",],doctor: [colors.accent(colors.strong("hypit doctor")),colors.dim("Diagnose project Results and, when selected or supplied, one Runtime Profile."),"",- " hypit doctor [--runtime <profile>] [--workspace <project>]",+ " hypit doctor [--runtime <profile>] [--workspace <project>] [--endpoint <instance>]"," A positional Profile is also accepted in place of --runtime.",+ " Repeat --endpoint <instance> to limit the operation to chosen services; omission covers the Profile."," Without a Runtime Profile, checks only the project's selected Result Store.",],plan: [colors.accent(colors.strong("hypit plan")),- colors.dim("Freeze the demanded subgraph and expose explicit Run choices and every external Need."),+ colors.dim("Show targets, demanded requests and their readiness without executing them."),""," hypit plan <run-source> [--runtime <profile>] [--workspace <workspace>] [--asset-root <directory>]","","With --runtime, plan also preflights only the demanded deployment slice and names the Provider","and price page behind each external request.",+ "--verbose expands Run choices and unreached declarations. --limit bounds that detail,",+ "while all demanded requests and diagnostics remain visible in both text and JSON.","Planning never starts external work.",],pricing: [@@ -823,13 +851,14 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi" hypit runtime init [<profile>] [--workspace <project>] create and select a starter Profile"," hypit runtime use <profile> [--workspace <project>] select the project Profile"," hypit runtime unset [--workspace <project>] remove only that selection",- " hypit runtime up [<profile>] prepare local packages and programs, then start the Worker",+ " hypit runtime up [<profile>] [--endpoint <instance>] prepare helpers, then start the Worker"," hypit runtime status [<profile>] inspect the local Worker, active Builds and programs"," hypit runtime logs [<profile>] [--lines <count>]"," hypit runtime down [<profile>] stop the Worker; external programs keep running","","The project is resolved first. Selection is read only from that project's .hypit/runtime.","All runtime actions accept --workspace <project>; operational actions also accept --runtime <profile>.",+ "For up, repeat --endpoint <instance> to prepare only chosen services; omission prepares the Profile.","No Profile filename discovery or parent-project inheritance is performed.","Remote Endpoints such as HypiHub are not started by this command; use doctor to test them.",],@@ -841,7 +870,8 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi" hypit packages install <package@exact-version>","","The package is reused by every project and later session on this machine.",- "npm owns the ordinary package.json; Hypit creates no package lock or receipt.",+ "Each exact version has its own installation; npm owns package.json and package-lock.json.",+ "Preparation reports its install.log for live output and later diagnosis.",],programs: [colors.accent(colors.strong("hypit programs")),@@ -851,6 +881,7 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi" hypit programs status [--runtime <profile>] [--workspace <project>]"," hypit programs down [--runtime <profile>] [--workspace <project>]"," A positional Profile is also accepted in place of --runtime.",+ " Repeat --endpoint <instance> to limit the operation to chosen services; omission covers the Profile.",],activity: [colors.accent(colors.strong("hypit activity")),@@ -874,6 +905,14 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi""," hypit builds [--workspace <project>] [--limit <count>] [--before <build-id>]",],+ logs: [+ colors.accent(colors.strong("hypit logs")),+ colors.dim("Read Build execution evidence; finished logs need only the project Result Repository."),+ "",+ " hypit logs <build-id> [--workspace <project>] [--runtime <profile>] [--lines <count>]",+ " --lines <count> show the last N records (default 50)",+ " runtime logs reads the Worker process log instead",+ ],status: [colors.accent(colors.strong("hypit status")),colors.dim("Show one Build now, or keep watching it without owning execution."),@@ -887,6 +926,8 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undeficolors.dim("Inspect one project-owned Build Result and its public Outputs."),""," hypit inspect <build-id> [--output <name>] [--limit <count>] [--workspace <project>]",+ " Defaults to targets and highlighted Outputs. --verbose expands other available Outputs.",+ " --output selects one exact name; --limit bounds expanded lists.",],get: [colors.accent(colors.strong("hypit get")),@@ -958,6 +999,7 @@ export function writeCliHelp(io: CliIo, topic?: string): void {colors.strong("Results"),row("builds", "list Results newest first"),row("history <output>", "find one named Output across Builds"),+ row("logs <build-id> [--lines <count>]", "read saved Build execution phases and diagnostics"),row("status <build-id> [--watch]", "show current work and Result facts"),row("inspect <build-id>", "inspect one Result"),row("get <build-id> --output <name> --to <path>", "export one Build Output"),@@ -969,7 +1011,7 @@ export function writeCliHelp(io: CliIo, topic?: string): void {row("runtime up|status|logs|down", "prepare and manage the local Build Runtime"),row("programs up|status|down", "manage declared external programs only"),row("packages install|status", "manage pinned upstream packages in the machine home"),- row("activity [--watch]", "inspect active Builds and shared capacity"),+ row("activity [--watch]", "show active Builds and their current phases"),row("cancel <build-id>", "withdraw one active Build"),row("paths", "show physical state locations"),row("auth status|login|logout", "manage Endpoint credentials"),diff --git a/packages/cli/src/view.ts b/packages/cli/src/view.tsindex 41a71d95..f944a2f1 100644--- a/packages/cli/src/view.ts+++ b/packages/cli/src/view.ts@@ -46,15 +46,27 @@ export type CliBuildResultView = {readonly targets: readonly string[];readonly omittedTargets?: number;readonly outputs: readonly CliOutputView[];+ readonly outputCount: number;+ /** Available Outputs outside the selected inspection scope. */+ readonly otherOutputCount?: number;readonly omittedOutputs?: number;readonly failure?: string;- readonly operations?: BuildResultManifest["operations"];+ readonly operations?: readonly Pick<NonNullable<BuildResultManifest["operations"]>[number],+ "endpoint" | "status" | "receipt" | "failure">[];+ readonly executionLog?: BuildResultManifest["executionLog"];readonly omittedOperations?: number;};export type CliBuildStatusView = {readonly id: string;readonly title?: string;+ readonly targets?: readonly string[];+ readonly failure?: string;+ readonly commands?: readonly {+ readonly id?: string;+ readonly endpoint: string;+ readonly progress: NonNullable<BuildView["commands"]>[number]["progress"];+ }[];readonly work: {readonly state: "unknown" | "submitting" | "working" | "done";readonly outcome?: "complete" | "failed" | "cancelled";@@ -68,6 +80,7 @@ export type CliBuildStatusView = {};readonly attention?: { readonly message: string; readonly action?: string };readonly operations?: readonly {+ readonly count?: number;readonly id?: string;readonly receipt?: { readonly id: string; readonly url?: string };readonly endpoint: string;@@ -127,8 +140,8 @@ function orderedOutputNames(manifest: BuildResultManifest): readonly string[] {const highlighted = new Set(manifest.highlightedOutputs ?? []);const targets = new Set(manifest.targets);return names.sort((left, right) => {- const leftRank = highlighted.has(left) ? 0 : targets.has(left) ? 1 : 2;- const rightRank = highlighted.has(right) ? 0 : targets.has(right) ? 1 : 2;+ const leftRank = targets.has(left) ? 0 : highlighted.has(left) ? 1 : 2;+ const rightRank = targets.has(right) ? 0 : highlighted.has(right) ? 1 : 2;return leftRank - rightRank || left.localeCompare(right);});}@@ -146,7 +159,6 @@ export function buildStatusView(options: {readonly result?: BuildResultManifest;readonly resultReadError?: string;readonly verbose?: boolean;- readonly operationLimit?: number;}): CliBuildStatusView {const resultState = options.resultReadError !== undefined? "unavailable" as const@@ -154,6 +166,15 @@ export function buildStatusView(options: {const issue = options.runtime?.issue;return {id: options.id,+ ...((options.runtime?.targets ?? options.result?.targets) === undefined ? {} : {+ targets: options.runtime?.targets ?? options.result!.targets,+ }),+ ...((options.result?.failure ?? options.runtime?.stop?.reason) === undefined ? {} : {+ failure: options.result?.failure ?? options.runtime!.stop!.reason,+ }),+ ...(options.runtime?.commands?.length ? { commands: options.runtime.commands.map((command) => ({+ ...(options.verbose ? { id: command.id } : {}), endpoint: command.endpoint, progress: command.progress,+ })) } : {}),...(options.result?.title === undefined ? {} : { title: options.result.title }),work: {state: workState(options.runtime, options.result),@@ -176,13 +197,12 @@ export function buildStatusView(options: {}: { message: options.resultReadError! },}),- ...(!options.verbose ? {} : {- operations: (options.runtime?.operations ?? options.result?.operations ?? [])+ ...((options.runtime?.operations ?? options.result?.operations ?? []).some((item) => item.status !== "completed") ? {+ operations: groupOperationViews((options.runtime?.operations ?? options.result?.operations ?? []).filter((item) => item.status !== "completed")- .slice(0, options.operationLimit ?? 20).map((item) => ({- ...("operation" in item ? { id: item.operation } : item.id === undefined ? {} : { id: item.id }),- ...(item.receipt === undefined ? {} : { receipt: item.receipt }),+ ...(!options.verbose ? {} : "operation" in item ? { id: item.operation } : item.id === undefined ? {} : { id: item.id }),+ ...(item.receipt === undefined || (!options.verbose && item.failure === undefined) ? {} : { receipt: item.receipt }),endpoint: item.endpoint,state: item.status,...(item.progress === undefined ? {} : { progress: item.progress }),@@ -190,23 +210,43 @@ export function buildStatusView(options: {code: item.failure.code,message: item.failure.message,} }),- })),- }),+ })), options.verbose === true),+ } : {}),};}+function groupOperationViews(+ operations: NonNullable<CliBuildStatusView["operations"]>,+ verbose: boolean,+): NonNullable<CliBuildStatusView["operations"]> {+ if (verbose) return operations;+ const groups = new Map<string, { view: typeof operations[number]; count: number }>();+ for (const operation of operations) {+ const key = JSON.stringify(operation);+ const existing = groups.get(key);+ if (existing !== undefined) existing.count += 1;+ else groups.set(key, { view: operation, count: 1 });+ }+ return [...groups.values()].map(({ view, count }) => count === 1 ? view : { ...view, count });+}+export async function buildResultView(repository: BuildResultRepository,manifest: BuildResultManifest,- options: { readonly projectRoot: string; readonly output?: string; readonly limit: number },+ options: { readonly projectRoot: string; readonly output?: string; readonly limit: number; readonly verbose?: boolean },): Promise<CliBuildResultView> {if (options.output !== undefined && manifest.outputs[options.output] === undefined) {throw new Error(`Build Result ${manifest.id} has no public Output ${options.output}`);}- const allNames = options.output === undefined ? orderedOutputNames(manifest) : [options.output];- const selected = allNames.slice(0, options.limit);+ const available = orderedOutputNames(manifest);+ const allNames = options.output !== undefined ? [options.output] : options.verbose ? available+ : available.filter((name) => manifest.targets.includes(name) || manifest.highlightedOutputs?.includes(name));+ const selected = options.verbose ? allNames.slice(0, options.limit) : allNames;const outputs = await Promise.all(selected.map(async (name) =>await outputView(repository, manifest, name)));+ const operations = options.verbose ? manifest.operations ?? []+ : (manifest.operations ?? []).filter((item) => item.failure !== undefined);+ const selectedOperations = options.verbose ? operations.slice(0, options.limit) : operations;return {id: manifest.id,...(manifest.title === undefined ? {} : { title: manifest.title }),@@ -217,12 +257,18 @@ export async function buildResultView(source: projectPath(manifest.source.path, options.projectRoot),...(manifest.run === undefined ? {} : { run: projectPath(manifest.run.path, options.projectRoot) }),targetCount: manifest.targets.length,- targets: manifest.targets.slice(0, options.limit),- ...(manifest.targets.length <= options.limit ? {} : { omittedTargets: manifest.targets.length - options.limit }),+ targets: manifest.targets,+ outputCount: available.length,outputs,+ ...(available.length === allNames.length ? {} : { otherOutputCount: available.length - allNames.length }),...(selected.length === allNames.length ? {} : { omittedOutputs: allNames.length - selected.length }),...(manifest.failure === undefined ? {} : { failure: manifest.failure }),- ...(manifest.operations === undefined ? {} : { operations: manifest.operations.slice(0, options.limit) }),- ...((manifest.operations?.length ?? 0) <= options.limit ? {} : { omittedOperations: manifest.operations!.length - options.limit }),+ ...(manifest.executionLog === undefined ? {} : { executionLog: manifest.executionLog }),+ ...(selectedOperations.length === 0 ? {} : { operations: selectedOperations.map((item) => options.verbose ? item : ({+ endpoint: item.endpoint, status: item.status,+ ...(item.receipt === undefined ? {} : { receipt: item.receipt }),+ ...(item.failure === undefined ? {} : { failure: item.failure }),+ })) }),+ ...(selectedOperations.length === operations.length ? {} : { omittedOperations: operations.length - selectedOperations.length }),};}diff --git a/packages/cli/test/build-programs.test.ts b/packages/cli/test/build-programs.test.tsindex 963583e5..9461ed4d 100644--- a/packages/cli/test/build-programs.test.ts+++ b/packages/cli/test/build-programs.test.ts@@ -245,6 +245,6 @@ test("plan preserves the selected work summary but exits non-zero when cheap pre};assert.equal(value.ok, false);assert.equal(value.preflight.ok, false);- assert.equal(typeof value.steps, "number");+ assert.equal("steps" in value, false);assert.equal(exitCode, 1);});diff --git a/packages/cli/test/build-results.test.ts b/packages/cli/test/build-results.test.tsindex 76a63084..0dcfd678 100644--- a/packages/cli/test/build-results.test.ts+++ b/packages/cli/test/build-results.test.ts@@ -618,9 +618,32 @@ test("a failed Result exposes task receipts and credential references without abuild: { outcome: string; operations: unknown[] };};assert.equal(inspected.build.outcome, "failed");- assert.deepEqual(inspected.build.operations, [operation]);+ assert.deepEqual(inspected.build.operations, [{+ endpoint: operation.endpoint, status: operation.status, receipt: operation.receipt, failure: operation.failure,+ }]);+ const detailed = await jsonCommand(["inspect", id, "--verbose"], root) as { build: { operations: unknown[] } };+ assert.deepEqual(detailed.build.operations, [operation]);const human = await humanCommand(["inspect", id], root);assert.match(human, /remote-task-1/);assert.match(human, /DOWNLOAD_FAILED/);} finally { await rm(root, { recursive: true, force: true }); }});++test("logs reads finished evidence without a Runtime and clearly limits the tail", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-cli-logs-"));+ try {+ const id = "bld_20260913T130000000Z_0000000001";+ const result = await FileBuildResult.create(join(root, ".hypit/results"), {+ id, source: { path: "main.svml" }, targets: [], publishedOutputs: [],+ });+ const records = ["started", "completed"].map((kind, time) => ({ format: "hypit.execution-log@1", time, kind, endpoint: "renderer", command: "c1" }));+ await result.finish({ outcome: "complete", executionLog: (async function* () {+ yield Buffer.from(records.map((record) => JSON.stringify(record) + "\n").join(""));+ })() });+ await writeFile(join(root, ".hypit/runtime"), "missing-profile.json\n");+ assert.deepEqual(await jsonCommand(["logs", id, "--lines", "1"], root), {+ format: "hypit.cli-logs@1", build: id, source: "result", records: [records[1]], omittedRecords: 1,+ });+ assert.match(await humanCommand(["logs", id, "--lines", "1"], root), /earlier records omitted/u);+ } finally { await rm(root, { recursive: true, force: true }); }+});diff --git a/packages/cli/test/control-commands.test.ts b/packages/cli/test/control-commands.test.tsindex 380e11fc..928b5117 100644--- a/packages/cli/test/control-commands.test.ts+++ b/packages/cli/test/control-commands.test.ts@@ -52,6 +52,36 @@ test("activity opens Runtime control without constructing execution Providers",assert.deepEqual(result.builds, []);});+test("doctor retains later errors even with a small display limit", async () => {+ const diagnostics = Array.from({ length: 25 }, (_, index) => ({+ severity: "warning" as const, code: `NOTICE_${index}`, message: "setup note",+ }));+ const selected = { diagnoseProjectResults: async () => ({ diagnostics: [+ ...diagnostics, { severity: "error", code: "BROKEN_RESULT", message: "selected repository unavailable" },+ ] }) } as unknown as CliDistribution;+ let output = "";+ let exitCode = 0;+ await runCli(["doctor", "--workspace", "/tmp", "--limit", "1", "--json"], {+ write(text) { output += text; }, setExitCode(code) { exitCode = code; },+ }, selected);+ assert.equal(exitCode, 1);+ assert.equal(JSON.parse(output).diagnostics.at(-1).code, "BROKEN_RESULT");+});++test("finished status reports failure details and a nonzero exit without a Runtime", async () => {+ const selected = { openProjectResults: async () => ({+ repository: { read: async () => ({ id: "failed", outcome: "failed", targets: [], outputs: {}, failure: "renderer exited", operations: [] }) },+ close() {},+ }) } as unknown as CliDistribution;+ let output = "";+ let exitCode = 0;+ await runCli(["status", "failed", "--workspace", "/tmp"], {+ write(text) { output += text; }, setExitCode(code) { exitCode = code; },+ }, selected);+ assert.equal(exitCode, 1);+ assert.match(output, /renderer exited/u);+});+test("status --watch follows active execution, then reads its finished Result", async () => {const calls: string[] = [];const resultLocation = {@@ -239,7 +269,7 @@ test("status preserves Runtime decision and attention when its Result Store is utargets: [],acceptedRecords: 0,outstandingCommands: 0,- operations: [{ endpoint: "kie.internal", status: "failed" as const,+ operations: [{ endpoint: "images.internal", status: "failed" as const,failure: { code: "REMOTE", message: "provider detail" } }],};const control = {@@ -270,7 +300,9 @@ test("status preserves Runtime decision and attention when its Result Store is uassert.equal(result.build.work.outcome, "failed");assert.equal(result.build.result.state, "unavailable");assert.equal(result.build.attention.message, "S3 unavailable");- assert.equal("operations" in result.build, false);+ assert.deepEqual((result.build as { operations?: unknown }).operations, [{+ endpoint: "images.internal", state: "failed", failure: { code: "REMOTE", message: "provider detail" },+ }]);assert.equal(exitCode, 1);});@@ -423,11 +455,11 @@ test("auth opens only one Endpoint credential control, never the execution Runtiasync credentials(endpoint?: string) {calls.push(`credentials.status:${endpoint}`);return [{- endpoint: "kie.project",+ endpoint: "images.project",slot: "apiKey",- label: "KIE API key",+ label: "Image service API key",kind: "secret",- ref: { store: "env", key: "KIE_API_KEY" },+ ref: { store: "env", key: "IMAGE_API_KEY" },configured: false,writable: false,}];@@ -450,15 +482,15 @@ test("auth opens only one Endpoint credential control, never the execution Runtilet output = "";await runCli([- "auth", "status", "kie.project", "--runtime", "/tmp/runtime.json", "--json",+ "auth", "status", "images.project", "--runtime", "/tmp/runtime.json", "--json",], { write: (text) => { output += text; } }, distribution);assert.deepEqual(calls, [- "credentials.create:kie.project",- "credentials.status:kie.project",+ "credentials.create:images.project",+ "credentials.status:images.project","credentials.close",]);- assert.equal((JSON.parse(output) as { readonly endpoint?: string }).endpoint, "kie.project");+ assert.equal((JSON.parse(output) as { readonly endpoint?: string }).endpoint, "images.project");const machine = JSON.parse(output) as { readonly credentials: readonly Record<string, unknown>[] };assert.equal("ref" in machine.credentials[0]!, false);assert.equal("key" in machine.credentials[0]!, false);@@ -494,11 +526,11 @@ test("auth login explains an environment-owned credential before asking for a seconst credentials = {async credentials() {return [{- endpoint: "kie.project",+ endpoint: "images.project",slot: "apiKey",- label: "KIE API key",+ label: "Image service API key",kind: "secret",- ref: { store: "env", key: "KIE_API_KEY" },+ ref: { store: "env", key: "IMAGE_API_KEY" },configured: false,writable: false,}];@@ -514,7 +546,7 @@ test("auth login explains an environment-owned credential before asking for a seawait assert.rejects(async () => await runCli([- "auth", "login", "kie.project", "--runtime", "/tmp/runtime.json",+ "auth", "login", "images.project", "--runtime", "/tmp/runtime.json",], {write() {},readSecret: async () => {@@ -522,7 +554,7 @@ test("auth login explains an environment-owned credential before asking for a sereturn "must-not-be-read";},}, distribution),- /cannot be written.*set KIE_API_KEY/u,+ /cannot be written.*set IMAGE_API_KEY/u,);assert.equal(prompted, false);assert.equal(closed, true);@@ -566,6 +598,7 @@ test("cancelling a completed Build reports that no cancellation was requested",requested: false,build: {id: "build-complete",+ targets: [],work: { state: "done", outcome: "complete" },result: { state: "complete", outputCount: 0 },},diff --git a/packages/cli/test/observation.test.ts b/packages/cli/test/observation.test.tsindex b81050bd..262024f0 100644--- a/packages/cli/test/observation.test.ts+++ b/packages/cli/test/observation.test.ts@@ -27,15 +27,24 @@ function view(outstandingCommands: pending,operations: [...Array.from({ length: pending }, () => ({- endpoint: "kie.default",+ endpoint: "images.default",status: "pending" as const,progress: { phase: "generating" },})),- ...Array.from({ length: completed }, () => ({ endpoint: "kie.default", status: "completed" as const })),+ ...Array.from({ length: completed }, () => ({ endpoint: "images.default", status: "completed" as const })),],};}+test("local command activity appears without verbose and wakes observation when frame counts change", () => {+ const initial = { ...view("running", 0, 0), commands: [{ id: "render", endpoint: "local.example",+ progress: { phase: "drawing", completed: 40, total: 100, unit: "frames" } }] };+ const advanced = { ...initial, commands: [{ ...initial.commands[0]!,+ progress: { ...initial.commands[0]!.progress, completed: 60 } }] };+ assert.notEqual(buildObservationKey(initial), buildObservationKey(advanced));+ assert.match(buildProgressLines(buildProgressView(initial), { verbose: false, limit: 20 }).join("\n"), /drawing.*40\/100 frames/);+});+test("Build observation ignores Worker turn churn and coalesces rapid real progress", async () => {const running = view("running", 7, 0);const waiting = view("waiting", 7, 0);diff --git a/packages/cli/test/output.test.ts b/packages/cli/test/output.test.tsindex 6edd28d7..a5bd3769 100644--- a/packages/cli/test/output.test.ts+++ b/packages/cli/test/output.test.ts@@ -1,7 +1,7 @@import assert from "node:assert/strict";import test from "node:test";-import { createPricingOutput, renderCliError, writeCliHelp, writeCliOutput } from "../src/output.js";+import { createPlanOutput, createPricingOutput, renderCliError, writeCliHelp, writeCliOutput } from "../src/output.js";import type { PlanNeed, PricingEntry } from "../src/output.js";import { parseCommand } from "../src/arguments.js";@@ -95,7 +95,8 @@ test("plan presents useful choices and readable requests without default graph i},} as const;const output = capture(human, presentation);- assert.match(output, /take\.video\s+← preview/u);+ assert.match(output, /Run choices\s+1/u);+ assert.doesNotMatch(output, /← preview/u);assert.match(output, /Requests\s+1/u);assert.match(output, /Preflight\s+ready/u);assert.doesNotMatch(output, /Runtime\s+ready/u);@@ -104,6 +105,7 @@ test("plan presents useful choices and readable requests without default graph iconst verbose = capture({ ...human, verbose: true }, presentation);assert.match(verbose, /Requests\s+1/u);assert.match(verbose, /unused\.image/u);+ assert.match(verbose, /take\.video\s+← preview/u);});test("plan names the Provider and price page behind each request, and points at --runtime when it cannot", () => {@@ -164,9 +166,9 @@ test("plan names the Provider and price page behind each request, and points atassert.doesNotMatch(output, /seedance@1#/u);const verbose = capture({ ...human, verbose: true }, { kind: "plan", machine: { ...base, providers: [- { request: "seedance:one", capability: "@hypit/seedance@1#seedance-2-mini", status: "ambiguous", endpoints: ["hypihub.default", "kie.default"] },+ { request: "seedance:one", capability: "@hypit/seedance@1#seedance-2-mini", status: "ambiguous", endpoints: ["hypihub.default", "images.personal"] },] } });- assert.match(verbose, /@hypit\/seedance@1#seedance-2-mini\n\s+hypihub\.default, kie\.default all offer it/u);+ assert.match(verbose, /@hypit\/seedance@1#seedance-2-mini\n\s+hypihub\.default, images\.personal all offer it/u);});test("pricing presents Provider-owned material beside the corresponding Needs", () => {@@ -180,15 +182,15 @@ test("pricing presents Provider-owned material beside the corresponding Needs",}],}, {request: "image:one", capability: "@hypit/gpt-image@1#gpt-image-2", status: "resolved",- endpoint: "kie.default", use: "@hypit/provider-kie",- pricing: { kind: "page", url: "https://kie.ai/pricing" },+ endpoint: "images.personal", use: "@studio/provider-images",+ pricing: { kind: "page", url: "https://images.example/pricing" },}], [{request: "seedance:one", step: "video::component::presenter.generate", port: "generation",capability: "@hypit/seedance@1#seedance-2", endpoint: "hypihub.default",summary: { fields: { duration: 5, resolution: "720p" }, references: {} }, pending: [],}, {request: "image:one", step: "video::component::portrait.generate", port: "generation",- capability: "@hypit/gpt-image@1#gpt-image-2", endpoint: "kie.default", pending: [],+ capability: "@hypit/gpt-image@1#gpt-image-2", endpoint: "images.personal", pending: [],}]),} as const;const output = capture(human, presentation);@@ -196,7 +198,7 @@ test("pricing presents Provider-owned material beside the corresponding Needs",assert.match(output, /https:\/\/hypit\.ai\/v1\/pricing\?model=bytedance%2Fseedance-2/u);assert.match(output, /"per_second_usd": 0\.1045/u);assert.match(output, /duration 5 · resolution 720p/u);- assert.match(output, /Pricing page\s+https:\/\/kie\.ai\/pricing/u);+ assert.match(output, /Pricing page\s+https:\/\/images\.example\/pricing/u);const verbose = capture({ ...human, verbose: true }, presentation);assert.match(verbose, /"per_second_usd": 0\.1045/u);@@ -304,6 +306,7 @@ test("run check treats historical reuse as a normal summary", () => {targets: ["final.video"],candidates: 1,satisfactions: 1,+ historicalOutputCount: 1,unresolvedHistoricalOutputs: [{ candidate: "previous", build: "bld_previous", output: "take.video" }],},});@@ -312,6 +315,47 @@ test("run check treats historical reuse as a normal summary", () => {assert.doesNotMatch(output, /unresolved|bld_previous|Candidate/u);});+test("plan scope omits unused branches while retaining every demanded request and diagnostic", () => {+ const needs = Array.from({ length: 61 }, (_, index): PlanNeed => ({+ request: `need-${index}`, step: `item-${index}`, port: "request", capability: "example@1#render", pending: [],+ ...(index === 60 ? { issue: "missing source" } : {}),+ }));+ const plan = {+ format: "hypit.cli-plan@1" as const, ok: false, run: "build.svrun", targetCount: 2,+ targets: ["final.video", "poster.image"], steps: 400, requestCount: needs.length, requestIssueCount: 1,+ choiceCount: 35, choices: Array.from({ length: 35 }, (_, i) => ({ output: `old-${i}`, candidate: `selected-${i}` })),+ unreached: Array.from({ length: 125 }, (_, i) => ({ output: `unused-${i}`, operation: "old-producer" })),+ needs, providers: needs.map((need) => ({ request: need.request, capability: need.capability, status: "resolved" as const, endpoint: "local" })),+ preflight: { ok: false, capabilityCount: 2, capabilities: ["a", "b"], diagnosticCount: 2,+ diagnostics: [{ severity: "warning" as const, code: "WARNING", message: "first" },+ { severity: "error" as const, code: "REQUIRED", message: "last required error" }] },+ };+ const machine = createPlanOutput(plan, { verbose: false, limit: 1 });+ const parsed = JSON.parse(capture({ ...human, json: true }, { kind: "plan", machine }));+ assert.equal(parsed.choiceCount, 35);+ assert.equal("choices" in parsed, false);+ assert.equal("unreached" in parsed, false);+ assert.equal("steps" in parsed, false);+ assert.equal(parsed.needs.length, 61);+ assert.equal(parsed.providers.length, 61);+ assert.deepEqual(parsed.targets, plan.targets);+ assert.deepEqual(parsed.preflight.diagnostics, plan.preflight.diagnostics);+ const rendered = capture(human, { kind: "plan", machine });+ assert.match(rendered, /missing source/u);+ assert.match(rendered, /last required error/u);+ assert.doesNotMatch(rendered, /old-\d|unused-\d/u);+ assert.match(rendered, /request summary unavailable/u);+ assert.doesNotMatch(rendered, /no parameters/u);++ const detailed = createPlanOutput(plan, { verbose: true, limit: 1 });+ assert.equal(detailed.choices?.length, 1);+ assert.equal(detailed.omittedChoices, 34);+ assert.equal(detailed.unreached?.length, 1);+ assert.equal(detailed.omittedUnreached, 124);+ assert.equal(detailed.needs?.length, 61);+ assert.deepEqual(detailed.preflight?.diagnostics, plan.preflight.diagnostics);+});+test("help is concise and describes stable rather than complete output", () => {let output = "";writeCliHelp({ write(text) { output += text; } });diff --git a/packages/cli/test/programs-command.test.ts b/packages/cli/test/programs-command.test.tsindex f4a76892..d9ca3229 100644--- a/packages/cli/test/programs-command.test.ts+++ b/packages/cli/test/programs-command.test.ts@@ -68,6 +68,47 @@ test("programs accepts only up, down and status", async () => {);});+test("scoped preparation and startup receive the same explicit Endpoint set", async () => {+ const calls: string[] = [];+ let prepared: unknown;+ const selected = distribution(calls);+ const base = selected.openRuntimeHost!;+ await runCli(["programs", "up", "/p/hypit.runtime.json", "--endpoint", "chosen", "--endpoint", "media"], io, {+ ...selected,+ openRuntimeHost: async (...args) => {+ const host = await base(...args);+ return { ...host, prepare: async (scope) => { prepared = scope?.endpoints; return []; } };+ },+ });+ assert.deepEqual(prepared, ["chosen", "media"]);+ assert.match(calls[0]!, /"endpoints":\["chosen","media"\]/u);+});++test("program discovery preserves readiness and failed shutdown names the service still running", async () => {+ const reports: CliManagedProgramReport[] = [+ ...Array.from({ length: 25 }, (_, index) => ({ id: `ready-${index}`, endpoint: "chosen", state: { state: "ready" as const } })),+ { id: "needs-help", endpoint: "other", state: { state: "down", detail: "cannot connect" } },+ ];+ let output = "";+ await runCli(["programs", "status", "/tmp/profile.json", "--json", "--limit", "2"], {+ write(text) { output += text; },+ }, distribution([], reports));+ const parsed = JSON.parse(output);+ assert.equal(parsed.programCount, 26);+ assert.equal(parsed.readyCount, 25);+ assert.deepEqual(parsed.programs.map((item: { id: string }) => item.id), ["needs-help", "ready-0"]);+ assert.equal(parsed.omittedPrograms, 24);++ let failure = "";+ let exitCode = 0;+ await runCli(["programs", "down", "/tmp/profile.json", "--limit", "1"], {+ write(text) { failure += text; }, setExitCode(code) { exitCode = code; },+ }, distribution([], reports));+ assert.equal(exitCode, 1);+ assert.match(failure, /ready-24: ready/u);+ assert.doesNotMatch(failure, /needs-help/u);+});+test("waiting belongs only to programs up", async () => {await assert.rejects(runCli(["programs", "status", "/p/hypit.runtime.json", "--max-wait-ms", "1000"], io, distribution([])),diff --git a/packages/cli/test/runtime-selection.test.ts b/packages/cli/test/runtime-selection.test.tsindex 212ba157..0b657c7c 100644--- a/packages/cli/test/runtime-selection.test.ts+++ b/packages/cli/test/runtime-selection.test.ts@@ -7,9 +7,9 @@ import test from "node:test";import type { CliDistribution } from "../src/distribution.js";import { parseCommand } from "../src/arguments.js";import { runCli } from "../src/main.js";-import { resolveProjectRoot } from "../src/project-context.js";+import { resolveProjectRoot } from "@hypit/project-context-node";import type { CliRuntimeControl } from "../src/runtime-port.js";-import { findRuntimeProfile, selectRuntimeProfile } from "../src/runtime-selection.js";+import { findRuntimeProfile, selectRuntimeProfile } from "@hypit/project-context-node";test("check has no Runtime context", () => {assert.throws(@@ -212,3 +212,18 @@ test("runtime status without a selected Profile reports the missing context instawait rm(root, { recursive: true, force: true });}});+++test("Runtime selection explains a directory collision without changing its contents", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-runtime-collision-"));+ try {+ const selection = join(root, ".hypit", "runtime");+ await mkdir(selection, { recursive: true });+ await writeFile(join(selection, "kept.txt"), "runtime data");+ const profile = join(root, "hypit.runtime.json");+ await writeFile(profile, "{}\n");+ await assert.rejects(findRuntimeProfile(root), /Runtime selection must be a file:.*occupied by a directory/u);+ await assert.rejects(selectRuntimeProfile(root, profile), /Runtime selection must be a file:.*occupied by a directory/u);+ assert.equal(await readFile(join(selection, "kept.txt"), "utf8"), "runtime data");+ } finally { await rm(root, { recursive: true, force: true }); }+});diff --git a/packages/cli/test/view.test.ts b/packages/cli/test/view.test.tsnew file mode 100644index 00000000..20003d01--- /dev/null+++ b/packages/cli/test/view.test.ts@@ -0,0 +1,62 @@+import assert from "node:assert/strict";+import test from "node:test";++import type { BuildResultManifest, BuildResultRepository } from "@hypit/build-result";+import type { BuildView } from "@hypit/runtime-host-node";+import { buildResultView, buildStatusView } from "../src/view.js";++test("inspection chooses its scope before following any Output reference", async () => {+ const names = ["final", "important", ...Array.from({ length: 50 }, (_, i) => `unused-${i}`)];+ const manifest = {+ id: "bld_20260913T093030369Z_55907CDA9E", source: { path: "main.svml" },+ targets: ["final"], highlightedOutputs: ["important"],+ outputs: Object.fromEntries(names.map((name) => [name, {}])),+ } as unknown as BuildResultManifest;+ const reads: string[] = [];+ const repository = {+ async describeOutput(_build: string, name: string) {+ reads.push(name);+ if (name.startsWith("unused-")) throw new Error("unrelated reference is unavailable");+ return { kind: "scalar", type: { module: { name: "example", version: "1" }, name: "Value" } };+ },+ } as unknown as BuildResultRepository;+ const view = await buildResultView(repository, manifest, { projectRoot: "/project", limit: 1 });+ assert.deepEqual(reads, ["final", "important"]);+ assert.equal(view.outputCount, 52);+ assert.equal(view.otherOutputCount, 50);+ assert.equal(view.omittedOutputs, undefined);+ reads.length = 0;+ await buildResultView(repository, manifest, { projectRoot: "/project", limit: 1, output: "important" });+ assert.deepEqual(reads, ["important"]);+ reads.length = 0;+ const detailed = await buildResultView(repository, manifest, { projectRoot: "/project", limit: 1, verbose: true });+ assert.deepEqual(reads, ["final"]);+ assert.equal(detailed.omittedOutputs, 51);+});++test("status groups identical active requests and retains late failures without verbose", () => {+ const pending = Array.from({ length: 30 }, (_, index) => ({+ id: `op-${index}`, endpoint: "chosen", status: "pending", receipt: { id: `remote-${index}` },+ progress: { phase: "generating" },+ }));+ const runtime = {+ id: "build", targets: ["final"], activity: "running",+ operations: [...pending,+ { id: "done", endpoint: "chosen", status: "completed" },+ { id: "failed", endpoint: "chosen", status: "failed", receipt: { id: "failed-remote" },+ failure: { code: "NETWORK", message: "download failed" } }],+ commands: [{ id: "raw-command-id", endpoint: "renderer", progress: { phase: "capturing", completed: 50, total: 100, unit: "frames" } }],+ } as unknown as BuildView;+ const view = buildStatusView({ id: "build", runtime });+ assert.deepEqual(view.targets, ["final"]);+ assert.equal(view.operations?.length, 2);+ assert.equal(view.operations?.[0]?.count, 30);+ assert.equal(view.operations?.[0]?.receipt, undefined);+ assert.equal(view.operations?.[1]?.failure?.message, "download failed");+ assert.equal(view.operations?.[1]?.receipt?.id, "failed-remote");+ assert.equal(view.commands?.[0]?.progress.completed, 50);+ assert.equal(view.commands?.[0]?.id, undefined);+ const detailed = buildStatusView({ id: "build", runtime, verbose: true });+ assert.equal(detailed.operations?.length, 31);+ assert.equal(detailed.operations?.[0]?.receipt?.id, "remote-0");+});diff --git a/packages/credential-store-env/README.md b/packages/credential-store-env/README.mdindex 8c92b4c9..ae223b7e 100644--- a/packages/credential-store-env/README.md+++ b/packages/credential-store-env/README.md@@ -3,7 +3,7 @@Read-only `CredentialStore` backed by explicitly named environment variables.```ts-credentialRef("env", "KIE_API_KEY")+credentialRef("env", "IMAGE_API_KEY")```It resolves only the requested key when an Endpoint needs it. It never enumerates or serializes thediff --git a/packages/driver-node/src/driver.ts b/packages/driver-node/src/driver.tsindex 08709e8d..e3076193 100644--- a/packages/driver-node/src/driver.ts+++ b/packages/driver-node/src/driver.ts@@ -337,6 +337,22 @@ export class NodeDriver {operation: OperationSnapshot,registration: EndpointRegistration,runtimeContext: RuntimeExecutionContext,+ ): Promise<OperationSnapshot> {+ const result = await this.#advanceOperationStep(operation, registration, runtimeContext);+ if (result.status === "failed" && operation.status !== "failed") {+ await runtimeContext.recordExecution?.({ endpoint: operation.endpoint, kind: "failed", message: result.failure!.message });+ } else if (result.completion !== undefined && operation.completion === undefined) {+ await runtimeContext.recordExecution?.({ endpoint: operation.endpoint, kind: "completed" });+ } else if (result.progress?.phase !== undefined && result.progress.phase !== operation.progress?.phase) {+ await runtimeContext.recordExecution?.({ endpoint: operation.endpoint, kind: "phase", phase: result.progress.phase });+ }+ return result;+ }++ async #advanceOperationStep(+ operation: OperationSnapshot,+ registration: EndpointRegistration,+ runtimeContext: RuntimeExecutionContext,): Promise<OperationSnapshot> {const operations = this.operations!;if (registration.kind !== "asynchronous") throw new Error("Operation Endpoint is not asynchronous");@@ -358,6 +374,10 @@ export class NodeDriver {command: structuredClone(command), need: structuredClone(command.need),resources: this.#resourceStore(operation.build), operation: operation.id,credentials: await this.#endpointCredentials({ ...registration, credentials: operation.credentials ?? registration.credentials ?? {} }),+ ...(runtimeContext.recordExecution === undefined ? {} : {+ reportDiagnostic: (diagnostic: import("@hypit/runtime").ExecutionDiagnostic) =>+ runtimeContext.recordExecution!({ endpoint: operation.endpoint, kind: "diagnostic", ...diagnostic }),+ }),checkpoint: async (checkpoint: import("@hypit/endpoint-kit").EndpointCheckpoint) => {await operations.update(operation.id, { status: "pending", ...checkpoint,submission: "accepted", acknowledgedAt: operation.acknowledgedAt ?? Date.now(), wakeAt: Date.now(), progress: { phase: checkpoint.remoteEnded ? "collecting" : "submitted" } });@@ -366,10 +386,12 @@ export class NodeDriver {};if (action === "submit") {await operations.update(operation.id, { status: "pending", submission: "started", progress: { phase: "submitting" } });+ await runtimeContext.recordExecution?.({ endpoint: operation.endpoint, kind: "started" });return await endpoint.start(context);}const pollContext = { ...context, handle: structuredClone(operation.handle!) };if (action === "collect") {+ await runtimeContext.recordExecution?.({ endpoint: operation.endpoint, kind: "phase", phase: "collecting" });if (endpoint.collect === undefined) throw new Error(`Endpoint ${registration.id} declared artifacts ready but has no collect action`);return await endpoint.collect(pollContext);}@@ -418,13 +440,13 @@ export class NodeDriver {});}- async advanceOperation(operation: OperationSnapshot): Promise<OperationSnapshot> {+ async advanceOperation(operation: OperationSnapshot, context?: RuntimeExecutionContext): Promise<OperationSnapshot> {if (operation.request === undefined) throw new Error(`Operation ${operation.id} has no stored request`);const selected = this.endpoints.resolve(operation.request.need);if (selected.status !== "resolved" || selected.registration.id !== operation.endpoint) {throw new Error(`Operation ${operation.id} cannot change its selected Endpoint ${operation.endpoint}`);}- return await this.#advanceOperation(operation, selected.registration, { build: operation.build });+ return await this.#advanceOperation(operation, selected.registration, context ?? { build: operation.build });}async #execute(@@ -464,21 +486,37 @@ export class NodeDriver {try {return await this.#executeEndpoint(state, executable, context);} catch (error) {+ await context.recordExecution?.({ endpoint: executable.endpointId, kind: "failed", message: failureMessage(error) });throw new Error(`Endpoint ${executable.endpointId} failed ${executable.command.need.capability.name}: ${failureMessage(error)}`,{ cause: error },);}}+ let phase: string | undefined;+ await context?.recordExecution?.({ endpoint: executable.endpointId, kind: "started" });try {const result = await executable.registration.handler({command: structuredClone(executable.command),need: structuredClone(executable.command.need),resources: this.#resourceStore(context?.build),credentials: await this.#endpointCredentials(executable.registration),+ reportProgress: async (progress) => {+ await context?.reportProgress?.({ endpoint: executable.endpointId, progress });+ if (progress.phase !== phase) {+ phase = progress.phase;+ await context?.recordExecution?.({ endpoint: executable.endpointId, kind: "phase", phase });+ }+ },+ ...(context?.recordExecution === undefined ? {} : {+ reportDiagnostic: (diagnostic) => context.recordExecution!({ endpoint: executable.endpointId, kind: "diagnostic", ...diagnostic }),+ }),});- return { status: "completed", event: await this.#endpointEvent(state, executable, result) };+ const event = await this.#endpointEvent(state, executable, result);+ await context?.recordExecution?.({ endpoint: executable.endpointId, kind: "completed" });+ return { status: "completed", event };} catch (error) {+ await context?.recordExecution?.({ endpoint: executable.endpointId, kind: "failed", message: failureMessage(error) });throw new Error(`Endpoint ${executable.endpointId} failed ${executable.command.need.capability.name}: ${failureMessage(error)}`,{ cause: error },diff --git a/packages/endpoint-kit/README.md b/packages/endpoint-kit/README.mdindex eae62ea2..bfc5dae9 100644--- a/packages/endpoint-kit/README.md+++ b/packages/endpoint-kit/README.md@@ -13,6 +13,12 @@ import type { AsyncEndpoint, CredentialRef, EndpointRequest } from "@hypit/hypitimport { generationTypes, compileWireRequest, sealGeneratedImageSet } from "@hypit/hypit/generation";```+The shipped [project Provider example](../../examples/provider-package/README.md) follows an image+request through configuration, support, upload, submission, receipt, polling, collection and pricing.+It uses an explicitly illustrative service protocol and imports only public SDK subpaths.+This SDK also exports `canonicalize`, `BlobRef`, `ResourceId`, `credentialRef` and+`isStreamingResourceStore` for Providers that construct stored results or use streaming resource IO.+For an existing model, name its exact versioned Capability and expected result Type. Map its requestports into the service's wire format; the Provider need not import the model's implementation.`@hypit/hypit/generation` supplies the common generated-media values and optional wire-mapping helpers.@@ -29,6 +35,13 @@ without changing Core demand. Each resource declares a `limit` and optional `uniA capability may add `resources` and a pure `unitsForRequest(request)` resolver for quantities ofalready declared resources. Runtime admits all claims atomically for one `fulfill-need` Command.+A long immediate call can report its current activity with+`await context.reportProgress?.({ phase: "processing", completed: 12, total: 40, unit: "items" })`.+The Provider chooses meaningful phases and quantities and reports non-secret, human-readable facts.+The Runtime attaches them to the currently executing Command; they do not change its outcome,+scheduling or Core facts. Completion clears the live activity. Direct callers may omit the callback.+For asynchronous work, return `progress` in the existing pending outcome instead.+Asynchronous execution moves forward through `start`, `poll`, and optional `collect`. `start` returnsa task handle; `pending` means an acknowledged task is still running. `ready` records remote completionand hands its artifacts to `collect`, allowing download capacity to differ from task capacity.@@ -109,3 +122,14 @@ represented by a semantic `pendingInputs` slot instead. A Provider may use the smedia role to enforce support limits, but it never receives graph traversal rules or future bytes.It returns either `supported`, or `unsupported` with the Provider's reason. Selection infrastructurepreserves that reason without interpreting request fields or maintaining a central limitation table.++An Endpoint can additionally emit explicit, non-secret diagnostics:++```ts+await context.reportDiagnostic?.({ level: "info", message: "Encoder initialized" });+```++The Runtime binds each message to this call's Build, Command and Endpoint and owns persistence.+The Provider does not select a log path or Result repository. Messages describe operational evidence;+credentials, request bodies and opaque vendor payloads remain private. `reportProgress` continues to+report current activity; repeated counters are not an append-only log. Phase names belong to the Provider.diff --git a/packages/endpoint-kit/src/index.ts b/packages/endpoint-kit/src/index.tsindex 21a49076..8a612692 100644--- a/packages/endpoint-kit/src/index.ts+++ b/packages/endpoint-kit/src/index.ts@@ -20,7 +20,9 @@ import type {} from "@hypit/runtime";import { capacityUnits, verifyCredentialRef } from "@hypit/runtime";-export type { CanonicalValue, CapabilityRef, ModuleRef, StoredValue, TypeRef } from "@hypit/protocol";+export { canonicalize } from "@hypit/protocol";+export type { BlobRef, CanonicalValue, CapabilityRef, ModuleRef, ResourceId, StoredValue, TypeRef } from "@hypit/protocol";+export { credentialRef, isStreamingResourceStore } from "@hypit/runtime";export type {CapacityResourceClaim,CredentialAcquisition,@@ -97,6 +99,10 @@ export type EndpointInvocationContext = {readonly resources: ResourceStore;/** Only slots explicitly declared by this configured Endpoint instance are present. */readonly credentials: Readonly<Record<string, EndpointCredential>>;+ /** Explicit non-secret diagnostic output. The Provider owns its content, never its storage. */+ readonly reportDiagnostic?: (diagnostic: import("@hypit/runtime").ExecutionDiagnostic) => Promise<void>;+ /** Report non-secret activity of a long local call without creating a remote Operation. */+ readonly reportProgress?: (progress: OperationProgress) => Promise<void>;};export type ImmediateEndpointHandler = (diff --git a/packages/generation/README.md b/packages/generation/README.mdindex 1d1ad80d..9b1262c2 100644--- a/packages/generation/README.md+++ b/packages/generation/README.md@@ -15,5 +15,15 @@ schemas, validators and graph facets. Generated sets are atomic Products: a Provreturned bytes in an ResourceStore and returns typed Blob references rather than transient URLs.This package does not choose a model, Provider, credential, queue or retry policy. Model packages-declare exact request Capabilities; Endpoint packages such as `@hypit/provider-kie` implement those+declare exact request Capabilities; selected Endpoint packages implement thoseCapabilities in a selected Runtime Profile.++## Reference fields in resource transport++A service may consume per-media metadata while preparing a URL rather than in its generation JSON.+Media wire mappings (`url`, `urlArray`, `itemObject`) may declare `resourceFields: ["fieldName"]`.+`compileWireRequest` supplies those present item fields as the second argument to its URL resolver;+`itemObject.fieldKeys` separately maps fields into the generation body. Port coverage checks both+paths against the declared media fields. False, zero and empty strings remain values; omitted fields+remain absent. The resolver implements the service protocol; this package knows no particular+service or classification. Providers using custom transports carry those fields through that boundary.diff --git a/packages/generation/src/mapping.ts b/packages/generation/src/mapping.tsindex 38d28a9d..e844e0ac 100644--- a/packages/generation/src/mapping.ts+++ b/packages/generation/src/mapping.ts@@ -2,10 +2,16 @@ import { canonicalize } from "@hypit/protocol";import type { BlobRef, CanonicalValue, CapabilityRef } from "@hypit/protocol";import { isMediaPort } from "./ports.js";-import type { GenerationMediaRole, GenerationMediaValue, GenerationPortTable } from "./ports.js";+import type { GenerationMediaValue, GenerationPortTable } from "./ports.js";import { presentPorts } from "./request.js";import type { GenerationRequest } from "./request.js";+/** Per-reference fields consumed by the service's resource transport rather than its generation body. */+export type GenerationArtifactUrlResolver = (+ artifact: BlobRef,+ fields?: Readonly<Record<string, string | number | boolean>>,+) => Promise<string>;+/*** How one service names the fields of one model's declared input ports.*@@ -13,8 +19,6 @@ import type { GenerationRequest } from "./request.js";* Provider package therefore never imports a model package: the model owns what* it eats, the service owns what it calls that on the wire.*/-export type GenerationArtifactUrlResolver = (artifact: BlobRef) => Promise<string>;-export type GenerationFieldMapping =/** One scalar written as-is. */| { readonly as: "value"; readonly field: string; readonly whenAbsent?: CanonicalValue }@@ -23,14 +27,15 @@ export type GenerationFieldMapping =/** Several scalars written as one array. */| { readonly as: "valueArray"; readonly field: string; readonly whenAbsent?: CanonicalValue }/** One media item written as a resolved URL. */- | { readonly as: "url"; readonly field: string; readonly whenAbsent?: CanonicalValue }+ | { readonly as: "url"; readonly field: string; readonly resourceFields?: readonly string[]; readonly whenAbsent?: CanonicalValue }/** Several media items written as one array of resolved URLs. */- | { readonly as: "urlArray"; readonly field: string; readonly whenAbsent?: CanonicalValue }+ | { readonly as: "urlArray"; readonly field: string; readonly resourceFields?: readonly string[]; readonly whenAbsent?: CanonicalValue }/** Media items written as objects carrying the resolved URL and their item fields. */| {readonly as: "itemObject";readonly field: string;readonly urlKey: string;+ readonly resourceFields?: readonly string[];readonly fieldKeys: Readonly<Record<string, string>>;readonly whenAbsent?: CanonicalValue;};@@ -95,11 +100,9 @@ export function selectWireModelForRequest(return selectWireModel(mapping, present);}-async function urlsOf(- values: readonly GenerationMediaValue[],- resolve: GenerationArtifactUrlResolver,-): Promise<string[]> {- return await Promise.all(values.map((item) => resolve(item.artifact)));+function resourceFields(item: GenerationMediaValue, names: readonly string[] = []) {+ return Object.fromEntries(names.filter((name) => item.fields?.[name] !== undefined)+ .map((name) => [name, item.fields![name]!]));}/**@@ -127,13 +130,15 @@ export async function compileWireRequest(} else if (field.as === "valueArray") {input[field.field] = supplied as readonly CanonicalValue[];} else if (field.as === "url") {- input[field.field] = await resolve((supplied[0] as GenerationMediaValue).artifact);+ const item = supplied[0] as GenerationMediaValue;+ input[field.field] = await resolve(item.artifact, resourceFields(item, field.resourceFields));} else if (field.as === "urlArray") {- input[field.field] = await urlsOf(supplied as readonly GenerationMediaValue[], resolve);+ input[field.field] = await Promise.all((supplied as readonly GenerationMediaValue[])+ .map((item) => resolve(item.artifact, resourceFields(item, field.resourceFields))));} else {const media = supplied as readonly GenerationMediaValue[];input[field.field] = await Promise.all(media.map(async (item) => ({- [field.urlKey]: await resolve(item.artifact),+ [field.urlKey]: await resolve(item.artifact, resourceFields(item, field.resourceFields)),...Object.fromEntries(Object.entries(field.fieldKeys).filter(([source]) => item.fields?.[source] !== undefined).map(([source, target]) => [target, item.fields![source] as CanonicalValue])),@@ -178,30 +183,23 @@ export function assertMappingCoversPorts(if (isMediaPort(port)) {const media = port.value;const itemFields = media.itemFields ?? [];- if (itemFields.length > 0) {- assert(field.as === "itemObject", `${subject} must use itemObject because the port carries item fields`);- for (const item of itemFields) {- if (item.optional === true) continue;- assert(field.fieldKeys[item.name] !== undefined,- `${subject} does not map required item field ${item.name}`);- }- Object.keys(field.fieldKeys).forEach((name) => assert(- itemFields.some((item) => item.name === name),- `${subject} maps unknown item field ${name}`,- ));- continue;- }- assert(media.accepts.length === 1,+ assert(itemFields.length > 0 || media.accepts.length === 1,`${subject} accepts ${media.accepts.join(", ")}; declare one port per media role so each maps to one wire field`);assert(field.as === "url" || field.as === "urlArray" || field.as === "itemObject",`${subject} must resolve media to a URL`);if (field.as === "url") {assert(port.maxItems === 1, `${subject} uses url but the port accepts up to ${port.maxItems} items`);}- if (field.as === "itemObject") {- assert(field.fieldKeys !== undefined && Object.keys(field.fieldKeys).length === 0,- `${subject} itemObject must not map undeclared item fields`);+ const mappedFields = [+ ...(field.resourceFields ?? []),+ ...(field.as === "itemObject" ? Object.keys(field.fieldKeys) : []),+ ];+ for (const item of itemFields) {+ if (item.optional !== true) assert(mappedFields.includes(item.name),+ `${subject} does not map required item field ${item.name}`);}+ for (const name of mappedFields) assert(itemFields.some((item) => item.name === name),+ `${subject} maps unknown item field ${name}`);continue;}if (port.maxItems > 1) {diff --git a/packages/generation/test/ports.test.ts b/packages/generation/test/ports.test.tsindex fb0f87f4..2c58c574 100644--- a/packages/generation/test/ports.test.ts+++ b/packages/generation/test/ports.test.ts@@ -239,3 +239,21 @@ test("runtime media stays on graph edges until a model-owned draft is finalized"assert.throws(() => bindGenerationMedia(table, base, "referenceImage",sealGenerationMediaBinding(imagePort as never, { role: "image" }), audio), /image\//u);});++test("media item fields can belong to URL preparation separately from the request body", async () => {+ const { video } = await artifacts();+ const transportMapping: GenerationWireMapping = { ...mapping, fields: { ...mapping.fields,+ excerpt: { as: "itemObject", field: "video_list", urlKey: "url", resourceFields: ["startSec"], fieldKeys: { endSec: "ends" } },+ } };+ assertMappingCoversPorts(table, transportMapping);+ assert.throws(() => assertMappingCoversPorts(table, { ...mapping, fields: { ...mapping.fields,+ excerpt: { as: "urlArray", field: "video_list", resourceFields: ["startSec"] },+ } }), /required item field endSec/);+ const seen: unknown[] = [];+ const request = sealGenerationPortRequest(table, { prompt: ["motion"], duration: [8], resolution: ["720p"],+ excerpt: [{ role: "video", artifact: video, fields: { startSec: 0, endSec: 4 } }],+ });+ const result = await compileWireRequest(transportMapping, request, async (_artifact, fields) => { seen.push(fields); return "https://media.test/prepared"; });+ assert.deepEqual(seen, [{ startSec: 0 }]);+ assert.deepEqual((result.input as Record<string, unknown>).video_list, [{ url: "https://media.test/prepared", ends: 4 }]);+});diff --git a/packages/gpt-image/README.md b/packages/gpt-image/README.mdindex b2e0d7f4..1493435c 100644--- a/packages/gpt-image/README.md+++ b/packages/gpt-image/README.md@@ -5,8 +5,7 @@ Exact model/compute contracts for GPT Image 2 requests.One closed Port Table accepts the supported scalar settings and optional reference images. Runtime-produced references remain explicit Blob edges: the model-owned Draft is bound one edge at a time,then finalized into the only `GenerationRequest` a Provider can receive. The package owns model-semantics but no API key, Provider selection, queue or network code. `@hypit/provider-kie` is-one optional Runtime implementation.+semantics but no API key, Provider selection, queue or network code. The selected Provider implements its exact capability.Provider-specific combination limits are checked by that Provider before any paid operation. Theydo not narrow this model-owned vocabulary or leak into author source.diff --git a/packages/grok-imagine/README.md b/packages/grok-imagine/README.mdindex d4ef31dd..4f52a50e 100644--- a/packages/grok-imagine/README.md+++ b/packages/grok-imagine/README.md@@ -4,8 +4,7 @@ Exact author/compute contracts and package-owned author Surfaces for Grok ImaginIt exposes the standard and 1.5-preview models as distinct Surfaces. Each request is nominally typed andvalidated before yielding an ordinary video Artifact. The package declares the model-choice; it does not route to another model or access a Provider. `@hypit/provider-kie` is one-optional Runtime implementation.+choice; it does not route to another model or access a Provider. The selected Provider implements its exact capability.```xml<grok:Video id="clip" prompt={prompt} duration="6" aspect-ratio="9:16" resolution="720p">diff --git a/packages/hyperframes/README.md b/packages/hyperframes/README.mdindex a027367e..65f55c08 100644--- a/packages/hyperframes/README.md+++ b/packages/hyperframes/README.md@@ -55,8 +55,12 @@ This keeps actual video available to the renderer's exact source-frame preparatiCSS is scoped to the generated program root with `@scope`; `:scope` styles that root. The HTML cancontain arbitrary local structure, SVG, internal stacking, masks and backdrop filters. The optional`setup` string is a JavaScript function body with `root` and `data` arguments. It returns a synchronous-`render(localFrame)` function, evaluated on initial load and every `hf-seek`. Express animation state-as a function of this frame and inputs so any worker can begin at any frame. Async work belongs to+`render(localFrame)` function, evaluated on initial load and active `hf-seek` events. Outside the+Present's lifetime, the dispatcher settles the boundary pose once instead of repeatedly updating+an invisible program. Active seeks always redraw, including the same frame after resources become+ready, and seeking back into the Present computes its requested pose directly. Prepare stable+objects in `setup`; express animation state as a function of frame and inputs so any worker can+begin at any frame. Async work belongs tomaterial preparation before rendering; browser resources belong in the program's declared artifacts.Use `hyperframesResourceUri(artifact.resource)` in resource-bearing markup or CSS.diff --git a/packages/hyperframes/src/browser-program.ts b/packages/hyperframes/src/browser-program.tsindex afd95600..f4265f6a 100644--- a/packages/hyperframes/src/browser-program.ts+++ b/packages/hyperframes/src/browser-program.ts@@ -63,13 +63,22 @@ export function browserProgramScript(entries: readonly {const render = entry.program.setup === undefined ? () => {} :new Function('root', 'data', entry.program.setup)(root, entry.program.data);if (typeof render !== 'function') throw new Error('Browser program setup must return render(localFrame).');- return { ...entry, render };+ return { ...entry, render, region: undefined };} catch (error) { fail(error); return { ...entry, render: () => {} }; }});const apply = time => {const frame = Math.round(Number(time || 0) * ${numerator} / ${denominator});for (const entry of renders) {- try { entry.render(Math.max(0, Math.min(entry.durationFrames, frame - entry.startFrame))); }+ const local = frame - entry.startFrame;+ const region = local < 0 ? 'before' : local >= entry.durationFrames ? 'after' : 'active';+ // Preserve the initial/boundary pose, but stop updating an invisible+ // program at the same clamped endpoint. Active seeks always render,+ // including repeated frame 0 after images/fonts finish loading.+ if (region !== 'active' && entry.region === region) continue;+ try {+ entry.render(Math.max(0, Math.min(entry.durationFrames, local)));+ entry.region = region;+ }catch (error) { fail(error); }}};diff --git a/packages/hyperframes/test/document.test.ts b/packages/hyperframes/test/document.test.tsindex a7745a3d..5c1271aa 100644--- a/packages/hyperframes/test/document.test.ts+++ b/packages/hyperframes/test/document.test.ts@@ -560,3 +560,26 @@ test("browser program state follows direct seeks and reports authored evaluationseek({ detail: { time: 3 } });assert.match(window.__hypitBrowserProgramError!, /bad pose/);});++test("inactive programs settle once, while re-entry and repeated active seeks still redraw ready assets", async () => {+ const { runInNewContext } = await import("node:vm");+ const { browserProgramScript } = await import("../src/browser-program.js");+ const root = { frames: [] as number[], ready: false, painted: false };+ let seek: (event: { detail: { time: number } }) => void = () => {};+ runInNewContext(browserProgramScript([{ id: "scene", startFrame: 30, durationFrames: 30,+ program: { html: "", setup: 'return frame => { root.frames.push(frame); root.painted=root.ready; };' },+ }], 30, 1), { window: { addEventListener: (_: string, callback: typeof seek) => { seek = callback; } },+ document: { getElementById: () => root } });+ seek({ detail: { time: 0.5 } });+ assert.deepEqual(root.frames, [0]);+ seek({ detail: { time: 1 } });+ root.ready = true;+ seek({ detail: { time: 1 } });+ assert.equal(root.painted, true);+ seek({ detail: { time: 2 } });+ seek({ detail: { time: 3 } });+ assert.deepEqual(root.frames, [0, 0, 0, 30]);+ seek({ detail: { time: 1.5 } });+ seek({ detail: { time: 0.5 } });+ assert.deepEqual(root.frames, [0, 0, 0, 30, 15, 0]);+});diff --git a/packages/media-execution/README.md b/packages/media-execution/README.mdindex bf9682b9..ed80aab8 100644--- a/packages/media-execution/README.md+++ b/packages/media-execution/README.md@@ -20,9 +20,8 @@ owns the byte-level implementations of the eight current operations:- render an exact sample-domain audio program;- mux rendered visual and audio products.-Local and AWS Lambda Providers call these same functions with different Artifact I/O and FFmpeg-launch environments. They therefore share stream selection, timing, codec and validation behavior-instead of reimplementing media semantics per deployment.+The local Provider calls these functions with its Artifact I/O and FFmpeg launch environment. Other+deployments can reuse the same functions to preserve stream selection, timing, codec and validation behavior.This is not an author package, Provider, queue or Core extension. It performs no endpoint selection,credential lookup or SVML parsing.diff --git a/packages/media-pipeline/README.md b/packages/media-pipeline/README.mdindex da47f642..bc29dd46 100644--- a/packages/media-pipeline/README.md+++ b/packages/media-pipeline/README.md@@ -109,8 +109,8 @@ RenderedVisual + TimelineAudio -> mux-program-media Need -> MuxedMediaCompiling an `AudioProgramPlan` is ordinary deterministic code. Reading Artifact bytes, decoding,resampling, mixing, encoding or muxing is never a Producer shortcut: it is an explicit ProviderNeed. The plan fixes exact 48 kHz sample boundaries, gain/fade/playback parameters and the absence-of hidden normalization/limiting. The local FFmpeg and AWS Lambda Providers consume the same shared-execution body and return the same public contracts.+of hidden normalization/limiting. The local FFmpeg Provider consumes the shared execution body. Other Providers implement the same+public request and result semantics.AudioProgramPlan preserves AudioClip `gainEnvelope` and `audibility` on the full program sampleclock. The [Composition definition](../composition/README.md#audio-presentation-on-the-program-clock)diff --git a/packages/media-pipeline/src/component.ts b/packages/media-pipeline/src/component.tsindex 47febd12..463f64b6 100644--- a/packages/media-pipeline/src/component.ts+++ b/packages/media-pipeline/src/component.ts@@ -66,6 +66,7 @@ function plannedMediaNeed(port: string,capability: CapabilityRef,roles: Readonly<Record<string, string>> = {},+ present?: PlannedNeedFacet["present"],): PlannedNeedFacet {return {producer,@@ -75,6 +76,7 @@ function plannedMediaNeed(return { constraints: {}, pendingInputs: plannedNeedInputs(state, step, roles) };},present(specification) {+ if (present !== undefined) return present(specification);const references: Record<string, number> = {};for (const item of specification.pendingInputs) {const role = item.role;@@ -86,6 +88,18 @@ function plannedMediaNeed(};}+const presentAudioRender: NonNullable<PlannedNeedFacet["present"]> = (specification) => {+ const request = specification.constraints as Partial<RenderAudioNeed>;+ if (request.plan === undefined) return { fields: {}, references: {} };+ const { plan, range } = request;+ return { fields: {+ startFrame: [range?.startFrame ?? 0],+ endFrameExclusive: [range?.endFrameExclusive ?? plan.frameCount],+ frameRate: [`${plan.frameRate.numerator}/${plan.frameRate.denominator}`],+ sampleRate: [plan.sampleRate],+ }, references: {} };+};+export const mediaPipelineComponent = {validators: [{@@ -363,8 +377,8 @@ export const mediaPipelineComponent = {mediaPipelineCapabilities.projectSpeechEvidenceAudio,{ media: "audio" },),- plannedMediaNeed(mediaPipelineProducers.renderAudio, "audio", mediaPipelineCapabilities.renderAudio, { plan: "audio" }),- plannedMediaNeed(mediaPipelineProducers.renderAudioRange, "audio", mediaPipelineCapabilities.renderAudio, { plan: "audio" }),+ plannedMediaNeed(mediaPipelineProducers.renderAudio, "audio", mediaPipelineCapabilities.renderAudio, {}, presentAudioRender),+ plannedMediaNeed(mediaPipelineProducers.renderAudioRange, "audio", mediaPipelineCapabilities.renderAudio, {}, presentAudioRender),plannedMediaNeed(mediaPipelineProducers.mux, "media", mediaPipelineCapabilities.mux, { visual: "video", audio: "audio" }),],} satisfies ComponentPackage;diff --git a/packages/media-pipeline/test/presentation.test.ts b/packages/media-pipeline/test/presentation.test.tsnew file mode 100644index 00000000..f7a43a4e--- /dev/null+++ b/packages/media-pipeline/test/presentation.test.ts@@ -0,0 +1,14 @@+import assert from "node:assert/strict";+import test from "node:test";+import { mediaPipelineComponent } from "../src/component.js";+import { mediaPipelineProducers } from "../src/manifest.js";++test("audio render presentation describes its own range without listing every clip", () => {+ const facet = mediaPipelineComponent.plannedNeeds.find((item) => item.producer.name === mediaPipelineProducers.renderAudioRange.name)!;+ const plan = { frameRate: { numerator: 30, denominator: 1 }, frameCount: 600, sampleRate: 48000,+ clips: Array.from({ length: 35 }, () => ({ source: "not a CLI output" })) };+ assert.deepEqual(facet.present!({ constraints: {}, pendingInputs: [] }), { fields: {}, references: {} });+ assert.deepEqual(facet.present!({ constraints: { plan, range: { startFrame: 30, endFrameExclusive: 91 } }, pendingInputs: [] }), {+ fields: { startFrame: [30], endFrameExclusive: [91], frameRate: ["30/1"], sampleRate: [48000] }, references: {},+ });+});diff --git a/packages/mimo-speech/README.md b/packages/mimo-speech/README.mdindex 15ea1a7e..db9cc33c 100644--- a/packages/mimo-speech/README.md+++ b/packages/mimo-speech/README.md@@ -9,7 +9,7 @@ The package owns two distinct speech operations:- `mimo-v2.5-tts-voiceclone` uses one accepted audio voice reference to create independent speech.It contains no API URL, credential, retry, queue or Xiaomi wire encoding. Those belong to a Runtime-Endpoint such as `@hypit/provider-xiaomi-mimo`. Both models return the shared `GeneratedAudioSet`;+Endpoint implementing the selected speech capability. Both models return the shared `GeneratedAudioSet`;the author Surfaces expose its primary member as an ordinary audio Resource.```xmldiff --git a/packages/minimax-h3/README.md b/packages/minimax-h3/README.mdindex fdfe7100..cf4147aa 100644--- a/packages/minimax-h3/README.md+++ b/packages/minimax-h3/README.md@@ -5,7 +5,7 @@ Exact author/compute contracts and package-owned author Surfaces for MiniMax H3Text, frame-guided and subject-reference modes are separate Surfaces rather than one dynamicport mode. Each produces an ordinary video Artifact. This package owns request semanticsand validation only; Provider calls, credentials, retries and queueing belong to a Runtime Endpoint-such as `@hypit/provider-kie`.+selected in the Runtime Profile.```xml<h3:TextVideo id="idea" prompt={prompt} duration="6" resolution="768P" aspect-ratio="9:16"/>diff --git a/packages/nano-banana/README.md b/packages/nano-banana/README.mdindex 74941e79..8072655c 100644--- a/packages/nano-banana/README.md+++ b/packages/nano-banana/README.md@@ -4,7 +4,7 @@ Exact author/compute contracts and package-owned author Surfaces for Nano BananaThe model variants are separate endpoints with exact request validation. Their Surfaces project theprimary result to an ordinary image Artifact. The package contains no Provider selection, API key or-network execution; `@hypit/provider-kie` is one optional Runtime implementation.+network execution. The selected Provider implements its exact capability.Import the model variant you mean and connect prompt and references as ordinary graph edges:diff --git a/packages/package-loader-node/README.md b/packages/package-loader-node/README.mdindex 96583d2a..008e2ad9 100644--- a/packages/package-loader-node/README.md+++ b/packages/package-loader-node/README.md@@ -21,3 +21,33 @@ It does not use a CommonJS root export as evidence that a package is installed:import-only and resource-only packages are valid. The active Distribution owns `@hypit/*`;Distribution code may use upstream dependencies from the machine npm home, while project packagescontinue to resolve their own dependencies from the project.++The machine home stores `<package-name>/<exact-version>/node_modules`, with the importing package's+ordinary `dependencies` selecting the version. Loading a second Distribution does not replace an+existing release. ESM, resource and executable lookup use the same selection; project dependencies+retain ordinary project ownership. There is no inventory or source-content matching.++Runtime declaration discovery may use `deferExternalDependencies` to inspect capabilities and+Managed Programs before their execution tools are prepared. Actual JavaScript imports still follow+Node resolution and must be available. A selected Profile remains a valid package configuration;+Endpoint scoping is not permission to execute an invalid or absent Provider implementation.++## Execution-owned module scopes++`NodePackageLoadOptions.importModule` lets the Host own module lifetime while package selection and+contribution validation stay here. The default uses ordinary process imports. The local execution+Host supplies a `NodeModuleScope` for each Build: selected project packages and their transitive+JavaScript dependencies receive scope-local module identities. The installed `@hypit/*` Distribution+remains shared process code. Registries and configured adapter instances are still created per Build.++`NodeModuleScope` uses Node resolution/loading hooks and transpiles scope-owned TypeScript/TSX. Its CommonJS+bridge has a scope-owned module cache, Node-style named-export discovery and synchronous evaluation;+Node's VM dynamic-import support is enabled only for the execution carrier. Public paths such as+`import.meta.url`, `__filename` and relative asset reads remain real filesystem locations. Module+identity URLs are internal names; no copied source directory is created. Closing a scope drops its+live lookup and CommonJS table; the Host retires an empty carrier to release Node's ESM cache.++This is trusted execution, not a sandbox. Builtins, native libraries and process-global state+(including `process.cwd()` and `process.env`) remain shared. Existing module bindings do not change+under an active Build; a file or dependency first+read later uses ordinary filesystem semantics. Scoped loading does not make a project tree immutable.diff --git a/packages/package-loader-node/package.json b/packages/package-loader-node/package.jsonindex dcde5cfd..a1888b39 100644--- a/packages/package-loader-node/package.json+++ b/packages/package-loader-node/package.json@@ -5,11 +5,14 @@"private": true,"type": "module","exports": {- ".": "./src/index.ts"+ ".": "./src/index.ts",+ "./module-scope": "./src/module-scope.ts"},"dependencies": {"@hypit/component-kit": "workspace:*","@hypit/host": "workspace:*",- "@hypit/protocol": "workspace:*"+ "@hypit/protocol": "workspace:*",+ "cjs-module-lexer": "2.2.1",+ "typescript": "5.9.3"}}diff --git a/packages/package-loader-node/src/distribution-resolution.ts b/packages/package-loader-node/src/distribution-resolution.tsindex 8213d3d6..50ddccee 100644--- a/packages/package-loader-node/src/distribution-resolution.ts+++ b/packages/package-loader-node/src/distribution-resolution.ts@@ -5,6 +5,7 @@ import { pathToFileURL } from "node:url";import {distributionPackageDirectory,+ declaredExternalPackageRoot,setActiveDistributionPackageRoots,setActiveExternalPackageRoots,} from "./location.js";@@ -100,7 +101,7 @@ export function installDistributionPackageResolution(roots: readonly string[]):}for (const root of installed) {const entry = resolveDistributionPackageImport(root, specifier);- if (entry !== undefined) return { url: pathToFileURL(entry).href, shortCircuit: true };+ if (entry !== undefined) return nextResolve(pathToFileURL(entry).href, context);}throw new Error(`Active Hypit Distribution does not provide ${specifier}`);}@@ -123,7 +124,6 @@ export function installExternalPackageResolution(roots: readonly string[]): void}externalInstalled = next;setActiveExternalPackageRoots(externalInstalled);- const parentUrls = externalInstalled.map((root) => pathToFileURL(join(root, "__hypit_external__.mjs")).href);registerHooks({resolve(specifier, context, nextResolve) {if (specifier.startsWith("@hypit/") || !barePackageSpecifier(specifier)) {@@ -132,8 +132,15 @@ export function installExternalPackageResolution(roots: readonly string[]): voidtry {return nextResolve(specifier, context);} catch (original) {- for (const parentURL of parentUrls) {+ if (context.parentURL === undefined || !context.parentURL.startsWith("file:")) throw original;+ if (installed.length > 0 && !installed.some((root) =>+ context.parentURL!.startsWith(pathToFileURL(`${root}/`).href))) throw original;+ for (const root of externalInstalled) {try {+ const name = packageAddress(specifier)?.name;+ const selected = name === undefined ? undefined : declaredExternalPackageRoot(root, context.parentURL, name);+ if (selected === undefined) continue;+ const parentURL = pathToFileURL(join(selected, "__hypit_external__.mjs")).href;return nextResolve(specifier, { ...context, parentURL });} catch {// Try the next machine package root before preserving Node's error.diff --git a/packages/package-loader-node/src/index.ts b/packages/package-loader-node/src/index.tsindex f42e074e..7ad95818 100644--- a/packages/package-loader-node/src/index.ts+++ b/packages/package-loader-node/src/index.ts@@ -15,6 +15,7 @@ export {} from "./distribution-resolution.js";export {locateNodePackage,+ externalPackageInstallRoot,resolveNodePackageExecutable,resolveNodePackageResource,resolveNodePackageSource,diff --git a/packages/package-loader-node/src/loader.ts b/packages/package-loader-node/src/loader.tsindex 14ca7f29..15038082 100644--- a/packages/package-loader-node/src/loader.ts+++ b/packages/package-loader-node/src/loader.ts@@ -97,10 +97,12 @@ function activationPath(item: ResolvedPackage): string {return target;}-async function importContribution(item: ResolvedPackage): Promise<NodePackageContribution> {+async function importContribution(item: ResolvedPackage, options: NodePackageLoadOptions): Promise<NodePackageContribution> {const target = activationPath(item);assert((await stat(target)).isFile(), `${item.json.name} activation is not a file`);- const imported = await import(pathToFileURL(target).href) as { readonly default?: unknown };+ const url = pathToFileURL(target).href;+ const imported = await (options.importModule !== undefined && !item.json.name.startsWith("@hypit/")+ ? options.importModule(url) : import(url)) as { readonly default?: unknown };assert(imported.default !== null && typeof imported.default === "object", `${item.json.name} activation has no default package export`);const contribution = imported.default as Partial<NodePackageContribution>;assert(contribution.format === "hypit.node-package@1", `${item.json.name} activation has an unsupported package format`);@@ -185,7 +187,7 @@ export async function distributionExternalPackageRequirements(const root = resolve(distributionRoot);const queue = [...new Set(specifiers.filter((name) => name.startsWith("@hypit/")))].sort();const visited = new Set<string>();- const external = new Map<string, string>();+ const external = new Map<string, { readonly name: string; readonly version: string; readonly specifier: string }>();while (queue.length > 0) {const name = queue.shift()!;if (visited.has(name)) continue;@@ -196,16 +198,11 @@ export async function distributionExternalPackageRequirements(queue.push(dependency);continue;}- const previous = external.get(dependency);- if (previous !== undefined && previous !== version) {- throw new Error(`${dependency} is required at both ${previous} and ${version} by the selected Distribution packages`);- }- external.set(dependency, version);+ const specifier = `${dependency}@${version}`;+ external.set(specifier, { name: dependency, version, specifier });}}- return [...external.entries()]- .sort(([left], [right]) => left.localeCompare(right))- .map(([name, version]) => ({ name, version, specifier: `${name}@${version}` }));+ return [...external.values()].sort((left, right) => left.specifier.localeCompare(right.specifier));}/**@@ -256,8 +253,8 @@ export async function loadNodePackageSelection(for (const item of await Promise.all(roots.map(async (physical) => ({physical,contribution: await (async () => {- await assertExternalDependencies(physical, distributionRoots, externalRoots);- return await importContribution(physical);+ if (!options.deferExternalDependencies) await assertExternalDependencies(physical, distributionRoots, externalRoots);+ return await importContribution(physical, options);})(),})))) add(item);@@ -270,8 +267,8 @@ export async function loadNodePackageSelection(providerPackage,resolutionRoots(providerPackage, [requirement.from, root], distributionRoots),);- await assertExternalDependencies(physical, distributionRoots, externalRoots);- const provider = { physical, contribution: await importContribution(physical) };+ if (!options.deferExternalDependencies) await assertExternalDependencies(physical, distributionRoots, externalRoots);+ const provider = { physical, contribution: await importContribution(physical, options) };add(provider);assert(providedModules.has(requirement.key), `${providerPackage} does not provide the required ${requirement.key}`);}diff --git a/packages/package-loader-node/src/location.ts b/packages/package-loader-node/src/location.tsindex d73a8a26..da2f3abb 100644--- a/packages/package-loader-node/src/location.ts+++ b/packages/package-loader-node/src/location.ts@@ -66,6 +66,31 @@ function packageName(value: string): string {return value;}+/** One ordinary npm installation per exact upstream release; no shared mutable node_modules. */+export function externalPackageInstallRoot(root: string, name: string, version: string): string {+ packageName(name);+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(version)) {+ throw new Error(`${name}@${version} must select an exact upstream version`);+ }+ return join(resolve(root), ...name.split("/"), version);+}++/** The importing package's own manifest owns its upstream version selection. */+export function declaredExternalPackageRoot(root: string, from: string | URL, name: string): string | undefined {+ let cursor = dirname(fromPath(from));+ while (true) {+ const manifest = join(cursor, "package.json");+ if (existsSync(manifest)) {+ const value = JSON.parse(readFileSync(manifest, "utf8")) as { dependencies?: Record<string, string> };+ const version = value.dependencies?.[name];+ return version === undefined ? undefined : externalPackageInstallRoot(root, name, version);+ }+ const parent = dirname(cursor);+ if (parent === cursor) return undefined;+ cursor = parent;+ }+}+function packageSourceAddress(value: string): { readonly name: string; readonly subpath: string } {if (value.startsWith(".") || value.startsWith("/") || value.startsWith("#") || value.includes(":")) {throw new Error(`${value} must be one npm package Source export`);@@ -187,7 +212,8 @@ export function locateNodePackage(nameValue: string, options: LocateNodePackageO?? distributionRoots.some((root) => within(root, dirname(from)));if (allowExternal) {for (const root of externalRoots) {- const found = nodeModulesPackage(root, name);+ const installation = declaredExternalPackageRoot(root, from, name);+ const found = installation === undefined ? undefined : nodeModulesPackage(installation, name);if (found !== undefined) return found;}}diff --git a/packages/package-loader-node/src/module-scope.ts b/packages/package-loader-node/src/module-scope.tsnew file mode 100644index 00000000..ca40f4bb--- /dev/null+++ b/packages/package-loader-node/src/module-scope.ts@@ -0,0 +1,183 @@+import Module, { createRequire, findPackageJSON, isBuiltin, registerHooks } from "node:module";+import { readFileSync } from "node:fs";+import { dirname, extname, isAbsolute, join, sep } from "node:path";+import { tmpdir } from "node:os";+import { fileURLToPath, pathToFileURL } from "node:url";+import { compileFunction } from "node:vm";+import { initSync, parse as parseCommonJs } from "cjs-module-lexer";+import { transpileModule, ModuleKind, ScriptTarget, JsxEmit } from "typescript";++/** A module identity namespace, not a filesystem directory. No files are written here. */+const prefix = pathToFileURL(join(tmpdir(), ".hypit-module-scopes", String(process.pid)) + sep).href;+const bridge = "hypit-internal:module-scope";+const requestPrefix = "hypit-module-request:";+const scopes = new Map<string, NodeModuleScope>();+let serial = 0;+let installed = false;++function address(value: string | undefined): { scope: string; url: string } | undefined {+ if (value === undefined) return undefined;+ const url = isAbsolute(value) ? pathToFileURL(value).href : value;+ if (!url.startsWith(prefix)) return undefined;+ const [scope, encoded] = url.slice(prefix.length).split("/");+ if (!scope || !encoded) return undefined;+ return { scope, url: Buffer.from(encoded.slice(0, -4), "base64url").toString("utf8") };+}++function moduleUrl(scope: string, url: string): string {+ return `${prefix}${scope}/${Buffer.from(url).toString("base64url")}.mjs`;+}++function commonJsSource(filename: string): string {+ const source = readFileSync(filename, "utf8").replace(/^#!/u, "//");+ return /\.[cm]?tsx?$|\.jsx$/u.test(filename) ? transpileModule(source, {+ fileName: filename,+ compilerOptions: { module: ModuleKind.CommonJS, target: ScriptTarget.ES2023, jsx: JsxEmit.ReactJSX, esModuleInterop: true },+ }).outputText : source;+}++function esmSource(filename: string): string {+ const source = readFileSync(filename, "utf8").replace(/^#!/u, "//");+ return /\.[cm]?tsx?$|\.jsx$/u.test(filename)+ ? transpileModule(source, {+ fileName: filename,+ compilerOptions: { module: ModuleKind.ESNext, target: ScriptTarget.ES2023, jsx: JsxEmit.ReactJSX, esModuleInterop: true },+ }).outputText : source;+}++function exportNames(filename: string, visited = new Set<string>()): readonly string[] {+ // Node's CJS named-export discovery does not infer names from ESM or JSON reexports.+ if (visited.has(filename) || isEsModule(filename) || extname(filename) === ".json") return [];+ visited.add(filename);+ const parsed = parseCommonJs(commonJsSource(filename));+ const require = createRequire(filename);+ return [...new Set([...parsed.exports, ...parsed.reexports.flatMap((specifier) => {+ const target = require.resolve(specifier);+ return isBuiltin(target) || target.endsWith(".node") ? Object.keys(require(specifier) as object) : exportNames(target, visited);+ })])].filter((name) => name !== "default" && name !== "module.exports");+}++function isEsModule(filename: string): boolean {+ const extension = extname(filename);+ if (extension === ".mjs" || extension === ".mts") return true;+ if (extension === ".cjs" || extension === ".cts") return false;+ const manifest = findPackageJSON(pathToFileURL(filename));+ return manifest !== undefined && (JSON.parse(readFileSync(manifest, "utf8")) as { type?: string }).type === "module";+}++function scopeFor(id: string): NodeModuleScope {+ const scope = scopes.get(id);+ if (scope === undefined) throw new Error(`Module scope ${id} has ended`);+ return scope;+}++/** Internal bridge used by Node's ESM/CommonJS interop. */+export function scopedCommonJs(id: string, filename: string): unknown { return scopeFor(id).commonJs(filename); }++function install(): void {+ if (installed) return;+ initSync();+ installed = true;+ registerHooks({+ resolve(specifier, context, nextResolve) {+ if (specifier === bridge) return { url: import.meta.url, shortCircuit: true };+ if (specifier.startsWith(requestPrefix)) {+ const [scope, request, parentURL] = JSON.parse(Buffer.from(specifier.slice(requestPrefix.length), "base64url").toString("utf8")) as [string, string, string];+ scopeFor(scope);+ const found = nextResolve(request, { ...context, parentURL });+ return found.url.startsWith("file:") && !request.startsWith("@hypit/") ? { ...found, url: moduleUrl(scope, found.url) } : found;+ }+ const direct = address(specifier);+ const parent = address(context.parentURL);+ const scope = direct?.scope ?? parent?.scope;+ const target = direct === undefined ? specifier+ : new Set(context.conditions).has("require") ? fileURLToPath(direct.url) : direct.url;+ const found = nextResolve(target, parent ? { ...context, parentURL: parent.url } : context);+ // The installed Distribution is process code. Its package APIs remain shared; each+ // invocation still creates the Build's own registries, adapters and configuration.+ if (scope === undefined || !found.url.startsWith("file:") || specifier.startsWith("@hypit/")) return found;+ scopeFor(scope);+ return { ...found, url: moduleUrl(scope, found.url) };+ },+ load(url, context, nextLoad) {+ const item = address(url);+ if (item === undefined) return nextLoad(url, context);+ scopeFor(item.scope);+ const filename = fileURLToPath(item.url);+ // The scope owns loading its JS/TS implementation closure. It must not rely+ // on an outer TS hook recognizing the namespace's synthetic .mjs address.+ if (!/\.[cm]?[jt]sx?$/u.test(filename)) return nextLoad(item.url, { ...context, format: undefined });+ if (!isEsModule(filename)) {+ const names = exportNames(filename);+ return { format: "module", shortCircuit: true, source: [+ `import {scopedCommonJs} from ${JSON.stringify(bridge)};`,+ `const value=scopedCommonJs(${JSON.stringify(item.scope)},${JSON.stringify(filename)});`,+ "export default value; export {value as 'module.exports'};",+ ...names.map((name, i) => `const e${i}=value[${JSON.stringify(name)}];export {e${i} as ${JSON.stringify(name)}};`),+ ].join("\n") };+ }+ const source = esmSource(filename);+ // Author-visible filesystem addresses stay real, including import.meta.resolve().+ // Keep metadata restoration local: requiring a synchronous project ESM module+ // must not add an edge back into the asynchronously bootstrapped loader.+ const prelude = `import.meta.url=${JSON.stringify(item.url)};import.meta.filename=${JSON.stringify(filename)};` ++ `import.meta.dirname=${JSON.stringify(dirname(filename))};` ++ `{const resolve=import.meta.resolve;import.meta.resolve=(id)=>{const url=resolve(id);` ++ `if(!url.startsWith(${JSON.stringify(prefix)}))return url;` ++ `return globalThis.Buffer.from(url.slice(${prefix.length}).split('/')[1].slice(0,-4),'base64url').toString('utf8');};}\n`;+ return { format: "module", shortCircuit: true, source: prelude + source };+ },+ });+}++/** Independent loaded bindings in a shared trusted Node process; not a security sandbox. */+export class NodeModuleScope {+ readonly #id = String(++serial);+ readonly #commonJs: Record<string, NodeJS.Module> = Object.create(null) as Record<string, NodeJS.Module>;+ constructor() { install(); scopes.set(this.#id, this); }++ async import(url: string): Promise<unknown> { return await import(moduleUrl(this.#id, url)); }++ commonJs(filename: string, parent?: NodeJS.Module): unknown {+ const cached = this.#commonJs[filename];+ if (cached !== undefined) return cached.exports;+ const nativeRequire = createRequire(filename);+ const mod = new Module(filename, parent);+ mod.filename = filename;+ mod.path = dirname(filename);+ mod.paths = nativeRequire.resolve.paths("module") ?? [];+ const require = Object.assign((specifier: string): unknown => {+ if (isBuiltin(specifier)) return nativeRequire(specifier);+ const resolved = nativeRequire.resolve(specifier);+ if (specifier.startsWith("@hypit/") || resolved.endsWith(".node")) return nativeRequire(specifier);+ if (resolved.endsWith(".json")) {+ if (this.#commonJs[resolved] === undefined) {+ const json = new Module(resolved, mod);+ json.exports = JSON.parse(readFileSync(resolved, "utf8")); json.loaded = true;+ this.#commonJs[resolved] = json;+ }+ return this.#commonJs[resolved]!.exports;+ }+ if (isEsModule(resolved)) return nativeRequire(fileURLToPath(moduleUrl(this.#id, pathToFileURL(resolved).href)));+ return this.commonJs(resolved, mod);+ }, { resolve: nativeRequire.resolve, cache: this.#commonJs, extensions: nativeRequire.extensions, main: undefined }) as NodeRequire;+ mod.require = require;+ this.#commonJs[filename] = mod;+ try {+ compileFunction(commonJsSource(filename), ["exports", "require", "module", "__filename", "__dirname"], {+ filename,+ importModuleDynamically: async (specifier) => await import(requestPrefix + Buffer.from(JSON.stringify([+ this.#id, specifier, pathToFileURL(filename).href,+ ])).toString("base64url")),+ })+ .call(mod.exports, mod.exports, require, mod, filename, dirname(filename));+ mod.loaded = true;+ return mod.exports;+ } catch (error) { delete this.#commonJs[filename]; throw error; }+ }++ close(): void {+ scopes.delete(this.#id);+ for (const key of Object.keys(this.#commonJs)) delete this.#commonJs[key];+ }+}diff --git a/packages/package-loader-node/src/types.ts b/packages/package-loader-node/src/types.tsindex 4e619077..c46ef42a 100644--- a/packages/package-loader-node/src/types.ts+++ b/packages/package-loader-node/src/types.ts@@ -47,6 +47,8 @@ export type NodePackageSelectionRequest = {};export type NodePackageLoadOptions = {+ /** Host-owned module scope. Omitting this uses Node's ordinary process imports. */+ readonly importModule?: (url: string) => Promise<unknown>;/*** Additional read-only Distribution roots. They are fallbacks for project-scoped packages;* the reserved @hypit namespace resolves only from these roots when they are present.@@ -57,4 +59,6 @@ export type NodePackageLoadOptions = {* dependencies. Defaults to the roots installed by the Hypit launcher.*/readonly externalRoots?: readonly string[];+ /** Runtime declarations can be read before their optional execution tools are prepared. */+ readonly deferExternalDependencies?: boolean;};diff --git a/packages/package-loader-node/test/loader.test.ts b/packages/package-loader-node/test/loader.test.tsindex a8c70b11..c3fca473 100644--- a/packages/package-loader-node/test/loader.test.ts+++ b/packages/package-loader-node/test/loader.test.ts@@ -93,7 +93,7 @@ test("a Distribution package accepts an exact CLI-only dependency from the machiformat: "hypit.node-package@1",hostFacets: [{ abi: "example.provider@1", offers: ["example"] }]}`, { "cli-only": "1.2.3" });- const cli = join(machine, "node_modules", "cli-only");+ const cli = join(machine, "cli-only", "1.2.3", "node_modules", "cli-only");await mkdir(join(cli, "bin"), { recursive: true });await writeFile(join(cli, "package.json"), JSON.stringify({name: "cli-only",diff --git a/packages/package-loader-node/test/location.test.ts b/packages/package-loader-node/test/location.test.tsindex 0d6df09e..a21c9c9f 100644--- a/packages/package-loader-node/test/location.test.ts+++ b/packages/package-loader-node/test/location.test.ts@@ -6,6 +6,7 @@ import test from "node:test";import {installExternalPackageResolution,+ externalPackageInstallRoot,locateNodePackage,resolveNodePackageExecutable,resolveNodePackageResource,@@ -33,15 +34,19 @@ test("one physical locator distinguishes CLI packages, resources and project ownconst project = await mkdtemp(join(tmpdir(), "hypit-locator-project-"));const machine = await mkdtemp(join(tmpdir(), "hypit-locator-machine-"));try {- const cli = await machinePackage(machine, "cli-only", {+ const cli = await machinePackage(externalPackageInstallRoot(machine, "cli-only", "1.2.3"), "cli-only", {version: "1.2.3",type: "module",bin: { tool: "./bin/tool.mjs" },}, { "bin/tool.mjs": "export {};\n" });- const resource = await machinePackage(machine, "resource-only", {+ const resource = await machinePackage(externalPackageInstallRoot(machine, "resource-only", "2.3.4"), "resource-only", {version: "2.3.4",}, { "files/value.txt": "value\n" });const fromDistribution = join(distribution, "packages", "provider", "activation.mjs");+ await mkdir(join(fromDistribution, ".."), { recursive: true });+ await writeFile(join(fromDistribution, "..", "package.json"), JSON.stringify({+ dependencies: { "cli-only": "1.2.3", "resource-only": "2.3.4" },+ }));const options = {from: fromDistribution,distributionRoots: [distribution],@@ -64,21 +69,24 @@ test("one physical locator distinguishes CLI packages, resources and project own}});-test("machine npm fallback preserves ESM import conditions", async () => {+test("machine npm fallback preserves ESM conditions and each importing package's version", async () => {const machine = await mkdtemp(join(tmpdir(), "hypit-esm-machine-"));try {- await machinePackage(machine, "import-only", {- version: "1.0.0",- type: "module",- exports: { ".": { import: "./index.mjs" } },- }, { "index.mjs": "export const value = 42;\n" });+ for (const [version, value] of [["1.0.0", 42], ["2.0.0", 84]] as const) {+ await machinePackage(externalPackageInstallRoot(machine, "import-only", version), "import-only", {+ version, type: "module", exports: { ".": { import: "./index.mjs" } },+ }, { "index.mjs": `export const value = ${value};\n` });+ const consumer = join(machine, `consumer-${version}`);+ await mkdir(consumer);+ await writeFile(join(consumer, "package.json"), JSON.stringify({ dependencies: { "import-only": version } }));+ await writeFile(join(consumer, "entry.mjs"), 'export { value } from "import-only";\n');+ }installExternalPackageResolution([machine]);- const specifier = "import-only";- const imported = await import(specifier) as { readonly value?: unknown };- assert.equal(imported.value, 42);- } finally {- await rm(machine, { recursive: true, force: true });- }+ const first = await import(join(machine, "consumer-1.0.0", "entry.mjs"));+ const second = await import(join(machine, "consumer-2.0.0", "entry.mjs"));+ assert.equal(first.value, 42);+ assert.equal(second.value, 84);+ } finally { await rm(machine, { recursive: true, force: true }); }});test("package Source resolution reads one public export without activating package code", async () => {diff --git a/packages/package-loader-node/test/module-scope.test.ts b/packages/package-loader-node/test/module-scope.test.tsnew file mode 100644index 00000000..41ad5714--- /dev/null+++ b/packages/package-loader-node/test/module-scope.test.ts@@ -0,0 +1,95 @@+import assert from "node:assert/strict";+import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { pathToFileURL } from "node:url";+import test from "node:test";+import { NodeModuleScope } from "../src/module-scope.js";+import { execFile } from "node:child_process";+import { promisify } from "node:util";++test("Build module scopes preserve old bindings and read new ESM and CommonJS dependencies", async () => {+ const root = await realpath(await mkdtemp(join(tmpdir(), "hypit-module-scope-")));+ const a = new NodeModuleScope(); const b = new NodeModuleScope();+ try {+ await writeFile(join(root, "package.json"), '{"type":"module"}');+ await writeFile(join(root, "entry.ts"), `+ import {revision} from './nested.mjs';+ import cjs, {next} from './state.cjs';+ import {readFileSync} from 'node:fs';+ enum Label { Name='count' }+ export const inspect=(): Record<string,unknown>=>({revision,cjs:cjs.revision,[Label.Name]:next(),+ file:import.meta.filename,dir:import.meta.dirname,url:import.meta.url,+ resolved:import.meta.resolve('./nested.mjs'),cjsFile:cjs.file,+ text:readFileSync(new URL('./data.txt',import.meta.url),'utf8')});+ `);+ await writeFile(join(root, "state.cjs"), `const dep=require('./dep.cjs');let n=0;+ exports.revision=dep.revision;exports.file=__filename;exports.next=()=>++n;`);+ await writeFile(join(root, "nested.mjs"), "export const revision='old';");+ await writeFile(join(root, "dep.cjs"), "exports.revision='old';");+ await writeFile(join(root, "typed.cts"), "enum Value { Answer=42 }; module.exports={value:Value.Answer};");+ const jsxPackage = join(root, 'node_modules', 'fixture-jsx');+ await mkdir(jsxPackage, {recursive:true});+ await writeFile(join(jsxPackage,'package.json'), '{"name":"fixture-jsx","type":"module","exports":{"./jsx-runtime":"./runtime.js"}}');+ await writeFile(join(jsxPackage,'runtime.js'), 'export const jsx=(tag,props)=>({tag,props});');+ await writeFile(join(root,'view.tsx'), `/** @jsxImportSource fixture-jsx */+ import {revision} from './nested.mjs';+ export const view=<card label={revision}/>;`);+ await writeFile(join(root, "data.txt"), "old data");+ const url = pathToFileURL(join(root, "entry.ts")).href;+ type Entry = { inspect: () => Record<string, unknown> };+ const old = await a.import(url) as Entry;+ assert.equal((await a.import(pathToFileURL(join(root, "typed.cts")).href) as {default:{value:number}}).default.value, 42);+ type View = {view: {tag:string,props:{label:string}}};+ const oldView = await a.import(pathToFileURL(join(root,'view.tsx')).href) as View;+ assert.equal(oldView.view.props.label,'old');+ assert.equal(old.inspect().count, 1);+ await writeFile(join(root, "nested.mjs"), "export const revision='new';");+ await writeFile(join(root, "dep.cjs"), "exports.revision='new';");+ await writeFile(join(root, "data.txt"), "new data");+ const next = await b.import(url) as Entry;+ assert.equal(await a.import(url), old);+ assert.deepEqual(old.inspect(), {revision:'old',cjs:'old',count:2,file:join(root,'entry.ts'),dir:root,url,+ resolved:pathToFileURL(join(root,'nested.mjs')).href,cjsFile:join(root,'state.cjs'),text:'new data'});+ assert.equal(next.inspect().count, 1);+ assert.equal(next.inspect().revision, "new");+ assert.equal(next.inspect().cjs, "new");+ const newView = await b.import(pathToFileURL(join(root,'view.tsx')).href) as View;+ assert.equal(newView.view.props.label,'new');+ assert.equal(oldView.view.props.label,'old');+ } finally { a.close(); b.close(); await rm(root,{recursive:true,force:true}); }+});++test("execution entry point keeps mixed module imports, top-level await, and circular CommonJS local to the Build", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-module-interop-"));+ try {+ await writeFile(join(root, "esm.mjs"), "export const value=42;");+ await writeFile(join(root, "async.mjs"), "await Promise.resolve(); export const value=43;");+ await writeFile(join(root, "circle.cjs"), "exports.ready=true;exports.entry=require('./entry.cjs');");+ await writeFile(join(root, "entry.cjs"), "exports.value=require('./esm.mjs').value;exports.circle=require('./circle.cjs');exports.dynamic=()=>import('./async.mjs');");+ await writeFile(join(root, "reexport.cjs"), "module.exports=require('./esm.mjs');");+ const loader = new URL("../src/module-scope.ts", import.meta.url).href;+ await writeFile(join(root, "check.mjs"), `+ import {register} from ${JSON.stringify(import.meta.resolve("tsx/esm/api"))};+ register();+ const {NodeModuleScope}=await import(${JSON.stringify(loader)});+ const {writeFile}=await import('node:fs/promises');+ const {default:assert}=await import('node:assert/strict');+ const a=new NodeModuleScope(),b=new NodeModuleScope();+ const entry=new URL('./entry.cjs',import.meta.url).href;+ try {+ const old=await a.import(entry);+ assert.equal((await a.import(new URL('./reexport.cjs',import.meta.url).href)).default.value,42);+ assert.equal(old.default.circle.entry,old.default);+ assert.equal((await old.default.dynamic()).value,43);+ await writeFile(new URL('./esm.mjs',import.meta.url),'export const value=44;');+ await writeFile(new URL('./async.mjs',import.meta.url),'export const value=45;');+ const next=await b.import(entry);+ assert.equal(old.default.value,42);assert.equal(next.default.value,44);+ assert.equal((await old.default.dynamic()).value,43);+ assert.equal((await next.default.dynamic()).value,45);+ }finally{a.close();b.close();}+ `);+ await promisify(execFile)(process.execPath, ["--experimental-vm-modules", join(root, "check.mjs")]);+ } finally { await rm(root, { recursive: true, force: true }); }+});diff --git a/packages/project-context-node/README.md b/packages/project-context-node/README.mdnew file mode 100644index 00000000..09c49277--- /dev/null+++ b/packages/project-context-node/README.md@@ -0,0 +1,20 @@+# `@hypit/project-context-node`++Shared project and Runtime selection for Node entrypoints: CLI, Studio and creation tools.+This package resolves locations and reads or explicitly changes the project's Runtime pointer.+It does not load Providers, install programs, inspect credentials or select services.++1. `resolveProjectRoot({ workspaceRoot?, cwd? })` uses the explicit Workspace, otherwise the nearest+ `package.json` above cwd, otherwise cwd itself. Source and Run filenames do not choose the project.+2. `findRuntimeProfile(projectRoot)` reads only that project's `.hypit/runtime` file and resolves its+ path relative to the project. An entrypoint's explicit `--runtime` overrides this read for that invocation.+3. The selected Runtime implementation interprets the Profile, including `dataRoot`, Credentials,+ Providers and capability bindings. This package does not interpret its contents.++`selectRuntimeProfile(projectRoot, profile)` writes the explicit choice; `clearRuntimeProfile` removes+only that pointer. A directory occupying the pointer path is reported without replacing it. Runtime+working data belongs at the Profile's separate `dataRoot`.++Project packages, the installed Distribution and machine-managed executables have different owners.+The Distribution supplies code; it does not supply a second project environment. Provider adapters+resolve their executable configuration and report availability through the Runtime's existing ports.diff --git a/packages/project-context-node/package.json b/packages/project-context-node/package.jsonnew file mode 100644index 00000000..a634e78c--- /dev/null+++ b/packages/project-context-node/package.json@@ -0,0 +1,10 @@+{+ "name": "@hypit/project-context-node",+ "version": "0.0.0-dev",+ "license": "SEE LICENSE IN LICENSE",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ }+}diff --git a/packages/project-context-node/src/index.ts b/packages/project-context-node/src/index.tsnew file mode 100644index 00000000..d08019e6--- /dev/null+++ b/packages/project-context-node/src/index.ts@@ -0,0 +1,3 @@+export { resolveProjectRoot, resolvePackageRoot } from "./project-context.js";+export { findRuntimeProfile, selectRuntimeProfile, clearRuntimeProfile } from "./runtime-selection.js";+export type { RuntimeProfileSelection } from "./runtime-selection.js";diff --git a/packages/cli/src/project-context.ts b/packages/project-context-node/src/project-context.tssimilarity index 100%rename from packages/cli/src/project-context.tsrename to packages/project-context-node/src/project-context.tsdiff --git a/packages/cli/src/runtime-selection.ts b/packages/project-context-node/src/runtime-selection.tssimilarity index 87%rename from packages/cli/src/runtime-selection.tsrename to packages/project-context-node/src/runtime-selection.tsindex 54b7e27e..cc182522 100644--- a/packages/cli/src/runtime-selection.ts+++ b/packages/project-context-node/src/runtime-selection.ts@@ -1,4 +1,4 @@-import { mkdir, readFile, realpath, unlink, writeFile } from "node:fs/promises";+import { mkdir, readFile, realpath, stat, unlink, writeFile } from "node:fs/promises";import { relative, resolve } from "node:path";const stateDirectoryName = ".hypit";@@ -24,6 +24,10 @@ async function readSelectionFile(projectRoot: string): Promise<{const root = resolve(projectRoot);const selectionFile = resolve(root, stateDirectoryName, selectionFileName);try {+ if (!(await stat(selectionFile)).isFile()) {+ throw new Error(`Runtime selection must be a file: ${selectionFile}; this path is occupied by a directory. `+ + "Move that directory and update its configuration before running hypit runtime use <profile>.");+ }return {projectRoot: root,selectionFile,@@ -36,7 +40,7 @@ async function readSelectionFile(projectRoot: string): Promise<{}/**- * Remember one Runtime Profile for a project. This is local CLI context, not+ * Remember one Runtime Profile for a project. This is project execution context, not* Author Source, Run Source, package selection or Core state.*/export async function selectRuntimeProfile(projectRoot: string, profile: string): Promise<RuntimeProfileSelection> {@@ -50,6 +54,7 @@ export async function selectRuntimeProfile(projectRoot: string, profile: string)} catch (error) {if (errorCode(error) !== "EEXIST") throw error;}+ await readSelectionFile(root);const stored = relative(root, selectedProfile) || ".";await writeFile(selectionFile, `${stored}\n`, "utf8");return { profile: selectedProfile, projectRoot: root, selectionFile };diff --git a/packages/provider-hyperframes-aws-lambda/README.md b/packages/provider-hyperframes-aws-lambda/README.mddeleted file mode 100644index 3e61fa23..00000000--- a/packages/provider-hyperframes-aws-lambda/README.md+++ /dev/null@@ -1,30 +0,0 @@-# `@hypit/provider-hyperframes-aws-lambda`--Asynchronous AWS Step Functions/Lambda implementation of the exact-`@hypit/render-hyperframes#render-visual` capability.--The Endpoint stages the immutable `HyperframesDocument` with the shared-`stageHyperframesProject()` layout, uploads that operation-scoped site, starts one distributed-render and persists its execution ARN in the Operation checkpoint. Its Step Functions execution name is derived from the-Runtime Operation id, so recovery cannot accidentally submit the same attempt twice.-Cancellation uses that same identity to stop the remote Step Functions execution, including the-crash window before the first checkpoint was saved.--This Provider accepts whole-document requests at integer 24, 30 and 60 fps; it currently declines-requests containing a frame range. Its chunk settings partition a whole render across Lambda workers,-whereas the local Provider also accepts a selected interval. Unsupported Needs-are declined by `supports()` so another Endpoint may satisfy them; no frame rate or GPU intent is-silently changed. The Provider always requests strict SDR H.264, exact CFR assembly, software-browser rendering and plan protocol v2. It also declines Surface-bearing documents until the-remote route owns the same byte verifier as the local Endpoint. Chunking remains deployment-configuration.--On success the Endpoint requires HyperFrames' plan and completed-frame counts to equal the source-document, then streams the returned S3 object into the current Build's working byte area.-The Endpoint's Runtime Profile entry selects the AWS state machine and deployment settings. The Provider does not repeat-the request or selected endpoint as vendor metadata. Container and stream conformance stays in the explicit media-inspection/mux capabilities, so the orchestrating machine does not acquire a hidden FFmpeg-dependency.--The production client uses the AWS SDK default credential chain. No access key is accepted by the-package configuration or written into Build state.diff --git a/packages/provider-hyperframes-aws-lambda/package.json b/packages/provider-hyperframes-aws-lambda/package.jsondeleted file mode 100644index 9268f7fe..00000000--- a/packages/provider-hyperframes-aws-lambda/package.json+++ /dev/null@@ -1,30 +0,0 @@-{- "name": "@hypit/provider-hyperframes-aws-lambda",- "version": "0.0.0-dev",- "license": "SEE LICENSE IN LICENSE",- "private": true,- "type": "module",- "exports": {- ".": "./src/index.ts"- },- "hypit": {- "activation": "./src/activation.ts"- },- "dependencies": {- "@aws-sdk/client-s3": "3.1103.0",- "@aws-sdk/client-sfn": "3.1103.0",- "@hyperframes/aws-lambda": "0.7.101",- "@hypit/endpoint-kit": "workspace:*",- "@hypit/hyperframes": "workspace:*",- "@hypit/media": "workspace:*",- "@hypit/protocol": "workspace:*",- "@hypit/render-hyperframes": "workspace:*",- "@hypit/runtime": "workspace:*",- "@hypit/runtime-kit": "workspace:*"- },- "devDependencies": {- "@hypit/composition": "workspace:*",- "@hypit/driver-node": "workspace:*",- "@hypit/program-space": "workspace:*"- }-}diff --git a/packages/provider-hyperframes-aws-lambda/src/activation.ts b/packages/provider-hyperframes-aws-lambda/src/activation.tsdeleted file mode 100644index c9d1fa9c..00000000--- a/packages/provider-hyperframes-aws-lambda/src/activation.ts+++ /dev/null@@ -1,97 +0,0 @@-import type { CanonicalValue } from "@hypit/protocol";-import {- createRuntimeEndpointAdapterFacet,- runtimeConfigExact,- runtimeConfigObject,- runtimeConfigPositiveInteger,- runtimeConfigString,-} from "@hypit/runtime-kit";-import type { RuntimeAdapterFactoryContext } from "@hypit/runtime-kit";--import { createAwsLambdaHyperframesProvider } from "./provider.js";-import type {- CreateAwsLambdaHyperframesProviderOptions,- HyperframesLambdaQuality,-} from "./provider.js";--const CONFIG_KEYS = [- "stateMachineArn", "bucketName", "quality", "chunkSize", "maxParallelChunks",- "targetChunkFrames", "defaultMemorySizeMb", "defaultConcurrency", "pollIntervalMs",- "maxOperationMs", "maxRenderedBytes",-] as const;--type RuntimeProviderOptions = Omit<- CreateAwsLambdaHyperframesProviderOptions,- "client" | "now"->;--function optionalInteger(- config: Record<string, CanonicalValue>,- name: string,-): number | undefined {- return runtimeConfigPositiveInteger(config[name], `HyperFrames ${name}`);-}--function providerOptions(context: RuntimeAdapterFactoryContext): RuntimeProviderOptions {- if (context.pool === undefined) throw new Error("AWS Lambda HyperFrames Provider Pool is required");- const config = runtimeConfigObject(context.config, "AWS Lambda HyperFrames");- runtimeConfigExact(config, CONFIG_KEYS, "AWS Lambda HyperFrames");- const stateMachineArn = runtimeConfigString(config.stateMachineArn, "HyperFrames stateMachineArn");- if (stateMachineArn === undefined) throw new Error("AWS Lambda HyperFrames stateMachineArn is required");- const machine = /^(arn:aws(?:-[a-z]+)*:states):([a-z0-9-]+):(\d{12}):stateMachine:([A-Za-z0-9_-]+)$/u- .exec(stateMachineArn);- if (machine === null) {- throw new Error(`HyperFrames stateMachineArn must be an unqualified AWS Step Functions state-machine ARN; got ${stateMachineArn}`);- }- const bucketName = runtimeConfigString(config.bucketName, "HyperFrames bucketName");- if (bucketName === undefined) throw new Error("AWS Lambda HyperFrames bucketName is required");- if (!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/u.test(bucketName)- || bucketName.includes("..") || bucketName.includes(".-") || bucketName.includes("-.")- || /^\d{1,3}(?:\.\d{1,3}){3}$/u.test(bucketName)) {- throw new Error("HyperFrames bucketName is invalid");- }- const quality = runtimeConfigString(config.quality, "HyperFrames quality");- if (quality !== undefined && quality !== "draft" && quality !== "standard" && quality !== "high") {- throw new Error("HyperFrames quality is invalid");- }- const chunkSize = optionalInteger(config, "chunkSize");- const maxParallelChunks = optionalInteger(config, "maxParallelChunks");- const targetChunkFrames = optionalInteger(config, "targetChunkFrames");- if (chunkSize !== undefined && targetChunkFrames !== undefined) {- throw new Error("HyperFrames chunkSize and targetChunkFrames are mutually exclusive");- }- const defaultMemorySizeMb = optionalInteger(config, "defaultMemorySizeMb");- const defaultConcurrency = optionalInteger(config, "defaultConcurrency");- const pollIntervalMs = optionalInteger(config, "pollIntervalMs");- const maxOperationMs = optionalInteger(config, "maxOperationMs");- const maxRenderedBytes = optionalInteger(config, "maxRenderedBytes");- return {- instance: context.instance,- pool: context.pool,- stateMachineArn,- bucketName,- ...(quality === undefined ? {} : { quality: quality as HyperframesLambdaQuality }),- ...(chunkSize === undefined ? {} : { chunkSize }),- ...(maxParallelChunks === undefined ? {} : { maxParallelChunks }),- ...(targetChunkFrames === undefined ? {} : { targetChunkFrames }),- ...(defaultMemorySizeMb === undefined ? {} : { defaultMemorySizeMb }),- ...(defaultConcurrency === undefined ? {} : { defaultConcurrency }),- ...(pollIntervalMs === undefined ? {} : { pollIntervalMs }),- ...(maxOperationMs === undefined ? {} : { maxOperationMs }),- ...(maxRenderedBytes === undefined ? {} : { maxRenderedBytes }),- };-}--const awsLambdaHyperframesRuntimeAdapter = createRuntimeEndpointAdapterFacet({- use: "@hypit/provider-hyperframes-aws-lambda",- activate(context) {- return { endpoint: createAwsLambdaHyperframesProvider(providerOptions(context)) };- },-});--export const hypitPackage = {- format: "hypit.node-package@1" as const,- hostFacets: [awsLambdaHyperframesRuntimeAdapter],-};--export default hypitPackage;diff --git a/packages/provider-hyperframes-aws-lambda/src/client.ts b/packages/provider-hyperframes-aws-lambda/src/client.tsdeleted file mode 100644index bf4e5a55..00000000--- a/packages/provider-hyperframes-aws-lambda/src/client.ts+++ /dev/null@@ -1,114 +0,0 @@-import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";-import { SFNClient, StopExecutionCommand } from "@aws-sdk/client-sfn";-import {- deploySite,- getRenderProgress,- renderToLambda,-} from "@hyperframes/aws-lambda/sdk";-import type {- RenderHandle,- RenderProgress,- SerializableDistributedRenderConfig,- SiteHandle,-} from "@hyperframes/aws-lambda/sdk";--export type HyperframesLambdaSite = SiteHandle;-export type HyperframesLambdaRender = RenderHandle;-export type HyperframesLambdaProgress = RenderProgress;-export type HyperframesLambdaRenderConfig = SerializableDistributedRenderConfig;--export type HyperframesLambdaOutput = {- readonly chunks: AsyncIterable<Uint8Array>;- readonly contentLength?: number;-};--export interface HyperframesAwsLambdaClient {- deploySite(input: {- readonly projectDir: string;- readonly bucketName: string;- readonly region: string;- }): Promise<HyperframesLambdaSite>;- render(input: {- readonly siteHandle: HyperframesLambdaSite;- readonly config: HyperframesLambdaRenderConfig;- readonly bucketName: string;- readonly stateMachineArn: string;- readonly region: string;- readonly outputKey: string;- readonly executionName: string;- }): Promise<HyperframesLambdaRender>;- progress(input: {- readonly executionArn: string;- readonly defaultMemorySizeMb: number;- readonly region: string;- }): Promise<HyperframesLambdaProgress>;- stop(input: {- readonly executionArn: string;- readonly region: string;- readonly reason: string;- }): Promise<void>;- openOutput(input: {- readonly s3Uri: string;- readonly region: string;- }): Promise<HyperframesLambdaOutput>;-}--function assert(condition: unknown, message: string): asserts condition {- if (!condition) throw new Error(message);-}--export function parseS3Uri(uri: string): { readonly bucket: string; readonly key: string } {- let parsed: URL;- try {- parsed = new URL(uri);- } catch {- throw new Error(`HyperFrames output URI is invalid: ${uri}`);- }- assert(parsed.protocol === "s3:" && parsed.hostname.length > 0 && parsed.pathname.length > 1,- `HyperFrames output URI must be s3://bucket/key; got ${uri}`);- assert(parsed.search.length === 0 && parsed.hash.length === 0,- "HyperFrames output URI must not contain a query or fragment");- return { bucket: parsed.hostname, key: decodeURIComponent(parsed.pathname.slice(1)) };-}--async function* byteChunks(body: unknown): AsyncIterable<Uint8Array> {- assert(body !== null && typeof body === "object" && Symbol.asyncIterator in body,- "HyperFrames S3 output has no streaming body");- for await (const chunk of body as AsyncIterable<unknown>) {- if (typeof chunk === "string") yield Buffer.from(chunk);- else if (chunk instanceof Uint8Array) yield chunk;- else throw new Error("HyperFrames S3 output emitted a non-byte chunk");- }-}--/** Uses only the AWS SDK default credential chain. No credential bytes enter this package. */-export function createHyperframesAwsLambdaClient(region: string): HyperframesAwsLambdaClient {- const s3 = new S3Client({ region });- const sfn = new SFNClient({ region });- return {- deploySite: async (input) => await deploySite({ ...input, s3 }),- render: async (input) => await renderToLambda({- ...input,- planProtocol: "v2",- s3,- sfn,- }),- progress: async (input) => await getRenderProgress({ ...input, sfn }),- async stop(input) {- await sfn.send(new StopExecutionCommand({- executionArn: input.executionArn,- error: "HypitBuildCancelled",- cause: input.reason,- }));- },- async openOutput(input) {- const target = parseS3Uri(input.s3Uri);- const output = await s3.send(new GetObjectCommand({ Bucket: target.bucket, Key: target.key }));- if (output.Body === undefined) throw new Error(`HyperFrames output ${input.s3Uri} has no body`);- return {- chunks: byteChunks(output.Body),- ...(output.ContentLength === undefined ? {} : { contentLength: output.ContentLength }),- };- },- };-}diff --git a/packages/provider-hyperframes-aws-lambda/src/index.ts b/packages/provider-hyperframes-aws-lambda/src/index.tsdeleted file mode 100644index 9cf9a303..00000000--- a/packages/provider-hyperframes-aws-lambda/src/index.ts+++ /dev/null@@ -1,21 +0,0 @@-export {- createHyperframesAwsLambdaClient,- parseS3Uri,-} from "./client.js";-export type {- HyperframesAwsLambdaClient,- HyperframesLambdaOutput,- HyperframesLambdaProgress,- HyperframesLambdaRender,- HyperframesLambdaRenderConfig,- HyperframesLambdaSite,-} from "./client.js";-export {- awsLambdaHyperframesProviderModuleRef,- createAwsLambdaHyperframesProvider,- supportsAwsLambdaHyperframes,-} from "./provider.js";-export type {- CreateAwsLambdaHyperframesProviderOptions,- HyperframesLambdaQuality,-} from "./provider.js";diff --git a/packages/provider-hyperframes-aws-lambda/src/provider.ts b/packages/provider-hyperframes-aws-lambda/src/provider.tsdeleted file mode 100644index c5b878ae..00000000--- a/packages/provider-hyperframes-aws-lambda/src/provider.ts+++ /dev/null@@ -1,522 +0,0 @@-import { mkdtemp, rm } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";--import {- defineEndpointPackage,- wakeAfter,-} from "@hypit/endpoint-kit";-import type {- EndpointFulfillment,- EndpointOutcome,- EndpointPollContext,- EndpointStartContext,- AsyncEndpoint,-} from "@hypit/endpoint-kit";-import {- assertHyperframesDocument,-} from "@hypit/hyperframes";-import type { HyperframesDocument } from "@hypit/hyperframes";-import { stageHyperframesProject } from "@hypit/hyperframes/project";-import {- mediaTypes,- sealRenderedVisual,-} from "@hypit/media";-import type { RenderedVisual } from "@hypit/media";-import {- canonicalize,-} from "@hypit/protocol";-import type {- BlobRef,- CanonicalValue,-} from "@hypit/protocol";-import { renderHyperframesCapabilities } from "@hypit/render-hyperframes";-import { isStreamingResourceStore } from "@hypit/runtime";--import {- createHyperframesAwsLambdaClient,- parseS3Uri,-} from "./client.js";-import type {- HyperframesAwsLambdaClient,- HyperframesLambdaProgress,- HyperframesLambdaRender,- HyperframesLambdaRenderConfig,- HyperframesLambdaSite,-} from "./client.js";--const HANDLE_CONTRACT = "hypit.hyperframes-aws-lambda-operation@1";-const SUPPORTED_FPS = new Set([24, 30, 60]);--export const awsLambdaHyperframesProviderModuleRef = {- name: "@hypit/provider-hyperframes-aws-lambda",- version: "1",-} as const;-export type HyperframesLambdaQuality = "draft" | "standard" | "high";--export type CreateAwsLambdaHyperframesProviderOptions = {- readonly instance?: string;- readonly pool?: string;- readonly stateMachineArn: string;- readonly bucketName: string;- readonly quality?: HyperframesLambdaQuality;- readonly chunkSize?: number;- readonly maxParallelChunks?: number;- readonly targetChunkFrames?: number;- readonly defaultMemorySizeMb?: number;- readonly defaultConcurrency?: number;- readonly pollIntervalMs?: number;- readonly maxOperationMs?: number;- readonly maxRenderedBytes?: number;- readonly client?: HyperframesAwsLambdaClient;- readonly now?: () => number;-};--type HyperframesHandle = {- readonly contract: typeof HANDLE_CONTRACT;- readonly operationId: string;- readonly executionArn: string;- readonly outputS3Uri: string;- readonly bucketName: string;- readonly site: HyperframesLambdaSite;- readonly startedAt: number;- readonly polls: number;-};--function assert(condition: unknown, message: string): asserts condition {- if (!condition) throw new Error(message);-}--function positiveInteger(value: number, subject: string): number {- assert(Number.isSafeInteger(value) && value > 0, `${subject} must be a positive integer`);- return value;-}--function nonNegativeInteger(value: number, subject: string): number {- assert(Number.isSafeInteger(value) && value >= 0, `${subject} must be a non-negative integer`);- return value;-}--function stateMachine(value: string): { readonly arn: string; readonly region: string; readonly name: string } {- const found = /^(arn:aws(?:-[a-z]+)*:states):([a-z0-9-]+):(\d{12}):stateMachine:([A-Za-z0-9_-]+)$/u.exec(value);- assert(found !== null,- `HyperFrames stateMachineArn must be an unqualified AWS Step Functions state-machine ARN; got ${value}`);- return { arn: value, region: found[2]!, name: found[4]! };-}--function executionArn(machine: ReturnType<typeof stateMachine>, executionName: string): string {- const prefix = machine.arn.slice(0, machine.arn.indexOf(":states") + ":states".length);- const account = machine.arn.split(":")[4]!;- return `${prefix}:${machine.region}:${account}:execution:${machine.name}:${executionName}`;-}--function requestDocument(value: CanonicalValue): HyperframesDocument {- assert(value !== null && typeof value === "object" && !Array.isArray(value),- "HyperFrames visual request must be an object");- const request = value as { readonly document?: unknown };- assert(Object.keys(request).sort().join(",") === "document",- "HyperFrames visual request contains unsupported requirements");- assertHyperframesDocument(request.document as HyperframesDocument);- return request.document as HyperframesDocument;-}--function awsLambdaHyperframesRejection(value: CanonicalValue): string | undefined {- try {- const document = requestDocument(value);- if (document.surfaces.length > 0) return "AWS Lambda HyperFrames does not accept embedded Surfaces";- if (document.frameRate.denominator !== 1 || !SUPPORTED_FPS.has(document.frameRate.numerator)) {- return "AWS Lambda HyperFrames accepts integer 24, 30 or 60 fps";- }- return undefined;- } catch (error) {- return error instanceof Error ? error.message : String(error);- }-}--export function supportsAwsLambdaHyperframes(value: CanonicalValue): boolean {- return awsLambdaHyperframesRejection(value) === undefined;-}--function implementationFailure(code: string, error: unknown): EndpointOutcome {- return {- status: "failed",- failure: {- code,- message: error instanceof Error ? error.message : String(error),- },- };-}--function operationName(operationId: string): string {- return operationId.replace(/[^A-Za-z0-9_-]/gu, "-").slice(0, 64);-}--function executionName(operationId: string): string {- return `hypit-${operationName(operationId)}`;-}--function outputKey(operationId: string): string {- return `renders/hypit/${operationName(operationId)}/visual.mp4`;-}--function alreadyStopped(error: unknown): boolean {- return error !== null && typeof error === "object"- && ["ExecutionDoesNotExist", "SFN.ExecutionDoesNotExist", "ExecutionNotRunning"]- .includes(String((error as { readonly name?: unknown }).name));-}--async function artifactBytes(- context: EndpointStartContext,- artifact: BlobRef,-): Promise<Uint8Array | AsyncIterable<Uint8Array>> {- if (isStreamingResourceStore(context.resources)) {- const chunks = await context.resources.open(artifact.resource);- assert(chunks !== undefined, `HyperFrames Artifact ${artifact.resource} is unavailable`);- return chunks;- }- const bytes = await context.resources.get(artifact.resource);- assert(bytes !== undefined, `HyperFrames Artifact ${artifact.resource} is unavailable`);- assert(bytes.byteLength === artifact.size, `HyperFrames Artifact ${artifact.resource} size differs`);- return bytes;-}--function verifySite(site: HyperframesLambdaSite, bucketName: string): void {- assert(/^[A-Za-z0-9._-]+$/u.test(site.siteId), "HyperFrames site id is invalid");- assert(site.bucketName === bucketName, "HyperFrames site was deployed to another bucket");- const target = parseS3Uri(site.projectS3Uri);- assert(target.bucket === bucketName && target.key === `sites/${site.siteId}/project.tar.gz`,- "HyperFrames site URI does not name its deployed project");- positiveInteger(site.bytes, "HyperFrames site bytes");- assert(Number.isFinite(Date.parse(site.uploadedAt)), "HyperFrames site upload timestamp is invalid");- assert(typeof site.uploaded === "boolean", "HyperFrames site upload state is invalid");-}--function readHandle(value: CanonicalValue | undefined, context: EndpointPollContext): HyperframesHandle {- assert(value !== undefined && value !== null && typeof value === "object" && !Array.isArray(value),- "HyperFrames handle is absent or invalid");- const item = value as unknown as HyperframesHandle;- assert(item.contract === HANDLE_CONTRACT, "HyperFrames handle contract is invalid");- assert(item.operationId === context.operation, "HyperFrames handle Operation differs");- assert(typeof item.executionArn === "string" && item.executionArn.length > 0,- "HyperFrames handle execution ARN is missing");- assert(item.startedAt >= 0 && Number.isSafeInteger(item.startedAt), "HyperFrames handle start time is invalid");- nonNegativeInteger(item.polls, "HyperFrames handle polls");- return structuredClone(item);-}--function boundedChunks(- chunks: AsyncIterable<Uint8Array>,- maximum: number,- expected: number | null,- count: { value: number },-): AsyncIterable<Uint8Array> {- return (async function* () {- for await (const chunk of chunks) {- count.value += chunk.byteLength;- assert(count.value <= maximum, "HyperFrames output exceeded the configured byte limit");- if (expected !== null) assert(count.value <= expected, "HyperFrames output exceeded its reported byte count");- yield chunk;- }- assert(count.value > 0, "HyperFrames output is empty");- if (expected !== null) assert(count.value === expected, "HyperFrames output byte count differs from progress");- })();-}--async function storeOutput(- context: EndpointPollContext,- client: HyperframesAwsLambdaClient,- progress: HyperframesLambdaProgress,- handle: HyperframesHandle,- region: string,- maxRenderedBytes: number,-): Promise<BlobRef> {- const output = progress.outputFile;- assert(output !== null, "HyperFrames succeeded without an output file");- assert(output.s3Uri === handle.outputS3Uri, "HyperFrames completed at an unexpected output URI");- const target = parseS3Uri(output.s3Uri);- assert(target.bucket === handle.bucketName, "HyperFrames output is outside its configured bucket");- if (output.bytes !== null) positiveInteger(output.bytes, "HyperFrames output bytes");- const source = await client.openOutput({ s3Uri: output.s3Uri, region });- if (source.contentLength !== undefined) {- positiveInteger(source.contentLength, "HyperFrames S3 content length");- if (output.bytes !== null) assert(source.contentLength === output.bytes,- "HyperFrames S3 content length differs from progress");- }- const expected = output.bytes ?? source.contentLength ?? null;- if (expected !== null) assert(expected <= maxRenderedBytes,- "HyperFrames output exceeded the configured byte limit");- const count = { value: 0 };- const bounded = boundedChunks(source.chunks, maxRenderedBytes, expected, count);- if (isStreamingResourceStore(context.resources)) {- return await context.resources.putStream(bounded, "video/mp4");- }- const buffers: Uint8Array[] = [];- for await (const chunk of bounded) buffers.push(chunk);- const bytes = new Uint8Array(count.value);- let offset = 0;- for (const chunk of buffers) {- bytes.set(chunk, offset);- offset += chunk.byteLength;- }- return await context.resources.put(bytes, "video/mp4");-}--function fulfillment(- document: HyperframesDocument,- artifact: BlobRef,-): EndpointFulfillment {- const value: RenderedVisual = sealRenderedVisual({- frameRate: document.frameRate,- frameCount: document.frameCount,- canvas: document.canvas,- artifact,- });- return { value: { kind: "inline", value: canonicalize(value) } };-}--function renderConfiguration(document: HyperframesDocument, options: {- readonly quality: HyperframesLambdaQuality;- readonly chunkSize?: number;- readonly maxParallelChunks: number;- readonly targetChunkFrames?: number;-}): HyperframesLambdaRenderConfig {- assert(document.surfaces.length === 0,- "AWS Lambda HyperFrames has no deployed Surface-byte verifier");- assert(document.frameRate.denominator === 1 && SUPPORTED_FPS.has(document.frameRate.numerator),- "AWS Lambda HyperFrames supports only integer 24, 30 or 60 fps documents");- return {- fps: document.frameRate.numerator as 24 | 30 | 60,- width: document.canvas.width,- height: document.canvas.height,- format: "mp4",- codec: "h264",- quality: options.quality,- ...(options.chunkSize === undefined ? {} : { chunkSize: options.chunkSize }),- maxParallelChunks: options.maxParallelChunks,- ...(options.targetChunkFrames === undefined ? {} : { targetChunkFrames: options.targetChunkFrames }),- runtimeCap: "lambda",- rejectOnSystemFonts: true,- failClosedFontFetch: true,- hdrMode: "force-sdr",- cfr: true,- entryFile: "index.html",- strictness: "strict",- };-}--function verifyProgress(progress: HyperframesLambdaProgress, document: HyperframesDocument): void {- assert(["RUNNING", "SUCCEEDED", "FAILED", "TIMED_OUT", "ABORTED", "PENDING_REDRIVE"]- .includes(progress.status), "HyperFrames status is invalid");- assert(Number.isFinite(progress.overallProgress)- && progress.overallProgress >= 0 && progress.overallProgress <= 1,- "HyperFrames overall progress is invalid");- nonNegativeInteger(progress.framesRendered, "HyperFrames rendered frames");- nonNegativeInteger(progress.lambdasInvoked, "HyperFrames Lambda invocation count");- assert(Array.isArray(progress.errors), "HyperFrames errors are invalid");- for (const error of progress.errors) {- assert(typeof error.state === "string" && typeof error.error === "string"- && typeof error.cause === "string", "HyperFrames error entry is invalid");- }- assert(typeof progress.fatalErrorEncountered === "boolean",- "HyperFrames fatal-error marker is invalid");- assert(Number.isFinite(Date.parse(progress.startedAt)), "HyperFrames progress start time is invalid");- assert(progress.endedAt === null || Number.isFinite(Date.parse(progress.endedAt)),- "HyperFrames progress end time is invalid");- if (progress.totalFrames !== null) {- positiveInteger(progress.totalFrames, "HyperFrames planned frames");- assert(progress.totalFrames === document.frameCount,- `HyperFrames planned ${progress.totalFrames} frames for a ${document.frameCount}-frame document`);- assert(progress.framesRendered <= progress.totalFrames,- "HyperFrames rendered frame count exceeds its plan");- }- if (progress.status === "SUCCEEDED") {- assert(progress.fatalErrorEncountered === false,- "HyperFrames succeeded while reporting a fatal error");- assert(progress.overallProgress === 1,- "HyperFrames succeeded without reporting complete progress");- assert(progress.totalFrames === document.frameCount- && progress.framesRendered === document.frameCount,- "HyperFrames succeeded without reporting the complete document frame domain");- assert(progress.outputFile !== null,- "HyperFrames succeeded without reporting an output file");- }-}--export function createAwsLambdaHyperframesProvider(config: CreateAwsLambdaHyperframesProviderOptions) {- const machine = stateMachine(config.stateMachineArn);- const region = machine.region;- const quality = config.quality ?? "standard";- assert(["draft", "standard", "high"].includes(quality), "HyperFrames quality is invalid");- const chunkSize = config.chunkSize === undefined ? undefined : positiveInteger(config.chunkSize, "chunkSize");- const maxParallelChunks = positiveInteger(config.maxParallelChunks ?? 16, "maxParallelChunks");- const targetChunkFrames = config.targetChunkFrames === undefined- ? undefined : positiveInteger(config.targetChunkFrames, "targetChunkFrames");- assert(chunkSize === undefined || targetChunkFrames === undefined,- "HyperFrames chunkSize and targetChunkFrames are mutually exclusive");- const defaultMemorySizeMb = positiveInteger(config.defaultMemorySizeMb ?? 10_240, "defaultMemorySizeMb");- const pollIntervalMs = positiveInteger(config.pollIntervalMs ?? 5_000, "pollIntervalMs");- const maxOperationMs = positiveInteger(config.maxOperationMs ?? 6 * 60 * 60_000, "maxOperationMs");- const maxRenderedBytes = positiveInteger(config.maxRenderedBytes ?? 16 * 1024 * 1024 * 1024,- "maxRenderedBytes");- const client = config.client ?? createHyperframesAwsLambdaClient(region);- const now = config.now ?? Date.now;-- const makeHandle = (- context: EndpointStartContext,- site: HyperframesLambdaSite,- handle: HyperframesLambdaRender,- startedAt: number,- ): HyperframesHandle => {- return {- contract: HANDLE_CONTRACT,- operationId: context.operation,- executionArn: handle.executionArn,- outputS3Uri: handle.outputS3Uri,- bucketName: handle.bucketName,- site,- startedAt,- polls: 0,- };- };-- const submit = async (context: EndpointStartContext): Promise<EndpointOutcome> => {- const startedAt = now();- const document = requestDocument(context.need.constraints);- const renderConfig = renderConfiguration(document, {- quality,- ...(chunkSize === undefined ? {} : { chunkSize }),- maxParallelChunks,- ...(targetChunkFrames === undefined ? {} : { targetChunkFrames }),- });- let site: HyperframesLambdaSite;- const work = await mkdtemp(join(tmpdir(), "hypit-hyperframes-aws-"));- try {- await stageHyperframesProject({- document,- directory: work,- read: (artifact) => artifactBytes(context, artifact),- });- site = await client.deploySite({ projectDir: work, bucketName: config.bucketName, region });- } catch (error) {- return implementationFailure("HYPERFRAMES_SITE_DEPLOY_FAILED", error);- } finally {- await rm(work, { recursive: true, force: true }).catch(() => {});- }- verifySite(site, config.bucketName);- let render: HyperframesLambdaRender;- try {- render = await client.render({- siteHandle: site,- config: renderConfig,- bucketName: config.bucketName,- stateMachineArn: machine.arn,- region,- outputKey: outputKey(context.operation),- executionName: executionName(context.operation),- });- const handle = makeHandle(context, site, render, startedAt);- const receipt = { id: handle.executionArn };- await context.checkpoint?.({ handle: canonicalize(handle), receipt });- return { ...wakeAfter(canonicalize(handle), pollIntervalMs, now(), { phase: "submitted" }), receipt };- } catch (error) {- return implementationFailure("HYPERFRAMES_SUBMISSION_FAILED", error);- }- };-- const safeSubmit = async (- context: EndpointStartContext,- ): Promise<EndpointOutcome> => {- try {- return await submit(context);- } catch (error) {- return implementationFailure("HYPERFRAMES_SUBMISSION_INVALID", error);- }- };-- const endpoint: AsyncEndpoint = {- start: async (context) => await safeSubmit(context),- async poll(context) {- let handle: HyperframesHandle;- try {- handle = readHandle(context.handle, context);- } catch (error) {- throw error;- }- if (now() - handle.startedAt >= maxOperationMs) {- return implementationFailure("HYPERFRAMES_OPERATION_TIMEOUT", new Error("HyperFrames deadline exceeded"));- }- let document: HyperframesDocument;- let progress: HyperframesLambdaProgress;- try {- document = requestDocument(context.need.constraints);- progress = await client.progress({- executionArn: handle.executionArn,- defaultMemorySizeMb,- region,- });- } catch (error) {- return implementationFailure("HYPERFRAMES_POLL_FAILED", error);- }- try {- verifyProgress(progress, document);- } catch (error) {- return implementationFailure("HYPERFRAMES_POLL_FAILED", error);- }- const next = { ...handle, polls: handle.polls + 1 };- if (progress.status === "RUNNING") {- return wakeAfter(canonicalize(next), pollIntervalMs, now(), {- phase: "rendering",- completed: progress.framesRendered,- ...(progress.totalFrames === null ? {} : { total: progress.totalFrames }),- unit: "frames",- });- }- if (progress.status !== "SUCCEEDED") {- const details = progress.errors.map((item) => `${item.state}: ${item.error}: ${item.cause}`).join("; ");- return implementationFailure(`HYPERFRAMES_${progress.status}`,- new Error(details || `HyperFrames execution ended as ${progress.status}`));- }- try {- const artifact = await storeOutput(context, client, progress, next, region, maxRenderedBytes);- return {- status: "completed",- result: fulfillment(document, artifact),- };- } catch (error) {- return implementationFailure("HYPERFRAMES_OUTPUT_INVALID", error);- }- },- async cancel(context) {- const target = readHandle(context.handle, context).executionArn;- try {- await client.stop({- executionArn: target,- region,- reason: `Hypit cancelled Operation ${context.operation}`,- });- } catch (error) {- if (!alreadyStopped(error)) throw error;- }- return { status: "accepted" };- },- };-- return defineEndpointPackage({- module: awsLambdaHyperframesProviderModuleRef,- facet: "render",- instance: config.instance ?? "hyperframes.aws-lambda",- pool: config.pool ?? config.instance ?? "hyperframes.aws-lambda",- pricing: { kind: "page", url: "https://aws.amazon.com/lambda/pricing/" },- defaultConcurrency: config.defaultConcurrency ?? 2,- capabilities: [{- lifecycle: "asynchronous" as const,- capability: renderHyperframesCapabilities.renderVisual,- returns: mediaTypes.renderedVisual,- supports: (need) => {- const reason = awsLambdaHyperframesRejection(need.constraints);- return reason === undefined ? { status: "supported" } : { status: "unsupported", reason };- },- endpoint,- }],- });-}diff --git a/packages/provider-hyperframes-aws-lambda/test/provider.test.ts b/packages/provider-hyperframes-aws-lambda/test/provider.test.tsdeleted file mode 100644index 856ca9d0..00000000--- a/packages/provider-hyperframes-aws-lambda/test/provider.test.ts+++ /dev/null@@ -1,369 +0,0 @@-import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";-import test from "node:test";-import { fixtureResource } from "../../../test/fixture-resource.js";--import { validateDistributedRenderConfig } from "@hyperframes/aws-lambda/sdk";-import { EndpointRegistry, MemoryResourceStore } from "@hypit/driver-node";-import type { EndpointRegistration } from "@hypit/driver-node";-import type { AsyncEndpoint } from "@hypit/endpoint-kit";-import type { HyperframesDocument } from "@hypit/hyperframes";-import { mediaTypes, verifyRenderedVisual } from "@hypit/media";-import type { RenderedVisual } from "@hypit/media";-import {- createAwsLambdaHyperframesProvider,- supportsAwsLambdaHyperframes,-} from "@hypit/provider-hyperframes-aws-lambda";-import type {- HyperframesAwsLambdaClient,- HyperframesLambdaProgress,- HyperframesLambdaRender,- HyperframesLambdaRenderConfig,- HyperframesLambdaSite,-} from "@hypit/provider-hyperframes-aws-lambda";-import { canonicalize } from "@hypit/protocol";-import type { CanonicalValue, Need } from "@hypit/protocol";-import type { RuntimeEndpointAdapterImplementation } from "@hypit/runtime-kit";-import {- hyperframesVisualRequest,- renderHyperframesCapabilities,-} from "@hypit/render-hyperframes";-import type { ResourceStore, StreamingResourceStore } from "@hypit/runtime";--import { hypitPackage as awsLambdaActivation } from "../src/activation.js";--const ACCOUNT = "123456789012";-const REGION = "us-east-1";-const BUCKET = "hypit-render-test";-const STATE_MACHINE = `arn:aws:states:${REGION}:${ACCOUNT}:stateMachine:hypit-hyperframes`;-const EXECUTION_PREFIX = `arn:aws:states:${REGION}:${ACCOUNT}:execution:hypit-hyperframes:`;-function documentFixture(fps = 30, denominator = 1): HyperframesDocument {- return {- visualIr: "hypit.visual-ir@1",- frameRate: { numerator: fps, denominator },- frameCount: 60,- canvas: { width: 720, height: 1280 },- artifacts: [],- surfaces: [],- html: "<!doctype html><html><body><div>SVML</div></body></html>",- };-}--function requestNeed(document = documentFixture()): Need {- const constraints = hyperframesVisualRequest(document);- return {- id: "need:hyperframes-lambda-test",- capability: renderHyperframesCapabilities.renderVisual,- returns: mediaTypes.renderedVisual,- constraints,- result: "record:hyperframes-lambda-test",- };-}--function operation(request: Need) {- return `operation:${request.id}`;-}--function successfulProgress(outputS3Uri: string, overrides: Partial<HyperframesLambdaProgress> = {}) {- return {- status: "SUCCEEDED",- overallProgress: 1,- framesRendered: 60,- totalFrames: 60,- lambdasInvoked: 4,- costs: {- accruedSoFarUsd: 0.0123,- displayCost: "$0.0123",- breakdown: {- lambdaUsd: 0.01,- stepFunctionsUsd: 0.0023,- s3Estimate: "not-included",- estimated: false,- },- },- outputFile: { s3Uri: outputS3Uri, bytes: 5 },- errors: [],- fatalErrorEncountered: false,- startedAt: "2026-08-08T00:00:00.000Z",- endedAt: "2026-08-08T00:00:03.000Z",- ...overrides,- } as HyperframesLambdaProgress;-}--type FakeState = {- deployCalls: number;- renderInputs: Array<{- readonly config: HyperframesLambdaRenderConfig;- readonly executionName: string;- readonly outputKey: string;- }>;- progressCalls: number;- stopped: string[];- opened: string[];-};--function fakeClient(options: {- readonly render?: (input: {- readonly site: HyperframesLambdaSite;- readonly config: HyperframesLambdaRenderConfig;- readonly executionName: string;- readonly outputKey: string;- }) => Promise<HyperframesLambdaRender>;- readonly progress?: (executionArn: string, call: number) => Promise<HyperframesLambdaProgress>;- readonly output?: Uint8Array;-} = {}): { readonly client: HyperframesAwsLambdaClient; readonly state: FakeState } {- const state: FakeState = { deployCalls: 0, renderInputs: [], progressCalls: 0, stopped: [], opened: [] };- const client: HyperframesAwsLambdaClient = {- async deploySite(input) {- state.deployCalls += 1;- const html = await readFile(`${input.projectDir}/index.html`, "utf8");- assert.match(html, /SVML/u);- assert.equal(input.bucketName, BUCKET);- assert.equal(input.region, REGION);- return {- siteId: "site-test-content",- bucketName: BUCKET,- projectS3Uri: `s3://${BUCKET}/sites/site-test-content/project.tar.gz`,- bytes: 123,- uploadedAt: "2026-08-08T00:00:00.000Z",- uploaded: true,- };- },- async render(input) {- state.renderInputs.push({- config: input.config,- executionName: input.executionName,- outputKey: input.outputKey,- });- if (options.render !== undefined) {- return await options.render({- site: input.siteHandle,- config: input.config,- executionName: input.executionName,- outputKey: input.outputKey,- });- }- return {- renderId: input.executionName,- executionArn: `${EXECUTION_PREFIX}${input.executionName}`,- bucketName: input.bucketName,- stateMachineArn: input.stateMachineArn,- outputS3Uri: `s3://${input.bucketName}/${input.outputKey}`,- projectS3Uri: input.siteHandle.projectS3Uri,- startedAt: "2026-08-08T00:00:00.000Z",- };- },- async progress(input) {- state.progressCalls += 1;- if (options.progress !== undefined) return await options.progress(input.executionArn, state.progressCalls);- return successfulProgress(`s3://${BUCKET}/${state.renderInputs.at(-1)!.outputKey}`);- },- async stop(input) {- state.stopped.push(input.executionArn);- assert.equal(input.region, REGION);- assert.match(input.reason, /Hypit cancelled Operation/u);- },- async openOutput(input) {- state.opened.push(input.s3Uri);- const bytes = options.output ?? new Uint8Array([1, 2, 3, 4, 5]);- return {- contentLength: bytes.byteLength,- chunks: (async function* () {- yield bytes.slice(0, 2);- yield bytes.slice(2);- })(),- };- },- };- return { client, state };-}--async function endpointFor(- request: Need,- client: HyperframesAwsLambdaClient,-): Promise<{ readonly endpoint: AsyncEndpoint; readonly registration: EndpointRegistration }> {- const registry = new EndpointRegistry();- const provider = createAwsLambdaHyperframesProvider({- instance: "hyperframes.aws-lambda.test",- stateMachineArn: STATE_MACHINE,- bucketName: BUCKET,- client,- pollIntervalMs: 1,- maxOperationMs: 60_000,- now: () => 1_000,- });- await provider.install(registry);- const resolution = registry.resolve(request);- assert.equal(resolution.status, "resolved");- assert.equal(resolution.registration.kind, "asynchronous");- return { endpoint: resolution.registration.endpoint, registration: resolution.registration };-}--function context(request: Need, resources: ResourceStore) {- return {- command: { kind: "fulfill-need", id: "command:hyperframes-lambda-test", need: request } as const,- need: request,- resources,- credentials: {},- operation: operation(request),- };-}--test("the Lambda Endpoint declines frame domains and requirements it cannot preserve", () => {- assert.equal(supportsAwsLambdaHyperframes(hyperframesVisualRequest(documentFixture(30), {- range: { startFrame: 3, endFrameExclusive: 6 },- })), false, "a range must not silently become a whole-document render");- assert.equal(supportsAwsLambdaHyperframes(hyperframesVisualRequest(documentFixture(24))), true);- assert.equal(supportsAwsLambdaHyperframes(hyperframesVisualRequest(documentFixture(30))), true);- assert.equal(supportsAwsLambdaHyperframes(hyperframesVisualRequest(documentFixture(60))), true);- assert.equal(supportsAwsLambdaHyperframes(hyperframesVisualRequest(documentFixture(12))), false);- assert.equal(supportsAwsLambdaHyperframes(hyperframesVisualRequest(documentFixture(30_000, 1_001))), false);- assert.equal(supportsAwsLambdaHyperframes(canonicalize({- document: documentFixture(),- browserGpu: "hardware",- })), false, "an unsupported hardware requirement must fall through to another Endpoint");- const artifact = {- kind: "blob" as const,- resource: fixtureResource("lambda-surface-without-verifier"),- size: 100,- mediaType: "image/png",- };- const withSurface: HyperframesDocument = {- ...documentFixture(30),- artifacts: [artifact],- surfaces: [{- artifact,- width: 1,- height: 1,- colorSpace: "srgb",- alphaMode: "straight",- timing: { kind: "still" },- }],- html: `<!doctype html><img data-hypit-surface-resource="${artifact.resource}" src="hypit-resource://${artifact.resource}"/>`,- };- assert.equal(supportsAwsLambdaHyperframes(hyperframesVisualRequest(withSurface)), false,- "a deployment without a Surface verifier must fail closed");-});--test("the Runtime adapter refuses a hardware-GPU deployment wish instead of ignoring it", () => {- const facet = awsLambdaActivation.hostFacets[0]!;- const implementation = facet.implementation as RuntimeEndpointAdapterImplementation;- assert.throws(() => implementation.activate({- hostStateRoot: "/host",- dataRoot: "/tmp",- instance: "hyperframes.lambda.test",- pool: "hyperframes.lambda.test",- config: canonicalize({- stateMachineArn: STATE_MACHINE,- bucketName: BUCKET,- browserGpu: "hardware",- }),- }), /does not accept browserGpu/u);-});--test("one submission is polled and streams the output into the ResourceStore", async () => {- const request = requestNeed();- const { client, state } = fakeClient();- const { endpoint, registration } = await endpointFor(request, client);- assert.equal(registration.scheduling?.resources.find((item) =>- item.id.startsWith("pool:"))?.limit, 2);-- const memory = new MemoryResourceStore();- let streamed = 0;- const resources: StreamingResourceStore = {- put: (bytes, mediaType) => memory.put(bytes, mediaType),- write: (resource, bytes) => memory.write(resource, bytes),- get: (resource) => memory.get(resource),- has: (resource) => memory.has(resource),- async putStream(chunks, mediaType) {- const values: number[] = [];- for await (const chunk of chunks) {- streamed += 1;- values.push(...chunk);- }- return await memory.put(Uint8Array.from(values), mediaType);- },- async writeStream(resource, chunks) {- const values: number[] = [];- for await (const chunk of chunks) values.push(...chunk);- await memory.write(resource, Uint8Array.from(values));- },- async open(resource) {- const bytes = await memory.get(resource);- if (bytes === undefined) return undefined;- return (async function* () { yield bytes; })();- },- };- const common = context(request, resources);- const started = await endpoint.start(common);- assert.equal(started.status, "pending");- if (started.status !== "pending") return;- assert.equal(state.deployCalls, 1);- assert.equal(state.renderInputs.length, 1);- assert.equal(state.renderInputs[0]!.config.fps, 30);- assert.equal(state.renderInputs[0]!.config.runtimeCap, "lambda");- assert.equal(state.renderInputs[0]!.config.maxParallelChunks, 16);- assert.doesNotThrow(() => validateDistributedRenderConfig(state.renderInputs[0]!.config),- "the locked SDK must accept the exact configuration sent by the Endpoint");- assert.equal(state.renderInputs[0]!.executionName,- `hypit-${common.operation.replace(/[^A-Za-z0-9_-]/gu, "-")}`);-- const completed = await endpoint.poll({- ...common,- handle: started.handle!,- });- assert.equal(completed.status, "completed", JSON.stringify(completed));- assert.equal(streamed, 2, "the remote object should use the streaming ResourceStore facet");- assert.equal(state.opened.length, 1);- if (completed.status !== "completed" || completed.result.value.kind !== "inline") return;- verifyRenderedVisual(completed.result.value.value);- const visual = completed.result.value.value as unknown as RenderedVisual;- assert.equal(visual.frameCount, 60);- assert.equal(await resources.has(visual.artifact.resource), true);- assert.deepEqual(await resources.get(visual.artifact.resource), new Uint8Array([1, 2, 3, 4, 5]));-});--test("running render progress is projected without exposing the private handle", async () => {- const request = requestNeed();- const { client } = fakeClient({- async progress() {- return successfulProgress("s3://unused/while-running", {- status: "RUNNING",- overallProgress: 0.4,- framesRendered: 24,- totalFrames: 60,- outputFile: null,- endedAt: null,- });- },- });- const { endpoint } = await endpointFor(request, client);- const common = context(request, new MemoryResourceStore());- const started = await endpoint.start(common);- if (started.status !== "pending") return;- const running = await endpoint.poll({- ...common,- handle: started.handle!,- });- assert.equal(running.status, "pending");- if (running.status === "pending") {- assert.deepEqual(running.progress,- { phase: "rendering", completed: 24, total: 60, unit: "frames" });- }-});--test("cancellation stops the submitted execution", async () => {- const request = requestNeed();- const { client, state } = fakeClient();- const { endpoint } = await endpointFor(request, client);- assert.ok(endpoint.cancel);- const common = context(request, new MemoryResourceStore());- const started = await endpoint.start(common);- assert.equal(started.status, "pending");- if (started.status !== "pending") return;- await endpoint.cancel({- ...common,- handle: started.handle!,- });- assert.equal(state.stopped.length, 1);-});diff --git a/packages/provider-hyperframes-local/README.md b/packages/provider-hyperframes-local/README.mdindex 487c18a8..595b742f 100644--- a/packages/provider-hyperframes-local/README.md+++ b/packages/provider-hyperframes-local/README.md@@ -9,24 +9,32 @@ content identity or hidden output metadata.Normalized transparent videos displayed by Media or project components use the ordinary video path.The engine decodes them to PNG frames with alpha, then Chrome blends them with lower layers and-the authored Canvas background. PNG is the intermediate capture format; it does not ask to erase-the Film's background. The returned MP4 contains the completed composition.+the authored Canvas background. Final frames use fast PNG encoding after Chrome has composited+the image onto an opaque canvas (black beneath the authored background). This trades intermediate+compression effort for speed without JPEG frame compression. Source alpha, CSS filters, canvas and+WebGL remain part of the browser composition. The returned MP4 contains the completed composition.Runtime configuration separates work size from shared capacity:- `defaultConcurrency` limits whole render requests admitted by the Endpoint's Runtime capacity resource.- Optional `browserCapacity` limits Chrome slots shared by all render Needs in the same `pool`.- Each Need reserves its actual worker count atomically with the whole-request slot. A request larger- than this budget reports a configuration error; it does not silently reduce the requested workers.+ Each Need reserves its fixed count or automatic ceiling atomically with the whole-request slot.+ An explicit count larger than this budget reports a configuration error. Auto fits its ceiling+ to the shared budget before admission.Both reservations last for the whole Need, including preparation and final encoding. Closing oneChrome early does not release part of that reservation. Without `browserCapacity`, admission usesthe whole-request limit alone.- `workers` controls independent Chrome processes inside one admitted render. Explicit counts are- honored, capped only by selected frame count. `auto` uses half the available CPU parallelism,- bounded to 1–4 workers.+ honored, capped only by selected frame count. `auto` starts below its ceiling, then compares useful+ capture batches before adding another browser. Insufficient benefit or falling throughput retires+ surplus browsers between batches. Completed frames are retained; there is no calibration render.+- Optional `maxWorkers` sets the automatic ceiling. Without it, the Provider leaves two CPU slots+ and half the machine/container memory for other work, budgeting about 1.5 GiB per Chrome process.+ Auto also caps the reservation to the number of roughly one-second batches in the selected range.The Runtime Profile configures these controls through the Provider because they are deployment policy.-`auto` is resolved when the Provider is activated, so admission and execution use the same count. It never+The automatic ceiling is fixed at activation, and range sizing is identical in admission and execution.+Actual concurrency adapts inside that reservation; it is not a machine-wide history or performance database. It neverrenders program audio; `@hypit/provider-media-local` separately prepares `TimelineAudio` and muxesthe final media.@@ -48,11 +56,16 @@ For a Runtime Profile, place `pool` on the Endpoint entry and these Provider setThis configuration admits one 4-worker request at a time under its 6-browser budget even thoughthe whole-request limit is 2. Two 4-worker requests would need 8 browser slots. Choose budgets fromthe actual machine and shared workloads; the example is not an automatic tuning recommendation.-Reload the Runtime Worker after changing its Profile and restart Studio if it uses that Profile.+New Builds use the edited Provider configuration; active Builds retain their selected configuration.+Restart Studio if its existing session needs to load the edited Profile.`browserGpu` picks Chrome's rasterizer and defaults to `hardware`. Set `software` without a usableGPU, or `auto` to let the engine decide. Capture uses screenshots and independent browser processes;-the CLI's automatic worker and drawElement policies do not override the count.+the CLI's automatic worker and drawElement policies do not override the count. The opaque screenshot+adapter uses the engine's public session, video injector and page seek protocol plus Chrome CDP.+It waits for seek completion, dynamic images/fonts and the page compositor before capturing PNGs.+The pinned engine couples its PNG session setup to transparent export, so this adapter initializes+an opaque session and chooses PNG separately at capture. It does not patch engine methods or files.The Runtime Adapter also declares one managed browser program. `programs up` invokes the pinnedHyperFrames CLI's `browser ensure`; its probe resolves and starts that browser and checks@@ -71,8 +84,12 @@ const visual = await renderHyperframesVisual(Omit `range` for the complete document. Ranges are zero-based and half-open on the originalprogramme clock. At 30 fps, `[240, 360)` returns 120 frames covering seconds 8–12.-`onProgress` reports preparation, worker ranges, browser PIDs, completion and elapsed time to direct-executor callers. The Runtime Provider does not currently forward these events as Build progress.+`onProgress` reports resource staging, source decoding, the requested range, per-worker frame counts, browser PIDs,+encoding, storage and elapsed time to direct executor callers. The Provider reduces parallel worker+events to a single phase and aggregate count through `context.reportProgress`. CLI status and follow+display that activity without `--verbose`. Counter writes are coalesced to about once per second;+phase changes and completed counts are reported promptly. Local activity belongs to the running+Command, not a remote Operation or a repeatedly rewritten Result manifest.`processTimeoutMs` defaults to 30 minutes and starts one deadline before resource preparation. Itcovers resource reads, Surface validation, rendering and output storage. `signal` can end the sameexecution earlier. ResourceStore I/O and Surface probes receive the cancellation signal; a custom@@ -95,10 +112,13 @@ cleanup. A completed worker closes its Chrome immediately.One call stages the HTML and every declared asset once. Typed Surface validation includes a completedecoded-frame count, even for a short render interval. The renderer then finds source-frame windowsneeded by that interval, merges overlapping windows, and extracts them one source/window at a time.-Decoded PNGs are shared by all workers in this call. Each worker initializes its own page and captures-its assigned frames at their original absolute times. Output numbering starts at zero; final H.264-encoding runs once after all workers finish. More workers parallelize capture, while staging,-validation, source extraction and final encoding still contribute their own cost.+Decoded PNGs are shared by all workers in this call. Each worker initializes its own page, then takes+short contiguous frame batches from the render's in-memory queue. A free worker can continue with+another batch instead of waiting for a worker assigned a more expensive passage. Batches span at+most about one second and preserve the original absolute frame times. Output numbering starts at+zero; final H.264 encoding runs once after all workers finish. This division is internal to one+render call; it does not create or resume Builds. Extra workers help only while aggregate throughput+improves. Staging, validation, source extraction and final encoding still contribute their own cost.Each call has its own temporary directory, local server port and Chrome processes. Separate rendersdo not share staged files or decoded PNGs. Exact compiler sampling markers retain loops, holds and@@ -127,3 +147,11 @@ Direct `renderHyperframesVisual()` calls do not enter Runtime's shared admissionThe current package executes trusted official code in a local process. It is not a sandbox foruntrusted documents or community renderer implementations.++Provider calls forward renderer diagnostics through `context.reportDiagnostic`. The initial record+states the frame count, worker policy/ceiling, capture path, quality, GPU mode and selected encoder.+Phase timings, concurrency changes and per-worker seek/preparation/PNG totals are recorded once+per phase, decision or finished worker. Disposable capture-process+stdout/stderr are streamed as diagnostics and drained before the call returns; existing output limits+still apply. Phase changes cover preparation, decoding, browser startup, capture, encoding and storage.+`hypit logs <build-id>` retains those records after temporary rendering files have been removed.diff --git a/packages/provider-hyperframes-local/src/activation.ts b/packages/provider-hyperframes-local/src/activation.tsindex 5d26369c..f60e066d 100644--- a/packages/provider-hyperframes-local/src/activation.ts+++ b/packages/provider-hyperframes-local/src/activation.ts@@ -21,7 +21,7 @@ const localHyperframesRuntimeAdapter = createRuntimeEndpointAdapterFacet({if (context.pool === undefined) throw new Error("local HyperFrames Provider Pool is required");const config = runtimeConfigObject(context.config, "local HyperFrames");runtimeConfigExact(config, [- "nodePath", "hyperframesCliPath", "ffprobePath", "ffmpegPath", "workers", "quality", "browserGpu",+ "nodePath", "hyperframesCliPath", "ffprobePath", "ffmpegPath", "workers", "maxWorkers", "quality", "browserGpu","defaultConcurrency", "browserCapacity", "initializationTimeoutMs", "frameTimeoutMs", "processTimeoutMs", "maxProcessOutputBytes", "maxRenderedBytes",], "local HyperFrames");runtimeConfigString(config.nodePath, "HyperFrames nodePath");@@ -43,11 +43,12 @@ const localHyperframesRuntimeAdapter = createRuntimeEndpointAdapterFacet({const configuredCli = runtimeConfigString(config.hyperframesCliPath, "HyperFrames hyperframesCliPath");const configuredFfprobe = runtimeConfigString(config.ffprobePath, "HyperFrames ffprobePath");const nodePath = resolveRuntimeExecutable(context.dataRoot, configuredNode ?? process.execPath);- const hyperframesCliPath = resolveRuntimeExecutable(context.dataRoot, configuredCli ?? defaultHyperframesCliPath());+ const hyperframesCliPath = () => resolveRuntimeExecutable(context.dataRoot, configuredCli ?? defaultHyperframesCliPath());const configuredFfmpeg = runtimeConfigString(config.ffmpegPath, "HyperFrames ffmpegPath");const ffmpegPath = resolveRuntimeExecutable(context.dataRoot, configuredFfmpeg ?? "ffmpeg");const ffprobePath = resolveRuntimeExecutable(context.dataRoot, configuredFfprobe ?? "ffprobe");const defaultConcurrency = runtimeConfigPositiveInteger(config.defaultConcurrency, "HyperFrames defaultConcurrency");+ const maxWorkers = runtimeConfigPositiveInteger(config.maxWorkers, "HyperFrames maxWorkers");const browserCapacity = runtimeConfigPositiveInteger(config.browserCapacity, "HyperFrames browserCapacity");const initializationTimeoutMs = runtimeConfigPositiveInteger(config.initializationTimeoutMs, "HyperFrames initializationTimeoutMs");const frameTimeoutMs = runtimeConfigPositiveInteger(config.frameTimeoutMs, "HyperFrames frameTimeoutMs");@@ -59,10 +60,10 @@ const localHyperframesRuntimeAdapter = createRuntimeEndpointAdapterFacet({instance: context.instance,pool: context.pool,nodePath,- hyperframesCliPath,ffprobePath,ffmpegPath,...(workers === undefined ? {} : { workers: workers as HyperframesWorkers }),+ ...(maxWorkers === undefined ? {} : { maxWorkers }),...(quality === undefined ? {} : { quality: quality as HyperframesQuality }),...(browserGpu === undefined ? {} : { browserGpu: browserGpu as HyperframesBrowserGpu }),...(defaultConcurrency === undefined ? {} : { defaultConcurrency }),diff --git a/packages/provider-hyperframes-local/src/capture-process.ts b/packages/provider-hyperframes-local/src/capture-process.tsindex b771454a..7313ecb1 100644--- a/packages/provider-hyperframes-local/src/capture-process.ts+++ b/packages/provider-hyperframes-local/src/capture-process.ts@@ -1,3 +1,4 @@+import type { ExecutionDiagnostic } from "@hypit/runtime";import { execFile, spawn } from "node:child_process";import { promisify } from "node:util";import { fileURLToPath } from "node:url";@@ -47,6 +48,7 @@ export async function runCaptureProcess(signal: AbortSignal,onProgress: (event: HyperframesRenderProgress) => void,entry = new URL("./capture-worker.ts", import.meta.url),+ onDiagnostic?: (diagnostic: ExecutionDiagnostic) => Promise<void>,): Promise<void> {signal.throwIfAborted();await new Promise<void>((resolve, reject) => {@@ -58,6 +60,7 @@ export async function runCaptureProcess(let completed = false;let outputBytes = 0;let stderr = "";+ let diagnostics = Promise.resolve();let grace: ReturnType<typeof setTimeout> | undefined;let killing: Promise<void> | undefined;const kill = () => {@@ -80,8 +83,16 @@ export async function runCaptureProcess(if (error) stderr = `${stderr}${chunk.toString()}`.slice(-32_000);if (outputBytes > input.config.maxProcessOutputBytes) stop(new Error("HyperFrames process output exceeded the configured limit"));};- child.stdout?.on("data", (chunk: Buffer) => log(chunk, false));- child.stderr?.on("data", (chunk: Buffer) => log(chunk, true));+ for (const [stream, pipe] of [["stdout", child.stdout], ["stderr", child.stderr]] as const) {+ pipe?.setEncoding("utf8");+ pipe?.on("data", (text: string) => {+ log(Buffer.from(text), stream === "stderr");+ if (onDiagnostic !== undefined && text.trim()) {+ diagnostics = diagnostics.then(() => onDiagnostic({ stream, level: "info", message: text.trimEnd() }))+ .catch((error) => stop(error instanceof Error ? error : new Error(String(error))));+ }+ });+ }child.on("message", (value: { type: string; event?: HyperframesRenderProgress; error?: string }) => {if (value.type === "progress" && value.event !== undefined) {try { onProgress(value.event); } catch (error) { stop(error instanceof Error ? error : new Error(String(error))); }@@ -98,7 +109,8 @@ export async function runCaptureProcess(child.on("close", () => {if (grace !== undefined) clearTimeout(grace);signal.removeEventListener("abort", abort);- void (killing ?? Promise.resolve()).then(() => {+ void (killing ?? Promise.resolve()).then(async () => {+ await diagnostics;if (failure !== undefined) reject(failure);else if (!completed) reject(new Error(`HyperFrames process exited before completion: ${stderr}`));else resolve();diff --git a/packages/provider-hyperframes-local/src/capture.ts b/packages/provider-hyperframes-local/src/capture.tsindex 6b5ba25c..95ccc353 100644--- a/packages/provider-hyperframes-local/src/capture.ts+++ b/packages/provider-hyperframes-local/src/capture.ts@@ -6,6 +6,9 @@ import type { HyperframesRenderProgress, resolveExecutionOptions } from "./rendeimport { assert, runProcess } from "./process.js";import { verifyOutput } from "./output.js";import { distributeFrameRange, sourceFrameAt, sourceWindows, videoSlots } from "./sampling.js";+import { renderWorkerLimit } from "./render.js";+import { CaptureConcurrency } from "./concurrency.js";+import { createOpaqueFrameCapture } from "./opaque-capture.js";export type CaptureInput = {readonly document: HyperframesDocument;@@ -22,8 +25,14 @@ export async function captureStagedVisual(input: CaptureInput, controller: Abortconst { document, range, config, directory: work } = input;const signal = controller.signal;const frameCount = range.endFrameExclusive - range.startFrame;- const tasks = distributeFrameRange(range, config.workers);const fps = { num: document.frameRate.numerator, den: document.frameRate.denominator };+ const limit = renderWorkerLimit(config, frameCount, fps.num / fps.den);+ const concurrency = new CaptureConcurrency(limit, config.workers === "auto");+ // Short contiguous batches retain sequential capture while allowing free browsers+ // to help with expensive passages. This queue exists only inside this render.+ const batchCount = Math.max(limit, Math.ceil(frameCount / Math.max(1, Math.round(fps.num / fps.den))));+ const batches = distributeFrameRange(range, batchCount);+ let nextBatch = 0;const started = performance.now();const elapsedMs = () => Math.round(performance.now() - started);const engine = await import(input.engineModule) as typeof import("@hyperframes/engine");@@ -65,7 +74,11 @@ export async function captureStagedVisual(input: CaptureInput, controller: Abortconst sources = new Map<string, { frames: Map<number, string>; width: number; height: number }>();let sourceFrames = 0;// One source at a time bounds decoder pressure independently of browser concurrency.- for (const source of sourceWindows(slots, range)) {+ const windows = sourceWindows(slots, range);+ const sourceTotal = windows.reduce((sum, source) => sum + source.windows.reduce((count, window) =>+ count + window.endFrameExclusive - window.startFrame, 0), 0);+ if (sourceTotal > 0) onProgress({ phase: "decoding", completed: 0, total: sourceTotal, elapsedMs: elapsedMs() });+ for (const source of windows) {const path = resolve(work, source.src);assert(path.startsWith(`${work}${sep}`), "HyperFrames source is outside the staged project");const frames = new Map<number, string>();@@ -86,6 +99,7 @@ export async function captureStagedVisual(input: CaptureInput, controller: Abortwidth = extracted.metadata.width;height = extracted.metadata.height;sourceFrames += count;+ onProgress({ phase: "decoding", completed: sourceFrames, total: sourceTotal, elapsedMs: elapsedMs() });}sources.set(source.src, { frames, width, height });}@@ -109,9 +123,24 @@ export async function captureStagedVisual(input: CaptureInput, controller: Abortconst serverUrl = server.url;const outputFrames = join(work, "frames");await mkdir(outputFrames);- onProgress?.({ phase: "prepared", workers: tasks.length, sourceFrames, elapsedMs: elapsedMs() });- const results = await Promise.allSettled(tasks.map(async (task, worker) => {+ onProgress?.({ phase: "prepared", workers: concurrency.target, sourceFrames, elapsedMs: elapsedMs() });+ const jobs: Promise<void>[] = [];+ let active = 0, open = 0, initializing = 0, capturedFrames = 0;+ let startupMs = 0;+ const launch = (): void => {+ const worker = jobs.length;+ jobs.push(runWorker(worker));+ // Failure stops all jobs promptly; all jobs are still awaited below.+ void jobs[worker]!.catch(() => {});+ };+ const runWorker = async (worker: number): Promise<void> => {let session: Session | undefined;+ let ready = false;+ active++;+ open++;+ initializing++;+ const launched = performance.now();+ let setupMs = 0;try {signal.throwIfAborted();const directory = join(work, `worker-${worker}`);@@ -120,7 +149,9 @@ export async function captureStagedVisual(input: CaptureInput, controller: AbortframeSrcResolver: (path) => new URL(relative(work, path).split(sep).map(encodeURIComponent).join("/"), `${serverUrl}/`).href,});session = await engine.createCaptureSession(serverUrl, directory, {- ...document.canvas, fps, format: "png",+ // Engine initialization couples PNG to transparent-export mode. Use+ // its opaque session setup; our capture adapter writes lossless PNG.+ ...document.canvas, fps, format: "jpeg",compositionDurationSeconds: document.frameCount * fps.den / fps.num,skipReadinessVideoIds: slots.map((slot) => slot.id),videoMetadataHints: slots.flatMap((slot) => {@@ -132,38 +163,77 @@ export async function captureStagedVisual(input: CaptureInput, controller: Abortsignal.throwIfAborted();const activeSession = session;const browserPid = session.browser.process()?.pid;- onProgress?.({ phase: "worker-initializing", worker, range: task, browserPid, elapsedMs: elapsedMs() });+ onProgress?.({ phase: "worker-initializing", worker, range, browserPid, elapsedMs: elapsedMs() });await stage(`worker ${worker} initialization`, config.initializationTimeoutMs, () => engine.initializeSession(activeSession));- // HyperFrames' PNG capture clears the page/composition backgrounds for- // standalone transparent exports. Here PNGs are intermediate frames of- // a Film, whose authored Canvas background still belongs in the image.- await activeSession.page.evaluate(() => {- globalThis.document.getElementById("__hf_transparent_bg__")?.remove();- });- onProgress?.({ phase: "worker-start", worker, range: task, browserPid, elapsedMs: elapsedMs() });- for (let frame = task.startFrame; frame < task.endFrameExclusive; frame++) {- signal.throwIfAborted();- const captured = await stage(`worker ${worker} frame ${frame}`, config.frameTimeoutMs, async () => {- const capture = await engine.captureFrameToBuffer(activeSession, frame, frame * fps.den / fps.num);- const programError = await activeSession.page.evaluate(() =>- (window as unknown as { __hypitBrowserProgramError?: string }).__hypitBrowserProgramError);- if (programError !== undefined) throw new Error(`Browser program failed at frame ${frame}: ${programError}`);- return capture;- });- await writeFile(join(outputFrames, `${String(frame - range.startFrame).padStart(9, "0")}.png`), captured.buffer);+ const captureFrame = await createOpaqueFrameCapture(activeSession);+ setupMs = performance.now() - launched;+ startupMs = Math.max(startupMs, setupMs);+ ready = true;+ initializing--;+ if (initializing === 0) concurrency.settled(performance.now());+ onProgress?.({ phase: "worker-start", worker, range, browserPid, elapsedMs: elapsedMs() });+ let completed = 0;+ let lastProgressAt = performance.now();+ const timing = { seekMs: 0, prepareMs: 0, screenshotMs: 0 };+ while (true) {+ // Retire only between complete batches, before claiming more work.+ if (active > concurrency.target) break;+ const batch = batches[nextBatch++];+ if (batch === undefined) break;+ for (let frame = batch.startFrame; frame < batch.endFrameExclusive; frame++) {+ signal.throwIfAborted();+ const captured = await stage(`worker ${worker} frame ${frame}`, config.frameTimeoutMs, () => captureFrame(frame));+ timing.seekMs += captured.seekMs;+ timing.prepareMs += captured.prepareMs;+ timing.screenshotMs += captured.screenshotMs;+ await writeFile(join(outputFrames, `${String(frame - range.startFrame).padStart(9, "0")}.png`), captured.buffer);+ completed++;+ capturedFrames++;+ if (performance.now() - lastProgressAt >= 1_000) {+ onProgress({ phase: "worker-progress", worker, completed, elapsedMs: elapsedMs() });+ lastProgressAt = performance.now();+ }+ }+ const decision = concurrency.complete({ now: performance.now(), frames: batch.endFrameExclusive - batch.startFrame,+ remainingFrames: frameCount - capturedFrames, startupMs, active: initializing === 0 ? active : 0 });+ if (decision !== undefined) {+ console.log(`Capture auto: ${active} -> ${decision.workers} browsers; ${decision.fps.toFixed(1)} frames/s; ${decision.reason}`);+ while (active < decision.workers && open < limit && nextBatch < batches.length) launch();+ }}- onProgress?.({ phase: "worker-complete", worker, range: task, browserPid, elapsedMs: elapsedMs() });+ console.log(`Capture worker ${worker}: ${completed} frames; startup ${Math.round(setupMs)} ms; `+ + `seek ${Math.round(timing.seekMs)} ms; prepare ${Math.round(timing.prepareMs)} ms; PNG ${Math.round(timing.screenshotMs)} ms`);+ onProgress({ phase: "worker-complete", worker, completed, browserPid, elapsedMs: elapsedMs() });} catch (error) {controller.abort(error);throw error;} finally {+ active--;+ if (!ready) initializing--;if (session !== undefined) await close(session);+ open--;+ // A restoring decision can wait for a retiring Chrome to release its+ // slot. Closing processes still count against the reserved ceiling.+ if (!signal.aborted && active < concurrency.target && open < limit && nextBatch < batches.length) launch();}- }));+ };+ const initialWorkers = concurrency.target;+ console.log(`Capture: opaque fast PNG; ${config.workers === "auto" ? "auto" : "fixed"} workers ${initialWorkers}, limit ${limit}`);+ for (let i = 0; i < initialWorkers; i++) launch();+ // New workers can join while earlier jobs run; collect every launched job.+ let awaited = 0;+ let failure: unknown;+ while (awaited < jobs.length) {+ const pending = jobs.slice(awaited);+ awaited = jobs.length;+ const results = await Promise.allSettled(pending);+ for (const result of results) if (result.status === "rejected") failure ??= result.reason;+ }+ if (failure !== undefined) throw failure;signal.throwIfAborted();- for (const result of results) if (result.status === "rejected") throw result.reason;await Promise.all(closing.values());const output = join(work, "visual.mp4");+ onProgress({ phase: "encoding", elapsedMs: elapsedMs() });const crf = { draft: 28, standard: 23, high: 18 }[config.quality];await runProcess({ executable: config.ffmpegPath,argv: ["-v", "error", "-y", "-framerate", `${fps.num}/${fps.den}`, "-i", join(outputFrames, "%09d.png"),diff --git a/packages/provider-hyperframes-local/src/concurrency.ts b/packages/provider-hyperframes-local/src/concurrency.tsnew file mode 100644index 00000000..39303e41--- /dev/null+++ b/packages/provider-hyperframes-local/src/concurrency.ts@@ -0,0 +1,86 @@+import { availableParallelism, totalmem } from "node:os";++function hostMemory(): number {+ const constrained = process.constrainedMemory?.() ?? 0;+ return constrained > 0 ? Math.min(totalmem(), constrained) : totalmem();+}++/** Stable reservation ceiling. Actual load tuning happens inside the admitted render. */+export function autoWorkerLimit(cpu = availableParallelism(), memory = hostMemory()): number {+ // Chrome owns raster surfaces, decoded media and the JS heap in separate+ // processes. Leave half the memory and two CPU slots to the host/other stages.+ const byMemory = Math.floor(memory / 2 / (1.5 * 1024 ** 3));+ return Math.max(1, Math.min(Math.max(1, cpu - 2), byMemory));+}++/**+ * Online throughput comparison of useful capture batches. All samples and+ * decisions die with this attempt. A change never invalidates captured frames.+ */+export class CaptureConcurrency {+ target: number;+ private since: number | undefined;+ private frames = 0;+ private batches = 0;+ private baseline: { workers: number; rate: number } | undefined;+ private previousRate: number | undefined;+ private growth = true;++ constructor(readonly limit: number, readonly automatic: boolean) {+ this.target = automatic ? Math.max(1, Math.ceil(limit / 2)) : limit;+ }++ settled(now: number): void {+ this.since = now;+ this.frames = 0;+ this.batches = 0;+ }++ complete(input: { now: number; frames: number; remainingFrames: number; startupMs: number; active: number }):+ { workers: number; reason: string; fps: number } | undefined {+ if (!this.automatic) return;+ if (input.active !== this.target) { this.since = undefined; return; }+ if (this.since === undefined) { this.settled(input.now); return; }+ this.frames += input.frames;+ this.batches++;+ const elapsed = input.now - this.since;+ // At least two batches per worker and a browser startup's worth of useful+ // work amortize short fluctuations. No synthetic calibration is rendered.+ if (this.batches < this.target * 2 || elapsed < Math.max(1_000, input.startupMs)) return;+ const rate = this.frames * 1_000 / elapsed;+ let next = this.target;+ let reason = "";+ if (this.baseline !== undefined) {+ const before = this.baseline;+ this.baseline = undefined;+ const added = this.target > before.workers;+ if (rate < before.rate * (added ? 1.05 : 0.95)) {+ next = before.workers;+ reason = added ? "extra browser did not improve throughput" : "fewer browsers reduced throughput";+ this.growth = false;+ }+ } else if (this.previousRate !== undefined && rate < this.previousRate * 0.7 && this.target > 1+ && input.remainingFrames > this.frames * 2) {+ // A slower passage is not proof of contention. Compare fewer browsers+ // on subsequent useful work and restore the old count if it is worse.+ this.baseline = { workers: this.target, rate };+ next--;+ reason = "compare fewer browsers after throughput changed";+ this.growth = false;+ }+ if (next === this.target && this.growth && next < this.limit+ && input.remainingFrames / rate * 1_000 > input.startupMs * (next + 1) * 2) {+ // A new browser must have enough remaining work to repay its startup,+ // even if its ideal contribution is only 1/(N+1) of current throughput.+ this.baseline = { workers: this.target, rate };+ next++;+ reason = "remaining capture can amortize another browser";+ }+ this.previousRate = rate;+ this.settled(input.now);+ if (next === this.target) return;+ this.target = next;+ this.since = undefined;+ return { workers: next, reason, fps: rate };+ }+}diff --git a/packages/provider-hyperframes-local/src/opaque-capture.ts b/packages/provider-hyperframes-local/src/opaque-capture.tsnew file mode 100644index 00000000..f8e9dfb0--- /dev/null+++ b/packages/provider-hyperframes-local/src/opaque-capture.ts@@ -0,0 +1,92 @@+import type { CaptureSession, HfProtocol } from "@hyperframes/engine";+import { getCdpSession } from "@hyperframes/engine";++/** The optional completion hooks supplied by the pinned Hyperframes page runtime. */+type RenderWindow = Window & {+ __hf: HfProtocol & { colorGrading?: { waitForActiveLuts?: () => Promise<void> } };+ __hfWaitForSeekCompletion?: () => Promise<void>;+ __hf_page_composite_pending?: boolean;+ __hf_page_composite_prepare?: () => Promise<void>;+ __hf_page_composite_resolve?: () => void;+ __hypitBrowserProgramError?: string;+};++/**+ * A screenshot adapter for this Provider's opaque MP4 output. Session lifecycle,+ * the page's seek protocol and the video injector remain engine-owned. Encoding+ * the already-composited frame as a fast PNG does not change source alpha.+ * No engine/session methods are replaced and no installed dependency is patched.+ */+export async function createOpaqueFrameCapture(session: CaptureSession) {+ const { page, options } = session;+ const cdp = await getCdpSession(page);+ // MP4 has no alpha channel. The authored Canvas paints over this final matte.+ await cdp.send("Emulation.setDefaultBackgroundColorOverride", { color: { r: 0, g: 0, b: 0, a: 1 } });+ // These decoded image handles belong to this page, just like its DOM. Retain+ // only URLs used by inline background images; changing a style can need a load+ // even after initializeSession has finished its initial resource readiness.+ await page.evaluate(() => {+ const decoded = new Map<string, Promise<void>>();+ (window as unknown as { __hypitPrepareImages: () => Promise<void> }).__hypitPrepareImages = async () => {+ const pending: Promise<unknown>[] = [];+ if (document.fonts.status === "loading") pending.push(document.fonts.ready);+ for (const image of Array.from(document.images)) {+ if (!image.complete) pending.push(image.decode());+ }+ for (const element of Array.from(document.querySelectorAll<HTMLElement>('[style*="background"]'))) {+ const background = element.style.backgroundImage;+ for (const match of background.matchAll(/url\(\s*(?:"((?:\\.|[^"])*)"|'((?:\\.|[^'])*)'|([^)]*))\s*\)/gu)) {+ const url = (match[1] ?? match[2] ?? match[3] ?? "").trim();+ if (!url) continue;+ let ready = decoded.get(url);+ if (ready === undefined) {+ const image = new Image();+ image.src = url;+ ready = image.decode();+ decoded.set(url, ready);+ }+ pending.push(ready);+ }+ }+ await Promise.all(pending);+ };+ });+ return async (frame: number) => {+ const time = frame * options.fps.den / options.fps.num;+ const start = performance.now();+ await page.evaluate(async t => {+ const w = window as unknown as RenderWindow;+ await w.__hf.seek(t);+ }, time);+ const sought = performance.now();+ await session.onBeforeCapture?.(page, time);+ const composite = await page.evaluate(async () => {+ const w = window as unknown as RenderWindow & { __hypitPrepareImages: () => Promise<void> };+ await w.__hfWaitForSeekCompletion?.();+ await w.__hf.colorGrading?.waitForActiveLuts?.();+ await w.__hypitPrepareImages();+ if (w.__hypitBrowserProgramError !== undefined) throw new Error(w.__hypitBrowserProgramError);+ if (w.__hf_page_composite_pending) {+ await w.__hf_page_composite_prepare?.();+ return true;+ }+ return false;+ });+ if (composite) {+ // The runtime's shader compositor needs a paint between preparing its DOM+ // layers and resolving them. A 1 px capture flushes Chrome's compositor.+ await cdp.send("Page.captureScreenshot", {+ format: "jpeg", quality: 1, clip: { x: 0, y: 0, width: 1, height: 1, scale: 1 },+ });+ await page.evaluate(() => (window as unknown as RenderWindow).__hf_page_composite_resolve?.());+ }+ const prepared = performance.now();+ const result = await cdp.send("Page.captureScreenshot", {+ format: "png", optimizeForSpeed: true, fromSurface: true,+ captureBeyondViewport: options.captureBeyondViewport ?? false,+ clip: { x: 0, y: 0, width: options.width, height: options.height, scale: options.deviceScaleFactor ?? 1 },+ });+ return { buffer: Buffer.from(result.data, "base64"),+ seekMs: sought - start, prepareMs: prepared - sought, screenshotMs: performance.now() - prepared };+ };+}diff --git a/packages/provider-hyperframes-local/src/options.ts b/packages/provider-hyperframes-local/src/options.tsindex c182a7c3..ef535cf9 100644--- a/packages/provider-hyperframes-local/src/options.ts+++ b/packages/provider-hyperframes-local/src/options.ts@@ -8,6 +8,8 @@ export type HyperframesExecutionOptions = {readonly ffmpegPath?: string;/** Parallel Chrome workers inside one render. This is separate from Provider request concurrency. */readonly workers?: HyperframesWorkers;+ /** Upper bound for auto's browser reservation; explicit workers remain fixed. */+ readonly maxWorkers?: number;readonly quality?: HyperframesQuality;/** Chrome's rasterizer, default hardware. Use software without a usable GPU. */readonly browserGpu?: HyperframesBrowserGpu;diff --git a/packages/provider-hyperframes-local/src/program.ts b/packages/provider-hyperframes-local/src/program.tsindex 182f3de7..fd521053 100644--- a/packages/provider-hyperframes-local/src/program.ts+++ b/packages/provider-hyperframes-local/src/program.ts@@ -22,13 +22,16 @@ export function localHyperframesBrowserProgram(input: {readonly id: string;readonly nodePath: string;- readonly hyperframesCliPath: string;+ readonly hyperframesCliPath: string | (() => string);readonly ffprobePath: string;readonly ffmpegPath?: string;},): ManagedProgram {+ const cliPath = () => typeof input.hyperframesCliPath === "string" ? input.hyperframesCliPath : input.hyperframesCliPath();const probeBrowser = async (): Promise<ManagedProgramState> => {- const located = await run(input.nodePath, [input.hyperframesCliPath, "browser", "path"]);+ let executable: string;+ try { executable = cliPath(); } catch (error) { return { state: "down", detail: error instanceof Error ? error.message : String(error) }; }+ const located = await run(input.nodePath, [executable, "browser", "path"]);if (!located.ok) return { state: "down", detail: `HyperFrames browser is unavailable: ${located.output}` };const path = located.output.trim();if (path.length === 0 || path.includes("\n") || path.includes("\r")) {@@ -44,7 +47,7 @@ export function localHyperframesBrowserProgram(id: input.id,installation: {probe: probeBrowser,- commands: [{ command: input.nodePath, args: [input.hyperframesCliPath, "browser", "ensure"] }],+ get commands() { return [{ command: input.nodePath, args: [cliPath(), "browser", "ensure"] }]; },},async probe(): Promise<ManagedProgramState> {const browser = await probeBrowser();diff --git a/packages/provider-hyperframes-local/src/progress.ts b/packages/provider-hyperframes-local/src/progress.tsnew file mode 100644index 00000000..740e5590--- /dev/null+++ b/packages/provider-hyperframes-local/src/progress.ts@@ -0,0 +1,53 @@+import type { OperationProgress } from "@hypit/endpoint-kit";+import type { HyperframesRenderProgress } from "./render.js";++/** Reduce parallel capture events to one readable progress report for this render request. */+export function renderProgressReporter(+ report: ((progress: OperationProgress) => Promise<void>) | undefined,+ totalFrames: number,+ now: () => number = Date.now,+) {+ const workers = new Map<number, number>();+ let rendering = false;+ let lastPhase: string | undefined;+ let lastAt = -Infinity;+ let writes = Promise.resolve();+ const frames = () => ({ phase: "rendering frames", completed: [...workers.values()].reduce((a, b) => a + b, 0),+ total: totalFrames, unit: "frames" });+ return {+ onProgress(event: HyperframesRenderProgress): void {+ if (report === undefined) return;+ let progress: OperationProgress;+ switch (event.phase) {+ case "staging": progress = { phase: "preparing resources" }; break;+ case "decoding": progress = { phase: "decoding source frames", completed: event.completed, total: event.total, unit: "frames" }; break;+ case "prepared":+ case "worker-initializing":+ if (rendering) return;+ progress = { phase: "starting browsers" }; break;+ case "worker-start":+ rendering = true;+ workers.set(event.worker, 0);+ progress = frames(); break;+ case "worker-progress":+ workers.set(event.worker, event.completed);+ progress = frames(); break;+ case "worker-complete":+ workers.set(event.worker, event.completed);+ progress = frames(); break;+ case "encoding": progress = { phase: "encoding video" }; break;+ case "storing": progress = { phase: "storing output" }; break;+ case "complete": return;+ }+ const at = now();+ if (progress.phase === lastPhase && at - lastAt < 1_000+ && (progress.total === undefined || progress.completed !== progress.total)) return;+ lastPhase = progress.phase;+ lastAt = at;+ // Attach rejection handling immediately; flush still propagates storage failure to the caller.+ writes = writes.then(() => report(progress));+ void writes.catch(() => {});+ },+ flush: () => writes,+ };+}diff --git a/packages/provider-hyperframes-local/src/provider.ts b/packages/provider-hyperframes-local/src/provider.tsindex 7574e2e8..fcfa1ba4 100644--- a/packages/provider-hyperframes-local/src/provider.ts+++ b/packages/provider-hyperframes-local/src/provider.ts@@ -3,8 +3,9 @@ import { mediaTypes } from "@hypit/media";import { renderHyperframesCapabilities, verifyHyperframesVisualRequest } from "@hypit/render-hyperframes";import { canonicalize } from "@hypit/protocol";import { resolveNodePackageExecutable } from "@hypit/package-loader-node";-import { renderHyperframesVisual, resolveExecutionOptions } from "./render.js";+import { renderHyperframesVisual, resolveExecutionOptions, renderWorkerLimit } from "./render.js";import type { HyperframesExecutionOptions } from "./options.js";+import { renderProgressReporter } from "./progress.js";export type * from "./options.js";export const localHyperframesProviderModuleRef = { name: "@hypit/provider-hyperframes-local", version: "1" } as const;@@ -31,6 +32,8 @@ export function createLocalHyperframesProvider(config: CreateLocalHyperframesProif (config.browserCapacity !== undefined && (!Number.isSafeInteger(config.browserCapacity) || config.browserCapacity < 1)) {throw new Error("HyperFrames browserCapacity must be a positive integer");}+ const maxWorkers = execution.workers === "auto" ? Math.min(execution.maxWorkers, config.browserCapacity ?? Infinity) : execution.maxWorkers;+ const reserved = { ...execution, maxWorkers };return defineEndpointPackage({module: localHyperframesProviderModuleRef,facet: "render",@@ -47,15 +50,25 @@ export function createLocalHyperframesProvider(config: CreateLocalHyperframesProunitsForRequest: (request: import("@hypit/endpoint-kit").EndpointRequest) => {verifyHyperframesVisualRequest(request.constraints);const { document, range } = request.constraints;- return { [browsers]: Math.min(execution.workers,- range === undefined ? document.frameCount : range.endFrameExclusive - range.startFrame) };+ return { [browsers]: renderWorkerLimit(reserved,+ range === undefined ? document.frameCount : range.endFrameExclusive - range.startFrame,+ document.frameRate.numerator / document.frameRate.denominator) };},}),handler: async (context) => {const request = context.need.constraints;verifyHyperframesVisualRequest(request);- const visual = await renderHyperframesVisual(request, { ...config, workers: execution.workers, resources: context.resources });- return { value: { kind: "inline", value: canonicalize(visual) } };+ const frameCount = request.range === undefined ? request.document.frameCount+ : request.range.endFrameExclusive - request.range.startFrame;+ const progress = renderProgressReporter(context.reportProgress, frameCount);+ try {+ const visual = await renderHyperframesVisual(request, { ...config, workers: execution.workers, maxWorkers,+ resources: context.resources, onProgress: progress.onProgress,+ ...(context.reportDiagnostic === undefined ? {} : { onDiagnostic: context.reportDiagnostic }) });+ return { value: { kind: "inline", value: canonicalize(visual) } };+ } finally {+ await progress.flush();+ }},}],});diff --git a/packages/provider-hyperframes-local/src/render.ts b/packages/provider-hyperframes-local/src/render.tsindex 98044dc1..7883a5cb 100644--- a/packages/provider-hyperframes-local/src/render.ts+++ b/packages/provider-hyperframes-local/src/render.ts@@ -1,6 +1,6 @@import { createReadStream } from "node:fs";import { mkdtemp, readFile, rm } from "node:fs/promises";-import { availableParallelism, tmpdir } from "node:os";+import { tmpdir } from "node:os";import { join } from "node:path";import type { EndpointInvocationContext } from "@hypit/endpoint-kit";import { stageHyperframesProject } from "@hypit/hyperframes/project";@@ -14,16 +14,23 @@ import type { HyperframesExecutionOptions } from "./options.js";import { assert, positiveInteger } from "./process.js";import { runCaptureProcess } from "./capture-process.js";import { finished } from "node:stream/promises";+import { autoWorkerLimit } from "./concurrency.js";export type HyperframesRenderProgress =+ | { readonly phase: "staging" | "encoding" | "storing"; readonly elapsedMs: number }+ | { readonly phase: "decoding"; readonly completed: number; readonly total: number; readonly elapsedMs: number }+ | { readonly phase: "worker-progress"; readonly worker: number; readonly completed: number; readonly elapsedMs: number }| { readonly phase: "prepared"; readonly workers: number; readonly sourceFrames: number; readonly elapsedMs: number }- | { readonly phase: "worker-initializing" | "worker-start" | "worker-complete"; readonly worker: number; readonly range: MediaFrameRange;+ | { readonly phase: "worker-initializing" | "worker-start"; readonly worker: number; readonly range: MediaFrameRange;+ readonly browserPid: number | undefined; readonly elapsedMs: number }+ | { readonly phase: "worker-complete"; readonly worker: number; readonly completed: number;readonly browserPid: number | undefined; readonly elapsedMs: number }| { readonly phase: "complete"; readonly frames: number; readonly elapsedMs: number };export type RenderHyperframesVisualOptions = HyperframesExecutionOptions & {readonly resources: EndpointInvocationContext["resources"];readonly signal?: AbortSignal;+ readonly onDiagnostic?: (diagnostic: import("@hypit/runtime").ExecutionDiagnostic) => Promise<void>;readonly onProgress?: (event: HyperframesRenderProgress) => void;};@@ -36,7 +43,8 @@ export function resolveExecutionOptions(options: HyperframesExecutionOptions) {const browserGpu = options.browserGpu ?? "hardware";assert(["auto", "software", "hardware"].includes(browserGpu), "HyperFrames browserGpu is invalid");return {- workers: workers === "auto" ? Math.min(4, Math.max(1, Math.floor(availableParallelism() / 2))) : workers,+ workers,+ maxWorkers: workers === "auto" ? positiveInteger(options.maxWorkers ?? autoWorkerLimit(), "maxWorkers") : workers,quality, browserGpu,ffmpegPath: options.ffmpegPath ?? "ffmpeg",ffprobePath: options.ffprobePath ?? "ffprobe",@@ -52,6 +60,11 @@ export function resolveExecutionOptions(options: HyperframesExecutionOptions) {};}+/** Same deterministic reservation for Runtime admission and the capture attempt. */+export function renderWorkerLimit(config: ReturnType<typeof resolveExecutionOptions>, frameCount: number, fps: number): number {+ return Math.min(config.maxWorkers, config.workers === "auto" ? Math.max(1, Math.ceil(frameCount / fps)) : frameCount);+}+/** Execute one attempt. Its deadline includes resource preparation and output storage. */export async function renderHyperframesVisual(request: HyperframesVisualRequest,@@ -61,14 +74,32 @@ export async function renderHyperframesVisual(const config = resolveExecutionOptions(options);const { document } = request;const range = request.range ?? { startFrame: 0, endFrameExclusive: document.frameCount };+ const frameCount = range.endFrameExclusive - range.startFrame;const controller = new AbortController();const signal = options.signal === undefined ? controller.signal : AbortSignal.any([controller.signal, options.signal]);const started = performance.now();+ let phaseStarted = started;let phase = "preparing resources";const timer = setTimeout(() => controller.abort(new Error(`HyperFrames render timed out during ${phase}`)), config.processTimeoutMs);let work: string | undefined;+ const diagnostics: Promise<void>[] = [];+ const diagnostic = (message: string) => {+ if (options.onDiagnostic === undefined) return;+ const pending = options.onDiagnostic({ level: "info", message });+ diagnostics.push(pending);+ void pending.catch(() => {});+ };+ const changePhase = (next: string) => {+ const now = performance.now();+ diagnostic(`${phase}: ${Math.round(now - phaseStarted)} ms`);+ phaseStarted = now;+ phase = next;+ };try {signal.throwIfAborted();+ await options.onDiagnostic?.({ level: "info", message:+ `Render ${frameCount} frames; workers ${config.workers} (limit ${renderWorkerLimit(config, frameCount, document.frameRate.numerator / document.frameRate.denominator)}); opaque fast PNG; quality ${config.quality}; GPU ${config.browserGpu}; encoder ${config.ffmpegPath}` });+ options.onProgress?.({ phase: "staging", elapsedMs: 0 });work = await mkdtemp(join(tmpdir(), "hypit-hyperframes-local-"));await stageHyperframesProject({ document, directory: work, signal,read: async (artifact, readSignal) => {@@ -82,13 +113,20 @@ export async function renderHyperframesVisual(ffprobePath: config.ffprobePath, processTimeoutMs: config.processTimeoutMs,maxProbeOutputBytes: config.maxProcessOutputBytes, signal: probeSignal! }),});- phase = "rendering frames";+ changePhase("decoding source frames");await runCaptureProcess({ document, range, config, directory: work,engineModule: import.meta.resolve("@hyperframes/engine"),producerModule: import.meta.resolve("@hyperframes/producer"),- }, signal, (event) => options.onProgress?.({ ...event, elapsedMs: Math.round(performance.now() - started) }));+ }, signal, (event) => {+ if (event.phase === "prepared") changePhase("starting browsers");+ if (event.phase === "worker-start" && phase === "starting browsers") changePhase("capturing frames");+ if (event.phase === "encoding") changePhase("encoding and verifying video");+ options.onProgress?.({ ...event, elapsedMs: Math.round(performance.now() - started) });+ },+ undefined, options.onDiagnostic);signal.throwIfAborted();- phase = "storing output";+ changePhase("storing output");+ options.onProgress?.({ phase: "storing", elapsedMs: Math.round(performance.now() - started) });const output = join(work, "visual.mp4");let artifact;if (isStreamingResourceStore(options.resources)) {@@ -100,7 +138,9 @@ export async function renderHyperframesVisual(artifact = await options.resources.put(await readFile(output, { signal }), "video/mp4", { signal });}signal.throwIfAborted();- const frameCount = range.endFrameExclusive - range.startFrame;++ changePhase("complete");+ await Promise.all(diagnostics);options.onProgress?.({ phase: "complete", frames: frameCount, elapsedMs: Math.round(performance.now() - started) });return sealRenderedVisual({ frameRate: document.frameRate, frameCount, canvas: document.canvas, artifact });} catch (error) {@@ -110,5 +150,6 @@ export async function renderHyperframesVisual(} finally {clearTimeout(timer);if (work !== undefined) await rm(work, { recursive: true, force: true });+ await Promise.all(diagnostics);}}diff --git a/packages/provider-hyperframes-local/test/capture-process.test.ts b/packages/provider-hyperframes-local/test/capture-process.test.tsindex a6fd7904..e95e9351 100644--- a/packages/provider-hyperframes-local/test/capture-process.test.ts+++ b/packages/provider-hyperframes-local/test/capture-process.test.ts@@ -40,3 +40,22 @@ setInterval(() => {}, 1000);await rm(root, { recursive: true, force: true });}});++test("renderer stdout and stderr diagnostics are drained before reporting success", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-render-diagnostics-"));+ const messages: import("@hypit/runtime").ExecutionDiagnostic[] = [];+ try {+ const entry = join(root, "report.mjs");+ await writeFile(entry, `process.once('message', () => {+ process.stdout.write('browser ready\\n');+ process.stderr.write('render diagnostic\\n');+ process.send({ type: 'completed' });+ });`);+ await runCaptureProcess({ config: resolveExecutionOptions({}) } as CaptureInput,+ new AbortController().signal, () => {}, pathToFileURL(entry), async (message) => {+ await new Promise((resolve) => setTimeout(resolve, 5)); messages.push(message);+ });+ assert.ok(messages.some((item) => item.stream === "stdout" && item.message.includes("browser ready")));+ assert.ok(messages.some((item) => item.stream === "stderr" && item.message.includes("render diagnostic")));+ } finally { await rm(root, { recursive: true, force: true }); }+});diff --git a/packages/provider-hyperframes-local/test/concurrency.test.ts b/packages/provider-hyperframes-local/test/concurrency.test.tsnew file mode 100644index 00000000..2fd6707b--- /dev/null+++ b/packages/provider-hyperframes-local/test/concurrency.test.ts@@ -0,0 +1,62 @@+import assert from "node:assert/strict";+import test from "node:test";+import { autoWorkerLimit, CaptureConcurrency } from "../src/concurrency.js";+import { renderWorkerLimit, resolveExecutionOptions } from "../src/render.js";++test("automatic reservations respect memory, explicit ceiling and actual frame range", () => {+ assert.equal(autoWorkerLimit(16, 6 * 1024 ** 3), 2);+ assert.equal(autoWorkerLimit(2, 32 * 1024 ** 3), 1);+ const auto = resolveExecutionOptions({ workers: "auto", maxWorkers: 6 });+ assert.equal(renderWorkerLimit(auto, 45, 30), 2);+ assert.equal(renderWorkerLimit(auto, 900, 30), 6);+ const fixed = resolveExecutionOptions({ workers: 8 });+ assert.equal(renderWorkerLimit(fixed, 45, 30), 8);+ assert.equal(renderWorkerLimit(fixed, 3, 30), 3);+});++test("auto expands using completed work and retires the extra browser when throughput falls", () => {+ const scheduler = new CaptureConcurrency(4, true);+ assert.equal(scheduler.target, 2);+ scheduler.settled(0);+ let decision;+ for (let i = 1; i <= 4; i++) decision = scheduler.complete({ now: i * 500, frames: 30,+ remainingFrames: 20_000, startupMs: 1_000, active: 2 });+ assert.equal(decision?.workers, 3);+ scheduler.settled(3_000);+ for (let i = 1; i <= 6; i++) decision = scheduler.complete({ now: 3_000 + i * 750, frames: 30,+ remainingFrames: 20_000, startupMs: 1_000, active: 3 });+ assert.equal(decision?.workers, 2);+ assert.match(decision!.reason, /did not improve/);+});++test("short remaining work does not pay for more browsers, and fixed workers never adapt", () => {+ for (const automatic of [true, false]) {+ const scheduler = new CaptureConcurrency(4, automatic);+ scheduler.settled(0);+ const original = scheduler.target;+ for (let i = 1; i <= 12; i++) {+ assert.equal(scheduler.complete({ now: i * 500, frames: 30, remainingFrames: 20,+ startupMs: 1_000, active: original }), undefined);+ }+ assert.equal(scheduler.target, original);+ }+});++test("a slower scene is not assumed to improve with fewer browsers", () => {+ const scheduler = new CaptureConcurrency(4, true);+ let now = 0;+ scheduler.settled(now);+ const sample = (active: number, interval: number, remainingFrames: number) => {+ let result;+ for (let i = 0; i < active * 2; i++) {+ now += interval;+ result = scheduler.complete({ now, frames: 30, remainingFrames, startupMs: 1_000, active });+ }+ return result;+ };+ // Establish a rate without enough work to justify adding a browser.+ sample(2, 500, 1);+ assert.equal(sample(2, 1_000, 10_000)?.workers, 1);+ scheduler.settled(now);+ assert.equal(sample(1, 2_000, 10_000)?.workers, 2);+});diff --git a/packages/provider-hyperframes-local/test/progress.test.ts b/packages/provider-hyperframes-local/test/progress.test.tsnew file mode 100644index 00000000..60aec738--- /dev/null+++ b/packages/provider-hyperframes-local/test/progress.test.ts@@ -0,0 +1,29 @@+import assert from "node:assert/strict";+import test from "node:test";+import type { OperationProgress } from "@hypit/endpoint-kit";+import { renderProgressReporter } from "../src/progress.js";++test("parallel render progress sums frames and does not regress when another browser starts", async () => {+ let clock = 0;+ const reports: OperationProgress[] = [];+ const reporter = renderProgressReporter(async (p) => { reports.push(p); }, 20, () => clock);+ reporter.onProgress({ phase: "staging", elapsedMs: 0 });+ reporter.onProgress({ phase: "decoding", completed: 0, total: 15, elapsedMs: 0 });+ const worker = (n: number) => ({ worker: n, range: { startFrame: n * 10, endFrameExclusive: (n + 1) * 10 }, browserPid: undefined, elapsedMs: 0 });+ reporter.onProgress({ phase: "worker-start", ...worker(0) });+ reporter.onProgress({ phase: "worker-initializing", ...worker(1) });+ reporter.onProgress({ phase: "worker-start", ...worker(1) });+ reporter.onProgress({ phase: "worker-progress", worker: 0, completed: 4, elapsedMs: 0 });+ clock = 1_001;+ reporter.onProgress({ phase: "worker-progress", worker: 1, completed: 3, elapsedMs: 0 });+ reporter.onProgress({ phase: "worker-complete", ...worker(0), completed: 14 });+ reporter.onProgress({ phase: "worker-complete", ...worker(1), completed: 6 });+ reporter.onProgress({ phase: "encoding", elapsedMs: 0 });+ reporter.onProgress({ phase: "storing", elapsedMs: 0 });+ await reporter.flush();+ assert.deepEqual(reports.map((p) => [p.phase, p.completed]), [+ ["preparing resources", undefined], ["decoding source frames", 0],+ ["rendering frames", 0], ["rendering frames", 7], ["rendering frames", 20],+ ["encoding video", undefined], ["storing output", undefined],+ ]);+});diff --git a/packages/provider-hyperframes-local/test/range.test.ts b/packages/provider-hyperframes-local/test/range.test.tsindex 9c6d7f55..45eea5b3 100644--- a/packages/provider-hyperframes-local/test/range.test.ts+++ b/packages/provider-hyperframes-local/test/range.test.ts@@ -114,7 +114,7 @@ test("real selected renders sample video correctly across loop, hold and stretchconst full = await render("full", undefined, 1);events.length = 0;const selected = await render("selected", { startFrame: 3, endFrameExclusive: 11 }, 3);- const starts = events.filter((e): e is Extract<HyperframesRenderProgress, { worker: number }> => e.phase === "worker-start");+ const starts = events.filter((e): e is Extract<HyperframesRenderProgress, { browserPid: number | undefined }> => e.phase === "worker-start");assert.equal(starts.length, 3);assert.equal(new Set(starts.map((e) => e.browserPid)).size, 3);const one = await render("one", { startFrame: 7, endFrameExclusive: 8 }, 4);diff --git a/packages/provider-hypihub/README.md b/packages/provider-hypihub/README.mdindex 23b0538e..db58dbfe 100644--- a/packages/provider-hypihub/README.md+++ b/packages/provider-hypihub/README.md@@ -1,21 +1,26 @@# `@hypit/provider-hypihub`Thin Hypit Runtime Provider for a HypiHub deployment. It is an optional default gateway for-paid generation and WhisperX alignment requests; callers may keep their own Provider and select HypiHub only-when its OAuth login is configured.+paid generation and WhisperX alignment requests. Select it for a chosen HypiHub account, with OAuth+or an API key in the configured Credential Store; other Providers remain ordinary Profile choices.-It maps the currently shipped image/video model capabilities to HypiHub, including image edits and+`doctor` is read-only. If a stored OAuth access token needs refresh, it reports that account access+and refresh validity remain unchecked; it does not rotate credentials or conclude that their Store+is read-only. Authorized execution and pricing reads retain the normal refresh-and-persist path.+An actual refresh rejection calls for reconnecting the selected account.++Its mapping table declares the image/video/speech model capabilities it implements, including image edits andimage-to-video first-frame inputs, submits jobs, polls them, downloads the first-class assets andadmits them into the current Build's working byte area. Image references use HypiHub's documented`reference_images` object shape (`[{ "url": "…" }]`); video references use the public-`reference_image_urls`, `reference_videos`, and `reference_audios` fields (with `ref_video_url`-for one video). First/last-frame images use `first_frame` and `last_frame`.+`reference_image_urls`, `reference_videos`, and `reference_audios` fields. A single reference video+remains in `reference_videos`; `ref_video_url` is reserved for a model's source-video port. First/last-frame images use `first_frame` and `last_frame`.Seedance 2.5 (`@hypit/seedance` model `2.5`) maps to `bytedance/seedance-2-5` and supports`480p`, `720p` and `1080p`. The Provider passes the authored `resolution` to `POST /v1/videos`;omitting it in the Seedance Surface defaults to `720p`.-The current HypiHub GPT Image 2 route exposes the same request surface as its KIE upstream:+The current HypiHub GPT Image 2 route has these service-specific limits:| Resolution | Ratios unavailable at this Endpoint | `background` || --- | --- | --- |@@ -23,10 +28,14 @@ The current HypiHub GPT Image 2 route exposes the same request surface as its KI| `2K` | `5:4`, `4:5`, `3:1`, `1:3`, `9:21` | omit || `4K` | `3:1`, `1:3`, `9:21` | omit |-HypiHub owns this support check independently: it neither imports the KIE Provider nor narrows the-GPT Image model package. When the service surface changes, this Provider can change without changing+HypiHub owns this support check independently: it leaves the GPT Image model package unchanged. When the service surface changes, this Provider can change without changingthe model or another Provider.+Model identity is preserved across input modes: Seedream 5 Lite references use the Lite image-edit+route, and Grok 1.5 Preview remains the Preview model. A deployment's current catalogue may offer+newer models or omit one implemented here. Availability and unsupported-input errors retain their+service explanation; they do not imply expired credentials or authorize substituting another model.+For moving portraits, [Volcengine Matting](../volcengine-matting/README.md) maps`@hypit/volcengine-matting@1#matte-portrait-video` to `POST /v1/videos` with`model: "matte-portrait-video"`, `ref_video_url` and `format` (`WEBM` by default, or `MOV`).@@ -35,8 +44,8 @@ references; the returned job uses the same polling and asset collection lifecyclaccount's `/v1/models` establishes availability. The processed video enters ordinary Normalize,then either semantic alignment for a Script performance or Media Track for B-roll.-The existing [Background Removal](../background-removal/README.md) package handles single images-through KIE Recraft. This Provider does not bind that separate image capability either.+[Background Removal](../background-removal/README.md) declares a separate single-image capability.+This Provider does not currently implement it; select a project Provider for that operation.Runtime Profile example:@@ -68,8 +77,16 @@ Resources are uploaded through a session from `POST /v1/files/uploads`, followedregional multipart instructions returned by HypiHub. The Provider follows the server-selected partsize and part concurrency, retries a failed part with a fresh signed URL, completes or cancels thatone upload, and then passes the returned HTTPS URL to generation or transcription. One-Resource identity is uploaded once within one Runtime operation. Hypit keeps no upload catalog or-cross-Build cache. Embedded callers may replace this transport with `publicAssetUrl`.+Resource identity with the same declared person-reference classification is uploaded once within one Runtime operation. Hypit keeps no upload catalog or+cross-Build cache. Seedance visual references can carry `personReference` in their media fields;+the mapping declares it as a resource-transport field and the upload session receives+`is_person_reference`, preserving true, false and omission. It stays out of the generation body.+HypiHub stores the authored classification and prepares the applicable upstream person reference;+this Provider does not detect faces or select an upstream private-avatar group.++Embedded callers may replace transport with `publicAssetUrl(artifact, resources, fields)`. That+callback receives the declared resource fields and must preserve any required service preparation,+such as uploading a marked person reference through HypiHub before returning its URL.OAuth login stores the access token, refresh token and expiry as one opaque credential value. Thebrowser callback only confirms that authorization returned to the CLI; the CLI reports success after@@ -97,7 +114,7 @@ the Provider does not maintain a second list of billing formulas or calculate aHypiHub declares MiMo Voice Design and Voice Clone together with every other capability it serves; itnever hides one. Voice Design produces an accepted voice-reference Resource, and Voice Clone usesthat reference to produce independent speech. Hypit does not expose MiMo preset voices. When another-selected Endpoint offers the same capability (a local WhisperX or the official MiMo+selected Endpoint offers the same capability (such as local WhisperX or a project-owned speechProvider), the Runtime Profile's `bindings` say which Endpoint serves it.Execution policy remains local to this Provider:diff --git a/packages/provider-hypihub/src/mapping.ts b/packages/provider-hypihub/src/mapping.tsindex 8a5b64e6..92f9529c 100644--- a/packages/provider-hypihub/src/mapping.ts+++ b/packages/provider-hypihub/src/mapping.ts@@ -14,11 +14,11 @@ const seedance = (name: string, model: string): GenerationWireMapping => ({capability: { module: SEEDANCE, name }, result: "video", routes: [{ model }],fields: {prompt: { as: "value", field: "prompt" },- referenceImage: { as: "urlArray", field: "reference_image_urls" },- referenceVideo: { as: "urlArray", field: "reference_videos" },+ referenceImage: { as: "urlArray", field: "reference_image_urls", resourceFields: ["personReference"] },+ referenceVideo: { as: "urlArray", field: "reference_videos", resourceFields: ["personReference"] },referenceAudio: { as: "urlArray", field: "reference_audios" },- firstFrame: { as: "url", field: "first_frame" },- lastFrame: { as: "url", field: "last_frame" },+ firstFrame: { as: "url", field: "first_frame", resourceFields: ["personReference"] },+ lastFrame: { as: "url", field: "last_frame", resourceFields: ["personReference"] },resolution: { as: "value", field: "resolution" },aspectRatio: { as: "value", field: "aspect_ratio" },duration: { as: "value", field: "seconds" },@@ -65,7 +65,7 @@ export const hypiHubMappings: readonly GenerationWireMapping[] = [})),{capability: { module: SEEDREAM, name: "seedream-5-lite" }, result: "image", routes: [- { model: "seedream/5-pro-image-to-image", whenPresent: ["images"] },+ { model: "seedream/5-lite-image-to-image", whenPresent: ["images"] },{ model: "seedream/5-lite-text-to-image" },],fields: {@@ -108,8 +108,7 @@ export const hypiHubMappings: readonly GenerationWireMapping[] = [},{capability: { module: GROK, name: "grok-imagine-video-1.5-preview" }, result: "video", routes: [- { model: "grok-imagine/image-to-video", whenPresent: ["images"] },- { model: "grok-imagine/text-to-video" },+ { model: "grok-imagine-video-1.5-preview" },],fields: {prompt: { as: "value", field: "prompt" }, duration: { as: "value", field: "seconds" },diff --git a/packages/provider-hypihub/src/oauth.ts b/packages/provider-hypihub/src/oauth.tsindex f3642613..8dbb3f5c 100644--- a/packages/provider-hypihub/src/oauth.ts+++ b/packages/provider-hypihub/src/oauth.ts@@ -5,6 +5,12 @@ import { requestDeadline } from "@hypit/runtime-kit";const OAUTH_CLIENT_ID = "hyc_d5d5e8e7131b0c877756e66c";const REFRESH_SKEW_MS = 60_000;+/** Read-only diagnostics can identify expiry without attempting credential rotation. */+export function hypiHubCredentialNeedsRefresh(secret: string, now = Date.now()): boolean {+ const expiresAt = decodeOAuth2Credential(secret)?.expiresAt;+ return expiresAt !== undefined && expiresAt <= now + REFRESH_SKEW_MS;+}+type OAuthTokenResponse = {readonly access_token?: unknown;readonly refresh_token?: unknown;diff --git a/packages/provider-hypihub/src/provider.ts b/packages/provider-hypihub/src/provider.tsindex f11cd58d..e371bdda 100644--- a/packages/provider-hypihub/src/provider.ts+++ b/packages/provider-hypihub/src/provider.ts@@ -18,7 +18,7 @@ import type { WhisperXTranscriptResponse } from "@hypit/whisperx";import { hypiHubRouteForCapability, hypiHubRoutes } from "./routes.js";import { HypiHubUploader } from "./upload.js";import type { RuntimeDoctorDiagnostic } from "@hypit/runtime-kit";-import { createHypiHubAuth } from "./oauth.js";+import { createHypiHubAuth, hypiHubCredentialNeedsRefresh } from "./oauth.js";import type { HypiHubAuth } from "./oauth.js";export const hypiHubProviderModuleRef = { name: "@hypit/provider-hypihub", version: "1" } as const;@@ -45,7 +45,7 @@ export type CreateHypiHubProviderOptions = {readonly transcriptionModel?: string;readonly fetch?: typeof globalThis.fetch;/** Overrides HypiHub's negotiated upload transport for referenced Resources. */- readonly publicAssetUrl?: (artifact: BlobRef, artifacts: ResourceStore) => Promise<string>;+ readonly publicAssetUrl?: (artifact: BlobRef, artifacts: ResourceStore, fields?: Readonly<Record<string, string | number | boolean>>) => Promise<string>;};type Handle = { readonly contract: "hypit.hypihub-operation@1"; readonly jobId: string; readonly route: string; readonly startedAt: number };@@ -69,7 +69,7 @@ function credential(credentials: Readonly<Record<string, EndpointCredential>>) {}function guidedMessage(error: unknown): string {const message = error instanceof Error ? error.message : String(error);- return /API key is unavailable|HypiHub login is unavailable|HTTP (?:401|403|404)\b|not enabled for|model_not_found|no_capable_provider/iu.test(message)+ return /API key is unavailable|HypiHub login is unavailable|HTTP 401\b/iu.test(message)? `${message}. Sign in to HypiHub at https://hypit.ai with hypit auth login`: message;}@@ -155,11 +155,14 @@ class HypiHubClient {}throw lastError instanceof Error ? lastError : new Error(String(lastError));}- async upload(artifact: BlobRef, resources: ResourceStore, auth: HypiHubAuth): Promise<string> {+ async upload(artifact: BlobRef, resources: ResourceStore, auth: HypiHubAuth, fields?: Readonly<Record<string, string | number | boolean>>): Promise<string> {const bytes = await resources.get(artifact.resource);assert(bytes !== undefined, `HypiHub reference artifact ${artifact.resource} is unavailable`);assert(bytes.byteLength === artifact.size, `HypiHub reference artifact ${artifact.resource} size differs`);- return await this.uploader.upload({ bytes, mediaType: artifact.mediaType }, auth);+ const personReference = fields?.personReference;+ assert(personReference === undefined || typeof personReference === "boolean", "HypiHub personReference must be a boolean");+ return await this.uploader.upload({ bytes, mediaType: artifact.mediaType,+ ...(personReference === undefined ? {} : { isPersonReference: personReference }) }, auth);}async transcribe(body: Record<string, unknown>, auth: HypiHubAuth): Promise<Record<string, unknown>> {@@ -300,6 +303,11 @@ export async function diagnoseHypiHubProvider(): Promise<readonly RuntimeDoctorDiagnostic[]> {const apiKey = context.credentials.apiKey?.secret;assert(typeof apiKey === "string" && apiKey.length > 0, "HypiHub login is unavailable");+ if (hypiHubCredentialNeedsRefresh(apiKey)) return [{+ severity: "warning",+ code: "HYPIHUB_OAUTH_REFRESH_UNCHECKED",+ message: "The stored HypiHub access token needs refresh. Read-only doctor has not checked account access or refresh validity. Authorized execution can refresh through a writable Credential Store; reconnect if that refresh is rejected.",+ }];const client = new HypiHubClient({baseUrl: apiBaseUrl(options.baseUrl ?? "https://hypit.ai/v1"),timeout: options.requestTimeoutMs ?? 30_000,@@ -373,9 +381,9 @@ async function synthesizeAudio(client: HypiHubClient, context: EndpointInvocatioconst route = hypiHubRouteForCapability(context.need.capability);assert(route !== undefined && route.media === "audio", "HypiHub does not implement this exact capability");const auth = authFor(context, client);- const compiled = await route.compile(context.need.constraints, async (artifact) => publicAssetUrl === undefined- ? await client.upload(artifact, context.resources, auth)- : await publicAssetUrl(artifact, context.resources));+ const compiled = await route.compile(context.need.constraints, async (artifact, fields) => publicAssetUrl === undefined+ ? await client.upload(artifact, context.resources, auth, fields)+ : await publicAssetUrl(artifact, context.resources, fields));await verifyModelRoute(client, auth, compiled.model, "audio_speech");const audio = await client.speech(auth, { model: compiled.model, ...(compiled.input as Record<string, unknown>) });const artifacts = await Promise.all(audio.map(async (item) => await context.resources.put(item.bytes, item.mediaType)));@@ -390,13 +398,14 @@ function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs:assert(route !== undefined, "HypiHub does not implement this exact capability");const auth = authFor(context, client);const uploaded = new Map<string, Promise<string>>();- const resolve = (artifact: BlobRef): Promise<string> => {- const existing = uploaded.get(artifact.resource);+ const resolve = (artifact: BlobRef, fields?: Readonly<Record<string, string | number | boolean>>): Promise<string> => {+ const key = JSON.stringify([artifact.resource, canonicalize(fields ?? {})]);+ const existing = uploaded.get(key);if (existing !== undefined) return existing;const promise = publicAssetUrl === undefined- ? client.upload(artifact, context.resources, auth)- : publicAssetUrl(artifact, context.resources);- uploaded.set(artifact.resource, promise);+ ? client.upload(artifact, context.resources, auth, fields)+ : publicAssetUrl(artifact, context.resources, fields);+ uploaded.set(key, promise);return promise;};const compiled = await route.compile(context.need.constraints, resolve);@@ -511,9 +520,11 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}assertWhisperXEvidenceWav(bytes, request.sampleFrames);const auth = authFor(context, client);await verifyModelRoute(client, auth, transcriptionModel, "transcriptions");+ await context.reportProgress?.({ phase: "Preparing audio for hosted transcription" });const url = options.publicAssetUrl === undefined? await client.upload(request.audio, context.resources, auth): await options.publicAssetUrl(request.audio, context.resources);+ await context.reportProgress?.({ phase: "Transcribing and aligning words" });const response = await client.transcribe({model: transcriptionModel,url,@@ -524,6 +535,7 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}const evidence = sealAlignedTranscriptEvidence({passages: interpretWhisperXTranscript(response as WhisperXTranscriptResponse, request.sampleFrames),});+ await context.reportProgress?.({ phase: "Word timing ready" });return { value: { kind: "inline", value: canonicalize(evidence) } };} catch (error) {throw new Error(guidedMessage(error), { cause: error });diff --git a/packages/provider-hypihub/src/routes.ts b/packages/provider-hypihub/src/routes.tsindex 870ded4b..a50e9ff3 100644--- a/packages/provider-hypihub/src/routes.ts+++ b/packages/provider-hypihub/src/routes.ts@@ -117,8 +117,7 @@ function normalizeHypiHubRequest(? (item as Record<string, unknown>).url : item).filter((item): item is string => typeof item === "string" && item.length > 0);if (urls.length > 0) input.reference_image_urls = urls;}- if (Array.isArray(videoRefs) && videoRefs.length === 1) input.ref_video_url = videoRefs[0];- else if (Array.isArray(videoRefs) && videoRefs.length > 1) input.reference_videos = videoRefs;+ if (Array.isArray(videoRefs) && videoRefs.length > 0) input.reference_videos = videoRefs;if (Array.isArray(audioRefs) && audioRefs.length > 0) input.reference_audios = audioRefs;return { model: request.model, input: canonicalize(input) };}diff --git a/packages/provider-hypihub/src/upload.ts b/packages/provider-hypihub/src/upload.tsindex 826c0a42..1ce0b3cb 100644--- a/packages/provider-hypihub/src/upload.ts+++ b/packages/provider-hypihub/src/upload.ts@@ -70,6 +70,7 @@ export type HypiHubUploadInput = {readonly mediaType: string;readonly filename?: string;readonly purpose?: string;+ readonly isPersonReference?: boolean;};type PartDeclaration = {@@ -385,6 +386,7 @@ export class HypiHubUploader {bytes: input.bytes.byteLength,mime_type: input.mediaType,purpose: input.purpose ?? "reference",+ ...(input.isPersonReference === undefined ? {} : { is_person_reference: input.isPersonReference }),sha256: digest,head_base64: Buffer.from(input.bytes.subarray(0, 512)).toString("base64"),}),diff --git a/packages/provider-hypihub/test/provider.test.ts b/packages/provider-hypihub/test/provider.test.tsindex 32b62c39..521542cf 100644--- a/packages/provider-hypihub/test/provider.test.ts+++ b/packages/provider-hypihub/test/provider.test.ts@@ -1,5 +1,6 @@import assert from "node:assert/strict";import test from "node:test";+import { encodeOAuth2Credential } from "@hypit/runtime";import { EndpointRegistry, MemoryResourceStore } from "@hypit/driver-node";import { defineEndpointPackage } from "@hypit/endpoint-kit";@@ -233,6 +234,20 @@ test("HypiHub prices the wire route selected by an authored future input", async});});+test("HypiHub doctor leaves expired OAuth refresh validity unknown without misidentifying the Store", async () => {+ const diagnostics = await diagnoseHypiHubProvider({ fetch: async () => {+ throw new Error("Read-only doctor must not rotate an expired credential");+ } }, {+ credentials: { apiKey: { secret: encodeOAuth2Credential({+ accessToken: "expired", refreshToken: "unverified-refresh", expiresAt: Date.now() - 1_000,+ }) } },+ capabilities: [whisperXCapabilities.alignment],+ });+ assert.equal(diagnostics[0]?.code, "HYPIHUB_OAUTH_REFRESH_UNCHECKED");+ assert.equal(diagnostics[0]?.severity, "warning");+ assert.doesNotMatch(diagnostics[0]!.message, /credential is read-only/u);+});+test("HypiHub doctor checks the authenticated catalogue only when actively invoked", async () => {let calls = 0;const diagnostics = await diagnoseHypiHubProvider({ fetch: async (input, init) => {@@ -353,8 +368,8 @@ test("HypiHub uploads one referenced Resource once and submits its HTTPS URL", aconst request = need(sealSeedanceRequest("seedance-2-mini", {prompt: ["A presenter turns toward camera."],referenceImage: [- { role: "image", artifact: reference },- { role: "image", artifact: reference },+ { role: "image", artifact: reference, fields: { personReference: true } },+ { role: "image", artifact: reference, fields: { personReference: true } },],resolution: ["720p"], aspectRatio: ["16:9"], duration: [5],generateAudio: [false], webSearch: [false],@@ -372,6 +387,7 @@ test("HypiHub uploads one referenced Resource once and submits its HTTPS URL", aassert.equal(body.bytes, referenceBytes.byteLength);assert.equal(body.mime_type, "image/png");assert.equal(body.filename, "reference.png");+ assert.equal(body.is_person_reference, true);return Response.json({upload_mode: "s3_multipart",upload_id: "up_reference",@@ -668,3 +684,53 @@ test("HypiHub polling errors and operation deadlines fail without settlement polassert.match(offline.status === "failed" ? offline.failure.message : "", /offline/);assert.equal(requests, 1);});++test("reference URL reuse includes its authored classification and forwards it to custom transport", async () => {+ const resources = new MemoryResourceStore();+ const reference = await resources.put(new Uint8Array([1, 2, 3]), "image/png");+ const flags = [true, false, undefined, true];+ const request = need(sealSeedanceRequest("seedance-2-mini", {+ prompt: ["A person waves."], resolution: ["720p"], aspectRatio: ["9:16"],+ duration: [5], generateAudio: [false], webSearch: [false],+ referenceImage: flags.map((flag) => ({ role: "image", artifact: reference,+ ...(flag === undefined ? {} : { fields: { personReference: flag } }) })),+ }) as unknown as CanonicalValue);+ const seen: unknown[] = [];+ const provider = createHypiHubProvider({+ publicAssetUrl: async (_artifact, _resources, fields) => {+ seen.push(fields);+ return `https://media.test/${String(fields?.personReference)}`;+ },+ fetch: async (input, init) => {+ if (String(input).includes("/models/")) return Response.json({ endpoints: ["videos"] });+ assert.deepEqual(JSON.parse(String(init?.body)).reference_image_urls, flags.map((flag) => `https://media.test/${String(flag)}`));+ return Response.json({ id: "classified-inputs", status: "queued" });+ },+ });+ const registry = new EndpointRegistry();+ await provider.install(registry);+ const resolved = registry.resolve(request);+ assert.equal(resolved.status, "resolved");+ assert.equal(resolved.registration.kind, "asynchronous");+ const started = await resolved.registration.endpoint.start({ command: { kind: "fulfill-need", id: "classified", need: request }, need: request, resources,+ credentials: { apiKey: { secret: "test-key" } }, operation: "classified" });+ assert.equal(started.status, "pending");+ assert.deepEqual(seen, [{ personReference: true }, { personReference: false }, {}]);+});++test("an unavailable model reports availability without prescribing another login", async () => {+ const request = need(sealSeedanceRequest("seedance-2-mini", {+ prompt: ["A presenter speaks."], resolution: ["720p"], aspectRatio: ["9:16"],+ duration: [5], generateAudio: [true], webSearch: [false],+ }) as unknown as CanonicalValue);+ const endpoint = await endpointFor(request, async () => Response.json({ error: "model_not_found" }, { status: 404 }));+ const outcome = await endpoint.start({+ command: { kind: "fulfill-need", id: "command:unavailable", need: request },+ need: request, resources: new MemoryResourceStore(),+ credentials: { apiKey: { secret: "test-key" } }, operation: "operation:unavailable",+ });+ assert.equal(outcome.status, "failed");+ if (outcome.status !== "failed") return;+ assert.match(outcome.failure.message, /404.*model_not_found/u);+ assert.doesNotMatch(outcome.failure.message, /sign in|auth login/iu);+});diff --git a/packages/provider-hypihub/test/routes.test.ts b/packages/provider-hypihub/test/routes.test.tsindex a9e1ca08..511d2f5e 100644--- a/packages/provider-hypihub/test/routes.test.ts+++ b/packages/provider-hypihub/test/routes.test.ts@@ -153,7 +153,7 @@ test("HypiHub MiniMax reference mode preserves the public image array", async ()});});-test("HypiHub uses ref_video_url for one video and the public array for multiple videos", async () => {+test("HypiHub preserves reference-video roles for one or several videos", async () => {const route = hypiHubRoutes.find((item) => item.capability.name === "minimax-h3");assert.ok(route);const video = { ...image, mediaType: "video/mp4" };@@ -165,7 +165,7 @@ test("HypiHub uses ref_video_url for one video and the public array for multiple} }, resolveVideo);assert.deepEqual(single.input, {prompt: "animate", seconds: 6, resolution: "2k",- ref_video_url: "https://hypit.ai/files/1.mp4",+ reference_videos: ["https://hypit.ai/files/1.mp4"],});const multiple = await route.compile({ ports: {@@ -206,3 +206,32 @@ test("HypiHub MiMo Speech mappings use the public audio speech fields", async ()reference_audio: ["data:audio/wav;base64,AQID"],});});++test("Seedance person metadata reaches resource transport without changing video request fields", async () => {+ for (const port of ["referenceImage", "referenceVideo", "firstFrame", "lastFrame"] as const) {+ const route = hypiHubRoutes.find((item) => item.capability.name === "seedance-2-mini")!;+ for (const flag of [true, false, undefined]) {+ const fields = flag === undefined ? {} : { personReference: flag };+ const seen: unknown[] = [];+ const result = await route.compile({ ports: {+ prompt: ["animate"], duration: [5],+ [port]: [{ role: port === "referenceVideo" ? "video" : "image", artifact: image, fields }],+ } }, async (_artifact, metadata) => { seen.push(metadata); return "https://media.test/ref"; });+ assert.deepEqual(seen, [fields]);+ const wireField = { referenceImage: "reference_image_urls", referenceVideo: "reference_videos", firstFrame: "first_frame", lastFrame: "last_frame" }[port];+ assert.deepEqual((result.input as Record<string, unknown>)[wireField], port.startsWith("reference") ? ["https://media.test/ref"] : "https://media.test/ref");+ assert.equal(JSON.stringify(result.input).includes("person"), false);+ }+ }+});++test("exact model identity survives reference mode and preview selection", async () => {+ const lite = hypiHubRoutes.find((item) => item.capability.name === "seedream-5-lite")!;+ const preview = hypiHubRoutes.find((item) => item.capability.name === "grok-imagine-video-1.5-preview")!;+ for (const images of [[], [{ role: "image", artifact: image }]]) {+ const request = { ports: { prompt: ["A scene"], ...(images.length ? { images } : {}) } };+ assert.equal((await lite.compile(request, resolve)).model,+ images.length ? "seedream/5-lite-image-to-image" : "seedream/5-lite-text-to-image");+ assert.equal((await preview.compile(request, resolve)).model, "grok-imagine-video-1.5-preview");+ }+});diff --git a/packages/provider-hypihub/test/upload.test.ts b/packages/provider-hypihub/test/upload.test.tsindex e3b21a5c..63be783c 100644--- a/packages/provider-hypihub/test/upload.test.ts+++ b/packages/provider-hypihub/test/upload.test.ts@@ -230,3 +230,16 @@ test("OAuth refresh keeps the existing upload session and retries only its rejecassert.equal(f.calls.filter((call) => call.endsWith("/parts")).length, 2);assert.equal(f.calls.filter((call) => call.startsWith("DELETE")).length, 0);});++test("upload sessions preserve explicit person-reference flags and omission", async () => {+ for (const flag of [true, false, undefined]) {+ const f = fixture((url, init) => {+ if (!url.endsWith("/files/uploads")) return;+ const body = JSON.parse(String(init.body));+ assert.equal(body.is_person_reference, flag);+ assert.equal(Object.hasOwn(body, "is_person_reference"), flag !== undefined);+ return undefined;+ });+ await f.uploader().upload({ ...input, ...(flag === undefined ? {} : { isPersonReference: flag }) }, "test-key");+ }+});diff --git a/packages/provider-kie/README.md b/packages/provider-kie/README.mddeleted file mode 100644index 9290069f..00000000--- a/packages/provider-kie/README.md+++ /dev/null@@ -1,134 +0,0 @@-# `@hypit/provider-kie`--Asynchronous KIE Market Provider for the eleven explicitly selected exact models and one generic-background-removal capability.--This package is deployment code. Author source imports model modules such as `@hypit/seedance` or-`@hypit/gpt-image`; trusted Runtime configuration installs `createKieProvider()`. The Provider binds-only those exact model capabilities and never interprets a generic image/video request as permission to-choose another model.--It imports no exact-model package. Every supported Capability contributes one `KieRoute`: exact-Capability, return Type, request compiler, media/count limits and result packer. All Routes share one-upload, paid submission, durable Operation polling, download and working-Resource write path. Model mappings-generate eleven Routes; Background Removal contributes the twelfth.--## Supported catalog--One Capability per exact model; a service that splits a model across endpoints expresses that as-routes rather than extra Capabilities.--| Author module | Exact models | KIE model slugs |-|---|---|---|-| `@hypit/seedance` | `seedance-2`, `-fast`, `-mini`, `seedance-2.5` | `bytedance/seedance-2*`, `bytedance/seedance-2-5` |-| `@hypit/minimax-h3` | `minimax-h3` | `minimax-h3/{text,image,reference}-to-video` |-| `@hypit/grok-imagine` | `grok-imagine-video`, `-1.5-preview` | Grok Imagine video endpoints |-| `@hypit/gpt-image` | `gpt-image-2` | `gpt-image-2-{text,image}-to-image` |-| `@hypit/nano-banana` | `nano-banana-2`, `-pro` | `nano-banana-2`, `nano-banana-pro` |-| `@hypit/seedream` | `seedream-5-lite` | `seedream/5-lite-{text,image}-to-image` |-| `@hypit/background-removal` | `remove-background` | `recraft/remove-background` |--KIE's current GPT Image 2 request surface is:--| Resolution | Ratios unavailable at this Endpoint | `background` |-| --- | --- | --- |-| `1K` | none | optional |-| `2K` | `5:4`, `4:5`, `3:1`, `1:3`, `9:21` | omit |-| `4K` | `3:1`, `1:3`, `9:21` | omit |--These facts were checked against KIE's live `createTask` endpoint on 2026-09-07. The live API accepts-`5:4` and `4:5` at 4K even though KIE's [model page](https://kie.ai/gpt-image-2) currently lists a-broader restriction. At 2K and 4K, any explicit `background` value is rejected, including `opaque`-and `auto`. The KIE Endpoint checks this boundary before upload or paid submission; the GPT Image-model package continues to expose the complete Provider-neutral vocabulary.--KIE's Grok Imagine endpoints accept up to seven reference images, but only one at 1080p. This is-also checked by the KIE Endpoint; the Grok model packages retain their model-level seven-image-capacity.--KIE publishes a public model-pricing catalogue at `POST /client/v1/model-pricing/page`. For each-selected Need, `readPricing` derives the same KIE wire model used for execution, reads the catalogue's-pages with that wire model in KIE's `modelDescription` query, and preserves the returned records. The-Provider contains no Hypit model-price table and does not interpret KIE's descriptions or formulas.-All returned parameter rows remain intact for the Agent to read beside the Need. Reading this public-catalogue does not resolve the generation API credential and submits no work.-The optional document summary presents each row's model description, USD price, credit price and-billing unit. Comparison prices and promotion fields remain in the original data for JSON or verbose-inspection; the summary does not guess a matching tier from KIE's description text.--There is deliberately no Grok image capability and no MiMo capability in this release. Seedream's-`nsfwCheck` is explicit author request content; KIE cannot silently enable or disable it. A-customer-specific “spicy” treatment belongs in a Recipe that selects and parameterizes exact model-requests, not in Provider routing.--## Local Runtime--Declarative activation names an ordinary CredentialRef, not an environment-specific Provider field:--```json-"kie.personal": {- "use": "@hypit/provider-kie",- "config": {- "apiKey": { "store": "os", "key": "kie.api-key" },- "defaultConcurrency": 8,- "capabilityConcurrency": {- "seedance-2.5": 4,- "gpt-image-2": 3- }- }-}-```--The selected writable CredentialStore then enables `hypit auth login kie.personal --runtime-hypit.runtime.json`; KIE contributes the credential description and the generic CLI contains no KIE-branch.--```ts-import { createKieProvider } from "@hypit/provider-kie";-import { credentialRef } from "@hypit/runtime";--const kie = createKieProvider({- instance: "kie.personal",- apiKey: credentialRef("env", "KIE_API_KEY"),- defaultConcurrency: 8,- capabilityConcurrency: {- "seedance-2.5": 4,- "gpt-image-2": 3,- },-});-```--`defaultConcurrency` is the total capacity of this configured KIE Endpoint across all Builds. Each-optional `capabilityConcurrency` entry narrows the capacity of one exact KIE model inside that total. By-default the Endpoint instance is the shared-resource identity. Set Profile `pool` only when multiple-Endpoint instances really use the same account or deployment quota. Another Provider is independent-unless the Profile explicitly gives it that same real-resource identity.-One Need execution acquires its total and model-specific capacity claims atomically. These are shared-resource-limits, not parent and child queues.--Optional `actionLimits` uses the shared Endpoint vocabulary for `submit`, `poll` and `collect`.-For example, `submit: { rate: { limit: 1, periodMs: 200 } }` admits one start action every 200 ms,-with an initial burst of one. It is shared by instances in the same pool. A start includes reference-preparation and submission; this is an action-admission limit, not a timestamp guarantee for each-HTTP request. `collect: { concurrency: 2 }` separately bounds concurrent result downloads.-Polling transport errors and operation deadlines fail the attempt and retain the task receipt.--An advanced embedding adds `kie` to its Endpoint list beside a complete, explicit set of Runtime-service packages and selections. The `.svml` Module Closure separately contains only the model-Manifests actually imported by the author document; installing KIE does not add author intent.--## Task execution and receipts--Reference Resources are uploaded before `createTask`. An acknowledged task ID is saved immediately;-normal polling uses that same ID. Submission, polling or collection errors end the attempt with the-actual error. A timeout without an ID records the missing acknowledgement; the next attempt can be a-new Build. No failure changes the selected Endpoint or account.--On success, poll reports artifacts ready and `collect` downloads them into the Build's working byte-area. The Result retains completed public Outputs and non-secret task receipts after active Runtime-state is removed. A task receipt identifies `/api/v1/jobs/recordInfo?taskId=<id>` on the configured-KIE API base URL; the selected credential reference supplies access without storing the key in Result.-These records support inspection and explicit reuse in a new Run, not restarting the old Build.--The automated tests exercise submission errors, accepted-task polling, full-response deadlines and-bounded downloads against fake services, without paid generation.diff --git a/packages/provider-kie/package.json b/packages/provider-kie/package.jsondeleted file mode 100644index 9f4f384a..00000000--- a/packages/provider-kie/package.json+++ /dev/null@@ -1,43 +0,0 @@-{- "name": "@hypit/provider-kie",- "version": "0.0.0-dev",- "license": "SEE LICENSE IN LICENSE",- "private": true,- "type": "module",- "exports": {- ".": "./src/index.ts"- },- "hypit": {- "activation": "./src/activation.ts"- },- "dependencies": {- "@hypit/artifact": "workspace:*",- "@hypit/background-removal": "workspace:*",- "@hypit/endpoint-kit": "workspace:*",- "@hypit/generation": "workspace:*",- "@hypit/protocol": "workspace:*",- "@hypit/runtime": "workspace:*",- "@hypit/runtime-kit": "workspace:*"- },- "devDependencies": {- "@hypit/resource-store-fs": "workspace:*",- "@hypit/component-kit": "workspace:*",- "@hypit/core": "workspace:*",- "@hypit/credential-store-env": "workspace:*",- "@hypit/driver-node": "workspace:*",- "@hypit/elaborator": "workspace:*",- "@hypit/gpt-image": "workspace:*",- "@hypit/grok-imagine": "workspace:*",- "@hypit/runtime-local": "workspace:*",- "@hypit/media": "workspace:*",- "@hypit/minimax-h3": "workspace:*",- "@hypit/model-kit": "workspace:*",- "@hypit/nano-banana": "workspace:*",- "@hypit/narrative": "workspace:*",- "@hypit/seedance": "workspace:*",- "@hypit/seedream": "workspace:*",- "@hypit/store-sqlite": "workspace:*",- "@hypit/text": "workspace:*",- "@hypit/validation": "workspace:*"- }-}diff --git a/packages/provider-kie/src/activation.ts b/packages/provider-kie/src/activation.tsdeleted file mode 100644index 578ba1dc..00000000--- a/packages/provider-kie/src/activation.ts+++ /dev/null@@ -1,71 +0,0 @@-import {- createRuntimeEndpointAdapterFacet,- runtimeConfigCredentialRef,- runtimeConfigActionLimits,- runtimeConfigExact,- runtimeConfigObject,- runtimeConfigPositiveInteger,- runtimeConfigString,-} from "@hypit/runtime-kit";--import { createKieProvider } from "./provider.js";--const kieRuntimeAdapter = createRuntimeEndpointAdapterFacet({- use: "@hypit/provider-kie",- activate(context) {- if (context.pool === undefined) throw new Error("KIE Provider Pool is required");- const config = runtimeConfigObject(context.config, "KIE");- runtimeConfigExact(config, [- "apiBaseUrl", "uploadBaseUrl", "apiKey", "defaultConcurrency", "pollIntervalMs",- "capabilityConcurrency", "actionLimits", "requestTimeoutMs", "maxOperationMs", "maxArtifactBytes",- ], "KIE");- const apiBaseUrl = runtimeConfigString(config.apiBaseUrl, "KIE apiBaseUrl");- const uploadBaseUrl = runtimeConfigString(config.uploadBaseUrl, "KIE uploadBaseUrl");- for (const [value, subject] of [[apiBaseUrl, "KIE apiBaseUrl"], [uploadBaseUrl, "KIE uploadBaseUrl"]] as const) {- if (value === undefined) continue;- const url = new URL(value);- if (url.protocol !== "https:" && url.hostname !== "localhost") {- throw new Error(`${subject} must use HTTPS or localhost`);- }- }- const apiKey = runtimeConfigCredentialRef(config.apiKey, "KIE apiKey");- if (apiKey === undefined) throw new Error("KIE apiKey CredentialRef is required");- const defaultConcurrency = runtimeConfigPositiveInteger(config.defaultConcurrency, "KIE defaultConcurrency");- const capabilityConcurrency = config.capabilityConcurrency === undefined- ? undefined- : Object.fromEntries(Object.entries(runtimeConfigObject(config.capabilityConcurrency, "KIE capabilityConcurrency"))- .map(([capability, value]) => {- const concurrency = runtimeConfigPositiveInteger(value, `KIE capabilityConcurrency.${capability}`);- if (concurrency === undefined) throw new Error(`KIE capabilityConcurrency.${capability} is required`);- return [capability, concurrency];- }));- const pollIntervalMs = runtimeConfigPositiveInteger(config.pollIntervalMs, "KIE pollIntervalMs");- const actionLimits = runtimeConfigActionLimits(config.actionLimits);- const requestTimeoutMs = runtimeConfigPositiveInteger(config.requestTimeoutMs, "KIE requestTimeoutMs");- const maxOperationMs = runtimeConfigPositiveInteger(config.maxOperationMs, "KIE maxOperationMs");- const maxArtifactBytes = runtimeConfigPositiveInteger(config.maxArtifactBytes, "KIE maxArtifactBytes");- return {- endpoint: createKieProvider({- instance: context.instance,- pool: context.pool,- ...(apiBaseUrl === undefined ? {} : { apiBaseUrl }),- ...(uploadBaseUrl === undefined ? {} : { uploadBaseUrl }),- apiKey,- ...(defaultConcurrency === undefined ? {} : { defaultConcurrency }),- ...(capabilityConcurrency === undefined ? {} : { capabilityConcurrency }),- ...(pollIntervalMs === undefined ? {} : { pollIntervalMs }),- ...(actionLimits === undefined ? {} : { actionLimits }),- ...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }),- ...(maxOperationMs === undefined ? {} : { maxOperationMs }),- ...(maxArtifactBytes === undefined ? {} : { maxArtifactBytes }),- }),- };- },-});--export const hypitPackage = {- format: "hypit.node-package@1" as const,- hostFacets: [kieRuntimeAdapter],-};--export default hypitPackage;diff --git a/packages/provider-kie/src/index.ts b/packages/provider-kie/src/index.tsdeleted file mode 100644index ab243814..00000000--- a/packages/provider-kie/src/index.ts+++ /dev/null@@ -1,10 +0,0 @@-export {- kieMappingForCapability,- kieModelCatalog,- verifyKieModelCatalog,-} from "./mapping.js";-export {- createKieProvider,- kieProviderModuleRef,-} from "./provider.js";-export type { CreateKieProviderOptions } from "./provider.js";diff --git a/packages/provider-kie/src/mapping.ts b/packages/provider-kie/src/mapping.tsdeleted file mode 100644index 191a1d48..00000000--- a/packages/provider-kie/src/mapping.ts+++ /dev/null@@ -1,182 +0,0 @@-import type { CapabilityRef, ModuleRef } from "@hypit/protocol";-import type { GenerationWireMapping } from "@hypit/generation";--/**- * How KIE names each model's declared input ports.- *- * This file contains data only. It references Capabilities by module and model- * name, so this Provider package imports no model package: a model owns what it- * accepts, and KIE owns what it calls that on its wire. Splitting one model- * across several KIE endpoints is a KIE fact and lives in `routes`.- */--/** Model packages this KIE release is written against. A version bump is a mapping review. */-const SEEDANCE: ModuleRef = { name: "@hypit/seedance", version: "1" };-const MINIMAX: ModuleRef = { name: "@hypit/minimax-h3", version: "1" };-const GROK: ModuleRef = { name: "@hypit/grok-imagine", version: "1" };-const GPT_IMAGE: ModuleRef = { name: "@hypit/gpt-image", version: "1" };-const NANO_BANANA: ModuleRef = { name: "@hypit/nano-banana", version: "1" };-const SEEDREAM: ModuleRef = { name: "@hypit/seedream", version: "1" };--/** KIE keeps each reference modality in its own array, as its schema documents. */-const referenceFields = {- referenceImage: { as: "urlArray", field: "reference_image_urls" },- referenceVideo: { as: "urlArray", field: "reference_video_urls" },- referenceAudio: { as: "urlArray", field: "reference_audio_urls" },-} as const;--function seedanceMapping(model: string, kieModel: string): GenerationWireMapping {- return {- capability: { module: SEEDANCE, name: model },- result: "video",- routes: [{ model: kieModel }],- fields: {- prompt: { as: "value", field: "prompt" },- ...referenceFields,- firstFrame: { as: "url", field: "first_frame_url" },- lastFrame: { as: "url", field: "last_frame_url" },- resolution: { as: "value", field: "resolution" },- aspectRatio: { as: "value", field: "aspect_ratio" },- duration: { as: "value", field: "duration" },- generateAudio: { as: "value", field: "generate_audio" },- webSearch: { as: "value", field: "web_search" },- },- };-}--const minimaxMapping: GenerationWireMapping = {- capability: { module: MINIMAX, name: "minimax-h3" },- result: "video",- routes: [- { model: "minimax-h3/image-to-video", whenPresent: ["lastFrame"] },- { model: "minimax-h3/image-to-video", whenPresent: ["firstFrame"] },- { model: "minimax-h3/reference-to-video", whenPresent: ["referenceImage"] },- { model: "minimax-h3/reference-to-video", whenPresent: ["referenceVideo"] },- { model: "minimax-h3/text-to-video" },- ],- fields: {- prompt: { as: "value", field: "prompt" },- duration: { as: "value", field: "duration" },- resolution: { as: "value", field: "resolution" },- aspectRatio: { as: "value", field: "aspect_ratio" },- ...referenceFields,- firstFrame: { as: "url", field: "first_frame_url" },- lastFrame: { as: "url", field: "last_frame_url" },- },-};--const grokVideoMapping: GenerationWireMapping = {- capability: { module: GROK, name: "grok-imagine-video" },- result: "video",- routes: [- { model: "grok-imagine/image-to-video", whenPresent: ["images"] },- { model: "grok-imagine/text-to-video" },- ],- fields: {- prompt: { as: "value", field: "prompt" },- aspectRatio: { as: "value", field: "aspect_ratio" },- resolution: { as: "value", field: "resolution" },- duration: { as: "string", field: "duration" },- images: { as: "urlArray", field: "image_urls" },- },- constants: { mode: "normal" },-};--const grokPreviewMapping: GenerationWireMapping = {- capability: { module: GROK, name: "grok-imagine-video-1.5-preview" },- result: "video",- routes: [{ model: "grok-imagine-video-1-5-preview" }],- fields: {- prompt: { as: "value", field: "prompt" },- aspectRatio: { as: "value", field: "aspect_ratio" },- resolution: { as: "value", field: "resolution" },- duration: { as: "value", field: "duration" },- images: { as: "urlArray", field: "image_urls" },- },-};--const gptImageMapping: GenerationWireMapping = {- capability: { module: GPT_IMAGE, name: "gpt-image-2" },- result: "image",- routes: [- { model: "gpt-image-2-image-to-image", whenPresent: ["images"] },- { model: "gpt-image-2-text-to-image" },- ],- fields: {- prompt: { as: "value", field: "prompt" },- aspectRatio: { as: "value", field: "aspect_ratio" },- resolution: { as: "value", field: "resolution" },- background: { as: "value", field: "background" },- images: { as: "urlArray", field: "input_urls" },- },-};--function nanoBananaMapping(model: string): GenerationWireMapping {- return {- capability: { module: NANO_BANANA, name: model },- result: "image",- routes: [{ model }],- fields: {- prompt: { as: "value", field: "prompt" },- /** KIE expects the key even with no input image. */- images: { as: "urlArray", field: "image_input", whenAbsent: [] },- aspectRatio: { as: "value", field: "aspect_ratio" },- resolution: { as: "value", field: "resolution" },- outputFormat: { as: "value", field: "output_format" },- },- };-}--const seedreamMapping: GenerationWireMapping = {- capability: { module: SEEDREAM, name: "seedream-5-lite" },- result: "image",- routes: [- { model: "seedream/5-lite-image-to-image", whenPresent: ["images"] },- { model: "seedream/5-lite-text-to-image" },- ],- fields: {- prompt: { as: "value", field: "prompt" },- aspectRatio: { as: "value", field: "aspect_ratio" },- quality: { as: "value", field: "quality" },- outputFormat: { as: "value", field: "output_format" },- nsfwCheck: { as: "value", field: "nsfw_checker" },- images: { as: "urlArray", field: "image_urls" },- },-};--export const kieModelCatalog: readonly GenerationWireMapping[] = [- seedanceMapping("seedance-2", "bytedance/seedance-2"),- seedanceMapping("seedance-2-fast", "bytedance/seedance-2-fast"),- seedanceMapping("seedance-2-mini", "bytedance/seedance-2-mini"),- {- ...seedanceMapping("seedance-2.5", "bytedance/seedance-2-5"),- // These are KIE output-envelope choices, not Seedance model inputs.- constants: { return_last_frame: false, output_format: "mp4" },- },- minimaxMapping,- grokVideoMapping,- grokPreviewMapping,- gptImageMapping,- nanoBananaMapping("nano-banana-2"),- nanoBananaMapping("nano-banana-pro"),- seedreamMapping,-];--function capabilityKey(ref: CapabilityRef): string {- return `${ref.module.name}@${ref.module.version}#${ref.name}`;-}--const catalogByCapability = new Map(kieModelCatalog.map((item) => [capabilityKey(item.capability), item]));--export function kieMappingForCapability(capability: CapabilityRef): GenerationWireMapping | undefined {- return catalogByCapability.get(capabilityKey(capability));-}--export function verifyKieModelCatalog(): void {- if (catalogByCapability.size !== kieModelCatalog.length) {- throw new Error("KIE model catalog repeats a capability");- }- kieModelCatalog.forEach((item) => {- if (item.capability.name.trim().length === 0) throw new Error("KIE model catalog contains an empty model");- });-}diff --git a/packages/provider-kie/src/provider.ts b/packages/provider-kie/src/provider.tsdeleted file mode 100644index 50b44512..00000000--- a/packages/provider-kie/src/provider.ts+++ /dev/null@@ -1,657 +0,0 @@-import { requestDeadline } from "@hypit/runtime-kit";-import type {- AsyncEndpoint,- EndpointPollContext,- EndpointPricingReader,- EndpointStartContext,- EndpointOutcome,-} from "@hypit/endpoint-kit";-import {- canonicalize,-} from "@hypit/protocol";-import type {- BlobRef,- CanonicalValue,- ResourceId,-} from "@hypit/protocol";-import {- defineEndpointPackage,- wakeAfter,-} from "@hypit/endpoint-kit";-import { credentialRef, isStreamingResourceStore } from "@hypit/runtime";-import type { ResourceStore, CredentialRef } from "@hypit/runtime";--import {- kieRouteForCapability,- kieRoutes,- verifyKieRoutes,-} from "./routes.js";-import type { KieTaskRequest } from "./routes.js";--export const kieProviderModuleRef = { name: "@hypit/provider-kie", version: "1" } as const;--type Fetch = typeof globalThis.fetch;--export type CreateKieProviderOptions = {- readonly instance?: string;- readonly pool?: string;- readonly apiBaseUrl?: string;- readonly uploadBaseUrl?: string;- readonly apiKey?: CredentialRef;- /** Total in-flight capacity shared by every KIE lane. */- readonly defaultConcurrency?: number;- /** Optional KIE lane limits keyed by capability name, for example seedance-2.5. */- readonly capabilityConcurrency?: Readonly<Record<string, number>>;- readonly pollIntervalMs?: number;- readonly actionLimits?: import("@hypit/endpoint-kit").EndpointActionLimits;- readonly requestTimeoutMs?: number;- readonly maxOperationMs?: number;- readonly maxArtifactBytes?: number;- readonly fetch?: Fetch;- readonly now?: () => number;-};--type KieHandle = {- readonly taskId: string;- readonly routeKey: string;- readonly startedAt: number;-};--class KieError extends Error {- readonly code: string;- readonly status: number | undefined;-- constructor(code: string, message: string, options: { readonly status?: number } = {}) {- super(message);- this.name = "KieError";- this.code = code;- this.status = options.status;- }-}--function assert(condition: unknown, message: string): asserts condition {- if (!condition) throw new Error(message);-}--function positiveInteger(value: number, subject: string): number {- assert(Number.isSafeInteger(value) && value > 0, `${subject} must be a positive safe integer`);- return value;-}--function nonNegativeInteger(value: number, subject: string): number {- assert(Number.isSafeInteger(value) && value >= 0, `${subject} must be a non-negative safe integer`);- return value;-}--function baseUrl(value: string, subject: string): string {- const url = new URL(value);- assert(url.protocol === "https:" || url.hostname === "localhost", `${subject} must use HTTPS or localhost`);- return url.href.replace(/\/$/u, "");-}--function object(value: unknown, subject: string): Record<string, unknown> {- if (value === null || typeof value !== "object" || Array.isArray(value)) throw new KieError("KIE_INVALID_RESPONSE", `${subject} is not an object`);- return value as Record<string, unknown>;-}--function secret(context: EndpointStartContext | EndpointPollContext): string {- const value = context.credentials.apiKey?.secret;- if (value === undefined || value.length === 0) throw new KieError("KIE_MISSING_CREDENTIAL", "KIE API key is unavailable");- return value;-}--function mediaExtension(mediaType: string): string {- const known: Readonly<Record<string, string>> = {- "image/jpeg": "jpg",- "image/png": "png",- "image/webp": "webp",- "video/mp4": "mp4",- "video/quicktime": "mov",- "audio/mpeg": "mp3",- "audio/wav": "wav",- "audio/x-wav": "wav",- };- return known[mediaType] ?? "bin";-}--type KieClientOptions = {- readonly apiBaseUrl: string;- readonly uploadBaseUrl: string;- readonly requestTimeoutMs: number;- readonly maxArtifactBytes: number;- readonly fetch: Fetch;-};--class KieClient {- readonly #options: KieClientOptions;- readonly #pricingRecords = new Map<string, Promise<readonly Record<string, unknown>[]>>();-- constructor(options: KieClientOptions) {- this.#options = options;- }-- async #open(url: string, init: RequestInit): Promise<{- readonly response: Response;- readonly wait: <T>(work: Promise<T>) => Promise<T>;- readonly finish: () => void;- }> {- const deadline = requestDeadline(this.#options.requestTimeoutMs, () => new KieError("KIE_REQUEST_TIMEOUT", "KIE request timed out"));- const { wait, finish } = deadline;- try {- const response = await wait(this.#options.fetch(url, { ...init, signal: deadline.signal }));- return { response, wait, finish };- } catch (error) {- finish();- if (error instanceof KieError) throw error;- throw new KieError("KIE_NETWORK_ERROR", error instanceof Error ? error.message : "KIE network request failed");- }- }-- async #json(url: string, init: RequestInit): Promise<Record<string, unknown>> {- const opened = await this.#open(url, init);- try {- const response = opened.response;- if (!response.ok) {- throw new KieError("KIE_HTTP_ERROR", `KIE returned HTTP ${response.status}`, { status: response.status });- }- const limit = 2_000_000;- const reader = response.body?.getReader();- let text: string;- if (reader === undefined) {- const bytes = new Uint8Array(await opened.wait(response.arrayBuffer()));- if (bytes.byteLength > limit) throw new KieError("KIE_RESPONSE_TOO_LARGE", "KIE JSON response is too large");- text = new TextDecoder().decode(bytes);- } else {- const decoder = new TextDecoder();- let size = 0;- let decoded = "";- try {- while (true) {- const item = await opened.wait(reader.read());- if (item.done) break;- size += item.value.byteLength;- if (size > limit) {- await reader.cancel();- throw new KieError("KIE_RESPONSE_TOO_LARGE", "KIE JSON response is too large");- }- decoded += decoder.decode(item.value, { stream: true });- }- text = decoded + decoder.decode();- } finally {- reader.releaseLock();- }- }- try {- return object(JSON.parse(text), "KIE response");- } catch (error) {- if (error instanceof KieError) throw error;- throw new KieError("KIE_INVALID_JSON", "KIE returned invalid JSON");- }- } catch (error) {- if (error instanceof KieError) throw error;- throw new KieError("KIE_NETWORK_ERROR", error instanceof Error ? error.message : "KIE network request failed");- } finally {- opened.finish();- }- }-- get pricingSource(): string {- return `${this.#options.apiBaseUrl}/client/v1/model-pricing/page`;- }-- async pricingRecords(model: string): Promise<readonly Record<string, unknown>[]> {- let pending = this.#pricingRecords.get(model);- if (pending === undefined) {- pending = (async () => {- const records: Record<string, unknown>[] = [];- let page = 1;- let pages = 1;- while (page <= pages) {- const response = await this.#json(this.pricingSource, {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({ pageNum: page, pageSize: 100, modelDescription: model, interfaceType: "" }),- });- assert(response.code === 200, "KIE pricing service rejected the rate-card request");- const data = object(response.data, "KIE pricing data");- assert(Array.isArray(data.records), "KIE pricing data contains no records array");- for (const value of data.records) records.push(object(value, "KIE pricing record"));- const reportedPages = data.pages;- assert(typeof reportedPages === "number" && Number.isSafeInteger(reportedPages)- && reportedPages >= 0 && reportedPages <= 100, "KIE pricing page count is invalid");- pages = reportedPages;- page += 1;- }- return records;- })();- this.#pricingRecords.set(model, pending);- }- return await pending;- }-- async upload(artifact: BlobRef, resources: ResourceStore, apiKey: string): Promise<string> {- if (artifact.size > this.#options.maxArtifactBytes) {- throw new KieError("KIE_ARTIFACT_TOO_LARGE", `Artifact ${artifact.resource} exceeds the configured KIE upload limit`);- }- const fileName = `${artifact.resource}.${mediaExtension(artifact.mediaType)}`;- const boundary = `hypit-${artifact.resource}`;- const encode = (value: string) => new TextEncoder().encode(value);- const fileHead = encode(- `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${fileName}"\r\n`- + `Content-Type: ${artifact.mediaType}\r\n\r\n`,- );- const fields = encode(- `\r\n--${boundary}\r\nContent-Disposition: form-data; name="uploadPath"\r\n\r\nhypit/resources`- + `\r\n--${boundary}\r\nContent-Disposition: form-data; name="fileName"\r\n\r\n${fileName}`- + `\r\n--${boundary}--\r\n`,- );- const source = isStreamingResourceStore(resources)- ? await resources.open(artifact.resource)- : await resources.get(artifact.resource).then((bytes) => bytes === undefined- ? undefined- : (async function* () { yield bytes; })());- if (source === undefined) {- throw new KieError("KIE_ARTIFACT_MISSING", `Artifact ${artifact.resource} is unavailable`);- }- const maximum = this.#options.maxArtifactBytes;- const multipart = (async function* () {- yield fileHead;- let size = 0;- for await (const chunk of source) {- size += chunk.byteLength;- if (size > artifact.size || size > maximum) {- throw new KieError("KIE_ARTIFACT_SIZE_MISMATCH", `Artifact ${artifact.resource} size differs`);- }- yield chunk;- }- if (size !== artifact.size) {- throw new KieError("KIE_ARTIFACT_SIZE_MISMATCH", `Artifact ${artifact.resource} size differs`);- }- yield fields;- })();- let response: Record<string, unknown>;- try {- response = await this.#json(`${this.#options.uploadBaseUrl}/api/file-stream-upload`, {- method: "POST",- headers: {- authorization: `Bearer ${apiKey}`,- "content-type": `multipart/form-data; boundary=${boundary}`,- "content-length": String(fileHead.byteLength + artifact.size + fields.byteLength),- },- body: multipart as unknown as BodyInit,- duplex: "half",- } as RequestInit & { duplex: "half" });- } catch (error) {- if (error instanceof KieError) {- throw new KieError("KIE_UPLOAD_FAILED", error.message, {- ...(error.status === undefined ? {} : { status: error.status }),- });- }- throw error;- }- const data = object(response.data, "KIE upload data");- const url = typeof data.downloadUrl === "string" ? data.downloadUrl- : typeof data.fileUrl === "string" ? data.fileUrl : undefined;- if (url === undefined || new URL(url).protocol !== "https:") {- throw new KieError("KIE_UPLOAD_INVALID", "KIE upload returned no HTTPS URL");- }- return url;- }-- async createTask(task: KieTaskRequest, apiKey: string): Promise<string> {- let response: Record<string, unknown>;- try {- response = await this.#json(`${this.#options.apiBaseUrl}/api/v1/jobs/createTask`, {- method: "POST",- headers: {- authorization: `Bearer ${apiKey}`,- "content-type": "application/json",- },- body: JSON.stringify({ model: task.model, input: task.input }),- });- if (response.code !== undefined && response.code !== 200) {- const vendorMessage = typeof response.msg === "string" && response.msg.length > 0- ? response.msg.slice(0, 500) : "KIE rejected createTask";- throw new KieError(- "KIE_SUBMISSION_REJECTED",- `${vendorMessage} (KIE code ${String(response.code).slice(0, 100)})`,- );- }- } catch (error) {- if (error instanceof KieError) {- if (error.code === "KIE_SUBMISSION_REJECTED") throw error;- if (error.status === 429) {- throw new KieError("KIE_RATE_LIMITED", "KIE createTask was rate limited", { status: 429 });- }- if (error.status !== undefined && error.status >= 400 && error.status < 500) {- throw new KieError("KIE_SUBMISSION_REJECTED", error.message, { status: error.status });- }- throw new KieError("KIE_SUBMISSION_FAILED", error.message,- error.status === undefined ? {} : { status: error.status });- }- throw error;- }- const data = object(response.data, "KIE createTask data");- if (typeof data.taskId !== "string" || data.taskId.length === 0) {- throw new KieError("KIE_SUBMISSION_INVALID", "KIE createTask returned no taskId");- }- return data.taskId;- }-- async taskInfo(taskId: string, apiKey: string): Promise<Record<string, unknown>> {- const response = await this.#json(- `${this.#options.apiBaseUrl}/api/v1/jobs/recordInfo?taskId=${encodeURIComponent(taskId)}`,- { method: "GET", headers: { authorization: `Bearer ${apiKey}` } },- );- return object(response.data, "KIE task data");- }-- async #downloadUrl(original: string, apiKey: string): Promise<string> {- const response = await this.#json(`${this.#options.apiBaseUrl}/api/v1/common/download-url`, {- method: "POST",- headers: {- authorization: `Bearer ${apiKey}`,- "content-type": "application/json",- },- body: JSON.stringify({ url: original }),- });- if (typeof response.data !== "string" || new URL(response.data).protocol !== "https:") {- throw new KieError("KIE_DOWNLOAD_URL_INVALID", "KIE returned no HTTPS download URL");- }- return response.data;- }-- async download(original: string, expected: "image" | "video", apiKey: string): Promise<{- chunks: AsyncIterable<Uint8Array>;- mediaType: string;- }> {- const url = await this.#downloadUrl(original, apiKey);- const opened = await this.#open(url, { method: "GET" });- let handedOff = false;- try {- const response = opened.response;- if (!response.ok) throw new KieError("KIE_DOWNLOAD_FAILED", `KIE artifact download returned HTTP ${response.status}`);- const declared = Number(response.headers.get("content-length"));- if (Number.isFinite(declared) && declared > this.#options.maxArtifactBytes) {- throw new KieError("KIE_ARTIFACT_TOO_LARGE", "KIE result exceeds the configured artifact limit");- }- const header = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();- const fallback = expected === "image" ? "image/png" : "video/mp4";- const mediaType = header === undefined || header === "application/octet-stream" ? fallback : header;- if (!mediaType.startsWith(`${expected}/`)) {- throw new KieError("KIE_RESULT_MEDIA_MISMATCH", `KIE returned ${mediaType} for ${expected} generation`);- }- const maximum = this.#options.maxArtifactBytes;- const finish = opened.finish;- const chunks = response.body === null- ? (async function* () {- try {- const bytes = new Uint8Array(await opened.wait(response.arrayBuffer()));- if (bytes.byteLength > maximum) throw new KieError("KIE_ARTIFACT_TOO_LARGE", "KIE result is too large");- yield bytes;- } catch (error) {- if (error instanceof KieError) throw error;- throw new KieError("KIE_NETWORK_ERROR", error instanceof Error ? error.message : "KIE result download failed");- } finally {- finish();- }- })()- : (async function* () {- const reader = response.body!.getReader();- let size = 0;- try {- while (true) {- const item = await opened.wait(reader.read());- if (item.done) break;- size += item.value.byteLength;- if (size > maximum) {- await reader.cancel();- throw new KieError("KIE_ARTIFACT_TOO_LARGE", "KIE result is too large");- }- yield item.value;- }- } catch (error) {- if (error instanceof KieError) throw error;- throw new KieError("KIE_NETWORK_ERROR", error instanceof Error ? error.message : "KIE result download failed");- } finally {- reader.releaseLock();- finish();- }- })();- handedOff = true;- return { chunks, mediaType };- } finally {- if (!handedOff) opened.finish();- }- }-}--function kiePricingReader(client: KieClient): EndpointPricingReader {- return async ({ request }) => {- const route = kieRouteForCapability(request.capability);- if (route === undefined) return [];- const selectedModel = route.selectModel(request);- const records = await client.pricingRecords(selectedModel);- if (records.length === 0) return [];- const lines = records.map((record) => {- if (typeof record.modelDescription !== "string" || typeof record.creditUnit !== "string") return undefined;- const value = (item: unknown) => typeof item === "string" || typeof item === "number" ? String(item) : undefined;- const usd = value(record.usdPrice);- const credits = value(record.creditPrice);- if (usd === undefined && credits === undefined) return undefined;- const amounts = [usd === undefined ? undefined : `USD ${usd}`, credits === undefined ? undefined : `${credits} credits`];- return `${record.modelDescription}: ${amounts.filter((item) => item !== undefined).join("; ")} (${record.creditUnit})`;- });- return [{- source: client.pricingSource,- data: canonicalize({ model: selectedModel, records }),- ...(lines.every((line) => line !== undefined) ? { summary: lines.join("\n") } : {}),- }];- };-}--function resultUrls(data: Record<string, unknown>): string[] {- let result: unknown = data.resultJson;- if (typeof result === "string") {- try { result = JSON.parse(result); } catch { throw new KieError("KIE_RESULT_INVALID", "KIE resultJson is invalid JSON"); }- }- const value = object(result, "KIE resultJson");- const candidate = value.resultUrls ?? value.result_urls ?? value.urls;- if (!Array.isArray(candidate) || candidate.length === 0 || candidate.some((item) => typeof item !== "string")) {- throw new KieError("KIE_RESULT_MISSING", "KIE successful task returned no result URLs");- }- return candidate.map((item) => {- const url = new URL(item as string);- if (url.protocol !== "https:") throw new KieError("KIE_RESULT_URL_INVALID", "KIE result URL must use HTTPS");- return url.href;- });-}--function readHandle(value: CanonicalValue | undefined, context: EndpointPollContext): KieHandle {- if (value === undefined) {- throw new KieError(- "KIE_SUBMISSION_HANDLE_MISSING",- "KIE Operation has no task handle",- );- }- const handle = object(value, "KIE handle") as unknown as KieHandle;- const route = kieRouteForCapability(context.need.capability);- if (typeof handle.taskId !== "string"- || route === undefined- || handle.routeKey !== route.key- || !Number.isSafeInteger(handle.startedAt)) {- throw new KieError("KIE_HANDLE_INVALID", "KIE handle does not match the current Need");- }- return handle;-}--function endpoint(options: {- readonly client: KieClient;- readonly pollIntervalMs: number;- readonly maxOperationMs: number;- readonly now: () => number;-}): AsyncEndpoint {- const failure = (error: unknown): EndpointOutcome => {- const known = error instanceof KieError ? error : new KieError("KIE_INTERNAL_ERROR", error instanceof Error ? error.message : String(error));- return {- status: "failed",- failure: {- code: known.code,- message: known.message,- },- };- };- return {- async start(context) {- try {- const route = kieRouteForCapability(context.need.capability);- if (route === undefined) throw new KieError("KIE_UNSUPPORTED_CAPABILITY", "KIE does not implement this exact capability");- const key = secret(context);- const uploaded = new Map<ResourceId, Promise<string>>();- const resolve = (artifact: BlobRef): Promise<string> => {- const existing = uploaded.get(artifact.resource);- if (existing !== undefined) return existing;- const promise = options.client.upload(artifact, context.resources, key);- uploaded.set(artifact.resource, promise);- return promise;- };- const task = await route.compile(context.need.constraints, resolve);- const taskId = await options.client.createTask(task, key);- const handle: KieHandle = {- taskId,- routeKey: route.key,- startedAt: options.now(),- };- const receipt = { id: taskId };- await context.checkpoint?.({ handle: canonicalize(handle), receipt });- return { ...wakeAfter(canonicalize(handle), options.pollIntervalMs, options.now(), { phase: "submitted" }), receipt };- } catch (error) {- return failure(error);- }- },- async poll(context) {- let handle: KieHandle;- try {- handle = readHandle(context.handle, context);- } catch (error) {- throw error;- }- try {- const route = kieRouteForCapability(context.need.capability);- if (route === undefined || route.key !== handle.routeKey) {- throw new KieError("KIE_HANDLE_INVALID", "KIE handle capability differs");- }- if (options.now() - handle.startedAt >= options.maxOperationMs) {- throw new KieError("KIE_OPERATION_TIMEOUT", "KIE task exceeded its operation deadline");- }- const key = secret(context);- const data = await options.client.taskInfo(handle.taskId, key);- const state = data.state;- if (state === "waiting" || state === "queuing" || state === "generating") {- return wakeAfter(canonicalize(handle), options.pollIntervalMs, options.now(), {- phase: state,- });- }- if (state === "fail") {- const vendorCode = typeof data.failCode === "string" && data.failCode.length > 0 ? data.failCode : "unknown";- const vendorMessage = typeof data.failMsg === "string" && data.failMsg.length > 0- ? data.failMsg.slice(0, 500) : "KIE task failed";- throw new KieError("KIE_TASK_FAILED", `${vendorMessage} (${vendorCode})`);- }- if (state !== "success") throw new KieError("KIE_TASK_STATE_INVALID", "KIE returned an unknown task state");- const urls = resultUrls(data);- if (urls.length > route.maxResults) throw new KieError("KIE_RESULT_COUNT_EXCEEDED", "KIE returned too many result artifacts");- return { status: "ready", handle: canonicalize({ ...handle, urls }), receipt: { id: handle.taskId } };- } catch (error) {- return failure(error);- }- },- async collect(context) {- readHandle(context.handle, context);- const route = kieRouteForCapability(context.need.capability)!;- const raw = object(context.handle, "KIE handle");- const urls = raw.urls;- if (!Array.isArray(urls) || !urls.every((url) => typeof url === "string")) throw new KieError("KIE_HANDLE_INVALID", "KIE collection has no artifact addresses");- const key = secret(context);- const artifacts: BlobRef[] = [];- for (const url of urls) {- const downloaded = await options.client.download(url, route.media, key);- if (isStreamingResourceStore(context.resources)) {- artifacts.push(await context.resources.putStream(downloaded.chunks, downloaded.mediaType));- } else {- const chunks: Uint8Array[] = [];- let size = 0;- for await (const chunk of downloaded.chunks) {- chunks.push(Uint8Array.from(chunk));- size += chunk.byteLength;- }- const bytes = new Uint8Array(size);- let offset = 0;- for (const chunk of chunks) {- bytes.set(chunk, offset);- offset += chunk.byteLength;- }- artifacts.push(await context.resources.put(bytes, downloaded.mediaType));- }- }- const result = route.packageResult(artifacts);- return {- status: "completed",- result: { value: result },- };- },-- };-}--export function createKieProvider(config: CreateKieProviderOptions) {- verifyKieRoutes();- const capacityNames = new Set(kieRoutes.map((route) => route.capability.name));- const capabilityConcurrency = Object.fromEntries(Object.entries(config.capabilityConcurrency ?? {}).map(([capability, limit]) => {- if (!capacityNames.has(capability)) throw new Error(`unknown KIE capacity ${capability}`);- return [capability, positiveInteger(limit, `${capability} capabilityConcurrency`)];- }));- const apiBaseUrl = baseUrl(config.apiBaseUrl ?? "https://api.kie.ai", "apiBaseUrl");- const uploadBaseUrl = baseUrl(config.uploadBaseUrl ?? "https://kieai.redpandaai.co", "uploadBaseUrl");- const pollIntervalMs = nonNegativeInteger(config.pollIntervalMs ?? 3_000, "pollIntervalMs");- const requestTimeoutMs = positiveInteger(config.requestTimeoutMs ?? 30_000, "requestTimeoutMs");- const maxOperationMs = positiveInteger(config.maxOperationMs ?? 20 * 60_000, "maxOperationMs");- const maxArtifactBytes = positiveInteger(config.maxArtifactBytes ?? 512 * 1024 * 1024, "maxArtifactBytes");- const now = config.now ?? Date.now;- const client = new KieClient({- apiBaseUrl,- uploadBaseUrl,- requestTimeoutMs,- maxArtifactBytes,- fetch: config.fetch ?? globalThis.fetch,- });- const providerEndpoint = endpoint({- client,- pollIntervalMs,- maxOperationMs,- now,- });- return defineEndpointPackage({- module: kieProviderModuleRef,- facet: "market",- instance: config.instance ?? "kie.default",- pool: config.pool ?? config.instance ?? "kie.default",- pricing: { kind: "page", url: "https://kie.ai/pricing" },- readPricing: kiePricingReader(client),- credentials: { apiKey: config.apiKey ?? credentialRef("env", "KIE_API_KEY") },- credentialInputs: { apiKey: { label: "KIE API key" } },- defaultConcurrency: config.defaultConcurrency ?? 10,- ...(config.actionLimits === undefined ? {} : { actionLimits: config.actionLimits }),- capabilities: kieRoutes.map((route) => ({- capability: route.capability,- returns: route.returns,- capacity: route.capability.name,- ...(capabilityConcurrency[route.capability.name] === undefined- ? {}- : { maxConcurrency: capabilityConcurrency[route.capability.name] }),- lifecycle: "asynchronous" as const,- endpoint: providerEndpoint,- ...(route.supports === undefined ? {} : { supports: route.supports }),- })),- });-}diff --git a/packages/provider-kie/src/routes.ts b/packages/provider-kie/src/routes.tsdeleted file mode 100644index fd6d69c1..00000000--- a/packages/provider-kie/src/routes.ts+++ /dev/null@@ -1,150 +0,0 @@-import { artifactTypes } from "@hypit/artifact";-import {- assertBackgroundRemovalRequest,- backgroundRemovalCapabilities,-} from "@hypit/background-removal";-import type { BackgroundRemovalRequest } from "@hypit/background-removal";-import {- compileWireRequest,- generationTypes,- selectWireModelForRequest,- sealGeneratedImageSet,- sealGeneratedVideoSet,-} from "@hypit/generation";-import type { GenerationArtifactUrlResolver, GenerationRequest, GenerationWireMapping } from "@hypit/generation";-import { canonicalize } from "@hypit/protocol";-import type { BlobRef, CanonicalValue, CapabilityRef, StoredValue, TypeRef } from "@hypit/protocol";-import type { EndpointRequest, EndpointSupport } from "@hypit/endpoint-kit";--import { kieModelCatalog, verifyKieModelCatalog } from "./mapping.js";--export type KieTaskRequest = {- readonly model: string;- readonly input: CanonicalValue;-};--export type KieRoute = {- readonly key: string;- readonly capability: CapabilityRef;- readonly returns: TypeRef;- readonly media: "image" | "video";- readonly maxResults: number;- readonly supports?: (request: EndpointRequest) => EndpointSupport;- /** Select the same service model before or during execution, without resolving Resource bytes. */- readonly selectModel: (request: EndpointRequest) => string;- readonly compile: (- constraints: CanonicalValue,- resolve: GenerationArtifactUrlResolver,- ) => Promise<KieTaskRequest>;- readonly packageResult: (artifacts: readonly BlobRef[]) => StoredValue;-};--function capabilityKey(ref: CapabilityRef): string {- return `${ref.module.name}@${ref.module.version}#${ref.name}`;-}--function scalar(request: GenerationRequest, port: string): string | number | boolean | undefined {- const value = request.ports[port]?.[0];- return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? value : undefined;-}--/** Returns the KIE-wire limitation that rejects an otherwise valid model request. */-function kieGenerationRejection(mapping: GenerationWireMapping, request: GenerationRequest): string | undefined {- if (mapping.capability.module.name === "@hypit/gpt-image" && mapping.capability.name === "gpt-image-2") {- const ratio = scalar(request, "aspectRatio");- const resolution = scalar(request, "resolution");- const background = scalar(request, "background");- const unsupportedRatios = resolution === "2K"- ? ["5:4", "4:5", "3:1", "1:3", "9:21"]- : resolution === "4K" ? ["3:1", "1:3", "9:21"] : [];- if (unsupportedRatios.includes(String(ratio))) {- return `KIE GPT Image 2 does not accept ${String(ratio)} at ${String(resolution)}`;- }- if (background !== undefined && resolution !== "1K") {- return `KIE GPT Image 2 accepts the background option only at 1K; omit it at ${String(resolution)}`;- }- }- if (mapping.capability.module.name === "@hypit/grok-imagine"- && (mapping.capability.name === "grok-imagine-video"- || mapping.capability.name === "grok-imagine-video-1.5-preview")- && scalar(request, "resolution") === "1080p"- && (request.ports.images?.length ?? 0) > 1) {- return `KIE ${mapping.capability.name} accepts at most one reference image at 1080p`;- }- return undefined;-}--const kieGenerationMappings: readonly (GenerationWireMapping & { readonly result: "image" | "video" })[] = kieModelCatalog.map((mapping) => {- if (mapping.result === "audio") {- throw new Error(`KIE route ${mapping.capability.name} declares unsupported audio output`);- }- return mapping as GenerationWireMapping & { readonly result: "image" | "video" };-});--const generationRoutes: readonly KieRoute[] = kieGenerationMappings.map((mapping) => ({- key: capabilityKey(mapping.capability),- capability: mapping.capability,- returns: mapping.result === "image" ? generationTypes.imageSet : generationTypes.videoSet,- media: mapping.result,- maxResults: mapping.result === "image" ? 16 : 8,- supports: (need: EndpointRequest) => {- const reason = kieGenerationRejection(mapping, need.constraints as unknown as GenerationRequest);- return reason === undefined ? { status: "supported" } : { status: "unsupported", reason };- },- selectModel: (need) => selectWireModelForRequest(- mapping,- need.constraints as unknown as GenerationRequest,- need.pendingInputs?.map((input) => input.input),- ),- compile: async (constraints, resolve) => {- const request = constraints as unknown as GenerationRequest;- const rejection = kieGenerationRejection(mapping, request);- if (rejection !== undefined) throw new Error(rejection);- return await compileWireRequest(mapping, request, resolve);- },- packageResult: (artifacts) => ({- kind: "inline",- value: canonicalize(mapping.result === "image"- ? sealGeneratedImageSet({ images: artifacts })- : sealGeneratedVideoSet({ videos: artifacts })),- }),-}));--const backgroundRemovalRoute: KieRoute = {- key: capabilityKey(backgroundRemovalCapabilities.remove),- capability: backgroundRemovalCapabilities.remove,- returns: artifactTypes.blob,- media: "image",- maxResults: 1,- selectModel: () => "recraft/remove-background",- compile: async (constraints, resolve) => {- const request = constraints as unknown as BackgroundRemovalRequest;- assertBackgroundRemovalRequest(request);- return {- model: "recraft/remove-background",- input: canonicalize({ image: await resolve(request.source) }),- };- },- packageResult: (artifacts) => {- if (artifacts.length !== 1 || artifacts[0] === undefined) {- throw new Error("KIE Background Removal requires exactly one image result");- }- return artifacts[0];- },-};--export const kieRoutes: readonly KieRoute[] = [...generationRoutes, backgroundRemovalRoute];-const routeByCapability = new Map(kieRoutes.map((route) => [route.key, route]));--export function kieRouteForCapability(capability: CapabilityRef): KieRoute | undefined {- return routeByCapability.get(capabilityKey(capability));-}--export function verifyKieRoutes(): void {- verifyKieModelCatalog();- if (routeByCapability.size !== kieRoutes.length) throw new Error("KIE routes repeat a capability");- kieRoutes.forEach((route) => {- if (route.key !== capabilityKey(route.capability)) throw new Error("KIE route key differs from its capability");- if (!Number.isSafeInteger(route.maxResults) || route.maxResults <= 0) throw new Error("KIE route result limit is invalid");- });-}diff --git a/packages/provider-kie/test/models.test.ts b/packages/provider-kie/test/models.test.tsdeleted file mode 100644index 738d21e0..00000000--- a/packages/provider-kie/test/models.test.ts+++ /dev/null@@ -1,267 +0,0 @@-import assert from "node:assert/strict";-import test from "node:test";-import { MemoryResourceStore } from "@hypit/driver-node";-import type { EndpointSupport } from "@hypit/endpoint-kit";-import {- assertMappingCoversPorts,- compileWireRequest,-} from "@hypit/generation";-import type { GenerationPortTable } from "@hypit/generation";-import {- gptImageDefinition,- sealGptImage2Request,-} from "@hypit/gpt-image";-import {- grokImagineDefinition,- sealGrokImagineRequest,-} from "@hypit/grok-imagine";-import {- minimaxH3Definition,- sealMinimaxH3Request,-} from "@hypit/minimax-h3";-import {- nanoBananaDefinition,- sealNanoBananaRequest,-} from "@hypit/nano-banana";-import { kieModelCatalog } from "@hypit/provider-kie";-import { seedanceDefinition, sealSeedanceRequest } from "@hypit/seedance";-import {- seedreamDefinition,- sealSeedreamRequest,-} from "@hypit/seedream";-import type { CanonicalValue, CapabilityRef } from "@hypit/protocol";-import { kieRoutes } from "../src/routes.js";--/**- * Every exact model this repository ships, paired with the Capability it publishes.- * The Capability carries the module version, so a mapping written for an older model- * version fails here rather than at submission time.- */-const modelCapabilities: readonly { readonly ports: GenerationPortTable; readonly capability: CapabilityRef }[] = [- seedanceDefinition, minimaxH3Definition, grokImagineDefinition,- gptImageDefinition, nanoBananaDefinition, seedreamDefinition,-].flatMap((definition) => Object.values(definition.endpoints)- .map((endpoint) => ({ ports: endpoint.ports, capability: endpoint.capability })));--function capabilityKey(ref: CapabilityRef): string {- return `${ref.module.name}@${ref.module.version}#${ref.name}`;-}--const upload = async (artifact: { readonly resource: string }) => `https://upload.test/${artifact.resource}`;--/** Every declared model port must have an explicit KIE wire mapping. */-test("the KIE mapping covers every port every exact model declares", () => {- assert.equal(modelCapabilities.length, kieModelCatalog.length);- const mappings = new Map(kieModelCatalog.map((item) => [capabilityKey(item.capability), item]));- for (const { ports, capability } of modelCapabilities) {- // The full Capability includes the model module version.- const mapping = mappings.get(capabilityKey(capability));- assert.ok(mapping, `KIE declares no mapping for ${capabilityKey(capability)}`);- assertMappingCoversPorts(ports, mapping);- }-});--test("all eleven exact capabilities route to their documented KIE model slug", async () => {- const store = new MemoryResourceStore();- const image = await store.put(new Uint8Array([1]), "image/png");- const video = await store.put(new Uint8Array([2]), "video/mp4");- const audio = await store.put(new Uint8Array([3]), "audio/wav");- const seedance = (model: "seedance-2" | "seedance-2-fast" | "seedance-2-mini" | "seedance-2.5") => sealSeedanceRequest(model, {- prompt: ["A studio shot."],- resolution: [model === "seedance-2" ? "1080p" : "720p"],- aspectRatio: ["16:9"],- duration: [5],- generateAudio: [false],- webSearch: [false],- });- const commonGrok = {- prompt: ["A studio shot."],- aspectRatio: ["16:9"],- resolution: ["480p"],- duration: [6],- } as const;- const commonSeedream = {- prompt: ["A studio portrait."],- aspectRatio: ["1:1"],- quality: ["basic"],- outputFormat: ["png"],- nsfwCheck: [true],- };- const cases = [- ["seedance-2", seedance("seedance-2"), "bytedance/seedance-2"],- ["seedance-2-fast", seedance("seedance-2-fast"), "bytedance/seedance-2-fast"],- ["seedance-2-mini", seedance("seedance-2-mini"), "bytedance/seedance-2-mini"],- ["seedance-2.5", seedance("seedance-2.5"), "bytedance/seedance-2-5"],- ["minimax-h3", sealMinimaxH3Request({- prompt: ["A studio shot."],- duration: [6],- aspectRatio: ["16:9"],- }), "minimax-h3/text-to-video"],- ["minimax-h3", sealMinimaxH3Request({- prompt: ["A studio shot."],- duration: [6],- firstFrame: [{ role: "image", artifact: image }],- }), "minimax-h3/image-to-video"],- ["minimax-h3", sealMinimaxH3Request({- prompt: ["A studio shot."],- duration: [6],- referenceImage: [{ role: "image", artifact: image }],- referenceVideo: [{ role: "video", artifact: video }],- referenceAudio: [{ role: "audio", artifact: audio }],- }), "minimax-h3/reference-to-video"],- ["grok-imagine-video", sealGrokImagineRequest("grok-imagine-video", commonGrok), "grok-imagine/text-to-video"],- ["grok-imagine-video", sealGrokImagineRequest("grok-imagine-video", {- ...commonGrok,- images: [{ role: "image", artifact: image }],- }), "grok-imagine/image-to-video"],- ["grok-imagine-video-1.5-preview",- sealGrokImagineRequest("grok-imagine-video-1.5-preview", commonGrok),- "grok-imagine-video-1-5-preview"],- ["gpt-image-2", sealGptImage2Request({- prompt: ["A studio portrait."],- aspectRatio: ["auto"],- resolution: ["1K"],- }), "gpt-image-2-text-to-image"],- ["gpt-image-2", sealGptImage2Request({- prompt: ["A studio portrait."],- aspectRatio: ["auto"],- resolution: ["1K"],- images: [{ role: "image", artifact: image }],- }), "gpt-image-2-image-to-image"],- ["nano-banana-2", sealNanoBananaRequest("nano-banana-2", {- prompt: ["A studio portrait."],- aspectRatio: ["auto"],- resolution: ["2K"],- outputFormat: ["jpg"],- }), "nano-banana-2"],- ["nano-banana-pro", sealNanoBananaRequest("nano-banana-pro", {- prompt: ["A studio portrait."],- images: [{ role: "image", artifact: image }],- aspectRatio: ["1:1"],- resolution: ["1K"],- outputFormat: ["png"],- }), "nano-banana-pro"],- ["seedream-5-lite", sealSeedreamRequest(commonSeedream), "seedream/5-lite-text-to-image"],- ["seedream-5-lite", sealSeedreamRequest({- ...commonSeedream,- images: [{ role: "image", artifact: image }],- }), "seedream/5-lite-image-to-image"],- ] as const;- for (const [model, request, expectedModel] of cases) {- const mapping = kieModelCatalog.find((candidate) => candidate.capability.name === model);- assert.ok(mapping, model);- const task = await compileWireRequest(mapping, request, upload);- assert.equal(task.model, expectedModel, `${model} -> ${expectedModel}`);- }-});--test("Seedance 2.5 maps its exact request without leaking KIE envelope controls into the model", async () => {- const request = sealSeedanceRequest("seedance-2.5", {- prompt: ["A car crosses the desert."],- resolution: ["720p"],- aspectRatio: ["21:9"],- duration: [30],- generateAudio: [true],- webSearch: [false],- });- const mapping = kieModelCatalog.find((item) => item.capability.name === "seedance-2.5");- assert.ok(mapping);- const task = await compileWireRequest(mapping, request, upload);- assert.equal(task.model, "bytedance/seedance-2-5");- assert.deepEqual(task.input, {- prompt: "A car crosses the desert.",- resolution: "720p",- aspect_ratio: "21:9",- duration: 30,- generate_audio: true,- web_search: false,- return_last_frame: false,- output_format: "mp4",- });-});--test("KIE maps GPT Image background and applies its measured request combinations", async () => {- const route = kieRoutes.find((item) => item.capability.name === "gpt-image-2");- assert.ok(route);- const request = sealGptImage2Request({- prompt: ["A product cutout."],- aspectRatio: ["1:1"],- resolution: ["1K"],- background: ["transparent"],- });- const task = await route.compile(request as unknown as CanonicalValue, upload);- assert.deepEqual(task.input, {- prompt: "A product cutout.",- aspect_ratio: "1:1",- resolution: "1K",- background: "transparent",- });-- for (const unsupported of [- sealGptImage2Request({- prompt: ["A product cutout."], aspectRatio: ["1:1"], resolution: ["2K"],- background: ["opaque"],- }),- sealGptImage2Request({- prompt: ["A portrait."], aspectRatio: ["5:4"], resolution: ["2K"],- }),- sealGptImage2Request({- prompt: ["A portrait."], aspectRatio: ["3:1"], resolution: ["4K"],- }),- ]) {- const support: EndpointSupport | undefined = route.supports?.({- capability: route.capability,- returns: route.returns,- constraints: unsupported as unknown as CanonicalValue,- });- assert.equal(support?.status, "unsupported");- assert.match(support?.status === "unsupported" ? support.reason : "", /KIE GPT Image 2/u);- }-- for (const supported of [- sealGptImage2Request({- prompt: ["A portrait."], aspectRatio: ["auto"], resolution: ["4K"],- }),- sealGptImage2Request({- prompt: ["A portrait."], aspectRatio: ["1:1"], resolution: ["4K"],- }),- sealGptImage2Request({- prompt: ["A portrait."], aspectRatio: ["5:4"], resolution: ["4K"],- }),- ]) {- assert.deepEqual(route.supports?.({- capability: route.capability,- returns: route.returns,- constraints: supported as unknown as CanonicalValue,- }), { status: "supported" });- }-});--test("one model reaching a service that splits it keeps the reference roles intact", async () => {- const store = new MemoryResourceStore();- const image = await store.put(new Uint8Array([1]), "image/png");- const audio = await store.put(new Uint8Array([3]), "audio/wav");- const request = sealSeedanceRequest("seedance-2-mini", {- prompt: ["A presenter speaks."],- referenceImage: [{ role: "image", artifact: image }],- referenceAudio: [{ role: "audio", artifact: audio }],- resolution: ["720p"],- aspectRatio: ["9:16"],- duration: [5],- generateAudio: [true],- webSearch: [false],- });- const mapping = kieModelCatalog.find((item) => item.capability.name === "seedance-2-mini");- assert.ok(mapping);- const task = await compileWireRequest(mapping, request, upload);- assert.deepEqual(task.input, {- prompt: "A presenter speaks.",- reference_image_urls: [`https://upload.test/${image.resource}`],- reference_audio_urls: [`https://upload.test/${audio.resource}`],- resolution: "720p",- aspect_ratio: "9:16",- duration: 5,- generate_audio: true,- web_search: false,- });-});diff --git a/packages/provider-kie/test/provider.test.ts b/packages/provider-kie/test/provider.test.tsdeleted file mode 100644index 6ec7933e..00000000--- a/packages/provider-kie/test/provider.test.ts+++ /dev/null@@ -1,360 +0,0 @@-import assert from "node:assert/strict";-import test from "node:test";-import { fixtureResource } from "../../../test/fixture-resource.js";--import {- MemoryResourceStore,- EndpointRegistry,-} from "@hypit/driver-node";-import type { EndpointRegistration } from "@hypit/driver-node";-import type { AsyncEndpoint } from "@hypit/endpoint-kit";-import { artifactTypes } from "@hypit/artifact";-import { backgroundRemovalCapabilities, backgroundRemovalRequest } from "@hypit/background-removal";-import { seedanceEndpoints, sealSeedanceRequest } from "@hypit/seedance";-import { generationTypes } from "@hypit/generation";-import type { CanonicalValue, Need } from "@hypit/protocol";-import { createKieProvider } from "@hypit/provider-kie";--function need(constraints: CanonicalValue): Need {- return {- id: "need:kie-test",- capability: seedanceEndpoints.mini!.capability,- returns: seedanceEndpoints.mini!.returns,- constraints,- result: "record:kie-test",- };-}--function removeBackgroundNeed(constraints: CanonicalValue): Need {- return {- id: "need:remove-background", capability: backgroundRemovalCapabilities.remove, returns: artifactTypes.blob,- constraints, result: "record:remove-background",- };-}--async function endpointFor(- request: Need,- fetch: typeof globalThis.fetch,- now = () => 1_000,- requestTimeoutMs = 1_000,-): Promise<{ endpoint: AsyncEndpoint; registration: EndpointRegistration }> {- const registry = new EndpointRegistry();- const provider = createKieProvider({- fetch,- now,- pollIntervalMs: 0,- requestTimeoutMs,- maxOperationMs: 60_000,- });- await provider.install(registry);- const resolution = registry.resolve(request);- assert.equal(resolution.status, "resolved");- assert.equal(resolution.registration.kind, "asynchronous");- return { endpoint: resolution.registration.endpoint, registration: resolution.registration };-}--function operation(_request: Need): string {- return "operation:kie-test";-}--test("all KIE capabilities share one asynchronous task engine and use exact-model capacity", async () => {- const provider = createKieProvider({- fetch: async () => { throw new Error("no request expected"); },- defaultConcurrency: 8,- capabilityConcurrency: { "seedance-2-mini": 4 },- });- const registry = new EndpointRegistry();- await provider.install(registry);- const seed = need(sealSeedanceRequest("seedance-2-mini", {- prompt: ["A clean studio shot."], resolution: ["720p"], aspectRatio: ["16:9"],- duration: [5], generateAudio: [false], webSearch: [false],- }) as unknown as CanonicalValue);- const source = { kind: "blob" as const, resource: fixtureResource("lane-source"), size: 1, mediaType: "image/png" };- const removal = removeBackgroundNeed(backgroundRemovalRequest(source) as unknown as CanonicalValue);- const seedResolution = registry.resolve(seed);- const removalResolution = registry.resolve(removal);- assert.equal(seedResolution.status, "resolved");- assert.equal(removalResolution.status, "resolved");- assert.equal(seedResolution.registration.kind, "asynchronous");- assert.equal(removalResolution.registration.kind, "asynchronous");- assert.equal(seedResolution.registration.endpoint, removalResolution.registration.endpoint);- assert.deepEqual(seedResolution.registration.scheduling, {- resources: [- { id: "pool:kie.default", limit: 8 },- { id: "capacity:kie.default/seedance-2-mini", limit: 4 },- ],- });-});--test("KIE exposes the rate-card records returned for the request's wire model", async () => {- const provider = createKieProvider({- fetch: async (input, init) => {- assert.equal(String(input), "https://api.kie.ai/client/v1/model-pricing/page");- assert.deepEqual(JSON.parse(String(init?.body)), {- pageNum: 1,- pageSize: 100,- modelDescription: "bytedance/seedance-2-mini",- interfaceType: "",- });- return Response.json({ code: 200, data: {- records: [{- modelDescription: "bytedance/seedance-2-mini, 720P no video",- creditPrice: "8.2",- creditUnit: "per second",- usdPrice: "0.041",- }],- pages: 1,- } });- },- });- const request = {- capability: seedanceEndpoints.mini!.capability,- returns: seedanceEndpoints.mini!.returns,- constraints: sealSeedanceRequest("seedance-2-mini", {- prompt: ["A presenter speaks to camera."], resolution: ["720p"], aspectRatio: ["9:16"],- duration: [5], generateAudio: [true], webSearch: [false],- }) as unknown as CanonicalValue,- };- assert.deepEqual(await provider.readPricing!({- request,- credentials: async () => { throw new Error("public pricing must not require credentials"); },- }), [{- source: "https://api.kie.ai/client/v1/model-pricing/page",- summary: "bytedance/seedance-2-mini, 720P no video: USD 0.041; 8.2 credits (per second)",- data: {- model: "bytedance/seedance-2-mini",- records: [{- modelDescription: "bytedance/seedance-2-mini, 720P no video",- creditPrice: "8.2",- creditUnit: "per second",- usdPrice: "0.041",- }],- },- }]);-});--test("KIE prices the wire route selected by an authored future input", async () => {- const provider = createKieProvider({- fetch: async () => Response.json({ code: 200, data: {- records: [{- modelDescription: "gpt-image-2-image-to-image, 1K",- creditPrice: "8",- creditUnit: "per image",- }],- pages: 1,- } }),- });- const request = {- capability: { module: { name: "@hypit/gpt-image", version: "1" }, name: "gpt-image-2" },- returns: generationTypes.imageSet,- constraints: {- ports: { prompt: ["A portrait."], aspectRatio: ["9:16"], resolution: ["1K"] },- },- pendingInputs: [{ input: "images", role: "image" }],- } as const;- const [document] = await provider.readPricing!({- request,- credentials: async () => { throw new Error("public pricing must not require credentials"); },- });- assert.deepEqual(document?.data, {- model: "gpt-image-2-image-to-image",- records: [{- modelDescription: "gpt-image-2-image-to-image, 1K",- creditPrice: "8",- creditUnit: "per image",- }],- });-});--test("KIE uploads referenced resources, polls one task, and persists generated bytes", async () => {- const resources = new MemoryResourceStore();- const firstFrame = await resources.put(new Uint8Array([1, 2, 3]), "image/png");- const requestValue = sealSeedanceRequest("seedance-2-mini", {- prompt: ["A presenter turns toward camera."],- firstFrame: [{ role: "image", artifact: firstFrame }],- resolution: ["720p"],- aspectRatio: ["16:9"],- duration: [6],- generateAudio: [false],- webSearch: [false],- });- const request = need(requestValue as unknown as CanonicalValue);- const calls: string[] = [];- const fakeFetch: typeof globalThis.fetch = async (input, init) => {- const url = String(input);- calls.push(url);- if (url.endsWith("/api/file-stream-upload")) {- assert.equal(init?.method, "POST");- assert.match(String((init?.headers as Record<string, string>)["content-type"]), /^multipart\/form-data; boundary=/u);- const chunks: Uint8Array[] = [];- for await (const chunk of init?.body as unknown as AsyncIterable<Uint8Array>) chunks.push(chunk);- const multipart = Buffer.concat(chunks).toString("latin1");- assert.match(multipart, /name="fileName"\r\n\r\nres_[a-zA-Z0-9-]+\.png/u);- assert.match(multipart, /name="uploadPath"\r\n\r\nhypit\/resources/u);- assert.doesNotMatch(multipart, /svml\/resources/u);- assert.ok(Buffer.concat(chunks).includes(Buffer.from([1, 2, 3])));- return Response.json({- success: true,- code: 200,- data: { downloadUrl: "https://tempfile.redpandaai.co/reference.png" },- });- }- if (url.endsWith("/api/v1/jobs/createTask")) {- const body = JSON.parse(String(init?.body)) as Record<string, unknown>;- assert.equal(body.model, "bytedance/seedance-2-mini");- const modelInput = body.input as Record<string, unknown>;- assert.equal(modelInput.first_frame_url, "https://tempfile.redpandaai.co/reference.png");- return Response.json({ code: 200, msg: "success", data: { taskId: "task_seedance_test" } });- }- if (url.includes("/api/v1/jobs/recordInfo")) {- return Response.json({- code: 200,- data: {- taskId: "task_seedance_test",- model: "bytedance/seedance-2-mini",- state: "success",- resultJson: JSON.stringify({ resultUrls: ["https://tempfile.aiquickdraw.com/result.mp4"] }),- },- });- }- if (url.endsWith("/api/v1/common/download-url")) {- return Response.json({ code: 200, data: "https://download.kie.test/result.mp4" });- }- if (url === "https://download.kie.test/result.mp4") {- return new Response(new Uint8Array([9, 8, 7, 6]), {- status: 200,- headers: { "content-type": "video/mp4", "content-length": "4" },- });- }- throw new Error(`Unexpected URL ${url}`);- };- const { endpoint } = await endpointFor(request, fakeFetch);- const common = {- command: { kind: "fulfill-need", id: "command:kie-test", need: request } as const,- need: request,- resources,- credentials: { apiKey: { secret: "test-key" } },- operation: operation(request),- };- const started = await endpoint.start(common);- assert.equal(started.status, "pending");- if (started.status !== "pending") return;- assert.deepEqual(started.status === "pending" && started.progress, { phase: "submitted" });- assert.equal(calls.length, 2);- assert.equal(started.status === "pending" && (started.handle as Record<string, unknown>).taskId, "task_seedance_test");- const ready = await endpoint.poll({- ...common,- handle: started.handle!,- });- assert.equal(ready.status, "ready");- if (ready.status !== "ready") return;- const completed = await endpoint.collect!({ ...common, handle: ready.handle });- assert.equal(completed.status, "completed");- assert.equal(calls.length, 5);- if (completed.status !== "completed") return;- assert.equal(completed.result.value.kind, "inline");- const result = completed.result.value.kind === "inline"- ? completed.result.value.value as Record<string, unknown> : {};- assert.equal("model" in result, false, "model choice belongs to the request graph");- const videos = result.videos as Array<{ resource: string }>;- assert.equal(videos.length, 1);- assert.equal(await resources.has(videos[0]!.resource as `res_${string}`), true);-});--test("KIE fulfills generic Background Removal with the documented Recraft wire mapping", async () => {- const resources = new MemoryResourceStore();- const source = await resources.put(new Uint8Array([1, 2, 3, 4]), "image/png");- const request = removeBackgroundNeed(backgroundRemovalRequest(source) as unknown as CanonicalValue);- const calls: string[] = [];- const fakeFetch: typeof globalThis.fetch = async (input, init) => {- const url = String(input); calls.push(url);- if (url.endsWith("/api/file-stream-upload")) {- return Response.json({ code: 200, data: { downloadUrl: "https://tempfile.redpandaai.co/source.png" } });- }- if (url.endsWith("/api/v1/jobs/createTask")) {- assert.deepEqual(JSON.parse(String(init?.body)), {- model: "recraft/remove-background", input: { image: "https://tempfile.redpandaai.co/source.png" },- });- return Response.json({ code: 200, data: { taskId: "task_remove_background" } });- }- if (url.includes("/api/v1/jobs/recordInfo")) {- return Response.json({ code: 200, data: {- taskId: "task_remove_background", model: "recraft/remove-background", state: "success",- resultJson: JSON.stringify({ resultUrls: ["https://tempfile.aiquickdraw.com/cutout.png"] }),- } });- }- if (url.endsWith("/api/v1/common/download-url")) {- return Response.json({ code: 200, data: "https://download.kie.test/cutout.png" });- }- if (url === "https://download.kie.test/cutout.png") {- return new Response(new Uint8Array([9, 8, 7]), { status: 200, headers: { "content-type": "image/png" } });- }- throw new Error(`Unexpected URL ${url}`);- };- const { endpoint } = await endpointFor(request, fakeFetch);- const common = {- command: { kind: "fulfill-need", id: "command:remove-background", need: request } as const,- need: request, resources, credentials: { apiKey: { secret: "test-key" } }, operation: operation(request),- };- const started = await endpoint.start(common);- assert.equal(started.status, "pending");- if (started.status !== "pending") return;- const ready = await endpoint.poll({- ...common, handle: started.handle!,- });- assert.equal(ready.status, "ready");- if (ready.status !== "ready") return;- const completed = await endpoint.collect!({ ...common, handle: ready.handle });- assert.equal(completed.status, "completed");- if (completed.status !== "completed") return;- assert.equal(completed.result.value.kind, "blob");- assert.equal(completed.result.value.kind === "blob" && completed.result.value.mediaType, "image/png");- assert.equal(calls.length, 5);-});--test("KIE polling errors and operation deadlines are terminal request failures", async () => {- const request = need({});- let now = 0, requests = 0;- const { endpoint } = await endpointFor(request, async () => {- requests++; throw new Error("offline");- }, () => now);- const { kieRouteForCapability } = await import("../src/routes.js");- const common = { command: { kind: "fulfill-need", id: "need:test", need: request } as const,- need: request, resources: new MemoryResourceStore(), credentials: { apiKey: { secret: "test" } }, operation: "op:test",- handle: { taskId: "existing", routeKey: kieRouteForCapability(request.capability)!.key, startedAt: 0 } };- const offline = await endpoint.poll(common);- assert.equal(offline.status, "failed");- assert.match(offline.status === "failed" ? offline.failure.message : "", /offline/);- now = 60_001;- const timedOut = await endpoint.poll(common);- assert.equal(timedOut.status, "failed");- assert.equal(timedOut.status === "failed" && timedOut.failure.code, "KIE_OPERATION_TIMEOUT");- assert.equal(requests, 1, "an expired operation does no further network work");-});--test("KIE request timeout covers a response body that never finishes", async () => {- const request = need({});- const { endpoint } = await endpointFor(request, async () => {- // Some gateways return headers and then leave a body open without reacting- // to AbortSignal. The Provider deadline must still release the Build turn.- const stream = new ReadableStream<Uint8Array>({ start() {} });- return new Response(stream, { status: 200, headers: { "content-type": "application/json" } });- }, () => 1_000, 20);- const { kieRouteForCapability } = await import("../src/routes.js");- const startedAt = Date.now();- const outcome = await endpoint.poll({- command: { kind: "fulfill-need", id: "need:body-timeout", need: request },- need: request,- resources: new MemoryResourceStore(),- credentials: { apiKey: { secret: "test" } },- operation: "op:body-timeout",- handle: {- taskId: "existing",- routeKey: kieRouteForCapability(request.capability)!.key,- startedAt: 1_000,- },- });- assert.equal(outcome.status, "failed");- assert.equal(outcome.status === "failed" && outcome.failure.code, "KIE_REQUEST_TIMEOUT");- assert.ok(Date.now() - startedAt < 500, "poll returns after the configured network timeout");-});diff --git a/packages/provider-media-local/README.md b/packages/provider-media-local/README.mdindex 6625557f..924d2a48 100644--- a/packages/provider-media-local/README.md+++ b/packages/provider-media-local/README.md@@ -53,6 +53,5 @@ programme-audio rendering and final muxing remain Build-only. This is declared pRuntime and Studio contain no media capability allowlist.Video-backed normalization is video-authoritative so an AAC packet tail cannot extend the program-past its final picture. Audio-only normalization is audio-authoritative. The AWS Lambda media Provider-must return the same public contracts and timing laws; Lambda is an execution topology, not another-author meaning.+past its final picture. Audio-only normalization is audio-authoritative. Other implementations of these capabilities must preserve the same public values and timing laws;+a different execution topology leaves author meaning unchanged.diff --git a/packages/provider-whisperx-local/src/program.ts b/packages/provider-whisperx-local/src/program.tsindex 24637d20..0f0c5f3d 100644--- a/packages/provider-whisperx-local/src/program.ts+++ b/packages/provider-whisperx-local/src/program.ts@@ -124,6 +124,7 @@ export function localWhisperXProgram(options: LocalWhisperXProgramOptions): ManastateRoot,installation: {probe: installationProbe,+ prepareBeforeStart: true,commands: [{command: "uv",args: ["sync", "--project", localWhisperXManagedProject, "--frozen", "--no-editable"],diff --git a/packages/provider-whisperx-local/src/provider.ts b/packages/provider-whisperx-local/src/provider.tsindex b5857bc6..9078448e 100644--- a/packages/provider-whisperx-local/src/provider.ts+++ b/packages/provider-whisperx-local/src/provider.ts@@ -141,6 +141,7 @@ export function createLocalWhisperXProvider(config: CreateLocalWhisperXProviderOconst audioPath = join(work, "alignment-evidence.wav");await writeFile(audioPath, audio);const signal = AbortSignal.timeout(requestTimeoutMs);+ await context.reportProgress?.({ phase: "Checking local transcription service" });const healthResponse = await fetch(`${normalizedBaseUrl}/health`, { signal });const health = await limitedJson(healthResponse, Math.min(maxResponseBytes, 64 * 1024), "WhisperX health");assert(health.value !== null && typeof health.value === "object" && !Array.isArray(health.value),@@ -164,6 +165,7 @@ export function createLocalWhisperXProvider(config: CreateLocalWhisperXProviderO&& healthValue.compute === expectedCompute&& healthValue.batchSize === expectedBatchSize,"WhisperX service runtime identity differs from the configured Provider");+ await context.reportProgress?.({ phase: "Transcribing and aligning words" });const transcriptionResponse = await fetch(`${normalizedBaseUrl}/transcribe`, {method: "POST",headers: { "content-type": "application/json" },@@ -181,6 +183,7 @@ export function createLocalWhisperXProvider(config: CreateLocalWhisperXProviderOconst evidence: AlignedTranscriptEvidence = sealAlignedTranscriptEvidence({passages,});+ await context.reportProgress?.({ phase: "Word timing ready" });return result(canonicalize(evidence));} finally {await rm(work, { recursive: true, force: true }).catch(() => {});diff --git a/packages/provider-xiaomi-mimo/README.md b/packages/provider-xiaomi-mimo/README.mddeleted file mode 100644index e890d36e..00000000--- a/packages/provider-xiaomi-mimo/README.md+++ /dev/null@@ -1,32 +0,0 @@-# `@hypit/provider-xiaomi-mimo`--Immediate Runtime Endpoint for Xiaomi's official MiMo V2.5 Voice Design and Voice Clone APIs.--This package owns the `chat/completions` wire shape, `api-key` credential, timeout, response bounds,-voice-reference encoding and ResourceStore ingestion. It names `@hypit/mimo-speech@1` capabilities-as versioned data and does not import the model package at runtime.--Runtime Profile example:--```json-{- "endpoints": {- "mimo.official": {- "use": "@hypit/provider-xiaomi-mimo",- "pool": "mimo.official",- "config": {- "apiKey": { "store": "os", "key": "xiaomi-mimo.api-key" },- "defaultConcurrency": 2- }- }- }-}-```--Voice Design sends the authored voice description. Voice Clone reads the selected audio Resource,-checks Xiaomi's accepted MP3/WAV formats and sends it as the vendor's data-URL voice reference.-The Provider always requests final WAV bytes.--Selecting this Provider in the Runtime Profile is independent from author syntax. Its pool and-capability claims participate in the shared Runtime capacity model; the package has no private-scheduler.diff --git a/packages/provider-xiaomi-mimo/package.json b/packages/provider-xiaomi-mimo/package.jsondeleted file mode 100644index 024877c1..00000000--- a/packages/provider-xiaomi-mimo/package.json+++ /dev/null@@ -1,24 +0,0 @@-{- "name": "@hypit/provider-xiaomi-mimo",- "version": "0.0.0-dev",- "license": "SEE LICENSE IN LICENSE",- "private": true,- "type": "module",- "exports": {- ".": "./src/index.ts"- },- "hypit": {- "activation": "./src/activation.ts"- },- "dependencies": {- "@hypit/endpoint-kit": "workspace:*",- "@hypit/generation": "workspace:*",- "@hypit/protocol": "workspace:*",- "@hypit/runtime": "workspace:*",- "@hypit/runtime-kit": "workspace:*"- },- "devDependencies": {- "@hypit/driver-node": "workspace:*",- "@hypit/mimo-speech": "workspace:*"- }-}diff --git a/packages/provider-xiaomi-mimo/src/activation.ts b/packages/provider-xiaomi-mimo/src/activation.tsdeleted file mode 100644index 3c6b6873..00000000--- a/packages/provider-xiaomi-mimo/src/activation.ts+++ /dev/null@@ -1,57 +0,0 @@-import {- createRuntimeEndpointAdapterFacet,- runtimeConfigCredentialRef,- runtimeConfigExact,- runtimeConfigObject,- runtimeConfigPositiveInteger,- runtimeConfigString,-} from "@hypit/runtime-kit";--import { createXiaomiMimoProvider } from "./provider.js";--const adapter = createRuntimeEndpointAdapterFacet({- use: "@hypit/provider-xiaomi-mimo",- activate(context) {- if (context.pool === undefined) throw new Error("Xiaomi MiMo Provider Pool is required");- const config = runtimeConfigObject(context.config, "Xiaomi MiMo");- runtimeConfigExact(config, [- "apiBaseUrl", "apiKey", "defaultConcurrency", "requestTimeoutMs",- "maxResponseBytes", "maxVoiceReferenceBase64Bytes",- ], "Xiaomi MiMo");- const apiBaseUrl = runtimeConfigString(config.apiBaseUrl, "Xiaomi MiMo apiBaseUrl");- if (apiBaseUrl !== undefined) {- const url = new URL(apiBaseUrl);- if (url.protocol !== "https:" && url.hostname !== "localhost" && url.hostname !== "127.0.0.1") {- throw new Error("Xiaomi MiMo apiBaseUrl must use HTTPS or loopback");- }- }- const apiKey = runtimeConfigCredentialRef(config.apiKey, "Xiaomi MiMo apiKey");- if (apiKey === undefined) throw new Error("Xiaomi MiMo apiKey CredentialRef is required");- const defaultConcurrency = runtimeConfigPositiveInteger(config.defaultConcurrency, "Xiaomi MiMo defaultConcurrency");- const requestTimeoutMs = runtimeConfigPositiveInteger(config.requestTimeoutMs, "Xiaomi MiMo requestTimeoutMs");- const maxResponseBytes = runtimeConfigPositiveInteger(config.maxResponseBytes, "Xiaomi MiMo maxResponseBytes");- const maxVoiceReferenceBase64Bytes = runtimeConfigPositiveInteger(- config.maxVoiceReferenceBase64Bytes,- "Xiaomi MiMo maxVoiceReferenceBase64Bytes",- );- return {- endpoint: createXiaomiMimoProvider({- instance: context.instance,- pool: context.pool,- ...(apiBaseUrl === undefined ? {} : { apiBaseUrl }),- apiKey,- ...(defaultConcurrency === undefined ? {} : { defaultConcurrency }),- ...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }),- ...(maxResponseBytes === undefined ? {} : { maxResponseBytes }),- ...(maxVoiceReferenceBase64Bytes === undefined ? {} : { maxVoiceReferenceBase64Bytes }),- }),- };- },-});--export const hypitPackage = {- format: "hypit.node-package@1" as const,- hostFacets: [adapter],-};--export default hypitPackage;diff --git a/packages/provider-xiaomi-mimo/src/index.ts b/packages/provider-xiaomi-mimo/src/index.tsdeleted file mode 100644index eb38d881..00000000--- a/packages/provider-xiaomi-mimo/src/index.ts+++ /dev/null@@ -1,5 +0,0 @@-export {- createXiaomiMimoProvider,- xiaomiMimoProviderModuleRef,-} from "./provider.js";-export type { CreateXiaomiMimoProviderOptions } from "./provider.js";diff --git a/packages/provider-xiaomi-mimo/src/provider.ts b/packages/provider-xiaomi-mimo/src/provider.tsdeleted file mode 100644index bd7b328c..00000000--- a/packages/provider-xiaomi-mimo/src/provider.ts+++ /dev/null@@ -1,214 +0,0 @@-import { defineEndpointPackage } from "@hypit/endpoint-kit";-import type { EndpointInvocationContext } from "@hypit/endpoint-kit";-import {- generationTypes,- sealGeneratedAudioSet,-} from "@hypit/generation";-import type { GenerationMediaValue, GenerationRequest } from "@hypit/generation";-import type { CanonicalValue, CapabilityRef } from "@hypit/protocol";-import { credentialRef } from "@hypit/runtime";-import type { CredentialRef } from "@hypit/runtime";--export const xiaomiMimoProviderModuleRef = { name: "@hypit/provider-xiaomi-mimo", version: "1" } as const;-const mimoModelModule = { name: "@hypit/mimo-speech", version: "1" } as const;-const modelNames = ["mimo-v2.5-tts-voicedesign", "mimo-v2.5-tts-voiceclone"] as const;-type Model = typeof modelNames[number];--const capabilities = Object.fromEntries(modelNames.map((name) => [name, {- module: mimoModelModule,- name,-}])) as Readonly<Record<Model, CapabilityRef>>;--type Fetch = typeof globalThis.fetch;--export type CreateXiaomiMimoProviderOptions = {- readonly instance?: string;- readonly pool?: string;- readonly apiBaseUrl?: string;- readonly apiKey?: CredentialRef;- readonly defaultConcurrency?: number;- readonly requestTimeoutMs?: number;- readonly maxResponseBytes?: number;- readonly maxVoiceReferenceBase64Bytes?: number;- readonly fetch?: Fetch;-};--function assert(condition: unknown, message: string): asserts condition {- if (!condition) throw new Error(message);-}--function positiveInteger(value: number, subject: string): number {- assert(Number.isSafeInteger(value) && value > 0, `${subject} must be a positive integer`);- return value;-}--function normalizeBaseUrl(value: string): string {- const url = new URL(value);- assert(url.protocol === "https:" || url.hostname === "localhost" || url.hostname === "127.0.0.1",- "Xiaomi MiMo apiBaseUrl must use HTTPS or loopback");- return url.href.replace(/\/$/u, "");-}--function request(value: CanonicalValue, model: Model): GenerationRequest {- const result = value as unknown as GenerationRequest;- assert(result.ports !== null && typeof result.ports === "object", "Xiaomi MiMo request has no ports");- const allowed = model === "mimo-v2.5-tts-voicedesign"- ? new Set(["text", "voiceDescription"])- : new Set(["text", "instruction", "voiceReference"]);- assert(Object.keys(result.ports).every((name) => allowed.has(name)),- `${model} request contains an unsupported port`);- return result;-}--function scalar(req: GenerationRequest, model: Model, name: string, required = true): string | undefined {- const values = req.ports[name];- if (values === undefined) {- if (required) throw new Error(`${model} requires ${name}`);- return undefined;- }- assert(values.length === 1 && typeof values[0] === "string", `${model} ${name} must contain one string`);- return values[0];-}--function credential(context: EndpointInvocationContext): string {- const value = context.credentials.apiKey?.secret;- assert(value !== undefined && value.length > 0, "Xiaomi MiMo API key is unavailable");- return value;-}--async function readVoiceReference(- context: EndpointInvocationContext,- req: GenerationRequest,- maxBase64Bytes: number,-): Promise<string> {- const values = req.ports.voiceReference;- assert(values?.length === 1, "MiMo Voice Clone requires exactly one voiceReference");- const value = values[0] as GenerationMediaValue;- assert(value.role === "audio", "MiMo Voice Clone voiceReference must be audio");- const supported = new Set(["audio/mpeg", "audio/mp3", "audio/wav", "audio/x-wav"]);- assert(supported.has(value.artifact.mediaType), "Xiaomi MiMo accepts only MP3 or WAV voice references");- const encodedSize = 4 * Math.ceil(value.artifact.size / 3);- assert(encodedSize <= maxBase64Bytes,- `MiMo voice reference exceeds the configured ${maxBase64Bytes}-byte Base64 limit`);- const bytes = await context.resources.get(value.artifact.resource);- assert(bytes !== undefined, `MiMo voice reference ${value.artifact.resource} is unavailable`);- assert(bytes.byteLength === value.artifact.size, "MiMo voice reference size differs from its BlobRef");- const mediaType = value.artifact.mediaType === "audio/x-wav"- ? "audio/wav"- : value.artifact.mediaType === "audio/mp3" ? "audio/mpeg" : value.artifact.mediaType;- const encoded = Buffer.from(bytes).toString("base64");- assert(Buffer.byteLength(encoded, "utf8") <= maxBase64Bytes,- `MiMo voice reference exceeds the configured ${maxBase64Bytes}-byte Base64 limit`);- return `data:${mediaType};base64,${encoded}`;-}--function parseAudio(text: string, maxAudioBytes: number): Uint8Array {- let raw: unknown;- try {- raw = JSON.parse(text);- } catch {- throw new Error("Xiaomi MiMo returned invalid JSON");- }- const root = raw as { choices?: Array<{ message?: { audio?: { data?: unknown } } }> };- const data = root.choices?.[0]?.message?.audio?.data;- assert(typeof data === "string" && data.length > 0, "Xiaomi MiMo returned no audio data");- assert(data.length % 4 === 0 && /^[A-Za-z0-9+/]*={0,2}$/u.test(data),- "Xiaomi MiMo returned malformed Base64 audio");- const bytes = Uint8Array.from(Buffer.from(data, "base64"));- assert(bytes.byteLength > 0, "Xiaomi MiMo returned empty audio");- assert(bytes.byteLength <= maxAudioBytes, "Xiaomi MiMo audio exceeds the configured limit");- return bytes;-}--async function limitedResponseText(response: Response, maxBytes: number): Promise<string> {- const announced = response.headers.get("content-length");- if (announced !== null) {- const size = Number(announced);- assert(Number.isSafeInteger(size) && size >= 0, "Xiaomi MiMo returned invalid Content-Length");- assert(size <= maxBytes, "Xiaomi MiMo response exceeds the configured limit");- }- const reader = response.body?.getReader();- if (reader === undefined) {- const bytes = new Uint8Array(await response.arrayBuffer());- assert(bytes.byteLength <= maxBytes, "Xiaomi MiMo response exceeds the configured limit");- return Buffer.from(bytes).toString("utf8");- }- const chunks: Uint8Array[] = [];- let size = 0;- while (true) {- const item = await reader.read();- if (item.done) break;- size += item.value.byteLength;- if (size > maxBytes) {- await reader.cancel();- throw new Error("Xiaomi MiMo response exceeds the configured limit");- }- chunks.push(item.value);- }- const bytes = new Uint8Array(size);- let offset = 0;- chunks.forEach((chunk) => { bytes.set(chunk, offset); offset += chunk.byteLength; });- return Buffer.from(bytes).toString("utf8");-}--export function createXiaomiMimoProvider(options: CreateXiaomiMimoProviderOptions) {- const apiBaseUrl = normalizeBaseUrl(options.apiBaseUrl ?? "https://api.xiaomimimo.com/v1");- const requestTimeoutMs = positiveInteger(options.requestTimeoutMs ?? 180_000, "requestTimeoutMs");- const maxResponseBytes = positiveInteger(options.maxResponseBytes ?? 64 * 1024 * 1024, "maxResponseBytes");- const maxVoiceReferenceBase64Bytes = positiveInteger(- options.maxVoiceReferenceBase64Bytes ?? 10_000_000,- "maxVoiceReferenceBase64Bytes",- );- const fetcher = options.fetch ?? globalThis.fetch;- const endpointCapabilities = modelNames.map((model) => ({- capability: capabilities[model],- returns: generationTypes.audioSet,- lifecycle: "immediate" as const,- handler: async (context: EndpointInvocationContext) => {- const req = request(context.need.constraints, model);- const text = scalar(req, model, "text")!;- const messages: Array<{ role: "user" | "assistant"; content: string }> = [];- const audio: Record<string, CanonicalValue> = { format: "wav" };- if (model === "mimo-v2.5-tts-voicedesign") {- messages.push({ role: "user", content: scalar(req, model, "voiceDescription")! });- } else {- const instruction = scalar(req, model, "instruction", false);- if (instruction !== undefined) messages.push({ role: "user", content: instruction });- audio.voice = await readVoiceReference(context, req, maxVoiceReferenceBase64Bytes);- }- messages.push({ role: "assistant", content: text });- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(new Error("Xiaomi MiMo request timed out")), requestTimeoutMs);- let response: Response;- let responseText: string;- try {- response = await fetcher(`${apiBaseUrl}/chat/completions`, {- method: "POST",- headers: { "content-type": "application/json", "api-key": credential(context) },- body: JSON.stringify({ model, messages, audio }),- signal: controller.signal,- });- responseText = await limitedResponseText(response, maxResponseBytes);- } finally {- clearTimeout(timer);- }- if (!response.ok) throw new Error(`Xiaomi MiMo returned HTTP ${response.status}: ${responseText.slice(0, 300)}`);- const bytes = parseAudio(responseText, maxResponseBytes);- const artifact = await context.resources.put(bytes, "audio/wav");- const result = sealGeneratedAudioSet({ audios: [artifact] });- return { value: { kind: "inline" as const, value: result as unknown as CanonicalValue } };- },- }));-- return defineEndpointPackage({- module: xiaomiMimoProviderModuleRef,- facet: "speech",- instance: options.instance ?? "xiaomi-mimo.default",- pool: options.pool ?? options.instance ?? "xiaomi-mimo.default",- pricing: { kind: "page", url: "https://mimo.mi.com/docs/en-US/pricing" },- credentials: { apiKey: options.apiKey ?? credentialRef("env", "MIMO_API_KEY") },- credentialInputs: { apiKey: { label: "Xiaomi MiMo API key" } },- defaultConcurrency: options.defaultConcurrency ?? 2,- capabilities: endpointCapabilities,- });-}diff --git a/packages/provider-xiaomi-mimo/test/provider.test.ts b/packages/provider-xiaomi-mimo/test/provider.test.tsdeleted file mode 100644index edc3e60b..00000000--- a/packages/provider-xiaomi-mimo/test/provider.test.ts+++ /dev/null@@ -1,98 +0,0 @@-import assert from "node:assert/strict";-import test from "node:test";--import { EndpointRegistry, MemoryResourceStore } from "@hypit/driver-node";-import { mimoSpeechEndpoints, sealMimoSpeechRequest } from "@hypit/mimo-speech";-import type { CanonicalValue, Need } from "@hypit/protocol";-import { createXiaomiMimoProvider } from "@hypit/provider-xiaomi-mimo";--function need(- endpoint: (typeof mimoSpeechEndpoints)[keyof typeof mimoSpeechEndpoints],- constraints: CanonicalValue,- id: string,-): Need {- return {- id: `need:${id}`,- capability: endpoint.capability,- returns: endpoint.returns,- constraints,- result: `record:${id}`,- };-}--async function invoke(request: Need, resources: MemoryResourceStore, fetch: typeof globalThis.fetch) {- const provider = createXiaomiMimoProvider({ fetch });- const registry = new EndpointRegistry();- await provider.install(registry);- const resolution = registry.resolve(request);- assert.equal(resolution.status, "resolved");- assert.equal(resolution.registration.kind, "immediate");- return await resolution.registration.handler({- command: { kind: "fulfill-need", id: `command:${request.id}`, need: request },- need: request,- resources,- credentials: { apiKey: { secret: "test-key" } },- });-}--function audioResponse(bytes: Uint8Array) {- return Response.json({ choices: [{ message: { audio: { data: Buffer.from(bytes).toString("base64") } } }] });-}--test("the official Provider maps Voice Design and Voice Clone to Xiaomi's wire", async () => {- const resources = new MemoryResourceStore();- const voiceReference = await resources.put(new Uint8Array([1, 2, 3, 4]), "audio/wav");- const cases = [- {- endpoint: mimoSpeechEndpoints.voiceDesign,- request: sealMimoSpeechRequest("mimo-v2.5-tts-voicedesign", {- text: ["Keep every authored word."],- voiceDescription: ["A clear, grounded female voice."],- }),- assertBody(body: Record<string, unknown>) {- assert.deepEqual(body.audio, { format: "wav" });- assert.deepEqual(body.messages, [- { role: "user", content: "A clear, grounded female voice." },- { role: "assistant", content: "Keep every authored word." },- ]);- },- },- {- endpoint: mimoSpeechEndpoints.voiceClone,- request: sealMimoSpeechRequest("mimo-v2.5-tts-voiceclone", {- text: ["Keep every authored word."],- instruction: ["Calm and restrained."],- voiceReference: [{ role: "audio", artifact: voiceReference }],- }),- assertBody(body: Record<string, unknown>) {- const audio = body.audio as Record<string, string>;- assert.equal(audio.format, "wav");- assert.match(audio.voice!, /^data:audio\/wav;base64,/u);- assert.deepEqual(body.messages, [- { role: "user", content: "Calm and restrained." },- { role: "assistant", content: "Keep every authored word." },- ]);- },- },- ];-- for (const [index, item] of cases.entries()) {- const result = await invoke(- need(item.endpoint, item.request as unknown as CanonicalValue, String(index)),- resources,- async (input, init) => {- assert.equal(String(input), "https://api.xiaomimimo.com/v1/chat/completions");- assert.equal(new Headers(init?.headers).get("api-key"), "test-key");- const body = JSON.parse(String(init?.body)) as Record<string, unknown>;- assert.equal(body.model, item.endpoint.capability.name);- item.assertBody(body);- return audioResponse(new Uint8Array([9, 8, 7, index]));- },- );- assert.equal(result.value.kind, "inline");- const set = result.value.kind === "inline" ? result.value.value as Record<string, unknown> : {};- const audios = set.audios as Array<{ mediaType: string; resource: string }>;- assert.equal(audios[0]?.mediaType, "audio/wav");- assert.equal(await resources.has(audios[0]!.resource as `res_${string}`), true);- }-});diff --git a/packages/render-hyperframes/README.md b/packages/render-hyperframes/README.mdindex 039d8205..b6d2cc7c 100644--- a/packages/render-hyperframes/README.md+++ b/packages/render-hyperframes/README.md@@ -29,7 +29,7 @@ Core therefore sees three real byte-operation Needs, not one opaque mega-render.contiguous or interleaved chunks, retries and image-sequence assembly remain inside the selectedvisual Endpoint; clip decoding/mixing remains inside the audio Endpoint; container encoding remainsinside the mux Endpoint. A single Provider package may implement all three locally, or a Runtime may-bind them to separate Lambda-backed Endpoints. The author still sees one `<render:Video>` result.+bind them to separate compatible Endpoints. The author still sees one `<render:Video>` result.Film is not a dependency of this author meaning. Any package that produces the common Compositioncontract can feed the render Surface. Conversely, targeting Composition never demands this package;@@ -54,5 +54,5 @@ Provider's Runtime configuration.In TypeScript, `hyperframesVisualRequest(document, { range })` constructs the visual request;`createRenderHyperframesFragment(true)` accepts a `MediaFrameRange` input and connects it to visual-and audio requests. The AWS Lambda Provider currently declines range requests. Selection limits+and audio requests. Provider support checks establish range support for other deployments. Selection limitsfinal rendering work; it does not prune upstream generation dependencies.diff --git a/packages/render-hyperframes/src/component.ts b/packages/render-hyperframes/src/component.tsindex 4c8bd2d7..6939facb 100644--- a/packages/render-hyperframes/src/component.ts+++ b/packages/render-hyperframes/src/component.ts@@ -4,6 +4,7 @@ import type { ComponentPackage } from "@hypit/component-kit";import type { StoredValue } from "@hypit/protocol";import { hyperframesVisualRequest } from "./product.js";+import type { HyperframesVisualRequest } from "./product.js";import { renderHyperframesCapabilities, renderHyperframesProducers } from "./manifest.js";/** Declares the visual Need. It contains no renderer, queue, credentials or deployment choice. */@@ -26,7 +27,16 @@ export const renderHyperframesComponent = {return { constraints: {}, pendingInputs: plannedNeedInputs(state, step) };},present(specification) {- return { fields: {}, references: {} };+ const request = specification.constraints as Partial<HyperframesVisualRequest>;+ if (request.document === undefined) return { fields: {}, references: {} };+ const { document, range } = request;+ const startFrame = range?.startFrame ?? 0;+ const endFrameExclusive = range?.endFrameExclusive ?? document.frameCount;+ return { fields: {+ width: [document.canvas.width], height: [document.canvas.height],+ startFrame: [startFrame], endFrameExclusive: [endFrameExclusive],+ frameRate: [`${document.frameRate.numerator}/${document.frameRate.denominator}`],+ }, references: {} };},})),} satisfies ComponentPackage;diff --git a/packages/render-hyperframes/test/presentation.test.ts b/packages/render-hyperframes/test/presentation.test.tsnew file mode 100644index 00000000..c0699eed--- /dev/null+++ b/packages/render-hyperframes/test/presentation.test.ts@@ -0,0 +1,20 @@+import assert from "node:assert/strict";+import test from "node:test";+import { renderHyperframesComponent } from "../src/component.js";++test("render requests describe their own frame range and canvas without exposing HTML", () => {+ const present = renderHyperframesComponent.plannedNeeds[0]!.present;+ const document = {+ canvas: { width: 1080, height: 1920 }, frameRate: { numerator: 30000, denominator: 1001 },+ frameCount: 600, html: "large HTML belongs to execution", artifacts: [], surfaces: [],+ };+ assert.deepEqual(present({ constraints: {}, pendingInputs: [] }), { fields: {}, references: {} });+ const whole = present({ constraints: { document }, pendingInputs: [] });+ assert.deepEqual(whole.fields, {+ width: [1080], height: [1920], startFrame: [0], endFrameExclusive: [600], frameRate: ["30000/1001"],+ });+ const range = present({ constraints: { document, range: { startFrame: 30, endFrameExclusive: 91 } }, pendingInputs: [] });+ assert.equal(range.fields.startFrame?.[0], 30);+ assert.equal(range.fields.endFrameExclusive?.[0], 91);+ assert.equal("html" in range.fields, false);+});diff --git a/packages/run-markup/test/run.test.ts b/packages/run-markup/test/run.test.tsindex 2ce3c52a..d6a39551 100644--- a/packages/run-markup/test/run.test.ts+++ b/packages/run-markup/test/run.test.ts@@ -273,7 +273,7 @@ test("Run imports are a prologue and Runtime settings are not language elements"<author source="./main.svml"/><target output="film"/><import from="@example/run" as="run"/></svrun>`), /bad\.svrun:2:\d+:.*opening prologue/u);assert.throws(() => parseRunDocument("bad.svrun", `<svrun version="1">- <author source="./main.svml"/><target output="film"/><provider name="kie"/>+ <author source="./main.svml"/><target output="film"/><provider name="images"/></svrun>`), /does not accept <provider>/u);});diff --git a/packages/runtime-host-node/README.md b/packages/runtime-host-node/README.mdindex 70d48ae2..4978dfad 100644--- a/packages/runtime-host-node/README.md+++ b/packages/runtime-host-node/README.md@@ -23,3 +23,33 @@ over a graph state, deterministic Producers, validators and temporary Resources;Endpoint selection, handlers and concurrency for that disposable session private and returns the evaluatedstate. This is an execution boundary, not a second Runtime Profile, Build type, cross-Build scheduler orpreview registry.++`RuntimeHostControl.logs(build, lines)` optionally exposes a bounded tail of active Build evidence.+Finished logs belong to `BuildResultManifest.executionLog` and are read through the project's Repository;+reading a finished log needs no Runtime or execution Provider. Runtime process logs keep their separate+process-control operation.++`prepare`, `preflight`, `doctor` and Program lifecycle operations accept explicit Endpoint instance+names. Build preflight uses resolved Endpoints, not every Provider offering the capability. Omitting+a scope retains whole-Profile inspection or preparation.++`prepareHostPackages` keeps exact releases in separate ordinary npm installations below the Host+package home. `HostPackageProgress.logPath` identifies live and retained npm output; failures include+that path. npm owns each installation's dependency tree and lockfile. No parallel package inventory is+maintained. `RuntimeInvocationObservation` passes direct-call progress and diagnostics through the+same Provider callbacks used in Builds, without giving immediate calls durable Operation semantics.++## Execution choices and lifetime++`createRuntime({ endpoints })` scopes a submission to the selected Endpoint instances. The local Host+records those choices and its project package root with the active execution request. Its long-lived+Worker supervises carriers with independent per-Build module and registry contexts. Managed+Programs remain independently warm. `runWorker` accepts an internal carrier entry point; execution+readiness and Endpoint capacity are independent of the number of unfinished Builds. Other Hosts own+their choice of code-loading and physical execution mechanisms.++Submission clients use `const controller = await host.controller(); await controller.worker.up()`+to start execution, then `const runtime = await host.createRuntime(); await runtime.build(request)`+to submit work. `RuntimeHostExecution` does not run a second embedded Worker loop. A local carrier+may stop accepting new Builds and drain; its assigned Builds stay in place and all carriers continue+using the same resource accounting. Process policy belongs to the local Runtime, not this Host ABI.diff --git a/packages/runtime-host-node/package.json b/packages/runtime-host-node/package.jsonindex 82e6e040..f4b97360 100644--- a/packages/runtime-host-node/package.json+++ b/packages/runtime-host-node/package.json@@ -11,6 +11,7 @@"@hypit/build-result": "workspace:*","@hypit/build-result-kit": "workspace:*","@hypit/driver-node": "workspace:*",+ "@hypit/package-loader-node": "workspace:*","@hypit/protocol": "workspace:*","@hypit/runtime": "workspace:*","@hypit/runtime-kit": "workspace:*",diff --git a/packages/runtime-host-node/src/index.ts b/packages/runtime-host-node/src/index.tsindex 0833064f..d0740cf5 100644--- a/packages/runtime-host-node/src/index.ts+++ b/packages/runtime-host-node/src/index.ts@@ -16,7 +16,6 @@ import type {CredentialRef,OperationSnapshot,ResourceStore,- RuntimeWorkerRunOptions,} from "@hypit/runtime";import type { RuntimeDoctorDiagnostic } from "@hypit/runtime-kit";@@ -63,6 +62,12 @@ export type BuildView = {readonly acceptedRecords: number;readonly outstandingCommands: number;readonly operations: readonly BuildOperationView[];+ /** Activity reported by calls running in the local Worker. */+ readonly commands?: readonly {+ readonly id: string;+ readonly endpoint: string;+ readonly progress: NonNullable<OperationSnapshot["progress"]>;+ }[];};export type RuntimeHostCredentialStatus = {@@ -77,6 +82,8 @@ export type RuntimeHostCredentialStatus = {};export type RuntimeHostControl = {+ /** Build evidence while active. Finished evidence is read through its Result Repository. */+ logs?(build: string, lines: number): Promise<import("@hypit/runtime").ExecutionLogView | undefined>;inspect(build: string): Promise<BuildView | undefined>;activity(): Promise<{readonly builds: readonly BuildView[];@@ -127,7 +134,6 @@ export type RuntimeHostExecution = RuntimeHostControl & RuntimeHostCredentialConreadonly maxWaitMs?: number;readonly signal?: AbortSignal;}): Promise<RuntimeHostBuildSubmission>;- work(options: RuntimeWorkerRunOptions): Promise<void>;};export type RuntimeHostDoctorResult = {@@ -214,7 +220,6 @@ export type ManagedProgramReport = {export type RuntimeWorkerState = {readonly state: "running" | "stopped";- readonly configuration?: "current" | "changed";readonly profile: string;readonly pid?: number;readonly startedAt?: number;@@ -235,9 +240,10 @@ export type RuntimeController = {readonly maxWaitMs?: number;readonly onProgress?: (event: ManagedProgramProgress) => void;readonly capabilities?: readonly CapabilityRef[];+ readonly endpoints?: readonly string[];}): Promise<{ readonly dataRoot: string; readonly programs: readonly ManagedProgramReport[] }>;- down(): Promise<{ readonly dataRoot: string; readonly programs: readonly ManagedProgramReport[] }>;- report(): Promise<{ readonly dataRoot: string; readonly programs: readonly ManagedProgramReport[] }>;+ down(options?: { readonly endpoints?: readonly string[] }): Promise<{ readonly dataRoot: string; readonly programs: readonly ManagedProgramReport[] }>;+ report(options?: { readonly endpoints?: readonly string[] }): Promise<{ readonly dataRoot: string; readonly programs: readonly ManagedProgramReport[] }>;};};@@ -255,7 +261,7 @@ export type NodeRuntimeHost = {controller(options?: {readonly packageRoot?: string;}): Promise<RuntimeController>;- createRuntime(): Promise<RuntimeHostExecution>;+ createRuntime(options?: { readonly endpoints?: readonly string[] }): Promise<RuntimeHostExecution>;openControl(options?: { readonly readOnly?: boolean }): Promise<RuntimeHostControl>;/** Open only Result-writing dependencies; never construct execution Providers. */openResultControl(): Promise<RuntimeHostResultControl>;@@ -263,6 +269,7 @@ export type NodeRuntimeHost = {/** Explicitly prepare upstream packages selected by this Runtime Profile. */prepare(options?: {readonly onProgress?: (event: import("./packages.js").HostPackageProgress) => void;+ readonly endpoints?: readonly string[];}): Promise<readonly import("./packages.js").HostPackageReport[]>;/*** Read-only, bounded deployment validation for one demanded Build slice.@@ -271,10 +278,12 @@ export type NodeRuntimeHost = {*/preflight(options?: {readonly capabilities?: readonly CapabilityRef[];+ readonly endpoints?: readonly string[];}): Promise<RuntimeHostDoctorResult>;/** Active deployment diagnosis. Unlike preflight, adapters may contact their configured services. */doctor(options?: {readonly capabilities?: readonly CapabilityRef[];+ readonly endpoints?: readonly string[];}): Promise<RuntimeHostDoctorResult>;/*** Which selected Endpoint would serve each capability and where its Provider publishes prices.@@ -288,10 +297,16 @@ export type NodeRuntimeHost = {* The creation-time boundary for observation, transcription and other quick capabilities; it* creates no Build, Result or state, and refuses asynchronous capabilities.*/- invoke(need: Need, resources: ResourceStore): Promise<{ readonly value: StoredValue }>;+ invoke(need: Need, resources: ResourceStore, observation?: RuntimeInvocationObservation): Promise<{ readonly value: StoredValue }>;/** Open one disposable authoring execution. It creates no Build, Result or recoverable Operation. */openTransientExecution(): Promise<RuntimeHostTransientExecution>;- runWorker(readyFile: string, owner: string): Promise<void>;+ runWorker(readyFile: string, owner: string, execution?: { readonly dataRoot: string }): Promise<void>;+};++/** Progress stays with the selected Provider; immediate calls need no synthetic Build. */+export type RuntimeInvocationObservation = {+ readonly reportProgress?: (progress: import("@hypit/runtime").OperationProgress) => Promise<void>;+ readonly reportDiagnostic?: (diagnostic: import("@hypit/runtime").ExecutionDiagnostic) => Promise<void>;};/**@@ -321,7 +336,7 @@ export function hypitHostStateRoot(options: {: state, "hypit");}-/** Upstream npm packages shared by every Hypit project and future session on this machine. */+/** Home of version-isolated upstream npm installations shared across projects. */export function hypitHostPackageRoot(hostStateRoot = hypitHostStateRoot()): string {return join(resolve(hostStateRoot), "packages");}diff --git a/packages/runtime-host-node/src/packages.ts b/packages/runtime-host-node/src/packages.tsindex 17ed66e9..2d125d09 100644--- a/packages/runtime-host-node/src/packages.ts+++ b/packages/runtime-host-node/src/packages.ts@@ -1,6 +1,7 @@import { spawn } from "node:child_process";-import { mkdir, readFile, writeFile } from "node:fs/promises";+import { mkdir, open, readFile, realpath, writeFile } from "node:fs/promises";import { join, resolve } from "node:path";+import { externalPackageInstallRoot } from "@hypit/package-loader-node";export type RegistryPackageSpec = {readonly name: string;@@ -10,11 +11,13 @@ export type RegistryPackageSpec = {export type HostPackageReport = RegistryPackageSpec & {readonly root: string;+ readonly logPath?: string;readonly action: "already-installed" | "installed";};export type HostPackageProgress = RegistryPackageSpec & {readonly phase: "checking" | "installing" | "ready";+ readonly logPath?: string;};function exactVersion(value: string): boolean {@@ -63,18 +66,20 @@ export async function inspectHostPackage(root: string,): Promise<HostPackageReport | undefined> {const required = parseRegistryPackageSpec(specifier);- const version = await installedVersion(resolve(root), required.name);+ const installation = externalPackageInstallRoot(root, required.name, required.version);+ const version = await installedVersion(installation, required.name);return version === required.version- ? { ...required, root: resolve(root), action: "already-installed" }+ ? { ...required, root: installation, action: "already-installed" }: undefined;}-function runNpm(root: string, specifiers: readonly string[]): Promise<void> {+async function runNpm(root: string, specifiers: readonly string[], logPath: string): Promise<void> {+ // npm's prefix and cwd must denote the same physical project (not /tmp vs /private/tmp).+ const cwd = await realpath(root);const npmArgs = ["install",- "--prefix", root,+ "--prefix", cwd,"--save-exact",- "--package-lock=false","--no-audit","--no-fund","--omit=dev",@@ -83,27 +88,30 @@ function runNpm(root: string, specifiers: readonly string[]): Promise<void> {const windows = process.platform === "win32";const command = windows ? (process.env.ComSpec ?? "cmd.exe") : "npm";const args = windows ? ["/d", "/s", "/c", "npm.cmd", ...npmArgs] : npmArgs;- return new Promise((done, reject) => {- const child = spawn(command, args, {- shell: false,- windowsHide: true,- stdio: ["ignore", "pipe", "pipe"],- });- let output = "";- child.stdout.on("data", (chunk: Buffer) => { output = `${output}${chunk.toString()}`.slice(-32_000); });- child.stderr.on("data", (chunk: Buffer) => { output = `${output}${chunk.toString()}`.slice(-32_000); });- child.on("error", reject);- child.on("close", (code) => {- if (code === 0) done();- else reject(new Error(`npm install failed${output.trim().length === 0 ? "" : `: ${output.trim().split("\n").at(-1)}`}`));+ const log = await open(logPath, "a");+ await log.write(`\n${new Date().toISOString()} npm ${npmArgs.join(" ")}\n`);+ try {+ await new Promise<void>((done, reject) => {+ const child = spawn(command, args, {+ cwd,+ shell: false,+ windowsHide: true,+ stdio: ["ignore", log.fd, log.fd],+ });+ child.on("error", (error) => reject(new Error(`Cannot start npm: ${error.message}. Log: ${logPath}`, { cause: error })));+ child.on("close", (code) => {+ if (code === 0) done();+ else reject(new Error(`npm install failed (exit ${code ?? "signal"}). Log: ${logPath}`));+ });});- });+ } finally {+ await log.close();+ }}/**- * Install missing upstream packages into one user/machine npm home.- * npm's ordinary package.json is the only persistent package-set record; Hypit- * creates no lock, receipt, hash inventory or project-local copy.+ * Reuse each exact upstream release in its own npm installation. npm owns its+ * package.json, lockfile and dependencies; Hypit keeps no parallel inventory.*/export async function prepareHostPackages(specifiers: readonly string[],@@ -113,46 +121,35 @@ export async function prepareHostPackages(},): Promise<readonly HostPackageReport[]> {const root = resolve(options.root);- const byName = new Map<string, RegistryPackageSpec>();+ const bySpecifier = new Map<string, RegistryPackageSpec>();for (const specifier of specifiers) {const parsed = parseRegistryPackageSpec(specifier);- const previous = byName.get(parsed.name);- if (previous !== undefined && previous.version !== parsed.version) {- throw new Error(`${parsed.name} is required at both ${previous.version} and ${parsed.version}`);- }- byName.set(parsed.name, parsed);+ bySpecifier.set(parsed.specifier, parsed);}- const required = [...byName.values()].sort((left, right) => left.name.localeCompare(right.name));- const missing: RegistryPackageSpec[] = [];+ const required = [...bySpecifier.values()].sort((left, right) => left.specifier.localeCompare(right.specifier));+ const reports: HostPackageReport[] = [];for (const item of required) {+ const installation = externalPackageInstallRoot(root, item.name, item.version);options.onProgress?.({ ...item, phase: "checking" });- if (await installedVersion(root, item.name) !== item.version) missing.push(item);- }- if (missing.length > 0) {- await mkdir(root, { recursive: true });- try {- await readFile(join(root, "package.json"), "utf8");- } catch (error) {- if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;- await writeFile(join(root, "package.json"), `${JSON.stringify({+ const missing = await installedVersion(installation, item.name) !== item.version;+ const logPath = join(installation, "install.log");+ if (missing) {+ await mkdir(installation, { recursive: true });+ await writeFile(join(installation, "package.json"), `${JSON.stringify({name: "hypit-machine-packages",private: true,description: "Upstream npm packages used on demand by Hypit",- dependencies: {},+ dependencies: { [item.name]: item.version },}, null, 2)}\n`, "utf8");+ options.onProgress?.({ ...item, phase: "installing", logPath });+ await runNpm(installation, [item.specifier], logPath);}- for (const item of missing) options.onProgress?.({ ...item, phase: "installing" });- await runNpm(root, missing.map((item) => item.specifier));- }- const installed = new Set(missing.map((item) => item.name));- const reports: HostPackageReport[] = [];- for (const item of required) {- const version = await installedVersion(root, item.name);+ const version = await installedVersion(installation, item.name);if (version !== item.version) {- throw new Error(`npm did not install ${item.specifier} into ${root}`);+ throw new Error(`npm did not install ${item.specifier} into ${installation}. Log: ${logPath}`);}options.onProgress?.({ ...item, phase: "ready" });- reports.push({ ...item, root, action: installed.has(item.name) ? "installed" : "already-installed" });+ reports.push({ ...item, root: installation, ...(missing ? { logPath } : {}), action: missing ? "installed" : "already-installed" });}return reports;}diff --git a/packages/runtime-host-node/test/runtime-host-node.test.ts b/packages/runtime-host-node/test/runtime-host-node.test.tsindex b5531f8c..705428af 100644--- a/packages/runtime-host-node/test/runtime-host-node.test.ts+++ b/packages/runtime-host-node/test/runtime-host-node.test.ts@@ -31,12 +31,13 @@ test("configured executable paths are rooted at the Runtime Profile project", as}});-test("machine packages are exact npm packages reused from one Host root", async () => {+test("machine packages reuse exact releases without overwriting another version", async () => {const root = await mkdtemp(join(tmpdir(), "hypit-machine-packages-"));try {const packageRoot = hypitHostPackageRoot(root);- await mkdir(join(packageRoot, "node_modules", "hyperframes"), { recursive: true });- await writeFile(join(packageRoot, "node_modules", "hyperframes", "package.json"), JSON.stringify({+ const installation = join(packageRoot, "hyperframes", "0.7.101");+ await mkdir(join(installation, "node_modules", "hyperframes"), { recursive: true });+ await writeFile(join(installation, "node_modules", "hyperframes", "package.json"), JSON.stringify({name: "hyperframes",version: "0.7.101",}));@@ -48,6 +49,13 @@ test("machine packages are exact npm packages reused from one Host root", asyncassert.throws(() => parseRegistryPackageSpec("@hypit/[email protected]"), /external npm registry package/u);const reports = await prepareHostPackages(["[email protected]"], { root: packageRoot });assert.equal(reports[0]?.action, "already-installed");+ assert.equal(reports[0]?.root, installation);+ const other = join(packageRoot, "hyperframes", "0.7.102");+ await mkdir(join(other, "node_modules", "hyperframes"), { recursive: true });+ await writeFile(join(other, "node_modules", "hyperframes", "package.json"), JSON.stringify({ name: "hyperframes", version: "0.7.102" }));+ assert.equal((await prepareHostPackages(["[email protected]"], { root: packageRoot }))[0]?.root, other);+ assert.equal((await prepareHostPackages(["[email protected]"], { root: packageRoot }))[0]?.action, "already-installed");+ assert.equal((await prepareHostPackages(["[email protected]", "[email protected]"], { root: packageRoot })).length, 2);} finally {await rm(root, { recursive: true, force: true });}diff --git a/packages/runtime-kit/README.md b/packages/runtime-kit/README.mdindex 09b61371..a337c966 100644--- a/packages/runtime-kit/README.md+++ b/packages/runtime-kit/README.md@@ -40,3 +40,8 @@ WhisperX process. Credential adapters validate configuration before opening a ststorage belongs to the Runtime implementation, while project Build Result repositories use theseparate `@hypit/build-result-kit` boundary. Runtime Kit knows no Provider, filesystem, database orvideo package by name.++`ManagedProgram.installation.prepareBeforeStart` lets a Provider reconcile its installed environment+before a cold start, even when the installation probe already passes. The declared commands use the+Provider's ordinary package manager. A healthy running Program is reused before this preparation is+considered; Runtime does not inspect source files or infer implementation versions.diff --git a/packages/runtime-kit/src/index.ts b/packages/runtime-kit/src/index.tsindex 1ac64635..3f02f614 100644--- a/packages/runtime-kit/src/index.ts+++ b/packages/runtime-kit/src/index.ts@@ -42,7 +42,9 @@ export type ManagedProgramCommand = {export type ManagedProgramInstallation = {/** Truthful inspection of the installed program; no installer-owned receipt. */probe(): Promise<ManagedProgramState>;- /** Commands run only when the installation probe is not ready. */+ /** Reconcile an installed environment before a cold start, using its package manager's cache. */+ readonly prepareBeforeStart?: boolean;+ /** Commands run when installation is missing, or before a cold start when requested above. */readonly commands: readonly ManagedProgramCommand[];};diff --git a/packages/runtime-local/README.md b/packages/runtime-local/README.mdindex 39274254..c09e3e6b 100644--- a/packages/runtime-local/README.md+++ b/packages/runtime-local/README.md@@ -70,7 +70,7 @@ quota; exact-model limits may narrow it further. Build identity is not a capacitno second queue.Claims may carry `units` (default 1): one render Need can occupy one request slot and four browserslots at once. The same admission rule applies to total Provider capacity, exact models, and local-compute resources. SQLite retains the weighted reservation across Worker turns and restarts. This+compute resources. SQLite retains the weighted reservation across execution turns; an ended attempt releases its reservations. Thiscoordinates Builds sharing this Runtime's Execution Store; it does not enforce a service's quotasacross other machines. Short-action limits are described below.@@ -95,8 +95,7 @@ becomes available; known Operations are polled from their own lightweight recordserialized, while network actions and local work remain concurrent under their declared limits.HypiHub can be the explicitly selected gateway for users without their own service keys. A bound-Provider's authentication, quota or transport error never changes that selection. Separate Kie and-HypiHub accounts use separate pools even when they implement the same model.+Provider's authentication, quota or transport error never changes that selection. Separate accounts use separate pools even when they implement the same model.Without `hypit.results.json`, the official video Distribution selects the filesystem adapter at theproject's `.hypit/results` directory, with no cloud account or service. Runtime Local opens that default@@ -128,7 +127,9 @@ The lifecycle commands have deliberately narrow meanings:- `hypit runtime init` writes and selects the Distribution's starter Profile; it performs no setup ornetwork access and never overwrites an existing Profile.- `hypit runtime up` prepares selected local dependencies, starts declared local Programs and starts- the Worker. `hypit runtime down` stops the Worker; `hypit programs down` stops the Programs.+ the Worker. Repeat `--endpoint <instance>` to limit preparation to chosen services; omission covers+ the whole Profile. `doctor` and Program operations accept the same scope. Build preflight receives+ actual resolved Endpoint IDs and checks only their credentials and Programs. `hypit runtime down` stops the Worker; `hypit programs down` stops the Programs.Remote services have no lifecycle for Hypit to start or stop.- `hypit runtime logs` reads the Worker's output, including separately redirected standard errorson Windows. The files are `worker.log` and `worker.err.log` under the Runtime data directory's@@ -136,3 +137,90 @@ The lifecycle commands have deliberately narrow meanings:event order. A failure before readiness also includes the recorded error in its startup message.- `hypit doctor` is the active, read-only check. Endpoint-owned diagnostics may authenticate and read aremote capability catalog; normal preflight never does.++## Build execution evidence++The Worker records Endpoint calls independently of CLI follow. Local calls use the execution context;+remote Operations retain their existing receipts and contribute phase changes as they advance.+`fileExecutionLogs` appends `hypit.execution-log@1` records to `work/<build>/execution.jsonl` under the+Profile's `dataRoot`. Each record carries time, Command and Endpoint identity. Pure graph evaluation+and repeated progress counters do not become log entries. The latest counters remain active Runtime+state; Provider-authored diagnostics and phase changes are durable evidence.++Result finishing streams this log through the selected Repository before publishing the terminal+manifest or clearing the Build working directory. Complete, failed and cancelled Builds use the same+finishing path. A failed archive leaves Result attention and preserves the working directory; finishing+that Result performs no external execution. Log write failures also surface at the Result boundary,+without converting a successful Provider call into another generation attempt.++`hypit logs <build-id>` reads active evidence through Runtime control or finished evidence through the+project Result Repository. `runtime logs` remains the Worker's process log. Program installation and+service logs remain owned by their Program; they are shared service history, not copied into every Build.+The logger does not capture the process environment, credential values, request bodies or global console.++## Build-scoped execution++The long-lived Worker supervises execution carriers. Each Build has its own module scope,+component/Provider registries and selected configuration. Editing project code or Profile selections+applies to the next Build without restarting the Worker; already loaded modules remain bound to their+original Build. Installed Distribution modules stay process-owned. The Package Loader owns scoped+JavaScript/TypeScript loading, including transitive ESM and CommonJS dependencies.++One carrier shares a SQLite connection and event loop across active Builds. The database returns+ready Build IDs; the dispatcher opens that Build's context once, hydrates local work in sequence, then+lets asynchronous actions proceed concurrently. Pending remote submission does not hold a whole-Build+admission slot. Accepted Operations retain receipts and wake times; their next poll can advance without+materializing the whole graph. Endpoint-declared task limits, action concurrency and rates still govern+actual work. A remote task waiting in an eight-slot pool does not block another Build's unrelated local+step. CPU-heavy rendering belongs to its execution backend and declared resources.++The active execution request owns its opaque local context: project package root, Distribution root,+selected Endpoint configurations and bindings, and relevant Credential Store declarations. Source+compilation and execution use the same project package root. Core does not see these choices. Different+Profiles selecting the same Runtime data directory share its coordinator and capacity accounting; the+coordinator's startup directory and recorded Profile path do not select later Builds' project code.++`startedAt` records assignment to an execution carrier. Losing that carrier ends its assigned attempts+and preserves completed Outputs and external receipts, without resubmitting work. Unstarted queue+entries may still start. Result-writing failures retain the attention and `result finish` path. A live+carrier never reclaims another carrier's turns. These are module/registry contexts in trusted code,+not OS or security isolation: process globals, native libraries and a fatal process failure are shared.+The carrier has one working directory and inherited environment. Package-relative file access uses+module URLs; spawned tools receive their own explicit working directory and environment as needed.++After its assigned Builds end, the carrier exits and releases Node's module cache. The coordinator and+Managed Programs stay available. With continuous submissions, the coordinator can retire a carrier+from accepting new Builds while its assigned work continues in place. New work uses a fresh carrier;+all carriers share the same SQLite resource accounting. A live Build is never unloaded or moved.++The coordinator reads process policy from its startup Profile:++```json+"worker": { "executionMemoryMb": 1024 }+```++The default is 1024 MiB of execution-process RSS. It is a soft retirement budget, not a memory ceiling+or a limit on active Builds. Carriers report RSS after opening a Build context and when a Build ends.+Once a carrier has completed work and its reported RSS reaches the budget, it stops accepting new+Builds. Its remaining Builds finish before it exits. Live work alone does not trigger rotation, and+a fresh carrier can accept work even when its startup footprint exceeds the budget. There is no+forced timeout or replay. Draining carriers can still use substantial memory while long jobs run;+this policy reclaims finished-work accumulation, not the memory required by unfinished work.+The Profile that starts the coordinator owns this process policy until that coordinator exits.++Loaded module bindings are scoped, not the filesystem. Later file reads observe ordinary files;+a first-time dynamic import reads the implementation then available and subsequently remains cached+in that Build's scope. No source snapshot, filesystem scan, content hash or Build recovery is involved.+`createLocalRuntime` remains available for embeddings that explicitly supply their implementations.+Its `workOnce` advances fresh work or work already owned by that instance; an explicit request to+take over another context's started Build fails before any Provider call. The coordinator supplies+the assignment when opening each production Build context. Client code calls `worker.up()` on the+controller returned by `await host.controller()`, and calls `build(...)` on the Runtime returned by+`await host.createRuntime()`. There is one production process-lifecycle path.++Managed Programs have independent lifetimes. A healthy WhisperX service keeps its model loaded;+`prepareBeforeStart` reconciles a cold installation through uv's source-aware synchronization.+`runtime down` stops the coordinator and asks its executors to stop; Programs are stopped separately.+Distribution changes and shell environment changes still concern the coordinator's bootstrap process.+Inspect active work before restarting it. Environment-backed credentials use that inherited process+environment; external writable Credential Stores resolve through their own implementation.diff --git a/packages/runtime-local/src/config.ts b/packages/runtime-local/src/config.tsindex 63b97cda..3f8f02af 100644--- a/packages/runtime-local/src/config.ts+++ b/packages/runtime-local/src/config.ts@@ -1,3 +1,4 @@+import { fileExecutionLogs } from "./log.js";import { readFile, rm, stat } from "node:fs/promises";import { dirname, relative, resolve, sep } from "node:path";@@ -56,6 +57,7 @@ import type {RuntimeHostCapabilityProvider,RuntimeHostProviderQuery,RuntimeHostTransientExecution,+ RuntimeInvocationObservation,} from "@hypit/runtime-host-node";import { SqliteRuntimeState } from "@hypit/store-sqlite";@@ -82,6 +84,8 @@ export type LocalRuntimeAdapterSelection = {export type LocalRuntimeProfile = {readonly format: "hypit.runtime-local@1";readonly dataRoot: string;+ /** Coordinator policy, independent of any Build's selected Endpoints. */+ readonly worker?: { readonly executionMemoryMb: number };readonly credentials: readonly LocalRuntimeAdapterSelection[];readonly endpoints: readonly LocalRuntimeAdapterSelection[];/**@@ -106,6 +110,9 @@ export type ProjectBuildResultDoctorResult = {export type LoadRuntimeConfigOptions = {readonly registry?: RuntimeAdapterRegistry;readonly resultRegistry?: BuildResultRepositoryRegistry;+ /** Execution-owned module bindings; omitted for ordinary short-lived CLI calls. */+ readonly importModule?: (url: string) => Promise<unknown>;+ readonly endpoints?: readonly string[];readonly packageRoot?: string;readonly distributionPackageRoot?: string;/** Persistent machine/user state. Defaults to the platform Hypit state root. */@@ -119,9 +126,35 @@ export type RuntimeConfigDoctorResult = {type RuntimeInspectionOptions = LoadRuntimeConfigOptions & {readonly capabilities?: readonly CapabilityRef[];+ readonly endpoints?: readonly string[];readonly active: boolean;};+/** Explicit deployment scope. Bindings narrow discovery before unused packages are loaded. */+function scopedProfile(document: LocalRuntimeProfile, scope: {+ readonly endpoints?: readonly string[];+ readonly capabilities?: readonly CapabilityRef[];+}): LocalRuntimeProfile {+ const bound = scope.capabilities?.map((capability) => document.bindings[capabilityKey(capability)]);+ const names = scope.endpoints ?? (bound?.every((name) => name !== undefined) ? bound as string[] : undefined);+ if (names === undefined) return document;+ for (const name of names) {+ if (!document.endpoints.some((item) => item.instance === name)) throw new Error(`Runtime Profile has no Endpoint ${name}`);+ }+ const selected = new Set(names);+ return { ...document,+ endpoints: document.endpoints.filter((item) => selected.has(item.instance)),+ bindings: Object.fromEntries(Object.entries(document.bindings).filter(([, name]) => selected.has(name))),+ };+}++function requestsCapability(document: LocalRuntimeProfile, instance: string, capability: CapabilityRef,+ requested: ReadonlySet<string> | undefined): boolean {+ const key = capabilityKey(capability);+ return requested === undefined || requested.has(key)+ && (document.bindings[key] === undefined || document.bindings[key] === instance);+}+export type ResolvedRuntimeConfigPaths = {readonly packageRoot: string;readonly dataRoot: string;@@ -194,7 +227,7 @@ function bindings(value: unknown, endpoints: readonly LocalRuntimeAdapterSelectiexport function parseLocalRuntimeProfile(value: unknown): LocalRuntimeProfile {const item = object(value, "$runtime");- exactKeys(item, ["format", "dataRoot", "credentials", "endpoints", "bindings"], "$runtime");+ exactKeys(item, ["format", "dataRoot", "worker", "credentials", "endpoints", "bindings"], "$runtime");if (item.format !== "hypit.runtime-local@1") {throw new Error("$runtime.format must be hypit.runtime-local@1");}@@ -202,15 +235,31 @@ export function parseLocalRuntimeProfile(value: unknown): LocalRuntimeProfile {const endpoints = entries(item.endpoints, "$runtime.endpoints", true);const ids = [...credentials, ...endpoints].map((value) => value.instance);if (new Set(ids).size !== ids.length) throw new Error("$runtime repeats a Runtime instance id");+ let worker: LocalRuntimeProfile["worker"];+ if (item.worker !== undefined) {+ const settings = object(item.worker, "$runtime.worker");+ exactKeys(settings, ["executionMemoryMb"], "$runtime.worker");+ const budget = settings.executionMemoryMb;+ if (typeof budget !== "number" || !Number.isSafeInteger(budget) || budget <= 0) {+ throw new Error("$runtime.worker.executionMemoryMb must be a positive integer in MiB");+ }+ worker = { executionMemoryMb: budget };+ }return {format: "hypit.runtime-local@1",dataRoot: requiredString(item.dataRoot, "$runtime.dataRoot"),+ ...(worker === undefined ? {} : { worker }),credentials,endpoints,bindings: bindings(item.bindings, endpoints),};}+/** Read only process policy; starting a coordinator does not load selected project packages. */+export async function readRuntimeWorkerOptions(path: string): Promise<{ readonly executionMemoryMb: number }> {+ return (await openRuntimeConfig(path)).document.worker ?? { executionMemoryMb: 1024 };+}+async function openRuntimeConfig(path: string, packageRootHint?: string): Promise<OpenedRuntimeConfig> {const absolute = resolve(path);const document = parseLocalRuntimeProfile(JSON.parse(await readFile(absolute, "utf8")));@@ -253,6 +302,7 @@ async function installRuntimeAdapters(packageRoot: string,selection: NodePackageSelectionRequest,distributionPackageRoot?: string,+ importModule?: (url: string) => Promise<unknown>,): Promise<void> {const logical = selection.logical?.filter((address) => {if (address.abi === runtimeEndpointAdapterHostAbi) return !registry.has(address.name, "endpoint");@@ -261,6 +311,8 @@ async function installRuntimeAdapters(}) ?? [];if (selection.selected.length === 0 && logical.length === 0) return;const loaded = await loadNodePackageSelection({ selected: selection.selected, logical }, packageRoot, {+ deferExternalDependencies: true,+ ...(importModule === undefined ? {} : { importModule }),...(distributionPackageRoot === undefined ? {} : { fallbackRoots: [distributionPackageRoot] }),});for (const item of loaded) {@@ -275,9 +327,11 @@ async function installBuildResultAdapter(packageRoot: string,use: string,distributionPackageRoot?: string,+ importModule?: (url: string) => Promise<unknown>,): Promise<void> {if (registry.has(use)) return;const loaded = await loadNodePackageSelection(resultPackageSelection(use), packageRoot, {+ ...(importModule === undefined ? {} : { importModule }),...(distributionPackageRoot === undefined ? {} : { fallbackRoots: [distributionPackageRoot] }),});for (const item of loaded) {@@ -294,7 +348,7 @@ async function openBuildResultLocation(packageRoot: string,registry: BuildResultRepositoryRegistry,): Promise<BuildResultRepositoryOpened> {- await installBuildResultAdapter(registry, packageRoot, location.selection.use, options.distributionPackageRoot);+ await installBuildResultAdapter(registry, packageRoot, location.selection.use, options.distributionPackageRoot, options.importModule);return await registry.open(location.selection, location.root);}@@ -394,13 +448,19 @@ export async function prepareRuntimeConfigPackages(path: string,options: LoadRuntimeConfigOptions & {readonly onProgress?: (event: HostPackageProgress) => void;+ readonly endpoints?: readonly string[];} = {},): Promise<readonly HostPackageReport[]> {if (options.distributionPackageRoot === undefined) return [];- const { document } = await openRuntimeConfig(path, options.packageRoot);+ const opened = await openRuntimeConfig(path, options.packageRoot);+ const document = scopedProfile(opened.document, options);+ const registry = options.registry ?? new RuntimeAdapterRegistry();+ await installRuntimeAdapters(registry, opened.packageRoot, endpointPackageSelection(document), options.distributionPackageRoot);+ const activations = await activatedEndpoints(document, opened.root, resolve(options.hostStateRoot ?? hypitHostStateRoot()), registry);+ const credentials = credentialProfile(document, activations.map(({ activation }) => activation.endpoint));const requirements = await distributionExternalPackageRequirements([- ...document.credentials.map((item) => item.use),...document.endpoints.map((item) => item.use),+ ...credentials.credentials.map((item) => item.use),], options.distributionPackageRoot);return await prepareHostPackages(requirements.map((item) => item.specifier), {root: hypitHostPackageRoot(options.hostStateRoot),@@ -450,11 +510,18 @@ async function activatedEndpoints(})));}+function credentialProfile(document: LocalRuntimeProfile, endpoints: readonly EndpointPackage[]): LocalRuntimeProfile {+ const used = new Set(endpoints.flatMap((endpoint) => endpoint.credentials.map((slot) => slot.ref.store)));+ return { ...document, credentials: document.credentials.filter((item) => used.has(item.instance)) };+}+export async function declaredManagedPrograms(path: string,- options: LoadRuntimeConfigOptions & { readonly capabilities?: readonly CapabilityRef[] } = {},+ options: LoadRuntimeConfigOptions & { readonly capabilities?: readonly CapabilityRef[]; readonly endpoints?: readonly string[] } = {},): Promise<{ readonly dataRoot: string; readonly programs: readonly DeclaredManagedProgram[] }> {- const { document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+ const opened = await openRuntimeConfig(path, options.packageRoot);+ const { root, packageRoot } = opened;+ const document = scopedProfile(opened.document, options);if (options.capabilities?.length === 0) return { dataRoot: root, programs: [] };const hostStateRoot = resolve(options.hostStateRoot ?? hypitHostStateRoot());const registry = options.registry ?? new RuntimeAdapterRegistry();@@ -464,7 +531,7 @@ export async function declaredManagedPrograms(: new Set(options.capabilities.map(capabilityKey));const programs: DeclaredManagedProgram[] = [];for (const { entry, activation } of await activatedEndpoints(document, root, hostStateRoot, registry)) {- if (requested !== undefined && !activation.endpoint.offers.some((offer) => requested.has(capabilityKey(offer.capability)))) continue;+ if (requested !== undefined && !activation.endpoint.offers.some((offer) => requestsCapability(document, entry.instance, offer.capability, requested))) continue;if (activation.program !== undefined) programs.push({ instance: entry.instance, program: activation.program });}return { dataRoot: root, programs };@@ -627,7 +694,9 @@ export async function describeRuntimeConfigProviders(options: LoadRuntimeConfigOptions = {},): Promise<readonly RuntimeHostCapabilityProvider[]> {if (requests.length === 0) return [];- const { document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+ const opened = await openRuntimeConfig(path, options.packageRoot);+ const { root, packageRoot } = opened;+ const document = scopedProfile(opened.document, { capabilities: requests.map((request) => request.capability) });const hostStateRoot = resolve(options.hostStateRoot ?? hypitHostStateRoot());const registry = options.registry ?? new RuntimeAdapterRegistry();await installRuntimeAdapters(registry, packageRoot, endpointPackageSelection(document), options.distributionPackageRoot);@@ -708,14 +777,25 @@ export async function readRuntimeConfigPricing(options: LoadRuntimeConfigOptions = {},): Promise<readonly RuntimeHostCapabilityPricing[]> {if (requests.length === 0) return [];- const { absolute, document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+ const opened = await openRuntimeConfig(path, options.packageRoot);+ const { absolute, root, packageRoot } = opened;+ const document = scopedProfile(opened.document, { capabilities: requests.map((request) => request.capability) });const hostStateRoot = resolve(options.hostStateRoot ?? hypitHostStateRoot());const registry = options.registry ?? new RuntimeAdapterRegistry();- await installRuntimeAdapters(registry, packageRoot, runtimePackageSelection(document), options.distributionPackageRoot);+ await installRuntimeAdapters(registry, packageRoot, endpointPackageSelection(document), options.distributionPackageRoot);const activations = await activatedEndpoints(document, root, hostStateRoot, registry);const endpoints = await installedEndpointRegistry(document, activations);- let stores: Awaited<ReturnType<typeof openCredentialStores>> | undefined;- const openedStores = async () => stores ??= await openCredentialStores(document, root, hostStateRoot, registry);+ const stores = new Map<string, Awaited<ReturnType<typeof openCredentialStores>>>();+ const openedStores = async (endpoint: EndpointPackage) => {+ let opened = stores.get(endpoint.instance.id);+ if (opened === undefined) {+ const selected = credentialProfile(document, [endpoint]);+ await installRuntimeAdapters(registry, packageRoot, runtimePackageSelection({ ...selected, endpoints: [] }), options.distributionPackageRoot);+ opened = await openCredentialStores(selected, root, hostStateRoot, registry);+ stores.set(endpoint.instance.id, opened);+ }+ return opened;+ };const result: RuntimeHostCapabilityPricing[] = [];try {for (const request of requests) {@@ -784,7 +864,7 @@ export async function readRuntimeConfigPricing(const pricingDocuments = await match.activation.endpoint.readPricing({request: endpointRequest,credentials: async () => {- const opened = await openedStores();+ const opened = await openedStores(match.activation.endpoint);return await resolveEndpointCredentials(match.activation.endpoint, opened.store, absolute);},});@@ -804,7 +884,7 @@ export async function readRuntimeConfigPricing(}return result;} finally {- await stores?.close();+ await Promise.all([...stores.values()].map((opened) => opened.close()));}}@@ -820,12 +900,14 @@ export async function invokeRuntimeConfigNeed(path: string,need: Need,resources: ResourceStore,- options: LoadRuntimeConfigOptions = {},+ options: LoadRuntimeConfigOptions & RuntimeInvocationObservation = {},): Promise<EndpointFulfillment> {- const { absolute, document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+ const opened = await openRuntimeConfig(path, options.packageRoot);+ const { absolute, root, packageRoot } = opened;+ const document = scopedProfile(opened.document, { capabilities: [need.capability] });const hostStateRoot = resolve(options.hostStateRoot ?? hypitHostStateRoot());const registry = options.registry ?? new RuntimeAdapterRegistry();- await installRuntimeAdapters(registry, packageRoot, runtimePackageSelection(document), options.distributionPackageRoot);+ await installRuntimeAdapters(registry, packageRoot, endpointPackageSelection(document), options.distributionPackageRoot);const activations = await activatedEndpoints(document, root, hostStateRoot, registry);const endpoints = await installedEndpointRegistry(document, activations);const subject = capabilityKey(need.capability);@@ -850,7 +932,9 @@ export async function invokeRuntimeConfigNeed(}const activation = activations.find(({ activation: item }) => item.endpoint.instance.id === registration.id)?.activation;if (activation === undefined) throw new Error(`Endpoint ${registration.id} is not declared by ${absolute}`);- const stores = await openCredentialStores(document, root, hostStateRoot, registry);+ const selected = credentialProfile(document, [activation.endpoint]);+ await installRuntimeAdapters(registry, packageRoot, runtimePackageSelection({ ...selected, endpoints: [] }), options.distributionPackageRoot);+ const stores = await openCredentialStores(selected, root, hostStateRoot, registry);try {const credentials = await resolveEndpointCredentials(activation.endpoint, stores.store, absolute);return await registration.handler({@@ -858,6 +942,8 @@ export async function invokeRuntimeConfigNeed(need,resources,credentials,+ ...(options.reportProgress === undefined ? {} : { reportProgress: options.reportProgress }),+ ...(options.reportDiagnostic === undefined ? {} : { reportDiagnostic: options.reportDiagnostic }),});} finally {await stores.close();@@ -896,7 +982,7 @@ async function openCredentialStores(}}-function statePath(root: string): string {+export function statePath(root: string): string {return resolve(root, "runtime.sqlite");}@@ -915,7 +1001,10 @@ async function inspectRuntimeConfig(path: string,options: RuntimeInspectionOptions,): Promise<RuntimeConfigDoctorResult> {- const { absolute, document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+ const opened = await openRuntimeConfig(path, options.packageRoot);+ const { absolute, root, packageRoot } = opened;+ const document = scopedProfile(opened.document, options);+ const scoped = options.endpoints !== undefined || options.capabilities !== undefined;const hostStateRoot = resolve(options.hostStateRoot ?? hypitHostStateRoot());const diagnostics: RuntimeDoctorDiagnostic[] = [];try {@@ -927,24 +1016,10 @@ async function inspectRuntimeConfig(}const registry = options.registry ?? new RuntimeAdapterRegistry();try {- await installRuntimeAdapters(registry, packageRoot, runtimePackageSelection(document), options.distributionPackageRoot);+ await installRuntimeAdapters(registry, packageRoot, endpointPackageSelection(document), options.distributionPackageRoot);} catch (error) {return { dataRoot: root, diagnostics: [diagnostic(error, "RUNTIME_PACKAGE_SELECTION_INVALID")] };}- const storeSelections = [- ...document.credentials.map((item) => ({ item, kind: "credential-store" as const })),- ];- for (const selection of storeSelections) {- const context = adapterContext(root, hostStateRoot, selection.item);- try {- diagnostics.push(...registry.validate(selection.item.use, selection.kind, context));- if (options.active) {- diagnostics.push(...await registry.doctor(selection.item.use, selection.kind, context));- }- } catch (error) {- diagnostics.push(diagnostic(error, "RUNTIME_COMPONENT_CONFIG_INVALID", selection.item.instance));- }- }const requested = options.capabilities === undefined? undefined: new Set(options.capabilities.map(capabilityKey));@@ -963,7 +1038,7 @@ async function inspectRuntimeConfig(continue;}activated.push({ item, activation });- if (requested !== undefined && !activation.endpoint.offers.some((offer) => requested.has(capabilityKey(offer.capability)))) continue;+ if (requested !== undefined && !activation.endpoint.offers.some((offer) => requestsCapability(document, item.instance, offer.capability, requested))) continue;for (const offer of activation.endpoint.offers) covered.add(capabilityKey(offer.capability));selectedEndpoints.push({ item, activation });const program = activation.program;@@ -1028,10 +1103,32 @@ async function inspectRuntimeConfig(} catch (error) {diagnostics.push(diagnostic(error, "RUNTIME_ENDPOINT_INSTALL_FAILED"));}+ const credentialDocument = scoped ? credentialProfile(document, selectedEndpoints.map(({ activation }) => activation.endpoint)) : document;+ try {+ await installRuntimeAdapters(registry, packageRoot, {+ selected: [], logical: credentialDocument.credentials.map((item) => ({ abi: runtimeCredentialStoreAdapterHostAbi, name: item.use })),+ }, options.distributionPackageRoot);+ const storeSelections = [+ ...credentialDocument.credentials.map((item) => ({ item, kind: "credential-store" as const })),+ ];+ for (const selection of storeSelections) {+ const context = adapterContext(root, hostStateRoot, selection.item);+ try {+ diagnostics.push(...registry.validate(selection.item.use, selection.kind, context));+ if (options.active) {+ diagnostics.push(...await registry.doctor(selection.item.use, selection.kind, context));+ }+ } catch (error) {+ diagnostics.push(diagnostic(error, "RUNTIME_COMPONENT_CONFIG_INVALID", selection.item.instance));+ }+ }+ } catch (error) {+ diagnostics.push(diagnostic(error, "RUNTIME_CREDENTIAL_CHECK_FAILED"));+ }if (selectedEndpoints.length > 0) {let stores: Awaited<ReturnType<typeof openCredentialStores>> | undefined;try {- stores = await openCredentialStores(document, root, hostStateRoot, registry);+ stores = await openCredentialStores(credentialDocument, root, hostStateRoot, registry);for (const { item, activation } of selectedEndpoints) {const credentials: Record<string, CredentialValue> = {};let missing = false;@@ -1081,7 +1178,7 @@ async function inspectRuntimeConfig(*/export async function preflightRuntimeConfig(path: string,- options: LoadRuntimeConfigOptions & { readonly capabilities?: readonly CapabilityRef[] } = {},+ options: LoadRuntimeConfigOptions & { readonly capabilities?: readonly CapabilityRef[]; readonly endpoints?: readonly string[] } = {},): Promise<RuntimeConfigDoctorResult> {return await inspectRuntimeConfig(path, { ...options, active: false });}@@ -1089,7 +1186,7 @@ export async function preflightRuntimeConfig(/** Active diagnosis may ask selected credentials and Endpoints to verify their configured services. */export async function doctorRuntimeConfig(path: string,- options: LoadRuntimeConfigOptions & { readonly capabilities?: readonly CapabilityRef[] } = {},+ options: LoadRuntimeConfigOptions & { readonly capabilities?: readonly CapabilityRef[]; readonly endpoints?: readonly string[] } = {},): Promise<RuntimeConfigDoctorResult> {return await inspectRuntimeConfig(path, { ...options, active: true });}@@ -1098,35 +1195,75 @@ export async function createRuntimeFromConfig(path: string,options: LoadRuntimeConfigOptions = {},): Promise<LocalRuntime> {- const { document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+ return await createRuntimeFromOpened(await openRuntimeConfig(path, options.packageRoot), options);+}++/** Execution choices are captured at submission; later Profile edits belong to later Builds. */+export type LocalExecutionContext = {+ readonly format: "hypit.local-execution@1";+ readonly packageRoot: string;+ readonly hostStateRoot: string;+ readonly distributionPackageRoot?: string;+ readonly profile: CanonicalValue;+};++export function localExecutionContext(value: CanonicalValue | undefined): LocalExecutionContext {+ const record = object(value, "Build execution context");+ if (record.format !== "hypit.local-execution@1") throw new Error("Build has no local execution context; create a new Build");+ return {+ format: "hypit.local-execution@1",+ packageRoot: requiredString(record.packageRoot, "execution.packageRoot"),+ hostStateRoot: requiredString(record.hostStateRoot, "execution.hostStateRoot"),+ ...(record.distributionPackageRoot === undefined ? {} : { distributionPackageRoot: requiredString(record.distributionPackageRoot, "execution.distributionPackageRoot") }),+ profile: record.profile as CanonicalValue,+ };+}++export async function createRuntimeForBuild(dataRoot: string, build: string, execution: {+ readonly state: SqliteRuntimeState;+ readonly importModule: (url: string) => Promise<unknown>;+}): Promise<LocalRuntime> {+ const context = localExecutionContext((await execution.state.execution.read(build))?.context);+ return await createRuntimeFromOpened({+ absolute: dataRoot, profileRoot: dataRoot, root: dataRoot,+ packageRoot: context.packageRoot, document: parseLocalRuntimeProfile(context.profile),+ }, { ...context, importModule: execution.importModule }, { state: execution.state, build });+}++async function createRuntimeFromOpened(opened: OpenedRuntimeConfig, options: LoadRuntimeConfigOptions, execution?: {+ readonly state: SqliteRuntimeState; readonly build: string;+}): Promise<LocalRuntime> {+ const { root, packageRoot } = opened;+ let document = scopedProfile(opened.document, options);const hostStateRoot = resolve(options.hostStateRoot ?? hypitHostStateRoot());const registry = options.registry ?? new RuntimeAdapterRegistry();const resultRegistry = options.resultRegistry ?? new BuildResultRepositoryRegistry();- await installRuntimeAdapters(registry, packageRoot, runtimePackageSelection(document), options.distributionPackageRoot);- const state = new SqliteRuntimeState(statePath(root));- // Only selections that can change Command execution or an Operation handle are pinned until- // every Build using them has left active Runtime state.- const environmentConfig = canonicalStringify({- credentials: document.credentials,- endpoints: document.endpoints,- bindings: document.bindings,- });+ await installRuntimeAdapters(registry, packageRoot, endpointPackageSelection(document), options.distributionPackageRoot, options.importModule);+ const state = execution?.state ?? new SqliteRuntimeState(statePath(root));let credentials: Awaited<ReturnType<typeof openCredentialStores>> | undefined;try {- await state.environment.use(environmentConfig);- credentials = await openCredentialStores(document, root, hostStateRoot, registry);const endpoints = await Promise.all(document.endpoints.map(async (item) => await registry.createEndpoint(item.use,adapterContext(root, hostStateRoot, { ...item, pool: item.pool ?? item.instance }),)));+ document = credentialProfile(document, endpoints);+ await installRuntimeAdapters(registry, packageRoot, runtimePackageSelection({ ...document, endpoints: [] }), options.distributionPackageRoot, options.importModule);+ credentials = await openCredentialStores(document, root, hostStateRoot, registry);+ const selections = (items: readonly LocalRuntimeAdapterSelection[]) => Object.fromEntries(items.map(({ instance, ...selection }) => [instance, selection]));+ const context = {+ format: "hypit.local-execution@1", packageRoot, hostStateRoot,+ ...(options.distributionPackageRoot === undefined ? {} : { distributionPackageRoot: options.distributionPackageRoot }),+ profile: { format: document.format, dataRoot: root, credentials: selections(document.credentials),+ endpoints: selections(document.endpoints), bindings: document.bindings },+ } as CanonicalValue;return await createLocalRuntime({+ ...(execution === undefined ? {} : { executionBuild: execution.build }),+ executionContext: context,buildStore: state.builds,buildCatalog: state.catalog,operationStore: state.operations,commandExecutionStore: state.commandExecutions,- assertEnvironment: async () => {- await state.environment.assert(environmentConfig);- },+ executionLogs: fileExecutionLogs((build) => buildWorkPath(root, build)),executionStore: state.execution,removeActiveBuild: async (build) => await state.removeActiveBuild(build),submissionStore: state.submissions,@@ -1139,6 +1276,7 @@ export async function createRuntimeFromConfig(credentialStore: credentials.store,loadComponentPackages: async (specifiers) => {const loaded = await loadNodePackageSelection(specifiers, packageRoot, {+ ...(options.importModule === undefined ? {} : { importModule: options.importModule }),...(options.distributionPackageRoot === undefined? {}: { fallbackRoots: [options.distributionPackageRoot] }),@@ -1149,12 +1287,12 @@ export async function createRuntimeFromConfig(bindings: document.bindings,close: async () => {await credentials?.close();- state.close();+ if (execution === undefined) state.close();},});} catch (error) {await credentials?.close();- state.close();+ if (execution === undefined) state.close();throw error;}}@@ -1167,6 +1305,8 @@ export async function createRuntimeControlFromConfig(const state = new SqliteRuntimeState(statePath(root), { readOnly: options.readOnly === true });return createLocalRuntimeControl({buildStore: state.builds,+ commandExecutionStore: state.commandExecutions,+ executionLogs: fileExecutionLogs((build) => buildWorkPath(root, build)),buildCatalog: state.catalog,operationStore: state.operations,executionStore: state.execution,@@ -1180,12 +1320,18 @@ export async function createRuntimeResultControlFromConfig(options: LoadRuntimeConfigOptions = {},): Promise<LocalResultWriter> {const { root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+ return createRuntimeResultWriter(root, { ...options, packageRoot });+}++export function createRuntimeResultWriter(root: string, options: LoadRuntimeConfigOptions & { readonly packageRoot: string }): LocalResultWriter {+ const { packageRoot } = options;const state = new SqliteRuntimeState(statePath(root));const resultRegistry = options.resultRegistry ?? new BuildResultRepositoryRegistry();return createLocalResultWriter({buildStore: state.builds,operationStore: state.operations,commandExecutionStore: state.commandExecutions,+ executionLogs: fileExecutionLogs((build) => buildWorkPath(root, build)),executionStore: state.execution,removeActiveBuild: async (build) => await state.removeActiveBuild(build),submissionStore: state.submissions,diff --git a/packages/runtime-local/src/control.ts b/packages/runtime-local/src/control.tsindex 9bb68a18..9b4cdc8e 100644--- a/packages/runtime-local/src/control.ts+++ b/packages/runtime-local/src/control.ts@@ -20,6 +20,7 @@ function buildView(input: {readonly submission?: PendingBuildSubmission;readonly execution?: BuildExecutionSnapshot;readonly operations: readonly OperationSnapshot[];+ readonly commands: readonly import("@hypit/runtime").CommandExecutionReceipt[];}): BuildView | undefined {if (input.submission === undefined && input.execution === undefined) return undefined;const createdAt = buildIdCreatedAt(input.build);@@ -57,6 +58,8 @@ function buildView(input: {...(requests === undefined ? {} : { requests }),acceptedRecords: input.snapshot?.state.records.length ?? 0,outstandingCommands: input.snapshot?.state.outstanding.length ?? 0,+ commands: input.commands.flatMap((command) => command.status === "started" && command.activity !== undefined+ ? [{ id: command.command, ...command.activity }] : []),operations: input.operations.map((operation) => ({id: operation.id,endpoint: operation.endpoint,@@ -75,12 +78,13 @@ export function createLocalRuntimeControl(): LocalRuntimeControl {const buildCatalog = options.buildCatalog;const inspect = async (build: string): Promise<BuildView | undefined> => {- const [snapshot, catalog, operations, submission, execution] = await Promise.all([+ const [snapshot, catalog, operations, submission, execution, commands] = await Promise.all([options.buildStore.read(build),buildCatalog?.read(build),options.operationStore.list({ build }),options.submissionStore.read(build),options.executionStore.read(build),+ options.commandExecutionStore.list(build),]);return buildView({build,@@ -89,10 +93,14 @@ export function createLocalRuntimeControl(...(submission === undefined ? {} : { submission }),...(execution === undefined ? {} : { execution }),operations,+ commands,});};return {inspect,+ async logs(build, lines) {+ return await options.executionLogs?.read(build, lines);+ },async activity() {const [submissions, executions, capacity] = await Promise.all([options.submissionStore.list(),diff --git a/packages/runtime-local/src/executor.ts b/packages/runtime-local/src/executor.tsnew file mode 100644index 00000000..88222669--- /dev/null+++ b/packages/runtime-local/src/executor.ts@@ -0,0 +1,66 @@+import { setImmediate, setTimeout as pause } from "node:timers/promises";+import { NodeModuleScope } from "@hypit/package-loader-node/module-scope";+import { SqliteRuntimeState } from "@hypit/store-sqlite";+import { createRuntimeForBuild, statePath } from "./config.js";+import type { LocalRuntime } from "./types.js";++type Context = { readonly scope: NodeModuleScope; readonly runtime: LocalRuntime; task?: Promise<void> };++/** A shared execution carrier. Database readiness selects work; waiting is not an occupied process. */+export async function executeBuilds(dataRoot: string, signal: AbortSignal): Promise<void> {+ const state = new SqliteRuntimeState(statePath(dataRoot));+ const pending = new Set<string>();+ const contexts = new Map<string, Context>();+ const finished = (build: string, error?: unknown): void => {+ process.send?.({ kind: "build-finished", build, rssBytes: process.memoryUsage.rss(),+ ...(error === undefined ? {} : { error: error instanceof Error ? error.message : String(error) }) });+ };+ const receive = (message: unknown): void => {+ if (typeof message === "object" && message !== null && "kind" in message && message.kind === "start-build"+ && "build" in message && typeof message.build === "string") pending.add(message.build);+ };+ const close = async (build: string, context: Context): Promise<void> => {+ contexts.delete(build);+ try { await context.runtime.close(); } finally { context.scope.close(); }+ };+ process.on("message", receive);+ process.send?.({ kind: "executor-ready" });+ try {+ while (!signal.aborted) {+ for (const build of await state.execution.listReady()) {+ if (signal.aborted) break;+ let context = contexts.get(build);+ if (context === undefined && pending.delete(build)) {+ const scope = new NodeModuleScope();+ try {+ const runtime = await createRuntimeForBuild(dataRoot, build, { state, importModule: (url) => scope.import(url) });+ context = { scope, runtime };+ contexts.set(build, context);+ process.send?.({ kind: "executor-memory", rssBytes: process.memoryUsage.rss() });+ } catch (error) { scope.close(); finished(build, error); }+ }+ if (context === undefined || context.task !== undefined) continue;+ const current = context;+ let hydrated!: () => void;+ const hydration = new Promise<void>((resolve) => { hydrated = resolve; });+ current.task = current.runtime.workOnce({ build, hydrated }).then(async (result) => {+ if (result !== undefined && ("outcome" in result || result.decision !== undefined)) {+ await close(build, current); finished(build);+ }+ }).catch(async (error: unknown) => {+ await close(build, current).catch(() => undefined); finished(build, error);+ }).finally(() => { delete current.task; });+ // Only local hydration is sequenced. Slow submission/poll/collection continues+ // asynchronously while the next ready Build advances its independent work.+ await Promise.race([hydration, current.task]);+ await setImmediate();+ }+ await pause(25, undefined, { signal }).catch((error) => { if (!signal.aborted) throw error; });+ }+ } finally {+ process.removeListener("message", receive);+ await Promise.allSettled([...contexts.values()].flatMap((item) => item.task === undefined ? [] : [item.task]));+ await Promise.allSettled([...contexts].map(([build, context]) => close(build, context)));+ state.close();+ }+}diff --git a/packages/runtime-local/src/host.ts b/packages/runtime-local/src/host.tsindex 1d3b3265..7d499c38 100644--- a/packages/runtime-local/src/host.ts+++ b/packages/runtime-local/src/host.ts@@ -5,6 +5,7 @@ import type {} from "@hypit/runtime-host-node";import { hypitHostStateRoot } from "@hypit/runtime-host-node";import { resolve } from "node:path";+import { superviseBuilds } from "./supervisor.js";import {createRuntimeControlFromConfig,@@ -82,8 +83,8 @@ export async function openLocalRuntimeHost(},programs: {up: async (programOptions) => await bringManagedProgramsUp(profile, { ...programOptions, packageRoot, ...distribution }),- down: async () => await takeManagedProgramsDown(profile, { packageRoot, ...distribution }),- report: async () => await reportManagedPrograms(profile, { packageRoot, ...distribution }),+ down: async (scope) => await takeManagedProgramsDown(profile, { ...scope, packageRoot, ...distribution }),+ report: async (scope) => await reportManagedPrograms(profile, { ...scope, packageRoot, ...distribution }),},};};@@ -102,7 +103,7 @@ export async function openLocalRuntimeHost(};},controller,- createRuntime: async () => await createRuntimeFromConfig(profile, { packageRoot: basePackageRoot, ...distribution }),+ createRuntime: async (scope) => await createRuntimeFromConfig(profile, { packageRoot: basePackageRoot, ...distribution, ...scope }),openControl: async (options) => await createRuntimeControlFromConfig(profile, {packageRoot: basePackageRoot,...distribution,@@ -121,16 +122,19 @@ export async function openLocalRuntimeHost(packageRoot: basePackageRoot,...distribution,...(options?.onProgress === undefined ? {} : { onProgress: options.onProgress }),+ ...(options?.endpoints === undefined ? {} : { endpoints: options.endpoints }),}),preflight: async (options) => await preflightRuntimeConfig(profile, {packageRoot: basePackageRoot,...distribution,...(options?.capabilities === undefined ? {} : { capabilities: options.capabilities }),+ ...(options?.endpoints === undefined ? {} : { endpoints: options.endpoints }),}),doctor: async (options) => await doctorRuntimeConfig(profile, {packageRoot: basePackageRoot,...distribution,...(options?.capabilities === undefined ? {} : { capabilities: options.capabilities }),+ ...(options?.endpoints === undefined ? {} : { endpoints: options.endpoints }),}),providers: async (capabilities) => await describeRuntimeConfigProviders(profile, capabilities, {packageRoot: basePackageRoot,@@ -140,34 +144,50 @@ export async function openLocalRuntimeHost(packageRoot: basePackageRoot,...distribution,}),- invoke: async (need, resources) => await invokeRuntimeConfigNeed(profile, need, resources, {+ invoke: async (need, resources, observation) => await invokeRuntimeConfigNeed(profile, need, resources, {packageRoot: basePackageRoot,...distribution,+ ...observation,}),openTransientExecution: async () => await openTransientRuntimeConfigExecution(profile, {packageRoot: basePackageRoot,...distribution,}),- runWorker: async (readyFile, owner) => {- let runtime: Awaited<ReturnType<typeof createRuntimeFromConfig>> | undefined;+ runWorker: async (readyFile, owner, execution) => {const abort = new AbortController();- const stop = (): void => abort.abort();+ const stop = (): void => { abort.abort(); };+ // A Build never survives loss of its supervisor by silently changing code owners.+ const disconnected = (): never => process.exit(1);+ const message = (value: unknown): void => {+ if (typeof value === "object" && value !== null && "kind" in value && value.kind === "stop-execution") stop();+ };process.once("SIGTERM", stop);process.once("SIGINT", stop);+ if (execution !== undefined) {+ process.once("disconnect", disconnected);+ process.on("message", message);+ }try {- runtime = await createRuntimeFromConfig(profile, {- packageRoot: basePackageRoot,- ...distribution,- });- await runtime.work({- idlePollMs: 250,- signal: abort.signal,- ready: async () => await markRuntimeProcessReady(readyFile, owner),- });+ if (execution !== undefined) {+ const { executeBuilds } = await import("./executor.js");+ await executeBuilds(execution.dataRoot, abort.signal);+ } else {+ const paths = await resolveRuntimeConfigPaths(profile, { packageRoot: basePackageRoot, ...distribution });+ await superviseBuilds({+ profile, dataRoot: paths.dataRoot, readyFile, owner,+ launch: hostOptions.workerLaunch, signal: abort.signal,+ ready: async () => await markRuntimeProcessReady(readyFile, owner),+ });+ }+ } catch (error) {+ if (execution !== undefined && process.connected) process.send?.({ kind: "execution-error", message: error instanceof Error ? error.message : String(error) });+ throw error;} finally {process.removeListener("SIGTERM", stop);process.removeListener("SIGINT", stop);- await runtime?.close();+ process.removeListener("disconnect", disconnected);+ process.removeListener("message", message);+ if (execution !== undefined && process.connected) process.disconnect();}},};diff --git a/packages/runtime-local/src/log.ts b/packages/runtime-local/src/log.tsnew file mode 100644index 00000000..fd185da9--- /dev/null+++ b/packages/runtime-local/src/log.ts@@ -0,0 +1,48 @@+import { createReadStream } from "node:fs";+import { appendFile, mkdir, stat } from "node:fs/promises";+import { join } from "node:path";+import { readExecutionLog } from "@hypit/runtime";+import type { ExecutionLogEvent, ExecutionLogRecord, ExecutionLogView } from "@hypit/runtime";++export type LocalExecutionLogs = {+ record(build: string, command: string, event: ExecutionLogEvent): Promise<void>;+ open(build: string): Promise<AsyncIterable<Uint8Array> | undefined>;+ read(build: string, lines: number): Promise<ExecutionLogView | undefined>;+};++/** Append-only Build evidence. Queues coordinate writes, not execution or historical lookup. */+export function fileExecutionLogs(workDirectory: (build: string) => string): LocalExecutionLogs {+ const pending = new Map<string, Promise<void>>();+ const failures = new Map<string, unknown>();+ const path = (build: string) => join(workDirectory(build), "execution.jsonl");+ const open = async (build: string): Promise<AsyncIterable<Uint8Array> | undefined> => {+ await pending.get(build);+ if (failures.has(build)) throw new Error(`Build ${build} execution log could not be saved`, { cause: failures.get(build) });+ try { await stat(path(build)); }+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw error; }+ // Open only when the Repository consumes the stream, so a failed destination opens no source handle.+ return (async function* () { yield* createReadStream(path(build)); })();+ };+ return {+ async record(build, command, event) {+ const record: ExecutionLogRecord = { ...event, format: "hypit.execution-log@1", time: Date.now(), command };+ const write = (pending.get(build) ?? Promise.resolve()).then(async () => {+ await mkdir(workDirectory(build), { recursive: true });+ await appendFile(path(build), `${JSON.stringify(record)}\n`, "utf8");+ }).catch((error) => { failures.set(build, error); });+ pending.set(build, write);+ await write;+ if (pending.get(build) === write) pending.delete(build);+ },+ open,+ async read(build, lines) {+ const chunks = await open(build);+ try { return chunks === undefined ? undefined : await readExecutionLog(chunks, lines); }+ catch (error) {+ // The Result may have finished and cleaned work between opening an active view and reading it.+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;+ throw error;+ }+ },+ };+}diff --git a/packages/runtime-local/src/programs.ts b/packages/runtime-local/src/programs.tsindex aa21af93..2ebf67f6 100644--- a/packages/runtime-local/src/programs.ts+++ b/packages/runtime-local/src/programs.ts@@ -46,6 +46,7 @@ export type ManagedProgramOptions = LoadRuntimeConfigOptions & {readonly onProgress?: (event: ManagedProgramProgress) => void;/** When present, operate only programs backing at least one demanded capability. */readonly capabilities?: readonly CapabilityRef[];+ readonly endpoints?: readonly string[];};function independentPrograms(programs: readonly { instance: string; program: ManagedProgram }[]) {@@ -266,7 +267,7 @@ async function bringUp(const installLogPath = join(directory(root, program), "install.log");if (program.installation !== undefined) {const installation = await program.installation.probe();- if (installation.state !== "ready") {+ if (installation.state !== "ready" || program.installation.prepareBeforeStart === true) {await mkdir(directory(root, program), { recursive: true });await rotateLog(installLogPath);onProgress?.({ id: program.id, phase: "installing", logPath: installLogPath });diff --git a/packages/runtime-local/src/result-writer.ts b/packages/runtime-local/src/result-writer.tsindex 375d6a9a..1db43967 100644--- a/packages/runtime-local/src/result-writer.ts+++ b/packages/runtime-local/src/result-writer.ts@@ -150,7 +150,9 @@ export function createLocalResultWriter(...(operation.failure === undefined ? {} : { failure: operation.failure }),};});+ const executionLog = await options.executionLogs?.open(execution.build);await reopened.writer.finish({+ ...(executionLog === undefined ? {} : { executionLog }),operations,outcome: execution.decision.outcome,...(execution.decision.reason === undefined ? {} : { failure: execution.decision.reason }),diff --git a/packages/runtime-local/src/runtime.ts b/packages/runtime-local/src/runtime.tsindex cc245b85..4d003261 100644--- a/packages/runtime-local/src/runtime.ts+++ b/packages/runtime-local/src/runtime.ts@@ -153,6 +153,7 @@ export async function createLocalRuntime(validators,});const resultWriter = createLocalResultWriter({+ ...(options.executionLogs === undefined ? {} : { executionLogs: options.executionLogs }),buildStore: options.buildStore,operationStore: options.operationStore,commandExecutionStore: options.commandExecutionStore,@@ -165,6 +166,8 @@ export async function createLocalRuntime(openBuildResultRepository,});const worker = createDurableLocalWorker(driver, {+ ...(options.executionBuild === undefined ? {} : { executionBuild: options.executionBuild }),+ ...(options.executionLogs === undefined ? {} : { executionLogs: options.executionLogs }),stores: {builds: options.buildStore,operations: options.operationStore,@@ -174,7 +177,6 @@ export async function createLocalRuntime(resourceStore: options.resourceStore,...(options.resourceStoreForBuild === undefined ? {} : { resourceStoreForBuild: options.resourceStoreForBuild }),openBuildResultRepository,- ...(options.assertEnvironment === undefined ? {} : { assertEnvironment: options.assertEnvironment }),installComponentPackages,resultWriter,});@@ -183,7 +185,9 @@ export async function createLocalRuntime(endpoints: options.endpoints ?? [],});const control = createLocalRuntimeControl({+ ...(options.executionLogs === undefined ? {} : { executionLogs: options.executionLogs }),buildStore: options.buildStore,+ commandExecutionStore: options.commandExecutionStore,buildCatalog,operationStore: options.operationStore,executionStore: options.executionStore,@@ -256,6 +260,7 @@ export async function createLocalRuntime(const resultRequest = request.result;const executionRequest = {build: request.id,+ ...(options.executionContext === undefined ? {} : { context: options.executionContext }),componentPackages: [...new Set(request.componentPackages ?? [])].sort(),result: resultRequest.repository,} as const;@@ -331,11 +336,8 @@ export async function createLocalRuntime(...credentialControl,...resultWriter,build: runBuild,- async workOnce() {- return await worker.runOnce();- },- async work(workOptions) {- await worker.run(workOptions);+ async workOnce(workOptions) {+ return await worker.runOnce(workOptions);},close() {return options.close?.();diff --git a/packages/runtime-local/src/supervisor.ts b/packages/runtime-local/src/supervisor.tsnew file mode 100644index 00000000..c2cf0929--- /dev/null+++ b/packages/runtime-local/src/supervisor.ts@@ -0,0 +1,142 @@+import { spawn, type ChildProcess } from "node:child_process";+import { setTimeout as pause } from "node:timers/promises";+import { SqliteRuntimeState } from "@hypit/store-sqlite";+import type { RuntimeWorkerLaunch } from "./worker-process.js";+import { createRuntimeResultWriter, localExecutionContext, readRuntimeWorkerOptions, statePath } from "./config.js";++type Carrier = { readonly child: ChildProcess; readonly builds: Set<string>; readonly ready: Promise<void>;+ done: Promise<void>; exited: boolean; stopping: boolean; completed: number; rssBytes: number };++/** Owns execution-carrier lifetimes, not project implementations. */+export async function superviseBuilds(options: {+ readonly profile: string;+ readonly dataRoot: string;+ readonly readyFile: string;+ readonly owner: string;+ readonly launch: RuntimeWorkerLaunch;+ readonly signal: AbortSignal;+ readonly ready: () => Promise<void>;+}): Promise<void> {+ const { executionMemoryMb } = await readRuntimeWorkerOptions(options.profile);+ const memoryBudget = executionMemoryMb * 1024 * 1024;+ const state = new SqliteRuntimeState(statePath(options.dataRoot));+ const carriers = new Set<Carrier>();+ let accepting: Carrier | undefined;+ const considerRetirement = (carrier: Carrier): void => {+ // Retire accumulated completed work. Live work alone is not a reason to multiply+ // processes, and a cold process above the budget must still be able to accept work.+ if (accepting === carrier && carrier.completed > 0 && carrier.rssBytes >= memoryBudget) {+ accepting = undefined;+ process.stderr.write(`Executor ${carrier.child.pid}: draining at ${Math.ceil(carrier.rssBytes / 1024 / 1024)} MiB; active Builds continue in place\n`);+ }+ };+ const finishInterrupted = async (build: string, reason: string): Promise<void> => {+ const current = await state.execution.read(build);+ if (current === undefined) return;+ const decided = await state.execution.interrupt(build, reason);+ try {+ const writer = createRuntimeResultWriter(options.dataRoot, localExecutionContext(current.context));+ try { await writer.completeResult(decided); }+ finally { await writer.close(); }+ } catch (error) {+ await state.execution.setAttention(build, { step: "result", error: error instanceof Error ? error.message : String(error) });+ }+ };+ const launch = (): Carrier => {+ const child = spawn(options.launch.command, [+ ...options.launch.args, "_worker", options.profile,+ "--ready-file", options.readyFile, "--worker-owner", options.owner,+ "--execution-root", options.dataRoot,+ ], {+ stdio: ["ignore", "inherit", "inherit", "ipc"], windowsHide: true,+ // Node's CommonJS evaluation callback needs this for scoped dynamic import().+ env: { ...process.env, NODE_OPTIONS: [process.env.NODE_OPTIONS, "--experimental-vm-modules"].filter(Boolean).join(" ") },+ });+ let detail: string | undefined;+ let ready!: () => void;+ let rejectReady!: (error: Error) => void;+ let reports = Promise.resolve();+ const carrier: Carrier = { child, builds: new Set(), ready: new Promise((resolve, reject) => { ready = resolve; rejectReady = reject; }),+ done: Promise.resolve(), exited: false, stopping: false, completed: 0, rssBytes: 0 };+ child.on("message", (message: unknown) => {+ if (typeof message !== "object" || message === null || !("kind" in message)) return;+ if (message.kind === "executor-ready") ready();+ if ("rssBytes" in message && typeof message.rssBytes === "number" && Number.isFinite(message.rssBytes)) {+ carrier.rssBytes = message.rssBytes;+ considerRetirement(carrier);+ }+ if (message.kind === "execution-error" && "message" in message && typeof message.message === "string") detail = message.message;+ if (message.kind === "build-finished" && "build" in message && typeof message.build === "string") {+ const build = message.build;+ reports = reports.then(async () => {+ if (!carrier.builds.has(build)) throw new Error(`Unassigned Build ${build} reported completion`);+ if ("error" in message && typeof message.error === "string") await finishInterrupted(build, message.error);+ carrier.builds.delete(build);+ carrier.completed++;+ considerRetirement(carrier);+ });+ void reports.catch((error) => { detail = String(error); child.kill(); });+ }+ });+ const exited = new Promise<void>((resolve) => {+ child.once("error", (error) => { detail = error.message; rejectReady(error); });+ child.once("close", (code, signal) => {+ carrier.exited = true;+ detail ??= `Build executor exited (${signal ?? code ?? "unknown"}); create a new Build to continue`;+ rejectReady(new Error(detail)); resolve();+ });+ });+ carrier.done = exited.then(async () => {+ await reports.catch(() => undefined);+ for (const build of carrier.builds) await finishInterrupted(build, detail!);+ }).finally(() => {+ carriers.delete(carrier);+ if (accepting === carrier) accepting = undefined;+ });+ void carrier.done.catch((error) => { process.stderr.write(`Executor: ${String(error)}\n`); });+ carriers.add(carrier);+ return carrier;+ };+ try {+ await state.execution.reclaimResultWrites();+ for (const execution of await state.execution.list()) {+ if (execution.decision === undefined && execution.startedAt !== undefined) {+ await finishInterrupted(execution.build, "Build executor was lost; its code context is gone. Create a new Build to continue");+ } else if (execution.decision !== undefined && execution.attention === undefined) {+ await state.execution.setAttention(execution.build, { step: "result", error: "Result writing was interrupted; run hypit result finish <build-id>" });+ }+ }+ await state.execution.reclaimActionCapacity();+ await options.ready();+ while (!options.signal.aborted) {+ for (const carrier of carriers) {+ if (carrier.builds.size !== 0 || carrier.stopping || carrier.exited) continue;+ carrier.stopping = true;+ if (carrier.child.connected) carrier.child.send({ kind: "stop-execution" }, () => undefined);+ if (accepting === carrier) accepting = undefined;+ }+ for (const build of await state.execution.listUnstarted()) {+ if (options.signal.aborted) break;+ accepting ??= launch();+ const carrier = accepting;+ await carrier.ready;+ if (carrier.exited) break;+ if (accepting !== carrier) continue;+ await state.execution.start(build);+ carrier.builds.add(build);+ try {+ await new Promise<void>((resolve, reject) => carrier.child.send({ kind: "start-build", build }, (error) => error ? reject(error) : resolve()));+ } catch (error) {+ await finishInterrupted(build, `Build dispatch failed: ${String(error)}; create a new Build to continue`);+ carrier.builds.delete(build);+ if (accepting === carrier) accepting = undefined;+ }+ }+ await pause(100, undefined, { signal: options.signal }).catch((error) => { if (!options.signal.aborted) throw error; });+ }+ } finally {+ for (const { child } of carriers) if (child.connected) child.send({ kind: "stop-execution" }, () => undefined);+ await Promise.allSettled([...carriers].map(({ done }) => done));+ state.close();+ }+}diff --git a/packages/runtime-local/src/types.ts b/packages/runtime-local/src/types.tsindex 44c79898..afb2aa68 100644--- a/packages/runtime-local/src/types.ts+++ b/packages/runtime-local/src/types.ts@@ -21,13 +21,16 @@ import type {} from "@hypit/runtime-host-node";export type CreateLocalRuntimeOptions = {+ /** Already assigned by the local coordinator. Embeddings omit this and start fresh work. */+ readonly executionBuild?: string;+ readonly executionContext?: import("@hypit/protocol").CanonicalValue;+ readonly executionLogs?: import("./log.js").LocalExecutionLogs;readonly buildStore: BuildStore;/** Host presentation metadata only; never part of Core state. */readonly buildCatalog: BuildCatalog;readonly operationStore: OperationStore;/** Durable receipt boundary: one immediate Command is never invoked twice for one Build. */readonly commandExecutionStore: import("@hypit/runtime").CommandExecutionStore;- readonly assertEnvironment?: () => Awaitable<void>;readonly executionStore: import("@hypit/runtime").BuildExecutionStore;readonly removeActiveBuild: (build: string) => Awaitable<BuildCompletion>;/** Atomic submission boundary: external preparation is never a claimable partial Build. */@@ -49,7 +52,9 @@ export type CreateLocalRuntimeOptions = {};export type CreateLocalRuntimeControlOptions = {+ readonly executionLogs?: import("./log.js").LocalExecutionLogs;readonly buildStore: BuildStore;+ readonly commandExecutionStore: import("@hypit/runtime").CommandExecutionStore;readonly buildCatalog?: BuildCatalog;readonly operationStore: OperationStore;readonly executionStore: BuildExecutionStore;@@ -59,6 +64,7 @@ export type CreateLocalRuntimeControlOptions = {};export type CreateLocalResultWriterOptions = {+ readonly executionLogs?: import("./log.js").LocalExecutionLogs;readonly buildStore: BuildStore;readonly operationStore: OperationStore;readonly commandExecutionStore: import("@hypit/runtime").CommandExecutionStore;@@ -83,7 +89,8 @@ export type LocalBuildOptions = Parameters<RuntimeHostExecution["build"]>[1];export type LocalBuildSubmission = RuntimeHostBuildSubmission;export type LocalRuntime = RuntimeHostExecution & {- workOnce(): Promise<BuildExecutionSnapshot | BuildCompletion | undefined>;+ /** Advance owned or unstarted work only. Process lifecycle belongs to the Runtime Host. */+ workOnce(options?: { readonly build?: string; readonly hydrated?: () => void }): Promise<BuildExecutionSnapshot | BuildCompletion | undefined>;};/** Active execution control that never opens the selected ResourceStore. */diff --git a/packages/runtime-local/src/worker-process.ts b/packages/runtime-local/src/worker-process.tsindex de7de136..5f13d1c4 100644--- a/packages/runtime-local/src/worker-process.ts+++ b/packages/runtime-local/src/worker-process.ts@@ -3,7 +3,6 @@ import { randomUUID } from "node:crypto";import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";import { dirname, join, resolve } from "node:path";-import { canonicalStringify } from "@hypit/protocol";import { processAlive, stopProcessTree } from "./process-control.js";import { readProcessLogs } from "./process-logs.js";@@ -17,7 +16,6 @@ export type RuntimeWorkerLaunch = {export type RuntimeProcessState = {readonly state: "running" | "stopped";- readonly configuration?: "current" | "changed";readonly profile: string;readonly pid?: number;readonly startedAt?: number;@@ -26,7 +24,6 @@ export type RuntimeProcessState = {type ProcessRecord = {readonly profile: string;- readonly profileConfig: string;readonly owner: string;readonly pid: number;readonly startedAt: number;@@ -68,12 +65,11 @@ async function rotateLog(path: string): Promise<void> {await rename(path, previous);}-async function record(profile: string, dataRoot: string): Promise<ProcessRecord | undefined> {+async function record(dataRoot: string): Promise<ProcessRecord | undefined> {const path = paths(dataRoot).pid;try {const value = JSON.parse(await readFile(path, "utf8")) as ProcessRecord;- if (value.profile !== resolve(profile)- || typeof value.profileConfig !== "string" || value.profileConfig.length === 0+ if (typeof value.profile !== "string" || value.profile.length === 0|| typeof value.owner !== "string" || value.owner.length === 0|| !Number.isSafeInteger(value.pid) || value.pid < 1|| !Number.isSafeInteger(value.startedAt) || value.startedAt < 0) {@@ -86,10 +82,6 @@ async function record(profile: string, dataRoot: string): Promise<ProcessRecord}}-async function profileConfig(profile: string): Promise<string> {- return canonicalStringify(JSON.parse(await readFile(resolve(profile), "utf8")));-}-async function readyOwner(path: string): Promise<string | undefined> {try {const value = (await readFile(path, "utf8")).trim();@@ -105,13 +97,12 @@ export async function runtimeProcessStatus(dataRoot: string,): Promise<RuntimeProcessState> {const location = paths(dataRoot);- const current = await record(profile, dataRoot);+ const current = await record(dataRoot);if (current === undefined || !processAlive(current.pid)) {return { state: "stopped", profile: resolve(profile), logPath: location.log };}return {state: "running",- configuration: current.profileConfig === await profileConfig(profile) ? "current" : "changed",profile: current.profile,pid: current.pid,startedAt: current.startedAt,@@ -159,7 +150,7 @@ async function waitForReady(const location = paths(dataRoot);const deadline = Date.now() + timeoutMs;while (Date.now() <= deadline) {- const current = await record(profile, dataRoot);+ const current = await record(dataRoot);if (current === undefined || !processAlive(current.pid)) {const log = await readProcessLogs(location.log, LOG_TAIL_BYTES);throw new Error(`Runtime Worker exited before becoming ready${log.length === 0 ? "" : `: ${log.trim().split("\n").at(-1)}`}`);@@ -197,18 +188,14 @@ export async function ensureRuntimeProcess(try {const current = await runtimeProcessStatus(profile, dataRoot);if (current.state === "running") {- if (current.configuration === "changed") {- throw new Error("Runtime Profile changed while its Worker is running; stop and start the Worker to activate it");- }return current;}- const stale = await record(profile, dataRoot).catch(() => undefined);+ const stale = await record(dataRoot).catch(() => undefined);if (stale !== undefined && !processAlive(stale.pid)) {await rm(location.pid, { force: true });await rm(location.ready, { force: true });}const owner = `worker_${randomUUID()}`;- const activeProfileConfig = await profileConfig(absolute);await rm(location.ready, { force: true });await rotateLog(location.log);const log = await open(location.log, "a");@@ -252,7 +239,6 @@ export async function ensureRuntimeProcess(const startedAt = Date.now();await writeFile(location.pid, JSON.stringify({profile: absolute,- profileConfig: activeProfileConfig,owner,pid: child.pid,startedAt,@@ -260,9 +246,6 @@ export async function ensureRuntimeProcess(child.unref?.();try {const ready = await waitForReady(absolute, dataRoot, owner, timeoutMs);- if (ready.configuration === "changed") {- throw new Error("Runtime Profile changed while its Worker was starting; start it again to activate the new Profile");- }return ready;} catch (error) {const stopped = await stopProcessTree(child.pid, true).catch(() => "denied" as const);@@ -272,7 +255,7 @@ export async function ensureRuntimeProcess({ cause: error },);}- const saved = await record(profile, dataRoot).catch(() => undefined);+ const saved = await record(dataRoot).catch(() => undefined);if (saved?.owner === owner) {await rm(location.pid, { force: true });await rm(location.ready, { force: true });@@ -288,7 +271,7 @@ export async function ensureRuntimeProcess(}async function stopRuntimeProcessUnlocked(profile: string, dataRoot: string, timeoutMs: number): Promise<RuntimeProcessState> {- const current = await record(profile, dataRoot);+ const current = await record(dataRoot);const location = paths(dataRoot);if (current === undefined || !processAlive(current.pid)) {await rm(location.pid, { force: true });diff --git a/packages/runtime-local/src/worker.ts b/packages/runtime-local/src/worker.tsindex 3c2f6b17..c4961bcf 100644--- a/packages/runtime-local/src/worker.ts+++ b/packages/runtime-local/src/worker.ts@@ -1,5 +1,4 @@import { randomUUID } from "node:crypto";-import { setImmediate } from "node:timers/promises";import type { BuildState } from "@hypit/protocol";import type {ResourceStore,@@ -10,12 +9,13 @@ import type {RuntimePreparation,RuntimeRunnableCommand,ScheduledBuildResult,- RuntimeWorkerRunOptions,} from "@hypit/runtime";import { LocalBuildScheduler } from "@hypit/runtime";import { BuildMachine } from "@hypit/core";type LocalWorkerOptions = {+ readonly executionBuild?: string;+ readonly executionLogs?: import("./log.js").LocalExecutionLogs;readonly stores: {readonly builds: import("@hypit/runtime").BuildStore;readonly operations: import("@hypit/runtime").OperationStore;@@ -25,7 +25,6 @@ type LocalWorkerOptions = {readonly resourceStore: ResourceStore;readonly resourceStoreForBuild?: (build: string) => ResourceStore;readonly openBuildResultRepository: NonNullable<import("./types.js").CreateLocalRuntimeOptions["openBuildResultRepository"]>;- readonly assertEnvironment?: () => Promise<void> | void;readonly installComponentPackages: (specifiers: readonly string[]) => Promise<void>;readonly resultWriter: import("./types.js").LocalResultWriter;};@@ -36,28 +35,6 @@ function assert(condition: unknown, message: string): asserts condition {if (!condition) throw new Error(message);}-function positive(value: number, subject: string): number {- assert(Number.isSafeInteger(value) && value > 0, `${subject} must be a positive safe integer`);- return value;-}--async function pause(ms: number, signal?: AbortSignal): Promise<void> {- if (signal?.aborted === true) throw signal.reason ?? new Error("Worker stopped");- await new Promise<void>((resolve, reject) => {- const done = (): void => {- signal?.removeEventListener("abort", abort);- resolve();- };- const timer = setTimeout(done, ms);- const abort = (): void => {- clearTimeout(timer);- signal?.removeEventListener("abort", abort);- reject(signal?.reason ?? new Error("Worker stopped"));- };- signal?.addEventListener("abort", abort, { once: true });- });-}-/** Shares declared capacity across independently advancing Builds. */class CapacityExecutor implements RuntimeCommandExecutor {readonly #delegate: RuntimeCommandExecutor;@@ -87,9 +64,13 @@ class CapacityExecutor implements RuntimeCommandExecutor {context: { readonly build: string },): Promise<RuntimeExecutionResult> {const store = this.#options.stores.executions;+ const recordExecution = this.#options.executionLogs === undefined ? {} : {+ recordExecution: (event: import("@hypit/runtime").ExecutionLogEvent) =>+ this.#options.executionLogs!.record(context.build, descriptor.command.id, event),+ };if (descriptor.capacityMode === "asynchronous") {return await this.#delegate.executeCommand(state, descriptor, {- ...context, releaseOperationCapacity: () => this.#options.stores.execution.releaseCapacity(context.build, descriptor.command.id),+ ...context, ...recordExecution, releaseOperationCapacity: () => this.#options.stores.execution.releaseCapacity(context.build, descriptor.command.id),});}const begun = await store.begin(context.build, descriptor.command.id);@@ -107,7 +88,10 @@ class CapacityExecutor implements RuntimeCommandExecutor {return { status: "completed", event };}try {- const result = await this.#delegate.executeCommand(state, descriptor, context);+ const result = await this.#delegate.executeCommand(state, descriptor, {+ ...context, ...recordExecution,+ reportProgress: (activity) => store.reportProgress(context.build, descriptor.command.id, activity),+ });assert(result.status === "completed",`Immediate Command ${descriptor.command.id} returned ${result.status}`);await store.complete(context.build, descriptor.command.id, result.event);@@ -190,11 +174,13 @@ class DurableLocalWorker {readonly #options: LocalWorkerOptions;readonly #executorWithCapacity: CapacityExecutor;readonly #owner = randomUUID();+ readonly #ownedBuilds = new Set<string>();#buildRead = Promise.resolve();constructor(executor: RuntimeCommandExecutor, options: LocalWorkerOptions) {this.#executor = executor;this.#options = options;+ if (options.executionBuild !== undefined) this.#ownedBuilds.add(options.executionBuild);this.#executorWithCapacity = new CapacityExecutor(executor, options, this.#owner);}@@ -247,7 +233,14 @@ class DurableLocalWorker {}if (execution.stop.cause === "user-cancelled") {for (const operation of await this.#options.stores.operations.list({ build: execution.build })) {- if (operation.status === "pending") await this.#executor.cancelOperation?.(machine.view(), operation);+ if (operation.status === "pending") {+ const cancelled = await this.#executor.cancelOperation?.(machine.view(), operation);+ if (cancelled !== undefined) await this.#options.executionLogs?.record(operation.build, operation.command, {+ endpoint: operation.endpoint, kind: "diagnostic", level: "info",+ message: `Cancellation: ${cancelled.cancellation?.outcome ?? "unsupported"}${+ cancelled.cancellation?.message === undefined ? "" : `; ${cancelled.cancellation.message}`}`,+ });+ }}}}@@ -322,7 +315,13 @@ class DurableLocalWorker {hydrated?.();const actions = await Promise.allSettled(pending.map(async (operation) => {if (operation === undefined) throw new Error(`Build ${execution.build} lost a waiting Operation`);- const result = await this.#executor.advanceOperation!(operation);+ const result = await this.#executor.advanceOperation!(operation, {+ build: operation.build,+ ...(this.#options.executionLogs === undefined ? {} : {+ recordExecution: (event: import("@hypit/runtime").ExecutionLogEvent) =>+ this.#options.executionLogs!.record(operation.build, operation.command, event),+ }),+ });if (result.remoteEnded || result.status !== "pending") {await this.#options.stores.execution.releaseCapacity(execution.build, result.command);}@@ -380,65 +379,38 @@ class DurableLocalWorker {return finished;}- async runOnce(): Promise<WorkerTurnResult | undefined> {- await this.#options.assertEnvironment?.();- const execution = await this.#options.stores.execution.claim(this.#owner, Date.now());- if (execution === undefined) return undefined;- const [result] = await this.#runClaimed([execution]);- return result;- }-- async run(options: RuntimeWorkerRunOptions): Promise<void> {- positive(options.idlePollMs, "Worker idlePollMs");- const active = new Set<Promise<void>>();- // The Runtime Host admits one Worker process. Any stored turn owner therefore belongs to the- // previous process; clearing it changes no external fact and performs no Result action.- await this.#options.assertEnvironment?.();- await this.#options.stores.execution.reclaimActionCapacity();- await this.#options.stores.execution.reclaimTurns(Date.now());- await this.#options.stores.execution.reclaimResultWrites();- for (const execution of await this.#options.stores.execution.list()) {- if (execution.decision !== undefined && execution.attention === undefined) {- await this.#options.stores.execution.setAttention(execution.build, {- step: "result",- error: "Result writing was interrupted; run `hypit result finish <build-id>`",- });- }+ async runOnce(options: { readonly build?: string; readonly hydrated?: () => void } = {}): Promise<WorkerTurnResult | undefined> {+ const store = this.#options.stores.execution;+ const assigned = this.#options.executionBuild;+ if (assigned !== undefined && options.build !== undefined && options.build !== assigned) {+ throw new Error(`This execution context belongs to Build ${assigned}, not ${options.build}`);}- await options.ready?.();- try {- while (options.signal?.aborted !== true) {- await this.#options.assertEnvironment?.();- while (!Boolean(options.signal?.aborted)) {- const execution = await this.#options.stores.execution.claim(this.#owner, Date.now());- if (execution === undefined) break;- let markHydrated!: () => void;- const hydration = new Promise<void>((resolve) => { markHydrated = resolve; });- let task: Promise<void>;- task = this.#runClaimed([execution], markHydrated)- .then(() => undefined)- .finally(() => active.delete(task));- active.add(task);- // The next Build may execute concurrently, but its persisted snapshot is- // not hydrated until this one has left the single-threaded JSON boundary.- await Promise.race([hydration, task]);- // Awaiting synchronous stores only drains microtasks. Let sockets, timers and- // stop signals run before claiming another piece of ready work.- await setImmediate();+ const selected = options.build ?? assigned;+ for (const build of selected === undefined ? await store.listReady() : [selected]) {+ const current = await store.read(build);+ if (current === undefined || current.decision !== undefined) continue;+ if (current.startedAt !== undefined && !this.#ownedBuilds.has(build)) {+ if (selected === undefined) continue;+ throw new Error(`Build ${build} already belongs to another execution context; create a new Build to continue`);+ }+ const execution = await store.claim(this.#owner, Date.now(), build);+ if (execution === undefined) continue;+ if (!this.#ownedBuilds.has(build)) {+ if (execution.startedAt !== undefined) {+ await store.releaseTurn(build, this.#owner, execution.wakeAt, execution.operationWait);+ throw new Error(`Build ${build} was assigned to another execution context`);}- const idle = new AbortController();- const signal = options.signal === undefined ? idle.signal : AbortSignal.any([idle.signal, options.signal]);- try {- await Promise.race([...active, pause(options.idlePollMs, signal)]);- } catch (error) {- if (!Boolean(options.signal?.aborted)) throw error;- } finally { idle.abort(); }-+ await store.start(build);+ this.#ownedBuilds.add(build);}- } finally {- await Promise.allSettled(active);+ const [result] = await this.#runClaimed([execution], options.hydrated);+ if (result !== undefined && ("outcome" in result || result.decision !== undefined)) this.#ownedBuilds.delete(build);+ return result;}+ return undefined;}++}export function createDurableLocalWorker(diff --git a/packages/runtime-local/test/concurrency-process.test.ts b/packages/runtime-local/test/concurrency-process.test.tsnew file mode 100644index 00000000..77c47b47--- /dev/null+++ b/packages/runtime-local/test/concurrency-process.test.ts@@ -0,0 +1,131 @@+import assert from "node:assert/strict";+import { createServer, type ServerResponse } from "node:http";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { setTimeout as pause } from "node:timers/promises";+import test from "node:test";+import { defineBuild } from "@hypit/core";+import { FileBuildResultRepository } from "@hypit/build-result";+import { SqliteRuntimeState } from "@hypit/store-sqlite";+import { createGreetingBuild, manifest, capabilities, producers, types } from "../../core/test/greeting-fixture.js";+import { statePath } from "../src/config.js";+import { superviseBuilds } from "../src/supervisor.js";++const distribution = fileURLToPath(new URL("../../../", import.meta.url));+async function until(predicate: () => boolean | Promise<boolean>): Promise<void> {+ const deadline = Date.now() + 90_000;+ while (!await predicate()) {+ if (Date.now() >= deadline) throw new Error("Expected concurrency progress within 90 seconds");+ await pause(25);+ }+}++for (const scenario of [{ count: 100, capacity: 8 }, { count: 1000, capacity: 1000 }]) {+ test(`${scenario.count} Builds advance local work while remote capacity is ${scenario.capacity}`, { timeout: 120_000 }, async (t) => {+ const root = await mkdtemp(join(tmpdir(), "hypit-many-builds-"));+ const dataRoot = join(root, "runtime");+ const profile = join(root, "profile.json");+ const state = new SqliteRuntimeState(statePath(dataRoot));+ const repository = new FileBuildResultRepository(join(root, "results"));+ const abort = new AbortController();+ let supervision: Promise<void> | undefined;+ let submitted = false, completed = false;+ const pending: ServerResponse[] = [];+ const local = new Set<string>(), starts = new Set<string>(), processes = new Set<number>();+ let peakRss = 0;+ const server = createServer(async (request, response) => {+ const parts: Buffer[] = [];+ for await (const chunk of request) parts.push(Buffer.from(chunk));+ const body = JSON.parse(Buffer.concat(parts).toString()) as { name: string; pid: number; rss: number };+ const send = () => response.end(JSON.stringify({ complete: completed }));+ if (request.url === "/a") { local.add(body.name); send(); }+ else if (request.url === "/submit") {+ assert.ok(!starts.has(body.name), `Build ${body.name} must submit only once`);+ starts.add(body.name); processes.add(body.pid); peakRss = Math.max(peakRss, body.rss);+ if (submitted) send(); else pending.push(response);+ } else send();+ });+ server.listen(0, "127.0.0.1");+ await new Promise<void>((resolve) => server.once("listening", resolve));+ const address = server.address(); assert.ok(address && typeof address === "object");+ const endpoint = `http://127.0.0.1:${address.port}`;+ try {+ const pkg = join(root, "node_modules", "fixture-concurrency");+ await mkdir(pkg, { recursive: true });+ await writeFile(join(pkg, "package.json"), JSON.stringify({ name: "fixture-concurrency", version: "1.0.0", type: "module", hypit: { activation: "./activation.mjs" } }));+ await writeFile(join(pkg, "activation.mjs"), `+ import {createRuntimeEndpointAdapterFacet} from '@hypit/runtime-kit';+ import {defineEndpointPackage} from '@hypit/endpoint-kit';+ const server=${JSON.stringify(endpoint)};+ async function call(path,name){const response=await fetch(server+path,{method:'POST',body:JSON.stringify({name,pid:process.pid,rss:process.memoryUsage().rss})});return response.json();}+ let localCount=0;+ export default {format:'hypit.node-package@1',modules:[{manifest:${JSON.stringify(manifest)}}],components:[{producers:[+ {producer:${JSON.stringify(producers.makePrompt)},handler:async({inputs})=>{+ if(++localCount!==1)throw Error('Component state leaked between Builds');+ const name=inputs.intent.value.value.name;await call('/a',name);+ return {outputs:{prompt:{kind:'inline',value:name}},needs:{}};+ }},+ {producer:${JSON.stringify(producers.requestText)},handler:({inputs})=>({outputs:{},needs:{generation:{prompt:inputs.prompt.value.value}}})}+ ]}],hostFacets:[createRuntimeEndpointAdapterFacet({use:'fixture-concurrency',activate(context){+ return {endpoint:defineEndpointPackage({module:{name:'fixture.provider',version:'1'},facet:'generation',instance:context.instance,pool:context.pool,+ defaultConcurrency:${scenario.capacity},actionLimits:{submit:{concurrency:${scenario.capacity}}},capabilities:[{lifecycle:'asynchronous',capability:${JSON.stringify(capabilities.generation)},returns:${JSON.stringify(types.generated)},endpoint:{+ async start({need,operation}){const name=need.constraints.prompt;await call('/submit',name);return {status:'pending',handle:{name},receipt:{id:operation},wakeAt:Date.now()+250};},+ async poll({handle}){const result=await call('/poll',handle.name);return result.complete?{status:'completed',result:{value:{kind:'inline',value:handle.name}}}:{status:'pending',handle,wakeAt:Date.now()+1000};}+ }}]})};+ }})]};+ `);+ const profileValue = { format: "hypit.runtime-local@1", dataRoot, credentials: {},+ endpoints: { selected: { use: "fixture-concurrency", pool: "shared" } }, bindings: {} };+ await writeFile(profile, JSON.stringify(profileValue));+ const initial = createGreetingBuild({ targetOutputs: ["generated"] });+ const authored = new Set(initial.program.records.map((record) => record.id));+ const base = defineBuild({ program: initial.program, initialRecords: initial.records.filter((record) => !authored.has(record.id)), plan: initial.plan, targets: initial.targets });+ const ids: string[] = [];+ for (let index = 0; index < scenario.count; index++) {+ const id = `bld_20260914T120000000Z_${String(index).padStart(10,"0")}`;+ ids.push(id);+ const request = { build: id, componentPackages: ["fixture-concurrency"],+ result: { root, selection: { use: "@hypit/build-result-fs", config: { path: "results" } } },+ context: { format: "hypit.local-execution@1", packageRoot: root, hostStateRoot: join(root,"host"), distributionPackageRoot: distribution, profile: profileValue },+ };+ await state.submissions.prepare(request);+ await repository.create({ id, source: { path: "main.svml" }, targets: ["generated"], publishedOutputs: [{name:"generated",output:"generated"}] });+ await state.submissions.commit({ ...request,+ definition: { ...base, program: { ...base.program, records: base.program.records.map((record) => record.id === "intent:root"+ ? { ...record, value: { kind: "inline", value: { name: String(index) } } } : record) } },+ catalog: { source: { path: join(root,"main.svml") }, publishedOutputs: [{name:"generated",ref:{kind:"logical-output",id:"generated"}}] },+ });+ }+ const startedAt = Date.now();+ supervision = superviseBuilds({ profile, dataRoot, readyFile: join(root,"ready"), owner:"concurrency-test", launch:{command:process.execPath,args:[join(distribution,"bin/hypit.mjs")]}, signal:abort.signal,ready:async()=>{} });+ await until(() => local.size === scenario.count && starts.size === scenario.capacity);+ assert.equal(processes.size, 1, "remote requests share one process, with private module bindings per Build");+ assert.equal((await state.execution.listCapacity()).length, scenario.capacity * 2, "each submitting operation owns its task and submit-action reservations");+ const allLocalAt = Date.now();+ submitted = true;+ for (const response of pending) response.end(JSON.stringify({complete:false}));+ await until(async () => (await state.operations.list({})).filter((item) => item.receipt !== undefined).length === scenario.capacity);+ assert.equal(local.size, scenario.count, "the remote wait must not prevent any local A step");+ completed = true;+ await until(async () => (await state.execution.list()).length === 0);+ assert.equal(starts.size, scenario.count);+ assert.equal((await state.execution.listCapacity()).length, 0);+ for (let index = 0; index < ids.length; index++) {+ const result = await repository.read(ids[index]!);+ assert.equal(result?.outcome, "complete", `Build ${index}`);+ const output = await repository.resolve(ids[index]!, "generated");+ assert.equal(output?.value.kind, "inline");+ assert.equal(output?.value.kind === "inline" ? output.value.value : undefined, String(index));+ }+ t.diagnostic(`local-ready=${allLocalAt-startedAt}ms total=${Date.now()-startedAt}ms executor-rss=${Math.round(peakRss/1024/1024)}MiB processes=${processes.size}`);+ } finally {+ completed = true; submitted = true;+ for (const response of pending) if (!response.writableEnded) response.end(JSON.stringify({complete:true}));+ abort.abort(); await supervision;+ server.closeAllConnections(); await new Promise<void>((resolve) => server.close(() => resolve()));+ state.close(); await rm(root,{recursive:true,force:true});+ }+ });+}diff --git a/packages/runtime-local/test/config.test.ts b/packages/runtime-local/test/config.test.tsindex cef4594b..485120bb 100644--- a/packages/runtime-local/test/config.test.ts+++ b/packages/runtime-local/test/config.test.ts@@ -109,6 +109,13 @@ test("Local Runtime Profile names credentials and Endpoints, not project resultassert.deepEqual(parsed.endpoints, [{ use: "example.provider", instance: "generation", pool: "shared" }]);});+test("execution memory policy belongs to the local Worker, with an explicit MiB budget", () => {+ assert.deepEqual(parseLocalRuntimeProfile({ ...profile(), worker: { executionMemoryMb: 768 } }).worker,+ { executionMemoryMb: 768 });+ assert.throws(() => parseLocalRuntimeProfile({ ...profile(), worker: { executionMemoryMb: 0 } }), /positive integer/u);+ assert.throws(() => parseLocalRuntimeProfile({ ...profile(), worker: { executionMemoryMb: 768, maxBuilds: 8 } }), /maxBuilds/u);+});+test("Build Result repositories default to the project path and can be selected explicitly", async () => {const root = await mkdtemp(join(tmpdir(), "hypit-runtime-results-"));const defaultProject = join(root, "default-project");@@ -685,9 +692,11 @@ test("Runtime invoke executes one immediate Need through the selected Endpoint acapability: observe,returns,lifecycle: "immediate",- handler: ({ need, credentials }) => ({- value: { kind: "inline", value: { seen: need.constraints, key: credentials.apiKey?.secret ?? null } },- }),+ handler: async ({ need, credentials, reportProgress, reportDiagnostic }) => {+ await reportProgress?.({ phase: "Aligning words" });+ await reportDiagnostic?.({ level: "info", message: "Timing ready" });+ return { value: { kind: "inline", value: { seen: need.constraints, key: credentials.apiKey?.secret ?? null } } };+ },}],}),}),@@ -717,9 +726,15 @@ test("Runtime invoke executes one immediate Need through the selected Endpoint aid: "need:creation-time", capability, returns, constraints: { question: "what happens?" }, result: "record:creation-time",});try {- assert.deepEqual(await invokeRuntimeConfigNeed(path, need(observe), resources, { registry }), {+ const messages: string[] = [];+ assert.deepEqual(await invokeRuntimeConfigNeed(path, need(observe), resources, {+ registry,+ reportProgress: async (event) => { messages.push(event.phase); },+ reportDiagnostic: async (event) => { messages.push(event.message); },+ }), {value: { kind: "inline", value: { seen: { question: "what happens?" }, key: "configured" } },});+ assert.deepEqual(messages, ["Aligning words", "Timing ready"]);await assert.rejects(invokeRuntimeConfigNeed(path, need(missing), resources, { registry }), /No Endpoint in .* serves example\.model@1#transcribe/u);await assert.rejects(invokeRuntimeConfigNeed(path, need(generate), resources, { registry }), /asynchronous capability/u);configured = false;@@ -863,3 +878,44 @@ test("doctor reports inconsistent limits for shared pools and capacity resourcesawait rm(root, { recursive: true, force: true });}});++test("demanded readiness and Programs follow the chosen Endpoint, including before package loading", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-chosen-readiness-"));+ const path = join(root, "runtime.json");+ const capability = { module: { name: "example.speech", version: "1" }, name: "transcribe" } as const;+ const returns = { module: { name: "example.value", version: "1" }, name: "Text" } as const;+ let chosen = "local";+ const registry = new RuntimeAdapterRegistry();+ registry.registerFacet(createRuntimeCredentialStoreAdapterFacet({+ use: "example.keys", validate() {},+ open: () => ({ value: { resolve: async () => chosen === "hosted" ? { secret: "fixture" } : undefined } }),+ }));+ for (const name of ["local", "hosted"]) registry.registerFacet(createRuntimeEndpointAdapterFacet({+ use: `example.${name}`,+ activate: (context) => ({+ endpoint: defineEndpointPackage({+ module: { name: `example.${name}`, version: "1" }, facet: name,+ instance: context.instance, pool: context.instance, pricing: { kind: "local" },+ ...(name === "hosted" ? { credentials: { key: credentialRef("keys", "account") } } : {}),+ capabilities: [{ capability, returns, lifecycle: "immediate", handler: () => ({ value: { kind: "inline", value: "ok" } }) }],+ }),+ ...(name === "local" ? { program: { id: "local-service", probe: async () => chosen === "local"+ ? { state: "ready" as const } : { state: "down" as const, detail: "not selected" } } } : {}),+ }),+ }));+ try {+ const { declaredManagedPrograms } = await import("../src/config.js");+ for (chosen of ["local", "hosted"]) {+ await writeFile(path, JSON.stringify(profile({ dataRoot: ".", credentials: { keys: { use: "example.keys" } },+ endpoints: { local: { use: "example.local" }, hosted: { use: "example.hosted" }, later: { use: "uninstalled.future.provider" } },+ bindings: { "example.speech@1#transcribe": chosen },+ })));+ assert.deepEqual((await preflightRuntimeConfig(path, { registry, capabilities: [capability] })).diagnostics, []);+ assert.deepEqual((await preflightRuntimeConfig(path, { registry, endpoints: [chosen] })).diagnostics, []);+ const programs = await declaredManagedPrograms(path, { registry, capabilities: [capability] });+ assert.deepEqual(programs.programs.map((item) => item.instance), chosen === "local" ? ["local"] : []);+ }+ assert.deepEqual((await preflightRuntimeConfig(path, { endpoints: [] })).diagnostics, []);+ await assert.rejects(preflightRuntimeConfig(path, { registry, endpoints: ["typo"] }), /no Endpoint typo/);+ } finally { await rm(root, { recursive: true, force: true }); }+});diff --git a/packages/runtime-local/test/execution-process.test.ts b/packages/runtime-local/test/execution-process.test.tsnew file mode 100644index 00000000..f0bd20bb--- /dev/null+++ b/packages/runtime-local/test/execution-process.test.ts@@ -0,0 +1,188 @@+import assert from "node:assert/strict";+import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { setTimeout as pause } from "node:timers/promises";+import test from "node:test";+import { defineBuild } from "@hypit/core";+import { FileBuildResultRepository } from "@hypit/build-result";+import { installDistributionPackageResolution } from "@hypit/package-loader-node";+import { SqliteRuntimeState } from "@hypit/store-sqlite";+import { createGreetingBuild, manifest, capabilities, producers, types } from "../../core/test/greeting-fixture.js";+import { createRuntimeFromConfig, statePath } from "../src/config.js";+import { superviseBuilds } from "../src/supervisor.js";++const repository = fileURLToPath(new URL("../../../", import.meta.url));+const cli = join(repository, "bin/hypit.mjs");+installDistributionPackageResolution([repository]);+async function eventually<T>(read: () => Promise<T | undefined>): Promise<T> {+ const deadline = Date.now() + 30_000;+ while (Date.now() < deadline) {+ const value = await read();+ if (value !== undefined) return value;+ await pause(30);+ }+ throw new Error("Expected execution progress within 30 seconds");+}+async function exists(path: string): Promise<boolean> { return access(path).then(() => true, () => false); }++test("isolated Builds load fresh transitive code and Profile choices, share capacity, and retain failed attempts", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-build-scope-"));+ const dataRoot = join(root, "runtime");+ const project = join(root, "project-a");+ const otherProject = join(root, "project-b");+ const profile = join(root, "runtime.json");+ const abort = new AbortController();+ let supervision: Promise<void> | undefined;+ const state = new SqliteRuntimeState(statePath(dataRoot));+ const runtimes: Awaited<ReturnType<typeof createRuntimeFromConfig>>[] = [];+ const requests: string[] = [];+ async function packageAt(directory: string, revision: string) {+ const pkg = join(directory, "node_modules", "fixture-components");+ await mkdir(pkg, { recursive: true });+ await writeFile(join(directory, "package.json"), JSON.stringify({ private: true }));+ await writeFile(join(pkg, "package.json"), JSON.stringify({ name: "fixture-components", version: "1.0.0", type: "module", hypit: { activation: "./activation.ts" } }));+ await writeFile(join(pkg, "revision.ts"), `export const revision: string = ${JSON.stringify(revision)};`);+ await writeFile(join(pkg, "activation.ts"), `+ import { revision } from './revision.js';+ import { access, writeFile, appendFile } from 'node:fs/promises';+ import { setTimeout as pause } from 'node:timers/promises';+ import { createRuntimeEndpointAdapterFacet } from '@hypit/runtime-kit';+ import { defineEndpointPackage } from '@hypit/endpoint-kit';+ const producers = ${JSON.stringify(producers)};+ export default {+ format: 'hypit.node-package@1', modules: [{ manifest: ${JSON.stringify(manifest)} }],+ components: [{ producers: [+ { producer: producers.makePrompt, handler: () => ({ outputs: { prompt: { kind: 'inline', value: revision } }, needs: {} }) },+ { producer: producers.requestText, handler: ({ inputs }) => ({ outputs: {}, needs: { generation: { prompt: inputs.prompt.value.value } } }) },+ { producer: producers.assemble, handler: ({ inputs }) => ({ outputs: { document: { kind: 'inline', value: { text: inputs.generated.value.value, revision } } }, needs: {} }) },+ ] }],+ hostFacets: [createRuntimeEndpointAdapterFacet({ use: 'fixture-components', activate(context) {+ const config = context.config;+ return { endpoint: defineEndpointPackage({+ module: { name: 'fixture.provider', version: '1' }, facet: 'generation',+ instance: context.instance, pool: context.pool, defaultConcurrency: 1,+ capabilities: [config.remote ? {+ lifecycle: 'asynchronous', capability: ${JSON.stringify(capabilities.generation)}, returns: ${JSON.stringify(types.generated)},+ endpoint: {+ async start({ operation }) {+ await appendFile(config.entered, JSON.stringify({ pid: process.pid, operation }) + '\\n');+ return { status: 'pending', handle: { task: operation }, receipt: { id: operation }, wakeAt: Date.now() + 100 };+ },+ async poll({ handle }) {+ if (!await access(config.gate).then(() => true, () => false)) return { status: 'pending', handle, wakeAt: Date.now() + 100 };+ return { status: 'completed', result: { value: { kind: 'inline', value: revision + ':' + config.label } } };+ },+ async cancel() { await writeFile(config.gate + '.cancelled', ''); return { status: 'confirmed' }; }+ }+ } : {+ lifecycle: 'immediate', capability: ${JSON.stringify(capabilities.generation)}, returns: ${JSON.stringify(types.generated)},+ async handler() {+ await writeFile(config.entered, JSON.stringify({ revision, label: config.label, pid: process.pid }));+ while (!await access(config.gate).then(() => true, () => false)) await pause(25);+ return { value: { kind: 'inline', value: revision + ':' + config.label } };+ }+ }]++ }) };+ } })]+ };+ `);+ return pkg;+ }+ async function submit(name: string, directory: string, label: string, remote = false) {+ const id = `bld_20260913T12000000${requests.length}Z_0000000001`;+ requests.push(id);+ await writeFile(profile, JSON.stringify({ format: "hypit.runtime-local@1", dataRoot, credentials: {},+ endpoints: {+ selected: { use: "fixture-components", pool: "shared", config: { label, remote, gate: join(root, name + ".gate"), entered: join(root, name + ".entered") } },+ unused: { use: "this-provider-is-not-installed" },+ }, bindings: {} }));+ const runtime = await createRuntimeFromConfig(profile, { packageRoot: directory, distributionPackageRoot: repository, endpoints: ["selected"] });+ runtimes.push(runtime);+ const initial = createGreetingBuild();+ const authored = new Set(initial.program.records.map((record) => record.id));+ await runtime.build({ id,+ definition: defineBuild({ program: initial.program, initialRecords: initial.records.filter((record) => !authored.has(record.id)), plan: initial.plan, targets: initial.targets }),+ componentPackages: ["fixture-components"],+ catalog: { source: { path: join(directory, "main.svml") }, publishedOutputs: [{ name: "document", ref: { kind: "logical-output", id: "document" } }] },+ result: { repository: { root: directory, selection: { use: "@hypit/build-result-fs", config: { path: "results" } } } },+ });+ return id;+ }+ const completed = (directory: string, id: string) => eventually(async () => {+ const value = await new FileBuildResultRepository(join(directory, "results")).read(id);+ return value?.outcome === undefined ? undefined : value;+ });+ const value = async (directory: string, id: string) => {+ const output = await new FileBuildResultRepository(join(directory, "results")).resolve(id, "document");+ assert.equal(output?.value.kind, "value");+ return output?.value.kind === "value" ? output.value.document.value : undefined;+ };+ try {+ const pkg = await packageAt(project, "old");+ await packageAt(otherProject, "other-project");+ await writeFile(profile, JSON.stringify({ format: "hypit.runtime-local@1", dataRoot }));+ let ready!: () => void;+ const started = new Promise<void>((resolve) => { ready = resolve; });+ supervision = superviseBuilds({ profile, dataRoot, readyFile: join(root, "ready"), owner: "test-supervisor",+ launch: { command: process.execPath, args: [cli] }, signal: abort.signal, ready: async () => ready() });+ await started;+ const a = await submit("a", project, "old-profile");+ const first = await eventually(async () => exists(join(root, "a.entered")).then(async (ok) => ok ? JSON.parse(await readFile(join(root, "a.entered"), "utf8")) : undefined));+ await writeFile(join(pkg, "revision.ts"), `export const revision: string = 'new';`);+ const b = await submit("b", project, "new-profile");+ await eventually(async () => {+ const execution = await state.execution.read(b);+ return execution?.startedAt !== undefined && execution.wakeAt === undefined ? true : undefined;+ });+ assert.equal(await exists(join(root, "b.entered")), false, "shared capacity must hold B while A is executing");+ await writeFile(join(root, "b.gate"), "");+ await writeFile(join(root, "a.gate"), "");+ const [resultA, resultB] = await Promise.all([completed(project, a), completed(project, b)]);+ assert.equal(resultA.outcome, "complete");+ assert.equal(resultB.outcome, "complete");+ assert.deepEqual(await value(project, a), { text: "old:old-profile", revision: "old" });+ assert.deepEqual(await value(project, b), { text: "new:new-profile", revision: "new" });+ const second = JSON.parse(await readFile(join(root, "b.entered"), "utf8"));+ assert.equal(first.pid, second.pid, "isolated Build modules share one asynchronous execution carrier");+ await writeFile(join(root, "c.gate"), "");+ const c = await submit("c", otherProject, "third-profile");+ assert.equal((await completed(otherProject, c)).outcome, "complete");+ assert.deepEqual(await value(otherProject, c), { text: "other-project:third-profile", revision: "other-project" });+ const d = await submit("d", project, "lost-executor");+ const lost = await eventually(async () => exists(join(root, "d.entered")).then(async (ok) => ok ? JSON.parse(await readFile(join(root, "d.entered"), "utf8")) : undefined));+ process.kill(lost.pid, "SIGKILL");+ const failed = await completed(project, d);+ assert.equal(failed.outcome, "failed");+ assert.match(failed.failure!, /executor exited/u);+ assert.equal((await state.execution.listCapacity()).length, 0);+ const e = await submit("e", project, "remote-job", true);+ const remote = await eventually(async () => {+ const [operation] = await state.operations.list({ build: e });+ const ended = await new FileBuildResultRepository(join(project, "results")).read(e);+ if (ended?.outcome !== undefined) throw new Error(JSON.stringify(ended));+ return operation?.receipt === undefined ? undefined : operation;+ });+ const remoteProcess = JSON.parse((await readFile(join(root, "e.entered"), "utf8")).trim());+ process.kill(remoteProcess.pid, "SIGKILL");+ const remoteFailed = await completed(project, e);+ assert.equal(remoteFailed.outcome, "failed");+ assert.deepEqual(remoteFailed.operations?.[0]?.receipt, remote.receipt);+ assert.equal((await readFile(join(root, "e.entered"), "utf8")).trim().split("\n").length, 1);+ const f = await submit("f", project, "cancel-job", true);+ await eventually(async () => (await state.operations.list({ build: f }))[0]?.receipt);+ await state.execution.requestStop(f, { cause: "user-cancelled", reason: "user cancelled" });+ assert.equal((await completed(project, f)).outcome, "cancelled");+ assert.equal(await exists(join(root, "f.gate.cancelled")), true);+ assert.equal((await state.execution.listCapacity()).length, 0);+ } finally {+ for (const name of ["a", "b", "c", "d", "e", "f"]) await writeFile(join(root, name + ".gate"), "").catch(() => undefined);+ abort.abort();+ await supervision;+ await Promise.all(runtimes.map((runtime) => runtime.close()));+ state.close();+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/packages/runtime-local/test/local.test.ts b/packages/runtime-local/test/local.test.tsindex 48af1da0..0fa538bc 100644--- a/packages/runtime-local/test/local.test.ts+++ b/packages/runtime-local/test/local.test.ts@@ -1,3 +1,5 @@+import { fileExecutionLogs } from "../src/log.js";+import { readExecutionLog } from "@hypit/runtime";import assert from "node:assert/strict";import {mkdir,@@ -55,6 +57,7 @@ function projectRuntimeFixture(directory: string) {const state = new SqliteRuntimeState(join(directory, ".hypit", "runtime.sqlite"));const work = join(directory, ".hypit", "work");return {+ executionLogs: fileExecutionLogs((build) => join(work, build)),buildStore: state.builds,buildCatalog: state.catalog,operationStore: state.operations,@@ -105,28 +108,6 @@ function durableBuildRequest(} as const;}-test("a Worker does not claim a Build when the pinned Runtime environment differs", async () => {- const directory = await mkdtemp(join(tmpdir(), "hypit-local-worker-owner-"));- const initial = createGreetingBuild();- try {- const runtime = await createLocalRuntime({- ...projectRuntimeFixture(directory),- assertEnvironment: () => {- throw new Error("Runtime Profile no longer matches this Worker's active environment");- },- });- await runtime.build(durableBuildRequest(directory, "bld_20260902T120000000Z_0000000001", initial));-- await assert.rejects(runtime.workOnce(), /no longer matches this Worker's active environment/u);- const status = await runtime.inspect("bld_20260902T120000000Z_0000000001");- assert.equal(status?.activity, "ready");- assert.deepEqual(status?.requests, { total: 1, completed: 0 });- await runtime.close();- } finally {- await rm(directory, { recursive: true, force: true });- }-});-async function finishClaimedBuild(runtime: Awaited<ReturnType<typeof createLocalRuntime>>,): Promise<BuildCompletion> {@@ -139,6 +120,27 @@ async function finishClaimedBuild(? "none" : "wakeAt" in snapshot ? buildExecutionActivity(snapshot) : "removed"}`);}+// An embedding test supplies implementations explicitly and advances their owned turns.+// Production process lifecycle is exercised through superviseBuilds in the process tests.+async function runFixture(runtime: Awaited<ReturnType<typeof createLocalRuntime>>,+ store: import("@hypit/runtime").BuildExecutionStore,+ options: {idlePollMs:number,signal:AbortSignal}): Promise<void> {+ const active = new Map<string,Promise<void>>();+ let failure: unknown;+ try {+ while (!options.signal.aborted && failure === undefined) {+ for (const build of await store.listReady()) {+ if (active.has(build)) continue;+ const task = runtime.workOnce({build}).then(() => undefined)+ .catch((error: unknown) => { failure = error; }).finally(() => active.delete(build));+ active.set(build,task);+ }+ await new Promise((resolve) => setTimeout(resolve,options.idlePollMs));+ }+ } finally { await Promise.all(active.values()); }+ if (failure !== undefined) throw failure;+}+test("Endpoint-declared credentials use the selected writable Store without a Provider switch", async () => {const directory = await mkdtemp(join(tmpdir(), "hypit-local-auth-"));const values = new Map<string, CredentialValue>();@@ -301,6 +303,13 @@ test("project local Runtime advances, polls and cancels work with replaceable paassert.equal(buildExecutionActivity(firstTurn), "ready");assert.equal(starts, 1);assert.equal(polls, 0);+ assert.equal("work" in firstRuntime, false, "execution lifecycle belongs to the Runtime Host");+ const otherRuntime = await createLocalRuntime({ ...projectRuntimeFixture(directory), components:[components], endpoints:[endpointPackage] });+ try {+ assert.equal(await otherRuntime.workOnce(), undefined);+ await assert.rejects(otherRuntime.workOnce({build:"bld_20260902T120000001Z_0000000001"}), /another execution context/u);+ assert.equal(starts,1); assert.equal(polls,0);+ } finally { await otherRuntime.close(); }const second = await firstRuntime.inspect("bld_20260902T120000001Z_0000000001");assert.equal(second?.activity, "ready");assert.equal((await finishClaimedBuild(firstRuntime)).outcome, "complete");@@ -773,7 +782,7 @@ test("a selected file is staged once and remains referenced in the produced Compkind: "external-file", uri: pathToFileURL(inputPath).href, size: bytes.length, mediaType: historical.mediaType,}]);const resultDirectory = join(directory, "results", "2026-09-02", "bld_20260902T120000009Z_0000000001");- assert.deepEqual((await readdir(resultDirectory)).sort(), ["result.json", "values"]);+ assert.deepEqual((await readdir(resultDirectory)).sort(), ["execution.jsonl", "result.json", "values"]);assert.deepEqual(await readFile(inputPath), Buffer.from(bytes));await runtime.close();} finally {@@ -892,7 +901,7 @@ test("one local Worker admits later Builds while preserving shared Endpoint capa});await runtime.build(durableBuildRequest(directory, "bld_20260902T120000010Z_0000000001", createGreetingBuild()));controller = new AbortController();- work = runtime.work({ idlePollMs: 5, signal: controller.signal });+ work = runFixture(runtime, fixture.executionStore, { idlePollMs: 5, signal: controller.signal });await firstStarted;await runtime.build(durableBuildRequest(directory, "bld_20260902T120000011Z_0000000001", createGreetingBuild()));const results = new FileBuildResultRepository(join(directory, "results"));@@ -1215,7 +1224,7 @@ test("concurrent durable Builds preserve action capacity and outcomes across fai}const deadline = setTimeout(() => controller.abort(), 20_000);try {- work = runtime.work({ idlePollMs: 2, signal: controller.signal });+ work = runFixture(runtime, fixture.executionStore, { idlePollMs: 2, signal: controller.signal });while ((await fixture.executionStore.list()).length > 0 && !controller.signal.aborted) {await new Promise((resolve) => setTimeout(resolve, 10));}@@ -1240,3 +1249,57 @@ test("concurrent durable Builds preserve action capacity and outcomes across faiawait rm(directory, { recursive: true, force: true });}});++test("local call logs survive cleanup and remain attributed across concurrent successful and failed Builds", { timeout: 15_000 }, async () => {+ const directory = await mkdtemp(join(tmpdir(), "hypit-execution-logs-"));+ let calls = 0;+ const fixture = projectRuntimeFixture(directory);+ const runtime = await createLocalRuntime({+ ...fixture,+ endpoints: [defineEndpointPackage({ module: providerModule, facet: "generation", instance: "local-logs", pool: "local-logs", defaultConcurrency: 2,+ capabilities: [{ capability: capabilities.generation, returns: types.generated, lifecycle: "immediate", async handler(context) {+ const call = ++calls;+ for (let completed = 0; completed < 4; completed++) await context.reportProgress?.({ phase: "rendering", completed, total: 4 });+ await context.reportDiagnostic?.({ level: "info", message: `call ${call}` });+ await new Promise((resolve) => setTimeout(resolve, 30));+ if (call === 2) throw new Error("render rejected");+ await context.reportProgress?.({ phase: "storing" });+ return { value: { kind: "inline", value: `call ${call}` } };+ } }] })],+ components: [{ producers: [+ { producer: producers.makePrompt, handler: () => ({ outputs: { prompt: { kind: "inline", value: "hello" } }, needs: {} }) },+ { producer: producers.requestText, handler: () => ({ outputs: {}, needs: { generation: { prompt: "hello" } } }) },+ ] }],+ });+ const ids = ["bld_20260913T120000000Z_0000000001", "bld_20260913T120000000Z_0000000002"];+ const controller = new AbortController();+ let work: Promise<void> | undefined;+ try {+ for (const id of ids) await runtime.build(durableBuildRequest(directory, id, createGreetingBuild({ targetOutputs: ["generated"] })));+ // The Worker records evidence with no CLI follower attached.+ work = runFixture(runtime, fixture.executionStore, { signal: controller.signal, idlePollMs: 2 });+ while (calls < 2) await new Promise((resolve) => setTimeout(resolve, 1));+ assert.ok((await runtime.logs!(ids[0]!, 30))!.records.length > 0);+ while ((await runtime.activity()).builds.length) await new Promise((resolve) => setTimeout(resolve, 2));+ const repository = new FileBuildResultRepository(join(directory, "results"));+ const seen = new Set<string>();+ for (const id of ids) {+ assert.equal(await runtime.inspect(id), undefined);+ assert.equal(await stat(join(directory, ".hypit/work", id)).then(() => true, () => false), false);+ const manifest = (await repository.read(id))!;+ assert.ok(manifest.executionLog);+ const log = await readExecutionLog((await repository.openFile(id, manifest.executionLog))!, 50);+ assert.equal(log.records.filter((record) => record.kind === "started").length, 1);+ assert.equal(log.records.filter((record) => record.kind === "phase" && record.phase === "rendering").length, 1);+ assert.ok(log.records.every((record) => record.endpoint === "local-logs"));+ const diagnostic = log.records.find((record) => record.kind === "diagnostic")!;+ assert.equal(diagnostic.kind, "diagnostic");+ if (diagnostic.kind !== "diagnostic") throw new Error("missing diagnostic");+ seen.add(diagnostic.message);+ assert.equal(manifest.outcome, diagnostic.message === "call 1" ? "complete" : "failed");+ assert.equal(log.records.at(-1)?.kind, manifest.outcome === "complete" ? "completed" : "failed");+ assert.equal(Object.keys(manifest.outputs).some((key) => key.includes("execution")), false);+ }+ assert.deepEqual([...seen].sort(), ["call 1", "call 2"]);+ } finally { controller.abort(); await work; await runtime.close(); await rm(directory, { recursive: true, force: true }); }+});diff --git a/packages/runtime-local/test/log.test.ts b/packages/runtime-local/test/log.test.tsnew file mode 100644index 00000000..7cb0be14--- /dev/null+++ b/packages/runtime-local/test/log.test.ts@@ -0,0 +1,33 @@+import assert from "node:assert/strict";+import { appendFile, mkdtemp, rm, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { tmpdir } from "node:os";+import test from "node:test";+import { fileExecutionLogs } from "../src/log.js";++test("parallel appends form complete records, another reader sees their bounded tail", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-log-"));+ try {+ const logs = fileExecutionLogs((build) => join(root, build));+ await Promise.all(Array.from({ length: 40 }, (_, index) => logs.record("build", `c${index}`, {+ endpoint: "renderer", kind: "diagnostic", level: "info", message: `中文 ${index}\nsecond line`,+ })));+ const reader = fileExecutionLogs((build) => join(root, build));+ const view = (await reader.read("build", 3))!;+ assert.equal(view.total, 40);+ assert.deepEqual(view.records.map((item) => item.command), ["c37", "c38", "c39"]);+ await appendFile(join(root, "build/execution.jsonl"), '{"unfinished":');+ assert.deepEqual(await reader.read("build", 3), view);+ assert.equal(await reader.read("missing", 3), undefined);+ } finally { await rm(root, { recursive: true, force: true }); }+});++test("a logging failure is surfaced to Result writing without throwing into the external call", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-log-failure-"));+ try {+ await writeFile(join(root, "occupied"), "not a directory");+ const logs = fileExecutionLogs(() => join(root, "occupied"));+ await logs.record("build", "c1", { endpoint: "renderer", kind: "started" });+ await assert.rejects(logs.open("build"), /execution log could not be saved/);+ } finally { await rm(root, { recursive: true, force: true }); }+});diff --git a/packages/runtime-local/test/programs.test.ts b/packages/runtime-local/test/programs.test.tsindex 4f490bea..3336521e 100644--- a/packages/runtime-local/test/programs.test.ts+++ b/packages/runtime-local/test/programs.test.ts@@ -117,6 +117,26 @@ function fileBackedProgram(marker: string): ManagedProgram {};}+test("Provider-owned preparation reconciles a cold installation and leaves a ready Program alone", async () => {+ const configured = await project((root) => ({+ id: "reconciled",+ probe: async () => {+ try { await readFile(join(root, "prepared")); return { state: "ready" }; }+ catch { return { state: "down", detail: "not prepared" }; }+ },+ installation: {+ prepareBeforeStart: true,+ probe: async () => ({ state: "ready" }),+ commands: [nodeProgram("require('node:fs').appendFileSync(process.argv[1], 'prepared\\n')", join(root, "prepared"))],+ },+ }));+ try {+ assert.equal((await bringManagedProgramsUp(configured.path, configured.options)).programs[0]?.action, "installed");+ assert.equal((await bringManagedProgramsUp(configured.path, configured.options)).programs[0]?.action, "already-running");+ assert.equal(await readFile(join(configured.root, "prepared"), "utf8"), "prepared\n");+ } finally { await rm(configured.root, { recursive: true, force: true }); }+});+test("up preserves installation logs through service startup and down stops it", async () => {const marker = join(await mkdtemp(join(tmpdir(), "hypit-marker-")), "ready");const installed = `${marker}.installed`;diff --git a/packages/runtime-local/test/rotation-process.test.ts b/packages/runtime-local/test/rotation-process.test.tsnew file mode 100644index 00000000..d2ccdef2--- /dev/null+++ b/packages/runtime-local/test/rotation-process.test.ts@@ -0,0 +1,105 @@+import assert from "node:assert/strict";+import { spawn, type ChildProcess } from "node:child_process";+import { createServer } from "node:http";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { setTimeout as pause } from "node:timers/promises";+import test from "node:test";+import { defineBuild } from "@hypit/core";+import { FileBuildResultRepository } from "@hypit/build-result";+import { SqliteRuntimeState } from "@hypit/store-sqlite";+import { createGreetingBuild, manifest, capabilities, producers, types } from "../../core/test/greeting-fixture.js";+import { statePath } from "../src/config.js";++const distribution = fileURLToPath(new URL("../../../", import.meta.url));+async function until(predicate: () => boolean | Promise<boolean>, detail: () => string): Promise<void> {+ const deadline = Date.now()+20_000;+ while (!await predicate()) {+ if (Date.now()>deadline) throw new Error(`Expected rotation progress: ${detail()}`);+ await pause(20);+ }+}+function alive(pid: number): boolean { try { process.kill(pid,0); return true; } catch { return false; } }++test("a draining carrier finishes its existing Build while a new carrier shares resource limits", {timeout:40_000}, async () => {+ const root=await mkdtemp(join(tmpdir(),"hypit-carrier-rotation-"));+ const dataRoot=join(root,"runtime"), profile=join(root,"profile.json");+ const state=new SqliteRuntimeState(statePath(dataRoot));+ const repository=new FileBuildResultRepository(join(root,"results"));+ const local=new Map<string,number>(), starts=new Map<string,number>(), finished=new Set<string>();+ let child: ChildProcess | undefined, exited: Promise<void> | undefined, log="", release=false;+ const server=createServer(async(req,res)=>{+ const chunks:Buffer[]=[]; for await(const chunk of req) chunks.push(Buffer.from(chunk));+ const {name,pid}=JSON.parse(Buffer.concat(chunks).toString()) as {name:string,pid:number};+ if(req.url==='/local') local.set(name,pid);+ if(req.url==='/start') { assert.ok(!starts.has(name),`duplicate submission ${name}`); starts.set(name,pid); }+ res.end(JSON.stringify({complete:release}));+ });+ server.listen(0,'127.0.0.1'); await new Promise<void>(resolve=>server.once('listening',resolve));+ const address=server.address(); assert.ok(address && typeof address==='object');+ const endpoint=`http://127.0.0.1:${address.port}`;+ try {+ const pkg=join(root,'node_modules','fixture-rotation'); await mkdir(pkg,{recursive:true});+ await writeFile(join(root,'package.json'),'{"private":true}');+ await writeFile(join(pkg,'package.json'),JSON.stringify({name:'fixture-rotation',version:'1.0.0',type:'module',hypit:{activation:'./activation.mjs'}}));+ await writeFile(join(pkg,'activation.mjs'),`+ import {createRuntimeEndpointAdapterFacet} from '@hypit/runtime-kit';+ import {defineEndpointPackage} from '@hypit/endpoint-kit';+ const server=${JSON.stringify(endpoint)};+ async function call(path,name){return (await fetch(server+path,{method:'POST',body:JSON.stringify({name,pid:process.pid})})).json();}+ let calls=0;+ export default {format:'hypit.node-package@1',modules:[{manifest:${JSON.stringify(manifest)}}],components:[{producers:[+ {producer:${JSON.stringify(producers.makePrompt)},handler:async({inputs})=>{+ if(++calls!==1)throw Error('Build module state leaked');+ const name=inputs.intent.value.value.name;await call('/local',name);return {outputs:{prompt:{kind:'inline',value:name}},needs:{}};+ }},+ {producer:${JSON.stringify(producers.requestText)},handler:({inputs})=>({outputs:{},needs:{generation:{prompt:inputs.prompt.value.value}}})}+ ]}],hostFacets:[createRuntimeEndpointAdapterFacet({use:'fixture-rotation',activate(context){return {endpoint:defineEndpointPackage({+ module:{name:'fixture.provider',version:'1'},facet:'generation',instance:context.instance,pool:context.pool,defaultConcurrency:1,+ capabilities:[{lifecycle:'asynchronous',capability:${JSON.stringify(capabilities.generation)},returns:${JSON.stringify(types.generated)},endpoint:{+ async start({need,operation}){const name=need.constraints.prompt;await call('/start',name);return {status:'pending',handle:{name},receipt:{id:operation},wakeAt:Date.now()+50};},+ async poll({handle}){const result=await call('/poll',handle.name);return result.complete?{status:'completed',result:{value:{kind:'inline',value:handle.name}}}:{status:'pending',handle,wakeAt:Date.now()+50};}+ }}]})};}})]};+ `);+ // A deliberately tiny soft budget exercises retirement without allocating large buffers.+ const profileValue={format:'hypit.runtime-local@1',dataRoot,worker:{executionMemoryMb:1},credentials:{},endpoints:{selected:{use:'fixture-rotation',pool:'shared'}},bindings:{}};+ await writeFile(profile,JSON.stringify(profileValue));+ const ids=new Map<string,string>();+ async function submit(name:string,target:'prompt'|'generated'){+ const id=`bld_20260914T120000000Z_${String(ids.size).padStart(10,'0')}`;ids.set(name,id);+ const initial=createGreetingBuild({targetOutputs:[target]});const authored=new Set(initial.program.records.map(r=>r.id));+ const base=defineBuild({program:initial.program,initialRecords:initial.records.filter(r=>!authored.has(r.id)),plan:initial.plan,targets:initial.targets});+ const request={build:id,componentPackages:['fixture-rotation'],result:{root,selection:{use:'@hypit/build-result-fs',config:{path:'results'}}},+ context:{format:'hypit.local-execution@1',packageRoot:root,hostStateRoot:join(root,'host'),distributionPackageRoot:distribution,profile:profileValue}};+ await state.submissions.prepare(request);+ await repository.create({id,source:{path:'main.svml'},targets:[target],publishedOutputs:[{name:target,output:target}]});+ await state.submissions.commit({...request,definition:{...base,program:{...base.program,records:base.program.records.map(r=>r.id==='intent:root'?{...r,value:{kind:'inline',value:{name}}}:r)}},+ catalog:{source:{path:join(root,'main.svml')},publishedOutputs:[{name:target,ref:{kind:'logical-output',id:target}}]}});+ return id;+ }+ child=spawn(process.execPath,[join(distribution,'bin/hypit.mjs'),'_worker',profile,'--package-root',root,'--ready-file',join(root,'ready'),'--worker-owner','rotation-test'],{cwd:root,stdio:['ignore','pipe','pipe']});+ child.stdout!.on('data',data=>{log+=String(data);}); child.stderr!.on('data',data=>{log+=String(data);});+ exited=new Promise<void>((resolve,reject)=>{child!.once('error',reject);child!.once('close',()=>resolve());});+ const a=await submit('A','generated');await until(()=>starts.has('A'),()=>log);+ const oldPid=local.get('A')!;+ const b=await submit('B','prompt');+ await until(()=>log.includes(`Executor ${oldPid}: draining`),()=>log);+ assert.equal(local.get('B'),oldPid);assert.equal((await repository.read(b))?.outcome,'complete');+ const c=await submit('C','generated');await until(()=>local.has('C'),()=>log);+ const newPid=local.get('C')!;assert.notEqual(newPid,oldPid);assert.ok(alive(oldPid));+ await until(async()=>{const current=await state.execution.read(c);return current?.startedAt!==undefined && current.turn===undefined && current.wakeAt===undefined;},()=>log);+ assert.deepEqual([...starts.keys()],['A'],'new carrier shares the occupied remote pool');+ assert.equal((await repository.read(a))?.outcome,undefined);+ release=true;+ await until(async()=>{for(const [name,id] of ids){if((await repository.read(id))?.outcome==='complete')finished.add(name);}return finished.size===3;},()=>log);+ await until(()=>!alive(oldPid)&&!alive(newPid),()=>log);+ assert.deepEqual([...starts.keys()],['A','C']);assert.equal(starts.get('A'),oldPid);assert.equal(starts.get('C'),newPid);+ assert.equal((await state.execution.listCapacity()).length,0);+ assert.ok(child.exitCode===null,'coordinator stays available after both carriers drain');+ } finally {+ release=true;child?.kill('SIGTERM');await exited;+ server.closeAllConnections();await new Promise<void>(resolve=>server.close(()=>resolve()));state.close();await rm(root,{recursive:true,force:true});+ }+});diff --git a/packages/runtime-local/test/worker-process.test.ts b/packages/runtime-local/test/worker-process.test.tsindex 19bdecd8..5ee8351c 100644--- a/packages/runtime-local/test/worker-process.test.ts+++ b/packages/runtime-local/test/worker-process.test.ts@@ -85,13 +85,13 @@ test("one live detached Runtime Worker survives repeated starts and stale startuassert.equal(afterMissingStartupMarker.pid, first.pid);await writeFile(profile, JSON.stringify({ format: "hypit.runtime-local@1", changed: true }), "utf8");- assert.equal((await runtimeProcessStatus(profile, dataRoot)).configuration, "changed");- await assert.rejects(- ensureRuntimeProcess(profile, dataRoot, { command: "must-not-run", args: [] }, 5_000),- /Runtime Profile changed/u,- );+ assert.equal((await ensureRuntimeProcess(profile, dataRoot, { command: "must-not-run", args: [] }, 5_000)).pid, first.pid);- assert.equal((await stopRuntimeProcess(profile, dataRoot, 5_000)).state, "stopped");+ const otherProfile = join(root, "other-runtime.json");+ await writeFile(otherProfile, JSON.stringify({ format: "hypit.runtime-local@1", dataRoot }), "utf8");+ assert.equal((await ensureRuntimeProcess(otherProfile, dataRoot, { command: "must-not-run", args: [] }, 5_000)).pid, first.pid);+ assert.equal((await runtimeProcessStatus(otherProfile, dataRoot)).pid, first.pid);+ assert.equal((await stopRuntimeProcess(otherProfile, dataRoot, 5_000)).state, "stopped");assert.equal((await runtimeProcessStatus(profile, dataRoot)).state, "stopped");} finally {await stopRuntimeProcess(profile, dataRoot, 1_000).catch(() => undefined);diff --git a/packages/runtime/README.md b/packages/runtime/README.mdindex ecaa1932..bdd130af 100644--- a/packages/runtime/README.md+++ b/packages/runtime/README.md@@ -7,7 +7,7 @@ The package defines the small ports used by a runtime:* `BuildStore` keeps one active Build definition and its accepted facts until the Result is saved and active state is removed.* `OperationStore` keeps asynchronous external work only while the owning Build is active.* `PendingBuildStore` owns the short submission transaction before the Build becomes active.-* `BuildExecutionStore` owns active scheduling facts, a stop request, the immutable decision, attention and shared capacity reservations.+* `BuildExecutionStore` owns active scheduling facts, opaque Host execution choices, a stop request, the immutable decision, attention and shared capacity reservations.* `ResourceStore` is the transient byte gateway used during Provider execution.* `CredentialStore` resolves secrets outside source and build state.* `RuntimeCommandExecutor` turns the commands regenerated by Core into component or endpoint calls.@@ -37,3 +37,10 @@ Capacity claims describe occupancy; action rate budgets describe admissions overOperation holds its declared occupancy while Runtime manages the remote task. Its submit, poll andcollect actions can have separate concurrency and rate limits. Waiting claims park until a resourcerelease or their next eligible time; polling does not require rematerializing the whole Build.++The local Host uses one code context per Build. `claim(owner, now, build)` limits an executor to its+own work; `start` records launch, and `interrupt` concludes a lost executor after its owner confirms+exit. These stores do not prescribe processes or module loading. They retain one active execution+record, while components and Providers remain ordinary replaceable implementations.+There is no turn-reclaim operation that makes a lost attempt runnable again. Result-writer ownership+can be cleared independently so an already decided outcome can still be saved.diff --git a/packages/runtime/src/environment.ts b/packages/runtime/src/environment.tsdeleted file mode 100644index 39cbc8db..00000000--- a/packages/runtime/src/environment.ts+++ /dev/null@@ -1,6 +0,0 @@-export type RuntimeEnvironmentStore = {- /** Select this literal normalized configuration, changing it only when no Runtime work is active. */- use(config: string): Promise<void>;- /** Refuse work when this Runtime instance was assembled from a different active configuration. */- assert(config: string): Promise<void>;-};diff --git a/packages/runtime/src/execution.ts b/packages/runtime/src/execution.tsindex db2a4f1b..3569d999 100644--- a/packages/runtime/src/execution.ts+++ b/packages/runtime/src/execution.ts@@ -10,7 +10,9 @@ export type BuildOutcome = "complete" | "failed" | "cancelled";export type BuildExecutionRequest = {readonly build: string;- /** Installed component packages loaded when a Worker takes an execution turn. */+ /** Host-owned execution choices. Opaque to the graph and Core. */+ readonly context?: import("@hypit/protocol").CanonicalValue;+ /** Installed component packages loaded when this execution context starts. */readonly componentPackages: readonly string[];/** Exact project Result Repository selected at submission. */readonly result: BuildResultRepositoryLocation;@@ -48,6 +50,8 @@ export type BuildResultWriteLease = BuildExecutionTurn;*/export type BuildExecutionSnapshot = BuildExecutionRequest & {readonly createdAt: number;+ /** An execution context has been assigned; losing it ends this attempt. */+ readonly startedAt?: number;/** Absent when waiting for a resource release. */readonly wakeAt?: number;/** Only these Operations can advance the Build until their next outcome. */@@ -79,10 +83,14 @@ export type BuildExecutionStore = {create(request: BuildExecutionRequest, options?: { readonly now?: number }): Promise<BuildExecutionSnapshot>;read(build: string): Promise<BuildExecutionSnapshot | undefined>;list(): Promise<readonly BuildExecutionSnapshot[]>;+ /** Lightweight scheduling views; no Definition, Profile or Operation payloads are loaded. */+ listUnstarted(): Promise<readonly string[]>;+ listReady(now?: number): Promise<readonly string[]>;/** Atomically take one ready, undecided execution turn for this Worker owner. */- claim(owner: string, now?: number): Promise<BuildExecutionSnapshot | undefined>;- /** A new owning Worker clears turns left by the previous process; no external action is repeated here. */- reclaimTurns(now?: number): Promise<readonly string[]>;+ claim(owner: string, now?: number, build?: string): Promise<BuildExecutionSnapshot | undefined>;+ start(build: string, now?: number): Promise<BuildExecutionSnapshot>;+ /** Conclude after the owner confirms this execution context has ended. Never repeats external work. */+ interrupt(build: string, reason: string): Promise<BuildExecutionSnapshot>;/** An unobserved stop wakes the next turn immediately to finish the attempt. */releaseTurn(build: string, owner: string, wakeAt: number | undefined, operationWait?: readonly string[]): Promise<BuildExecutionSnapshot>;/** Freeze the one conclusion. An execution with a decision can never be claimed again. */@@ -106,6 +114,8 @@ export type CommandExecutionReceipt = {readonly command: string;readonly status: "started" | "completed";readonly event?: CommandResult;+ /** Current Provider-reported activity; discarded when this call completes. */+ readonly activity?: { readonly endpoint: string; readonly progress: import("./operations.js").OperationProgress };};export type CommandExecutionBegin = {@@ -119,6 +129,7 @@ export type CommandExecutionBegin = {*/export type CommandExecutionStore = {begin(build: string, command: string): Promise<CommandExecutionBegin>;+ reportProgress(build: string, command: string, activity: NonNullable<CommandExecutionReceipt["activity"]>): Promise<void>;complete(build: string, command: string, event: CommandResult): Promise<CommandExecutionReceipt>;list(build: string): Promise<readonly CommandExecutionReceipt[]>;removeBuild(build: string): Promise<void>;diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.tsindex 5166d655..f1e663ef 100644--- a/packages/runtime/src/index.ts+++ b/packages/runtime/src/index.ts@@ -14,7 +14,6 @@ export type * from "./capacity.js";export { capacityUnits } from "./capacity.js";export { buildExecutionActivity } from "./execution.js";export type * from "./execution.js";-export type * from "./environment.js";export type * from "./operations.js";export { LocalBuildScheduler } from "./scheduler.js";export type * from "./submission.js";@@ -22,3 +21,5 @@ export {isStreamingResourceStore,} from "./types.js";export type * from "./types.js";+export type * from "./log.js";+export { readExecutionLog } from "./log.js";diff --git a/packages/runtime/src/log.ts b/packages/runtime/src/log.tsnew file mode 100644index 00000000..bf2d88b4--- /dev/null+++ b/packages/runtime/src/log.ts@@ -0,0 +1,51 @@+/** Provider-authored diagnostic text suitable for users; never credentials or request bodies. */+export type ExecutionDiagnostic = {+ readonly level: "info" | "warning" | "error";+ readonly message: string;+ readonly stream?: "stdout" | "stderr";+};++export type ExecutionLogEvent = { readonly endpoint: string } & (+ | { readonly kind: "started" | "completed" }+ | { readonly kind: "failed"; readonly message: string }+ | { readonly kind: "phase"; readonly phase: string }+ | ({ readonly kind: "diagnostic" } & ExecutionDiagnostic)+);++export type ExecutionLogRecord = ExecutionLogEvent & {+ readonly format: "hypit.execution-log@1";+ readonly time: number;+ readonly command: string;+};++export type ExecutionLogView = {+ readonly records: readonly ExecutionLogRecord[];+ readonly total: number;+};++/** Read a bounded tail without loading the whole log. Storage and transport remain caller-owned. */+export async function readExecutionLog(chunks: AsyncIterable<Uint8Array>, limit: number): Promise<ExecutionLogView> {+ if (!Number.isSafeInteger(limit) || limit < 1) throw new Error("Log line count must be a positive integer");+ const decoder = new TextDecoder();+ const records: ExecutionLogRecord[] = [];+ let pending = "";+ let total = 0;+ const consume = (line: string) => {+ if (!line.trim()) return;+ const record = JSON.parse(line) as ExecutionLogRecord;+ if (record.format !== "hypit.execution-log@1") throw new Error("Unsupported execution log format");+ records[total % limit] = record;+ total++;+ };+ for await (const chunk of chunks) {+ pending += decoder.decode(chunk, { stream: true });+ let newline: number;+ while ((newline = pending.indexOf("\n")) >= 0) {+ consume(pending.slice(0, newline));+ pending = pending.slice(newline + 1);+ }+ }+ // A running writer may still be appending its last record; only complete lines are visible.+ const offset = total > limit ? total % limit : 0;+ return { records: [...records.slice(offset), ...records.slice(0, offset)], total };+}diff --git a/packages/runtime/src/types.ts b/packages/runtime/src/types.tsindex 83eb7da6..ac243e4e 100644--- a/packages/runtime/src/types.ts+++ b/packages/runtime/src/types.ts@@ -25,13 +25,6 @@ export type RuntimeRunnableCommand = {export type RuntimeResourceClaim = import("./capacity.js").CapacityResourceClaim;-export type RuntimeWorkerRunOptions = {- readonly idlePollMs: number;- readonly signal?: AbortSignal;- /** Called after abandoned work is claimable and immediately before the claim loop starts. */- readonly ready?: () => void | Promise<void>;-};-export type RuntimePreparation = {readonly state: BuildState;readonly runnable: readonly RuntimeRunnableCommand[];@@ -41,6 +34,10 @@ export type RuntimePreparation = {export type RuntimeExecutionContext = {/** Stable Run-local identity; two identical BuildRequests may still be distinct Builds. */readonly build: string;+ /** Observational activity of this call; it never changes scheduling or Core facts. */+ readonly reportProgress?: (activity: NonNullable<import("./execution.js").CommandExecutionReceipt["activity"]>) => Promise<void>;+ /** Execution evidence; the Runtime owns persistence. Implementations keep logging failures out of Provider outcomes. */+ readonly recordExecution?: (event: import("./log.js").ExecutionLogEvent) => Promise<void>;/** Release only the asynchronous Operation's occupancy after its remote end is confirmed. */readonly releaseOperationCapacity?: () => Promise<void>;};@@ -72,7 +69,7 @@ export type RuntimeCommandExecutor = {state: BuildState,operation: OperationSnapshot,): Promise<OperationSnapshot>;- advanceOperation?(operation: OperationSnapshot): Promise<OperationSnapshot>;+ advanceOperation?(operation: OperationSnapshot, context?: RuntimeExecutionContext): Promise<OperationSnapshot>;/** Validate an already received result without invoking a Producer or contacting an Endpoint. */acceptOperation?(state: BuildState, operation: OperationSnapshot): Promise<CommandResult | undefined>;};diff --git a/packages/seedance-kits/README.md b/packages/seedance-kits/README.mdindex 21d77ec9..b2023be2 100644--- a/packages/seedance-kits/README.md+++ b/packages/seedance-kits/README.md@@ -44,7 +44,7 @@ Speaker uses the same graph vocabulary. The Kit assumes `@image1` is the visible<seedance:ReferenceVideo id="hook-take" model="mini"prompt={hook-prompt} duration="8"resolution="720p" aspect-ratio="9:16" generate-audio="true">- <seedance:Reference image={presenter}/>+ <seedance:Reference image={presenter} person-reference="true"/><seedance:Reference audio={voice}/></seedance:ReferenceVideo>```@@ -153,3 +153,9 @@ Avoid exaggerated reactions or constantly moving every person simply to preventFor a multi-scene B-roll montage, `story` can name the references in scene order and give each a smallaction. Choose an edit language compatible with cuts. “Continuous within each scene” and “onecontinuous shot for the whole montage” ask for different results.++Visual input classification belongs to the Seedance Reference, separately from Kit text. The+[Seedance author package](../seedance/README.md#visual-reference-metadata) explains `person-reference`+and its frame variants. The Kit supplies direction; the actual reference edges supply media and+metadata. For movement-led work, a reference video can carry the motion while the text explains what+to preserve and change.diff --git a/packages/seedance/README.md b/packages/seedance/README.mdindex 4de8c996..f0ca7c4f 100644--- a/packages/seedance/README.md+++ b/packages/seedance/README.md@@ -1,7 +1,7 @@# `@hypit/seedance`Exact Seedance author model module. It owns the request schema and exactly three invocation Surfaces;-it does not contain KIE credentials, HTTP code, queues, runtime routing or usage-specific Prompt assembly.+it does not contain service credentials, HTTP code, queues, runtime routing or usage-specific Prompt assembly.The three model invocation shapes are deliberately separate:@@ -17,3 +17,32 @@ generic Text Template or third-party author module can feed them without becominthe author's literal, in whole seconds inside the model's declared range; measure the spoken line firstwith `hypit measure` and write the number here. Nothing in the graph computes it, so a Build plan iscomplete before it starts.++## Visual reference metadata++Declare whether each image or video contains a person/avatar reference, including an AI-generated+human likeness. This describes the supplied material, independently of the prompt's requested action:++```xml+<seedance:ReferenceVideo id="dance" model="mini" prompt={direction} duration="8">+ <seedance:Reference image={presenter.image} person-reference="true"/>+ <seedance:Reference video={motion.video} person-reference="true"/>+ <seedance:Reference image={room.image} person-reference="false"/>+</seedance:ReferenceVideo>+```++`person-reference` is optional, accepts literal `true` or `false`, and applies to image/video, not+voice audio. Omission carries no classification; it is distinct from explicitly declaring false.+Inspect the actual reference when deciding the value. For `FrameVideo`, use+`first-frame-person-reference` and `last-frame-person-reference` beside their respective frame+inputs. A last-frame classification requires a last-frame input.++The model's media ports carry this as `fields.personReference`. Providers interpret it through their+service's media handling; it is not a prompt sentence or a Core-level identity. HypiHub sends it as+`is_person_reference` when uploading the file, then uses the returned URL in the ordinary video+request. A project Provider maps it according to its own API.++Video references can carry motion or camera behavior while image references carry the target+appearance. Request duration and reference-clip duration are different limits. Check the selected+Endpoint's reference duration and media limits when choosing an excerpt; the author's output duration+alone does not validate the input clip.diff --git a/packages/seedance/src/index.ts b/packages/seedance/src/index.tsindex 8bb027f5..21c1d507 100644--- a/packages/seedance/src/index.ts+++ b/packages/seedance/src/index.ts@@ -19,14 +19,16 @@ export type SeedanceModel = typeof seedanceModels[number];const ASPECT_RATIOS = ["1:1", "4:3", "3:4", "16:9", "9:16", "21:9", "adaptive"] as const;+const PERSON_REFERENCE_FIELDS = [{ name: "personReference", value: { kind: "boolean" }, optional: true }] as const;+const SEEDANCE_25_DURATIONS = [-1, ...Array.from({ length: 27 }, (_item, index) => index + 4)] as const;/*** Exact Seedance model inputs. Provider wire names are deliberately absent:- * KIE, Volcengine or another service maps these ports independently.+ * Each service maps these ports independently.** Seedance 2.5 is not treated as an alias for a Seedance 2 variant. Its public- * KIE contract widens prompt/reference capacities and duration independently,+ * request definition widens prompt/reference capacities and duration independently,* so it receives its own exact Capability while reusing the same three author* Surfaces.*/@@ -37,11 +39,11 @@ function seedancePortTable(model: SeedanceModel): GenerationPortTable {result: "video",ports: [{ name: "prompt", value: { kind: "text", maxChars: is25 ? 30_000 : 20_000 }, minItems: 1, maxItems: 1 },- { name: "referenceImage", value: { kind: "media", accepts: ["image"] }, minItems: 0, maxItems: is25 ? 30 : 9 },- { name: "referenceVideo", value: { kind: "media", accepts: ["video"] }, minItems: 0, maxItems: is25 ? 10 : 3 },+ { name: "referenceImage", value: { kind: "media", accepts: ["image"], itemFields: PERSON_REFERENCE_FIELDS }, minItems: 0, maxItems: is25 ? 30 : 9 },+ { name: "referenceVideo", value: { kind: "media", accepts: ["video"], itemFields: PERSON_REFERENCE_FIELDS }, minItems: 0, maxItems: is25 ? 10 : 3 },{ name: "referenceAudio", value: { kind: "media", accepts: ["audio"] }, minItems: 0, maxItems: is25 ? 10 : 3 },- { name: "firstFrame", value: { kind: "media", accepts: ["image"] }, minItems: 0, maxItems: 1 },- { name: "lastFrame", value: { kind: "media", accepts: ["image"] }, minItems: 0, maxItems: 1 },+ { name: "firstFrame", value: { kind: "media", accepts: ["image"], itemFields: PERSON_REFERENCE_FIELDS }, minItems: 0, maxItems: 1 },+ { name: "lastFrame", value: { kind: "media", accepts: ["image"], itemFields: PERSON_REFERENCE_FIELDS }, minItems: 0, maxItems: 1 },{name: "resolution",value: {@@ -174,6 +176,11 @@ const seedanceCommonAttributes: readonly SurfaceAttributeVocabulary[] = [},];+const personReferenceAttribute = (name: string): SurfaceAttributeVocabulary => ({+ name, kind: "literal", required: false, values: ["true", "false"],+ summary: "Declares whether this visual input contains a person/avatar reference, including an AI-generated human likeness. Omission leaves it unclassified.",+});+const seedanceVideoPort: readonly SurfacePortVocabulary[] = [{name: "video",type: artifactTypes.blob,@@ -229,6 +236,8 @@ export const seedanceMarkupSurfaces = [summary: "Generates one video with an exact Seedance model from a Text prompt and the images the video opens and closes on.",attributes: [...seedanceCommonAttributes,+ personReferenceAttribute("first-frame-person-reference"),+ personReferenceAttribute("last-frame-person-reference"),{name: "first-frame",kind: "reference",@@ -268,6 +277,7 @@ export const seedanceMarkupSurfaces = [cardinality: "many",summary: "Attaches one Artifact as a reference through exactly one of its `image`, `video` or `audio` references.",attributes: [+ personReferenceAttribute("person-reference"),{name: "image",kind: "reference",@@ -301,12 +311,13 @@ export const seedanceMarkupSurfaces = [aspect-ratio="9:16"generate-audio="true">- <seedance:Reference image={presenter-clean}/>+ <seedance:Reference image={presenter-clean} person-reference="true"/><seedance:Reference audio={presenter-voice}/></seedance:ReferenceVideo>`,notes: [...seedanceSettingNotes,"The element requires at least one `Reference` child, and the model's port limits cap how many of each role it accepts.",+ "`person-reference` applies to image/video references; voice audio carries no visual classification. The Provider transports the declared fact according to its API.","A `Reference` carries exactly one of `image`, `video` or `audio`, and is empty.",],},diff --git a/packages/seedance/src/surface.ts b/packages/seedance/src/surface.tsindex 280d6e06..ccd59b61 100644--- a/packages/seedance/src/surface.ts+++ b/packages/seedance/src/surface.ts@@ -28,6 +28,7 @@ type MediaInput = {readonly port: "referenceImage" | "referenceVideo" | "referenceAudio" | "firstFrame" | "lastFrame";readonly role: GenerationMediaRole;readonly source: SurfaceResolvedReference;+ readonly fields?: { readonly personReference: boolean };};function localName(value: string): string {@@ -142,6 +143,11 @@ function booleanAttribute(element: StructuredElement, name: string, fallback: bothrow new Error(`${element.name}.${name} must be true or false`);}+function personReferenceFields(element: StructuredElement, name: string) {+ return element.attributes[name] === undefined ? undefined+ : { personReference: booleanAttribute(element, name, false) };+}+function enumeratedPort(table: GenerationPortTable, name: string): readonly (string | number)[] {const port = generationPort(table, name);if (port.value.kind !== "enum") throw new Error(`${table.model} port ${name} is not enumerated`);@@ -204,12 +210,15 @@ function referenceInputs(continue;}if (localName(child.name) !== "Reference") throw new Error(`${element.name} accepts only Reference children`);- attributes(child, [], accepted);+ attributes(child, [], [...accepted, "person-reference"]);empty(child);const kinds = accepted.filter((kind) => child.attributes[kind] !== undefined);if (kinds.length !== 1) throw new Error(`${child.name} requires exactly one of ${accepted.join(", ")}`);const role = kinds[0]!;+ const fields = personReferenceFields(child, "person-reference");+ if (role === "audio" && fields !== undefined) throw new Error(`${child.name}.person-reference applies to image or video, not audio`);result.push({+ ...(fields === undefined ? {} : { fields }),role,port: REFERENCE_PORTS[role],source: mediaReference(resolved(child, role, resolveReference), role, `${child.name}.${role}`),@@ -230,10 +239,14 @@ function frameInputs(resolveReference: (path: string) => SurfaceResolvedReference | undefined,): MediaInput[] {const first = mediaReference(resolved(element, "first-frame", resolveReference), "image", `${element.name}.first-frame`);- const result: MediaInput[] = [{ port: "firstFrame", role: "image", source: first }];+ const firstFields = personReferenceFields(element, "first-frame-person-reference");+ const result: MediaInput[] = [{ port: "firstFrame", role: "image", source: first, ...(firstFields === undefined ? {} : { fields: firstFields }) }];+ const lastFields = personReferenceFields(element, "last-frame-person-reference");+ if (lastFields !== undefined && element.attributes["last-frame"] === undefined) throw new Error(`${element.name}.last-frame-person-reference requires last-frame`);if (element.attributes["last-frame"] !== undefined) {result.push({port: "lastFrame",+ ...(lastFields === undefined ? {} : { fields: lastFields }),role: "image",source: mediaReference(resolved(element, "last-frame", resolveReference), "image", `${element.name}.last-frame`),});@@ -266,7 +279,7 @@ function assembleMedia(type: binding.type,value: {kind: "inline",- value: sealGenerationMediaBinding(port as GenerationMediaPort, { role: value.role }) as unknown as CanonicalValue,+ value: sealGenerationMediaBinding(port as GenerationMediaPort, { role: value.role, ...(value.fields === undefined ? {} : { fields: value.fields }) }) as unknown as CanonicalValue,},range,});@@ -330,7 +343,7 @@ export const decodeSeedanceTextVideoSurface: StructuredSurfaceHandler = ({ eleme};export const decodeSeedanceFrameVideoSurface: StructuredSurfaceHandler = ({ element, resolveReference }) => {- attributes(element, ["id", "model", "prompt", "duration", "first-frame"], [...COMMON_OPTIONAL, "last-frame"]);+ attributes(element, ["id", "model", "prompt", "duration", "first-frame"], [...COMMON_OPTIONAL, "last-frame", "first-frame-person-reference", "last-frame-person-reference"]);empty(element);const selected = modelSelection(element);const promptSource = resolved(element, "prompt", resolveReference);diff --git a/packages/seedance/test/surface.test.ts b/packages/seedance/test/surface.test.tsindex 2adaf0be..67547310 100644--- a/packages/seedance/test/surface.test.ts+++ b/packages/seedance/test/surface.test.ts@@ -119,3 +119,26 @@ test("the three Surfaces make incompatible invocation shapes unrepresentable", a/requires/u,);});++test("visual reference classification survives authoring as per-input metadata", async () => {+ const result = await decode(`<seedance:ReferenceVideo id="motion" model="mini" prompt={direction} duration="6">+ <seedance:Reference image={generated.image} person-reference="true"/>+ <seedance:Reference video={first.image} person-reference="false"/>+ <seedance:Reference image={last.image}/>+ </seedance:ReferenceVideo>`, decodeSeedanceReferenceVideoSurface);+ const bindings = result.records.filter((record) => record.id.endsWith(".binding"));+ assert.deepEqual(bindings.map((record) => record.value.kind === "inline" ? record.value.value : null), [+ { role: "image", fields: { personReference: true } },+ { role: "video", fields: { personReference: false } },+ { role: "image" },+ ]);+ const frames = await decode('<seedance:FrameVideo id="frames" model="fast" prompt={direction} duration="5" first-frame={first.image} first-frame-person-reference="true" last-frame={last.image} last-frame-person-reference="false"/>', decodeSeedanceFrameVideoSurface);+ const frameBindings = frames.records.filter((record) => record.id.endsWith(".binding"));+ assert.deepEqual(frameBindings.map((record) => record.value.kind === "inline" ? record.value.value : null), [+ { role: "image", fields: { personReference: true } },+ { role: "image", fields: { personReference: false } },+ ]);+ await assert.rejects(decode('<seedance:ReferenceVideo id="bad" model="mini" prompt={direction} duration="6"><seedance:Reference audio={voice.audio} person-reference="true"/></seedance:ReferenceVideo>', decodeSeedanceReferenceVideoSurface), /applies to image or video/);+ await assert.rejects(decode('<seedance:ReferenceVideo id="bad" model="mini" prompt={direction} duration="6"><seedance:Reference image={generated.image} person-reference="maybe"/></seedance:ReferenceVideo>', decodeSeedanceReferenceVideoSurface), /must be true or false/);+ await assert.rejects(decode('<seedance:FrameVideo id="bad" model="mini" prompt={direction} duration="6" first-frame={first.image} last-frame-person-reference="true"/>', decodeSeedanceFrameVideoSurface), /requires last-frame/);+});diff --git a/packages/seedream/README.md b/packages/seedream/README.mdindex 1c0eb76a..7d1bf1e1 100644--- a/packages/seedream/README.md+++ b/packages/seedream/README.md@@ -4,7 +4,7 @@ Exact author/compute contracts and package-owned author Surfaces for Seedream imThe two modes are separate Surfaces and project the primary result to an ordinary image Artifact.This package defines what the author requested, not where it runs: API translation, credentials,-retry and queue behavior belong to a selected Runtime Endpoint such as `@hypit/provider-kie`.+retry and queue behavior belong to a selected Runtime Endpoint selected in the Runtime Profile.The modes stay explicit in the source:diff --git a/packages/store-sqlite/README.md b/packages/store-sqlite/README.mdindex 25050874..cb5b0de3 100644--- a/packages/store-sqlite/README.md+++ b/packages/store-sqlite/README.md@@ -12,3 +12,10 @@ has recorded them. Unknown remote outcomes do not keep a failed Build active.Artifact bytes and secret credential values never enter this database. Components and Endpoint packages do not importSQLite. `SqliteRuntimeState` exposes the narrow stores needed by the local Runtime and owns their sharedconnection.++Execution choices live in `context_json` on the existing submission/execution records. The store treats+that value as opaque Host data. `started_at` distinguishes queued work from an executor that was lost.+`listUnstarted` and `listReady` return only IDs for dispatch, without parsing every Profile or graph.+Scoped claims and shared capacity updates remain atomic across execution contexts and processes. No global Profile+pin prevents a new Build from using new selections. An interrupted executor is concluded only after+its supervisor knows the process has exited; stored Operation receipts are retained for Result writing.diff --git a/packages/store-sqlite/src/store.ts b/packages/store-sqlite/src/store.tsindex 8fd3b001..7e18e277 100644--- a/packages/store-sqlite/src/store.ts+++ b/packages/store-sqlite/src/store.ts@@ -35,7 +35,6 @@ import type {OperationSnapshot,OperationStore,OperationUpdate,- RuntimeEnvironmentStore,} from "@hypit/runtime";export type SqliteRuntimeStateOptions = {@@ -224,6 +223,7 @@ function parseExecutionRequest(row: Row, subject: string): BuildExecutionRequest`SQLite ${subject} Result location is invalid`);return {build: row.build_id,+ ...(typeof row.context_json === "string" ? { context: JSON.parse(row.context_json) as NonNullable<BuildExecutionRequest["context"]> } : {}),componentPackages,result: result as BuildExecutionRequest["result"],};@@ -263,12 +263,13 @@ class SqlitePendingBuildStore implements PendingBuildStore {assert(occupied === undefined, `Build ${request.build} already has Runtime state`);this.#database.prepare(`INSERT INTO hypit_submissions (- build_id, component_packages_json, result_location_json, created_at- ) VALUES (?, ?, ?, ?)+ build_id, component_packages_json, result_location_json, context_json, created_at+ ) VALUES (?, ?, ?, ?, ?)`).run(request.build,JSON.stringify(request.componentPackages),JSON.stringify(request.result),+ request.context === undefined ? null : JSON.stringify(request.context),now,);return parsePendingBuildSubmission(@@ -295,7 +296,8 @@ class SqlitePendingBuildStore implements PendingBuildStore {if (row === undefined) throw new Error(`Build submission ${request.build} was not prepared`);const submission = parsePendingBuildSubmission(row);assert(JSON.stringify(submission.componentPackages) === JSON.stringify(request.componentPackages)- && JSON.stringify(submission.result) === JSON.stringify(request.result),+ && JSON.stringify(submission.result) === JSON.stringify(request.result)+ && JSON.stringify(submission.context) === JSON.stringify(request.context),`Build submission ${request.build} does not match its prepared state`);this.#database.prepare(`INSERT INTO hypit_builds (build_id, definition_json) VALUES (?, ?)@@ -305,15 +307,16 @@ class SqlitePendingBuildStore implements PendingBuildStore {`).run(request.build, Date.now(), JSON.stringify(request.catalog));this.#database.prepare(`INSERT INTO hypit_executions (- build_id, component_packages_json, result_location_json, created_at, wake_at,+ build_id, component_packages_json, result_location_json, context_json, created_at, wake_at,turn_owner, turn_acquired_at, result_writer_owner, result_writer_acquired_at,stop_cause, stop_reason,decision_outcome, decision_reason, attention_step, attention_error- ) VALUES (?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)+ ) VALUES (?, ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)`).run(request.build,JSON.stringify(request.componentPackages),JSON.stringify(request.result),+ request.context === undefined ? null : JSON.stringify(request.context),submission.createdAt,Date.now(),);@@ -424,6 +427,9 @@ function parseCommandExecution(row: Row): CommandExecutionReceipt {command: row.command_id,status: row.status,...(event === undefined ? {} : { event }),+ ...(row.status !== "started" || typeof row.activity_json !== "string" ? {} : {+ activity: JSON.parse(row.activity_json) as NonNullable<CommandExecutionReceipt["activity"]>,+ }),};}@@ -456,7 +462,7 @@ class SqliteCommandExecutionStore implements CommandExecutionStore {const current = parseCommandExecution(row);if (current.status === "completed") return current;this.#database.prepare(`- UPDATE hypit_command_executions SET status = 'completed', event_json = ?+ UPDATE hypit_command_executions SET status = 'completed', event_json = ?, activity_json = NULLWHERE build_id = ? AND command_id = ? AND status = 'started'`).run(JSON.stringify(event), build, command);return parseCommandExecution(this.#database.prepare(`@@ -471,54 +477,18 @@ class SqliteCommandExecutionStore implements CommandExecutionStore {`).all(build) as Row[]).map(parseCommandExecution);}- async removeBuild(build: string): Promise<void> {- this.#database.prepare("DELETE FROM hypit_command_executions WHERE build_id = ?").run(build);- }-}--class SqliteRuntimeEnvironmentStore implements RuntimeEnvironmentStore {- readonly #database: DatabaseSync;-- constructor(database: DatabaseSync) {- this.#database = database;- }-- async use(config: string): Promise<void> {- assert(config.length > 0, "Runtime environment configuration is empty");- transaction(this.#database, () => {- const active = this.#database.prepare(- `SELECT- (SELECT COUNT(*) FROM hypit_submissions)- + (SELECT COUNT(*) FROM hypit_executions) AS count`,- ).get() as Row;- assert(typeof active.count === "number", "SQLite active Runtime work count is invalid");- const row = this.#database.prepare(- "SELECT config_json FROM hypit_runtime_environment WHERE singleton = 1",- ).get() as Row | undefined;- if (active.count > 0) {- assert(typeof row?.config_json === "string",- "Active Runtime work has no recorded environment; use its original Profile or resolve it explicitly");- assert(row.config_json === config,- "Runtime Profile differs from the environment pinned by active Builds");- return;- }- this.#database.prepare(`- INSERT INTO hypit_runtime_environment (singleton, config_json) VALUES (1, ?)- ON CONFLICT(singleton) DO UPDATE SET config_json = excluded.config_json- `).run(config);- });+ async reportProgress(build: string, command: string, activity: NonNullable<CommandExecutionReceipt["activity"]>): Promise<void> {+ this.#database.prepare(`+ UPDATE hypit_command_executions SET activity_json = ?+ WHERE build_id = ? AND command_id = ? AND status = 'started'+ `).run(JSON.stringify(activity), build, command);}- async assert(config: string): Promise<void> {- const row = this.#database.prepare(- "SELECT config_json FROM hypit_runtime_environment WHERE singleton = 1",- ).get() as Row | undefined;- assert(typeof row?.config_json === "string" && row.config_json === config,- "Runtime Profile no longer matches this Worker's active environment");+ async removeBuild(build: string): Promise<void> {+ this.#database.prepare("DELETE FROM hypit_command_executions WHERE build_id = ?").run(build);}}-function parseExecutionSnapshot(row: Row): BuildExecutionSnapshot {assert(typeof row.created_at === "number", "SQLite Execution creation time is invalid");assert(row.wake_at === null || typeof row.wake_at === "number", "SQLite Execution wake time is invalid");@@ -538,6 +508,7 @@ function parseExecutionSnapshot(row: Row): BuildExecutionSnapshot {return {...parseExecutionRequest(row, "Execution"),createdAt: row.created_at,+ ...(typeof row.started_at === "number" ? { startedAt: row.started_at } : {}),...(typeof row.wake_at === "number" ? { wakeAt: row.wake_at } : {}),...(typeof row.operation_wait_json === "string" ? { operationWait: JSON.parse(row.operation_wait_json) as string[] } : {}),...(typeof row.turn_owner === "string" ? {@@ -582,12 +553,12 @@ class SqliteBuildExecutionStore implements BuildExecutionStore {nonNegativeInteger(now, "Execution creation time");this.#database.prepare(`INSERT INTO hypit_executions (- build_id, component_packages_json, result_location_json, created_at, wake_at,+ build_id, component_packages_json, result_location_json, context_json, created_at, wake_at,turn_owner, turn_acquired_at, result_writer_owner, result_writer_acquired_at,stop_cause, stop_reason,decision_outcome, decision_reason, attention_step, attention_error- ) VALUES (?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)- `).run(request.build, JSON.stringify(request.componentPackages), JSON.stringify(request.result), now, now);+ ) VALUES (?, ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)+ `).run(request.build, JSON.stringify(request.componentPackages), JSON.stringify(request.result), request.context === undefined ? null : JSON.stringify(request.context), now, now);return {...copy(request),createdAt: now,@@ -608,19 +579,20 @@ class SqliteBuildExecutionStore implements BuildExecutionStore {return rows.map(parseExecutionSnapshot);}- async claim(owner: string, now = Date.now()): Promise<BuildExecutionSnapshot | undefined> {+ async claim(owner: string, now = Date.now(), build?: string): Promise<BuildExecutionSnapshot | undefined> {assert(owner.trim().length > 0, "Execution turn owner is empty");nonNegativeInteger(now, "Execution claim time");return transaction(this.#database, () => {const row = this.#database.prepare(`SELECT execution.build_id FROM hypit_executions AS executionWHERE decision_outcome IS NULL AND turn_owner IS NULL AND wake_at <= ?+ AND (? IS NULL OR execution.build_id = ?)ORDER BY EXISTS (SELECT 1 FROM hypit_capacity AS capacityWHERE capacity.build_id = execution.build_id) DESC, wake_at ASC, created_at ASC, execution.build_id ASCLIMIT 1- `).get(now) as Row | undefined;+ `).get(now, build ?? null, build ?? null) as Row | undefined;if (row === undefined) return undefined;assert(typeof row.build_id === "string", "SQLite ready Execution has no Build id");const updated = this.#database.prepare(`@@ -635,6 +607,45 @@ class SqliteBuildExecutionStore implements BuildExecutionStore {});}+ async listUnstarted(): Promise<readonly string[]> {+ return (this.#database.prepare(`SELECT build_id FROM hypit_executions+ WHERE decision_outcome IS NULL AND started_at IS NULL ORDER BY created_at, build_id`).all() as Row[])+ .map((row) => row.build_id as string);+ }++ async listReady(now = Date.now()): Promise<readonly string[]> {+ return (this.#database.prepare(`SELECT build_id FROM hypit_executions+ WHERE decision_outcome IS NULL AND turn_owner IS NULL AND wake_at <= ?+ ORDER BY wake_at, created_at, build_id`).all(now) as Row[]).map((row) => row.build_id as string);+ }++ async start(build: string, now = Date.now()): Promise<BuildExecutionSnapshot> {+ nonNegativeInteger(now, "Execution start time");+ const updated = this.#database.prepare(`+ UPDATE hypit_executions SET started_at = ?+ WHERE build_id = ? AND started_at IS NULL AND decision_outcome IS NULL+ `).run(now, build);+ assert(updated.changes === 1, `Execution ${build} has already started or ended`);+ return (await this.read(build))!;+ }++ async interrupt(build: string, reason: string): Promise<BuildExecutionSnapshot> {+ return transaction(this.#database, () => {+ const row = this.#database.prepare("SELECT * FROM hypit_executions WHERE build_id = ?").get(build) as Row | undefined;+ assert(row !== undefined, `Execution ${build} does not exist`);+ const current = parseExecutionSnapshot(row);+ if (current.decision !== undefined) return current;+ this.#release(build);+ this.#database.prepare(`+ UPDATE hypit_executions SET decision_outcome = ?, decision_reason = ?,+ turn_owner = NULL, turn_acquired_at = NULL,+ result_writer_owner = NULL, result_writer_acquired_at = NULL+ WHERE build_id = ?+ `).run(current.stop?.cause === "user-cancelled" ? "cancelled" : "failed", current.stop?.reason ?? reason, build);+ return parseExecutionSnapshot(this.#database.prepare("SELECT * FROM hypit_executions WHERE build_id = ?").get(build) as Row);+ });+ }+async releaseTurn(build: string, owner: string, wakeAt: number | undefined, operationWait?: readonly string[]): Promise<BuildExecutionSnapshot> {if (wakeAt !== undefined) nonNegativeInteger(wakeAt, "Execution wakeAt");return transaction(this.#database, () => {@@ -902,28 +913,6 @@ class SqliteBuildExecutionStore implements BuildExecutionStore {transaction(this.#database, () => this.#release(build));}- async reclaimTurns(now = Date.now()): Promise<readonly string[]> {- nonNegativeInteger(now, "Execution turn reclaim time");- return transaction(this.#database, () => {- const rows = this.#database.prepare(- "SELECT build_id FROM hypit_executions WHERE turn_owner IS NOT NULL AND decision_outcome IS NULL",- ).all() as Row[];- const builds = rows.map((row) => {- assert(typeof row.build_id === "string", "SQLite owned Execution has no Build id");- return row.build_id;- });- for (const row of rows) {- assert(typeof row.build_id === "string", "SQLite active Execution is invalid");- this.#database.prepare(`- UPDATE hypit_executions- SET turn_owner = NULL, turn_acquired_at = NULL, wake_at = ?- WHERE build_id = ? AND decision_outcome IS NULL- `).run(now, row.build_id);- }- return builds;- });- }-async listCapacity(): Promise<readonly CapacityReservation[]> {return (this.#database.prepare("SELECT * FROM hypit_capacity ORDER BY created_at ASC, build_id ASC, command_id ASC",@@ -961,7 +950,6 @@ export class SqliteRuntimeState {readonly commandExecutions: CommandExecutionStore;readonly execution: BuildExecutionStore;readonly catalog: BuildCatalog;- readonly environment: RuntimeEnvironmentStore;readonly submissions: PendingBuildStore;readonly #database: DatabaseSync;@@ -1007,6 +995,7 @@ export class SqliteRuntimeState {command_id TEXT NOT NULL,status TEXT NOT NULL CHECK (status IN ('started', 'completed')),event_json TEXT,+ activity_json TEXT,PRIMARY KEY (build_id, command_id)) STRICT;CREATE TABLE IF NOT EXISTS hypit_build_catalog (@@ -1018,13 +1007,16 @@ export class SqliteRuntimeState {build_id TEXT PRIMARY KEY,component_packages_json TEXT NOT NULL,result_location_json TEXT NOT NULL,+ context_json TEXT,created_at INTEGER NOT NULL) STRICT;CREATE TABLE IF NOT EXISTS hypit_executions (build_id TEXT PRIMARY KEY,component_packages_json TEXT NOT NULL,result_location_json TEXT NOT NULL,+ context_json TEXT,created_at INTEGER NOT NULL,+ started_at INTEGER,wake_at INTEGER,operation_wait_json TEXT,turn_owner TEXT,@@ -1062,17 +1054,26 @@ export class SqliteRuntimeState {resource_id TEXT PRIMARY KEY, limit_units INTEGER NOT NULL, period_ms INTEGER NOT NULL,tokens REAL NOT NULL, updated_at INTEGER NOT NULL) STRICT;- CREATE TABLE IF NOT EXISTS hypit_runtime_environment (- singleton INTEGER PRIMARY KEY CHECK (singleton = 1),- config_json TEXT NOT NULL- ) STRICT;`);+ if (!options.readOnly) transaction(database, () => {+ for (const table of ["hypit_submissions", "hypit_executions"]) {+ const columns = database.prepare(`PRAGMA table_info(${table})`).all() as Row[];+ if (!columns.some((column) => column.name === "context_json")) database.exec(`ALTER TABLE ${table} ADD COLUMN context_json TEXT`);+ if (table === "hypit_executions" && !columns.some((column) => column.name === "started_at")) database.exec("ALTER TABLE hypit_executions ADD COLUMN started_at INTEGER");+ }+ });+ // Add the nullable live-activity column without touching any accepted facts or Results.+ if (!options.readOnly) transaction(database, () => {+ if (!(database.prepare("PRAGMA table_info(hypit_command_executions)").all() as Row[])+ .some((column) => column.name === "activity_json")) {+ database.exec("ALTER TABLE hypit_command_executions ADD COLUMN activity_json TEXT");+ }+ });this.builds = new SqliteBuildStore(database);this.operations = new SqliteOperationStore(database);this.commandExecutions = new SqliteCommandExecutionStore(database);this.execution = new SqliteBuildExecutionStore(database);this.catalog = new SqliteBuildCatalog(database);- this.environment = new SqliteRuntimeEnvironmentStore(database);this.submissions = new SqlitePendingBuildStore(database);}diff --git a/packages/store-sqlite/test/store.test.ts b/packages/store-sqlite/test/store.test.tsindex 12295818..558b29a6 100644--- a/packages/store-sqlite/test/store.test.ts+++ b/packages/store-sqlite/test/store.test.ts@@ -13,6 +13,26 @@ const resultLocation = {selection: { use: "@hypit/build-result-fs", config: { path: ".hypit/results" } },} as const;+test("local command progress is visible across connections and ends with the command", async () => {+ const directory = await mkdtemp(join(tmpdir(), "hypit-command-progress-"));+ const path = join(directory, "runtime.sqlite");+ const writer = new SqliteRuntimeState(path);+ const observer = new SqliteRuntimeState(path, { readOnly: true });+ try {+ await writer.commandExecutions.begin("build", "draw");+ await writer.commandExecutions.reportProgress("build", "draw", {+ endpoint: "example.local", progress: { phase: "drawing", completed: 5, total: 10, unit: "frames" },+ });+ assert.equal((await observer.commandExecutions.list("build"))[0]?.activity?.progress.completed, 5);+ await writer.commandExecutions.complete("build", "draw", { kind: "command-failed", command: "draw", code: "STOP", message: "Stopped" });+ await writer.commandExecutions.reportProgress("build", "draw", { endpoint: "example.local", progress: { phase: "late" } });+ assert.equal((await observer.commandExecutions.list("build"))[0]?.activity, undefined);+ assert.deepEqual(await observer.operations.list({ build: "build" }), []);+ } finally {+ observer.close(); writer.close(); await rm(directory, { recursive: true, force: true });+ }+});+function definition(state: ReturnType<typeof createGreetingBuild>) {const authored = new Set(state.program.records.map((record) => record.id));return defineBuild({@@ -60,7 +80,7 @@ test("SQLite stores verified Build facts and Operation handles across reopen", aid: "operation:generation",build: "video",command: "command:generation",- endpoint: "kie.personal",+ endpoint: "images.personal",};const pending = await first.operations.create({ ...operation,status: "pending",@@ -202,37 +222,34 @@ test("Execution stores scheduling facts, one decision and independent operator a}});-test("Submissions and Executions pin the literal Runtime environment", async () => {- const directory = await mkdtemp(join(tmpdir(), "hypit-sqlite-environment-"));+test("each execution retains its own context and can be claimed without touching its sibling", async () => {+ const directory = await mkdtemp(join(tmpdir(), "hypit-sqlite-context-"));try {const state = new SqliteRuntimeState(join(directory, "runtime.sqlite"));- await state.environment.use('{"endpoints":{"kie":{"region":"us"}}}');- await state.submissions.prepare({ build: "active-build", componentPackages: [], result: resultLocation }, { now: 100 });- await assert.rejects(- state.environment.use('{"endpoints":{"kie":{"region":"eu"}}}'),- /pinned by active Builds/u,- );- await state.environment.assert('{"endpoints":{"kie":{"region":"us"}}}');- await assert.rejects(- state.environment.assert('{"endpoints":{"kie":{"region":"eu"}}}'),- /no longer matches/u,- );+ await state.execution.create({ build: "a", componentPackages: [], result: resultLocation, context: { provider: "old" } }, { now: 100 });+ await state.execution.create({ build: "b", componentPackages: [], result: resultLocation, context: { provider: "new" } }, { now: 100 });+ await state.execution.start("a", 101);+ await assert.rejects(state.execution.start("a", 102), /already started/u);+ assert.equal((await state.execution.claim("b-owner", 102, "b"))?.build, "b");+ assert.equal((await state.execution.read("a"))?.turn, undefined);+ assert.deepEqual((await state.execution.read("a"))?.context, { provider: "old" });+ const interrupted = await state.execution.interrupt("a", "executor exited");+ assert.equal(interrupted.decision?.outcome, "failed");+ assert.equal((await state.execution.read("b"))?.turn?.owner, "b-owner");state.close();- } finally {- await rm(directory, { recursive: true, force: true });- }+ } finally { await rm(directory, { recursive: true, force: true }); }});-test("a new Worker reclaims abandoned turns and Result-writer leases without external work", async () => {+test("a lost executor ends its attempt while Result-writer leases can be reclaimed", async () => {const directory = await mkdtemp(join(tmpdir(), "hypit-sqlite-turn-reclaim-"));try {const state = new SqliteRuntimeState(join(directory, "runtime.sqlite"));await state.execution.create({ build: "interrupted", componentPackages: [], result: resultLocation }, { now: 100 });assert.equal((await state.execution.claim("old-worker", 100))?.turn?.owner, "old-worker");- assert.deepEqual(await state.execution.reclaimTurns(200), ["interrupted"]);+ await state.execution.interrupt("interrupted", "executor lost");assert.equal((await state.execution.read("interrupted"))?.turn, undefined);- assert.equal((await state.execution.claim("new-worker", 200))?.turn?.owner, "new-worker");- await state.execution.decide("interrupted", "new-worker", "failed", "provider stopped");+ assert.equal(await state.execution.claim("new-worker", 200), undefined);+ assert.equal((await state.execution.read("interrupted"))?.decision?.outcome, "failed");assert.equal((await state.execution.claimResultWrite("interrupted", "old-result-writer", 201))?.resultWrite?.owner,"old-result-writer",@@ -254,9 +271,9 @@ test("shared capacity resources are acquired atomically across Builds", async ()const directory = await mkdtemp(join(tmpdir(), "hypit-sqlite-hierarchy-"));try {const state = new SqliteRuntimeState(join(directory, "runtime.sqlite"));- const pool = { id: "pool:kie.main", limit: 2 };- const seedance = { id: "capacity:kie.main/seedance-2-mini", limit: 1 };- const minimax = { id: "capacity:kie.main/minimax-h3", limit: 2 };+ const pool = { id: "pool:images.main", limit: 2 };+ const seedance = { id: "capacity:images.main/seedance-2-mini", limit: 1 };+ const minimax = { id: "capacity:images.main/minimax-h3", limit: 2 };const first = await state.execution.acquireCapacity({build: "seedance-a",diff --git a/packages/studio/README.md b/packages/studio/README.mdindex 4c4c142e..cf0ca441 100644--- a/packages/studio/README.md+++ b/packages/studio/README.md@@ -72,6 +72,66 @@ transient processing require the selected Runtime.## Opening and editing a session+The CLI prints the actual session URL and its direct `#comments` URL after the server chooses a port.+Open the latter to review the current composition before export. Browser playback creates no export+Build or encoded video; an export remains a separate Run execution when the user wants the file.++The top-right **Studio / Comments** tabs change the layout around the same composition player.+Comments gives the picture the available height with a notes column on the right. Click the picture+to play or pause; the wider progress control seeks, with a hovered-frame preview that leaves the+main playhead alone. The hover picture uses one lazy, muted instance of the current preview document,+released when leaving Comments. It needs no Build or thumbnail files.++Studio retains picture selection and its right-click menu for overlapping Companion entities.+Comments uses viewing controls without selecting objects. Switching views preserves the composition+time and Studio's selection; comments themselves only refer to a time and the user's words.++### Comments are project files++Studio saves comments in `<workspace>/FEEDBACK.json`, creating it on the first saved comment.+This path is Studio's project-file convention, rooted in the resolved workspace; it is independent+of the Runtime, Result repository and Agent implementation.+Each comment records its reviewed Run relative to that workspace, so the file can hold notes for+several Runs while the UI shows the current Run. Times are seconds, including fractional seconds:++```json+{+ "comments": [+ {+ "id": "caption-size",+ "run": "runs/main.svrun",+ "at": 12.5,+ "text": "Make this caption larger.",+ "resolved": false+ }+ ]+}+```++`id`, `run`, `at` and `text` are required. `resolved` defaults to false; setting it to true marks+the comment complete, and false reopens it. Deleting removes the entry. Following a note seeks to+its saved time; a changed composition can show something different at that time.++Focusing the comment composer pauses the picture and captures the current frame. The time chip+captures a new time. The draft keeps its time while the user writes. Click a saved timestamp to+revisit it. Comments can be edited, completed, reopened and deleted from the UI or by editing the file.+The list is ordered by timestamp. Its `#1`, `#2` labels follow submission order within the current+Run (the file's array order) and appear beside the completion control. Changing a timestamp or+filtering Open/Done preserves those numbers; deleting a note closes its gap in the numbering.+The stored `id` remains the stable identity. Clicking a note's text or time seeks+to its frame. The composer has an icon-only send control; emoji and drawing buttons are inactive placeholders.+Clicking outside the selected note clears its highlight without discarding an edit. Enter sends a+new note or saves an edited one; Shift+Enter or Alt+Enter inserts a line break. IME confirmation stays+with the text input rather than submitting the comment.++File changes refresh comments through filesystem events, without polling or recompiling the video.+Studio reads the file afresh for each edit, preserves unrelated notes and project-added fields, and+rejects an edit to a comment that has changed since it was displayed. An invalid manually edited+file remains intact and its error is shown. Unsent text stays in the browser. Agent notification is+a separate, planned connection; **Send comment** currently saves the note only.++### Composition editing+The selected targets must reach one Film and its resolved time source. Studio rejects severaldistinct Films in one view; use separate Runs/sessions for those. A Timeline supplies theplaced material and semantic timing, including wordless Segments. The ruler always shows programdiff --git a/packages/studio/package.json b/packages/studio/package.jsonindex bb1844a3..68a28448 100644--- a/packages/studio/package.json+++ b/packages/studio/package.json@@ -28,6 +28,7 @@"@hypit/performance-studio": "workspace:*","@hypit/sound-studio": "workspace:*","@hypit/program-space": "workspace:*",+ "@hypit/project-context-node": "workspace:*","@hypit/protocol": "workspace:*","@hypit/ranking-studio": "workspace:*","@hypit/run": "workspace:*",diff --git a/packages/studio/src/feedback-server.ts b/packages/studio/src/feedback-server.tsnew file mode 100644index 00000000..8b817d73--- /dev/null+++ b/packages/studio/src/feedback-server.ts@@ -0,0 +1,51 @@+import { watch } from "node:fs";+import { relative } from "node:path";+import type { Plugin } from "vite";+import { createFeedbackStore, FeedbackConflict } from "./feedback-store.js";+import { readFeedbackMutation } from "./feedback.js";+import type { FeedbackDocument, FeedbackView } from "./feedback.js";++/** Review storage is separate from compilation, Results and Agent delivery. */+export function studioFeedbackPlugin(workspaceRoot: string, runPath: string): Plugin {+ const store = createFeedbackStore(workspaceRoot);+ const run = relative(workspaceRoot, runPath).replaceAll("\\", "/");+ const view = (document: FeedbackDocument): FeedbackView => ({+ file: "FEEDBACK.json", run, comments: document.comments.filter((comment) => comment.run === run),+ });+ return {+ name: "hypit-studio-feedback",+ configureServer(server) {+ const watcher = watch(workspaceRoot, (_event, filename) => {+ if (filename === null || filename.toString() === "FEEDBACK.json") {+ server.ws.send({ type: "custom", event: "studio:feedback-changed", data: {} });+ }+ });+ server.httpServer?.once("close", () => watcher.close());+ server.middlewares.use((request, response, next) => {+ if (new URL(request.url ?? "/", "http://studio.hypit.local").pathname !== "/__studio/feedback") return next();+ response.setHeader("content-type", "application/json; charset=utf-8");+ response.setHeader("cache-control", "no-store");+ void (async () => {+ try {+ if (request.method === "GET") {+ response.end(JSON.stringify(view(await store.read())));+ return;+ }+ if (request.method !== "POST") { response.statusCode = 405; response.end(); return; }+ const chunks: Buffer[] = [];+ for await (const chunk of request) chunks.push(Buffer.from(chunk));+ const mutation = readFeedbackMutation(JSON.parse(Buffer.concat(chunks).toString("utf8")));+ const comment = mutation.type === "delete" ? mutation.before : mutation.comment;+ if (comment.run !== run) throw new Error("The comment belongs to another Run.");+ const result = view(await store.mutate(mutation));+ response.end(JSON.stringify(result));+ server.ws.send({ type: "custom", event: "studio:feedback-changed", data: {} });+ } catch (error) {+ response.statusCode = error instanceof FeedbackConflict ? 409 : 400;+ response.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));+ }+ })();+ });+ },+ };+}diff --git a/packages/studio/src/feedback-store.ts b/packages/studio/src/feedback-store.tsnew file mode 100644index 00000000..16750995--- /dev/null+++ b/packages/studio/src/feedback-store.ts@@ -0,0 +1,66 @@+import { isDeepStrictEqual } from "node:util";+import { randomUUID } from "node:crypto";+import { readFile, rename, unlink, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { readFeedbackDocument } from "./feedback.js";+import type { FeedbackDocument, FeedbackMutation } from "./feedback.js";++export class FeedbackConflict extends Error {}++/** The file is authoritative; every operation reads it afresh and edits one note. */+export function createFeedbackStore(workspaceRoot: string) {+ const path = join(workspaceRoot, "FEEDBACK.json");+ let pending: Promise<unknown> = Promise.resolve();+ const readText = async (): Promise<string | undefined> => {+ try { return await readFile(path, "utf8"); }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;+ throw error;+ }+ };+ const decode = (text: string | undefined): FeedbackDocument => text === undefined+ ? { comments: [] } : readFeedbackDocument(JSON.parse(text));++ const apply = async (mutation: FeedbackMutation): Promise<FeedbackDocument> => {+ const previous = await readText();+ const document = decode(previous);+ const comments = [...document.comments];+ if (mutation.type === "add") {+ if (comments.some((comment) => comment.id === mutation.comment.id)) throw new FeedbackConflict("This comment already exists.");+ comments.push(mutation.comment);+ } else {+ const index = comments.findIndex((comment) => comment.id === mutation.before.id);+ if (index < 0 || !isDeepStrictEqual(comments[index], mutation.before)) {+ throw new FeedbackConflict("This comment changed outside this view. Your unsaved text is kept in the editor; reopen the comment to edit its latest version.");+ }+ if (mutation.type === "delete") comments.splice(index, 1);+ else {+ if (mutation.comment.id !== mutation.before.id || mutation.comment.run !== mutation.before.run) {+ throw new Error("Editing a comment preserves its id and Run.");+ }+ comments[index] = mutation.comment;+ }+ }+ const next = { ...document, comments };+ const temporary = join(workspaceRoot, `.FEEDBACK.${randomUUID()}.tmp`);+ try {+ await writeFile(temporary, `${JSON.stringify(next, null, 2)}\n`, { encoding: "utf8", flag: "wx" });+ if (await readText() !== previous) throw new FeedbackConflict("FEEDBACK.json changed while saving. Your draft is kept; please try again.");+ await rename(temporary, path);+ } finally {+ await unlink(temporary).catch((error: NodeJS.ErrnoException) => { if (error.code !== "ENOENT") throw error; });+ }+ return next;+ };++ return {+ path,+ read: async (): Promise<FeedbackDocument> => decode(await readText()),+ mutate(mutation: FeedbackMutation): Promise<FeedbackDocument> {+ // Serialize browser submissions, without keeping a second copy of the document.+ const result = pending.then(() => apply(mutation));+ pending = result.catch(() => undefined);+ return result;+ },+ };+}diff --git a/packages/studio/src/feedback.ts b/packages/studio/src/feedback.tsnew file mode 100644index 00000000..747859aa--- /dev/null+++ b/packages/studio/src/feedback.ts@@ -0,0 +1,60 @@+/** Project-owned review notes. Times are seconds in the reviewed Run. */+export type FeedbackComment = {+ readonly id: string;+ readonly run: string;+ readonly at: number;+ readonly text: string;+ readonly resolved?: boolean;+};++export type FeedbackDocument = { readonly comments: readonly FeedbackComment[] };+export type FeedbackView = FeedbackDocument & { readonly file: string; readonly run: string };+export type FeedbackMutation =+ | { readonly type: "add"; readonly comment: FeedbackComment }+ | { readonly type: "replace"; readonly before: FeedbackComment; readonly comment: FeedbackComment }+ | { readonly type: "delete"; readonly before: FeedbackComment };++function record(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function nonempty(value: unknown): value is string {+ return typeof value === "string" && value.trim().length > 0;+}++function time(value: unknown): value is number {+ return typeof value === "number" && Number.isFinite(value) && value >= 0;+}++export function readFeedbackComment(value: unknown): FeedbackComment {+ if (!record(value) || !nonempty(value.id) || !nonempty(value.run) || !nonempty(value.text) || !time(value.at)) {+ throw new Error("Each comment needs an id, run, non-empty text and a non-negative time in seconds.");+ }+ if (value.resolved !== undefined && typeof value.resolved !== "boolean") throw new Error("Comment resolved must be true or false.");+ // Preserve any project-added fields when Studio edits this document.+ return value as FeedbackComment;+}++export function readFeedbackDocument(value: unknown): FeedbackDocument {+ if (!record(value) || !Array.isArray(value.comments)) throw new Error("FEEDBACK.json needs a comments array.");+ const ids = new Set<string>();+ for (const entry of value.comments) {+ const comment = readFeedbackComment(entry);+ if (ids.has(comment.id)) throw new Error(`Duplicate comment id: ${comment.id}`);+ ids.add(comment.id);+ }+ return value as FeedbackDocument;+}++export function readFeedbackMutation(value: unknown): FeedbackMutation {+ if (!record(value)) throw new Error("Expected a comment operation.");+ if (value.type === "add") return { type: "add", comment: readFeedbackComment(value.comment) };+ if (value.type === "delete") return { type: "delete", before: readFeedbackComment(value.before) };+ if (value.type === "replace") return { type: "replace", before: readFeedbackComment(value.before), comment: readFeedbackComment(value.comment) };+ throw new Error("Unknown comment operation.");+}++export function feedbackClock(seconds: number): string {+ const ticks = Math.round(seconds * 100);+ return `${String(Math.floor(ticks / 6000)).padStart(2, "0")}:${String(Math.floor(ticks / 100) % 60).padStart(2, "0")}.${String(ticks % 100).padStart(2, "0")}`;+}diff --git a/packages/studio/src/style.css b/packages/studio/src/style.cssindex 370f1d03..e8f8c27f 100644--- a/packages/studio/src/style.css+++ b/packages/studio/src/style.css@@ -10,6 +10,9 @@--text: #e7e8eb;--text-2: #a4a7ae;--text-3: #6f737c;+ --subtab-surface: #101114;+ --subtab-active-surface: #24262a;+ --subtab-active-text: #c9cbd0;/* Replace this ramp as one unit when Hypit's interaction identity changes. */--brand-200: #f8c1ce;--brand-400: #ed7898;@@ -139,6 +142,14 @@ button:focus-visible, textarea:focus-visible {white-space: nowrap;}.topbar-right { justify-self: end; display: flex; align-items: center; min-width: 0; }+.view-tabs { display: flex; align-items: center; gap: 2px; margin-left: 16px; padding: 2px; border-radius: 5px; background: var(--subtab-surface); }+.view-tabs button {+ display: flex; align-items: center; gap: 7px; height: 24px; padding: 0 10px;+ border: 0; border-radius: 4px; color: var(--text-3); background: transparent;+}+.view-tabs button[aria-selected="true"] { color: var(--subtab-active-text); background: var(--subtab-active-surface); }+.view-tabs button:focus-visible { outline: 1px solid #8a8f99; outline-offset: -1px; }+.view-tabs .icon { width: 14px; height: 14px; }.meta {color: var(--text-3);font: 500 11px/1 var(--font-ui);@@ -166,6 +177,67 @@ button:focus-visible, textarea:focus-visible {grid-template-columns: var(--source-width) 8px minmax(320px, 1fr) 8px var(--workspace-width);overflow: hidden;}+.comments-panel, .comments-handle { display: none; }+.studio-shell[data-view="comments"] { grid-template-rows: minmax(0, 1fr); padding-bottom: 6px; }+.studio-shell[data-view="comments"] > .handle,+.studio-shell[data-view="comments"] > .timeline-panel { display: none; }+.studio-shell[data-view="comments"] .upper-shell { grid-template-columns: minmax(240px, 1fr) 8px var(--comments-width, 360px); }+.studio-shell[data-view="comments"] .source-panel,+.studio-shell[data-view="comments"] .source-handle,+.studio-shell[data-view="comments"] .workspace-panel,+.studio-shell[data-view="comments"] .workspace-handle { display: none; }+.studio-shell[data-view="comments"] .comments-handle { display: block; }+.studio-shell[data-view="comments"] .comments-panel { display: flex; }+.comments-panel { flex-direction: column; min-width: 0; min-height: 0; background: var(--panel); border: 1px solid #08090a; }+.comments-heading { justify-content: space-between; flex: none; }+.comments-heading [data-count] { color: var(--text-3); font-size: 11px; margin-left: 2px; }+.comments-icon { display: inline-flex; align-items: center; justify-content: center; flex: none; width: 26px; height: 26px; padding: 5px; border: 0; border-radius: 3px; background: transparent; color: var(--text-3); }+.comments-icon:hover { background: var(--field); color: var(--text); }+.comments-icon .icon { width: 15px; height: 15px; }+.comments-icon.is-done { color: var(--ok); }+.comments-panel button:disabled { opacity: .4; }+.comments-filters { display: flex; gap: 4px; padding: 10px 12px; border-bottom: 1px solid var(--line); flex: none; }+.comments-filters button { border: 0; background: transparent; padding: 4px 11px; border-radius: 3px; color: var(--text-3); }+.comments-filters button[aria-pressed="true"] { color: var(--text); background: #282a30; }+.comments-list { flex: 1; min-height: 0; overflow: auto; padding: 4px 12px 12px; user-select: text; }+.comments-empty { display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 220px; height: 100%; padding: 24px; text-align: center; color: var(--text-3); }+.comments-empty > .icon { width: 28px; height: 28px; margin-bottom: 18px; opacity: .7; }+.comments-empty strong { font-size: 13px; font-weight: 500; color: var(--text-2); }+.comments-empty p { line-height: 1.7; max-width: 230px; margin: 8px 0; }+.comment-card { padding: 12px 10px 14px; border-bottom: 1px solid var(--line); border-radius: 2px; }+.comment-card.selected { background: #1e2025; }+.comment-card-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; }+.comment-location { display: inline-flex; align-items: center; gap: 9px; padding: 0; border: 0; background: transparent; cursor: pointer; }+.comment-number { margin-right: 5px; color: var(--text-3); font: 500 11px var(--font-mono); }+.comment-actions { display: flex; align-items: center; gap: 1px; }+.comment-time { display: inline-flex; align-items: center; gap: 6px; min-height: 23px; padding: 2px 6px; background: var(--brand-soft); border: 0; border-radius: 3px; color: var(--brand-400); font: 500 11px/1.5 var(--font-mono); white-space: nowrap; }+.comment-time .icon { width: 13px; height: 13px; }+.comment-text { font-size: 13px; line-height: 1.7; color: var(--text); white-space: pre-wrap; overflow-wrap: anywhere; margin: 10px 0 0; }+.comment-card.resolved .comment-text { color: var(--text-3); }+.comment-composer { flex: none; border-top: 1px solid var(--line); padding: 14px 14px 12px; background: #18191d; }+.comment-anchor { display: flex; align-items: center; flex-wrap: wrap; gap: 7px; margin-bottom: 10px; min-height: 24px; }+.comment-composer textarea, .comment-edit textarea { width: 100%; resize: none; background: #202227; color: var(--text); border: 1px solid #33363c; border-radius: 3px; padding: 10px 11px; font: 400 13px/1.7 var(--font-ui); display: block; min-height: 82px; user-select: text; }+.comment-composer textarea::placeholder { color: var(--text-3); }+.comments-panel textarea:focus { outline: none; box-shadow: none; }+.comment-edit textarea:focus { background: #292c32; }+.comments-panel textarea::selection { background: #dce1eb33; color: var(--text); }+.comment-input { border: 1px solid #33363c; border-radius: 4px; background: #202227; transition: background 120ms ease; }+.comment-input:focus-within { background: #292c32; }+.comment-input textarea { border: 0; background: transparent; }+.comment-input-actions { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 2px 9px 9px; }+.comment-tools { display: flex; align-items: center; gap: 4px; }+.comment-tools .comments-icon { width: 28px; height: 28px; padding: 5px; }+.comment-tools .icon { width: 18px; height: 18px; }+.comment-submit { display: grid; place-items: center; flex: none; width: 30px; height: 30px; padding: 0; border: 0; border-radius: 50%; background: #e4e6eb; color: #202227; }+.comment-submit .icon { display: block; width: 18px; height: 18px; }+.comment-submit:hover:not(:disabled) { background: #fff; }+.comment-submit:disabled { opacity: 1; background: #35383f; color: #858b95; }+.comment-submit:focus-visible { outline: 1px solid #aeb3bc; outline-offset: 3px; }+.comments-error { color: var(--brand-200); font-size: 12px; line-height: 1.6; padding: 10px 14px; border-bottom: 1px solid var(--line); }+.comment-edit { margin-top: 10px; }+.comment-edit-actions { display: flex; justify-content: end; gap: 6px; margin-top: 8px; }+.comment-edit-actions button { padding: 4px 11px; border: 1px solid var(--line-strong); border-radius: 3px; background: var(--field); color: var(--text-2); }+.comment-edit-actions button[type="submit"] { color: var(--text); }.source-panel, .preview-panel, .workspace-panel, .timeline-panel {min-width: 0;min-height: 0;@@ -609,7 +681,7 @@ button:focus-visible, textarea:focus-visible {margin: 10px 12px 4px;padding: 2px;border-radius: 5px;- background: #101114;+ background: var(--subtab-surface);overflow: hidden;}.inspector-subtab {@@ -633,7 +705,7 @@ button:focus-visible, textarea:focus-visible {line-height: 1;white-space: nowrap;}-.inspector-subtab.active { background: #24262a; color: #c9cbd0; }+.inspector-subtab.active { background: var(--subtab-active-surface); color: var(--subtab-active-text); }.inspector-empty { padding: 28px 14px; color: var(--text-3); font-size: 11px; text-align: center; }.property-group { min-width: 0; padding: 14px 14px 16px; border-bottom: 1px solid var(--line); }.property-group h3 { margin: 0 0 10px; color: #c4c6cc; font-size: 11px; font-weight: 500; }@@ -1510,11 +1582,26 @@ button:focus-visible, textarea:focus-visible {.stage-audio-wave { width: 85%; padding: 24px 12px; border-radius: 2px; color: #b5c2bb; background: #202824; text-align: center; }.stage-audio-wave img { display: block; width: 100%; height: 100px; }.stage-media-error { position: absolute; bottom: 12px; padding: 8px; background: #24262b; color: #cacdd4; font-size: 11px; }-.stage-scrubber { flex: none; width: 100%; height: 10px; padding: 0; margin: -5px 0; z-index: 2; appearance: none; background: transparent; cursor: pointer; }+.stage-progress { position: relative; flex: none; height: 0; z-index: 2; }+.stage-progress[hidden], .scrub-preview[hidden] { display: none; }+.stage-scrubber { position: absolute; inset: -5px 0 auto; width: 100%; height: 10px; padding: 0; margin: 0; appearance: none; background: transparent; cursor: pointer; }.stage-scrubber::-webkit-slider-runnable-track { height: 2px; background: #676c75; }.stage-scrubber::-webkit-slider-thumb { appearance: none; width: 8px; height: 8px; border-radius: 50%; margin-top: -3px; background: #e1e4e9; }.stage-scrubber::-moz-range-track { height: 2px; background: #676c75; }.stage-scrubber::-moz-range-thumb { width: 8px; height: 8px; border: 0; background: #e1e4e9; }+.stage-review .stage-scaler, .stage-review .stage-viewport { cursor: pointer; }+.stage-review .stage-progress { height: 24px; margin: 0 20px; }+.stage-review .stage-scrubber { top: 0; height: 24px; }+.stage-review .stage-scrubber::-webkit-slider-runnable-track { height: 4px; border-radius: 2px; background: #565b64; }+.stage-review .stage-scrubber::-webkit-slider-thumb { width: 12px; height: 12px; margin-top: -4px; }+.stage-review .stage-scrubber::-moz-range-track { height: 4px; border-radius: 2px; background: #565b64; }+.stage-review .stage-scrubber::-moz-range-thumb { width: 12px; height: 12px; }+.scrub-preview { position: absolute; bottom: calc(100% + 8px); padding: 3px; border: 1px solid #4b4f56; border-radius: 4px; background: #1b1d21; box-shadow: 0 4px 16px #0006; pointer-events: none; }+.scrub-preview-picture { position: relative; display: grid; place-items: center; overflow: hidden; background: #111215; }+.scrub-preview-picture iframe { position: absolute; top: 0; left: 0; border: 0; transform-origin: top left; pointer-events: none; }+.scrub-preview-picture span { padding: 8px; color: var(--text-3); font: 10px var(--font-ui); text-align: center; }+.scrub-preview-picture span[hidden] { display: none; }+.scrub-preview-time { padding: 5px 3px 2px; color: #d5d8df; font: 10px var(--font-mono); text-align: center; }.preview-unavailable .artifact-type { position: static; width: auto; height: auto; clip-path: none; color: #9298a2; font-size: 10px; }@@ -1522,7 +1609,7 @@ button:focus-visible, textarea:focus-visible {.artifact-card.selected .artifact-name-text { color: #f1f2f5; background: var(--artifact-selection); }.library-continuation { grid-column: 1 / -1; height: 28px; display: grid; place-items: center; color: #777e89; font-size: 10px; }-.timeline-overlap-menu {+.timeline-overlap-menu, .selection-menu {position: fixed;z-index: 100;min-width: 160px;@@ -1535,7 +1622,7 @@ button:focus-visible, textarea:focus-visible {background: var(--panel-raised);box-shadow: 0 6px 20px #0006;}-.timeline-overlap-menu button {+.timeline-overlap-menu button, .selection-menu button {display: block;width: 100%;padding: 6px 9px;@@ -1550,7 +1637,9 @@ button:focus-visible, textarea:focus-visible {overflow-wrap: anywhere;}.timeline-overlap-menu button:hover,-.timeline-overlap-menu button:focus-visible { background: var(--field); outline: none; }+.timeline-overlap-menu button:focus-visible,+.selection-menu button:hover,+.selection-menu button:focus-visible { background: var(--field); outline: none; }/* Compact authored rules keep interval geometry without a thumbnail body. */.clip-chrome-compact > .clip-head {diff --git a/packages/studio/src/ui/comments.ts b/packages/studio/src/ui/comments.tsnew file mode 100644index 00000000..c230e4da--- /dev/null+++ b/packages/studio/src/ui/comments.ts@@ -0,0 +1,233 @@+import { feedbackClock } from "../feedback.js";+import type { FeedbackComment, FeedbackMutation, FeedbackView } from "../feedback.js";+import { icon } from "./icons.js";+import type { Store } from "./selection.js";+import type { Stage } from "./stage.js";++type Anchor = Pick<FeedbackComment, "at">;++export function createComments(store: Store, stage: Stage) {+ const element = document.createElement("aside");+ element.className = "comments-panel";+ element.innerHTML = `+ <div class="pane-heading comments-heading">+ <div class="pane-title">${icon("comments")}<h2>Comments</h2><span data-count></span></div>+ <button type="button" class="comments-icon" data-refresh aria-label="Refresh comments" title="Refresh comments">${icon("refresh")}</button>+ </div>+ <div class="comments-filters" role="group" aria-label="Filter comments">+ <button type="button" data-filter="all" aria-pressed="true">All</button>+ <button type="button" data-filter="open" aria-pressed="false">Open</button>+ <button type="button" data-filter="done" aria-pressed="false">Done</button>+ </div>+ <div class="comments-error" role="status" aria-live="polite" hidden></div>+ <div class="comments-list" aria-label="Comments"></div>+ <form class="comment-composer">+ <div class="comment-anchor">+ <button type="button" class="comment-time" data-current-time title="Use current frame" aria-label="Use current frame">${icon("when")}<span>00:00.00</span></button>+ </div>+ <div class="comment-input">+ <textarea rows="3" aria-label="Write a comment" placeholder="What would you like to change?" spellcheck="true" enterkeyhint="send"></textarea>+ <div class="comment-input-actions">+ <div class="comment-tools">+ <button type="button" class="comments-icon" aria-label="Emoji — coming later" title="Emoji — coming later" disabled>${icon("smile")}</button>+ <button type="button" class="comments-icon" aria-label="Draw — coming later" title="Draw — coming later" disabled>${icon("edit")}</button>+ </div>+ <button class="comment-submit" type="submit" aria-label="Send comment" title="Send comment (Enter)" disabled>${icon("send")}</button>+ </div>+ </div>+ </form>`;+ const list = element.querySelector<HTMLElement>(".comments-list")!;+ const form = element.querySelector<HTMLFormElement>("form")!;+ const input = form.querySelector<HTMLTextAreaElement>("textarea")!;+ const submit = form.querySelector<HTMLButtonElement>(".comment-submit")!;+ const counter = element.querySelector<HTMLElement>("[data-count]")!;+ const timeLabel = form.querySelector<HTMLElement>("[data-current-time] span")!;+ const errorView = element.querySelector<HTMLElement>(".comments-error")!;+ let view: FeedbackView | undefined;+ let filter = "all";+ let selected: string | undefined;+ let anchor: Anchor | undefined;+ let busy = false;+ let active = false;+ let fetchId = 0;+ let editing: { id: string; before: FeedbackComment; text: string } | undefined;++ const showError = (error?: unknown): void => {+ errorView.hidden = error === undefined;+ errorView.textContent = error === undefined ? "" : error instanceof Error ? error.message : String(error);+ };+ const currentAnchor = (): Anchor | undefined => {+ const state = store.current();+ if (state === undefined) return undefined;+ return {+ at: state.playhead.frame * state.snapshot.space.frameRate.denominator / state.snapshot.space.frameRate.numerator,+ };+ };+ const renderAnchor = (): void => {+ timeLabel.textContent = feedbackClock(anchor?.at ?? 0);+ submit.disabled = busy || view === undefined || anchor === undefined || input.value.trim().length === 0;+ };+ const capture = (): void => { stage.pause(); anchor = currentAnchor(); renderAnchor(); };+ const button = (name: string, label: string, action: () => void): HTMLButtonElement => {+ const node = document.createElement("button");+ node.type = "button"; node.className = "comments-icon";+ node.innerHTML = icon(name); node.title = label; node.setAttribute("aria-label", label);+ node.disabled = busy;+ node.addEventListener("click", (event) => { event.stopPropagation(); action(); });+ return node;+ };+ const locate = (comment: FeedbackComment): void => {+ stage.pause(); stage.showComposition();+ const state = store.current();+ if (state === undefined) return;+ const frame = Math.round(comment.at * state.snapshot.space.frameRate.numerator / state.snapshot.space.frameRate.denominator);+ store.seek(frame, "video");+ selected = comment.id;+ render();+ };+ const render = (): void => {+ const focusedEdit = list.querySelector<HTMLTextAreaElement>(".comment-edit textarea");+ const cursor = focusedEdit === document.activeElement && focusedEdit !== null+ ? { start: focusedEdit.selectionStart, end: focusedEdit.selectionEnd } : undefined;+ counter.textContent = view === undefined ? "" : String(view.comments.length);+ // Notes are appended to the file in submission order. Number that order;+ // time sorting and filters only change where a note is displayed.+ const comments = [...view?.comments ?? []]+ .map((comment, index) => ({ comment, number: index + 1 }))+ .sort((a, b) => a.comment.at - b.comment.at)+ .filter(({ comment }) => filter === "all" || (filter === "done") === (comment.resolved === true));+ list.replaceChildren();+ if (comments.length === 0) {+ const empty = document.createElement("div");+ empty.className = "comments-empty";+ empty.innerHTML = `${icon(filter === "done" ? "check" : "comments")}<strong></strong><p></p>`;+ empty.querySelector("strong")!.textContent = view === undefined ? "Loading comments…" : filter === "done" ? "No completed comments" : filter === "open" ? "All caught up" : "A note starts here";+ empty.querySelector("p")!.textContent = filter === "all" ? "Pause on a frame and describe what you would like to change." : "Switch filters to see the other comments.";+ list.append(empty);+ }+ for (const { comment, number } of comments) {+ const row = document.createElement("article");+ row.className = `comment-card${comment.resolved ? " resolved" : ""}${comment.id === selected ? " selected" : ""}`;+ row.dataset.commentId = comment.id;+ const head = document.createElement("div"); head.className = "comment-card-head";+ const location = document.createElement("button"); location.type = "button"; location.className = "comment-location";+ const label = document.createElement("span"); label.className = "comment-number"; label.textContent = `#${number}`;+ const time = document.createElement("span"); time.className = "comment-time"; time.textContent = feedbackClock(comment.at);+ location.append(time);+ location.title = "Go to this frame"; location.addEventListener("click", () => locate(comment));+ row.addEventListener("click", (event) => {+ if ((event.target as Element).closest("button, form") !== null || window.getSelection()?.isCollapsed === false) return;+ locate(comment);+ });+ const actions = document.createElement("div"); actions.className = "comment-actions";+ const resolve = button("check", comment.resolved ? "Reopen comment" : "Mark complete", () => {+ void mutate({ type: "replace", before: comment, comment: { ...comment, resolved: !comment.resolved } });+ });+ resolve.classList.toggle("is-done", comment.resolved === true);+ resolve.setAttribute("aria-pressed", String(comment.resolved === true));+ actions.append(label, resolve, button("edit", "Edit comment", () => {+ editing = { id: comment.id, before: comment, text: comment.text }; selected = comment.id; render();+ list.querySelector<HTMLTextAreaElement>(".comment-edit textarea")?.focus();+ }), button("trash", "Delete comment", () => { void mutate({ type: "delete", before: comment }); }));+ head.append(location, actions); row.append(head);+ if (editing?.id === comment.id) {+ const edit = document.createElement("form"); edit.className = "comment-edit";+ const text = document.createElement("textarea"); text.rows = 3; text.value = editing.text;+ text.setAttribute("aria-label", "Edit comment text");+ text.addEventListener("input", () => { if (editing !== undefined) editing.text = text.value; });+ const controls = document.createElement("div"); controls.className = "comment-edit-actions";+ const cancel = document.createElement("button"); cancel.type = "button"; cancel.textContent = "Cancel";+ cancel.addEventListener("click", () => { editing = undefined; render(); });+ const save = document.createElement("button"); save.type = "submit"; save.textContent = "Save"; save.disabled = busy;+ controls.append(cancel, save); edit.append(text, controls);+ edit.addEventListener("submit", (event) => {+ event.preventDefault();+ if (editing === undefined || text.value.trim().length === 0) return;+ void mutate({ type: "replace", before: editing.before, comment: { ...editing.before, text: text.value.trim() } }, () => { editing = undefined; });+ }); row.append(edit);+ } else {+ const text = document.createElement("p"); text.className = "comment-text"; text.textContent = comment.text;+ row.append(text);+ }+ list.append(row);+ }+ if (cursor !== undefined) {+ const next = list.querySelector<HTMLTextAreaElement>(".comment-edit textarea");+ next?.focus({ preventScroll: true }); next?.setSelectionRange(cursor.start, cursor.end);+ }+ };+ const refresh = async (): Promise<void> => {+ const request = ++fetchId;+ try {+ const response = await fetch("/__studio/feedback");+ const data = await response.json() as FeedbackView & { error?: string };+ if (!response.ok) throw new Error(data.error ?? "Could not read comments.");+ if (request !== fetchId) return;+ if (JSON.stringify(view) !== JSON.stringify(data)) { view = data; render(); }+ showError(); renderAnchor();+ } catch (error) { if (request === fetchId) showError(error); }+ };+ const mutate = async (mutation: FeedbackMutation, saved?: () => void): Promise<void> => {+ if (busy) return;+ busy = true; showError(); renderAnchor();+ try {+ const response = await fetch("/__studio/feedback", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(mutation) });+ const data = await response.json() as FeedbackView & { error?: string };+ if (!response.ok) throw new Error(data.error ?? "Could not save comment.");+ ++fetchId; view = data; busy = false; saved?.();+ if (mutation.type === "delete" && selected === mutation.before.id) selected = undefined;+ if (mutation.type === "delete" && editing?.id === mutation.before.id) editing = undefined;+ render();+ } catch (error) { showError(error); }+ finally { busy = false; renderAnchor(); }+ };+ form.addEventListener("submit", (event) => {+ event.preventDefault();+ if (view === undefined || anchor === undefined || input.value.trim().length === 0) return;+ const comment: FeedbackComment = { id: `c-${crypto.randomUUID()}`, run: view.run, ...anchor, text: input.value.trim() };+ void mutate({ type: "add", comment }, () => {+ input.value = ""; input.style.height = ""; selected = comment.id; anchor = currentAnchor();+ });+ });+ input.addEventListener("focus", () => { if (input.value.length === 0) capture(); else stage.pause(); });+ input.addEventListener("input", () => {+ input.style.height = "auto"; input.style.height = `${Math.min(180, input.scrollHeight)}px`; renderAnchor();+ });+ element.addEventListener("keydown", (event) => {+ if (!(event.target instanceof HTMLTextAreaElement) || event.key !== "Enter") return;+ // Some IMEs report the confirming Enter as keyCode 229 after compositionend.+ if (event.isComposing || event.keyCode === 229 || event.shiftKey || event.altKey) return;+ event.preventDefault();+ event.stopPropagation();+ if (!event.repeat) event.target.form?.requestSubmit();+ });+ document.addEventListener("pointerdown", (event) => {+ if (!active || selected === undefined) return;+ const row = event.target instanceof Element ? event.target.closest(".comment-card") : null;+ if (row?.getAttribute("data-comment-id") === selected) return;+ selected = undefined;+ // Keep the clicked control and any unsaved editor mounted through pointerup.+ list.querySelector(".comment-card.selected")?.classList.remove("selected");+ });+ form.querySelector("[data-current-time]")!.addEventListener("click", capture);+ element.querySelector("[data-refresh]")!.addEventListener("click", () => { void refresh(); });+ element.querySelectorAll<HTMLButtonElement>("[data-filter]").forEach((button) => button.addEventListener("click", () => {+ filter = button.dataset.filter!;+ element.querySelectorAll<HTMLButtonElement>("[data-filter]").forEach((item) => item.setAttribute("aria-pressed", String(item === button)));+ render();+ }));+ store.subscribe(() => {+ if (input.value.length === 0) { anchor = currentAnchor(); renderAnchor(); }+ });+ type Hot = { on(event: string, listener: () => void): void };+ (import.meta as ImportMeta & { hot?: Hot }).hot?.on("studio:feedback-changed", () => { if (active) void refresh(); });+ render();+ return {+ element,+ activate(value: boolean) {+ active = value;+ stage.setReviewMode(value);+ if (active) { stage.showComposition(); anchor ??= currentAnchor(); renderAnchor(); void refresh(); }+ },+ };+}diff --git a/packages/studio/src/ui/icons.ts b/packages/studio/src/ui/icons.tsindex 8f031a69..104a029e 100644--- a/packages/studio/src/ui/icons.ts+++ b/packages/studio/src/ui/icons.ts@@ -2,6 +2,11 @@ const paths: Readonly<Record<string, string>> = {brand: '<g transform="translate(0 1.282) scale(.091603) translate(-50 -180)"><path fill="currentColor" stroke="none" d="M303.78,277.82c-5.98-8.63-15.83-13.77-26.32-13.77h-93.41c-12.28,0-24.92,7.44-29.6,18.8l-28.26,75.82c-4.6,11.25-4.54,24.05,2.22,34.16,6.79,10.15,19.36,16.15,31.57,16.15h85.98c14.12,0,26.9-8.88,31.84-22.1l29.69-79.57c3.67-9.84,2.29-20.86-3.69-29.48v-.02h-.02ZM252.02,377.25c-.94,2.52-3.39,4.22-6.08,4.22h-83.45c-4.34,0-6.68-2.8-7.49-3.99s-2.5-4.43-.84-8.44l23.85-66.24c2.29-6.35,8.08-10.87,14.82-11.22.33-.02.67-.02,1.02-.02h75.41s12.51,1.42,9.29,14.61l-26.53,71.09h0ZM106.85,361.73s-22.36-11.59-17.66-32.66l29.67-82.23c4.78-13.25,17.36-22.09,31.45-22.09h95.02c6.25,0,12.1,3.03,15.71,8.14l13.89,19.68h-112.97c-8.7,0-16.49,5.41-19.52,13.57l-35.59,95.6h0ZM73.3,323.27s-22.37-11.59-17.66-32.66l29.67-82.23c4.79-13.25,17.37-22.09,31.45-22.09h89.91c6.25,0,12.1,3.03,15.71,8.14l13.89,19.68h-107.84c-8.7,0-16.49,5.41-19.52,13.57l-35.59,95.6h-.02Z"/></g>',code: '<path d="M9 7 4 12l5 5M15 7l5 5-5 5M13 4l-2 16"/>',edit: '<path d="m4 16-.8 4 4-.8L18.5 8.9 15.1 5.5 4 16Z"/><path d="m13.8 6.8 3.4 3.4"/>',+ studio: '<rect x="3" y="4" width="18" height="16" rx="1.5"/><path d="M3 14h18M8 4v10M15 14v6"/>',+ comments: '<path d="M6 17H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-8l-5 4v-4Z"/><path d="M7 8h10M7 12h7"/>',+ trash: '<path d="M3 6h18M9 6V3h6v3M6 6l1 15h10l1-15M10 10v7M14 10v7"/>',+ send: '<path d="M12 20V4m-6 6 6-6 6 6"/>',+ smile: '<circle cx="12" cy="12" r="9"/><path d="M8 14a4.5 4.5 0 0 0 8 0M8.5 9h.01M15.5 9h.01"/>',eye: '<path d="M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"/><circle cx="12" cy="12" r="2.5"/>',preview: '<rect x="3" y="4" width="18" height="14" rx="2"/><path d="m10 8 5 3.5-5 3.5V8ZM8 21h8"/>',tune: '<path d="M4 7h10M18 7h2M4 17h2M10 17h10"/><circle cx="16" cy="7" r="2"/><circle cx="8" cy="17" r="2"/>',diff --git a/packages/studio/src/ui/main.ts b/packages/studio/src/ui/main.tsindex 643899f3..348db49d 100644--- a/packages/studio/src/ui/main.ts+++ b/packages/studio/src/ui/main.ts@@ -13,6 +13,7 @@ import { semanticGestureSpan } from "../temporal-edit.js";import type { SemanticTarget } from "../temporal-edit.js";import { applyStudioMutation } from "./writeback.js";import { createTimeline } from "./timeline.js";+import { createComments } from "./comments.js";import "../style.css";const app = document.querySelector<HTMLElement>("#app")!;@@ -39,6 +40,10 @@ app.innerHTML = `<div class="topbar-right"><div class="meta" data-meta></div><div class="status" data-status></div>+ <div class="view-tabs" role="tablist" aria-label="Studio view">+ <button type="button" role="tab" data-view="studio" aria-selected="true">${icon("studio")}Studio</button>+ <button type="button" role="tab" data-view="comments" aria-selected="false">${icon("comments")}Comments</button>+ </div></div></header><main class="studio-shell">@@ -65,6 +70,7 @@ const code = createCodePane();const stage = createStage(store, (id) => library.selectArtifact(id));const library = createLibraryPane(code, (artifact) => stage.openArtifact(artifact), (artifact) => stage.renameArtifact(artifact));const timeline = createTimeline(store);+const comments = createComments(store, stage);app.querySelector<HTMLElement>("[data-library]")!.append(library.element);app.querySelector<HTMLElement>("[data-timeline]")!.append(timeline.element);app.querySelector<HTMLElement>("[data-stage]")!.append(stage.element);@@ -91,6 +97,14 @@ const workspaceHandle = createHandle({});workspaceHandle.classList.add("workspace-handle");upperShell.insertBefore(workspaceHandle, workspacePanel);+const commentsHandle = createHandle({+ axis: "column", initial: 360, minimum: 280, invert: true,+ maximum: () => Math.max(280, upperShell.clientWidth - 360),+ apply: (size) => { upperShell.style.setProperty("--comments-width", `${size}px`); },+ remember: "hypit-studio.comments-width",+});+commentsHandle.classList.add("comments-handle");+upperShell.append(commentsHandle, comments.element);shell.insertBefore(createHandle({axis: "row", initial: Math.round(window.innerHeight * 0.45), minimum: 220, invert: true,maximum: () => Math.max(260, shell.clientHeight - 260),@@ -104,6 +118,29 @@ const project = app.querySelector<HTMLElement>("[data-project]")!;const status = app.querySelector<HTMLElement>("[data-status]")!;const failureView = app.querySelector<HTMLElement>("[data-failure]")!;+const changeView = (): void => {+ const current = window.location.hash === "#comments" ? "comments" : "studio";+ shell.dataset.view = current;+ app.querySelectorAll<HTMLButtonElement>(".view-tabs [data-view]").forEach((button) => {+ const selected = button.dataset.view === current;+ button.setAttribute("aria-selected", String(selected)); button.tabIndex = selected ? 0 : -1;+ });+ comments.activate(current === "comments");+};+app.querySelectorAll<HTMLButtonElement>(".view-tabs [data-view]").forEach((button) => {+ button.addEventListener("click", () => { window.location.hash = button.dataset.view!; });+ button.addEventListener("keydown", (event) => {+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;+ event.preventDefault();+ event.stopPropagation();+ const next = button.dataset.view === "studio" ? "comments" : "studio";+ window.location.hash = next;+ app.querySelector<HTMLButtonElement>(`.view-tabs [data-view="${next}"]`)!.focus();+ });+});+window.addEventListener("hashchange", changeView);+changeView();+timeline.element.addEventListener("studio:write", (event) => {const state = (event as CustomEvent<{ readonly state?: string }>).detail.state;status.className = state === "error" ? "status error" : state === "saved" ? "status saved" : "status saving";@@ -1081,6 +1118,7 @@ window.addEventListener("keydown", (event) => {event.preventDefault();return;}+ if (shell.dataset.view === "comments" && ["-", "_", "=", "+", "\\", "f", "F"].includes(event.key)) return;if (event.key === "-" || event.key === "_") {timeline.zoomOut();event.preventDefault();diff --git a/packages/studio/src/ui/overlay.ts b/packages/studio/src/ui/overlay.tsindex 86d7ed3c..75f888be 100644--- a/packages/studio/src/ui/overlay.ts+++ b/packages/studio/src/ui/overlay.ts@@ -20,6 +20,7 @@ export type Overlay = {readonly element: SVGSVGElement;/** The topmost clip drawn at a point, in client coordinates. */hitTest(clientX: number, clientY: number): Clip | undefined;+ hitsAt(clientX: number, clientY: number): readonly Clip[];/** Redraw against the picture, once it has mounted or moved. */refresh(): void;};@@ -127,19 +128,22 @@ export function createOverlay(store: Store, measure: Measure): Overlay {draw();});- return {- element,- refresh: draw,- hitTest(clientX, clientY) {+ const hitsAt = (clientX: number, clientY: number): readonly Clip[] => {const box = element.getBoundingClientRect();- if (box.width === 0 || box.height === 0) return undefined;+ if (box.width === 0 || box.height === 0) return [];const x = (clientX - box.left) / box.width * canvas.width;const y = (clientY - box.top) / box.height * canvas.height;// Hit individual parts, not the empty space inside a group's union box.- return entities.flatMap((clip) => drawnParts(clip)+ const hits = entities.flatMap((clip) => drawnParts(clip).filter((part) => inside(part, x, y)).map((part) => ({ clip, order: part.stackOrder })))- .sort((left, right) => right.order - left.order)[0]?.clip;- },+ .sort((left, right) => right.order - left.order);+ return [...new Map(hits.map(({ clip }) => [clip.id, clip])).values()];+ };+ return {+ element,+ refresh: draw,+ hitsAt,+ hitTest: (x, y) => hitsAt(x, y)[0],};}diff --git a/packages/studio/src/ui/scrub-preview.ts b/packages/studio/src/ui/scrub-preview.tsnew file mode 100644index 00000000..d40846b7--- /dev/null+++ b/packages/studio/src/ui/scrub-preview.ts@@ -0,0 +1,108 @@+import type { StudioSnapshot } from "../shared.js";+import { feedbackClock } from "../feedback.js";++type PreviewWindow = Window & {+ __hypitSeekFrame?: (frame: number) => Promise<boolean>;+ __hypitSetMuted?: (muted: boolean) => Promise<boolean>;+};++/** One lazy, muted picture for scrubbing; it never changes the main playhead. */+export function createScrubPreview(container: HTMLElement) {+ const element = document.createElement("div");+ element.className = "scrub-preview";+ element.hidden = true;+ element.innerHTML = '<div class="scrub-preview-picture"><span>Loading frame…</span></div><div class="scrub-preview-time"></div>';+ element.setAttribute("aria-hidden", "true");+ const picture = element.querySelector<HTMLElement>(".scrub-preview-picture")!;+ const status = picture.querySelector<HTMLElement>("span")!;+ const time = element.querySelector<HTMLElement>(".scrub-preview-time")!;+ container.append(element);+ let iframe: HTMLIFrameElement | undefined;+ let revision: number | undefined;+ let ready = false;+ let seeking = false;+ let requested: number | undefined;+ let displayed: number | undefined;++ const seek = async (): Promise<void> => {+ const current = iframe;+ if (!ready || seeking || current === undefined || requested === undefined || requested === displayed) return;+ seeking = true;+ try {+ while (iframe === current && requested !== undefined && requested !== displayed) {+ const frame: number = requested;+ const target = current.contentWindow as PreviewWindow | null;+ const placed = await target?.__hypitSeekFrame?.(frame);+ if (iframe !== current) return;+ if (!placed) throw new Error("Frame unavailable");+ displayed = frame;+ if (requested === frame) {+ current.style.visibility = "visible";+ status.hidden = true;+ element.dataset.frame = String(frame);+ }+ }+ } catch {+ if (iframe === current) status.textContent = "Frame unavailable";+ } finally {+ if (iframe === current) seeking = false;+ }+ };+ const hide = (): void => { element.hidden = true; requested = undefined; };+ const clear = (): void => {+ hide(); iframe?.remove(); iframe = undefined; revision = undefined;+ ready = false; seeking = false; displayed = undefined;+ delete element.dataset.frame;+ };+ return {+ hide, clear,+ show(snapshot: StudioSnapshot, frame: number, clientX: number): void {+ if (snapshot.revision !== revision) clear();+ if (iframe === undefined) {+ revision = snapshot.revision;+ const { canvasWidth, canvasHeight } = snapshot.space;+ const scale = Math.min(200 / canvasWidth, 170 / canvasHeight);+ picture.style.width = `${canvasWidth * scale}px`;+ picture.style.height = `${canvasHeight * scale}px`;+ const created = document.createElement("iframe");+ created.title = "Hovered frame";+ created.tabIndex = -1;+ created.setAttribute("sandbox", "allow-scripts allow-same-origin");+ created.setAttribute("allow", "autoplay 'none'");+ created.style.width = `${canvasWidth}px`;+ created.style.height = `${canvasHeight}px`;+ created.style.transform = `scale(${scale})`;+ created.style.visibility = "hidden";+ created.addEventListener("load", () => {+ void (async () => {+ const target = created.contentWindow as PreviewWindow | null;+ await target?.__hypitSetMuted?.(true);+ if (iframe !== created) return;+ ready = true;+ await seek();+ })().catch(() => { if (iframe === created) status.textContent = "Frame unavailable"; });+ });+ created.srcdoc = snapshot.preview.srcdoc;+ iframe = created;+ picture.prepend(created);+ }+ requested = frame;+ element.hidden = false;+ const room = container.getBoundingClientRect();+ const left = Math.max(0, Math.min(clientX - room.left - element.offsetWidth / 2, room.width - element.offsetWidth));+ element.style.left = `${left}px`;+ time.textContent = feedbackClock(frame * snapshot.space.frameRate.denominator / snapshot.space.frameRate.numerator);+ if (frame !== displayed) {+ iframe.style.visibility = "hidden";+ status.textContent = "Loading frame…";+ status.hidden = false;+ delete element.dataset.frame;+ } else {+ iframe.style.visibility = "visible";+ status.hidden = true;+ element.dataset.frame = String(frame);+ }+ void seek();+ },+ };+}diff --git a/packages/studio/src/ui/stage.ts b/packages/studio/src/ui/stage.tsindex fa125be1..71bb3cda 100644--- a/packages/studio/src/ui/stage.ts+++ b/packages/studio/src/ui/stage.ts@@ -2,12 +2,18 @@ import { createArtifactPreview } from "./artifact-preview.js";import type { StudioArtifactView, StudioSnapshot } from "../shared.js";import { createOverlay } from "./overlay.js";import { icon, setIcon } from "./icons.js";+import { createScrubPreview } from "./scrub-preview.js";import type { State, Store } from "./selection.js";export type Stage = {readonly element: HTMLElement;/** Start or stop playback, however the request arrived. */toggle(): void;+ pause(): void;+ /** Change picture interaction while preserving Studio's selection. */+ setReviewMode(enabled: boolean): void;+ /** Return from a Result artifact to the composition player. */+ showComposition(): void;openArtifact(artifact: StudioArtifactView): void;renameArtifact(artifact: StudioArtifactView): void;};@@ -33,7 +39,9 @@ export function createStage(store: Store, selectedArtifact: (id: string | undefi<iframe title="Preview" sandbox="allow-scripts allow-same-origin" allow="autoplay"></iframe></div></div>- <input class="stage-scrubber" type="range" min="0" max="0" value="0" step="0.01" aria-label="Media time" hidden>+ <div class="stage-progress" hidden>+ <input class="stage-scrubber" type="range" min="0" max="0" value="0" step="0.01" aria-label="Media time" hidden>+ </div><div class="stage-bar"><span class="stage-time" hidden></span><div class="stage-transport">@@ -55,6 +63,7 @@ export function createStage(store: Store, selectedArtifact: (id: string | undeficonst viewport = element.querySelector<HTMLElement>(".stage-viewport")!;const scaler = element.querySelector<HTMLElement>(".stage-scaler")!;const iframe = element.querySelector<HTMLIFrameElement>("iframe")!;+ let reviewMode = false;/*** Measure a clip in the rendered picture.*@@ -99,13 +108,45 @@ export function createStage(store: Store, selectedArtifact: (id: string | undefi// Clicking the picture selects whatever is drawn under the pointer, which is// the third way into the same selection.scaler.addEventListener("click", (event) => {+ if (reviewMode) { toggle(); return; }const clip = overlay.hitTest(event.clientX, event.clientY);if (clip !== undefined) store.select(clip.id, "video");else store.clearSelection();});+ // A broad component frame can cover smaller elements. Offer all actual+ // Companion hits without special knowledge of captions or any other family.+ let selectionMenu: HTMLElement | undefined;+ const closeSelectionMenu = (): void => { selectionMenu?.remove(); selectionMenu = undefined; };+ scaler.addEventListener("contextmenu", (event) => {+ if (reviewMode) { event.preventDefault(); return; }+ const hits = overlay.hitsAt(event.clientX, event.clientY);+ if (hits.length === 0) return;+ event.preventDefault(); stop(); closeSelectionMenu();+ const menu = document.createElement("div");+ menu.className = "selection-menu";+ menu.setAttribute("role", "menu"); menu.setAttribute("aria-label", "Elements at this point");+ for (const hit of hits) {+ const option = document.createElement("button"); option.type = "button";+ option.setAttribute("role", "menuitem"); option.textContent = hit.display.title;+ option.title = hit.id;+ option.addEventListener("click", () => { store.select(hit.id, "video"); closeSelectionMenu(); });+ menu.append(option);+ }+ element.append(menu);+ menu.style.left = `${Math.max(0, Math.min(event.clientX, window.innerWidth - menu.offsetWidth - 8))}px`;+ menu.style.top = `${Math.max(0, Math.min(event.clientY, window.innerHeight - menu.offsetHeight - 8))}px`;+ selectionMenu = menu; menu.querySelector("button")?.focus();+ });+ document.addEventListener("pointerdown", (event) => {+ if (event.target instanceof Node && !selectionMenu?.contains(event.target)) closeSelectionMenu();+ });+ document.addEventListener("keydown", (event) => { if (event.key === "Escape") closeSelectionMenu(); });// The room around the picture is empty in the plainest sense.viewport.addEventListener("click", (event) => {- if (event.target === viewport) store.clearSelection();+ if (event.target === viewport) {+ if (reviewMode) toggle();+ else store.clearSelection();+ }});const play = element.querySelector<HTMLButtonElement>("[data-play]")!;const previous = element.querySelector<HTMLButtonElement>("[data-previous]")!;@@ -213,6 +254,18 @@ export function createStage(store: Store, selectedArtifact: (id: string | undeficonst title = element.querySelector<HTMLElement>(".stage-title strong")!;const back = element.querySelector<HTMLButtonElement>(".stage-return")!;const scrubber = element.querySelector<HTMLInputElement>(".stage-scrubber")!;+ const progress = element.querySelector<HTMLElement>(".stage-progress")!;+ const scrubPreview = createScrubPreview(progress);+ scrubber.addEventListener("pointermove", (event) => {+ if (!reviewMode || state === undefined || scrubber.disabled || artifactPreview.selected !== undefined) return;+ const box = scrubber.getBoundingClientRect();+ // Native range thumbs travel between their centers, not the input edges.+ const fraction = Math.max(0, Math.min(1, (event.clientX - box.left - 6) / Math.max(1, box.width - 12)));+ const frame = Math.round(fraction * Math.max(0, state.snapshot.space.frameCount - 1));+ scrubPreview.show(state.snapshot, frame, event.clientX);+ });+ scrubber.addEventListener("pointerleave", scrubPreview.hide);+ scrubber.addEventListener("blur", scrubPreview.hide);const time = element.querySelector<HTMLElement>(".stage-time")!;const transport = element.querySelector<HTMLElement>(".stage-transport")!;const clock = (seconds: number): string => {@@ -227,7 +280,7 @@ export function createStage(store: Store, selectedArtifact: (id: string | undeficonst duration = media !== undefined && Number.isFinite(media.duration) ? media.duration : 0;transport.hidden = !timed;mute.hidden = !timed;- scrubber.hidden = !timed;+ progress.hidden = scrubber.hidden = !timed;time.hidden = !timed;play.disabled = duration <= 0 || media?.error != null;previous.disabled = next.disabled = play.disabled;@@ -244,7 +297,7 @@ export function createStage(store: Store, selectedArtifact: (id: string | undeficonst compositionTime = (): void => {if (state === undefined || artifactPreview.selected !== undefined) return;const rate = fps(state.snapshot);- scrubber.hidden = time.hidden = false;+ progress.hidden = scrubber.hidden = time.hidden = false;scrubber.disabled = !ready;scrubber.step = String(1 / rate);scrubber.max = String(Math.max(0, state.snapshot.space.frameCount - 1) / rate);@@ -309,6 +362,7 @@ export function createStage(store: Store, selectedArtifact: (id: string | undefistate = value;if (moved && value.playhead.origin !== "play" && artifactPreview.selected !== undefined) returnToComposition();if (value.snapshot.revision !== mounted) {+ scrubPreview.clear();mounted = value.snapshot.revision;if (artifactPreview.selected === undefined) stop();ready = false;@@ -339,6 +393,15 @@ export function createStage(store: Store, selectedArtifact: (id: string | undefi});return { element, toggle, openArtifact,+ setReviewMode(enabled) {+ reviewMode = enabled;+ element.classList.toggle("stage-review", enabled);+ overlay.element.style.display = enabled ? "none" : "";+ closeSelectionMenu();+ if (!enabled) scrubPreview.clear();+ },+ pause() { stop(); artifactPreview.media?.pause(); },+ showComposition() { if (artifactPreview.selected !== undefined) returnToComposition(); },renameArtifact(artifact) {const selected = artifactPreview.selected;if (selected?.build === artifact.build && selected.output === artifact.output) title.textContent = artifact.displayName ?? artifact.output;diff --git a/packages/studio/start.ts b/packages/studio/start.tsindex 17153c4e..5b41bb37 100644--- a/packages/studio/start.ts+++ b/packages/studio/start.ts@@ -50,7 +50,7 @@ export async function runStudio(argv: readonly string[], io: Pick<CliIo, "write"const runArgument = values.get("run");if (runArgument === undefined || runArgument.trim().length === 0) invalidArguments("Missing --run");const { createServer } = await import("vite");- const { findRuntimeProfile, resolveProjectRoot } = await import("@hypit/cli");+ const { findRuntimeProfile, resolveProjectRoot } = await import("@hypit/project-context-node");const { resolveDistributionPackageImport } = await import("@hypit/package-loader-node");const { videoCliDistribution, videoStudioCompanionPackages } = await import("@hypit/video-cli");const { openStudioBuildLibrary } = await import("./src/build-library.js");@@ -58,6 +58,7 @@ export async function runStudio(argv: readonly string[], io: Pick<CliIo, "write"const { loadStudioDomain } = await import("./src/domain.js");const { loadStudioRun } = await import("./src/run.js");const { studioPlugin } = await import("./src/server.js");+ const { studioFeedbackPlugin } = await import("./src/feedback-server.js");const { inspectStudioRun } = await import("./src/studio-preflight.js");const runPath = resolve(invokedFrom, runArgument);const packageRootArgument = values.get("package-root");@@ -136,7 +137,7 @@ export async function runStudio(argv: readonly string[], io: Pick<CliIo, "write"// available for Source and material previews.fs: { allow: [workspaceRoot, packageRoot, distributionPackageRoot, here] },},- plugins: [distributionImports, studioPlugin({+ plugins: [distributionImports, studioFeedbackPlugin(workspaceRoot, runPath), studioPlugin({source,runPath,workspaceRoot,@@ -152,4 +153,5 @@ export async function runStudio(argv: readonly string[], io: Pick<CliIo, "write"});await server.listen();server.printUrls();+ for (const url of server.resolvedUrls?.local ?? []) io.write(` Comments ${url}#comments\n`);}diff --git a/packages/studio/test/feedback.test.ts b/packages/studio/test/feedback.test.tsnew file mode 100644index 00000000..510656b9--- /dev/null+++ b/packages/studio/test/feedback.test.ts@@ -0,0 +1,54 @@+import assert from "node:assert/strict";+import test from "node:test";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createFeedbackStore, FeedbackConflict } from "../src/feedback-store.js";+import { readFeedbackComment } from "../src/feedback.js";+import type { FeedbackComment } from "../src/feedback.js";++const note: FeedbackComment = { id: "caption-size", run: "runs/main.svrun", at: 12.5, text: "字幕大一点" };++test("comments remain ordinary files through edits, completion, reopening and deletion", async (t) => {+ const directory = await mkdtemp(join(tmpdir(), "hypit-feedback-"));+ t.after(() => rm(directory, { recursive: true, force: true }));+ const store = createFeedbackStore(directory);+ assert.deepEqual(await store.read(), { comments: [] });+ await store.mutate({ type: "add", comment: note });+ const external = { comments: [note, { ...note, id: "agent-note", text: "保留这条", run: "runs/other.svrun" }], projectNote: "hand edited" };+ await writeFile(store.path, JSON.stringify(external));+ const complete = { ...note, resolved: true };+ await store.mutate({ type: "replace", before: note, comment: complete });+ assert.equal((await store.read()).comments[0]?.resolved, true);+ await store.mutate({ type: "replace", before: complete, comment: note });+ await store.mutate({ type: "delete", before: note });+ assert.deepEqual(JSON.parse(await readFile(store.path, "utf8")), { ...external, comments: [external.comments[1]] });+});++test("stale browser edits cannot overwrite a comment changed by the Agent", async (t) => {+ const directory = await mkdtemp(join(tmpdir(), "hypit-feedback-"));+ t.after(() => rm(directory, { recursive: true, force: true }));+ const store = createFeedbackStore(directory);+ const changed = { ...note, text: "新意见", resolved: true };+ await writeFile(store.path, JSON.stringify({ comments: [changed] }));+ await assert.rejects(store.mutate({ type: "delete", before: note }), FeedbackConflict);+ assert.deepEqual((await store.read()).comments, [changed]);+});++test("simultaneous comments are saved without replacing each other", async (t) => {+ const directory = await mkdtemp(join(tmpdir(), "hypit-feedback-"));+ t.after(() => rm(directory, { recursive: true, force: true }));+ const store = createFeedbackStore(directory);+ await Promise.all(["one", "two", "three"].map((id) => store.mutate({ type: "add", comment: { ...note, id } })));+ assert.equal((await store.read()).comments.length, 3);+});++test("unfinished manual JSON stays intact and timestamps are required", async (t) => {+ const directory = await mkdtemp(join(tmpdir(), "hypit-feedback-"));+ t.after(() => rm(directory, { recursive: true, force: true }));+ const store = createFeedbackStore(directory);+ await writeFile(store.path, '{"comments": [');+ await assert.rejects(store.mutate({ type: "add", comment: note }));+ assert.equal(await readFile(store.path, "utf8"), '{"comments": [');+ assert.throws(() => readFeedbackComment({ ...note, at: undefined }), /time/u);+});diff --git a/packages/video-cli/README.md b/packages/video-cli/README.mdindex ce490493..f58fea22 100644--- a/packages/video-cli/README.md+++ b/packages/video-cli/README.md@@ -46,7 +46,10 @@ Chinese speech containing English names; the requested language selects the recomodel, independently of the eventual caption font or script's simplified/traditional characters.`transcribe` uses the Profile's `whisperx-alignment` Endpoint (after-extracting 16 kHz mono speech audio with ffmpeg). `measure` counts a Segment's pronunciation units at a+extracting 16 kHz mono speech audio with ffmpeg). Direct invocation forwards the Provider's progress+and diagnostic callbacks; the CLI reports phase changes while waiting, with JSON progress on the+separate progress stream when supplied. Immediate invocation has no durable remote task receipt and+does not become resumable merely because it reports progress. `measure` counts a Segment's pronunciation units at adelivery policy and prints estimated seconds, the resolved rate, padding and rounding. Choose theliteral `duration` from that estimate and the intended performance. `measure` opens no Profile andspends nothing. It accepts `--pace slow|normal|fast` or `--rate <units/s>`; JSON includes the resolveddiff --git a/packages/video-cli/package.json b/packages/video-cli/package.jsonindex c6cd085d..a31cd702 100644--- a/packages/video-cli/package.json+++ b/packages/video-cli/package.json@@ -20,6 +20,7 @@"@hypit/markup": "workspace:*","@hypit/model-kit": "workspace:*","@hypit/package-loader-node": "workspace:*",+ "@hypit/project-context-node": "workspace:*","@hypit/protocol": "workspace:*","@hypit/provider-hypihub": "workspace:*","@hypit/runtime": "workspace:*",diff --git a/packages/video-cli/src/creation.ts b/packages/video-cli/src/creation.tsindex 535da6a4..ab47120b 100644--- a/packages/video-cli/src/creation.ts+++ b/packages/video-cli/src/creation.ts@@ -2,7 +2,8 @@ import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"import { tmpdir } from "node:os";import { dirname, join, resolve } from "node:path";-import { findRuntimeProfile, loadDiscoveredSourcePackages, resolveProjectRoot } from "@hypit/cli";+import { loadDiscoveredSourcePackages } from "@hypit/cli";+import { findRuntimeProfile, resolveProjectRoot } from "@hypit/project-context-node";import type { CliIo } from "@hypit/cli";import { MemoryResourceStore } from "@hypit/driver-node";import {@@ -14,7 +15,7 @@ import {} from "@hypit/estimate";import type { CanonicalValue, CapabilityRef, Need, StoredValue } from "@hypit/protocol";import type { ResourceStore } from "@hypit/runtime";-import type { RuntimeHostCapabilityProvider, RuntimeHostProviderQuery } from "@hypit/runtime-host-node";+import type { RuntimeHostCapabilityProvider, RuntimeHostProviderQuery, RuntimeInvocationObservation } from "@hypit/runtime-host-node";import { sealSpeechEvidenceAudio } from "@hypit/speech";import { speechEvidenceTypes } from "@hypit/speech-evidence";import type { AlignedTranscriptEvidence } from "@hypit/speech-evidence";@@ -32,7 +33,7 @@ export type CreationCommand = typeof creationCommands[number];/** The slice of the Runtime host these commands use; tests hand in a fake. */export type CreationHost = {providers(requests: readonly RuntimeHostProviderQuery[]): Promise<readonly RuntimeHostCapabilityProvider[]>;- invoke(need: Need, resources: ResourceStore): Promise<{ readonly value: StoredValue }>;+ invoke(need: Need, resources: ResourceStore, observation?: RuntimeInvocationObservation): Promise<{ readonly value: StoredValue }>;};export type CreationEnvironment = {@@ -297,7 +298,16 @@ async function transcribe(argv: readonly string[], io: CliIo, environment: Creat};const provider = await selectedProvider(host, need, profile);if (!parsed.json) io.write(`Transcribing through ${providerLine(provider)}\n`);- const fulfillment = await host.invoke(need, resources);+ const report = parsed.json ? io.writeProgress : io.writeProgress ?? io.write;+ let previousPhase: string | undefined;+ const fulfillment = await host.invoke(need, resources, {+ reportProgress: async (progress) => {+ if (progress.phase === previousPhase) return;+ previousPhase = progress.phase;+ report?.(` · ${progress.phase}\n`);+ },+ reportDiagnostic: async (diagnostic) => { report?.(` · ${diagnostic.message}\n`); },+ });assert(fulfillment.value.kind === "inline", "the transcript came back by reference");const passages = passagesInSeconds(fulfillment.value.value as unknown as AlignedTranscriptEvidence);const words = passages.reduce((total, passage) => total + passage.words.length, 0);diff --git a/packages/video-cli/src/index.ts b/packages/video-cli/src/index.tsindex 041f9cb6..d30884ff 100644--- a/packages/video-cli/src/index.ts+++ b/packages/video-cli/src/index.ts@@ -28,7 +28,7 @@ export { runCaptureCli, writeCaptureHelp } from "./capture.js";export { listPackages, listSurfaces, runVocabularyCli, visualSchema, writeVocabularyHelp } from "./vocabulary.js";export type { PackageListing, SurfaceListing } from "./vocabulary.js";/** The project's selected Runtime Profile, read the way `hypit` reads it, for tools that run beside the CLI. */-export { findRuntimeProfile } from "@hypit/cli";+export { findRuntimeProfile } from "@hypit/project-context-node";export function runVideoCli(argv: readonly string[],diff --git a/packages/video-cli/test/cli.test.ts b/packages/video-cli/test/cli.test.tsindex a2a03a60..ffad3a1a 100644--- a/packages/video-cli/test/cli.test.ts+++ b/packages/video-cli/test/cli.test.ts@@ -41,9 +41,8 @@ test("source package selection follows Run and Author imports", async () => {});test("provider-free example plans from installed Source packages", async () => {- // The examples directory is intentionally kept empty; use the maintained package preview- // fixture instead. It is a real installed Source package and exercises the same provider-free- // planning path (semantic track, composition and mux projections).+ // The installed package preview exercises Timeline, composition and mux planning without+ // requiring a generation account or an authored project copy.const fixture = join(process.cwd(), "packages", "media-track", "preview");let output = "";await runCli([@@ -54,11 +53,13 @@ test("provider-free example plans from installed Source packages", async () => {], { write: (text) => { output += text; } });const plan = JSON.parse(output) as {readonly format: string;- readonly steps: number;+ readonly ok: boolean;+ readonly requestCount: number;readonly targets: readonly string[];};assert.equal(plan.format, "hypit.cli-plan@1");- assert.equal(plan.steps > 0, true);+ assert.equal(plan.ok, true);+ assert.equal(plan.requestCount > 0, true);assert.equal(plan.targets.length, 1);});diff --git a/packages/video-cli/test/creation.test.ts b/packages/video-cli/test/creation.test.tsindex 79c3b230..88d841b9 100644--- a/packages/video-cli/test/creation.test.ts+++ b/packages/video-cli/test/creation.test.ts@@ -41,7 +41,9 @@ function host(seen: Need[]): CreationHost {use: "@hypit/provider-example",pricing: page,})),- invoke: async (need: Need, resources: ResourceStore) => {+ invoke: async (need, resources, observation) => {+ await observation?.reportProgress?.({ phase: "Aligning words" });+ await observation?.reportProgress?.({ phase: "Aligning words" });seen.push(need);if (need.capability.name === "whisperx-alignment") {const request = need.constraints as unknown as WhisperXAlignmentRequest;@@ -74,6 +76,7 @@ test("transcribe writes every word in seconds from the Profile's alignment Endpoawait runCreationCli(["transcribe", "speech.wav", "--to", "speech.json", "--language", "en"], out.io, environment(root, seen));assert.match(out.text(), /paid\.default \(@hypit\/provider-example\) · https:\/\/prices\.example\/models/u);assert.match(out.text(), /2 words in 1 passage over 2s/u);+ assert.equal(out.text().match(/Aligning words/gu)?.length, 1);const file = JSON.parse(await readFile(join(root, "speech.json"), "utf8")) as {readonly audio_seconds: number; readonly passages: readonly { readonly words: readonly { readonly text: string; readonly start_seconds: number }[] }[];};diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e9103ca3..38ef8c75 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -11,6 +11,9 @@ importers:'@puppeteer/browsers':specifier: 3.2.2version: 3.2.2+ cjs-module-lexer:+ specifier: 2.2.1+ version: 2.2.1cmu-pronouncing-dictionary:specifier: 3.0.0version: 3.0.0@@ -162,12 +165,12 @@ importers:'@hypit/program-space':specifier: workspace:*version: link:packages/program-space+ '@hypit/project-context-node':+ specifier: workspace:*+ version: link:packages/project-context-node'@hypit/protocol':specifier: workspace:*version: link:packages/protocol- '@hypit/provider-hyperframes-aws-lambda':- specifier: workspace:*- version: link:packages/provider-hyperframes-aws-lambda'@hypit/provider-hyperframes-local':specifier: workspace:*version: link:packages/provider-hyperframes-local@@ -177,18 +180,12 @@ importers:'@hypit/provider-image-opencv-local':specifier: workspace:*version: link:packages/provider-image-opencv-local- '@hypit/provider-kie':- specifier: workspace:*- version: link:packages/provider-kie'@hypit/provider-media-local':specifier: workspace:*version: link:packages/provider-media-local'@hypit/provider-whisperx-local':specifier: workspace:*version: link:packages/provider-whisperx-local- '@hypit/provider-xiaomi-mimo':- specifier: workspace:*- version: link:packages/provider-xiaomi-mimo'@hypit/ranking':specifier: workspace:*version: link:packages/ranking@@ -322,6 +319,21 @@ importers:specifier: 5.9.3version: 5.9.3+ examples/provider-package/packages/provider-images:+ devDependencies:+ '@hypit/driver-node':+ specifier: workspace:*+ version: link:../../../../packages/driver-node+ '@hypit/gpt-image':+ specifier: workspace:*+ version: link:../../../../packages/gpt-image+ '@hypit/hypit':+ specifier: workspace:*+ version: link:../../../..+ typescript:+ specifier: 5.9.3+ version: 5.9.3+examples/semantic-composition/packages/chat-scene:devDependencies:'@hypit/hypit':@@ -678,6 +690,9 @@ importers:'@hypit/package-loader-node':specifier: workspace:*version: link:../package-loader-node+ '@hypit/project-context-node':+ specifier: workspace:*+ version: link:../project-context-node'@hypit/protocol':specifier: workspace:*version: link:../protocol@@ -1973,6 +1988,12 @@ importers:'@hypit/protocol':specifier: workspace:*version: link:../protocol+ cjs-module-lexer:+ specifier: 2.2.1+ version: 2.2.1+ typescript:+ specifier: 5.9.3+ version: 5.9.3packages/performance:dependencies:@@ -2052,50 +2073,9 @@ importers:specifier: workspace:*version: link:../protocol- packages/protocol: {}+ packages/project-context-node: {}- packages/provider-hyperframes-aws-lambda:- dependencies:- '@aws-sdk/client-s3':- specifier: 3.1103.0- version: 3.1103.0- '@aws-sdk/client-sfn':- specifier: 3.1103.0- version: 3.1103.0- '@hyperframes/aws-lambda':- specifier: 0.7.101- version: 0.7.101- '@hypit/endpoint-kit':- specifier: workspace:*- version: link:../endpoint-kit- '@hypit/hyperframes':- specifier: workspace:*- version: link:../hyperframes- '@hypit/media':- specifier: workspace:*- version: link:../media- '@hypit/protocol':- specifier: workspace:*- version: link:../protocol- '@hypit/render-hyperframes':- specifier: workspace:*- version: link:../render-hyperframes- '@hypit/runtime':- specifier: workspace:*- version: link:../runtime- '@hypit/runtime-kit':- specifier: workspace:*- version: link:../runtime-kit- devDependencies:- '@hypit/composition':- specifier: workspace:*- version: link:../composition- '@hypit/driver-node':- specifier: workspace:*- version: link:../driver-node- '@hypit/program-space':- specifier: workspace:*- version: link:../program-space+ packages/protocol: {}packages/provider-hyperframes-local:dependencies:@@ -2229,88 +2209,6 @@ importers:specifier: workspace:*version: link:../image-transform- packages/provider-kie:- dependencies:- '@hypit/artifact':- specifier: workspace:*- version: link:../artifact- '@hypit/background-removal':- specifier: workspace:*- version: link:../background-removal- '@hypit/endpoint-kit':- specifier: workspace:*- version: link:../endpoint-kit- '@hypit/generation':- specifier: workspace:*- version: link:../generation- '@hypit/protocol':- specifier: workspace:*- version: link:../protocol- '@hypit/runtime':- specifier: workspace:*- version: link:../runtime- '@hypit/runtime-kit':- specifier: workspace:*- version: link:../runtime-kit- devDependencies:- '@hypit/component-kit':- specifier: workspace:*- version: link:../component-kit- '@hypit/core':- specifier: workspace:*- version: link:../core- '@hypit/credential-store-env':- specifier: workspace:*- version: link:../credential-store-env- '@hypit/driver-node':- specifier: workspace:*- version: link:../driver-node- '@hypit/elaborator':- specifier: workspace:*- version: link:../elaborator- '@hypit/gpt-image':- specifier: workspace:*- version: link:../gpt-image- '@hypit/grok-imagine':- specifier: workspace:*- version: link:../grok-imagine- '@hypit/media':- specifier: workspace:*- version: link:../media- '@hypit/minimax-h3':- specifier: workspace:*- version: link:../minimax-h3- '@hypit/model-kit':- specifier: workspace:*- version: link:../model-kit- '@hypit/nano-banana':- specifier: workspace:*- version: link:../nano-banana- '@hypit/narrative':- specifier: workspace:*- version: link:../narrative- '@hypit/resource-store-fs':- specifier: workspace:*- version: link:../resource-store-fs- '@hypit/runtime-local':- specifier: workspace:*- version: link:../runtime-local- '@hypit/seedance':- specifier: workspace:*- version: link:../seedance- '@hypit/seedream':- specifier: workspace:*- version: link:../seedream- '@hypit/store-sqlite':- specifier: workspace:*- version: link:../store-sqlite- '@hypit/text':- specifier: workspace:*- version: link:../text- '@hypit/validation':- specifier: workspace:*- version: link:../validation-packages/provider-media-local:dependencies:'@hypit/artifact':@@ -2382,31 +2280,6 @@ importers:specifier: workspace:*version: link:../speech- packages/provider-xiaomi-mimo:- dependencies:- '@hypit/endpoint-kit':- specifier: workspace:*- version: link:../endpoint-kit- '@hypit/generation':- specifier: workspace:*- version: link:../generation- '@hypit/protocol':- specifier: workspace:*- version: link:../protocol- '@hypit/runtime':- specifier: workspace:*- version: link:../runtime- '@hypit/runtime-kit':- specifier: workspace:*- version: link:../runtime-kit- devDependencies:- '@hypit/driver-node':- specifier: workspace:*- version: link:../driver-node- '@hypit/mimo-speech':- specifier: workspace:*- version: link:../mimo-speech-packages/ranking:dependencies:'@hypit/artifact':@@ -2616,6 +2489,9 @@ importers:'@hypit/driver-node':specifier: workspace:*version: link:../driver-node+ '@hypit/package-loader-node':+ specifier: workspace:*+ version: link:../package-loader-node'@hypit/protocol':specifier: workspace:*version: link:../protocol@@ -3077,6 +2953,9 @@ importers:'@hypit/program-space':specifier: workspace:*version: link:../program-space+ '@hypit/project-context-node':+ specifier: workspace:*+ version: link:../project-context-node'@hypit/protocol':specifier: workspace:*version: link:../protocol@@ -3413,6 +3292,9 @@ importers:'@hypit/package-loader-node':specifier: workspace:*version: link:../package-loader-node+ '@hypit/project-context-node':+ specifier: workspace:*+ version: link:../project-context-node'@hypit/protocol':specifier: workspace:*version: link:../protocol@@ -3633,10 +3515,6 @@ packages:resolution: {integrity: sha512-FO7SB2vLhZRN3lBHVhMhRm3YKSHK8e917qjB8LMEEhU69cQ0Ahd/OMyezu+KqNANqEtyxfSnFVvYt81x6ZKGZA==}engines: {node: '>=20.0.0'}- '@aws-sdk/[email protected]':- resolution: {integrity: sha512-QVA5lMtidoIZL2LAUs2lppS44YzGvxHw+qrdNZP33ulqtp8/ttgk8gf44Ttpzi8nlYF5lbpbsuFeuJXcbDOG/g==}- engines: {node: '>=20.0.0'}-'@aws-sdk/[email protected]':resolution: {integrity: sha512-QiaJV4/zDrB4ZY2mfeSXSzSTc36W16sZXcGz+SPFk0CJ26gziO0cS+4LjJUMAbdeeBOvS0k0Aq1cZpfGdUXxSw==}engines: {node: '>=20.0.0'}@@ -3725,10 +3603,6 @@ packages:'@chenglou/[email protected]':resolution: {integrity: sha512-A8GZN10REdFGsyuiUgLV8jjPDDFMg5GmgxGWV0I3igxBOnzj+jgz2VMmVD7g+SFyoctfeqHFxbNatKSzVRWtRg==}- '@derhuerst/[email protected]':- resolution: {integrity: sha512-F9rL9k9Xjf5blCz8HsJRO4diy111cayL2vkY2XE4r4t3n0yPXVYy3KD3nJ1qbrSn9743UWSXH4IwuCa/HWlGFw==}- engines: {node: '>=6.0.0'}-'@docsearch/[email protected]':resolution: {integrity: sha512-y05ayQFyUmCXze79+56v/4HpycYF3uFqB78pLPrSV5ZKAlDuIAAJNhaRi8tTdRNXh05yxX/TyNnzD6LwSM89vQ==}@@ -4568,18 +4442,6 @@ packages:peerDependencies:hono: ^4- '@hyperframes/[email protected]':- resolution: {integrity: sha512-SNv2b2cn/TKEuSWDeJ6POz29DYqFEnbhDkQ+57+6dv3Ztu4344ChGKlofzK8LxyVXGqLimOnxI8RG0cRxXBxFg==}- engines: {node: '>=22'}- peerDependencies:- aws-cdk-lib: ^2.130.0- constructs: ^10.3.0- peerDependenciesMeta:- aws-cdk-lib:- optional: true- constructs:- optional: true-'@hyperframes/[email protected]':resolution: {integrity: sha512-Zb23T8guk7XB+f3RymuF9Cj1mFvk+y8rW2RQGJcH45WwEk9p7w1ArTApc3y9HR+Ej2bFkCFVYpZQAc4/4++h0Q==}@@ -5216,10 +5078,6 @@ packages:resolution: {integrity: sha512-0JFs3V2y2M9tKW5na/qxe69Zv+uxLMO7QBbhxF/FHu/Gp2NFZAAL9tWl9PU02xxo07pb3G9FTyjNc6D5uZrJIg==}engines: {node: '>=18.0.0'}- '@sparticuz/[email protected]':- resolution: {integrity: sha512-na5beDSZkrlcEWEMt+eHu4Xe+MLUgCtHBjHaXGsNaQu5tJWwXE+McxAcMtyumEM/JzXrxGpkO5vAPD9TWhil3g==}- engines: {node: '>=22.17.0'}-'@swc/[email protected]':resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==}@@ -5241,9 +5099,6 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==}- '@types/[email protected]':- resolution: {integrity: sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw==}-'@types/[email protected]':resolution: {integrity: sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==}@@ -5365,10 +5220,6 @@ packages:resolution: {integrity: sha512-XleryMhbuksdKtofnWZ9Sk+4CUTbms4Mb/EU32SZwToAyZ5RgVos/ki8n+yr0LWHOGKuakbXTuuYNHLQjhddgg==}engines: {node: '>=14.0'}- resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}- engines: {node: '>= 6.0.0'}-resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}engines: {node: '>= 14'}@@ -5392,51 +5243,6 @@ packages:resolution: {integrity: sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg==}engines: {node: '>=4'}- resolution: {integrity: sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==}- peerDependencies:- react-native-b4a: '*'- peerDependenciesMeta:- react-native-b4a:- optional: true-- resolution: {integrity: sha512-Z0oHEHAFDZkffN8Qc39zNZjQlMDkPJRyyyZieU1VH7u8c5S+qHZ2S8ixdKIAxEjfHO7FJxXmJWgteOghVanIsg==}- peerDependencies:- bare-abort-controller: '*'- peerDependenciesMeta:- bare-abort-controller:- optional: true-- resolution: {integrity: sha512-fM+MhCvdQhZ7NV6S95a07gPSqjIYKn6mFaXfx266wN3ajZGl/+1AzH+ubkXQ0fFZvOe2nk9VHkzdYkQE5zMV3Q==}- engines: {bare: '>=1.28.0'}- peerDependencies:- bare-buffer: '*'- peerDependenciesMeta:- bare-buffer:- optional: true-- resolution: {integrity: sha512-JprUlveX3QjApC1cTpsUOiscADftCGVWkzitbHsRqv84hzYwYHw2mbluddsq5TvI8mH/8Ov1f4BiMAdcB0oYnQ==}-- resolution: {integrity: sha512-Kc+brLqvEqGkjyfiwJmImAOqLZL7OsoLKuavx+hJjgVV3nLTOjloJyPMFxjUPerGGHrNH0fLU06jjykMLWrERQ==}- peerDependencies:- bare-abort-controller: '*'- bare-buffer: '*'- bare-events: '*'- peerDependenciesMeta:- bare-abort-controller:- optional: true- bare-buffer:- optional: true- bare-events:- optional: true-- resolution: {integrity: sha512-cD5ciQuKlx+eumTCfqbfiL+fhQm+dHbVNB/cX4+d+I/nx4JsVop9VoFEPAs5RJ6I84QR6bZIBjpd2kjDOYeWcg==}-resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}@@ -5466,16 +5272,10 @@ packages:resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==}- resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}-resolution: {integrity: sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==}engines: {node: '>=18'}- resolution: {integrity: sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==}-resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}@@ -5498,6 +5298,9 @@ packages:resolution: {integrity: sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==}+ resolution: {integrity: sha512-Ca8swihM+/4yKecYHY52kgJd300hi2lADU/a1RxNTRe+RJ9jvqQlESpbz9DnG9mowez8qwXHB8qYdIUw9e+F5Q==}+resolution: {integrity: sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==}engines: {node: '>=20'}@@ -5515,10 +5318,6 @@ packages:resolution: {integrity: sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==}- resolution: {integrity: sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==}- engines: {'0': node >= 6.0}-resolution: {integrity: sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==}engines: {node: '>=18'}@@ -5636,9 +5435,6 @@ packages:resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==}- resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==}-resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}engines: {node: '>=0.12'}@@ -5651,10 +5447,6 @@ packages:resolution: {integrity: sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==}engines: {node: '>=20.19.0'}- resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}- engines: {node: '>=6'}-resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==}engines: {node: '>= 0.4'}@@ -5697,18 +5489,12 @@ packages:resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}- resolution: {integrity: sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==}-resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}- resolution: {integrity: sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==}-resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}engines: {node: '>=12.0.0'}@@ -5722,13 +5508,6 @@ packages:resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==}engines: {node: ^12.20 || >= 14.13}- resolution: {integrity: sha512-H+K6sW6TiIX6VGend0KQwthe+kaceeH/luE8dIZyOP35ik7ahYojDuqlTV1bOrtEwl01sy2HFNGQfi5IDJvotg==}- engines: {node: '>=16'}-- resolution: {integrity: sha512-Dvpa9uhVMOYivhHKWLGDoa512J751qN1WZAIO+Xw4L/mrUSPxS4DApzSUDbCFE/LUq2+xYnznEahTd63AqBSpA==}-resolution: {integrity: sha512-/yNdlIkpWbM0ptxno3ONTuf+2g318kh2ez3KSeZN5dZ8YC6AAmgeWz+GasYYiBJPFaYcSAPeu4GfhUaChzIJXA==}@@ -5812,13 +5591,6 @@ packages:resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==}- resolution: {integrity: sha512-bqX0XTF6fnXSQcEJ2Iuyr75yVakyjIDCqroJQ/aHfSdlM743Cwqoi2nDYMzLGWUcuTWGWy8AAvOKXTfiv6q9RA==}-- resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==}- engines: {node: '>= 6'}-resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==}engines: {node: '>= 14'}@@ -5832,9 +5604,6 @@ packages:resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}engines: {node: '>= 4'}- resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}-resolution: {integrity: sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==}engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}@@ -6041,9 +5810,6 @@ packages:resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==}engines: {node: '>= 0.4'}- resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}-resolution: {integrity: sha512-bUH8SDvPkH3ho3dvwJwfonjlQ4R80vjyvrU8YpxuROddv55vAEJrTuCuCVUhhsHbtlD9tGGbaNApGQckXhS8iQ==}@@ -6065,9 +5831,6 @@ packages:resolution: {integrity: sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==}- resolution: {integrity: sha512-60zvsJReQPX5/QP0Kzfd/VrpjScIQ7SHBW6bFCYfEP+fp0Eppr1SHhIO5nd1PjZtvclzSzES9D/p5nFJurwfWg==}-resolution: {integrity: sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==}@@ -6103,10 +5866,6 @@ packages:engines: {node: '>=14'}hasBin: true- resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==}- engines: {node: '>=0.4.0'}-resolution: {integrity: sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==}@@ -6114,9 +5873,6 @@ packages:resolution: {integrity: sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==}engines: {node: '>=12.0.0'}- resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==}-resolution: {integrity: sha512-Hy5eMQshOEMil4JUUx03h5pw1HYkYCso1RG/gcpPlFSd4cYPOcopxcXEAxpLPOkOPJb9LIJtwxuj66bSdvknFg==}engines: {node: '>=22.12.0'}@@ -6130,10 +5886,6 @@ packages:engines: {node: '>=22.12.0'}hasBin: true- resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}- engines: {node: '>= 6'}-resolution: {integrity: sha512-T98lym7kH+pnZmRaD8yDRdaNqyUbwnbEBx0MuchrzMFOEMray4AO3ZJoTUZ5r78Ao78X/OhzW0DL8GB85w/I2w==}engines: {node: '>= 4'}@@ -6233,9 +5985,6 @@ packages:resolution: {integrity: sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==}- resolution: {integrity: sha512-1Yowhzjf0ivGMrTIkY9hav5TxobO9qIVqUE41fiCGMGgc3CLlf4MY+9AHmZqBWgDTue0fY9zWjYFVyf6Diuobw==}-resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==}engines: {node: '>=18'}@@ -6244,9 +5993,6 @@ packages:resolution: {integrity: sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg==}engines: {node: '>=20'}- resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==}-resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==}@@ -6261,22 +6007,10 @@ packages:resolution: {integrity: sha512-wieBHXygIm7OyQOu5hQlkk62/WyCFYGlWg7L6/ZCUZwx0o398Zkn4pVmMyfYhfMG8kGrj/Krt8eIk6UKC6VzwA==}- resolution: {integrity: sha512-/hU4AXnIdZu+Gvl1pk0oI5f5HxWsCJRtY2aFaJdk9VvyL48DWU6iU5WAIPG+wIi1YvWA6eTJvIviP/tMAZZNwQ==}-- resolution: {integrity: sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg==}-resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==}engines: {node: '>=18'}- resolution: {integrity: sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==}-- resolution: {integrity: sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==}-resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==}@@ -6305,9 +6039,6 @@ packages:resolution: {integrity: sha512-EOPFbyIub4ngnEdqi2yOcNeDLaX/0jcE1JoAXQDDMIthap7FoN795lc/SHfIq2d416VufXpM8z/lD+WRm2gfOQ==}- resolution: {integrity: sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==}-resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}engines: {node: '>=14.17'}@@ -6461,9 +6192,6 @@ packages:resolution: {integrity: sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==}engines: {node: '>=18'}- resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}-resolution: {integrity: sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==}engines: {node: '>=10.0.0'}@@ -6661,17 +6389,6 @@ snapshots:'@smithy/types': 4.16.1tslib: 2.8.1- '@aws-sdk/[email protected]':- dependencies:- '@aws-sdk/core': 3.977.6- '@aws-sdk/credential-provider-node': 3.972.78- '@aws-sdk/types': 3.974.2- '@smithy/core': 3.31.1- '@smithy/fetch-http-handler': 5.6.13- '@smithy/node-http-handler': 4.9.13- '@smithy/types': 4.16.1- tslib: 2.8.1-'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.974.2@@ -6837,13 +6554,6 @@ snapshots:'@chenglou/[email protected]': {}- '@derhuerst/[email protected]':- dependencies:- caseless: 0.12.0- concat-stream: 2.0.0- http-response-object: 3.0.2- parse-cache-control: 1.0.1-'@docsearch/[email protected]': {}@@ -7452,27 +7162,6 @@ snapshots:dependencies:hono: 4.12.32- '@hyperframes/[email protected]':- dependencies:- '@aws-sdk/client-s3': 3.1103.0- '@aws-sdk/client-sfn': 3.1103.0- '@hyperframes/producer': 0.7.101- '@sparticuz/chromium': 148.0.0- ffmpeg-static: 5.3.0- ffprobe-static: 3.1.0- puppeteer-core: 25.5.0- tar: 7.5.22- transitivePeerDependencies:- - bare-abort-controller- - bare-buffer- - bufferutil- - canvas- - proxy-agent- - react-native-b4a- - supports-color- - utf-8-validate- - yauzl-'@hyperframes/[email protected]':dependencies:'@chenglou/pretext': 0.0.5@@ -7981,14 +7670,6 @@ snapshots:dependencies:tslib: 2.8.1- '@sparticuz/[email protected]':- dependencies:- tar-fs: 3.1.3- transitivePeerDependencies:- - bare-abort-controller- - bare-buffer- - react-native-b4a-'@swc/[email protected]':dependencies:tslib: 2.8.1@@ -8012,8 +7693,6 @@ snapshots:'@types/[email protected]': {}- '@types/[email protected]': {}-'@types/[email protected]':dependencies:undici-types: 7.16.0@@ -8139,12 +7818,6 @@ snapshots:- dependencies:- debug: 4.4.3- transitivePeerDependencies:- - supports-color-optional: true@@ -8175,37 +7848,6 @@ snapshots:dependencies:tslib: 2.8.1- [email protected]: {}-- [email protected]: {}-- dependencies:- bare-events: 2.9.1- bare-path: 3.1.1- bare-stream: 2.13.3([email protected])- bare-url: 2.5.1- fast-fifo: 1.3.2- transitivePeerDependencies:- - bare-abort-controller- - react-native-b4a-- [email protected]: {}-- dependencies:- b4a: 1.8.1- streamx: 2.28.0- teex: 1.0.1- optionalDependencies:- bare-events: 2.9.1- transitivePeerDependencies:- - react-native-b4a-- dependencies:- bare-path: 3.1.1-@@ -8228,14 +7870,10 @@ snapshots:optional: true- [email protected]: {}-dependencies:run-applescript: 7.1.0- [email protected]: {}-@@ -8258,6 +7896,8 @@ snapshots:+ [email protected]: {}+dependencies:string-width: 7.2.0@@ -8272,13 +7912,6 @@ snapshots:- dependencies:- buffer-from: 1.1.2- inherits: 2.0.4- readable-stream: 3.6.2- typedarray: 0.0.6-dependencies:is-what: 5.5.0@@ -8388,18 +8021,12 @@ snapshots:- dependencies:- once: 1.4.0-- [email protected]: {}-@@ -8498,19 +8125,11 @@ snapshots:- dependencies:- bare-events: 2.9.1- transitivePeerDependencies:- - bare-abort-controller-optional: true- [email protected]: {}-optionalDependencies:picomatch: 4.0.7@@ -8521,17 +8140,6 @@ snapshots:web-streams-polyfill: 3.3.3optional: true- dependencies:- '@derhuerst/http-basic': 8.2.4- env-paths: 2.2.1- https-proxy-agent: 5.0.1- progress: 2.0.3- transitivePeerDependencies:- - supports-color-- [email protected]: {}-dependencies:tabbable: 6.5.0@@ -8652,17 +8260,6 @@ snapshots:domutils: 3.2.2entities: 7.0.1- dependencies:- '@types/node': 10.17.60-- dependencies:- agent-base: 6.0.2- debug: 4.4.3- transitivePeerDependencies:- - supports-color-dependencies:agent-base: 7.1.4@@ -8703,8 +8300,6 @@ snapshots:- [email protected]: {}-@@ -8898,10 +8493,6 @@ snapshots:- dependencies:- wrappy: 1.0.2-dependencies:emoji-regex-xs: 1.0.0@@ -8931,8 +8522,6 @@ snapshots:- [email protected]: {}-@@ -8960,8 +8549,6 @@ snapshots:- [email protected]: {}-@@ -8979,11 +8566,6 @@ snapshots:long: 5.3.2optional: true- dependencies:- end-of-stream: 1.4.5- once: 1.4.0-dependencies:'@puppeteer/browsers': 3.2.2@@ -9026,12 +8608,6 @@ snapshots:- utf-8-validate- yauzl- dependencies:- inherits: 2.0.4- string_decoder: 1.3.0- util-deprecate: 1.0.2-dependencies:ast-types: 0.16.1@@ -9131,7 +8707,8 @@ snapshots:- [email protected]: {}+ optional: true@@ -9197,15 +8774,6 @@ snapshots:- dependencies:- events-universal: 1.0.1- fast-fifo: 1.3.2- text-decoder: 1.2.7- transitivePeerDependencies:- - bare-abort-controller- - react-native-b4a-dependencies:emoji-regex: 10.6.0@@ -9217,10 +8785,6 @@ snapshots:get-east-asian-width: 1.6.0strip-ansi: 7.2.0- dependencies:- safe-buffer: 5.2.1-dependencies:character-entities-html4: 2.1.0@@ -9236,29 +8800,6 @@ snapshots:- dependencies:- pump: 3.0.4- tar-stream: 3.2.0- optionalDependencies:- bare-fs: 4.8.0- bare-path: 3.1.1- transitivePeerDependencies:- - bare-abort-controller- - bare-buffer- - react-native-b4a-- dependencies:- b4a: 1.8.1- bare-fs: 4.8.0- fast-fifo: 1.3.2- streamx: 2.28.0- transitivePeerDependencies:- - bare-abort-controller- - bare-buffer- - react-native-b4a-dependencies:'@isaacs/fs-minipass': 4.0.1@@ -9267,19 +8808,6 @@ snapshots:minizlib: 3.1.0yallist: 5.0.0- dependencies:- streamx: 2.28.0- transitivePeerDependencies:- - bare-abort-controller- - react-native-b4a-- dependencies:- b4a: 1.8.1- transitivePeerDependencies:- - react-native-b4a-@@ -9304,8 +8832,6 @@ snapshots:- [email protected]: {}-@@ -9457,8 +8983,6 @@ snapshots:string-width: 7.2.0strip-ansi: 7.2.0- [email protected]: {}-diff --git a/scripts/pack-distribution.mjs b/scripts/pack-distribution.mjsindex 8481e1f2..8426fd7d 100644--- a/scripts/pack-distribution.mjs+++ b/scripts/pack-distribution.mjs@@ -36,7 +36,7 @@ readme = readme.replaceAll("https://github.com/user-attachments/assets/cc929974-96b8-4166-b81d-008e130b0f24", `${assets}star.gif`).replaceAll('href="./', `href="${github}`).replaceAll("](./", `](${github}`)- .replace("## Install once\n", "## Install once\n\nInstall the Hypit CLI (Node.js 22.12 or newer):\n\n```bash\nnpm install -g @hypit/hypit\n```\n\nAdd the Skill to your coding agent:\n");+ .replace("## Install once\n", "## Install once\n\nInstall the Hypit CLI (Node.js 22.15 or newer):\n\n```bash\nnpm install -g @hypit/hypit\n```\n\nAdd the Skill to your coding agent:\n");const stage = await mkdtemp(resolve(tmpdir(), "hypit-npm-"));try {diff --git a/services/whisperx/README.md b/services/whisperx/README.mdindex 05e35364..f9e7405d 100644--- a/services/whisperx/README.md+++ b/services/whisperx/README.md@@ -71,6 +71,14 @@ Configuration is deployment state:The Node Provider must configure the same model, device, compute, batch size, service version andWhisperX version. A mismatch fails before transcription results are accepted.+## Package preparation++Local package preparation includes `src/**/*.py` in uv's package cache inputs. Updating service code+therefore rebuilds its small wheel instead of reusing one selected only by an unchanged+`pyproject.toml`. This leaves dependency and speech-model caches intact. See+[uv's local dependency caching](https://docs.astral.sh/uv/concepts/cache/#dynamic-metadata).+This governs package installation; an already running service continues using its loaded code.+## Queue and concurrencyThe SVML Runtime Scheduler decides how many WhisperX Needs may enter this Provider lane. One service@@ -80,3 +88,9 @@ second direct request receives `503 BUSY` instead of entering a hidden service qRun multiple service processes on different devices/ports only when the Runtime registers andlocks them as distinct Provider instances.++The local Provider reconciles this packaged project through `uv sync` before a cold service start.+A passing version probe alone cannot establish that same-version checkout edits were installed;+the declared uv source cache keys decide whether the service wheel needs rebuilding. A healthy+running service remains untouched. To adopt edited service code, stop that selected helper when idle+and start it again through its Profile; restarting only the Build Worker does not reinstall Python.diff --git a/services/whisperx/pyproject.toml b/services/whisperx/pyproject.tomlindex 772ea890..2469bfac 100644--- a/services/whisperx/pyproject.toml+++ b/services/whisperx/pyproject.toml@@ -24,3 +24,5 @@ where = ["src"][tool.uv]package = true+# Rebuild this small service wheel when its packaged Python implementation changes.+cache-keys = [{ file = "pyproject.toml" }, { file = "src/**/*.py" }]diff --git a/skills/hypit/SKILL.md b/skills/hypit/SKILL.mdindex 68b122ed..6c6fc7b6 100644--- a/skills/hypit/SKILL.md+++ b/skills/hypit/SKILL.md@@ -25,7 +25,8 @@ remain grounded, curious, imaginative, and discerning. Be perceptive about the whonest about the details, and curious when something does not yet make sense. Look for connectionsthat explain an unexpected choice. Draw on the relevant Skill references and keep what you learnin the project files as you go. Speak in the user's language, with warmth and specifics from the-work. Share what you have understood, the choices shaping the piece and progress toward delivery.+work. **Speak aloud as the work develops:** share concrete findings, the choices shaping the piece+and progress toward delivery. Explain what the current evidence means and what you will examine next.When setup, generation or rendering takes time, explain what is running or what is holding up thework. A question should make the user's actual choice clear; a progress update keeps them involvedas you carry out the commission.@@ -33,8 +34,7 @@ as you carry out the commission.## Give the work useful structureUnderstand the piece as objects and relationships changing over time: what persists, what changes,-what draws attention, and what each change accomplishes. Express the relationships that should-survive a new product, wording or performance. Give those behaviors useful names and inputs; the+what draws attention, and what each change accomplishes. Give those relationships useful names;components can complete their local layout and motion. Hypit supplies shared authoring and executioninterfaces for both existing and project-defined components.@@ -48,8 +48,11 @@ Choose component boundaries through shared behavior. An ordinary media presentata playing video and a diagram exchanging space can share a scene that owns their layout and motion.Independent Caption or overlays can remain peers. Use an existing component when its behavior fits;create a project component when a new relationship deserves its own expression. A one-off scene is-normal production work. [Component design](references/production/component-design.md) helps turn the-visual idea into useful parts and author controls.+normal production work. Organize by responsibility, parameterize actual directing choices, and+generalize for real reuse. These are separate decisions: a self-contained scene can have a fixed+design and few or no editable parameters. Before implementing a new visual system, read+[Component design](references/production/component-design.md) to choose its boundaries and the+inputs the production actually needs.For spoken work, prefer to author meaning in Script and let the accepted performance give it time.In a clone, discover what a cut, picture, reveal or sound responds to, then recreate that relationship@@ -92,7 +95,8 @@ The Craft owns the explicit appearance, proportion and reusable speaking-view guBefore choosing, designing or changing a character's voice, read[Voice direction](references/playbooks/craft/voice-direction.md). Before writing or adapting a videoprompt, performance Recipe or action, read [Video direction](references/playbooks/craft/video-direction.md)-and the selected Kit's wording and choices. Apply these references when adapting earlier work as well.+and the selected Kit's wording and choices. For movement-led adaptation, that page also explains+letting a video reference carry dance, action or camera behavior. Apply these references when adapting earlier work as well.For A-roll, B-roll, Caption, MG or sound relationships, read the Craft that owns what the work shouldaccomplish. Use installed vocabulary and package-local documentation forthe exact Surface, inputs and limits. Craft supplies directing judgment; package documentation@@ -107,15 +111,22 @@ crafts explain resolution and duration choices.## Prepare for the work at hand-For a spoken reference, use WhisperX's transcript and word times to connect speech with picture-changes. Choose a practical local, hosted or mixed setup for the work, considering readiness,-preparation time, hardware, network and account preferences. Use+Start with the requested work and the next useful result. Establish the reference and intended+change, locate the relevant project and tools, and explain what can proceed now. For a spoken+reference, WhisperX's transcript and word times connect speech with picture changes. Before+preparing a new local inference service, explain its remaining setup effort alongside hosted+WhisperX; available weights can reduce that effort without deciding the user's service choice. Use[environment selection](references/environment/profile.md#choose-the-practical-capability-path-with-the-user)-to explain the options, including HypiHub's combined hosted transcription and generation, and the-effort, accounts and costs involved. Carry working, chosen services forward; prepare the selected-path and reconsider it when actual progress changes its usefulness. Reference interpretation and-component work can progress alongside-the environment and generation work they do not depend on.+to recommend a practical route, including HypiHub's integrated hosted transcription and generation.+Carry working, chosen services forward. Prepare the chosen path and reconsider it when actual+progress changes its usefulness. A Profile-wide readiness report describes configuration; the+current production determines which findings matter next.++As the material plan becomes concrete, connect the required generation capabilities through the+user's chosen accounts. [Models and Providers](references/environment/model-and-provider.md)+explains BYOK and project-owned extensions. Official local and HypiHub Providers are starting+implementations; new services can be connected through the same public package interfaces.+Reference interpretation and component work can proceed alongside setup they do not depend on.## Understand and adapt@@ -124,11 +135,19 @@ story from opening to close: what should the viewer feel, learn or decide, and hbring that about? Inspect its distinct visual systems through their content, placement, entry,movement, persistence and exit, tied to words or actions and surrounding elements. Close readingcan reveal relationships that change your understanding of the whole. Use-[reference understanding](references/creation/reference-video.md) to make both scales concrete.+[reference understanding](references/creation/reference-video.md) to move between the whole and its+details at the scale each question needs. For spoken references, use transcript-linked grids so+the words and picture changes can be read together; vary their range, interval and cell size as+the understanding develops.Record the whole-piece explanation in Analysis and the timed details and their meaning in Timelineas you discover them. Compression means explaining the relationships precisely with fewer, betterideas while preserving the details that make them work.+Make that understanding visible along the way: share a concrete discovery, the passage being+examined and what it suggests for this video. Once the reading supports a direction, show a concise+account with representative frames or a labeled grid and the relationships worth preserving.+This gives the user something tangible to respond to while execution continues under their choices.+The Brief holds the user's goal; the Treatment is your creative answer. Clone work often means"make this with my face" or "use my product." Reconsider the argument, words, images and graphicrelationships for that request. The reference helps explain what works; the new performance supplies@@ -156,6 +175,14 @@ lets B-roll cover the explanation it supports. The composition is ready when itscarry the Treatment clearly and compellingly. Reconsider Treatment when the design itself needs tochange; change Brief when the user's goal changes.+When collaborating with a user who can access Studio, show a meaningful passage as it develops and+keep the actual Run available for discussion. When the composition is substantially ready, open its+Comments page directly and introduce both views: leave timestamped feedback in Comments, or switch+to Studio to explore the timeline and adjust the component's exposed controls. Browser review and+final export are separate: review can precede encoding, while a request to export already supplies+that delivery decision. [Working in Studio](references/production/studio.md#discuss-the-work-while-composing)+connects that visible progress to the component's authored choices.+Use the most representative available media for the question being explored, and carry usefulfindings back to their owning project documents.Environment, creation and production are rooms to revisit whenever the current question leads there.@@ -200,13 +227,17 @@ practical, revisit that choice and carry the improvement into the work and its nbelongs in a project component, without patching the installed Distribution for one video.- **Done means watched.** Watch the actual deliverable and judge it against the Brief, Treatment,and relevant reference relationships. Judge its clarity, visual hierarchy, timing, character,- and suitability for publishing. Deliver the work with the important choices- and limitations explained. Alongside the finished video, show the editable production in+ and suitability for publishing. Browser review can settle the composition before export; when+ delivering an encoded video, inspect that file too. Explain the important choices and limitations.+ Alongside the finished video, show the editable production in[Studio](references/production/studio.md#show-the-finished-work) when it is readily accessibleto the user, so they can see how the piece is arranged and what they can change.## Where the current question is answered+Read the selected reference page in full so its judgment, usage and boundaries stay connected; follow+additional routes as the current question requires.+| When the question is about | Read || --- | --- || how to express a work through materials, components and authored relationships, and how execution realizes it | `references/production/system.md` |@@ -251,7 +282,7 @@ practical, revisit that choice and carry the improvement into the work and its n| drawing a component's elements, animation, resources or prepared surfaces | `references/production/component-visuals.md` || writing a Caption family with new word relationships, scheduling or layout | `references/production/caption-authoring.md` || `plan`, Provider pricing information, `build`, a retry or interrupted submission, following work, Results and exports | `references/production/builds.md` |-| opening Studio, using its views, editing parameters or moving semantic timing | `references/production/studio.md` |+| showing the editable work before export: Comments, Studio timeline, parameters and timestamped feedback | `references/production/studio.md` || giving a component useful timeline entities, picture selection and author controls | `references/production/studio-companions.md` || Film assembly, pure MG with authored time, picture and sound, final rendering or a selected frame interval | `references/production/rendering.md` || judging the preview or finished Result and deciding what to fix | `references/production/review.md` |diff --git a/skills/hypit/references/creation/project-files.md b/skills/hypit/references/creation/project-files.mdindex 129082a7..50effbc3 100644--- a/skills/hypit/references/creation/project-files.md+++ b/skills/hypit/references/creation/project-files.md@@ -221,3 +221,10 @@ A command interruption or missing reply can leave the Worker running. [Builds](.explains how to identify active work and continue through a new Run after a failed attempt.Completed Outputs remain in Results without being exported as files. Keep or add their Run Candidateswhen revising downstream work; neither the notes nor an unchanged output name selects them automatically.++## Keep review notes with the work++Studio's `FEEDBACK.json` belongs to the workspace and records timestamped comments for its Runs.+[Working from Comments](../production/studio.md#revise-from-timestamped-comments) explains reading,+resolving and preserving these shared notes. Carry settled creative choices into Treatment and+execution progress into Progress; retain comments as the review conversation.diff --git a/skills/hypit/references/creation/reference-video.md b/skills/hypit/references/creation/reference-video.mdindex 23290c27..dd5f5bf4 100644--- a/skills/hypit/references/creation/reference-video.md+++ b/skills/hypit/references/creation/reference-video.md@@ -40,6 +40,13 @@ replace an item, add to a collection, or temporarily cover it. Document the systits changes in time. Camera boundaries help navigation; meaning and continuity determine whichthings belong together.+Speak aloud as the understanding develops: share a specific finding, its significance for this work+and the next question being examined, while continuing the investigation. Once the direction is supported, present a+short account of the reference's structure with representative frames or a word-labeled grid:+what persists, what changes on which idea, and which relationships suit the user's adaptation.+Analysis and Timeline retain the detailed evidence; the visible account helps the user assess your+reading and contribute their taste. Routine progress does not require another approval.+Build an account of behavior that can become an editable production. A fixed screen image may bethe evidence the passage needs; a changing comparison also needs its arrivals, states and handoffs.Retain what the objects do together as well as what each looks like. Several implementations can@@ -83,19 +90,28 @@ The local `hypit media` commands expose the source at the scale needed:- `boundaries` locates abrupt visual changes worth inspecting;- `fetch` saves a supported video link locally.-Use broad grids across the full reference to follow its development. For a long reference, read-manageable passages while keeping their place in the whole clear. Inspect dense sequences around-the entries, changes and exits of its distinct visual systems. Choose the range and sampling-interval for the behavior being investigated. A brief animation needs neighboring frames; small-writing needs a larger cell or a full-resolution frame. A broad grid can miss brief events between-samples. Follow the developing idea and the visual systems through closer sequences to understand-their changes and handoffs.+Read grids along the developing explanation, using the transcript's phrases and word times as the+preferred guide for spoken references. Pass `--transcript` to keep those words beside the frames;+`--around` can locate the phrase whose picture change you want to understand.++Continuously adjust the viewed range, sampling interval and cell size to the question. Widen the+range to understand an argument or a persistent system; narrow it and bring samples closer to trace+an entrance, change or handoff; enlarge a frame to read its typography or spatial detail. These are+scales of the same investigation. Move between them whenever a detail changes the explanation or+the explanation directs attention elsewhere. A long reference can be read in manageable passages+while keeping its whole development clear.++Samples establish what appears at their times, with gaps between them. A wider overview can miss a+brief event even when neighboring samples look unchanged. Follow the words and visual systems+through those intervals at a useful density, accounting for their entries, changes, persistence and+exits. A few representative stills cannot supply that temporal account.```bashhypit transcribe references/ad/source.mp4 \--language en --to references/ad/transcript.jsonhypit media tile references/ad/source.mp4 --start 0 --end 12 --every 1 \+ --transcript references/ad/transcript.json \--to references/ad/evidence/opening.jpghypit media tile references/ad/source.mp4 --start 6.8 --end 8.4 --every 0.1 \@@ -196,3 +212,7 @@ Keep the current question, passages or systems still to examine, and next useful`PROGRESS.md`. Write discoveries into Analysis and Timeline while they are fresh, and revise thoseaccounts when the reading changes. When resuming, read these files and reopen the source at therecorded locations. The user's goal remains in Brief and your new design in Treatment.++When the intended adaptation depends on an action's exact movement or camera path, preserve a useful+source excerpt as motion evidence for [reference-directed generation](../playbooks/craft/video-direction.md#let-footage-carry-motion-that-matters).+The analysis explains what matters; the footage can carry that movement into the model request.diff --git a/skills/hypit/references/creation/script-and-time.md b/skills/hypit/references/creation/script-and-time.mdindex 54cdb339..cab4c2a7 100644--- a/skills/hypit/references/creation/script-and-time.md+++ b/skills/hypit/references/creation/script-and-time.md@@ -36,12 +36,12 @@ Choose Script structure from the thought being expressed and the performance car```svml<script id="story"><hook>- <HOST> @claim! I made @proof <Hypit | Hai-Pit> || work overnight @/proof.+ <HOST> @claim! I made the @proof <API | A P I> || work overnight @/proof.</hook></script>```-Here the viewer reads `Hypit` while the performance says `Hai-Pit`. The pair is one indivisible+Here the viewer reads `API` while the performance receives `A P I`. The pair is one indivisibleAlignment Unit. `||` ends one on-screen Caption Cue after that unit and lets the next Cue begin with`work`; `proof` remains one semantic range, and `claim` is a semantic point that other layers can use.@@ -111,15 +111,18 @@ Chinese, English and mixed-script grouping, spacing and their fit in the pictureChoose pronunciation while writing the Script. For coined names, unfamiliar brands and abbreviationswhose reading needs direction, use Dual Text to keep the intended display spelling and give theperformer a clear spoken form. Write that form as readable words, syllables or letter names in the-performed language. This lets the request express the sound the work needs.+performed language. Keep ordinary spelling when it already expresses the intended reading; an+English name inside Chinese speech does not automatically need a phonetic replacement. The spoken+side is literal model input, so invented respellings and punctuation can suggest unintended sounds.+Use a reading established for the selected language and voice, and retain the user's chosen spelling.```svml<script id="story"><opening>- <HOST> I make videos with <Hypit | Hai-Pit> and write with <ChatGPT | chat G P T>.+ <HOST> This app connects through an <API | A P I>.</opening><closing>- <HOST> Here is what I made with <Hypit | Hai-Pit>.+ <HOST> The same <API | A P I> works here too.</closing></script>```@@ -248,6 +251,12 @@ estimates can retain fractions with `--rounding none`. `ceil` rounds upward to a`round` chooses the nearest one. Most video requests use whole seconds; choose the final literal withthe selected model's supported values and the intended performance in mind.+An energetic performance can still give a dense explanation room to breathe. Use the reference's+pronunciation-unit count over its spoken passages to inform a candidate rate, then choose for the target's language,+terminology and actions. Inspect the effective density after rounding each request: fitting every+line into the shortest supported duration can make the whole delivery rushed. Keep the chosen rate+and meaningful padding with the production's direction so later Segments follow the same decision.+Let that estimate inform the shape of the passage. A short line may belong with the next response,benefit from a little fuller wording, or leave room for a meaningful action. A long passage may readbetter with tighter copy or a split at a natural change of thought. Preserve the intended meaning anddiff --git a/skills/hypit/references/environment/distribution.md b/skills/hypit/references/environment/distribution.mdindex 5164581d..b38a81f4 100644--- a/skills/hypit/references/environment/distribution.md+++ b/skills/hypit/references/environment/distribution.md@@ -64,6 +64,12 @@ source and choose a reachable route. Keep the requested version when changing re## Let the installation channel own updates+The Distribution supplies local execution and HypiHub Providers, plus public SDKs and examples for+project extensions. A service the user brings can use an installed or project-authored Provider;+its absence from the official bundle is an extension question. Follow+[Models and Providers](model-and-provider.md) for that connection. Installing the executable does+not choose a service account or prepare every model that a production might eventually use.+Install, update, and remove the Distribution through the same package or release channel. Updatingit does not update an installed Skill or edit a video project. Updating the Skill does not replace theexecutable Distribution. After installation or an update, use the selected launcher for `--version`,@@ -77,3 +83,11 @@ Explain whether the work needs an available package, a supported alternative orA contributor checkout can execute its own Distribution after its documented workspace setup, but itis a development arrangement, not an assumed location for ordinary production. Use one only when theuser explicitly supplied or selected that checkout.++Optional upstream npm tools live under the Host package home reported by `paths`, with one installation+per exact package version. Separate Distribution requirements can coexist there, while npm still shares+its download cache. `hypit packages install <package@version>` reports `install.log`; inspect that file+when a download appears stalled or fails. Installing an upstream tool does not start a service or+restart an existing service. Project component edits are loaded by the next Build. See+[Build execution](../production/builds.md#build-with-the-current-project-implementation) for Distribution+bootstrap changes and service lifetimes.diff --git a/skills/hypit/references/environment/local-tools.md b/skills/hypit/references/environment/local-tools.mdindex 364ca66e..0febb68b 100644--- a/skills/hypit/references/environment/local-tools.md+++ b/skills/hypit/references/environment/local-tools.md@@ -16,6 +16,9 @@ findings in [environment selection](profile.md#choose-the-practical-capability-pthen prepare the chosen setup using its Provider instructions and the evidence from its logs.Consider hardware and actual network reachability alongside installed files. A cached environmentcan still need speech-model weights or a language's alignment model before its first useful request.+Existing weights can make local preparation attractive; report that fact while offering the local+and hosted choice. Starting a newly configured large-model service is preparation even when all+weights are cached. A previously chosen, working service can be carried forward directly.## Diagnose the selected local capability@@ -72,24 +75,28 @@ needed by local HyperFrames. Its Provider owns the prepare command, start commanidentity, and configuration. The Runtime operates those declarations:```bash-hypit runtime up-hypit programs status+hypit programs up --endpoint whisperx.local+hypit programs status --endpoint whisperx.local```-`runtime up` prepares selected adapter dependencies, brings declared Programs to their expected local-state, and starts the Worker. It prepares all Endpoints declared in that Profile, including a local-Endpoint whose capability is currently bound to a hosted one. Keep the active Profile representative-of the chosen setup; bindings select request execution, not which declared Programs are prepared.+Name the chosen Profile instance with `--endpoint`; repeat it for several services. This scopes+package preparation and Program operations together. `runtime up --endpoint <instance>` also starts+the Worker. Omitting the flag deliberately covers the whole Profile. A binding selects which Endpoint+fulfills a request; `plan` checks the Endpoints resolved for its actual requests, so an unused local+service or hosted credential does not become a prerequisite for that Build.Program commands leave the Worker lifecycle alone:| Intention | Command || --- | --- |-| Prepare and start the selected helpers | `hypit programs up` |-| Inspect their current state | `hypit programs status` |-| Stop helpers managed by Hypit | `hypit programs down` |+| Prepare and start the selected helpers | `hypit programs up --endpoint <instance>` |+| Inspect their current state | `hypit programs status --endpoint <instance>` |+| Stop helpers managed by Hypit | `hypit programs down --endpoint <instance>` |-`runtime down` stops the Worker while leaving separately managed Programs available. This lets a later-Build reuse an already warm local model. Use `programs down` when those helpers themselves should stop.+`runtime down` stops the Worker and its execution processes while leaving separately managed Programs available. This lets a later+Build reuse an already warm local model. Use scoped `programs down` when a helper itself should stop.+A healthy service stays warm across repeated `up` calls. Local WhisperX reconciles its packaged Python+environment before a cold start; uv reuses cached dependencies and weights. This is separate from+loading project component code for a new Build.Ordinary projects use these declarations instead of running a service's internal `uv sync` or Pythonentry point by hand. Contributor/operator commands in a service README are for diagnosing that@@ -126,10 +133,10 @@ download. Weigh accuracy needs against setup and inference time, including the hThe Provider README owns exact settings, compute choices and the distinction between transcriptionand language-specific alignment. Configure the chosen model before preparing it.-With the Endpoint and model selected, run `hypit runtime up`. The first preparation may install Python+With the Endpoint and model selected, run `hypit runtime up --endpoint whisperx.local`. The first preparation may install Pythonand download model weights, while later projects reuse the machine Program. Success means the configured-service identity answers its health probe; `hypit doctor` then checks the selected Endpoint as part of-the full Profile.+service identity answers its health probe; `hypit doctor --endpoint whisperx.local` then checks that+selected service.## Make network preparation practical@@ -185,5 +192,7 @@ metadata successfully may still redirect large files to another host; diagnose t- A remote authentication, account, quota, or model-catalogue error belongs to the remote Endpoint and`profile.md`, even when the Worker happens to run locally.-After changing the Distribution or an already loaded project package, read `../production/builds.md`-before restarting the Worker so active work is preserved.+Project component and Profile edits apply to the next Build through its fresh execution context.+For a Distribution or inherited shell-environment change, read+[Build execution](../production/builds.md#build-with-the-current-project-implementation) before+restarting the coordinator so active work is preserved.diff --git a/skills/hypit/references/environment/model-and-provider.md b/skills/hypit/references/environment/model-and-provider.mdindex 445aae7b..7bfa73e6 100644--- a/skills/hypit/references/environment/model-and-provider.md+++ b/skills/hypit/references/environment/model-and-provider.md@@ -1,111 +1,106 @@# Models, services, and Keys-Read this when the user wants a new model, another service for a familiar model, or a new account.-A Key identifies access to a service. The model describes what the work asks that service to produce.-Look at the existing Profile and the service's actual documentation before deciding what to change.--## Follow one request through the possible changes--Suppose the Source already asks GPT Image 2 to make a 9:16, 2K picture from a portrait and a Prompt.-The Model describes that request. The KIE Provider knows how to send it to KIE. An Endpoint such as-`kie.personal` configures that Provider for a particular account, deployment and capacity.--**The same service, a new Key.** If the existing account merely replaces its Key, update the value in-its Credential Store; the Endpoint can keep the same CredentialRef. To retain a personal account and-add a company account, create another credential entry and configured Endpoint, such as-`kie.company`. Both use the same Provider code. The Profile chooses the intended account.--**The same protocol, another address.** Reuse the Provider when its documented configuration accepts-the address and the deployment supports the full required protocol: authentication, reference upload,-submission, polling and result transfer. A similar URL shape or model label does not establish that.-For example, KIE's Provider exposes API and upload base URLs; the destination must actually support-the operations that this Provider performs.--**The same model, another service.** First look for an installed Provider for that service. KIE and-HypiHub both implement GPT Image 2, so an explicit switch between those implementations is a Profile-choice. A new service with a different API needs a Provider mapping if none already supports it.-That package translates the same model inputs into the service's fields, follows its tasks and stores-the returned media. The Model and the creative Prompt can remain unchanged. If the service offers-only a subset, such as 1K output, report the unsupported 2K request and resolve that production choice.--**A model Hypit does not yet describe.** Supply a Model definition for its actual text/media inputs,-parameters and result types, together with a Provider that implements its capability. An existing-Provider can be reused when it already supports that capability. One package may contain both Model-and Provider facets; a Provider can serve several models, and several Providers can serve one model.-A local deployment follows the same relationship, with a Managed Program when Hypit should prepare-and run its helper service.--The Agent establishes which service owns the Key, which model the user wants, and whether an existing-implementation can perform the actual request. Explain the resulting work in practical language:-“Your service offers the model we need. I'll check how it accepts reference images and returns results,-then connect your account to that implementation.” Use known account information and ask only for-missing facts or a choice that affects cost, privacy, setup or capability. Credential entry follows-`hypit auth` and the selected Store, keeping the secret out of Source and conversation.--## Keep the request and its execution separate--The Model owns author-visible meaning: exact model identity, text and media inputs, reference roles,-parameter values, and result types. It lowers Source into a Need with a versioned capability, a-concrete request, and an expected result type.--The Provider implements that capability through its service. It owns wire fields, URLs, uploads,-authentication, task handling, result transfer, service-specific support limits, capacity, diagnostics,-and its price source. When useful machine-readable pricing exists, `readPricing` may use the complete-request to retrieve relevant Provider-owned material. The returned data keeps the Provider's own shape;-a pricing page remains the interface when that is what the service publishes. Generated media returns-as stored Resource references of the declared type.-The shared generated-media vocabulary carries text, media references, and image/video/audio results;-it does not choose a vendor or model on the author's behalf.--The Runtime Profile selects a configured Provider instance, called an Endpoint. A `binding` chooses-one when several Endpoints offer the same capability. The same Source can use another implementation-of that capability through an explicit Profile change. Different author inputs or model behavior may-instead require changing the Model and Source.--A service may expose only part of a model's supported range. Its Provider checks the complete request-through `supports` and reports unsupported combinations before submission. That service restriction-belongs to the Provider; it does not narrow the Model vocabulary for other implementations.--HypiHub participates in this same selection model. [Runtime Profile and capabilities](profile.md)-owns hosted, BYOK, local, account, and fallback choices.--## Extend through an ordinary project package--A custom Provider or Model can live in the project's `packages/` directory or arrive as an installed-package. Source selects Model contributions; the Runtime Profile selects Provider contributions by-`use`. The package's `hypit.activation` entry supplies the corresponding facets to those hosts.--The public APIs are supplied by the executable `@hypit/hypit` Distribution:+Read this when the user brings a Key, chooses another service, or needs a model that is not yet+available. Connecting a service through a project package is ordinary production work, like making+a project component. Hypit supplies the extension interfaces; the production selects implementations.++## Know which fact is changing++A **Model** describes what to generate: exact model identity, text and media inputs, reference roles,+parameters and result types. It produces a Need for its versioned capability. A **Provider** fulfills+that request through a particular API or local process. An **Endpoint** configures a Provider for an+account or deployment. The Runtime Profile selects the Endpoint, using a binding when several+implement the same capability.++| Situation | Work to do |+| --- | --- |+| Replace a Key for the same account | Update its Credential Store entry; retain the Endpoint's reference |+| Add another account on that service | Configure another Endpoint using the same Provider |+| Use another address with the same complete protocol | Use the Provider's supported address configuration |+| Use the same model through a different API | Reuse an installed suitable Provider, or write a project Provider |+| Use a model not yet described | Add its Model definition and an implementation of its capability |++A Key alone does not identify its service protocol. Establish the service and relevant API docs from+the user's information, known configuration or a concise question. Similar model labels do not prove+that uploads, input parameters, task handling or results match. For an existing exact capability,+map the request in the Provider; keep the Model and creative prompt unchanged. Resolve a service's+unsupported combination explicitly, such as requesting 2K where it only offers 1K.++## Choose a service for the work++The official Distribution supplies local Providers and HypiHub. HypiHub is the recommended integrated+hosted route, maintained alongside Hypit's supported production capabilities, including WhisperX+and generation. It is a useful way to start when the user wants hosted execution without connecting+several services. Current availability, account requirements and rates still come from that service.+Match its current catalogue to the installed Model vocabulary and Provider support for the requested+inputs. A service can add a model before the installed Distribution describes it; that calls for a+Model and Provider extension or a release containing them. A missing model or unsupported parameter+is a capability question, while an expired credential is an account question.++A user's existing service or local deployment remains a normal choice. BYOK means using that chosen+account through a Provider; it does not require an officially bundled adapter. Partner introductions+are maintained on the [service-partner page](https://github.com/hypit-ai/hypit/blob/main/docs/guide/service-partners.md).+A partner is an independent service with its own+account, pricing and API, and uses the same project-extension path as any other external service.++[Environment selection](profile.md#choose-the-practical-capability-path-with-the-user) owns readiness,+local preparation and account choices. Connect the capability needed next. For a spoken reference,+that may be WhisperX while the generation plan is still developing. Once the intended material is+clear, explain its required models and ask about an account only where that choice is unresolved.++## Implement the missing capability in the project++First inspect the selected model's vocabulary and README, then the service's actual API docs. Reuse+an installed compatible implementation when available. Otherwise create `packages/provider-…` in+the production, implementing the requests this work needs. The package may later be reused in other+projects under its owner's scope. Ordinary project extensions do not require a framework release.++Follow one concrete request through the service:++1. Name the Model's exact capability and expected result type. Identify scalar fields, text and+ media-reference roles in its request. A genuinely new model needs a Model definition as well.+2. Map those inputs to the API's fields and media transport. Declare `supports` for real service+ limits, considering authored inputs that are not yet produced. Support checks and pricing+ receive the request, not a graph to reverse-engineer.+3. Resolve only the declared CredentialRefs. Return immediate results directly, or implement+ `start`, `poll` and, where useful, `collect` for acknowledged remote tasks. Record the received+ task ID promptly; let Runtime drive the lifecycle and retain it through interruptions.+4. Admit returned media through `context.resources` and return the declared result type. Declare+ capacity for the actual account/deployment. Supply the pricing page or `readPricing` material+ with units and conditions, without inventing a bill for unknown future inputs.+5. Compile and install the package, select its `use` in the Profile, and inspect `plan` and `pricing`+ for the actual Run. An authorized real request establishes live execution; read-only checks+ establish configuration and support without spending on a test generation.++The complete **project Provider example** ships in the Distribution at+`examples/provider-package/README.md`, with compilable source, activation and Profile configuration.+Locate it through `hypit paths`. Its unbranded example API is illustrative; use the selected service's+actual protocol. It demonstrates reference upload, receipt, polling, collection, limits and rates+without introducing a second scheduler. For a new Model, the Model SDK README includes the definition+and author-package activation example.++## Use the public SDK| Import | Responsibility || --- | --- |-| `@hypit/hypit/author-kit` | Author Module, Surface, component, and Fragment declarations |-| `@hypit/hypit/model-kit` | Exact model requests and their Producer/Need construction |-| `@hypit/hypit/generation` | Shared generated-media inputs, results, validation, and wire-mapping helpers |-| `@hypit/hypit/endpoint-kit` | Capability handlers, credentials, receipts, and capacity declarations |-| `@hypit/hypit/runtime-kit` | Profile-selected activation, configuration, diagnostics, and Managed Programs |--Each API's package README owns its exact fields and examples. Locate those files in the active-Distribution reported by `hypit paths`: `packages/model-kit/README.md`,-`packages/generation/README.md`, `packages/endpoint-kit/README.md`, and-`packages/runtime-kit/README.md`. They ship with the executable; a repository checkout is unnecessary.--Compile a TypeScript extension against the selected `@hypit/hypit` development dependency and ship its-JavaScript and required assets. [Sharing a package](../production/component-sharing.md) explains direct-tarball handoff and registry releases. Creating an implementation of an existing public extension-point belongs in that package. Changing a shared port type, host protocol, or framework behavior is-a framework change and should be considered at that boundary.--## Establish that the connection works--Install the selected package, configure the Endpoint and credential reference, and use `doctor` to-inspect the selected deployment and its diagnostics. A Run's `plan` should identify the intended-capability, Endpoint, and price source, and accept the actual parameters and reference types needed-by this video. Read-only-checks establish configuration and declared support; a real media request needs the user's spending-authority and a result judged against the work.--A remote acknowledgement belongs to that submitted task. The Provider retains its non-secret receipt-and follows it through completion and collection. A failed attempt keeps the useful evidence and-Outputs; subsequent work selects them in a new Run. [Builds](../production/builds.md) explains this-execution model and its receipt handling.+| `@hypit/hypit/model-kit` | Exact model ports and Producer/Need construction |+| `@hypit/hypit/generation` | Generated-media values, validation and optional wire-mapping helpers |+| `@hypit/hypit/endpoint-kit` | Handlers, resource access, credentials, receipts, support and capacity |+| `@hypit/hypit/runtime-kit` | Profile activation, configuration, diagnostics and Managed Programs |+| `@hypit/hypit/author-kit` | Author Module, Surface and Fragment declarations for a new Model |++Each API's README in `packages/<name>/README.md` owns its exact interface and ships with the+executable. Use the active `@hypit/hypit` release as the extension's development dependency and ship+compiled JavaScript plus ordinary runtime dependencies. A repository checkout is unnecessary.+The package's `hypit.activation` exposes its facets; Source selects author contributions, while+Profile `use` selects execution contributions. Installing a package does not select its account.+[Package sharing](../production/component-sharing.md) explains tarballs and owner-managed releases.++Local inference follows the same model: implement the capability through the chosen local process.+Contribute a Managed Program when Hypit should prepare and operate a persistent helper. A Provider+owns its service mapping and diagnostics; it receives neither authority to change another account+nor a reason to alter the shared execution system.++Keep secrets in the selected Credential Store, and account/scope decisions in Brief. Report what+was connected and what remains needed in the user's language. [Builds](../production/builds.md)+owns spending scope, durable execution and reuse of produced Outputs.diff --git a/skills/hypit/references/environment/profile.md b/skills/hypit/references/environment/profile.mdindex f3c472e3..e614b33c 100644--- a/skills/hypit/references/environment/profile.md+++ b/skills/hypit/references/environment/profile.md@@ -32,7 +32,8 @@ A ready service, an installed Python environment and weights still downloading aFor a spoken reference, transcription may be the immediate need while generation is taking shape;recommend a path with both this immediate task and the likely production ahead in view.-`programs status` and `doctor` describe the selected Profile. A Profile containing only hosted+`programs status` and `doctor` describe the selected Profile, or the instances named with repeated+`--endpoint <instance>` flags. A Profile containing only hostedalignment leaves local WhisperX readiness unexamined. [Local tools](local-tools.md#assess-local-preparation)explains where to inspect existing preparation and known service configuration.@@ -41,7 +42,8 @@ explains where to inspect existing preparation and known service configuration.is a different proposition: weigh downloads, hardware, inference time and expected future use.Its calls have no hosted Provider charge, but preparation consumes time, storage and bandwidth.[Local tools](local-tools.md#select-local-whisperx-explicitly) owns setup and repair guidance.-- Use a supported BYOK Provider when the user already has that account and wants to use it.+- Use the user's chosen service when it supports the required model. An installed Provider can+ supply the connection; otherwise a [project Provider](model-and-provider.md) can implement it.- Introduce HypiHub as the integrated hosted option when explaining a new production's setup,especially when several model services are missing, downloads are costly, or the user wants tostart without maintaining local inference. It combines hosted WhisperX with supported image,@@ -55,6 +57,13 @@ generation. A user who only needs transcription may find an existing local serviopening a new paid account. Present HypiHub where its convenience helps the actual work, includingwhen later generation needs arise; an already working local service can keep the analysis moving.+Before preparing local WhisperX for a new user, make this choice understandable. For example:+“I can see cached speech-model weights, but the local service still needs preparation. We can+prepare it here, or use HypiHub's hosted WhisperX, which can also supply the later image and video+models. Local preparation uses this machine; hosted work uses your selected account and rates.”+Adapt the recommendation to the evidence. Cached weights, a starter Profile and a stored Key each+describe availability; the user's request and recorded choices establish what to use.+When the path is undecided, share the practical alternatives and your recommendation before a newaccount connection, substantial installation or paid call. Ask for the choice that is actuallyunresolved. Once the route is agreed, carry out ordinary setup and work with progress updates.@@ -63,6 +72,13 @@ Their decision can cover preparation as a whole. Record it in[Paid scope](../production/builds.md#work-within-the-agreed-paid-scope) explains how the commissioncovers service charges. Prepare further model credentials as the creative plan needs them.+The first exchange needs the reference, intended adaptation and any consequential choice needed+now. Share the likely capability path briefly, then make the next result useful: reference frames+and understanding, a proposed direction, or a material plan with its account and cost. Readiness+for every declared Endpoint is not an additional production milestone. Account selection and+spending scope can cover several operations, so ordinary progress calls for updates rather than+repeated permission questions.+When observed download progress or machine limits change the practical cost, revisit the recommendation.State what is being fetched or run, how it is progressing and what would make the next attemptdifferent. [Local tools](local-tools.md#make-network-preparation-practical) covers caches, mirrors and@@ -99,6 +115,12 @@ Each authored model needs an Endpoint that supports its exact requested capabiliRuntime selection is project-local. Commands read that project's `.hypit/runtime` pointer and do notchoose a Profile from a familiar filename or from another project above it.+That pointer is a file naming the selected Profile. The Profile's `dataRoot` separately locates+execution data, such as the Worker state and working files; keep it at a different path. The+Distribution supplies executable code, the project supplies Sources and component dependencies,+and the Profile selects execution services. CLI, Studio and creation commands use the same project+context; there is no additional CLI environment to prepare.+Use `hypit paths` to see the actual project, Profile, selection source and storage locations.`--runtime <profile>` selects a Profile for that invocation; `runtime use <profile>` records theproject's default. From elsewhere, `hypit paths --workspace /path/to/project` inspects that project.@@ -178,12 +200,14 @@ per-Build worker count or extra Build-wide concurrency limit to coordinate all m| A Provider's exact-model limit, where supported | A narrower quota within its total capacity; read that Provider's accepted configuration || Endpoint `pool` | Shared resource identity for instances using the same real account, deployment or compute budget || Endpoint action limits, where supported | Concurrent `submit`, `poll` or `collect` calls and starts admitted within a time period; these are distinct from remote tasks in progress |-| HyperFrames `config.workers` | Chrome processes requested by one render; this is work size |-| HyperFrames `config.browserCapacity` | Chrome slots shared by render Needs; each reserves its actual worker count alongside one request slot |+| HyperFrames `config.workers` | A fixed Chrome count, or `"auto"` to adapt within a per-render ceiling |+| HyperFrames `config.maxWorkers` | Optional per-render ceiling for `"auto"`; otherwise the Provider derives it from CPU and memory |+| HyperFrames `config.browserCapacity` | Chrome slots shared by render Needs; each reserves its fixed count or auto ceiling alongside one request slot |For example, two local render Endpoint instances using 4 and 2 workers can share a pool withrequest capacity 2 and browser capacity 6. Both fit together. With browser capacity 4, one waits;-a single request larger than the configured browser capacity is a configuration error. These are+a fixed request larger than the configured browser capacity is a configuration error. Auto fits its+ceiling to that capacity and the requested range. These areillustrative budgets, not universal machine recommendations. Increasing workers can increase memory,decode and I/O pressure; inspect actual progress before attributing every delay to capacity contention.The selected frame range belongs to the render request, while worker policy belongs to the Endpoint.@@ -193,12 +217,12 @@ currently open Chrome processes. Omitting `browserCapacity` leaves only the requConfigure these choices in the Runtime Profile's Endpoint entries, using each Provider's documentedfields. All instances sharing a resource must agree on its limit; use different pools for genuinely-independent resources. Kie and HypiHub use the same capacity-reservation mechanism, but separate-accounts do not share a pool merely because they offer the same model.+independent resources. Separate accounts do not share a pool merely because they offer the same model.Capacity reservations coordinate Builds sharing the same Runtime Execution Store. They are not across-machine account quota service. An accepted asynchronous Operation retains its task-capacity claim-while it is pending, including between polls and across a Worker restart. Each short `submit`, `poll` or+while it is pending, including between polls. Ending the Build attempt releases its local claims while+preserving any remote receipt and last known status. Each short `submit`, `poll` or`collect` call can separately consume action concurrency and rate; the call releases its concurrency whenit ends while a rate budget continues for its declared period. If an Endpoint action fails, that Operationand Build attempt fail and their local capacity claims are released; any receipt, last remote status and@@ -206,9 +230,9 @@ error remain evidence. Disconnecting a CLI observer does not change any of thesetransient work has session-local concurrency and does not consume durable Build capacity claims.Read the installed `@hypit/runtime-local` README for the shared model and the selected-`@hypit/provider-hyperframes-local`, `@hypit/provider-kie` or `@hypit/provider-hypihub` README for-accepted settings. Use `hypit activity` to inspect actual claims. After changing a Profile, follow-[Worker reload guidance](../production/builds.md#reload-changed-execution-code-deliberately).+Provider README for+accepted settings. Use `hypit activity` to inspect actual claims. New Builds use the current Profile+and project implementation; see [Build execution scope](../production/builds.md#build-with-the-current-project-implementation).## Put secrets behind credential references@@ -278,10 +302,12 @@ package APIs. The actual service protocol determines whether an existing Provide## Prepare the selected environment-After selecting or changing a Profile, `hypit runtime up` prepares the selected adapters' machine npm-dependencies, prepares and starts their declared local Managed Programs, validates the Runtime, and-starts its Worker. It does not log into or start remote services. `hypit doctor` is the active check-for those remote Endpoints.+After choosing the services for the next work, use `hypit programs up --endpoint <instance>` to+prepare those helpers, or `hypit runtime up --endpoint <instance>` to start the Worker as well.+Repeat the flag for several instances. Omission deliberately prepares the whole Profile, even when+a capability is bound elsewhere. Preparation follows each Provider's declared dependencies and+Programs; it does not log into remote accounts. `hypit doctor --endpoint <instance>` actively checks+that selected service. `plan` already narrows readiness to the Endpoints resolved for the Run.Use `local-tools.md` when a selected local binary or Managed Program needs installation or repair.Read `../production/builds.md` for how submission uses the prepared environment and Worker.diff --git a/skills/hypit/references/playbooks/craft/captions.md b/skills/hypit/references/playbooks/craft/captions.mdindex 8a1185f6..8055821e 100644--- a/skills/hypit/references/playbooks/craft/captions.md+++ b/skills/hypit/references/playbooks/craft/captions.md@@ -139,7 +139,7 @@ pauses. Making a Cue longer changes its reading group, not its character timing.Text appearing and text changing color are separate choices. `atom-reveal: all` keeps the completeCue available to read while Karaoke supplies emphasis; `on-start` reveals whole spoken units, and-`typewriter` reveals whole graphemes within them. A pronunciation span such as `<Hypit|Hai-Pit>`+`typewriter` reveals whole graphemes within them. A pronunciation span such as `<API|A P I>`remains one shared timing unit. Scope it to the expression needing a pronunciation hint so thesurrounding Chinese characters retain their own timing.diff --git a/skills/hypit/references/playbooks/craft/generated-dependencies.md b/skills/hypit/references/playbooks/craft/generated-dependencies.mdindex 39b5f704..c5fe22f9 100644--- a/skills/hypit/references/playbooks/craft/generated-dependencies.md+++ b/skills/hypit/references/playbooks/craft/generated-dependencies.md@@ -55,6 +55,10 @@ In ordinary UGC, podcast and interview production, stable reference views supporgenerated Takes that meet at editorial cuts. Those cuts can remove dead pauses, change the object ofattention and make the performance feel like edited social video.+When the movement itself is the reference, connect a useful video excerpt alongside the target+identity or world inputs. [Motion references](video-direction.md#let-footage-carry-motion-that-matters)+explains choosing excerpts and assigning those inputs distinct responsibilities.+A truly continuous action is a different creative requirement. Direct that intended shot throughthe chosen model's suitable mode; repeated references alone do not guarantee identical poses acrossgenerated seams.diff --git a/skills/hypit/references/playbooks/craft/graphic-compositions.md b/skills/hypit/references/playbooks/craft/graphic-compositions.mdindex 8dcc2236..580c336d 100644--- a/skills/hypit/references/playbooks/craft/graphic-compositions.md+++ b/skills/hypit/references/playbooks/craft/graphic-compositions.md@@ -21,6 +21,21 @@ Motion should make a change legible: arrival, replacement, accumulation, comparicompletion. Entry is not the whole design. Decide what remains after it, how later elements join,and how the system leaves the frame. A settled board may carry more meaning than its animation.+Make the visual direction concrete before extending it across scenes. Translate a reference's vibe+into a few shared choices: palette, type, edges, depth and motion character. A small representative+passage can show those choices together with the actual footage. Carry the accepted direction into+shared Recipes or project styling so a later change reaches the related components consistently.++Let action demonstrate the claim. A rejected placement can show the object follow an attempted+drag and visibly return. Keep a developing+demonstration active while the speech explains it, with acceleration, contact and settling that+make the relationship perceptible. Preserve continuing objects across phases when the argument+continues through them.++Give graphic text its own job: identify, compare or emphasize what the picture needs beyond Caption.+When removing a redundant heading or label, recompose the remaining content and its spacing. The+former text slot need not remain an unexplained hole; the demonstration should still feel complete.+## Put the right facts in editable structureUse authored text, exact fonts, geometry and state when wording, alignment, timing, data or repeateddiff --git a/skills/hypit/references/playbooks/craft/video-direction.md b/skills/hypit/references/playbooks/craft/video-direction.mdindex 7682854e..a97d43cc 100644--- a/skills/hypit/references/playbooks/craft/video-direction.md+++ b/skills/hypit/references/playbooks/craft/video-direction.md@@ -19,14 +19,19 @@ together. Their value is the performable relationship they contain.As with [Image direction](image-direction.md#compress-the-idea-into-decisive-anchors), high-levellanguage should carry sensory direction. The model can realize "admiring but incredulous" across a-whole passage. A pointed emphasis or a revealing gesture can then settle its most consequential-expression. The prompt names the attitude; the performance makes the audience experience it.+whole passage. Words such as "lively" or "expressive" set an energy level; the speaker's particular+response to the meaning gives that energy direction. Locate the consequential thought in the Script+and make its expression concrete: what earns an accent, changes the face, or moves the body?+Voice, expression and gesture can reinforce one response, with whichever channels make it legible.+A single revealing reaction can carry the thought; specifying all channels at every phrase adds no+inherent value.For example, alongside a Script that questions a price and ends with an ironic compliment:```text-She is venting to a friend with affectionate exasperation at how overpriced this is. Give the-price an incredulous emphasis; let the final compliment land with a teasing smile in her voice.+She is venting to a friend with affectionate exasperation at how overpriced this is. At the price,+her eyebrows rise and her open palm turns upward with an incredulous vocal accent. Let the final+compliment land with a teasing smile in her voice.```The first sentence directs the entire encounter. The details make the price and the ironic turn@@ -37,12 +42,16 @@ strengthening the expression.Let the thought determine whether the attitude develops or holds: an example may win a skepticalspeaker over, while a firm argument may sustain the same conviction throughout. When adapting a-reference, recover that relationship before selecting movements or vocal details for the new work.+reference, recover what prompts the reaction and how it lands, then find the corresponding thought+in the new Script. This preserves the expressive relationship while letting the new words call for+their own movements and phrasing. Phrase-level emphasis should fit the performed language's tones+and cadence; a source-language stress pattern is not a universal performance instruction.Carry the character, voice and useful physical relationships across Takes while directing theattitude each passage calls for. The same speaker can invite, question, tease and persuade as theargument develops. Shared direction can preserve their manner; the passage supplies the particular-response. Stable framing leaves room for changes in face, voice and posture.+response. Carry forward production continuity, and reconsider the expressive intention whenever the+thought changes. Stable framing leaves room for changes in face, voice and posture.## Give restraint an expressive purpose@@ -85,6 +94,19 @@ the video should perform. Give the later Caption, icon or product card its own cthrough composition. A prop or display intended to exist within the generated scene can be describedas that actual object and connected through the relevant references.+The spoken subject and the visible action have separate responsibilities. A speaker can discuss+objects, quantities, transformations or an imaginary demonstration while the camera records only+their performance in the referenced setting. Preserve the words in Dialogue; use action to describe+the person's response to those words. A quoted phrase can locate a vocal accent or a hand beat+without asking for its meaning to appear as an object, written label or event in the shot.++Make the performer the subject of the direction. "She gives the promise a satisfied accent and a+small nod" identifies what the camera and microphone should capture. "Make the idea tangible" or+"show that it works" leaves the means of demonstration open. Complete that translation into the+intended voice, expression or physical interaction before writing the request. Read the assembled+prompt as one account of the generated scene; a general no-text instruction does not resolve an+ambiguous invitation to demonstrate the spoken content visually.+Capable video models can turn figurative wording into literal objects, events or transformations. Useconcrete visible language for intended gaze, gesture, movement, camera behavior and cuts when ametaphor would introduce the wrong scene content. Social attitude and aesthetic shorthand remain@@ -109,6 +131,7 @@ encoder.| --- | --- || Character-and-scene references | appearance, setting, framing and the physical state to preserve || Product, interface or other factual references | the visible facts that need continuity or exactness |+| Motion or camera video references | temporal behavior whose phrasing, coordination or path should guide the new shot || Recurring voice references | a speaker's intended voice identity when the model accepts them || Script dialogue | the exact words, intended pronunciation and speaking turns for a visible performance || Prompt Kit or Recipe | a reusable prompt relationship that fits this kind of work |@@ -160,6 +183,28 @@ Read the selected template's wording when choosing its Recipe. Composition, cameperformance and gesture choices shape different aspects of the footage. Choose them to support theintended delivery, and use action Text for the passage's particular meaning and reactions.+## Let footage carry motion that matters++When the defining value of a reference is its movement, let a video reference carry that evidence to+an appropriate video model. Dance phrasing, coordinated body action and a distinctive camera move+can be easier to preserve through footage than through a long verbal reconstruction. Understand what+makes the movement work, then state which motion to follow and which person, setting or appearance+to change. The reference supplies temporal behavior; the prompt and other references direct the new+visible result.++Choose a useful excerpt around the complete action and its preparation or settling. Size it using+the source passage, the target's intended duration and the selected model's actual reference-duration,+count and size limits. A long reference can yield several purposeful excerpts. Preserve continuous+action where it matters, and use natural editorial boundaries where separate requests make sense.+Connect the actual video as a reference input; an excerpt mentioned only in prose is not an input.++The same [reference relationships](generated-dependencies.md) apply: each image, video or audio carries+specific facts, and the nearest useful references guide the next request. Image references can supply+the target identity or world while video supplies movement. The selected model and Provider determine+which combination is supported. Read their installed vocabulary and exact media requirements,+including any declared person-reference metadata, before submitting. Motion reference is another+way to direct capable generation, alongside text, camera images and voice references.+## Direct camera and cuts as part of the passageFor ordinary direct-to-camera social video, prefer pause-trim jump cuts at phrase boundaries. Thisdiff --git a/skills/hypit/references/playbooks/craft/voice-direction.md b/skills/hypit/references/playbooks/craft/voice-direction.mdindex 6b04503c..5a0753e3 100644--- a/skills/hypit/references/playbooks/craft/voice-direction.md+++ b/skills/hypit/references/playbooks/craft/voice-direction.md@@ -64,6 +64,11 @@ language and delivery density the actual work needs.## Let the sample carry the character+When choosing or designing a sample, prefer the performed language and a delivery compatible with+the new piece when available. A sample carries pronunciation and phrasing cues as well as timbre;+cross-language identity transfer does not by itself establish the target accent or cadence. Preserve+a supplied identity and direct those target-language qualities explicitly in the requests.+Choose a short, natural line that gives the intended voice room to show itself. A curious questionfollowed by a pleased response can demonstrate a lively character: "Wait, you did all that with onephoto? Okay, now you've got my attention." A considered observation can suit the second casting.diff --git a/skills/hypit/references/production/browser-capture.md b/skills/hypit/references/production/browser-capture.mdindex 73d7d9dd..6689291b 100644--- a/skills/hypit/references/production/browser-capture.md+++ b/skills/hypit/references/production/browser-capture.md@@ -70,6 +70,13 @@ to express the task. `browser` is also available for opening more pages; pass onargument to `screenshot` or `record` to capture it. Returning finishes open recordings and closesthe browser. Completed captures survive a later script failure.+For a scrolling demonstration, identify the container that actually scrolls; a gallery may move+inside a fixed page. Frame the useful content at its intended viewing size and record from a useful+start state through the action. Compare separated saved frames to confirm that the intended rows or+states change. Crop and presentation can then be revised around this recording without repeating+the capture. An authored diagram or simulated interaction whose motion must follow Script events+belongs in an editable component; a recording supplies the real interface behavior being shown.+For local inputs beside the script, `new URL('../assets/card.html', import.meta.url).href` locatesthe file. Relative output paths follow the directory where the command runs. `args` contains thearguments after `--`; use `log` for progress. `--json` reports every completed helper output with itsdiff --git a/skills/hypit/references/production/builds.md b/skills/hypit/references/production/builds.mdindex d06009db..d11e2696 100644--- a/skills/hypit/references/production/builds.md+++ b/skills/hypit/references/production/builds.md@@ -35,6 +35,17 @@ reuse completed Outputs. A closed terminal or interruptedobservation is distinct from a failed Provider request inside the Build. Finishing an incompleteResult is covered below and does not require regenerating media.+For a slow or failed stage, read its retained execution evidence:++```bash+hypit logs <build-id> --lines 80+```++This reads Provider diagnostics and execution phases from active work or the finished Result.+Completed Build logs remain accessible through the Result repository without the original Runtime.+Use `hypit runtime logs` for Worker startup or process failures. Start with the relevant tail and+expand it when the cause needs earlier context; a closed terminal does not erase the Build's log.+## Continue after a failed attemptA failed Build leaves the work and evidence produced by that attempt. Prepare a new Run that selects@@ -69,6 +80,11 @@ hypit plan path/to/build.svrundemanded subgraph after applying the Run's Candidate selections and lists every external Need thatwould be sent. Planning starts no external work.+Use the default reports to follow the remaining work. `--json` changes the encoding; `--verbose`+expands the scope. A Run's Candidate count is not its count of new requests or generated assets:+Candidates may supply existing values or select another Producer. Read demanded Needs to decide+what will execute, and `pricing` to identify the subset that may incur a Provider charge.+With a selected Runtime Profile, the plan also names the Endpoint behind each request, applies thatEndpoint's request-support rules, checks cheap readiness for the demanded capabilities, and shows theProvider's declared price page or that its price source is unknown. Planning remains local and does@@ -172,8 +188,8 @@ model limits declared by those Endpoints. Builds share only those actual resourccan advance together.Immediate work releases its capacity when it returns. An asynchronous Provider operation keeps its-claim while that same accepted operation is being polled to completion. A Worker restart continues-stored Provider operations rather than submitting their paid request again.+claim while that same accepted operation is being polled to completion. Losing the execution process+ends the attempt and preserves available remote receipts; it does not resubmit the paid request.When an action fails, the attempt ends and local reservations are released. Any last-observed remotestatus remains evidence, rather than a condition the old Build must resolve before the next attempt.@@ -215,8 +231,11 @@ Check the reported state afterward. Detaching the observer does not send this cacancellation request cannot undo already completed Provider work. Preserve completed usable Outputsand leave unrelated Builds alone.-Stopping a Worker is different from cancellation. `runtime down` pauses advancement of all active-Builds in that project Runtime; their durable facts remain available for the next Worker.+`runtime down` stops the coordinator and its execution processes for that Runtime. An unfinished+Build that loses its execution context ends that attempt; starting the Worker again does not resume+it. Completed Outputs and recorded receipts remain available for explicit reuse in a new Build.+Stopping the Worker does not itself cancel remote Provider work; use `cancel` for a selected Build+while its execution context is available.## Browse and export project Results@@ -227,9 +246,12 @@ hypit history <public-output-name>hypit get <build-id> --output <public-output-name> --to <destination>```-`builds` lists finished project Results newest first. `inspect` shows one Result and its exact public-Output names. `history` finds one named Output across Results; it does not select one for the current-Run. `get` exports one named Output to one explicit destination:+`builds` lists finished project Results newest first. `inspect` shows one Result's Targets,+highlighted Outputs and outcome. Use `inspect <build-id> --output <public-output-name>` for a known+Output, or `--verbose` to browse all available names and receipts. A Result can expose many forwarded+Outputs from earlier work; this inventory does not mean those files were generated or copied again.+`history` finds one named Output across Results, including reuse; it does not select one for the+current Run. `get` exports one named Output to one explicit destination:- a Scalar becomes a JSON file;- a Resource becomes one streamed file;@@ -273,14 +295,20 @@ reference Resources in the original Result.[Project handoff](../creation/project-files.md#hand-over-an-editable-production) explains carryingthose Results and the authored work to another machine or collaborator.-## Reload changed execution code deliberately+## Build with the current project implementation++Each normal local Build receives its own loaded project implementation and selected Provider+configuration. Edit project components or the Profile, then create a new Build;+previously started work keeps its loaded implementation. Reuse completed material through the Run+when changing composition. Warm services such as WhisperX remain available across Builds.-A running Worker keeps the Runtime Profile, inherited environment, Distribution code, and package-implementations it has already loaded. Before restarting it for a changed Profile, environment-backed-credential, Distribution, or loaded project package, inspect `hypit activity` and preserve active-work. Stop an idle Worker with `hypit runtime down`; the next prepared Build can start a fresh one.+Concurrent Builds share execution infrastructure; remote waiting does not reserve a whole-Build slot.+A lost executor ends its affected attempts; completed Outputs and available remote receipts are+retained. Continue with a new Build and explicit reuse. This execution boundary does not freeze files+that a component chooses to read later.-Credentials resolved from a writable external store may be visible without a process restart, while-environment variables are inherited when the Worker process starts. Let the Credential Store and-current Provider error determine which case applies instead of treating every authentication failure-as a restart problem.+Changing the installed Distribution or the coordinator's inherited shell environment is a separate+bootstrap change. Inspect `hypit activity` before restarting that Worker. External writable credential+stores may expose updated values directly; environment-backed credentials use the environment in+which the coordinator was started. `hypit runtime down` stops the Worker and its active executors;+Managed Programs have their own lifetime.diff --git a/skills/hypit/references/production/component-design.md b/skills/hypit/references/production/component-design.mdindex 14482990..aba097a7 100644--- a/skills/hypit/references/production/component-design.md+++ b/skills/hypit/references/production/component-design.md@@ -2,7 +2,8 @@Read this when deciding how to organize a picture, a transition or a recurring visual system.Design it with the taste of a director and the care of someone who will use it in a real composition.-A useful component makes a particular idea legible and gives its author clear ways to direct it.+A useful component makes a particular idea legible and keeps its behavior understandable within the+production. Its author interface can be as small as the work requires.[Graphic composition](../playbooks/craft/graphic-compositions.md) owns visual hierarchy and motion;[Track authoring](track-authoring.md) owns the implementation. A new Caption family also draws on@@ -35,10 +36,50 @@ coordinated geometry, state and transitions together where that makes their behafunctions and subcomponents can organize this code without each becoming another Track or package.The useful division preserves the relationship through change; more layers alone do not improve it.-Consider the change the user actually wants. If the product changes, the comparison's content may-change while its explanatory behavior remains. If delivery changes, its spoken reveal should move-with the relevant Moment. If a presenter and a diagram exchange space, their shared layout should-remain coordinated. These relationships suggest the inputs and boundaries worth authoring.+## Separate responsibility, parameters and reuse++Adaptive composition introduces structure where it makes the work easier to understand and direct.+A boundary gives a responsibility an owner; a parameter expresses a choice supplied from outside+that owner; reuse preserves a relationship across uses. These decisions serve different needs.++| Decision | What justifies it |+| --- | --- |+| Independent organization | A distinct visual responsibility, lifetime or behavior benefits from its own owner. Parts sharing geometry, state or motion can stay together. |+| Parameterization | The production needs an external choice: an asset, a spoken trigger, a placement or a setting the author will actually adjust. |+| Reusable design | Actual uses share a relationship or treatment. Share that behavior and generalize only the variation those uses need. |++One-off effects can be independently organized with fixed designs. A future edit may appropriately+change their implementation. Consider likely revisions to reveal tangled responsibilities or useful+inputs, rather than treating every possible edit as a parameter to implement in advance. Even repeated+use can share the same fixed treatment. Interface breadth and reuse count do not measure component quality.++For example, a backdrop and an editor demonstration have different jobs and can be organized+separately. The editor can keep its button sizes, panel spacing, illustrative labels and pointer paths+inside its implementation. Its pointer, dragged image and target slot share geometry and belong+together. Supply the actual assets and speech-linked events through author inputs; expose Caption+placement or color when those are useful adjustments. This gives the piece clear structure without+turning the illustrated editor into configurable editing software.++Choose peer Tracks for independently composed contributions, internal parts for a coordinated scene,+and ordinary modules for code organization. These boundaries need not coincide with parameter or+package boundaries. Splitting files helps maintenance; a named Track around a whole passage gives+it occupancy. Judge both by whether they clarify the actual responsibilities. The spoken outline+supplies timing context: several passages may develop one object, and one passage may contain+several independent objects. Sharing a Moment does not by itself require a shared Track.++## Keep implementation changes local++Keep revisions local as the scene grows. Separate independently edited scene bodies, styling and+frame evaluation into ordinary source modules while sharing their actual mechanics. A palette,+typing function or media-sampling helper can be an ordinary project dependency; it needs no Surface+or Track of its own. A shared package becomes useful when several components really use it.+Source connects selected assets, semantic events and the component's external choices; these modules+own their realization, including any fixed design specific to this piece.++Derive related geometry from one layout. A pointer's destination should come from the target it+clicks; an attached badge should follow its pointer; two presentations of one playing source should+share their sampling. Then revising a layout changes its dependent motion with it. Repeatedly fixing+the same choice in several places is evidence that its ownership needs consolidating.Choose visual grouping and timing independently. A combined scene can respond to spoken Moments;separate Tracks can share an authored event. What belongs together on the canvas does not decide@@ -54,10 +95,12 @@ layout through the Timeline and shared temporal projections. Replacing a productScript then changes content and semantic anchors while preserving the behavior. The final framepositions come from the placed Takes.-Sketch its intended Source use with this video's actual content. The tag and its children should-read like a concise account of the visual idea: which subjects are compared, which answer is already-known, and which statement reveals the next one. This makes the important choices visible early and-helps reveal a missing relationship before it becomes rendering code.+The repository's [video examples](https://github.com/hypit-ai/hypit/tree/main/examples) show different+applications: a persistent ranking board, related podcast views, a shared interview encounter and+coordinated explainer scenes. Trace why a behavior has its owner, what drives its time, and which+inputs a changed brief would replace. Their notes explain those choices; the scene lists are each+production's design. In the explainer, scenes retain fixed internal details while Script events,+Caption and presenter framing remain independently authored.## Let meaning drive the behavior@@ -87,22 +130,24 @@ Moment. A shared event is enough when each contribution already has a useful ind[Track authoring](track-authoring.md#keep-selection-projection-and-consumption-distinct) explains theprojection and consumption boundary in detail.-## Expose the choices that preserve the idea+## Expose the choices the work needs-Separate the work's content from the behavior that presents it. Words, images, identities and event-references belong in Source. Related visual choices can form a Recipe. The component supplies a-coherent default treatment and the reusable layout, state and motion that make its role recognizable.+A good parameter earns its place by enabling a useful directing choice or connecting a real dependency.+Keep Script wording and semantic anchors connected to their existing owners, and supplied media+explicitly wired. Illustrative text, decorative geometry and purpose-built animation may remain local+to a one-off scene. A fixed design is complete when it serves the piece; adding controls is a separate+decision. If a label later needs repeated variation, promote that choice to an input then.-A good parameter earns its place by enabling a useful directing choice. A comparison may need labels,-images, emphasis, a Frame and a reveal relationship. Its internal coordinates can follow those choices.-Keep independently useful decisions independent, while letting one meaningful control coordinate details-that belong together. Palette, spacing and motion defaults should already form a designed whole.+For the inputs that matter, sketch their Source use before implementing them. Related authored visual+choices can form a Style or Recipe. A comparison may need labels, images and a reveal relationship;+its internal layout can derive from those few inputs. One meaningful control can coordinate many+details while preserving a designed whole. Semantic triggers remain valuable even for a scene used+once: they connect its behavior to the actual performance without exposing every animation detail.-Support the variation the work actually needs. Longer names, another product, a different number of-rows or a changed performance may be ordinary inputs; a new visual relationship may deserve another-component. Reuse becomes valuable when the next author can change the content while retaining the-idea. [Caption craft](../playbooks/craft/captions.md#caption-families-styles-and-parameters) gives-a concrete example of this distinction through family, Recipe/Style and parameters.+When reuse is needed, support the actual variation: longer names, another product or a different+number of rows. A new visual relationship may deserve another component.+[Caption craft](../playbooks/craft/captions.md#caption-families-styles-and-parameters) illustrates+family, Style and parameter choices for a commonly reused role.## Design the component in its frame@@ -110,10 +155,11 @@ Judge it beside the presenter, coverage, Caption and other graphics it will sharGive the eye a clear entry point, useful grouping and a settled state that remains readable. Thecomponent's local palette, density and motion should support the whole composition's hierarchy.-Use the supplied Frame to express placement and derive the internal layout from it. Decide how real+Use the chosen Frame to express placement and derive the internal layout from it. Decide how realtext and media occupy that space: what wraps, what crops, what scales, and what stays aligned. A useful-default can suit the present work while leaving size, position and assets authored. Let a genuinely-unsupported configuration produce an actionable explanation of the content or space that needs changing.+fixed layout can suit the present work; expose placement or size when the composition needs to direct+them externally. Let a genuinely unsupported configuration produce an actionable explanation of the+content or space that needs changing.[Spatial layout](spatial.md) owns fitting and coordinate relationships; [Fonts and text](fonts-and-text.md)owns text resources and placement.@@ -129,9 +175,12 @@ Give the component vocabulary and an example that show its purpose, required inpand the meaning of its timing. For persistent state, explain what remains after activation. A previewshould reveal the behavior that makes someone choose this component, with useful default content.-When a Studio Companion helps, expose the same meaningful entities and choices: a board's lifetime,-a row's reveal, a Caption Cue's actual Style. Editing the displayed entity should change the owning-Source fact. [Companion authoring](studio-companions.md) owns those bindings.+For a production the user will explore in Studio, make its useful objects recognizable: a board's+lifetime, a row's reveal, a Caption Cue's actual Style. Watching and understanding the work are useful+on their own; a read-only scene with a clear identity can be complete. Expose controls for the real+adjustments the user needs, such as Caption position and color, through the existing author inputs.+An empty parameter panel alone is no reason to widen the component interface.+[Companion authoring](studio-companions.md) owns those bindings.For an existing example, read the installed `@hypit/ranking` README and the part of its implementationthat answers the current question. It connects semantic reveals, settled state, layout and editordiff --git a/skills/hypit/references/production/component-visuals.md b/skills/hypit/references/production/component-visuals.mdindex eb0218b1..9c1b0814 100644--- a/skills/hypit/references/production/component-visuals.md+++ b/skills/hypit/references/production/component-visuals.md@@ -97,6 +97,18 @@ owns the local structure; CSS supplies layout, stacking, masks, filters and blen`setup(root, data)` code returns `render(localFrame)`. This function sets the complete state at thatframe. A range render may start in the middle, so compute state from the frame and authored inputs.+Prepare stable structure in `setup`: locate elements, construct geometry and retain reusable drawing+objects there. Paint static procedural textures once their resources are ready.+Let `render(localFrame)` update the state that changes with time. This supports both+fast repeated capture and direct seeking. A program is sampled within its Present's lifetime;+outside it, the renderer may retain the boundary pose. Re-entry and repeated active seeks must+produce the complete requested state, including when an image became ready since the last call.++For a depth or material effect, choose the representation that carries its visible behavior:+CSS can tilt a panel, while a deforming textured surface may warrant mesh geometry and Canvas or+WebGL drawing. Keep that implementation inside the project component; give Source the useful+material, amplitude or timing choices rather than the renderer's internal construction.+For shared opacity or a filter, put the affected content under the element that owns the treatment.A translucent panel can use backdrop filtering; its painted position and browser compositing scopedetermine which background it affects. A transition can own both participating pictures and theirdiff --git a/skills/hypit/references/production/rendering.md b/skills/hypit/references/production/rendering.mdindex 97546ac3..4b664442 100644--- a/skills/hypit/references/production/rendering.md+++ b/skills/hypit/references/production/rendering.md@@ -106,17 +106,26 @@ can bind these capabilities to different compatible Endpoints.For the local HyperFrames Provider, `workers` selects independent Chrome processes within one render.They share the staged document and decoded source frames, capture different parts of the selected-interval, and produce one encoded result. `defaultConcurrency` limits simultaneous render Needs;-optional `browserCapacity` budgets their combined worker counts. These belong to the Runtime+interval, and produce one encoded result. Prefer `workers: "auto"` for ordinary local rendering;+the Provider adjusts capture concurrency within its reserved ceiling using the current job's work.+An explicit worker count preserves that deployment choice. `defaultConcurrency` limits simultaneous render Needs;+optional `browserCapacity` budgets their combined browser reservations. These belong to the Runtimeconfiguration; the Source keeps the same render declaration. [Runtime profiles](../environment/profile.md)explains shared capacity and inspecting the selected Provider's configuration. The local HyperFrames-Provider supports range requests; the AWS Lambda Provider currently accepts whole documents only.+Provider supports range requests. A project Provider declares the request forms its deployment supports.A short interval reduces frame capture and source-frame extraction, but still prepares the document's-declared assets and validates typed Surfaces. More workers accelerate capture, with preparation and-final encoding contributing separately. Reusing media through the Run avoids generation work; it does+declared assets and validates typed Surfaces. Extra browsers help only while the machine can use them;+preparation and final encoding contribute separately. Reusing media through the Run avoids generation work; it doesnot preserve a previous render's temporary preparation.+For a local composition change, render the interval that shows the changed relationship and its+handoffs. Keep accepted material selected in the Run, then render the complete deliverable when+the composition is ready. Frame ranges reduce repeated work without changing the authored clock.+While rendering, communicate the current phase and meaningful progress. The Provider reports+decoding, browser startup, capture, encoding and storage; `hypit logs <build-id>` preserves their+timings and execution details when a slow or failed stage needs investigation.+A local render timeout ends that execution attempt and releases capacity after its work has stopped.Its failure and already completed Outputs belong to the Build Result. Continue through a new Runand Build that explicitly reuse the available media, as described in [Runs](runs.md).diff --git a/skills/hypit/references/production/review.md b/skills/hypit/references/production/review.mdindex 14097436..fbb26b76 100644--- a/skills/hypit/references/production/review.md+++ b/skills/hypit/references/production/review.md@@ -4,7 +4,13 @@ Read this when opening Studio, judging an encoded Result, or improving the layouexpression of the new Film.[Studio](studio.md) explains launch, session reuse, displayed information, Source writeback and-project Companions. [Builds and Results](builds.md) explains retrieval and explicit Output reuse.+project Companions. [Timestamped Comments](studio.md#revise-from-timestamped-comments) connects user+feedback to the owning production facts. [Builds and Results](builds.md) explains retrieval and explicit Output reuse.++For a collaborative review, [show the editable work before export](studio.md#review-before-export)+and introduce both views: Comments for time-located direction, Studio for the timeline and exposed+parameters. Browser playback makes both available without first encoding a complete video. When a final file is requested,+render and inspect that encoded deliverable as a separate step.## Make the composition workdiff --git a/skills/hypit/references/production/studio-companions.md b/skills/hypit/references/production/studio-companions.mdindex 06c40b4e..4d563477 100644--- a/skills/hypit/references/production/studio-companions.md+++ b/skills/hypit/references/production/studio-companions.md@@ -8,6 +8,9 @@ The Companion describes two things: **what an author can recognize and select**,authored fact an edit changes**. Keep the same concepts across the picture, timeline and Inspector.A reveal can be one entity even when its graphic moves and later remains on a board. A coordinatedpresenter-and-diagram scene can stay one entity when its layout is intended to be edited together.+Recognition and editing are separate capabilities. A production may use Studio mainly to watch and+show its arrangement, with a few useful adjustments. Clear labels, timing and selected read-only+facts can fully serve a one-off scene; useful Caption controls can coexist with that fixed scene.## Choose useful entities and lanes@@ -16,6 +19,17 @@ AudioTrack entities are enough for simple occupancy. Use `project(context)` whendomain meaning that the terminal drawing no longer contains. A Surface preview supplies a usefulstatic recognition image; live entities and editable bindings come from the Companion.+Generic presentation recognizes the terminal Type, not the component's creative role. A custom+Caption Track can therefore render correct subtitles yet appear as a generic blue visual lane with+opaque ids when its package has no matching Companion. Inspect the selected Companion and its+Module/Surface match before treating this as misplaced content or moving visuals between Tracks.+The package declares its role; Studio does not infer one from a tag name or the text in a picture.++When adapting an existing family, carry forward its editor meaning wherever the public content,+schedule and author identities still agree. Reuse its Companion with the actual Module/Surface+identity, or adapt its projection for the changed behavior. Preserve useful Cue/Use or item/event+relationships along with rendering. A rendering wrapper alone does not activate that integration.+For example, a board can expose its outer lifetime and its individual reveal events. Publish thedeterministic schedule/program needed to describe these from the same Surface, then request itsexact output port through `requiredValues`. `requiredSurfaceValue(context, "schedule")` reads that@@ -65,8 +79,8 @@ the Companion carries their actual ids into `renderIds`. Studio uses the visiblecurrent frame. This preserves selection after an icon lands without duplicating animation geometryin the Companion. A preset with no separately exposed child remains part of the parent entity.-Picture selection and timeline selection identify the same authored object. Position and size can-then be adjusted through its declared Inspector fields.+Picture selection and timeline selection identify the same authored object. If position and size+are exposed choices, its declared Inspector fields can adjust them.## Expose decisions, not implementation debris@@ -74,6 +88,13 @@ Declare `bindings` for the actual author endpoints, then choose visible `inspectbinding can follow a shared authored Frame or Style through `referenced`, or an SVS Recipe through`recipe`. Use `parameterReferences` for an entity's actual reference, when a derived entity points to a different authored object. Shared values retain their shared effect when edited.+A Companion is a view of the author model, not a reason to expand it. When an Inspector adjustment+is actually needed, bind it to a real Source input or domain event. A label inside a one-off renderer+can remain an implementation detail until external control has a purpose. Useful child entities can+live inside the same Track, and selection can be read-only. The+[component boundary](component-design.md#separate-responsibility-parameters-and-reuse) determines+what is independently organized; it does not prescribe how many controls to provide.+Where describes placement and layout. When describes timing, playback and motion. How describesappearance, content and sound. Each Companion chooses useful pages and sections within them.diff --git a/skills/hypit/references/production/studio.md b/skills/hypit/references/production/studio.mdindex 5fb18f42..db06cb7c 100644--- a/skills/hypit/references/production/studio.md+++ b/skills/hypit/references/production/studio.md@@ -19,7 +19,9 @@ composition and time. The Timeline supplies the clock and any placed Script anchlanes, including a pure animation with no Takes. An image-generation-only Run is not a Film view; several distinctFilms need separate Runs or sessions.-Open the URL actually printed by the process and retain it with the Run it serves. The default+Open the URL actually printed by the process and retain it with the Run it serves. For review, open+that URL with `#comments` appended, such as `http://localhost:5179/#comments`; this selects the+Comments view directly. The printed port is authoritative. The defaultrequested port is 5179; `--port` selects another, and an occupied port can cause Vite to choose adifferent one. Reuse an existing session when it serves the intended project and Run.@@ -34,6 +36,80 @@ Runtime or Result repository requires restarting that Studio session: those implselections are loaded at startup. A browser refresh alone does not reload the server-side modules.Stop only the relevant Studio process; stopping Studio does not cancel a submitted Build.+## Discuss the work while composing++When the user is collaborating locally, open the actual composition once a meaningful passage is+available and keep its Studio URL connected to the current Run. Point to the passage, object or+transition being discussed so the user can give concrete direction. Continue through settled choices;+showing progress need not become an approval stop. Use the prepared production media and explain+which passages are already composed. A rendered frame or clip remains useful when it answers the+current question more directly.++Check that the objects being discussed are recognizable and that their useful author choices are+available. A successful preview establishes that the picture renders; the component's Companion+establishes what the user can select and revise. [Companion authoring](studio-companions.md) explains+this view of the same Source, including generic fallback and project-defined families.++## Revise from timestamped Comments++Open Comments directly when the user wants to point at a moment and describe a change.+It gives the same composition a larger player and a comment column. A change of visual style,+choreography or graphic structure often needs authored code or direction, while a position or color+may fit an Inspector field. Both are ordinary collaboration: Comments carries the desired result,+and the Agent chooses the owning Source, Recipe, component or material decision to change.++Comments live in `FEEDBACK.json` at the project workspace root. Read the entries for the reviewed Run+and the open notes before revising. Each entry has a stable `id`, workspace-relative `run`, `at` in+seconds, `text`, and optional `resolved` (false when omitted). For example:++```json+{"comments":[{"id":"opening-title","run":"runs/render.svrun","at":1.5,+"text":"Give the title a softer pink and a stronger offset shadow.","resolved":false}]}+```++The UI displays notes in time order; its `#` labels follow submission order within that Run. Identify+file edits by `id` and preserve the array order and unrelated entries. Clicking a note seeks to its+saved time. Interpret that time with its words and the reviewed composition: changing Script or Take+placement can move the intended event. Comments retain the reviewed seconds rather than silently+following new semantic timing.++Explain the changes you will make, apply them to their owning facts, and inspect the affected passage+and handoffs. Mark the addressed notes `resolved: true`; a note can be reopened with false. Both the+user and Agent can edit this file, and Studio observes saved changes. Read the current file before+writing so newly added comments survive. Retain useful directing decisions in Treatment or Progress;+comments remain the concrete review conversation.++Send saves a comment. Agent notification is not connected yet; when the user asks for another review+pass, read the latest file. [Composition review](review.md) explains the judgment, and+[project files](../creation/project-files.md) owns the production's durable memory.++## Review before export++When the composition is substantially ready and the user can access it, open the current Run at+`#comments` for discussion and introduce Comments and Studio together. Comments lets the user+pause and leave direction at a time; Studio shows the timeline, component relationships and exposed+parameters they can adjust. Both views stay with the same work and playhead. Browser playback does not render an MP4,+create an export Build or save frame sequences. It can therefore show real material and animation+while avoiding a full encode for changes the user is still choosing. Use Studio's other view for+Inspector or timeline edits, and an encoded frame or clip when that evidence is needed.++Introduce the review in the user's language: explain what is ready, invite timestamped comments,+and say whether export is waiting for their review or already covered by their request. For example:+“I've opened the editable video. You can pause and leave timestamped notes in Comments, or switch+to Studio to explore the timeline and adjust available parameters. When you're happy with it,+I can export the video.” This is a collaboration choice, not a mandatory+approval stage. A user who has asked for final export has already chosen that step.++A first-time reviewer may benefit from one short welcome note at the relevant time, saved with+`resolved: true`. Write it explicitly as the Agent's invitation, such as “You can pause here and+leave a note about anything you'd like changed.” It demonstrates the file workflow without adding+an unfinished production task or pretending that the user requested a change. Keep this optional+and specific to the collaboration; existing comments need no repeated welcome.++Once export is wanted, reuse the accepted material in a Build, retrieve its completed video and+check that encoded deliverable. [Rendering](rendering.md) and [Builds](builds.md) own that execution.+Comments is a review view of the editable work; the exported file is the deliverable.+## Show the finished workAlongside the delivered video, a brief look at its editable production can make the handoff morediff --git a/skills/hypit/references/production/system.md b/skills/hypit/references/production/system.mdindex 57ba12b2..65d15636 100644--- a/skills/hypit/references/production/system.md+++ b/skills/hypit/references/production/system.md@@ -112,9 +112,9 @@ A component gives an authored relationship its behavior. A ranking board can conSelection to animate an entry; a reveal, flash and sound can share one Moment. Each interprets theevent according to its role. The board may keep the revealed answer visible after the entrance ends.-Placement and appearance have their own inputs: a Frame says where the board belongs, a Style says-how it looks, and supplied text or images say what it contains. This lets one behavior serve several-productions while each production chooses its content and art direction.+Where placement, appearance or content need external direction, a component can accept a Frame,+Style, text or images for those choices. This lets one behavior serve different uses. A one-off scene+can instead keep its specific design local while receiving the media and semantic events it needs.Visual and audio components publish Tracks. A visual Track groups named appearances; each appearanceowns its lifetime, paint order and internal element tree. A moving video and its diagram can formdiff --git a/skills/hypit/references/production/track-authoring.md b/skills/hypit/references/production/track-authoring.mdindex 27f51ba1..b62fbc1e 100644--- a/skills/hypit/references/production/track-authoring.md+++ b/skills/hypit/references/production/track-authoring.md@@ -127,9 +127,11 @@ wires those projections, the shared Timeline/Canvas and authored values into theProducers. The Producer consumes the resulting time and geometry and owns the visual/state behavior;Studio consumes that published meaning for presentation and editing.-Keep actual text, icons, images, colors and event references in Source or Recipe. The package owns-its reusable persistent-state behavior, motion and visual structure. A new Caption family consumes-the common Caption document and timing.+Wire supplied media, Script content and event references through Source. Expose other content or+treatment in Source or Recipe where the work needs those choices. A one-off component can own fixed+illustrative labels, dimensions and animation alongside its state and visual structure; its boundary+does not require every detail to become a parameter. [Component design](component-design.md#separate-responsibility-parameters-and-reuse)+explains that distinction. A new Caption family consumes the common Caption document and timing.## Connect the implementation at its real boundariesdiff --git a/skills/hypit/references/production/vocabulary.md b/skills/hypit/references/production/vocabulary.mdindex 24aa91bb..7f96fc4d 100644--- a/skills/hypit/references/production/vocabulary.md+++ b/skills/hypit/references/production/vocabulary.md@@ -12,7 +12,7 @@ Name what the element must do in the work before choosing its implementation. Us- What does it consume and publish?- Does it follow a Script Selection, a Moment, an explicit time span, or another component state?- What changes over time, and what stays visually persistent?-- Which content belongs to this production, and which behavior should be reusable?+- Which choices need author inputs, and which design can stay specific to this piece?Query the likely package owners:@@ -40,6 +40,16 @@ Run Fragment libraries have a separate interface. A package can provideCandidates while declaring no Markup Surfaces. Read [Runs](runs.md) and the library'spackage-local Fragment documentation for those inputs and exports.+## Connect model references as typed inputs++Read the model Surface's reference roles and per-input metadata as well as its prompt parameters.+The prompt gives direction; the actual edges supply media and the declared facts needed to use it.+For example, Seedance's `person-reference="true"` identifies a supplied image/video containing a+person or generated human likeness; false describes a reference without it, and audio has no such+visual field. Its installed README owns the exact Reference and frame-mode forms. The+[Provider](../environment/model-and-provider.md) translates these facts into the selected service's+media preparation without adding service instructions to the creative prompt.+## Choose a component for its behaviorAn installed Surface fits when its semantic role, inputs and outputs, temporal behavior, composition@@ -62,9 +72,10 @@ component. Author the behavior in the video's project package and select it throKeep the boundary useful:-- the package owns reusable mechanics, rendering behavior, input shapes, defaults and the vocabulary- that explains them;-- Source and Recipe own this video's words, people, assets, timing, and chosen configuration;+- the package owns rendering behavior, fixed design, input shapes, defaults and the vocabulary that+ explains them, whether used once or reused;+- Source and Recipe connect supplied content, assets and semantic timing, and own the choices exposed+ by the component;- Runtime Profiles own external execution and credentials;- Provider packages implement media tools and external services.