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
feat(production): inspect frames and prepare retained performances
kashorina6f84f556463
diff --git a/docs/guide/studio-companion-architecture.md b/docs/guide/studio-companion-architecture.mdindex a6bed47b..cf36bc19 100644--- a/docs/guide/studio-companion-architecture.md+++ b/docs/guide/studio-companion-architecture.md@@ -42,5 +42,5 @@ uses, so the property represents that shared decision. Studio applies the edit tSource, recompiles the same Run, and reports an error with the previous files restored if the editcannot be published.-[Studio Temporal Lineage](./studio-temporal-windows.md) explains how these relationships retain their+[Timing edits in Studio](./studio-temporal-windows.md) explains how these relationships retain theirauthor meaning through projection. [Studio](../quickstart/preview.md) introduces the editing interface.diff --git a/docs/guide/studio-temporal-windows.md b/docs/guide/studio-temporal-windows.mdindex b4cba959..e11a1d92 100644--- a/docs/guide/studio-temporal-windows.md+++ b/docs/guide/studio-temporal-windows.md@@ -1,98 +1,69 @@----title: Studio Temporal Lineage-description: How author choice becomes an Instant or Window and returns to its real source.+title: Timing edits in Studio+description: Choose what follows speech, what uses the clock, and what a timing edit changes.----Time has three layers:--```text-author choice (Selection / Segment / Moment / program time)- -> projection (TemporalInstant / TemporalWindow)- -> domain consumption (Program / Schedule / Track)-```--Script's semantic ruler contains `2M + 2N + 2` author points: Token and Segment boundaries plus-distinct Program start/end anchors. Program anchors resolve at frame `0` and `frameCount` in the-Timeline; they are author points and therefore never have to be forged inside a SemanticTake.-Their Script order need not match physical time when Takes overlap or are reordered.-This does not make `during="program"` writable: that projection remains structurally fixed.--`@hypit/temporal-markup` owns the SVML author forms and lowers them before a domain component runs.-The compiler only composes records, components and fragments; it does not recognize `during`, `at`-or any time grammar. One Timeline supplies the complete range and any placed semantic evidence.-Domain components receive that same Timeline and projected time values, remaining independent from-both semantic lookup and Studio.--## Runtime values--A `TemporalInstant` contains the runtime source used to evaluate it, the exact point expression and-resolved frame, and one author authority: `semantic`, `parameter` or `fixed`.--The identity chain is author-visible rather than synthesized by Studio:--- `<script id="story">` becomes `Narrative.id = story`; every Selection, Moment, Segment excerpt- and CaptionDocument from that Script carries `narrativeId = story`;-- every terminal Track's `programSpaceId` names the selected Timeline. `ProgramSpace` is the shared- clock/range shape contained in Timeline, not a second author-declared time axis;-- every projected Instant carries the space identity; semantic sources also carry the Narrative- identity. Each includes the consumer's public domain identity (normally its SVML `id`) as `subjectId`.--The projection record `id` may be qualified to stay unique inside an expanded graph; it is not the-author identity. `subjectId` is kept separate and remains the exact board, card, item or sequence-identity published by the component's public Program.--These values are ordinary runtime provenance, not random hashes or Studio metadata. They let a-consumer and its inverse reject a same-named Selection from another Script or a Track projected on-another timeline. A Script id therefore names one Narrative across the active Source closure.-The Script Surface declares that identity, and compilation rejects duplicates before Studio needs-to choose a source.--A `TemporalWindow` contains two complete Instants and a non-empty half-open span. Its endpoints may-have different sources and different authorities, so a Window never pretends to have one source.-ProgramSpace boundaries are legal Instants; `program.end` is not disguised as a one-frame Window.-Out-of-range Instants and reversed or empty Windows are rejected, not clipped or repaired.--## Author forms--| Form | Start authority | End authority | Timeline writeback |-|---|---|---|---|-| `during={Selection}` | semantic Selection start | semantic Selection end | Script markers |-| `during={Segment}` / `during="program"` | fixed | fixed | read-only |-| `at={Moment} for="…"` | semantic Moment cue | parameter `for` | Script and/or SVML atomically |-| `until={Moment} for="…"` | parameter `for` | semantic Moment cue | Script and/or SVML atomically |-| `at="2s" for="…"` | parameter `at` | parameter `for` | SVML timing attributes |-| `start="…" end="…"` | parameter `start` | parameter `end` | SVML timing attributes |--A point consumer uses `at={Moment}` (or a chosen Selection boundary) for semantic authority, or-`at="2s"` for authored time. `instant="…"` accepts a projected expression. Text such as `at="moment.cue+3f"` is rejected because it hides-whether the author intended to move the Moment or the offset.--## Studio inverse--Studio indexes the actual executed `TemporalInstant` and `TemporalWindow` records plus their direct-consumer edges. Endpoint authority, not a component name or Companion declaration, determines the-inverse:--- semantic authority writes the shared Script identity;-- parameter authority names the author input selected by the runtime record;-- fixed authority disables a gesture that would change it.--For `at/for` and `until/for`, one gesture may touch both layers. For example, trimming the start of-an `at/for` Window moves the Moment and changes `for` so the end stays fixed. Studio applies both-source ranges as one revisioned transaction, recompiles, and rolls both back on failure.--Companion packages still decide how an entity looks and which Inspector fields are visible. They do-not declare common timeline inverse functions. A new component becomes time-editable by consuming-the same public Instant/Window protocol and carrying its executed lineage to its Studio entity.--Film and Script interpretation also remain outside Studio core. `film-studio` declares which Film-reference supplies the time axis and which child references are terminal Tracks; `script-studio` owns-Script source observation and marker relocation. Studio selects the Script source map whose-`narrativeId` exactly matches the active Timeline and delegates the edit back to that companion.-A zero-Take Timeline supplies the same physical time range without requiring a Script lane.--The binding name is not used as a global address. Markup retains the exact author element and input-range while decoding, Elaborator hygienizes that endpoint with its Source unit, and the compiled-`AuthorProvenance` joins the executed authority to one author endpoint. Studio therefore never-chooses the first same-named `start`, output or local id across imported Sources. The provenance is-recomputed with the compilation and is not persisted as metadata, a lock or an index file.+A timing expression records an authoring decision. An explanation can follow a spoken phrase;+a flash can follow its answer; an independently paced animation can use the film clock. Studio+edits the decision expressed by that form.++[Script](../quickstart/script.md) gives phrases and events their Selection and Moment identities.+The Timeline places the prepared performances; components use those identities or clock positions+to receive an Instant or Window. A silent animation uses the same Timeline with an authored extent.++## Choose the relationship to edit++| Author form | Moving it changes | Trimming it changes |+| --- | --- | --- |+| `during={story.selection.proof}` | Both shared Script anchors by the same number of semantic stops; duration may change | The chosen Selection boundary |+| `at={story.moment.reveal}` for an event | The shared Moment anchor | No duration is declared |+| `at={story.selection.proof} boundary="start"` for an event | Only the Selection's start anchor | No duration is declared |+| `at={story.moment.reveal} for="8f"` | The Moment; duration stays eight frames | The trailing duration; the Moment stays fixed |+| `until={story.moment.reveal} for="8f"` | The Moment; duration stays eight frames | The leading duration; the Moment stays fixed |+| `at="2s" for="8f"` | The authored clock position | The trailing duration |+| `instant="moment.cue + 2f" moment={story.moment.reveal}` | The local offset; the Moment stays fixed | No duration is declared |+| `start="…" end="…"` | Both endpoint expressions by the same frame delta | Only the chosen endpoint expression |+| `during={story.segment.opening}` or `during="program"` | Follows the structural span; no timeline drag | No timeline trim |++The consuming Surface decides whether it needs an Instant or a Window and which forms it exposes.+For an event bound to a Selection's end, use `boundary="end"` with the same boundary-only behavior.++## Keep shared meaning and local offsets distinct++Moving `at={story.moment.reveal}` relocates the Moment in Script. Every consumer of that Moment+then follows the changed relationship. Moving `instant="moment.cue"` with the same bound Moment+instead changes a local offset, initially zero. It leaves the shared Script event in place.++Use `instant="moment.cue + 2f"` with `moment={story.moment.reveal}` for a deliberate lead or lag.+Arithmetic does not go inside a graph reference such as `{story.moment.reveal}`.++An event and its duration are independent choices. `at/for` offers a duration handle on the trailing+edge; `until/for` offers it on the leading edge. There is no opposite trim handle that secretly moves+a shared event and compensates by changing its duration.++## Preserve the chosen words and boundaries++Word starts, word ends and structural boundaries are distinct semantic anchors. A pause can belong+to the preceding or following phrase. Dragging uses semantic stops at distinct frame positions;+where supported, the Inspector lets you choose the exact anchor when several share one frame.+Script order and physical time can differ when Takes overlap or are reordered.++Marker edits preserve unrelated prose, spaces, punctuation, pronunciation and word attributes.+Caption Cues keep their Script-derived content and measured word times. Change their wording or+Cue boundaries in Script, and their appearance through the Caption Style and timed Uses.++Unedited expressions retain their units: `2s` keeps its duration across frame rates, while `60f`+keeps its frame count. A clock position or offset changed by a drag is written in whole frames+at the current frame rate.++## Editing a project component++A component's Companion connects its entities to their actual authored inputs and projected time.+The time form determines the edit target; the component name or a coincident frame does not.+Source observation and marker relocation belong to the Script Companion. Adding a new component+therefore does not require teaching Studio another interpretation of Script.++[Studio](../quickstart/preview.md) explains the editing interface. The+[Companion guide](./studio-companion-architecture.md) explains exposing entities and controls;+the package-owned [temporal editing reference](https://github.com/hypit-ai/hypit/blob/main/packages/temporal-markup/EDITING.md)+contains the exact implementation interfaces and supported operations.diff --git a/docs/quickstart/composition.md b/docs/quickstart/composition.mdindex 1a2a383f..d4f29fef 100644--- a/docs/quickstart/composition.md+++ b/docs/quickstart/composition.md@@ -162,7 +162,7 @@ illustration. The complete runnable project is `examples/podcast/`; the commands<!-- 1. Script: the semantic truth --><script id="story">- <opening><HOST>Meaning @{demo} becomes the source @{/demo}.</opening>+ <opening><HOST>Meaning @{demo}becomes the source.@{/demo}</opening></script><!-- 2. Generation: Seedance talking head + standalone video -->diff --git a/docs/quickstart/preview.md b/docs/quickstart/preview.mdindex 11a6d283..03356490 100644--- a/docs/quickstart/preview.md+++ b/docs/quickstart/preview.md@@ -93,7 +93,7 @@ The exported video's audio is assembled by the render's media pipeline. When theready for delivery, run its export Build to create the encoded video. Studio and Comments remainavailable to explore the editable work and discuss further changes.-For component authors, [Studio Temporal Lineage](../guide/studio-temporal-windows.md) explains semantic+For component authors, [Timing edits in Studio](../guide/studio-temporal-windows.md) explains semanticediting, and the [Companion SDK](https://github.com/hypit-ai/hypit/blob/main/packages/studio-adapter/README.md)explains how to expose component entities and controls.diff --git a/docs/quickstart/run.md b/docs/quickstart/run.mdindex 8aeee3d9..39ffa9a1 100644--- a/docs/quickstart/run.md+++ b/docs/quickstart/run.md@@ -303,10 +303,12 @@ Keep credentials, generated media, Runtime data and logs out of commits.### 0. Prepare dependencies on demand-Users do not run `pnpm install`. `runtime up` reads the selected Runtime Profile, installs the-upstream npm packages its Adapters declare into a machine-shared directory, and prepares external-programs. [`uv`](https://docs.astral.sh/uv/) is only needed first when the Profile selects local-Python programs such as WhisperX or OpenCV.+Using the published Hypit executable does not require installing this repository with `pnpm`.+`runtime up` reads the selected Runtime Profile, installs the upstream npm packages its Adapters+declare into a machine-shared directory, and prepares external programs. Project-owned components+and Providers remain ordinary project dependencies, installed with that project's package manager.+[`uv`](https://docs.astral.sh/uv/) is only needed first when the Profile selects local Python+programs such as WhisperX or OpenCV.When an author package such as Fontsource is missing, `check`/`plan` report the precise command, forexample:diff --git a/docs/quickstart/script.md b/docs/quickstart/script.mdindex 7e723ffa..81fef56f 100644--- a/docs/quickstart/script.md+++ b/docs/quickstart/script.md@@ -46,7 +46,7 @@ a Script.- A Segment can be self-closing (`<pause/>`). An empty Segment has structure but no speech tokens; itdoes not imply silence or any default duration.- Segments cannot nest — every Segment is a top-level child of `<script>`.-- Segment names follow XML naming rules: letters, digits, hyphens, underscores.+- Segment names match `[a-z][a-z0-9_-]{0,63}`; `script` is reserved.Other components reference individual Segments via `{story.segment.opening}` and their textprojections via `{story.segment.opening.dialogue}` or `{story.segment.opening.speech}`.@@ -123,7 +123,8 @@ in other languages too, such as `<Git Hub|>`.Here the left side also supplies speech, so markers can be written and moved there:`<组@{beat!}件化|>`. Markers and display attributes never become spoken text. An explicit spoken side-still owns its own markers. Both sides empty is invalid.+still owns its own markers. The explicit or shared speech must contain a spoken word; a form such+as `<API|...>` supplies no timed correspondence and is invalid.`||` is the **Caption Cue Break** syntax. It records a boundary between complete Alignment Units;it cannot appear inside Dual Text or split an N:M unit. Cue timing is still obtained later by@@ -150,8 +151,8 @@ timing meaning:```An entry without `=` has the value `true`; scalar values may be written as `name=value`. Caption-maps attribute names to local word Styles, while a Selection still supplies the surrounding Unit-Style. Attributes cannot split or wrap a Dual Alignment Unit.+families interpret these attributes as roles for displayed words. Timed Uses select the surrounding+Caption Style; attributes do not split, wrap or retime a Dual Alignment Unit.### CaptionDocument vocabulary@@ -216,7 +217,7 @@ Selections are not required to nest like XML tags. They can cross each other:```svml<demo>- <HOST> @{a} One @{b} two @{/a} three @{/b}.+ <HOST> @{a}One @{b}two@{/a} three.@{/b}</demo>```@@ -289,7 +290,7 @@ A complete Script using all constructs together:</meeting><evidence>- <HOST> That gave me @{emphasis} the courage I was missing @{/emphasis}.+ <HOST> That gave me @{emphasis}the courage I was missing.@{/emphasis}</evidence><payoff>diff --git a/docs/zh/guide/studio-companion-architecture.md b/docs/zh/guide/studio-companion-architecture.mdindex 49250a62..70151141 100644--- a/docs/zh/guide/studio-companion-architecture.md+++ b/docs/zh/guide/studio-companion-architecture.md@@ -23,4 +23,4 @@ Track Companion 匹配组件的终端 Type 与作者 Surface,使用组件公Inspector 字段绑定到实际修改的作者值。共享 Recipe 或 Frame 可能影响多个使用位置,因此字段代表的是这项共享决定。Studio 将修改写到对应 Source,以同一份 Run 重新编译;修改无法发布时,显示错误并恢复之前的文件。-[Studio 时间谱系](./studio-temporal-windows.md) 介绍这些关系如何在投影后保留作者含义,[Studio](../quickstart/preview.md) 介绍编辑界面。+[Studio 中的时间编辑](./studio-temporal-windows.md) 介绍这些关系如何在投影后保留作者含义,[Studio](../quickstart/preview.md) 介绍编辑界面。diff --git a/docs/zh/guide/studio-temporal-windows.md b/docs/zh/guide/studio-temporal-windows.mdindex def5613e..3e348ceb 100644--- a/docs/zh/guide/studio-temporal-windows.md+++ b/docs/zh/guide/studio-temporal-windows.md@@ -1,106 +1,61 @@----title: Studio 时间谱系-description: 作者选择如何成为 Instant 或 Window,并准确回到真正的作者源。+title: Studio 中的时间编辑+description: 区分跟随语义、使用时钟,以及时间编辑实际改变的对象。----时间只有三层:--```text-选择层(Selection / Segment / Moment / 编排时间)- -> 投影层(TemporalInstant / TemporalWindow)- -> 消费层(Programme / Schedule / Track)-```--Script 的语义标尺包含 `2M + 2N + 2` 个点:Token 与 Segment 的首尾,再加彼此-独立的 Program start/end。Program 锚点由 Timeline 在 `0` 和 `frameCount` 解析,不需要-伪造进某个 SemanticTake。Take 交叠或重排时,Script 顺序不一定等于实际时间顺序。它们是 Selection/Moment 可选择的作者语义点;这不会让-`during="program"` 变成可写,后者依然是结构固定的投影。--`@hypit/temporal-markup` 统一拥有 SVML 时间语法,并在领域组件运行前把它降低成普通的投影-组件和运行图边。编译器只会组合 Record、Component 和 Fragment,不认识 `during`、`at`,-各 Track 也不再各写一套找帧算法。同一个 Timeline 提供全篇范围和其中已有的语义证据,-领域组件接收同一个 Timeline 与时间投影结果,-与选择层和 Studio 都解耦。--## 运行时对象--`TemporalInstant` 保存运行时求值来源、精确点表达式、解析后的帧,以及一个作者 authority:--- `semantic`:作者权威在 Selection 或 Moment;-- `parameter`:作者权威在组件表面的某个作者时间参数;-- `fixed`:Program 或 Segment 结构决定,不开放轻量反写。--身份链全部来自作者声明,不由 Studio 临时生成:--- `<script id="story">` 产生 `Narrative.id = story`,它派生出的 Selection、Moment、Segment- excerpt 与 CaptionDocument 全部携带 `narrativeId = story`;-- 所有终端 Track 的 `programSpaceId` 指向 Film 选定的 Timeline。`ProgramSpace` 是 Timeline- 内含的公共时钟与范围结构,不是另一种需要单独声明的时间线;-- 每个 Instant 保留 Space 身份,来自语义的来源额外保留 Narrative 身份;消费者的公开领域- 身份(通常就是 SVML `id`)作为 `subjectId`。--投影 record 的 `id` 可以为了展开后的图内唯一性带父级前缀,但它不是作者身份;`subjectId`-独立保留组件公共 Program 发布的 board、card、item 或 sequence 身份,Companion 只沿这一-身份接回实体。--这些是公开运行 provenance,不是随机哈希,也不是 Studio metadata。于是同名 Selection 来自-另一份 Script、或 Track 属于另一条时间轴时,会在边界处明确拒绝,不再靠“当前第一个”碰运气。-因此 Script id 在当前 Source closure 中必须唯一;两份不同 Script 声明同一个 id 时,Studio-不会等到逆写时再挑一份。Script Surface 把 `Narrative TypeRef + id` 声明为领域公开身份,-Elaborator 在整个 Source closure 编译期通用去重。编译器不认识 Script 或 Narrative,也不禁止-不同领域、不同父对象中的同名子项。--`TemporalWindow` 由两个完整 Instant 组合而成。两个端点可以有不同来源、不同 authority,-所以 Window 不再伪造一个“共同 source”。`program.end` 是合法 Instant,不再伪装成一帧窗口。-越出 ProgramSpace 的 Instant、反向窗口和零宽窗口直接拒绝,不裁切、不修复。--## 作者模式--| 写法 | 起点 authority | 终点 authority | 时间线写回 |-|---|---|---|---|-| `during={Selection}` | Selection start | Selection end | Script markers |-| `during={Segment}` / `during="program"` | fixed | fixed | 只读 |-| `at={Moment} for="…"` | Moment cue | parameter `for` | Script 与 SVML 可原子组合写回 |-| `until={Moment} for="…"` | parameter `for` | Moment cue | Script 与 SVML 可原子组合写回 |-| `start="…" end="…"` | `start` | `end` | 组件表面的 SVML 时间参数 |--点消费用 `at={Moment}` 或 Selection 的明确边界表达语义 authority;没有语义意图时用-`instant="…"` 兜底。`at="moment.cue+3f"` 会被拒绝,因为这种写法没有说清作者想移动-Moment 还是偏移量。--## Studio 如何反写--Studio 从本次 Run 的实际执行闭包读取 `TemporalInstant` / `TemporalWindow` 记录和直接消费边,-再逐端点读取 authority:--- `semantic` 写回共享 Script 身份;-- `parameter` 点名作者输入,再由编译来源定位它的精确 Source 端点;-- `fixed` 禁止会改变该端点的手势。--因此 `at/for`、`until/for` 可以出现一次手势同时修改 Script 与 SVML。例如拖动 `at/for`-的起点时,Moment 会移动,同时 `for` 会改变以保持终点不动。两处修改属于同一个 revision-事务;重新编译失败时一起回退。--Companion 仍负责实体外观和 Inspector 展示,但不再声明通用时间逆函数。新组件只要消费公共-Instant/Window,并由 Companion 把真实执行谱系连到实体,就自动获得同一套时间行为。--消费端也不是只读取 `frame`:每个官方组件在接收 Instant/Window 时核对 `subjectId`、-`ProgramSpace.id`。Script 与 Timeline 的对应关系在语义投影时核对。Timeline 是运行图上的显式输入边;不通过全局状态、-当前 Film 或 renderer 上下文补猜。--字幕 Cue 保持独立:`CaptionDocument -> TimedCaptionProjection -> FineCaptionSchedule` 直接从-Semantic token evidence 得到只读 Cue 时间,不伪装成可拖动的 TemporalWindow。两种投影共享-`spaceId / narrativeId / documentId` 的来源校验,但只有 Fine 的 lead、tail、handoff 作为普通-参数允许修改。--Film 与 Script 的解释也不留在 Studio 核心:`film-studio` 声明 Film 的时间来源和终端 Track-引用规则;`script-studio` 拥有 Script Source map 与 marker 移动。Studio 只选择-`narrativeId` 与当前 Timeline 一致的 Script,再把语义修改委托回该 Companion。-零 Take 的 Timeline 提供同样的物理时间范围,不需要 Script 轨道。`at="2s"` 表示作者编排的事件时刻,-可以单独用于 Instant,也可以与 `for` 配合形成 Window;其时间修改回写 SVML。--这里的 binding 名不是全局地址。Markup 在降低语法时保留作者元素和输入范围,Elaborator-把端点与 Record、Component、Output 一起按 Source unit hygienize;编译结果中的-`AuthorProvenance` 再把运行 authority 精确接回这个端点。Studio 不会在多份 import 中选择-第一个同名的 `start`、output 或本地 id。这份 provenance 每次编译重新产生,不落盘,也不是-lock、哈希清单或项目索引。+时间表达记录作者的选择。讲解画面可以跟随一句话,闪光可以响应答案,独立动画可以使用影片时钟。+Studio 修改的是该写法所表达的选择。++[Script](../quickstart/script.md) 用 Selection 和 Moment 为语义范围与事件命名。+Timeline 放置准备好的表演;组件通过这些身份或时钟位置获得 Instant、Window。+无声动画使用同一种 Timeline,由作者声明完整时长。++## 选择需要编辑的关系++| 作者写法 | 移动时改变什么 | 裁剪时改变什么 |+| --- | --- | --- |+| `during={story.selection.proof}` | 两个共享 Script 锚点移动相同数量的语义停靠点;时长可能变化 | 对应的 Selection 边界 |+| 事件的 `at={story.moment.reveal}` | 共享 Moment 锚点 | 该写法没有声明持续时间 |+| 事件的 `at={story.selection.proof} boundary="start"` | 仅 Selection 的起点锚点 | 该写法没有声明持续时间 |+| `at={story.moment.reveal} for="8f"` | Moment;持续时间保持八帧 | 从尾端改变持续时间;Moment 保持不变 |+| `until={story.moment.reveal} for="8f"` | Moment;持续时间保持八帧 | 从首端改变持续时间;Moment 保持不变 |+| `at="2s" for="8f"` | 作者指定的时钟位置 | 从尾端改变持续时间 |+| `instant="moment.cue + 2f" moment={story.moment.reveal}` | 局部偏移;Moment 保持不变 | 该写法没有声明持续时间 |+| `start="…" end="…"` | 两个端点表达式移动相同帧数 | 仅对应端点的表达式 |+| `during={story.segment.opening}` 或 `during="program"` | 跟随结构范围,不提供时间线拖动 | 不提供时间线裁剪 |++消费组件决定需要 Instant 还是 Window,以及支持哪些写法。事件跟随 Selection 终点时使用+`boundary="end"`,同样只修改选定边界。++## 分清共享语义与局部偏移++移动 `at={story.moment.reveal}` 会在 Script 中移动 Moment,所有使用它的组件随后一起跟随。+使用相同 Moment 的 `instant="moment.cue"` 则暴露一个初始为零的局部偏移;移动它不会改写共享事件。++需要有意提前或延后时,写 `instant="moment.cue + 2f"` 并绑定 `moment={story.moment.reveal}`。+计算表达式不写进 `{story.moment.reveal}` 这样的图值引用中。++事件与持续时间是两个独立决定。`at/for` 只在尾端提供时长裁剪,`until/for` 只在首端提供时长裁剪。+另一端不会提供一个同时移动共享事件、再补偿时长的隐藏操作。++## 保留原文与所选边界++词首、词尾和结构边界是不同的语义锚点。停顿可以属于前一句,也可以属于后一句。+拖动沿不同帧位置上的语义停靠点进行;多个锚点重合时,支持该编辑的 Inspector 可以选择精确身份。+Take 交叠或重排时,Script 顺序可以与实际时间顺序不同。++移动标记保留无关原文、空格、标点、发音和词属性。字幕 Cue 保留来自 Script 的内容及实测词时间。+在 Script 中修改文案或 Cue 边界,通过 Caption Style 与带时间范围的 Use 修改呈现。++未编辑的表达式保留原单位:`2s` 在帧率变化后仍是两秒,`60f` 则保持六十帧。+拖动改变的时钟位置或偏移以当前帧率下的整数帧写回。++## 编辑项目组件++组件的 Companion 把画面实体连接到实际作者输入和已投影的时间。时间形式决定编辑对象,+组件名称或偶然相同的帧位置不能代替该关系。Script Companion 拥有源码观察和标记移动;+增加新组件不需要让 Studio 再学习一种 Script 解释方式。++[Studio](../quickstart/preview.md) 介绍编辑界面,[Companion 指南](./studio-companion-architecture.md)+介绍如何公开实体和控件;包内的[时间编辑参考](https://github.com/hypit-ai/hypit/blob/main/packages/temporal-markup/EDITING.md)+维护精确实现接口和支持的操作。diff --git a/docs/zh/quickstart/composition.md b/docs/zh/quickstart/composition.mdindex e4be498c..26fe10a8 100644--- a/docs/zh/quickstart/composition.md+++ b/docs/zh/quickstart/composition.md@@ -156,7 +156,7 @@ Build Target,也可以直接接到媒体裁切、音频/帧提取或模型参<!-- 1. Script: the semantic truth --><script id="story">- <opening><HOST>Meaning @{demo} becomes the source @{/demo}.</opening>+ <opening><HOST>Meaning @{demo}becomes the source.@{/demo}</opening></script><!-- 2. Generation: Seedance talking head + standalone video -->diff --git a/docs/zh/quickstart/preview.md b/docs/zh/quickstart/preview.mdindex 78379083..a55bbb4b 100644--- a/docs/zh/quickstart/preview.md+++ b/docs/zh/quickstart/preview.md@@ -59,6 +59,6 @@ Source 编辑修改所选 `.svml`、`.svs` 或 `.svrun` 文件。支持的 Inspe预览播放包含 Film 选中的 AudioTrack,例如口播、音乐与音效。导出视频的音频由渲染的媒体管线装配。作品准备好交付后,运行导出 Build 得到编码后的成片;Studio 与 Comments 仍可用于查看可编辑作品、沟通后续修改。-组件作者可以阅读 [Studio 时间谱系](../guide/studio-temporal-windows.md) 了解语义编辑,以及 [Companion SDK](https://github.com/hypit-ai/hypit/blob/main/packages/studio-adapter/README.md) 了解如何公开组件实体和控件。+组件作者可以阅读 [Studio 中的时间编辑](../guide/studio-temporal-windows.md) 了解语义编辑,以及 [Companion SDK](https://github.com/hypit-ai/hypit/blob/main/packages/studio-adapter/README.md) 了解如何公开组件实体和控件。需要其他界面语言时,可以通过 `--locale-pack ./language.json` 加载本地 JSON 译文。[本地化指南](https://github.com/hypit-ai/hypit/blob/main/packages/studio/LOCALIZATION.md) 介绍译文格式、缺项检查和语言包分享方法。diff --git a/docs/zh/quickstart/run.md b/docs/zh/quickstart/run.mdindex 91a3d205..b6c2673f 100644--- a/docs/zh/quickstart/run.md+++ b/docs/zh/quickstart/run.md@@ -251,9 +251,10 @@ hypit pricing reference.svrun --json### 0. 准备按需依赖-普通用户不运行 `pnpm install`。`runtime up` 会读取所选 Runtime Profile,把其 Adapter-声明的上游 npm 包安装到机器共享目录,并准备外部程序。只有 Profile 选择 WhisperX、OpenCV-等本地 Python 程序时,才需要先安装 [`uv`](https://docs.astral.sh/uv/)。+使用已发布的 Hypit 命令,无需在 Hypit 源码仓库运行 `pnpm install`。`runtime up` 会读取所选+Runtime Profile,把其 Adapter 声明的上游 npm 包安装到机器共享目录,并准备外部程序。项目+自己的组件和 Provider 仍是普通项目依赖,由项目的包管理器安装。只有 Profile 选择 WhisperX、+OpenCV 等本地 Python 程序时,才需要先安装 [`uv`](https://docs.astral.sh/uv/)。作者侧缺少 Fontsource 等上游包时,`check`/`plan` 会给出精确命令,例如:diff --git a/docs/zh/quickstart/script.md b/docs/zh/quickstart/script.mdindex dcb73889..c64dca3c 100644--- a/docs/zh/quickstart/script.md+++ b/docs/zh/quickstart/script.md@@ -41,7 +41,7 @@ Segment 是按顺序排列的语音内容块。标签名**即**其 id——在- Segment 可以是自闭合标签(`<pause/>`)。空的 Segment 拥有结构但没有语音词元;它并不意味着静音或任何默认时长。- Segment 不能嵌套——每个 Segment 都是 `<script>` 的顶层子元素。-- Segment 名称遵循 XML 命名规则:字母、数字、连字符、下划线。+- Segment 名称符合 `[a-z][a-z0-9_-]{0,63}`;`script` 是保留名称。其他组件通过 `{story.segment.opening}` 引用单个 Segment,通过 `{story.segment.opening.dialogue}` 或 `{story.segment.opening.speech}` 引用其文本投影。@@ -114,7 +114,7 @@ Cue 的切换。这同样适用于其他语言的短语或名字,例如 `<Git这时左侧同时提供口播,因此标记也可以放在左侧,Studio 会回写到实际文字上:`<组@{beat!}件化|>`。标记和显示属性不会成为口播内容。若明确写了右侧口播,标记仍然属于-右侧。两侧都没有口播文字时无效。+右侧。明确或共享的口播都必须包含可说出的词;`<API|...>` 只有标点,无法建立时间对应,因此无效。`||` 是 **Caption Cue Break** 语法,只能位于完整对齐单元之间,不能写进 Dual Text 或切开N:M 单元。字幕稍后才把 CaptionDocument 与 Timeline 汇合得到帧时间。@@ -137,9 +137,9 @@ N:M 单元。字幕稍后才把 CaptionDocument 与 Timeline 汇合得到帧时<line><HOST>This is really{emphasis,keyword} important{brand}.</line>```-不写 `=` 的属性值默认为 `true`,也可以写成 `name=value`。Caption 包负责把属性名映射为-局部词样式;Selection 仍然负责整段 Alignment Unit 的基础样式。属性不能切开或包住 Dual-对齐单元。+不写 `=` 的属性值默认为 `true`,也可以写成 `name=value`。Caption 家族决定这些显示词属性+如何影响表现。带时间范围的 Use 选择字幕 Style;属性不会切开、包裹或改变 Dual+对齐单元的时间。### CaptionDocument 的组成@@ -201,7 +201,7 @@ Selection 不要求像 XML 标签那样嵌套,它们可以互相交叉:```svml<demo>- <HOST> @{a} One @{b} two @{/a} three @{/b}.+ <HOST> @{a}One @{b}two@{/a} three.@{/b}</demo>```@@ -274,7 +274,7 @@ Moment 是具名的时间**点**(不是范围):</meeting><evidence>- <HOST> That gave me @{emphasis} the courage I was missing @{/emphasis}.+ <HOST> That gave me @{emphasis}the courage I was missing.@{/emphasis}</evidence><payoff>diff --git a/examples/complex-explainer/productions/explainer/authors/script.svml b/examples/complex-explainer/productions/explainer/authors/script.svmlindex 53d92313..4e39a075 100644--- a/examples/complex-explainer/productions/explainer/authors/script.svml+++ b/examples/complex-explainer/productions/explainer/authors/script.svml@@ -37,13 +37,13 @@<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!} 一行代码都不用重写了!+ <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!} 一个时间点都不用改了!+ <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!} 而且跟原来那条爆款的效果 || 完全一模一样!diff --git a/packages/caption-fine/README.md b/packages/caption-fine/README.mdindex 3ae9d43f..dce404dd 100644--- a/packages/caption-fine/README.md+++ b/packages/caption-fine/README.md@@ -14,10 +14,10 @@ does not carry a private visual role.</caption-fine:Track>```-An optional Spatial Region Timeline replaces only the moving placement point. The timeline is authored-numeric input, measured from the actual footage before the composition pass that consumes it;-it is not a face-tracking request. A prior Build may produce that footage with ordinary fixed Caption,-and a later Run can reuse the same media and alignment while changing placement:+An optional Spatial Region Timeline supplies a moving placement point when the user's reference+visibly uses head-following Caption or the user asks for that treatment. Ordinary Caption uses the+Style's placement without regions. The Region Timeline is authored numeric input mapped from available picture+evidence to the composition that consumes it; it is not a face-tracking request:```xml<space:RegionTimeline id="heads" within={vertical} recipe={tracking.heads.default}/>diff --git a/packages/hyperframes/README.md b/packages/hyperframes/README.mdindex f2209cf9..1baf8ea4 100644--- a/packages/hyperframes/README.md+++ b/packages/hyperframes/README.md@@ -25,6 +25,13 @@ a Provider can verify and name staged bytes without guessing from the hash. A lorender Runtime calls `materializeHyperframesHtml()` with its own Artifact URL resolver beforehanding the HTML to HyperFrames. That environment-specific materialization is not a new compiledRecord and does not change the compiled document.++For observation of already materialized HTML, `HyperframesHtmlProject` carries the HTML and the+BlobRefs addressed by its media/font URLs. `hyperframesHtmlDomain` reads the compiler's exact root+frame clock and canvas; `stageHyperframesHtmlProject` stages those resources. This input does not+reconstruct a Composition or invent typed Surface facts from HTML. A caller with the original+`HyperframesDocument`, such as Studio, should pass that document to preserve all declared dependencies,+including resources embedded in browser-program data. The document remains the complete typed input.Staging assigns short local filenames; opaque Resource IDs are never interpreted as filesystempaths or filenames, so their length and punctuation do not restrict the host filesystem.`stageHyperframesProject` streams each asset into its staged file. Its `validateSurface(surface, path,diff --git a/packages/hyperframes/src/html-project.ts b/packages/hyperframes/src/html-project.tsnew file mode 100644index 00000000..e4038537--- /dev/null+++ b/packages/hyperframes/src/html-project.ts@@ -0,0 +1,79 @@+import type { BlobRef } from "@hypit/protocol";+import { isResourceId } from "@hypit/protocol";+import type { HyperframesCanvas, HyperframesFrameDomain } from "./types.js";++/** An already materialized HTML programme and the local files its URLs address. */+export type HyperframesHtmlProject = {+ readonly html: string;+ readonly assets: readonly { readonly url: string; readonly artifact: BlobRef }[];+};++/** Read the exact clock emitted by this package. Seconds never reconstruct frame identity. */+export function hyperframesHtmlDomain(html: string): HyperframesFrameDomain & { readonly canvas: HyperframesCanvas } {+ const roots = [...html.matchAll(/<[^!][^>]*\sdata-composition-id="[^"]*"[^>]*>/gu)];+ if (roots.length !== 1) throw new Error("Snapshot HTML needs exactly one compiled HyperFrames composition root");+ const attribute = (name: string) => {+ const value = new RegExp(`\\s${name}="([^"]*)"`, "u").exec(roots[0]![0])?.[1];+ if (value === undefined) throw new Error(`Snapshot HTML lacks ${name}; use the compiled HyperFrames HTML`);+ return value;+ };+ const positive = (value: string, name: string) => {+ const number = Number(value);+ if (!/^\d+$/u.test(value) || !Number.isSafeInteger(number) || number <= 0) throw new Error(`Invalid HyperFrames ${name}`);+ return number;+ };+ const fps = attribute("data-fps").split("/");+ if (fps.length > 2) throw new Error("HyperFrames data-fps must be an exact rational");+ return {+ frameRate: { numerator: positive(fps[0]!, "frame rate"), denominator: positive(fps[1] ?? "1", "frame rate denominator") },+ frameCount: positive(attribute("data-hypit-frame-count"), "frame count"),+ canvas: { width: positive(attribute("data-width"), "width"), height: positive(attribute("data-height"), "height") },+ };+}++function unescape(value: string): string {+ return value.replaceAll(""", '"').replaceAll("'", "'").replaceAll("<", "<").replaceAll(">", ">").replaceAll("&", "&");+}++/** Resource URL positions in the compiler's self-contained HTML (inline JS and CSS). */+export function mapHyperframesHtmlUrls(html: string, map: (url: string) => string): string {+ const escape = (value: string) => value.replaceAll("&", "&").replaceAll('"', """);+ const cssUrls = (css: string) => css.replace(/url\(\s*(["']?)([^)"']+)\1\s*\)/gu,+ (_all, _quote: string, url: string) => `url("${map(url.trim()).replaceAll("\\", "\\\\").replaceAll('"', '\\"')}")`);+ return html.replace(/<style\b([^>]*)>([\s\S]*?)<\/style>/gu,+ (_all, attributes: string, css: string) => `<style${attributes}>${cssUrls(css)}</style>`)+ .replace(/<[a-z][^>]*>/gu, tag => {+ const attributes = /^(?:<(?:img|video|source|image|use|script|link)\b)/u.test(tag)+ ? tag.replace(/\s(src|poster|href)="([^"]*)"/gu,+ (_all, key: string, url: string) => ` ${key}="${escape(map(unescape(url)))}"`) : tag;+ return attributes.replace(/\sstyle="([^"]*)"/gu,+ (_all, css: string) => ` style="${escape(cssUrls(unescape(css)))}"`);+ });+}++export function hyperframesHtmlAssetUrls(html: string): readonly string[] {+ const urls = new Set<string>();+ mapHyperframesHtmlUrls(html, url => {+ if (url !== "" && !url.startsWith("#") && !url.startsWith("data:")) urls.add(url);+ return url;+ });+ return [...urls];+}++export function assertHyperframesHtmlProject(value: unknown): asserts value is HyperframesHtmlProject {+ const project = value as HyperframesHtmlProject;+ if (!project || typeof project.html !== "string" || !Array.isArray(project.assets)) throw new Error("HyperFrames HTML project needs html and assets");+ hyperframesHtmlDomain(project.html);+ if (/hypit-resource:\/\//u.test(project.html)) throw new Error("HTML still has unresolved resources; materialize its HyperframesDocument first");+ const urls = new Set<string>();+ for (const asset of project.assets) {+ const blob = asset?.artifact;+ if (typeof asset?.url !== "string" || urls.has(asset.url) || blob?.kind !== "blob" || !isResourceId(blob.resource)+ || !Number.isSafeInteger(blob.size) || blob.size < 0 || typeof blob.mediaType !== "string" || !blob.mediaType) {+ throw new Error("Invalid or repeated HyperFrames HTML asset");+ }+ urls.add(asset.url);+ }+ const referenced = hyperframesHtmlAssetUrls(project.html);+ if (referenced.length !== urls.size || referenced.some(url => !urls.has(url))) throw new Error("HyperFrames HTML assets must address its referenced URLs");+}diff --git a/packages/hyperframes/src/index.ts b/packages/hyperframes/src/index.tsindex fac627b7..394f465d 100644--- a/packages/hyperframes/src/index.ts+++ b/packages/hyperframes/src/index.ts@@ -11,3 +11,5 @@ export {export type * from "./types.js";export { browserProgram, BROWSER_PROGRAM_FORMAT } from "./browser-program.js";export type { BrowserProgram } from "./browser-program.js";+export { assertHyperframesHtmlProject, hyperframesHtmlDomain, hyperframesHtmlAssetUrls, mapHyperframesHtmlUrls } from "./html-project.js";+export type { HyperframesHtmlProject } from "./html-project.js";diff --git a/packages/hyperframes/src/project.ts b/packages/hyperframes/src/project.tsindex 7bab3e98..bdf8f074 100644--- a/packages/hyperframes/src/project.ts+++ b/packages/hyperframes/src/project.ts@@ -6,6 +6,8 @@ import type { BlobRef } from "@hypit/protocol";import { assertHyperframesDocument, materializeHyperframesHtml } from "./document.js";import type { HyperframesDocument } from "./types.js";+import { assertHyperframesHtmlProject, mapHyperframesHtmlUrls } from "./html-project.js";+import type { HyperframesHtmlProject } from "./html-project.js";/** Reads one execution resource. Whose store it comes from is the caller's business. */export type HyperframesArtifactReader = (@@ -37,6 +39,32 @@ function extension(mediaType: string): string {return found;}+/** Stage an existing HTML programme; no reverse compilation or inferred Surface declarations. */+export async function stageHyperframesHtmlProject(options: {+ readonly project: HyperframesHtmlProject;+ readonly directory: string;+ readonly read: HyperframesArtifactReader;+ readonly signal?: AbortSignal;+}): Promise<void> {+ assertHyperframesHtmlProject(options.project);+ await mkdir(join(options.directory, "artifacts"), { recursive: true });+ const paths = new Map<string, string>();+ for (const [index, asset] of options.project.assets.entries()) {+ options.signal?.throwIfAborted();+ const path = `artifacts/asset-${index}${extension(asset.artifact.mediaType)}`;+ const bytes = await options.read(asset.artifact, options.signal);+ const file = await open(join(options.directory, path), "w");+ try {+ if (bytes instanceof Uint8Array) await file.writeFile(bytes);+ else for await (const chunk of bytes) { options.signal?.throwIfAborted(); await file.writeFile(chunk); }+ } finally { await file.close(); }+ paths.set(asset.url, `./${path}`);+ }+ await writeFile(join(options.directory, "index.html"), mapHyperframesHtmlUrls(options.project.html, url => paths.get(url) ?? url), {+ encoding: "utf8", ...(options.signal === undefined ? {} : { signal: options.signal }),+ });+}+/*** Lay one document out as a directory HyperFrames can render.*diff --git a/packages/hyperframes/test/html-project.test.ts b/packages/hyperframes/test/html-project.test.tsnew file mode 100644index 00000000..e0b5a78d--- /dev/null+++ b/packages/hyperframes/test/html-project.test.ts@@ -0,0 +1,14 @@+import assert from "node:assert/strict";+import test from "node:test";+import { hyperframesHtmlAssetUrls, mapHyperframesHtmlUrls } from "../src/index.js";++test("materialized HTML preserves CSS attribute quoting and internal SVG references while relocating media", () => {+ const html = '<style>@font-face{src:url("./font.woff2")}</style><div style="background-image:url("./picture.png");filter:url(#mask)">'+ + '<img src="./picture.png"><a href="https://example.org">link</a></div>';+ assert.deepEqual(hyperframesHtmlAssetUrls(html), ["./font.woff2", "./picture.png"]);+ const mapped = mapHyperframesHtmlUrls(html, url => url.startsWith("./") ? `./assets/${url.slice(2)}` : url);+ assert.match(mapped, /background-image:url\("\.\/assets\/picture.png"\)/u);+ assert.match(mapped, /filter:url\("#mask"\)/u);+ assert.match(mapped, /src="\.\/assets\/picture.png"/u);+ assert.match(mapped, /href="https:\/\/example.org"/u);+});diff --git a/packages/provider-hyperframes-local/README.md b/packages/provider-hyperframes-local/README.mdindex b0cb736e..8bf99d7f 100644--- a/packages/provider-hyperframes-local/README.md+++ b/packages/provider-hyperframes-local/README.md@@ -1,12 +1,22 @@# @hypit/provider-hyperframes-local-Trusted local Provider for the `@hypit/render-hyperframes#render-visual` capability. It stages the+Trusted local Provider for `@hypit/render-hyperframes@1#render-visual` and `#render-frames`. It stages theResource dependencies declared by a `HyperframesDocument`, renders a silent MP4 with theHyperFrames engine, probes the bytes, and returns a verified `RenderedVisual`. Before capturing a typedSurface it decodes the exact bytes and checks declared dimensions, still/frame timing, SDR/sRGB andopaque/straight-alpha facts. These checks validate the typed rendering input; they do not createcontent identity or hidden output metadata.+`render-frames` uses the same staging, source-frame mapping, readiness and opaque PNG capture as+video export, returning the PNGs before encoding. It accepts a compiled document or a materialized+HTML project. For selected frames it merges only their required source-frame windows; continuous+windows decode sequentially. A complete batch shares one staged project and browser lifetime.+The existing browser selection, explicit preparation, worker settings and cancellation apply.+`maxRenderedBytes` bounds the total returned PNG bytes, or the encoded MP4 for a video request.+`render-frames` has its own capability binding; it does not inherit a `render-visual` binding.+For immediate CLI invocation, the host calls the handler directly: Build admission reservations do+not coordinate separate CLI processes. Worker limits still bound browsers inside each invocation.+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 andthe authored Canvas background. Final frames use fast PNG encoding after Chrome has composited@@ -73,8 +83,7 @@ an opaque session and chooses PNG separately at capture. It does not patch enginThe Runtime Adapter declares one managed browser program. Prepare it explicitly:```sh-hypit programs up --runtime ./hypit.runtime.json --endpoint hyperframes.local-hypit doctor --runtime ./hypit.runtime.json+hypit programs prepare --runtime ./hypit.runtime.json --endpoint hyperframes.local```Use the instance name from the Profile. `runtime up` also prepares it and starts the Runtime Worker.@@ -110,17 +119,20 @@ receipt is stored. To install into an empty location, explicitly choose `browser`config.chromePath` selects a user-managed Chrome/Chromium executable. It cannot be combined with`browserVersion` or `browserDownloadBaseUrl`; invalid combinations fail instead of assigning precedence. Relative paths resolve-from the Runtime Profile root. This mode never downloads or repairs a browser. Its version remains+from the Runtime data root, as does `browserCacheDirectory`. The Profile's `dataRoot` itself resolves+relative to the Profile file. This mode never downloads or repairs a browser. Its version remainsunder the user's control, including system-browser auto-updates. `HYPERFRAMES_BROWSER_PATH` and`PRODUCER_HEADLESS_SHELL_PATH` do not select browsers in this Provider; configure `chromePath`.On platforms without a supported managed download, explicitly select an installed browser.`doctor` displays the selected path and its source, and only inspects it. Build preflight, rendering-and previews never install a browser. `programs up` / `runtime up` display the selected managed+and previews never install a browser. `programs prepare`, `programs up` and `runtime up` display the selected managedversion, installation location and download URL before running preparation. The probe runs `--version` and checksFFmpeg/FFprobe; it does not promise GPU or page compatibility. Capture receives that same selected-path as the engine's `chromePath`, including its GPU probe. Active Workers keep their loaded package-recommendation; restart them explicitly after changing Profile or package dependencies.+path as the engine's `chromePath`, including its GPU probe. New Builds read current Endpoint+configuration and project implementation; active Builds keep their selected configuration. A+Distribution update or change to the Worker's inherited environment requires an explicit Worker+restart when active work permits. Ordinary Profile edits do not require restarting every process.The Provider's `hypit.dependencyInstallEnv` disables Puppeteer's browser download while preparing itsengine/producer npm dependencies. The repository `.puppeteerrc.cjs` does the same for checkout installs.diff --git a/packages/provider-hyperframes-local/src/capture.ts b/packages/provider-hyperframes-local/src/capture.tsindex c499f2b0..ec0bb319 100644--- a/packages/provider-hyperframes-local/src/capture.ts+++ b/packages/provider-hyperframes-local/src/capture.ts@@ -11,7 +11,8 @@ import { CaptureConcurrency } from "./concurrency.js";import { createOpaqueFrameCapture } from "./opaque-capture.js";export type CaptureInput = {- readonly document: HyperframesDocument;+ readonly document: Pick<HyperframesDocument, "frameRate" | "frameCount" | "canvas">;+ readonly frames?: readonly number[];readonly range: MediaFrameRange;readonly config: ReturnType<typeof resolveExecutionOptions> & { readonly chromePath: string };readonly directory: string;@@ -24,14 +25,16 @@ export async function captureStagedVisual(input: CaptureInput, controller: AbortonProgress: (event: HyperframesRenderProgress) => void): Promise<string> {const { document, range, config, directory: work } = input;const signal = controller.signal;- const frameCount = range.endFrameExclusive - range.startFrame;+ const frameCount = input.frames?.length ?? range.endFrameExclusive - range.startFrame;+ const selected = input.frames === undefined ? undefined : new Set(input.frames);+ const at = (index: number) => input.frames?.[index] ?? range.startFrame + index;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);+ const batches = distributeFrameRange({ startFrame: 0, endFrameExclusive: frameCount }, batchCount);let nextBatch = 0;const started = performance.now();const elapsedMs = () => Math.round(performance.now() - started);@@ -81,7 +84,8 @@ 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.- const windows = sourceWindows(slots, range);+ const windows = sourceWindows(slots, input.frames === undefined ? [range]+ : input.frames.map(frame => ({ startFrame: frame, endFrameExclusive: frame + 1 })));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() });@@ -119,7 +123,7 @@ export async function captureStagedVisual(input: CaptureInput, controller: Abortconst frameIndex = sourceFrameAt(slot, frame);const framePath = sources.get(slot.src)?.frames.get(frameIndex);// Browser initialization may seek outside the requested interval.- if (frame < range.startFrame || frame >= range.endFrameExclusive) continue;+ if (selected === undefined ? frame < range.startFrame || frame >= range.endFrameExclusive : !selected.has(frame)) continue;assert(framePath !== undefined, `HyperFrames has no decoded frame ${frameIndex} for ${slot.id}`);payloads.set(slot.id, { framePath, frameIndex });}@@ -132,7 +136,7 @@ export async function captureStagedVisual(input: CaptureInput, controller: Abortawait mkdir(outputFrames);onProgress?.({ phase: "prepared", workers: concurrency.target, sourceFrames, elapsedMs: elapsedMs() });const jobs: Promise<void>[] = [];- let active = 0, open = 0, initializing = 0, capturedFrames = 0;+ let active = 0, open = 0, initializing = 0, capturedFrames = 0, capturedBytes = 0;let startupMs = 0;const launch = (): void => {const worker = jobs.length;@@ -187,13 +191,18 @@ export async function captureStagedVisual(input: CaptureInput, controller: Abortif (active > concurrency.target) break;const batch = batches[nextBatch++];if (batch === undefined) break;- for (let frame = batch.startFrame; frame < batch.endFrameExclusive; frame++) {+ for (let index = batch.startFrame; index < batch.endFrameExclusive; index++) {+ const frame = at(index);signal.throwIfAborted();const captured = await stage(`worker ${worker} frame ${frame}`, config.frameTimeoutMs, () => captureFrame(frame));+ if (input.frames !== undefined) {+ capturedBytes += captured.buffer.byteLength;+ assert(capturedBytes <= config.maxRenderedBytes, "HyperFrames PNG output exceeds its byte limit");+ }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);+ await writeFile(join(outputFrames, `${String(index).padStart(9, "0")}.png`), captured.buffer);completed++;capturedFrames++;if (performance.now() - lastProgressAt >= 1_000) {@@ -239,6 +248,7 @@ export async function captureStagedVisual(input: CaptureInput, controller: Abortif (failure !== undefined) throw failure;signal.throwIfAborted();await Promise.all(closing.values());+ if (input.frames !== undefined) return outputFrames;const output = join(work, "visual.mp4");onProgress({ phase: "encoding", elapsedMs: elapsedMs() });const crf = { draft: 28, standard: 23, high: 18 }[config.quality];diff --git a/packages/provider-hyperframes-local/src/index.ts b/packages/provider-hyperframes-local/src/index.tsindex 380f7e15..85c1fc91 100644--- a/packages/provider-hyperframes-local/src/index.ts+++ b/packages/provider-hyperframes-local/src/index.ts@@ -6,5 +6,5 @@ export type {HyperframesWorkers,} from "./provider.js";-export { renderHyperframesVisual } from "./render.js";+export { renderHyperframesVisual, renderHyperframesFrames } from "./render.js";export type { RenderHyperframesVisualOptions, HyperframesRenderProgress } from "./render.js";diff --git a/packages/provider-hyperframes-local/src/output.ts b/packages/provider-hyperframes-local/src/output.tsindex 415d2b9c..22fd3d35 100644--- a/packages/provider-hyperframes-local/src/output.ts+++ b/packages/provider-hyperframes-local/src/output.ts@@ -38,7 +38,7 @@ function outputFrameCount(stream: ProbeStream): number {export async function verifyOutput(args: {readonly path: string;- readonly document: HyperframesDocument;+ readonly document: Pick<HyperframesDocument, "frameRate" | "frameCount" | "canvas">;readonly ffprobePath: string;readonly timeoutMs: number;readonly maxOutputBytes: number;diff --git a/packages/provider-hyperframes-local/src/provider.ts b/packages/provider-hyperframes-local/src/provider.tsindex 0f76b0bf..425ad4ca 100644--- a/packages/provider-hyperframes-local/src/provider.ts+++ b/packages/provider-hyperframes-local/src/provider.ts@@ -1,8 +1,8 @@import { defineEndpointPackage } from "@hypit/endpoint-kit";import { mediaTypes } from "@hypit/media";-import { renderHyperframesCapabilities, verifyHyperframesVisualRequest } from "@hypit/render-hyperframes";+import { renderHyperframesCapabilities, renderHyperframesTypes, verifyHyperframesFramesRequest, hyperframesFramesDomain, verifyHyperframesVisualRequest } from "@hypit/render-hyperframes";import { canonicalize } from "@hypit/protocol";-import { renderHyperframesVisual, resolveExecutionOptions, renderWorkerLimit } from "./render.js";+import { renderHyperframesVisual, renderHyperframesFrames, resolveExecutionOptions, renderWorkerLimit } from "./render.js";import type { HyperframesExecutionOptions } from "./options.js";import { renderProgressReporter } from "./progress.js";@@ -67,6 +67,33 @@ export function createLocalHyperframesProvider(config: CreateLocalHyperframesProawait progress.flush();}},+ }, {+ lifecycle: "immediate" as const,+ capability: renderHyperframesCapabilities.renderFrames,+ returns: renderHyperframesTypes.frames,+ ...(config.browserCapacity === undefined ? {} : {+ resources: [{ id: browsers, limit: config.browserCapacity }],+ unitsForRequest: (request: import("@hypit/endpoint-kit").EndpointRequest) => {+ verifyHyperframesFramesRequest(request.constraints);+ const document = hyperframesFramesDomain(request.constraints);+ return { [browsers]: renderWorkerLimit(reserved, request.constraints.frames.length,+ document.frameRate.numerator / document.frameRate.denominator) };+ },+ }),+ handler: async context => {+ const request = context.need.constraints;+ verifyHyperframesFramesRequest(request);+ const progress = renderProgressReporter(context.reportProgress, request.frames.length);+ try {+ const frames = await renderHyperframesFrames(request, { ...config,+ ...(execution.chromePath === undefined ? { browserVersion: execution.browserVersion! } : { chromePath: execution.chromePath }),+ browserCacheDirectory: execution.browserCacheDirectory,+ workers: execution.workers, maxWorkers,+ resources: context.resources, onProgress: progress.onProgress,+ ...(context.reportDiagnostic === undefined ? {} : { onDiagnostic: context.reportDiagnostic }) });+ return { value: { kind: "inline", value: canonicalize(frames) } };+ } finally { await progress.flush(); }+ },}],});}diff --git a/packages/provider-hyperframes-local/src/render.ts b/packages/provider-hyperframes-local/src/render.tsindex 06e8ffec..86cac6a4 100644--- a/packages/provider-hyperframes-local/src/render.ts+++ b/packages/provider-hyperframes-local/src/render.ts@@ -3,12 +3,12 @@ import { mkdtemp, readFile, rm } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import type { EndpointInvocationContext } from "@hypit/endpoint-kit";-import { stageHyperframesProject } from "@hypit/hyperframes/project";+import { stageHyperframesProject, stageHyperframesHtmlProject } from "@hypit/hyperframes/project";import { sealRenderedVisual } from "@hypit/media";import type { MediaFrameRange, RenderedVisual } from "@hypit/media";import { verifyCompositableSurfaceFile } from "@hypit/media-execution";-import { verifyHyperframesVisualRequest } from "@hypit/render-hyperframes";-import type { HyperframesVisualRequest } from "@hypit/render-hyperframes";+import { verifyHyperframesVisualRequest, verifyHyperframesFramesRequest, hyperframesFramesDomain } from "@hypit/render-hyperframes";+import type { HyperframesVisualRequest, HyperframesFramesRequest, HyperframesFrames } from "@hypit/render-hyperframes";import { isStreamingResourceStore } from "@hypit/runtime";import type { HyperframesExecutionOptions } from "./options.js";import { assert, positiveInteger } from "./process.js";@@ -75,10 +75,22 @@ export async function renderHyperframesVisual(options: RenderHyperframesVisualOptions,): Promise<RenderedVisual> {verifyHyperframesVisualRequest(request);+ return capture(request, options) as Promise<RenderedVisual>;+}++export async function renderHyperframesFrames(request: HyperframesFramesRequest, options: RenderHyperframesVisualOptions): Promise<HyperframesFrames> {+ verifyHyperframesFramesRequest(request);+ return capture(request, options) as Promise<HyperframesFrames>;+}++async function capture(request: HyperframesVisualRequest | HyperframesFramesRequest, options: RenderHyperframesVisualOptions): Promise<RenderedVisual | HyperframesFrames> {const config = { ...resolveExecutionOptions(options), chromePath: browserExecutablePath(options) };- const { document } = request;- const range = request.range ?? { startFrame: 0, endFrameExclusive: document.frameCount };- const frameCount = range.endFrameExclusive - range.startFrame;+ const frames = "frames" in request ? request.frames : undefined;+ const document = "frames" in request ? hyperframesFramesDomain(request) : request.document;+ const range = frames === undefined+ ? (request as HyperframesVisualRequest).range ?? { startFrame: 0, endFrameExclusive: document.frameCount }+ : { startFrame: frames[0]!, endFrameExclusive: frames.at(-1)! + 1 };+ const frameCount = frames?.length ?? 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();@@ -103,23 +115,25 @@ export async function renderHyperframesVisual(signal.throwIfAborted();await requireBrowserExecutable(config.chromePath, config.browserVersion);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}; browser ${config.chromePath}; encoder ${config.ffmpegPath}` });+ `Capture ${frameCount} frames; workers ${config.workers} (limit ${renderWorkerLimit(config, frameCount, document.frameRate.numerator / document.frameRate.denominator)}); opaque fast PNG; GPU ${config.browserGpu}; browser ${config.chromePath}`+ + (frames === undefined ? `; quality ${config.quality}; encoder ${config.ffmpegPath}` : "; PNG output") });options.onProgress?.({ phase: "staging", elapsedMs: 0 });work = await mkdtemp(join(tmpdir(), "hypit-hyperframes-local-"));- await stageHyperframesProject({ document, directory: work, signal,- read: async (artifact, readSignal) => {+ const read: import("@hypit/hyperframes/project").HyperframesArtifactReader = async (artifact, readSignal) => {const io = { signal: readSignal! };const bytes = isStreamingResourceStore(options.resources)? await options.resources.open(artifact.resource, io) : await options.resources.get(artifact.resource, io);assert(bytes !== undefined, `HyperFrames Artifact ${artifact.resource} is unavailable`);return bytes;- },+ };+ if ("project" in request) await stageHyperframesHtmlProject({ project: request.project, directory: work, signal, read });+ else await stageHyperframesProject({ document: request.document, directory: work, signal, read,validateSurface: (surface, path, probeSignal) => verifyCompositableSurfaceFile({ surface, path,ffprobePath: config.ffprobePath, processTimeoutMs: config.processTimeoutMs,maxProbeOutputBytes: config.maxProcessOutputBytes, signal: probeSignal! }),});changePhase("decoding source frames");- await runCaptureProcess({ document, range, config, directory: work,+ await runCaptureProcess({ document, range, ...(frames === undefined ? {} : { frames }), config, directory: work,engineModule: import.meta.resolve("@hyperframes/engine"),producerModule: import.meta.resolve("@hyperframes/producer"),}, signal, (event) => {@@ -132,22 +146,33 @@ export async function renderHyperframesVisual(signal.throwIfAborted();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)) {- const stream = createReadStream(output, { signal });- const closed = finished(stream).catch(() => {});- try { artifact = await options.resources.putStream(stream, "video/mp4", { signal }); }- finally { stream.destroy(); await closed; }+ const store = async (output: string, mediaType: string) => {+ if (isStreamingResourceStore(options.resources)) {+ const stream = createReadStream(output, { signal });+ const closed = finished(stream).catch(() => {});+ try { return await options.resources.putStream(stream, mediaType, { signal }); }+ finally { stream.destroy(); await closed; }+ }+ return options.resources.put(await readFile(output, { signal }), mediaType, { signal });+ };+ let result: RenderedVisual | HyperframesFrames;+ if (frames === undefined) {+ result = sealRenderedVisual({ frameRate: document.frameRate, frameCount, canvas: document.canvas,+ artifact: await store(join(work, "visual.mp4"), "video/mp4") });} else {- artifact = await options.resources.put(await readFile(output, { signal }), "video/mp4", { signal });+ const artifacts = [];+ for (let index = 0; index < frames.length; index++) {+ signal.throwIfAborted();+ artifacts.push(await store(join(work, "frames", `${String(index).padStart(9, "0")}.png`), "image/png"));+ }+ result = artifacts;}signal.throwIfAborted();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 });+ return result;} catch (error) {if (signal.aborted) throw signal.reason;controller.abort(error);diff --git a/packages/provider-hyperframes-local/src/sampling.ts b/packages/provider-hyperframes-local/src/sampling.tsindex e09286a2..25590ebf 100644--- a/packages/provider-hyperframes-local/src/sampling.ts+++ b/packages/provider-hyperframes-local/src/sampling.ts@@ -51,9 +51,10 @@ export function sourceFrameAt(slot: VideoSlot, frame: number): number {return value;}-export function sourceWindows(slots: readonly VideoSlot[], range: MediaFrameRange) {+export function sourceWindows(slots: readonly VideoSlot[], selection: MediaFrameRange | readonly MediaFrameRange[]) {+ const ranges: readonly MediaFrameRange[] = Array.isArray(selection) ? selection : [selection as MediaFrameRange];const sources = new Map<string, { fps: VideoSlot["sourceFps"]; windows: MediaFrameRange[] }>();- for (const slot of slots) {+ for (const range of ranges) for (const slot of slots) {const first = Math.max(range.startFrame, slot.startFrame);const last = Math.min(range.endFrameExclusive, slot.endFrameExclusive) - 1;if (last < first) continue;diff --git a/packages/provider-hyperframes-local/test/alpha.test.ts b/packages/provider-hyperframes-local/test/alpha.test.tsindex 34b88457..8fe81f6d 100644--- a/packages/provider-hyperframes-local/test/alpha.test.ts+++ b/packages/provider-hyperframes-local/test/alpha.test.ts@@ -16,7 +16,8 @@ import { appendMediaItem, appendTimedMediaLayer, createMediaLayerSet, createMedifinalizeMediaTrack, projectMediaVisualTrack, sealMediaItemSpec, sealMediaSampleLayerSpec, sealMediaTrackHeader } from "@hypit/media-track";import { projectProgramWindow } from "../../../test/temporal-fixture.js";import { MemoryResourceStore, ffmpegBytes, normalizeTestVideo, transparentVideoFixture, writeTestArtifact } from "../../../test/alpha-video-fixture.js";-import { renderHyperframesVisual } from "../src/index.js";+import sharp from "sharp";+import { renderHyperframesVisual, renderHyperframesFrames } from "../src/index.js";test("transparent normalized media composites through both SemanticTake/Timeline and Media Track in Chrome", {skip: process.env.HYPIT_BROWSER_TESTS !== "1",@@ -86,6 +87,16 @@ test("transparent normalized media composites through both SemanticTake/Timelineclose(pixel(f, left + 32, 32), [240, 20, 20]);close(pixel(f, left + 60, 32), [130, 40, 120]);}+ const snapshots = await renderHyperframesFrames({ document, frames: [0, 11] }, { resources, workers: 2 });+ for (const snapshot of snapshots) {+ const pixels = await sharp((await resources.get(snapshot.resource))!).removeAlpha().raw().toBuffer();+ const at = (x: number, y: number) => [...pixels.subarray((y * 192 + x) * 3, (y * 192 + x) * 3 + 3)];+ for (const left of [0, 96]) {+ close(at(left + 4, 4), [20, 60, 220]);+ close(at(left + 32, 32), [240, 20, 20]);+ close(at(left + 60, 32), [130, 40, 120]);+ }+ }close(pixel(0, 18, 32), [240, 20, 20]);close(pixel(11, 18, 32), [20, 60, 220]);} finally {diff --git a/packages/provider-hyperframes-local/test/frames.test.ts b/packages/provider-hyperframes-local/test/frames.test.tsnew file mode 100644index 00000000..153d608b--- /dev/null+++ b/packages/provider-hyperframes-local/test/frames.test.ts@@ -0,0 +1,58 @@+import assert from "node:assert/strict";+import test from "node:test";+import { mkdtemp, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import sharp from "sharp";+import { sealComposition, sealVisualTrack } from "@hypit/composition";+import { sealProgramSpace } from "@hypit/program-space";+import { browserProgram, compileHyperframesDocument, hyperframesHtmlDomain } from "@hypit/hyperframes";+import { stageHyperframesProject } from "@hypit/hyperframes/project";+import { verifyHyperframesFramesRequest } from "@hypit/render-hyperframes";+import { MemoryResourceStore } from "@hypit/driver-node";+import { renderHyperframesFrames } from "../src/index.js";++function fixture() {+ const space = sealProgramSpace({ id: "space", durationSec: 1, frameRate: { numerator: 12, denominator: 1 } });+ return compileHyperframesDocument(sealComposition({ id: "frames", canvas: { width: 96, height: 64, clearColor: "#000000" },+ tracks: [sealVisualTrack({ id: "motion", programSpaceId: space.id, visualIr: "hypit.visual-ir@1", presents: [{ id: "reveal",+ span: { startFrame: 3, endFrameExclusive: 12 }, stacking: { order: 0, tieBreak: "reveal" }, elements: [{ id: "program", order: 0,+ kind: "program", style: [{ name: "position", value: "absolute" }, { name: "inset", value: 0 }],+ program: browserProgram({ html: '<div class="box"></div>', css: '.box{position:absolute;top:0;width:8px;height:64px;background:#ff0000}',+ setup: 'return frame => { root.querySelector(".box").style.left = `${frame * 8}px`; };' }),+ }] }] })] }), space);+}++test("frame selection validates original-frame bounds and exact HTML clock", () => {+ const document = fixture();+ verifyHyperframesFramesRequest({ document, frames: [0, 3, 11] });+ for (const frames of [[], [12], [3, 2], [1.5]]) assert.throws(() => verifyHyperframesFramesRequest({ document, frames }));+ assert.deepEqual(hyperframesHtmlDomain(document.html), { frameRate: document.frameRate, frameCount: 12, canvas: document.canvas });+});++test("snapshot captures original browser-program frames from document and staged HTML without video encoding", {+ skip: process.env.HYPIT_BROWSER_TESTS !== "1",+}, async () => {+ const resources = new MemoryResourceStore();+ const document = fixture();+ const directory = await mkdtemp(join(tmpdir(), "hypit-frames-proof-"));+ try {+ await stageHyperframesProject({ document, directory, read: async artifact => (await resources.get(artifact.resource))! });+ const html = await readFile(join(directory, "index.html"), "utf8");+ for (const input of [{ document }, { project: { html, assets: [] } }]) {+ const phases: string[] = [];+ const images = await renderHyperframesFrames({ ...input, frames: [0, 3, 4, 11] }, { resources, workers: 2,+ onProgress: event => { phases.push(event.phase); } });+ assert.equal(images.length, 4);+ assert.ok(!phases.includes("encoding"));+ for (const [index, expectedX] of [-1, 0, 8, 64].entries()) {+ const bytes = await resources.get(images[index]!.resource);+ const image = await sharp(bytes).removeAlpha().raw().toBuffer();+ const pixel = (x: number) => [...image.subarray(x * 3, x * 3 + 3)];+ assert.deepEqual(pixel(expectedX < 0 ? 0 : expectedX + 2), expectedX < 0 ? [0, 0, 0] : [255, 0, 0]);+ if (expectedX > 0) assert.deepEqual(pixel(0), [0, 0, 0]);+ }+ }+ await assert.rejects(renderHyperframesFrames({ document, frames: [3] }, { resources, workers: 1, maxRenderedBytes: 1 }), /PNG output exceeds/u);+ } finally { await rm(directory, { recursive: true, force: true }); }+});diff --git a/packages/provider-hyperframes-local/test/provider.test.ts b/packages/provider-hyperframes-local/test/provider.test.tsindex 7c75c4ef..25f7d368 100644--- a/packages/provider-hyperframes-local/test/provider.test.ts+++ b/packages/provider-hyperframes-local/test/provider.test.ts@@ -12,7 +12,7 @@ import { MemoryResourceStore, EndpointRegistry } from "@hypit/driver-node";import type { EndpointRegistration } from "@hypit/driver-node";import type { ImmediateEndpointHandler } from "@hypit/endpoint-kit";import { compileHyperframesDocument } from "@hypit/hyperframes";-import { renderHyperframesCapabilities, hyperframesVisualRequest } from "@hypit/render-hyperframes";+import { renderHyperframesCapabilities, renderHyperframesTypes, hyperframesVisualRequest } from "@hypit/render-hyperframes";import { canonicalize } from "@hypit/protocol";import type { CanonicalValue, Need } from "@hypit/protocol";@@ -125,14 +125,14 @@ async function handlerFor(request: Need): Promise<{return { handler: resolution.registration.handler, registration: resolution.registration };}-test("local HyperFrames Provider exposes one exact visual capability and two separate concurrency levels", async () => {+test("local HyperFrames Provider exposes visual and frame capabilities and two separate concurrency levels", async () => {const provider = createLocalHyperframesProvider({ workers: 4, defaultConcurrency: 2 });assert.equal(provider.instance.id, "hyperframes.local");assert.deepEqual(provider.offers, [{capability: renderHyperframesCapabilities.renderVisual,returns: mediaTypes.renderedVisual,endpoint: "hyperframes.local",- }]);+ }, { capability: renderHyperframesCapabilities.renderFrames, returns: renderHyperframesTypes.frames, endpoint: "hyperframes.local" }]);const resolved = await handlerFor(requestNeed());assert.equal(resolved.registration.scheduling?.resources.find((item) =>item.id.startsWith("pool:"))?.limit, 1,diff --git a/packages/provider-hyperframes-local/test/range.test.ts b/packages/provider-hyperframes-local/test/range.test.tsindex e30e76a8..3a30b447 100644--- a/packages/provider-hyperframes-local/test/range.test.ts+++ b/packages/provider-hyperframes-local/test/range.test.ts@@ -12,7 +12,8 @@ import { EndpointRegistry, MemoryResourceStore } from "@hypit/driver-node";import { compileHyperframesDocument } from "@hypit/hyperframes";import { sealProgramSpace } from "@hypit/program-space";import type { BlobRef } from "@hypit/protocol";-import { renderHyperframesVisual } from "../src/index.js";+import sharp from "sharp";+import { renderHyperframesVisual, renderHyperframesFrames } from "../src/index.js";import { resolveExecutionOptions } from "../src/render.js";import { hypitPackage } from "../src/activation.js";import type { RuntimeEndpointAdapterImplementation } from "@hypit/runtime-kit";@@ -141,6 +142,11 @@ test("real selected renders sample video correctly across loop, hold and stretch}}for (let channel = 0; channel < 3; channel++) assert.ok(Math.abs(one[center + channel]! - colors[3]![channel]!) < 12);+ const snapshots = await renderHyperframesFrames({ document, frames: [3, 7, 8, 11] }, { resources, workers: 2 });+ for (const [index, source] of [1, 3, 0, 1].entries()) {+ const pixels = await sharp((await resources.get(snapshots[index]!.resource))!).removeAlpha().raw().toBuffer();+ for (let channel = 0; channel < 3; channel++) assert.ok(Math.abs(pixels[center + channel]! - colors[source]![channel]!) < 12);+ }await assert.rejects(renderHyperframesVisual({ document, range: { startFrame: 7, endFrameExclusive: 8 } },{ resources, workers: 2, initializationTimeoutMs: 1, processTimeoutMs: 30_000 }), /worker 0 initialization timed out/);assert.equal((await render("after-timeout", { startFrame: 7, endFrameExclusive: 8 }, 1)).length, stride);diff --git a/packages/provider-whisperx-local/README.md b/packages/provider-whisperx-local/README.mdindex ffa8243a..f722845f 100644--- a/packages/provider-whisperx-local/README.md+++ b/packages/provider-whisperx-local/README.md@@ -91,16 +91,19 @@ torch caches and their environment settings. Changing a running service's cachean explicit restart when idle, just like changing its model or hardware. The managed installationdoes not require a global `whisperx` shell command.-Preparation and service processes inherit the environment of the command starting them. Set-network and cache variables there before `programs up` or `runtime up`. A service already running-retains its earlier environment. Inspect its reported log before deciding whether a selected-Program needs restarting, and account for active work using it.+Preparation and service processes inherit the environment of the command starting them. Set download+route variables on `programs prepare` (or the preparation performed by `programs up` / `runtime up`).+Changing only a download source does not require restarting a running service using the same cache.+Cache settings must select the same resource location for preparation and the service. A running+service retains its earlier environment; arrange an idle restart when changing that location or its+inference settings. Inspect its reported configuration and logs, and account for active work.If NLTK refuses a proxied fetch during preparation, follow the service’s[explicit proxy preparation](../../services/whisperx/README.md#preparing-sentence-data-through-a-proxy).Preparation commands write `install.log`; the running service writes `program.log`, with stderr in-`program.err.log` on Windows. Inspect the stderr file for Python model-loading and download messages.+`program.err.log` on Windows. Inspect service logs for Python model-loading and inference messages;+download messages belong to preparation's `install.log`.`programs status` reports these files as `installationLogPath`, `logPath` and `errorLogPath` when theyexist, even before installation finishes. Preparation notices name the Python environment and selected model/language resources separately. The service logs the start and completion of ASR loading, transcription,language-alignment model loading and alignment, with elapsed times. Downloads happen only indiff --git a/packages/render-hyperframes/README.md b/packages/render-hyperframes/README.mdindex b6d2cc7c..47599b03 100644--- a/packages/render-hyperframes/README.md+++ b/packages/render-hyperframes/README.md@@ -6,6 +6,15 @@ semantic coverage through the same frame and audio pipeline.Explicit author and capability boundary for final HyperFrames video rendering.+`@hypit/render-hyperframes@1#render-frames` captures an existing programme's selected frames.+`hyperframesFramesRequest({ document, frames })` accepts a `HyperframesDocument` and strictly+increasing original-frame indices. `{ project: { html, assets }, frames }` accepts already+materialized HTML with its URL-addressed assets. The `Frames` result is a PNG `BlobRef[]` in request+order; the request already owns the frame identities. Canvas and clock stay in the input.+This capability requests picture capture only. File names, contact sheets and pagination belong to+the caller. `hypit snapshot` invokes it immediately through a selected Profile; there is no Build+or video encoding in that observation path.+The package owns `<render:Video composition={...}/>` and lowers it to ordinary Operations that:1. obtain the `ProgramSpace` from the Timeline input and compile the referenced `Composition` into a `HyperframesDocument`;diff --git a/packages/render-hyperframes/src/index.ts b/packages/render-hyperframes/src/index.tsindex c141a273..472f81ab 100644--- a/packages/render-hyperframes/src/index.ts+++ b/packages/render-hyperframes/src/index.ts@@ -4,3 +4,6 @@ export { renderHyperframesCapabilities, renderHyperframesManifest, renderHyperfrexport { hyperframesVisualRequest, verifyHyperframesVisualRequest } from "./product.js";export type { HyperframesVisualRequest } from "./product.js";export { decodeHyperframesRenderSurface } from "./surface.js";+export { renderHyperframesTypes } from "./manifest.js";+export { hyperframesFramesRequest, hyperframesFramesDomain, verifyHyperframesFramesRequest, verifyHyperframesFrames } from "./product.js";+export type { HyperframesFramesRequest, HyperframesFrames } from "./product.js";diff --git a/packages/render-hyperframes/src/manifest.ts b/packages/render-hyperframes/src/manifest.tsindex 9d89e049..be423306 100644--- a/packages/render-hyperframes/src/manifest.ts+++ b/packages/render-hyperframes/src/manifest.ts@@ -12,6 +12,7 @@ import type {CapabilityRef,ModuleManifest,ProducerRef,+ TypeRef,} from "@hypit/protocol";import {mediaPipelineModuleRef,@@ -20,7 +21,11 @@ import {export const renderHyperframesModuleRef = { name: "@hypit/render-hyperframes", version: "1" } as const;export const renderHyperframesCapabilities = {renderVisual: { module: renderHyperframesModuleRef, name: "render-visual" },+ renderFrames: { module: renderHyperframesModuleRef, name: "render-frames" },} satisfies Record<string, CapabilityRef>;+export const renderHyperframesTypes = {+ frames: { module: renderHyperframesModuleRef, name: "Frames" },+} satisfies Record<string, TypeRef>;export const renderHyperframesProducers = {requestVisualRange: { module: renderHyperframesModuleRef, name: "request-visual-range" },requestVisual: { module: renderHyperframesModuleRef, name: "request-visual-render" },@@ -70,11 +75,11 @@ export const renderHyperframesManifest: ModuleManifest = {{ module: hyperframesModuleRef },{ module: mediaPipelineModuleRef },],- types: [],+ types: [{ name: renderHyperframesTypes.frames.name }],capabilities: [{name: renderHyperframesCapabilities.renderVisual.name,returns: mediaTypes.renderedVisual,- }],+ }, { name: renderHyperframesCapabilities.renderFrames.name, returns: renderHyperframesTypes.frames }],producers: [{name: renderHyperframesProducers.requestVisual.name,diff --git a/packages/render-hyperframes/src/product.ts b/packages/render-hyperframes/src/product.tsindex c72b769c..375ba3a6 100644--- a/packages/render-hyperframes/src/product.ts+++ b/packages/render-hyperframes/src/product.ts@@ -1,6 +1,8 @@import type { CanonicalValue } from "@hypit/protocol";-import { assertHyperframesDocument } from "@hypit/hyperframes";-import type { HyperframesDocument } from "@hypit/hyperframes";+import { assertHyperframesDocument, assertHyperframesHtmlProject, hyperframesHtmlDomain } from "@hypit/hyperframes";+import type { HyperframesDocument, HyperframesHtmlProject } from "@hypit/hyperframes";+import type { BlobRef } from "@hypit/protocol";+import { isResourceId } from "@hypit/protocol";import { verifyMediaFrameRange } from "@hypit/media";import type { MediaFrameRange } from "@hypit/media";@@ -9,6 +11,43 @@ export type HyperframesVisualRequest = {readonly range?: MediaFrameRange;};+/** Select original programme frames, in strictly increasing order. */+export type HyperframesFramesRequest = ({ readonly document: HyperframesDocument } | { readonly project: HyperframesHtmlProject }) & {+ readonly frames: readonly number[];+};+/** PNG images in request order. The request already supplies each frame's identity. */+export type HyperframesFrames = readonly BlobRef[];++export function hyperframesFramesDomain(request: HyperframesFramesRequest) {+ return "document" in request ? request.document : hyperframesHtmlDomain(request.project.html);+}++export function verifyHyperframesFramesRequest(value: unknown): asserts value is HyperframesFramesRequest {+ if (!value || typeof value !== "object" || Array.isArray(value)+ || Object.keys(value).some(key => !["document", "project", "frames"].includes(key))+ || ("document" in value) === ("project" in value)) throw new Error("Frame request needs exactly one document or HTML project, and frames");+ const request = value as HyperframesFramesRequest;+ if ("document" in request) assertHyperframesDocument(request.document);+ else assertHyperframesHtmlProject(request.project);+ const { frameCount } = hyperframesFramesDomain(request);+ if (!Array.isArray(request.frames) || request.frames.length === 0 || request.frames.some((frame, index) =>+ !Number.isSafeInteger(frame) || frame < 0 || frame >= frameCount || (index > 0 && frame <= request.frames[index - 1]!))) {+ throw new Error(`Frames must be strictly increasing integers in [0, ${frameCount})`);+ }+}++export function hyperframesFramesRequest(request: HyperframesFramesRequest): CanonicalValue {+ verifyHyperframesFramesRequest(request);+ return request as unknown as CanonicalValue;+}++export function verifyHyperframesFrames(value: unknown): asserts value is HyperframesFrames {+ if (!Array.isArray(value) || value.length === 0 || value.some(blob => !blob || blob.kind !== "blob"+ || !isResourceId(blob.resource) || blob.mediaType !== "image/png" || !Number.isSafeInteger(blob.size) || blob.size <= 0)) {+ throw new Error("HyperFrames frames must be PNG BlobRefs in request order");+ }+}+export function verifyHyperframesVisualRequest(value: unknown): asserts value is HyperframesVisualRequest {if (value === null || typeof value !== "object" || Array.isArray(value)|| Object.keys(value).some((key) => key !== "document" && key !== "range")) {diff --git a/packages/script-studio/test/script.test.ts b/packages/script-studio/test/script.test.tsnew file mode 100644index 00000000..834a1e83--- /dev/null+++ b/packages/script-studio/test/script.test.ts@@ -0,0 +1,35 @@+import assert from "node:assert/strict";+import test from "node:test";+import { decodeScriptSurface, parseScript, captionDocument } from "@hypit/script";+import { scriptStudioCompanions } from "../src/index.js";++test("Studio observes and edits the compiler's Script body without changing its prose", () => {+ const companion = scriptStudioCompanions[0]!;+ const body = '<line><host>是的 就是这样。 <진행자>@{beat!}“안녕”{emphasis} 세계. \\<!-- 설명</line>';+ const prefix = '<svml>\r\n<!-- 🎬 -->\r\n<script id="story">';+ const source = `${prefix}${body}</script>\r\n</svml>`;+ const input = { sourceName: "studio.svml", source, tag: "script", attributes: { id: "story" },+ openingStart: source.indexOf('<script'), contentStart: prefix.length };+ const decoded = decodeScriptSurface(input);+ const observed = companion.observe({ ...input, nextOffset: decoded.nextOffset })!;+ assert.equal(source.slice(observed.content.start, observed.content.end), body);+ assert.equal(source.slice(observed.moments[0]!.range.start, observed.moments[0]!.range.end), '@{beat!}');++ const parsed = parseScript("body", body);+ const anchorId = parsed.tokens[0]!.startAnchorId;+ const changed = companion.adjust({ sourceName: "body", source: body,+ adjustment: { kind: "moment", id: "beat", anchorId } });+ const after = parseScript("body", changed);+ assert.equal(after.moments[0]!.anchorId, anchorId);+ assert.equal(changed.replace('@{beat!}', ''), body.replace('@{beat!}', ''));+ assert.equal(after.serializations.speech, parsed.serializations.speech);+ assert.deepEqual(captionDocument(after, "caption", "story"), captionDocument(parsed, "caption", "story"));++ const projection = companion.project!({ source: { ...observed, companion: companion.id },+ values: decoded.records.flatMap(record => record.value.kind === "inline"+ ? [{ id: record.id, type: record.type, value: record.value.value }] : []),+ anchors: new Map(parsed.semanticIndex.anchors.map((anchor, index) => [anchor.id, index * 3])),+ });+ assert.deepEqual(projection.tokens.map(token => token.text), parsed.tokens.map(token => token.text));+ assert.deepEqual(projection.tokens.map(token => token.range), observed.tokens.map(token => token.range));+});diff --git a/packages/script/README.md b/packages/script/README.mdindex d2def36c..f8966655 100644--- a/packages/script/README.md+++ b/packages/script/README.md@@ -27,8 +27,10 @@ parser is inside a Segment, a valid bare tag such as `<ALICE>` is a Role Cue. Thnot indentation: the compact spelling`<opening><ALICE>I speak first.<BOB>I answer.</opening>` has the same semantic value.-A Role Cue is optional. Text before the first Role Cue is a roleless Turn, and Role state is reset-when every Segment closes; a Role can never leak into the following Segment.+A Role Cue is optional. A Segment without Role Cues contains a roleless Turn. If Roles are used,+the first Cue must precede that Segment's spoken text. Role state resets when the Segment closes;+a Role can never leak into the following Segment. Role labels may use Unicode letters, marks and+numbers; capitalization does not distinguish Roles from Segments.An empty Segment such as `<empty></empty>` (or `<empty/>`) is valid. `empty` is an ordinaryauthor-chosen name, not a reserved keyword. It retains the Segment identity and both boundary anchors@@ -101,7 +103,7 @@ Units; it does not split the Segment, cut the picture or end a Selection.<script id="story"><exchange><HOST> I use it || every day, || since <2012 | twenty twelve>.- <GUEST> Even @{proof} on holiday @{/proof}?+ <GUEST> Even @{proof}on holiday?@{/proof}<HOST> @{answer!} Especially then.</exchange></script>@@ -118,13 +120,18 @@ These units support precise timing and highlighting. A Caption Cue can hold a wh`||` chooses its handoff independently of character counts or visual line wrapping.Annotations do not create speech boundaries. Comments are transparent (`hel<!--note-->lo`-remains `hello`); a postfix attribute or `||` inside a word is invalid. Script analyzes a complete+remains `hello`), including when an attribute follows a comment or zero-width marker:+`hello<!--note-->{emphasis}` and `hello@{beat!}{emphasis}` still annotate `hello`.+An authored space before the attribute remains invalid. A postfix attribute or `||` inside a word+is invalid. Script analyzes a completeprose run before binding these constructs. An explicit Dual correspondence and a speaker/Segmentboundary remain authored structure. Shared Dual groups still expose their internal speech anchors.A Dual display side is literal authored text, including symbols and emoji: `<😀|smile>` and`<.|dot>` have explicit speech correspondence and require no invented speech token for the symbol.A literal-only display is one display surface within that correspondence.+Every Dual needs at least one spoken word on its explicit or shared speech side. `<API|...>` cannot+provide timed correspondence for `API` and is rejected; punctuation and markers are not spoken words.## Display spelling and separatorsdiff --git a/packages/script/src/format.ts b/packages/script/src/format.tsindex 41a420f0..eae70840 100644--- a/packages/script/src/format.ts+++ b/packages/script/src/format.ts@@ -3,38 +3,25 @@ import { canonicalStringify } from "@hypit/protocol";import { ScriptSyntaxError } from "./error.js";import { narrativeValue } from "./narrative.js";import { parseScript } from "./parser.js";--const ROLE = /^[\p{L}\p{M}\p{N}_](?:[\p{L}\p{M}\p{N}_. -]{0,30}[\p{L}\p{M}\p{N}_.-])?$/u;+import type { ParsedSegment } from "./types.js";function compact(value: string): string {return value.replace(/\s+/gu, " ").trim();}-function formatSegment(raw: string, id: string, selfClosing: boolean): string[] {+function formatSegment(source: string, segment: ParsedSegment): string[] {+ const { id, selfClosing, contentRange, atoms } = segment;if (selfClosing) return [`<${id}/>`];- const openEnd = raw.indexOf(">") + 1;- const closeStart = raw.lastIndexOf(`</${id}>`);- const body = raw.slice(openEnd, closeStart);const lines: string[] = [`<${id}>`];const turns: string[] = [];- let chunkStart = 0;- let cursor = 0;- while (cursor < body.length) {- if (body[cursor] !== "<" || body.startsWith("<!--", cursor)) {- cursor += 1;- continue;- }- const end = body.indexOf(">", cursor + 1);- if (end < 0) break;- const inside = body.slice(cursor + 1, end);- if (!inside.includes("|") && ROLE.test(inside)) {- const before = compact(body.slice(chunkStart, cursor));- if (before) turns.push(before);- chunkStart = cursor;- }- cursor = end + 1;+ let chunkStart = contentRange.start;+ for (const atom of atoms) {+ if (atom.kind !== "role") continue;+ const before = compact(source.slice(chunkStart, atom.range.start));+ if (before) turns.push(before);+ chunkStart = atom.range.start;}- const tail = compact(body.slice(chunkStart));+ const tail = compact(source.slice(chunkStart, contentRange.end));if (tail) turns.push(tail);lines.push(...turns.map((turn) => ` ${turn}`));lines.push(`</${id}>`);@@ -64,7 +51,7 @@ export function formatScript(sourceName: string, source: string): string {} else if (output.length) {output.push("");}- output.push(...formatSegment(source.slice(start, end), segment.id, segment.selfClosing));+ output.push(...formatSegment(source, segment));cursor = end;}const tail = formatOutside(source.slice(cursor));diff --git a/packages/script/src/manifest.ts b/packages/script/src/manifest.tsindex 45d41fa6..38d03ed6 100644--- a/packages/script/src/manifest.ts+++ b/packages/script/src/manifest.ts@@ -64,9 +64,9 @@ export const scriptMarkupSurfaces = ["A Script requires at least one Segment, and natural-language text is refused outside a Segment.","A Segment is opened by its own lower-case name and closed by that exact name, or written self-closing as `<pause/>`; the name is the Segment id, must be unique within the Script, and `script` is reserved. Segments do not nest.","A Role Cue such as `<HOST>` is a bare tag inside a Segment with no close; its turn runs until the next Cue or the end of the Segment, and a Cue may not follow unowned speech in the same Segment. Role state resets when the Segment closes.",- "Dual Text is written `<display | speech>`: the left side reaches Caption and the right side reaches dialogue and speech. `<display|>` inherits speech from the displayed prose and forms the same complete alignment unit; its word times remain individual. `<|speech>` speaks without displaying. Both sides empty is invalid.",+ "Dual Text is written `<display | speech>`: the left side reaches Caption and the right side reaches dialogue and speech. `<display|>` shares the displayed prose with speech and forms the same complete alignment unit; its word times remain individual. `<|speech>` speaks without displaying. The explicit or shared speech must contain a spoken word; markers and punctuation alone supply no correspondence.","Inside Dual Text, semantic markers belong to the source of spoken text: the explicit right side, or the shared left side when speech is omitted. Display attributes remain visual metadata and never enter spoken text.",- "A flat token attribute follows a complete display token as `{name}` or `{name=value}`; multiple attributes use one comma-separated block. Attributes do not nest, do not carry timing, and never split a Dual Alignment Unit.",+ "A flat token attribute follows a complete display token as `{name}` or `{name=value}`; multiple attributes use one comma-separated block. Zero-width markers and ordinary-prose comments do not interrupt that attachment; prose whitespace does. Attributes do not nest, do not carry timing, and never split a Dual Alignment Unit.","Selection and Moment markers are fully enclosed in `@{...}` with all sigils inside. They are zero-width, share one name namespace, and may not split a speech token. Surrounding prose spaces remain content; do not add spaces to delimit a name:",["| Marker | Meaning |",diff --git a/packages/script/src/parser.ts b/packages/script/src/parser.tsindex 7ca9cd67..86711db3 100644--- a/packages/script/src/parser.ts+++ b/packages/script/src/parser.ts@@ -492,10 +492,10 @@ export function parseScript(if (!shared && raw[index] === "{") fail("SCRIPT_DUAL_SPEECH_ATTRIBUTE", "Display attributes belong to the display side; escape literal braces in speech.", absoluteStart + index);if (shared && raw[index] === "{") {const before = raw.slice(partStart, index);- if (!before || /\s$/u.test(before)) {+ addLiteral(before, absoluteStart + partStart);+ if (!runText || /\s$/u.test(runText)) {fail("SCRIPT_ATTRIBUTE_TARGET", "A token attribute must immediately follow a display token.", absoluteStart + index);}- addLiteral(before, absoluteStart + partStart);const block = parseAttributeBlock(raw.slice(index), absoluteStart + index);runAttributes.push({ position: runText.length, offset: absoluteStart + index,end: absoluteStart + index + block.length, attributes: block.attributes });@@ -517,20 +517,20 @@ export function parseScript(addLiteral(raw.slice(partStart), absoluteStart + partStart);const display = caption ?? spokenParts.join("");const sharedMarks = finishLexicalRun();- if (shared && tokens.length === startToken) {- fail("SCRIPT_DUAL_EMPTY", "Dual Text with omitted speech must contain spoken text on its display side.", absoluteStart);- }- if (tokens.length > startToken) {- addCaptionRegion(- display,- current!.id,- startToken,- tokens.length,- cleanProjection(display) ? "alias" : "hidden",- { start: sourceOffset + absoluteStart, end: sourceOffset + absoluteStart + raw.length },- shared ? sharedMarks : marks,- );+ if (tokens.length === startToken) {+ fail("SCRIPT_DUAL_EMPTY", shared+ ? "Dual Text with omitted speech must contain spoken text on its display side."+ : "Dual Text speech side must contain a spoken word, not only markers or punctuation.", absoluteStart);}+ addCaptionRegion(+ display,+ current!.id,+ startToken,+ tokens.length,+ cleanProjection(display) ? "alias" : "hidden",+ { start: sourceOffset + absoluteStart, end: sourceOffset + absoluteStart + raw.length },+ shared ? sharedMarks : marks,+ );};const closeCurrent = (end: number, selfClosing: boolean, contentEnd = end): void => {@@ -626,18 +626,13 @@ export function parseScript(const speech = inside.slice(pipe + 1);if (!speech.trim()) {consumeSpeechSide(inside.slice(0, pipe), offset + 1, undefined);- finishLexicalRun();offset = end + 1;continue;}assertDualDisplayLiteral(inside.slice(0, pipe), offset + 1);const markedDisplay = parseMarkedDisplay(inside.slice(0, pipe), offset + 1);const display = markedDisplay.display;- if (!speech.replace(/@\{[^{}]*\}/gu, "").trim()) {- fail("SCRIPT_DUAL_EMPTY", "Dual Text speech side must not be empty.", offset);- }consumeSpeechSide(speech, offset + pipe + 2, display, markedDisplay.marks);- finishLexicalRun();offset = end + 1;continue;}@@ -674,7 +669,7 @@ export function parseScript(for (const piece of literalPieces(raw, textStart)) addText(piece.value, piece.value, piece.start, piece.end, true, piece.positions);if (source[offset] === "{") {const block = parseAttributeBlock(source.slice(offset), offset);- if (!raw || /\s$/u.test(raw)) {+ if (!runText || /\s$/u.test(runText)) {fail("SCRIPT_ATTRIBUTE_TARGET", "A token attribute must immediately follow a display token.", offset);}runAttributes.push({ position: runText.length, offset, end: offset + block.length, attributes: block.attributes });diff --git a/packages/script/src/surface.ts b/packages/script/src/surface.tsindex 80d0f46f..fdc8a261 100644--- a/packages/script/src/surface.ts+++ b/packages/script/src/surface.ts@@ -24,6 +24,10 @@ function findClose(input: ScriptSurfaceInput): { readonly start: number; readonlconst close = `</${input.tag}>`;let cursor = input.contentStart;while (cursor < input.source.length) {+ if (input.source[cursor] === "\\") {+ cursor += 2;+ continue;+ }if (input.source.startsWith("<!--", cursor)) {const commentEnd = input.source.indexOf("-->", cursor + 4);if (commentEnd < 0) {@@ -33,9 +37,7 @@ function findClose(input: ScriptSurfaceInput): { readonly start: number; readonlcontinue;}if (input.source.startsWith(close, cursor)) {- let slashes = 0;- for (let before = cursor - 1; before >= 0 && input.source[before] === "\\"; before -= 1) slashes += 1;- if (slashes % 2 === 0) return { start: cursor, end: cursor + close.length };+ return { start: cursor, end: cursor + close.length };}cursor += 1;}diff --git a/packages/script/src/types.ts b/packages/script/src/types.tsindex 123dd187..ca369d04 100644--- a/packages/script/src/types.ts+++ b/packages/script/src/types.ts@@ -35,7 +35,7 @@ export type ParsedSegment = NarrativeSegment & {readonly index: number;readonly atoms: readonly ParsedAtom[];readonly range: SourceRange;- /** Exact body range between the Segment tags, used only for source-preserving marker edits. */+ /** Exact body range between Segment tags for Script-owned source edits and formatting. */readonly contentRange: SourceRange;readonly selfClosing: boolean;};diff --git a/packages/script/test/markup-integration.test.ts b/packages/script/test/markup-integration.test.tsindex c519840c..98527504 100644--- a/packages/script/test/markup-integration.test.ts+++ b/packages/script/test/markup-integration.test.ts@@ -12,6 +12,7 @@ import {scriptManifest,scriptMarkupSurfaces,scriptModuleRef,+ parseScript,} from "@hypit/script";import {MarkupFrontendError,@@ -35,6 +36,14 @@ function scriptContext() {} as const;}+test("Script's raw boundary scanner respects escapes before comments and closing tags", async () => {+ const body = String.raw`<line>Show \<!-- and \</script> literally. \\<!-- </script> is a comment --> Done.</line>`;+ const source = `<svml><import from="@hypit/script@1"/><script id="story">${body}</script></svml>`;+ const result = await decodeMarkup({ name: "escapes.svml", text: source }, scriptContext());+ const speech = result.records.find(record => record.id === "story.segment.line.speech")!;+ assert.deepEqual(speech.value, { kind: "inline", value: { value: parseScript("body", body).serializations.speech } });+});+test("Script teaches Markup <script> only through its imported Manifest", async () => {const result = await decodeMarkup({diff --git a/packages/script/test/narrative-views.test.ts b/packages/script/test/narrative-views.test.tsindex 60620874..d8aed433 100644--- a/packages/script/test/narrative-views.test.ts+++ b/packages/script/test/narrative-views.test.ts@@ -20,6 +20,20 @@ function authored() {return narrativeValue(parseScript("views.svml", body), "story") as unknown as Narrative;}+test("formatting takes Role Cue boundaries from parsed source, including Unicode roles", () => {+ const cases = [+ [String.raw`<one>Show \<HOST> literally.</one>`, String.raw` Show \<HOST> literally.`],+ ['<one>hello<!-- <HOST> -->world.</one>', ' hello<!-- <HOST> -->world.'],+ ['<one><host>Then speak. <진행자>안녕하세요.</one>', ' <host>Then speak.\n <진행자>안녕하세요.'],+ ] as const;+ for (const [source, content] of cases) {+ const formatted = formatScript("format", source);+ assert.equal(formatted, `<one>\n${content}\n</one>\n`);+ assert.deepEqual(narrativeValue(parseScript("format", formatted), "story"),+ narrativeValue(parseScript("format", source), "story"));+ }+});+test("omitted speech shares display prose while retaining ordinary Narrative and caption exports", () => {for (const [short, expanded] of [['把<动效|><组件化|>。|| <直接复用|>。', '把<动效|动效><组件化|组件化>。|| <直接复用|直接复用>。'],diff --git a/packages/script/test/prose-boundaries.test.ts b/packages/script/test/prose-boundaries.test.tsindex 841fb801..14828280 100644--- a/packages/script/test/prose-boundaries.test.ts+++ b/packages/script/test/prose-boundaries.test.ts@@ -27,6 +27,29 @@ test("comments do not divide words, and source edits retain the comment", () =>assert.equal(changed, '<line>@{beat!}hel<!-- note -->lo 한<!-- 설명 -->글. </line>');});+test("display attributes follow the complete prose across zero-width annotations", () => {+ for (const body of [+ 'hello<!-- note -->{emphasis} world.',+ 'hello@{beat!}{emphasis} world.',+ '<hello@{beat!}{emphasis} world.|>',+ ]) {+ const parsed = parse(body);+ const document = captionDocument(parsed, "caption", "story");+ assert.equal(document.words.map(word => word.separatorBefore + word.text).join(""), "hello world.");+ assert.deepEqual(document.words[0]!.attributes, [{ name: "emphasis", value: true }]);+ }+ for (const body of ['hello <!-- note -->{emphasis}', 'hello @{beat!}{emphasis}', '<hello @{beat!}{emphasis}|>']) {+ assert.throws(() => parse(body), /SCRIPT_ATTRIBUTE_TARGET/u);+ }+});++test("a Dual's explicit speech must supply correspondence for its display", () => {+ for (const body of ['<API|...>', '<hello|@{beat!}!!!>', '<|!!!>', '<API|@{beat!}>']) {+ assert.throws(() => parse(body), /SCRIPT_DUAL_EMPTY/u);+ }+ assert.equal(caption('<😀|smile> <API|A P I>'), '😀 API');+});+test("Dual display spelling does not require speech characters", () => {for (const [body, expected] of [['<😀|smile>', '😀'], ['<❤️|love>', '❤️'], ['<.|dot>', '.'],diff --git a/packages/source/README.md b/packages/source/README.mdindex b00abb49..4cb0d300 100644--- a/packages/source/README.md+++ b/packages/source/README.md@@ -9,5 +9,5 @@ It recognizes exactly one mandatory bounded Header:```The Header selects an exact trusted Frontend. There is no suffix dispatch and no default parser.-The package masks the Header while preserving character offsets, but does not recognize imports,+The package masks the Header while preserving UTF-16 source offsets and line breaks, but does not recognize imports,XML, Script, Recipes, Run syntax or domain Types. Those belong to the selected Frontend.diff --git a/packages/source/src/header.ts b/packages/source/src/header.tsindex f5ca4b5e..061edbaf 100644--- a/packages/source/src/header.ts+++ b/packages/source/src/header.ts@@ -75,6 +75,7 @@ export function parseSourceHeader(sourceName: string, text: string): SourceHeade/** Preserve every original offset while making the Header ordinary whitespace to body Frontends. */export function maskSourceHeader(text: string, header: SourceHeader): string {- const prefix = text.slice(0, header.end).replace(/[^\r\n]/gu, " ");+ // Source ranges use UTF-16 offsets: replace each code unit, not each code point.+ const prefix = text.slice(0, header.end).replace(/[^\r\n]/g, " ");return `${prefix}${text.slice(header.end)}`;}diff --git a/packages/source/test/header.test.ts b/packages/source/test/header.test.tsindex 155df8df..9647b186 100644--- a/packages/source/test/header.test.ts+++ b/packages/source/test/header.test.ts@@ -17,6 +17,15 @@ test("Source Header explicitly selects one Frontend and masking preserves offsetassert.equal(masked.slice(0, header.end).trim(), "");});+test("Header masking preserves UTF-16 offsets for a non-BMP Frontend request", () => {+ const text = '<?svml using="project.𠮷@1"?>\r\n<body/>\r\n';+ const header = parseSourceHeader("project.svml", text);+ const masked = maskSourceHeader(text, header);+ assert.equal(masked.length, text.length);+ assert.equal(masked.slice(header.end), '\r\n<body/>\r\n');+ assert.equal(masked.indexOf('<body/>'), text.indexOf('<body/>'));+});+test("Source Header accepts a UTF-8 BOM but no implicit or duplicate Frontend", () => {assert.equal(parseSourceHeader("bom.svs", '\ufeff<?svml using="@hypit/svs@1"?>\n<sheet/>').using,diff --git a/packages/studio/README.md b/packages/studio/README.mdindex d85019b0..d23cc687 100644--- a/packages/studio/README.md+++ b/packages/studio/README.md@@ -1,5 +1,13 @@# Hypit Studio+For direct picture inspection, `hypit snapshot --studio <studio-url>` reads the current compiled+`HyperframesDocument` from `GET /__studio/document` and its existing `/__studio/material/<resource>`+resources. `GET /__studio/visual.html` exposes the same materialized picture without the interactive+Studio playback shim or audio. Both representations come from the same compilation as the displayed+preview. The snapshot invocation uses the selected Runtime Profile's frame Provider and creates no+Build. During a pending Source compilation the export route reports that state; a failed update+reports its error instead of returning the previous picture as current.+The single official Web Studio for SVML. It opens an explicit Run Source,traces its Film or Render target back to the semantic and visual projectionsStudio can edit, runs deterministic Producers and explicitly permitted transient Needs, and composites the@@ -159,6 +167,11 @@ the selected entity. A reference can resolve to a shared Frame or Recipe, so onemay affect several consumers. Structured fields save together when editing ends and the value is complete; missing required values stay in the editor with a completion hint.Check save status; source conflicts reject stale edits rather than overwrite newer files.+Script source ranges come from its raw Surface and Companion. Marker edits use Script's parsed+anchors and preserve unrelated prose, whitespace and word attributes; the displayed timeline words+are not a replacement text source. Recipe parameter reads use the same Source Header preparation+as compilation, preserving UTF-16 offsets for the exact property being edited.+The Timeline owns the editor's complete range; displayed objects do not extend it. Take placementand complete extent are reference information in Studio.diff --git a/packages/studio/src/parameters.ts b/packages/studio/src/parameters.tsindex e1d69cb0..b7a550bf 100644--- a/packages/studio/src/parameters.ts+++ b/packages/studio/src/parameters.ts@@ -17,6 +17,7 @@ import type {} from "@hypit/studio-adapter";import { parseSvs } from "@hypit/svs";import { parseOpeningTag } from "@hypit/markup";+import { prepareAuthorSource } from "@hypit/elaborator";import { parameterControlForSchema, parameterRecordSchema } from "./parameter-values.js";import type { CanonicalValue } from "@hypit/protocol";@@ -132,12 +133,6 @@ function sourceAbsolute(root: string, path: string, base?: string): string {return resolve(directory, path);}-function svsText(source: string): string {- const header = /^\s*<\?svml[\s\S]*?\?>/u.exec(source);- if (header === null) return source;- return `${header[0].replace(/[^\r\n]/gu, " ")}${source.slice(header[0].length)}`;-}-function recipeParameters(input: {readonly root: string;readonly files: readonly StudioSourceFile[];@@ -176,7 +171,8 @@ function recipeParameters(input: {const source = sourceFor(input.root, imported.source, input.files, input.current.path);if (source === undefined || source.language !== "svs") return [];const recipePath = parts.join(".");- const parsed = parseSvs(source.path, svsText(source.text));+ const prepared = prepareAuthorSource({ id: source.path, name: source.path, text: source.text });+ const parsed = parseSvs(source.path, prepared.text);const recipe = parsed.recipes.find((item) => item.value.path === recipePath);if (recipe === undefined) return [];return input.recipe.bindings.flatMap((declaration): readonly StudioSourceBinding[] => {diff --git a/packages/studio/src/preview/render.ts b/packages/studio/src/preview/render.tsindex 37c0263f..7a79e443 100644--- a/packages/studio/src/preview/render.ts+++ b/packages/studio/src/preview/render.ts@@ -1,5 +1,6 @@import type { AudioTrack, Composition } from "@hypit/composition";import { compileHyperframesDocument, materializeHyperframesHtml } from "@hypit/hyperframes";+import type { HyperframesDocument } from "@hypit/hyperframes";import type { ProgramSpace } from "@hypit/program-space";import { injectRuntimeShim } from "./runtime-shim.js";@@ -19,6 +20,11 @@ export type RenderInput = {* material all come from the projection selected by the Run.*/export function renderPreview(input: RenderInput): string {+ return renderStudioProgramme(input).preview;+}++/** The same compiled picture serves immediate frame capture and interactive playback. */+export function renderStudioProgramme(input: RenderInput): { readonly document: HyperframesDocument; readonly html: string; readonly preview: string } {const document = compileHyperframesDocument(input.composition, input.space);const html = materializeHyperframesHtml(document, (artifact) => {// The only Artifacts a preview can reference are files the author already@@ -51,5 +57,5 @@ export function renderPreview(input: RenderInput): string {fadeInSamples: clip.fadeInSamples, fadeOutSamples: clip.fadeOutSamples,}))}"></audio>`;}).join("");- return injectRuntimeShim(html, audio);+ return { document, html, preview: injectRuntimeShim(html, audio) };}diff --git a/packages/studio/src/server.ts b/packages/studio/src/server.tsindex a0fc7448..c94ef086 100644--- a/packages/studio/src/server.ts+++ b/packages/studio/src/server.ts@@ -81,6 +81,8 @@ class StudioMutationRejected extends Error {}export function studioPlugin(options: StudioPluginOptions): Plugin {let snapshot: StudioSnapshot | undefined;+ let visualHtml: string | undefined;+ let visualDocument: import("@hypit/hyperframes").HyperframesDocument | undefined;let failure: StudioFailure | undefined;let material: ReadonlyMap<string, ServedFile> = new Map();let revision = 0;@@ -159,6 +161,8 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {if (attempt !== requestedRevision) return;revision = attempt;snapshot = result.snapshot;+ visualHtml = result.visualHtml;+ visualDocument = result.document;material = result.material;failure = undefined;if (notify) server?.ws.send({ type: "custom", event: "studio:snapshot", data: snapshot });@@ -593,6 +597,28 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {next();return;}+ if (url.pathname === "/__studio/visual.html" || url.pathname === "/__studio/document") {+ void (async () => {+ if (timer !== undefined || publishing > 0) {+ json(response, 409, { error: "Studio is compiling a Source change; capture after the updated preview is ready." });+ return;+ }+ if (snapshot === undefined && failure === undefined) await publish(++requestedRevision);+ if (failure !== undefined || visualHtml === undefined) {+ json(response, 500, failure ?? { error: "Studio has no compiled picture." });+ return;+ }+ if (url.pathname === "/__studio/document") {+ json(response, 200, visualDocument);+ return;+ }+ response.statusCode = 200;+ response.setHeader("content-type", "text/html; charset=utf-8");+ response.setHeader("cache-control", "no-store");+ response.end(request.method === "HEAD" ? undefined : visualHtml);+ })();+ return;+ }if (url.pathname === "/__studio/session") {void (async () => {if (snapshot === undefined && failure === undefined) {diff --git a/packages/studio/src/session.ts b/packages/studio/src/session.tsindex 564778f7..2e757ef2 100644--- a/packages/studio/src/session.ts+++ b/packages/studio/src/session.ts@@ -9,7 +9,7 @@ import type { ServedFile } from "./compile.js";import type { StudioDomain } from "./domain.js";import type { Observations } from "./observe.js";import { preview } from "./programme.js";-import { renderPreview } from "./preview/render.js";+import { renderStudioProgramme } from "./preview/render.js";import type { RunPlan } from "./run.js";import type { StudioSnapshot } from "./shared.js";import type { StudioCompanionRegistry } from "./studio-registry.js";@@ -47,6 +47,8 @@ function sourceFiles(run: RunPlan): readonly StudioSourceFile[] {export type StudioSession = {readonly snapshot: StudioSnapshot;+ readonly document: import("@hypit/hyperframes").HyperframesDocument;+ readonly visualHtml: string;readonly material: ReadonlyMap<string, ServedFile>;readonly observations: Observations;readonly projections: readonly StudioViewRequirement[];@@ -77,7 +79,7 @@ export async function readStudioSession(input: {projections: inspection.projections,...(input.transientExecution === undefined ? {} : { transientExecution: input.transientExecution }),});- const rendered = renderPreview({+ const rendered = renderStudioProgramme({composition: built.composition,space: built.space as never,served: new Set(built.served.keys()),@@ -85,6 +87,8 @@ export async function readStudioSession(input: {const text = readFileSync(input.run.authorSource, "utf8");const files = sourceFiles(input.run);return {+ document: rendered.document,+ visualHtml: rendered.html,snapshot: snapshot(input.registry, built, {revision: input.revision,path: input.sourcePath ?? input.run.authorSource,@@ -99,7 +103,7 @@ export async function readStudioSession(input: {},canvas: built.canvas,frameRate: built.frameRate,- preview: { kind: "hyperframes", srcdoc: rendered },+ preview: { kind: "hyperframes", srcdoc: rendered.preview },workspaceRoot: input.workspaceRoot,sourceFiles: files,surfaces: input.domain.surfaces,diff --git a/packages/studio/src/ui/syntax.ts b/packages/studio/src/ui/syntax.tsindex b83fa392..7f0a2b33 100644--- a/packages/studio/src/ui/syntax.ts+++ b/packages/studio/src/ui/syntax.ts@@ -1,9 +1,8 @@/*** A tokenizer for SVML's own surface syntax.*- * SVML has a small, closed grammar — tags, quoted strings, whole-value- * references, and Script prose with markers — so it is tokenized directly rather- * than through a general highlighter that has no grammar for it. The Script+ * Recognize the common Markup shell and Script prose for highlighting, without+ * validating package-owned Surfaces. The Script* markers are the point: `@{claim} … @{/claim}` is what a Media Item binds to, so it* has to read as a distinct thing from an ordinary attribute.*@@ -105,8 +104,7 @@ export function tokenizeSvml(source: string): readonly Token[] {cursor = nameStart + name[0].length;cursor = tokenizeAttributes(source, cursor, push);- // Script is the language's one Raw Surface: its body is prose with- // markers, not markup, and must be scanned by different rules.+ // Script's Raw Surface has its own prose grammar.if (!closing && localName(name[0]) === "script" && source[cursor - 2] !== "/") {cursor = tokenizeScriptBody(source, cursor, name[0], push);}@@ -167,6 +165,7 @@ function tokenizeAttributes(source: string, from: number, push: Push): number {function tokenizeScriptBody(source: string, from: number, tag: string, push: Push): number {const close = `</${tag}>`;let cursor = from;+ let inSegment = false;while (cursor < source.length) {if (source[cursor] === "\\") { cursor += 2; continue; }if (source.startsWith(close, cursor)) {@@ -199,14 +198,16 @@ function tokenizeScriptBody(source: string, from: number, tag: string, push: Pus}const closing = source[cursor + 1] === "/";const nameStart = cursor + (closing ? 2 : 1);- const name = NAME.exec(source.slice(nameStart));- if (name === null) { cursor += 1; continue; }const end = source.indexOf(">", nameStart);const stop = end < 0 ? source.length : end + 1;+ const selfClosing = end >= 0 && source[end - 1] === "/";+ const nameEnd = end < 0 ? stop : end - (selfClosing ? 1 : 0);push(cursor, nameStart, "punct");- // An upper-case tag inside Script is a Role Cue, not a Segment.- push(nameStart, nameStart + name[0].length, /^[A-Z]/u.test(name[0]) ? "role" : "tag");- push(nameStart + name[0].length, stop, "punct");+ // Context distinguishes Segments from Role Cues, regardless of language or case.+ push(nameStart, nameEnd, inSegment && !closing ? "role" : "tag");+ push(nameEnd, stop, "punct");+ if (closing) inSegment = false;+ else if (!inSegment && !selfClosing) inSegment = true;cursor = stop;continue;}diff --git a/packages/studio/test/parameters.test.ts b/packages/studio/test/parameters.test.tsindex b1e8d368..d9bb7403 100644--- a/packages/studio/test/parameters.test.ts+++ b/packages/studio/test/parameters.test.ts@@ -279,7 +279,8 @@ test("nested declared references reach the font attribute, not the referring Stytest("a derived entity follows its actual Style and Companion-owned Recipe presentation", () => {const main = "<scene:Track id=\"captions\" layout={baseline-layout}/>";- const sheet = `<sheet version="1">+ const sheet = `<?svml using="@hypit/svs@1"?>+<sheet version="1">caption.alt { x: 0.4; handoff: overlap; colors: ["#FF3F56", "#FFA72D"]; }</sheet>`;const colors = { kind: "array", minItems: 1, items: { kind: "string", format: "color" } } as const;diff --git a/packages/studio/test/script-syntax.test.ts b/packages/studio/test/script-syntax.test.tsindex d0a036a1..c3345a79 100644--- a/packages/studio/test/script-syntax.test.ts+++ b/packages/studio/test/script-syntax.test.ts@@ -1,6 +1,18 @@import assert from "node:assert/strict";import test from "node:test";import { tokenizeSvml } from "../src/ui/syntax.js";+import { parseScript } from "@hypit/script";++test("Studio distinguishes Segments and Role Cues by context across writing systems", () => {+ const body = '<one><host>Hello. <진행자>안녕하세요. <主持人>你好。</one><pause/><two>Goodbye.</two>';+ parseScript("highlight", body);+ const source = `<script id="s">${body}</script>`;+ const tokens = tokenizeSvml(source);+ assert.deepEqual(tokens.filter(token => token.kind === "role")+ .map(token => source.slice(token.start, token.end)), ["host", "진행자", "主持人"]);+ assert.deepEqual(tokens.filter(token => token.kind === "tag")+ .map(token => source.slice(token.start, token.end)), ["script", "one", "one", "pause", "two", "two", "script"]);+});test("Studio distinguishes delimited Script markers from properties, escapes and generation references", () => {const source = '<script id="s"><line>@{a}hello{emphasis}@{/a} <New @{beat!}York|> <3D|three @{d!}D> \\@\\{literal\\}</line></script><prompt>@image1</prompt>';diff --git a/packages/temporal-markup/EDITING.md b/packages/temporal-markup/EDITING.mdindex 83cc9381..32105826 100644--- a/packages/temporal-markup/EDITING.md+++ b/packages/temporal-markup/EDITING.md@@ -164,7 +164,7 @@ write target. The `fixed` case means no temporal gesture writes that endpoint, nparameter editing is forbidden.- `@hypit/script` owns tokenization, anchor identities, legal marker sites, and structural writeback.- It normalizes equivalent marker whitespace, retains punctuation and attributes, writes coincident+ It relocates markers without rewriting unrelated prose whitespace, retains punctuation and attributes, writes coincidentmarkers together, and preserves all unrelated relationships and caption information.- `@hypit/temporal-markup` owns the interpretation of each time form and declares its write targets.Direct semantic references expose semantic targets; quoted time expressions expose parameterdiff --git a/packages/video-cli/README.md b/packages/video-cli/README.mdindex 18576d97..155d4b9b 100644--- a/packages/video-cli/README.md+++ b/packages/video-cli/README.md@@ -1,8 +1,8 @@# `@hypit/video-cli`Official video command application. It selects the Markup compiler Host and supplies one editable-starter Runtime Profile. The CLI still imports no Provider or Store implementation; installed packages-are activated only by explicit Source imports or Profile `use` entries.+starter Runtime Profile. Execution Endpoints are selected by Profile `use` entries; Source imports+activate author packages. Immediate tools own their temporary input/output resource storage.Every Frontend, Surface, deterministic Producer and Validator is activated from Source imports.Installing a new author package therefore does not require a video CLI or Core release. Source@@ -67,9 +67,35 @@ to the chosen file. `measure` estimates a passage locally:```bashhypit transcribe reference.mp4 --to notes/reference.transcript.json --language en+hypit transcribe assets/recorded-voice.wav --to notes/voice.transcript.json --language enhypit measure main.svml --segment hook --language en --pace normal --rounding round```+`snapshot` follows the same immediate invocation model for picture inspection. Prefer it for+existing production states and motion sequences, keeping Studio for playback with sound and Builds+for encoded delivery:++```bash+hypit snapshot --studio http://localhost:5191 --at-frame 240,255,269 --to evidence/states+hypit snapshot --studio http://localhost:5191 --start-frame 240 --end-frame-exclusive 270 \+ --grid 4x3 --cell 480 --to evidence/motion+hypit snapshot ./picture/index.html --at-frame 240 --to evidence/detail+```++`--studio` reads Studio's current compiled document and its declared resources; a path or HTML URL+reads materialized HTML with inline scripts/styles and directly addressed media/fonts. The Profile's+`@hypit/render-hyperframes@1#render-frames` Endpoint returns PNGs in selected-frame order.+`--runtime` and `--workspace` select the environment just as for `transcribe`. The call streams+resources through a temporary `FileResourceStore`, writes full-size PNGs and optional grid pages,+then releases that temporary storage. `--to` names a new directory. `--json` reports paths and original+frame positions. Grid labels remain outside the picture. No Build, Worker receipt or video encoding+is created. Provider-owned browser preparation is unchanged.++`media frames --every-frame` and `media tiles --every-frame` decode every source frame in a selected+half-open seconds interval once. Native timestamps, including variable frame rate, are read from+decoder PTS and time base. `tiles --ranges <json> --every-frame` decodes each listed interval and+paginates its images. `--transcript` adds word context. This native path uses no FPS resampling.+For `transcribe`, set `--language` to an explicit lowercase two- or three-letter spoken language code,such as `en`, `zh` or `ko`. The selected service owns which languages it can align. Chinese speech uses `zh`, includingChinese speech containing English names. The request selects the recognition language and@@ -106,6 +132,9 @@ prints what a Source may write:```bashhypit media probe reference.mp4hypit media cut reference.mp4 --start 12 --end 19.5 --label-time --to notes/hook.mp4+hypit media cut assets/talk.mp4 --start 12 --end 19.5 --to assets/opening.mp4+hypit media cut assets/talk.mp4 --keep 12:15.5 --keep 16:19.5 --to assets/opening-edited.mp4+hypit media cut assets/narration.wav --keep 0.3:4.1 --keep 4.6:9.2 --to assets/narration-edited.wavhypit media frames reference.mp4 --at 12.4,13.1 --label-time --to notes/hook-frameshypit media tile reference.mp4 --start 12 --end 19.5 --to notes/hook-grid.jpghypit media tile reference.mp4 --at 12.4,13.1,14.8 --columns 3 --to notes/exact-grid.jpg@@ -119,7 +148,21 @@ hypit vocabulary @hypit/media-pipeline --tag StillVideohypit vocabulary --visual text```-`cut` isolates the requested interval and can visibly overlay source time on the evidence copy.+`probe` accepts audio-only files as well as video. `cut` keeps one interval using `--start` and+`--end`, or joins explicitly retained, ordered, non-overlapping intervals using repeated+`--keep start:end` in source seconds. The latter is useful for removing gaps inside one recorded+performance; it does not decide where Script Segments belong. Video retains its available picture+and sound together (MP4 is a useful output container); audio-only outputs PCM WAV. A silent source+video stays silent. The+`--json` reports the source intervals, their nominal positions on the new local clock, and the+measured output duration; actual frame and sample boundaries can differ slightly from the nominal+positions. It writes a new file and refuses to+overwrite an existing one. `--label-time` retains its single-video-interval role: it visibly+overlays source time on an inspection copy, not on the clean production media.++`transcribe` also accepts audio or video. Its transcript refers to the *input file's* clock. A+cut or joined file has a new clock; use the final recorded performance and its Script in the+Build's semantic preparation rather than treating source transcript timestamps as final timing.`frames` writes one JPEG per requested time, selecting the first decoded frame at or after it.Visible frame labels use that frame's actual timestamp, as do the labels below each `tile` cell.Sampling is shared by `frames`, `tile` and `tiles`:@@ -149,7 +192,7 @@ and its Endpoint remain separate. `boundaries` reports adjacent-framechange candidates and their measured scores; it does not suppress short changes or call them shots.`prepare-fetch` explicitly prepares the locked downloader environment; `fetch` requires it andturns a link into a file with the pinned yt-dlp; [the downloader package](../yt-dlp/README.md)-owns its dependencies, download choices and file handling. Commands that create evidence write only+owns its dependencies, download choices and file handling. Commands that create files write onlywhat `--to` names and refuse to overwrite. `vocabulary` reads the installedmanifests: every package with its tags and models, or one package's Surfaces with their attributes,children and example, or the value shapes a drawing Producer must emit.diff --git a/packages/video-cli/package.json b/packages/video-cli/package.jsonindex 54c45b2f..530471bf 100644--- a/packages/video-cli/package.json+++ b/packages/video-cli/package.json@@ -18,6 +18,7 @@"@hypit/driver-node": "workspace:*","@hypit/estimate": "workspace:*","@hypit/generation": "workspace:*",+ "@hypit/hyperframes": "workspace:*","@hypit/markup": "workspace:*","@hypit/model-kit": "workspace:*","@hypit/package-loader-node": "workspace:*",@@ -28,6 +29,8 @@"@hypit/provider-monid": "workspace:*","@hypit/provider-pollo": "workspace:*","@hypit/provider-tokendance": "workspace:*",+ "@hypit/render-hyperframes": "workspace:*",+ "@hypit/resource-store-fs": "workspace:*","@hypit/runtime": "workspace:*","@hypit/runtime-kit": "workspace:*","@hypit/runtime-host-node": "workspace:*",diff --git a/packages/video-cli/src/cli.ts b/packages/video-cli/src/cli.tsindex 661c70f8..da2b0e21 100644--- a/packages/video-cli/src/cli.ts+++ b/packages/video-cli/src/cli.ts@@ -4,6 +4,7 @@ import type { CliIo } from "@hypit/cli";import { creationCommands, isCreationCommand, writeCreationHelp } from "./creation.js";import { isMediaCommand, mediaCommands, writeMediaHelp } from "./media.js";import { writeVocabularyHelp } from "./vocabulary.js";+import { writeSnapshotHelp } from "./snapshot.js";import { writeCaptureHelp } from "./capture.js";import { runVersionCli, writeVersionHelp } from "./version.js";import { acceptSecretBytes } from "./secret-input.js";@@ -66,6 +67,7 @@ async function main(): Promise<void> {const topic = argv[0] === "help" ? argv[1]: argv[0] === "--help" ? undefined: argv.includes("--help") ? argv[0] : undefined;+ if (topic === "snapshot") { writeSnapshotHelp(io); return; }if (topic === "version") { writeVersionHelp(io); return; }if (isCreationCommand(topic)) {writeCreationHelp(io, topic);@@ -87,7 +89,7 @@ async function main(): Promise<void> {writeCliHelp(io, topic);if (topic === undefined) {io.write(`\nInstallation\n version [--check] [--registry <url>] [--json]\n\nCreation tools (one request through the selected Runtime Profile, no Build)\n${- creationCommands.map((item) => ` ${item}`).join("\n")}\n hypit help <tool> for each\n`+ [...creationCommands, "snapshot"].map((item) => ` ${item}`).join("\n")}\n hypit help <tool> for each\n`+ `\nStudio\n studio --run <build.svrun>\n hypit studio --help for session options\n\nPreparation (local tools and project files)\n media ${mediaCommands.join(" | ")}\n capture screenshot | run | install-browser\n vocabulary\n hypit help media, hypit help capture, hypit help vocabulary\n`);}return;diff --git a/packages/video-cli/src/creation.ts b/packages/video-cli/src/creation.tsindex ae98b8db..e02ee99d 100644--- a/packages/video-cli/src/creation.ts+++ b/packages/video-cli/src/creation.ts@@ -150,7 +150,7 @@ function capabilityName(capability: CapabilityRef): string {}/** Which Endpoint will serve this call and where its Provider publishes prices, before spending. */-async function selectedProvider(host: CreationHost, need: Need, profile: string): Promise<RuntimeHostCapabilityProvider> {+export async function selectedProvider(host: CreationHost, need: Need, profile: string): Promise<RuntimeHostCapabilityProvider> {const [provider] = await host.providers([{request: need.id,capability: need.capability,@@ -176,7 +176,7 @@ function priceLine(provider: RuntimeHostCapabilityProvider): string {: provider.pricing.kind === "local" ? "local, no Provider charge" : provider.pricing.url;}-function providerView(provider: RuntimeHostCapabilityProvider) {+export function providerView(provider: RuntimeHostCapabilityProvider) {return {endpoint: provider.endpoint ?? null,use: provider.use ?? null,@@ -184,7 +184,7 @@ function providerView(provider: RuntimeHostCapabilityProvider) {};}-function providerLine(provider: RuntimeHostCapabilityProvider): string {+export function providerLine(provider: RuntimeHostCapabilityProvider): string {return `${provider.endpoint} (${provider.use}) · ${priceLine(provider)}`;}diff --git a/packages/video-cli/src/frame-grid.ts b/packages/video-cli/src/frame-grid.tsnew file mode 100644index 00000000..6c997606--- /dev/null+++ b/packages/video-cli/src/frame-grid.ts@@ -0,0 +1,34 @@+import sharp from "sharp";++/** Arrange already captured evidence. Decoding and time selection belong to the caller. */+export async function writeFrameGrid(+ frames: readonly { readonly path: string; readonly label: Buffer }[],+ target: string, cellWidth: number, columns: number,+): Promise<void> {+ if (frames.length === 0) throw new Error("A frame grid needs at least one image");+ const cells = [];+ for (const frame of frames) {+ const picture = await sharp(frame.path).resize({ width: cellWidth }).png().toBuffer({ resolveWithObject: true });+ const labelHeight = (await sharp(frame.label).metadata()).height!;+ cells.push({ picture: picture.data, height: picture.info.height, label: frame.label, labelHeight });+ }+ const pictureHeight = Math.max(...cells.map(cell => cell.height));+ const rowHeight = pictureHeight + Math.max(...cells.map(cell => cell.labelHeight));+ const rows = Math.ceil(cells.length / columns);+ await sharp({ create: {+ width: columns * (cellWidth + 8) + 8, height: rows * (rowHeight + 8) + 8,+ channels: 3, background: "#0c0c0c",+ } }).composite(cells.flatMap((cell, index) => {+ const left = 8 + index % columns * (cellWidth + 8);+ const top = 8 + Math.floor(index / columns) * (rowHeight + 8);+ return [{ input: cell.picture, left, top }, { input: cell.label, left, top: top + pictureHeight }];+ })).toFile(target);+}++export async function snapshotFrameLabel(frame: number, seconds: number, width: number): Promise<Buffer> {+ const text = await sharp({ text: { text: `<span foreground="#f5f5f5">Frame ${frame} · ${seconds.toFixed(6)} s</span>`,+ font: `sans ${Math.max(12, Math.round(width / 28))}`, width: width - 16, rgba: true,+ } }).png().toBuffer({ resolveWithObject: true });+ return sharp({ create: { width, height: text.info.height + 16, channels: 3, background: "#0c0c0c" } })+ .composite([{ input: text.data, left: 8, top: 8 }]).png().toBuffer();+}diff --git a/packages/video-cli/src/index.ts b/packages/video-cli/src/index.tsindex e07ef389..6629487e 100644--- a/packages/video-cli/src/index.ts+++ b/packages/video-cli/src/index.ts@@ -12,6 +12,7 @@ import { videoCliDistribution } from "./distribution.js";import { runMediaCli } from "./media.js";import { runVocabularyCli } from "./vocabulary.js";import { runCaptureCli } from "./capture.js";+import { runSnapshotCli } from "./snapshot.js";import { runVersionCli } from "./version.js";export {@@ -42,6 +43,7 @@ export function runVideoCli(: [videoCliDistribution.packageRoot]);installExternalPackageResolution([hypitHostPackageRoot()]);if (isCreationCommand(argv[0])) return runCreationCli(argv, io);+ if (argv[0] === "snapshot") return runSnapshotCli(argv, io);if (argv[0] === "media") return runMediaCli(argv, io);if (argv[0] === "capture") return runCaptureCli(argv, io);if (argv[0] === "vocabulary") return runVocabularyCli(argv, io);@@ -50,3 +52,5 @@ export function runVideoCli(bootstrapPackages: packages,});}++export { runSnapshotCli, writeSnapshotHelp } from "./snapshot.js";diff --git a/packages/video-cli/src/media-frames.ts b/packages/video-cli/src/media-frames.tsnew file mode 100644index 00000000..c20ad5e4--- /dev/null+++ b/packages/video-cli/src/media-frames.ts@@ -0,0 +1,25 @@+import { mkdir } from "node:fs/promises";+import { join } from "node:path";+import { runProcessOutput } from "./process.js";++export type DecodedFrame = { readonly at: number; readonly path: string };++/** Decode a source interval once, retaining each decoded frame and its actual source timestamp. */+export async function decodeMediaFrames(source: string, start: number, end: number, directory: string): Promise<readonly DecodedFrame[]> {+ if (!Number.isFinite(start) || start < 0 || !Number.isFinite(end) || end <= start) throw new Error("Native frames need 0 <= start < end");+ await mkdir(directory, { recursive: true });+ const times: number[] = [];+ let numerator = 0, denominator = 0;+ await runProcessOutput("ffmpeg", ["-hide_banner", "-loglevel", "info", "-nostdin", "-copyts", "-start_at_zero",+ ...(start > 0 ? ["-ss", String(start)] : []), "-i", source,+ "-map", "0:v:0", "-an", "-vf", `trim=start=${start}:end=${end},showinfo=checksum=0`,+ "-fps_mode", "passthrough", "-pix_fmt", "yuvj420p", "-q:v", "3", "-start_number", "0", join(directory, "%09d.jpg"),+ ], 300_000, line => {+ const base = /config in time_base:\s*(\d+)\/(\d+)/u.exec(line);+ if (base !== null) { numerator = Number(base[1]); denominator = Number(base[2]); }+ const pts = /\bn:\s*\d+\s+pts:\s*(-?\d+)/u.exec(line);+ if (pts !== null && denominator > 0) times.push(Number(pts[1]) * numerator / denominator);+ });+ if (times.length === 0) throw new Error(`No video frames in [${start}, ${end}) s`);+ return times.map((at, index) => ({ at, path: join(directory, `${String(index).padStart(9, "0")}.jpg`) }));+}diff --git a/packages/video-cli/src/media.ts b/packages/video-cli/src/media.tsindex beadd5e5..2ba3e9d3 100644--- a/packages/video-cli/src/media.ts+++ b/packages/video-cli/src/media.ts@@ -1,4 +1,4 @@-import { mkdir, mkdtemp, readFile, rename, rm, stat } from "node:fs/promises";+import { copyFile, link, mkdir, mkdtemp, readFile, rename, rm, stat } from "node:fs/promises";import { tmpdir } from "node:os";import { dirname, extname, join, resolve } from "node:path";@@ -6,6 +6,8 @@ import type { CliIo } from "@hypit/cli";import { downloadVideo, isVideoUrl, prepareVideoDownload } from "@hypit/yt-dlp";import sharp from "sharp";+import { decodeMediaFrames } from "./media-frames.js";+import { writeFrameGrid } from "./frame-grid.js";import { runProcess, runProcessOutput, runProcessWithInput } from "./process.js";import { phraseRanges, readTranscript, wordsAt } from "./transcript.js";import type { FrameWords, TranscriptWord } from "./transcript.js";@@ -35,13 +37,17 @@ function clamp(value: number, low: number, high: number): number { return Math.mtype Parsed = {readonly positionals: readonly string[];readonly options: ReadonlyMap<string, string>;+ readonly repeated: ReadonlyMap<string, readonly string[]>;readonly flags: ReadonlySet<string>;readonly json: boolean;};-function parseArguments(argv: readonly string[], allowed: readonly string[], allowedFlags: readonly string[] = []): Parsed {+function parseArguments(+ argv: readonly string[], allowed: readonly string[], allowedFlags: readonly string[] = [], repeatable: readonly string[] = [],+): Parsed {const positionals: string[] = [];const options = new Map<string, string>();+ const repeated = new Map<string, string[]>();const flags = new Set<string>();let json = false;for (let index = 0; index < argv.length; index += 1) {@@ -56,13 +62,14 @@ function parseArguments(argv: readonly string[], allowed: readonly string[], allcontinue;}if (!allowed.includes(item)) throw new Error(`unknown option ${item}`);- if (options.has(item)) throw new Error(`${item} cannot be repeated`);+ if (!repeatable.includes(item) && options.has(item)) throw new Error(`${item} cannot be repeated`);const value = argv[index + 1];if (value === undefined || (value.startsWith("--") && value.length > 2)) throw new Error(`${item} requires a value`);- options.set(item, value);+ if (repeatable.includes(item)) repeated.set(item, [...(repeated.get(item) ?? []), value]);+ else options.set(item, value);index += 1;}- return { positionals, options, flags, json };+ return { positionals, options, repeated, flags, json };}function required(parsed: Parsed, option: string, hint: string): string {@@ -132,14 +139,22 @@ async function destinationDirectory(parsed: Parsed, cwd: string, hint: string):// ---------------------------------------------------------------------------------------------------// ffmpeg-export type MediaProbe = {- readonly duration: number;+type VideoProbe = {+ readonly hasVideo: true;readonly width: number;readonly height: number;readonly frameRate: number;- readonly hasAudio: boolean;};+export type MediaProbe = {+ readonly duration: number;+ readonly hasAudio: boolean;+} & (VideoProbe | { readonly hasVideo: false });++function requireVideo(info: MediaProbe, path: string): asserts info is MediaProbe & VideoProbe {+ assert(info.hasVideo, `${path}: no video stream`);+}+export async function probeMedia(path: string): Promise<MediaProbe> {const raw = await runProcess("ffprobe", ["-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height,r_frame_rate", "-of", "json", path,@@ -151,16 +166,20 @@ export async function probeMedia(path: string): Promise<MediaProbe> {const video = parsed.streams?.find((item) => item.codec_type === "video");const duration = Number(parsed.format?.duration);assert(Number.isFinite(duration) && duration > 0, `${path}: duration is unavailable`);- assert(video?.width !== undefined && video.height !== undefined, `${path}: no video stream`);+ const hasAudio = parsed.streams?.some((item) => item.codec_type === "audio") ?? false;+ assert(video !== undefined || hasAudio, `${path}: no audio or video stream`);+ if (video === undefined) return { duration: round(duration), hasVideo: false, hasAudio };+ assert(video.width !== undefined && video.height !== undefined, `${path}: video dimensions are unavailable`);// ffprobe reports the rate as a ratio; a still image reports none.const ratio = (video.r_frame_rate ?? "").split("/");const rate = Number(ratio[0]) / Number(ratio[1] ?? 1);return {duration: round(duration),+ hasVideo: true,width: video.width,height: video.height,frameRate: Number.isFinite(rate) && rate > 0 ? round(rate) : 0,- hasAudio: parsed.streams?.some((item) => item.codec_type === "audio") ?? false,+ hasAudio,};}@@ -257,7 +276,7 @@ export async function cutClip(start: number,end: number,target: string,- labelInfo?: Pick<MediaProbe, "frameRate">,+ labelInfo?: Pick<VideoProbe, "frameRate">,): Promise<void> {assert(end > start, `the clip must end after it starts (${start} to ${end})`);const seconds = round(end - start);@@ -289,6 +308,64 @@ export async function cutClip(}}+type CutSpan = { readonly start: number; readonly end: number };++function keptSpan(raw: string, duration: number): CutSpan {+ const parts = raw.split(":");+ assert(parts.length === 2 && parts.every((part) => part.trim().length > 0), `--keep needs start:end in seconds, got ${raw}`);+ const [start, end] = parts.map(Number);+ assert(Number.isFinite(start) && Number.isFinite(end) && start! >= 0 && end! > start! && end! <= duration + 0.001,+ `--keep ${raw} must satisfy 0 <= start < end <= ${duration} s`);+ return { start: start!, end: end! };+}++/** Decode the selected parts once, join them on a new local clock, and preserve only existing streams. */+async function cutProduction(source: string, spans: readonly CutSpan[], target: string, info: MediaProbe): Promise<void> {+ const seek = Math.max(0, spans[0]!.start - SEEK_RUN_UP);+ const labels: string[] = [];+ const filters: string[] = [];+ const videoInputs = spans.map((_, index) => `vsrc${index}`);+ const audioInputs = spans.map((_, index) => `asrc${index}`);+ if (info.hasVideo && spans.length > 1) filters.push(`[0:v:0]split=${spans.length}${videoInputs.map((item) => `[${item}]`).join("")}`);+ if (info.hasAudio && spans.length > 1) filters.push(`[0:a:0]asplit=${spans.length}${audioInputs.map((item) => `[${item}]`).join("")}`);+ for (const [index, span] of spans.entries()) {+ const start = round(span.start - seek);+ const end = round(span.end - seek);+ if (info.hasVideo) filters.push(`[${spans.length === 1 ? "0:v:0" : videoInputs[index]}]trim=start=${start}:end=${end},setpts=PTS-STARTPTS[v${index}]`);+ if (info.hasAudio) filters.push(`[${spans.length === 1 ? "0:a:0" : audioInputs[index]}]atrim=start=${start}:end=${end},asetpts=PTS-STARTPTS[a${index}]`);+ labels.push(`${info.hasVideo ? `[v${index}]` : ""}${info.hasAudio ? `[a${index}]` : ""}`);+ }+ if (spans.length > 1) filters.push(`${labels.join("")}concat=n=${spans.length}:v=${info.hasVideo ? 1 : 0}:a=${info.hasAudio ? 1 : 0}${info.hasVideo ? "[v]" : ""}${info.hasAudio ? "[a]" : ""}`);+ const videoLabel = spans.length === 1 ? "[v0]" : "[v]";+ const audioLabel = spans.length === 1 ? "[a0]" : "[a]";+ await runProcess("ffmpeg", [+ "-hide_banner", "-loglevel", "error", "-y",+ ...(seek > 0 ? ["-ss", String(round(seek))] : []), "-i", source,+ "-filter_complex", filters.join(";"),+ ...(info.hasVideo ? ["-map", videoLabel, "-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p", "-fps_mode", "vfr",+ ...([".mp4", ".mov"].includes(extname(target).toLowerCase()) ? ["-movflags", "+faststart"] : [])] : []),+ ...(info.hasAudio ? ["-map", audioLabel, "-c:a", ...(info.hasVideo ? ["aac", "-b:a", "192k"] : ["pcm_s24le"])] : []),+ target,+ ]);+}++/** Publish a completed cut without overwriting a file another process may have created meanwhile. */+async function writeCut(+ source: string, spans: readonly CutSpan[], target: string, info: MediaProbe, labeled: boolean,+): Promise<void> {+ const work = await mkdtemp(join(dirname(target), ".hypit-cut-"));+ const staged = join(work, `cut${extname(target)}`);+ try {+ if (labeled) {+ requireVideo(info, source);+ await cutClip(source, spans[0]!.start, spans[0]!.end, staged, info);+ } else await cutProduction(source, spans, staged, info);+ await link(staged, target);+ } finally {+ await rm(work, { recursive: true, force: true });+ }+}+export async function cutFrame(source: string, at: number, target: string, labelTime = false): Promise<number> {if (!labelTime) {const jump = Math.max(0, at - SEEK_RUN_UP);@@ -362,29 +439,16 @@ export async function tileFrames(const temporary = await mkdtemp(join(tmpdir(), "hypit-tile-"));try {const frames: SampledFrame[] = [];- const cells: { picture: Buffer; label: Buffer; height: number; labelHeight: number }[] = [];+ const cells: { path: string; label: Buffer }[] = [];for (let index = 0; index < times.length; index += 1) {const at = times[index]!;const path = join(temporary, `${index}.jpg`);const actual = await cutFrame(source, at, path);const frameWords = words === undefined ? undefined : wordsAt(words, actual);frames.push({ requestedAt: at, at: actual, ...(frameWords === undefined ? {} : { words: frameWords }) });- const picture = await sharp(path).resize({ width: cellWidth }).png().toBuffer({ resolveWithObject: true });- const label = await frameLabel(actual, cellWidth, frameWords);- const labelHeight = (await sharp(label).metadata()).height!;- cells.push({ picture: picture.data, height: picture.info.height, label, labelHeight });+ cells.push({ path, label: await frameLabel(actual, cellWidth, frameWords) });}- const rows = Math.ceil(times.length / columns);- const pictureHeight = Math.max(...cells.map((cell) => cell.height));- const rowHeight = pictureHeight + Math.max(...cells.map((cell) => cell.labelHeight));- await sharp({ create: {- width: columns * (cellWidth + 8) + 8, height: rows * (rowHeight + 8) + 8,- channels: 3, background: "#0c0c0c",- } }).composite(cells.flatMap((cell, index) => {- const left = 8 + (index % columns) * (cellWidth + 8);- const top = 8 + Math.floor(index / columns) * (rowHeight + 8);- return [{ input: cell.picture, left, top }, { input: cell.label, left, top: top + pictureHeight }];- })).jpeg({ quality: 90 }).toFile(target);+ await writeFrameGrid(cells, target, cellWidth, columns);return frames;} finally {await rm(temporary, { recursive: true, force: true });@@ -490,27 +554,54 @@ async function probe(argv: readonly string[], io: CliIo, cwd: string): Promise<vconst source = await sourceFile(parsed, cwd);const info = await probeMedia(source);if (parsed.json) { io.write(`${JSON.stringify({ path: source, ...info }, null, 2)}\n`); return; }- io.write(`${source}\n ${info.duration} s ${info.width}×${info.height} ${info.frameRate > 0 ? `${info.frameRate} fps` : "still"} ${info.hasAudio ? "with audio" : "no audio"}\n`);+ io.write(`${source}\n ${info.duration} s ${info.hasVideo+ ? `${info.width}×${info.height} ${info.frameRate > 0 ? `${info.frameRate} fps` : "still"} ${info.hasAudio ? "with audio" : "no audio"}`+ : "audio only"}\n`);}async function cut(argv: readonly string[], io: CliIo, cwd: string): Promise<void> {- const parsed = parseArguments(argv, ["--start", "--end", "--to"], ["--label-time"]);+ const parsed = parseArguments(argv, ["--start", "--end", "--keep", "--to"], ["--label-time"], ["--keep"]);const source = await sourceFile(parsed, cwd);- const start = secondsOption(parsed, "--start", 0);const info = await probeMedia(source);- const end = secondsOption(parsed, "--end", info.duration);- assert(end <= info.duration + 0.001, `--end ${end} is past the end of the file (${info.duration} s)`);- const target = await destination(parsed, cwd, "the clip to write, for example notes/hook.mp4");+ const kept = parsed.repeated.get("--keep") ?? [];+ assert(kept.length === 0 || (!parsed.options.has("--start") && !parsed.options.has("--end")),+ "choose --keep intervals or --start/--end");+ const spans = kept.length > 0 ? kept.map((item) => keptSpan(item, info.duration)) : [{+ start: secondsOption(parsed, "--start", 0), end: secondsOption(parsed, "--end", info.duration),+ }];+ for (const [index, span] of spans.entries()) {+ assert(span.end > span.start && span.end <= info.duration + 0.001,+ `range must satisfy 0 <= start < end <= ${info.duration} s`);+ if (index > 0) assert(span.start >= spans[index - 1]!.end, "--keep intervals must be ordered and non-overlapping");+ }const labeled = parsed.flags.has("--label-time");- await cutClip(source, start, end, target, labeled ? info : undefined);- if (parsed.json) { io.write(`${JSON.stringify({ path: target, start, end, seconds: round(end - start), labeled }, null, 2)}\n`); return; }- io.write(`${target}\n ${start} s to ${end} s (${round(end - start)} s)${labeled ? ", source time visible" : ""}\n`);+ assert(!labeled || (info.hasVideo && spans.length === 1), "--label-time needs one video interval");+ const target = await destination(parsed, cwd, "the clip to write, for example notes/hook.mp4");+ if (!info.hasVideo) assert(extname(target).toLowerCase() === ".wav", "--to must end in .wav for audio-only media");+ await writeCut(source, spans, target, info, labeled);+ const output = await probeMedia(target);+ const requestedSeconds = round(spans.reduce((total, span) => total + span.end - span.start, 0));+ if (parsed.json) {+ let outputAt = 0;+ const mapping = spans.map((span) => {+ const item = { sourceStart: span.start, sourceEnd: span.end,+ nominalOutputStart: round(outputAt), nominalOutputEnd: round(outputAt + span.end - span.start) };+ outputAt += span.end - span.start;+ return item;+ });+ io.write(`${JSON.stringify({ path: target, ...(spans.length === 1 ? { start: spans[0]!.start, end: spans[0]!.end } : {}),+ spans, mapping, seconds: requestedSeconds, actualSeconds: output.duration, hasVideo: output.hasVideo, hasAudio: output.hasAudio, labeled }, null, 2)}\n`);+ return;+ }+ io.write(`${target}\n ${spans.map((span) => `${span.start}–${span.end} s`).join(" + ")} (${output.duration} s output)${labeled ? ", source time visible" : ""}\n`);}async function frames(argv: readonly string[], io: CliIo, cwd: string): Promise<void> {- const parsed = parseArguments(argv, [...SAMPLE_OPTIONS, "--to"], ["--label-time"]);+ const parsed = parseArguments(argv, [...SAMPLE_OPTIONS, "--to"], ["--label-time", "--every-frame"]);+ if (parsed.flags.has("--every-frame")) { await nativeFrames(parsed, io, cwd, false); return; }const source = await sourceFile(parsed, cwd);const info = await probeMedia(source);+ requireVideo(info, source);const words = await transcriptOption(parsed, cwd);const times = sampleTimes(parsed, info.duration, words, true);const to = await destinationDirectory(parsed, cwd, "the new directory to write the frames into");@@ -538,6 +629,7 @@ async function tile(argv: readonly string[], io: CliIo, cwd: string): Promise<voconst parsed = parseArguments(argv, [...SAMPLE_OPTIONS, "--frames", "--cell", "--columns", "--to"]);const source = await sourceFile(parsed, cwd);const info = await probeMedia(source);+ requireVideo(info, source);const words = await transcriptOption(parsed, cwd);const times = sampleTimes(parsed, info.duration, words);// Preserve source width unless an exceptionally tiny input needs room for a legible timecode.@@ -573,9 +665,11 @@ function tileRange(value: unknown, index: number, duration: number): TileRange {}async function tiles(argv: readonly string[], io: CliIo, cwd: string): Promise<void> {- const parsed = parseArguments(argv, [...SAMPLE_OPTIONS, "--ranges", "--frames", "--cell", "--columns", "--rows", "--to"]);+ const parsed = parseArguments(argv, [...SAMPLE_OPTIONS, "--ranges", "--frames", "--cell", "--columns", "--rows", "--to"], ["--every-frame"]);+ if (parsed.flags.has("--every-frame")) { await nativeFrames(parsed, io, cwd, true); return; }const source = await sourceFile(parsed, cwd);const info = await probeMedia(source);+ requireVideo(info, source);const words = await transcriptOption(parsed, cwd);const rangesPath = parsed.options.get("--ranges");let ranges: { id?: string; start: number; end: number; times: readonly number[] }[];@@ -631,9 +725,65 @@ async function tiles(argv: readonly string[], io: CliIo, cwd: string): Promise<vio.write(`${to}\n ${written.length} time-labeled ${written.length === 1 ? "grid" : "grids"}\n`);}+/** Native-frame observation: each requested interval is decoded once, then paginated. */+async function nativeFrames(parsed: Parsed, io: CliIo, cwd: string, grid: boolean): Promise<void> {+ for (const key of ["--at", "--every", "--frames"]) assert(!parsed.options.has(key), `--every-frame cannot be combined with ${key}`);+ const source = await sourceFile(parsed, cwd);+ const info = await probeMedia(source);+ requireVideo(info, source);+ const words = await transcriptOption(parsed, cwd);+ let ranges: TileRange[];+ const rangeFile = parsed.options.get("--ranges");+ if (rangeFile === undefined) ranges = [sampleRange(parsed, info.duration, words)];+ else {+ for (const key of ["--start", "--end", "--around", "--padding", "--occurrence"]) assert(!parsed.options.has(key), `--ranges cannot be combined with ${key}`);+ const raw = JSON.parse(await readFile(resolve(cwd, rangeFile), "utf8"));+ assert(Array.isArray(raw) && raw.length > 0, "--ranges needs a non-empty JSON array");+ ranges = raw.map((value, index) => tileRange(value, index, info.duration));+ assert(ranges.every(range => range.frames === undefined && range.every === undefined), "Native ranges cannot specify frames or every");+ }+ const cell = integerOption(parsed, "--cell", Math.max(80, Math.min(TILE_CELL_WIDTH, info.width)), 80);+ const columns = integerOption(parsed, "--columns", TILE_COLUMNS, 1);+ const rows = integerOption(parsed, "--rows", 3, 1);+ const to = await destinationDirectory(parsed, cwd, "the new directory for native frame evidence");+ const staging = await mkdtemp(join(dirname(to), ".hypit-native-"));+ const written: { at: number; path: string }[] = [];+ const grids: { path: string; frames: readonly { at: number }[] }[] = [];+ try {+ for (const [rangeIndex, range] of ranges.entries()) {+ const decodedDirectory = join(staging, "decoded");+ const decoded = await decodeMediaFrames(source, range.start, range.end, decodedDirectory);+ if (grid) {+ const perPage = columns * rows;+ for (let offset = 0; offset < decoded.length; offset += perPage) {+ const page = decoded.slice(offset, offset + perPage);+ const cells = [];+ for (const frame of page) cells.push({ path: frame.path, label: await frameLabel(frame.at, cell,+ words === undefined ? undefined : wordsAt(words, frame.at)) });+ const name = `${String(rangeIndex + 1).padStart(3, "0")}-${range.id ?? "frames"}-p${String(offset / perPage + 1).padStart(3, "0")}.jpg`;+ await writeFrameGrid(cells, join(staging, name), cell, columns);+ grids.push({ path: join(to, name), frames: page.map(frame => ({ at: frame.at })) });+ }+ } else for (const [index, frame] of decoded.entries()) {+ const name = `frame-${String(index).padStart(9, "0")}.jpg`;+ const target = join(staging, name);+ if (parsed.flags.has("--label-time") || words !== undefined) await writeFrameGrid([{ path: frame.path,+ label: await frameLabel(frame.at, info.width, words === undefined ? undefined : wordsAt(words, frame.at)) }], target, info.width, 1);+ else await copyFile(frame.path, target);+ written.push({ at: frame.at, path: join(to, name) });+ }+ await rm(decodedDirectory, { recursive: true, force: true });+ }+ await rename(staging, to);+ } catch (error) { await rm(staging, { recursive: true, force: true }); throw error; }+ if (parsed.json) io.write(`${JSON.stringify({ directory: to, ...(grid ? { grids } : { frames: written }) }, null, 2)}\n`);+ else io.write(`${to}\n ${grid ? `${grids.length} grids` : `${written.length} frames`} from continuous source decoding\n`);+}+async function boundaries(argv: readonly string[], io: CliIo, cwd: string): Promise<void> {const parsed = parseArguments(argv, ["--rate", "--threshold"]);const source = await sourceFile(parsed, cwd);+ requireVideo(await probeMedia(source), source);const rate = numberOption(parsed, "--rate", DEFAULT_BOUNDARY_RATE, 1, 120);const threshold = numberOption(parsed, "--threshold", DEFAULT_BOUNDARY_THRESHOLD, 0, 1);const candidates = await visualBoundaries(source, rate, threshold);@@ -653,6 +803,7 @@ async function fetch(argv: readonly string[], io: CliIo, cwd: string): Promise<vassert([".mp4", ".mkv", ".webm", ".mov"].includes(extname(target).toLowerCase()), "--to must end in .mp4, .mkv, .webm or .mov");await downloadVideo(url, target);const info = await probeMedia(target);+ requireVideo(info, target);if (parsed.json) { io.write(`${JSON.stringify({ path: target, url, ...info }, null, 2)}\n`); return; }io.write(`${target}\n ${info.duration} s ${info.width}×${info.height} ${info.hasAudio ? "with audio" : "no audio"}\n`);}@@ -662,26 +813,27 @@ async function fetch(argv: readonly string[], io: CliIo, cwd: string): Promise<vexport function writeMediaHelp(io: CliIo, topic?: MediaCommand): void {const sections: Record<MediaCommand, readonly string[]> = {- probe: [" hypit media probe <file>", " Duration, size, frame rate and whether there is audio."],- cut: [" hypit media cut <file> --start <s> --end <s> [--label-time] --to <clip.mp4>",- " One exact stretch. --label-time visibly overlays absolute source time on the evidence copy."],- frames: [" hypit media frames <file> (--at <s,s,…> | --every <s>) [--start <s> --end <s>] [--label-time] [--transcript <json>] --to <dir>",+ probe: [" hypit media probe <file>", " Duration and available audio/video streams; video adds size and frame rate."],+ cut: [" hypit media cut <file> [--start <s> --end <s> | --keep <start:end> ...] [--label-time] --to <clip.mp4|clip.wav>",+ " Keep one stretch or join ordered stretches from one source. Audio-only outputs WAV; MP4 is a useful video target.",+ " --label-time overlays source time on a single video evidence copy."],+ frames: [" hypit media frames <file> (--at <s,s,…> | --every <s> | --every-frame) [--start <s> --end <s>] [--label-time] [--transcript <json>] --to <dir>"," Individual frames named by source time; --transcript adds word times and context below each picture."],tile: [" hypit media tile <file> [--start <s> --end <s> | --at <s,s,…>] [--every <s> | --frames <n>] [--transcript <json>] [--cell <px>] [--columns <n>] --to <grid.jpg>"," One grid. --every samples from start, excluding end; --frames chooses evenly spaced midpoints."],- tiles: [" hypit media tiles <file> [--start <s> --end <s> | --at <s,s,…> | --ranges <json>] [--every <s> | --frames <n>] [--transcript <json>] [--cell <px>] [--columns <n>] [--rows <n>] --to <dir>",- " Paginated grids (3 rows by default). Range files contain { start, end, id?, frames?, every? }."],+ tiles: [" hypit media tiles <file> [--start <s> --end <s> | --at <s,s,…> | --ranges <json>] [--every <s> | --frames <n> | --every-frame] [--transcript <json>] [--cell <px>] [--columns <n>] [--rows <n>] --to <dir>",+ " Paginated grids (3 rows by default). --every-frame decodes every original frame once per interval, preserving actual timestamps. Range files contain { start, end, id?, frames?, every? }."],boundaries: [" hypit media boundaries <file> [--rate <samples/s>] [--threshold <0..1>]"," Mechanical adjacent-frame change candidates with scores; never editorial shot labels."],"prepare-fetch": [" hypit media prepare-fetch", " Explicitly prepare the pinned yt-dlp environment; does not fetch media."],fetch: [" hypit media fetch <url> --to <video.mp4>", " A link turned into a file with the pinned yt-dlp, video and audio together."],};const chosen = topic === undefined ? mediaCommands : [topic];- io.write(`hypit media\nInspect media at chosen times and scales. Local work; no Runtime Profile, no request, no state.\n\n${+ io.write(`hypit media\nInspect and prepare media locally. No Runtime Profile, network request or project state.\n\n${chosen.map((item) => sections[item].join("\n")).join("\n\n")}\n\nFrames and grids accept --around <phrase> with --transcript instead of --start/--end.\n`+ "Use --occurrence <n> for a repeated phrase; --padding <s> adds time on each side (default 0.3).\n"+ "Transcript times must share the input media's clock. An untimed gap is labeled as such, without inferring silence.\n"- + "Commands that create evidence write only what --to names and refuse to overwrite. Add --json for the complete machine view.\n");+ + "Commands write only what --to names and refuse to overwrite. Add --json for the complete machine view.\n");}export async function runMediaCli(argv: readonly string[], io: CliIo, cwd = process.cwd()): Promise<void> {diff --git a/packages/video-cli/src/process.ts b/packages/video-cli/src/process.tsindex b92defa5..669ec9d0 100644--- a/packages/video-cli/src/process.ts+++ b/packages/video-cli/src/process.ts@@ -9,6 +9,7 @@ function run(args: readonly string[],input: ProcessInput | undefined,timeoutMs: number,+ onStderrLine?: (line: string) => void,): Promise<ProcessOutput> {return new Promise((resolveRun, reject) => {const child = spawn(executable, [...args], { stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], windowsHide: true });@@ -24,7 +25,16 @@ function run(};const timer = setTimeout(() => { child.kill("SIGKILL"); finish(new Error(`${executable} timed out after ${timeoutMs} ms`)); }, timeoutMs);child.stdout?.on("data", (chunk: Buffer) => out.push(chunk));- child.stderr?.on("data", (chunk: Buffer) => { err = `${err}${chunk.toString("utf8")}`.slice(-100_000); });+ let pendingLine = "";+ child.stderr?.on("data", (chunk: Buffer) => {+ const text = chunk.toString("utf8");+ err = `${err}${text}`.slice(-100_000);+ if (onStderrLine !== undefined) {+ const lines = `${pendingLine}${text}`.split(/\r?\n/u);+ pendingLine = lines.pop()!;+ for (const line of lines) onStderrLine(line);+ }+ });child.on("error", (error) => finish(new Error(`${executable} could not start: ${error.message}`)));child.on("close", (code) => {if (code === 0) finish();@@ -56,8 +66,8 @@ export async function runProcess(executable: string, args: readonly string[], ti}/** Successful stderr can carry tool metadata, such as the timestamp of an extracted frame. */-export function runProcessOutput(executable: string, args: readonly string[], timeoutMs = 300_000): Promise<ProcessOutput> {- return run(executable, args, undefined, timeoutMs);+export function runProcessOutput(executable: string, args: readonly string[], timeoutMs = 300_000, onStderrLine?: (line: string) => void): Promise<ProcessOutput> {+ return run(executable, args, undefined, timeoutMs, onStderrLine);}/** The same process boundary when a deterministic byte stream is one of the program's inputs. */diff --git a/packages/video-cli/src/snapshot.ts b/packages/video-cli/src/snapshot.tsnew file mode 100644index 00000000..ff39ca69--- /dev/null+++ b/packages/video-cli/src/snapshot.ts@@ -0,0 +1,186 @@+import { createReadStream, createWriteStream } from "node:fs";+import { mkdir, mkdtemp, readFile, rename, rm, stat } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, extname, join, resolve } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { Readable } from "node:stream";+import type { ReadableStream as NodeReadableStream } from "node:stream/web";+import { pipeline } from "node:stream/promises";+import type { CliIo } from "@hypit/cli";+import { assertHyperframesDocument, hyperframesHtmlAssetUrls, hyperframesHtmlDomain } from "@hypit/hyperframes";+import type { HyperframesDocument, HyperframesHtmlProject } from "@hypit/hyperframes";+import { FileResourceStore } from "@hypit/resource-store-fs";+import { hyperframesFramesRequest, renderHyperframesCapabilities, renderHyperframesTypes, verifyHyperframesFrames } from "@hypit/render-hyperframes";+import type { Need } from "@hypit/protocol";+import { creationEnvironment, selectedProvider, providerLine, providerView } from "./creation.js";+import type { CreationEnvironment } from "./creation.js";+import { snapshotFrameLabel, writeFrameGrid } from "./frame-grid.js";++const MEDIA_TYPES: Readonly<Record<string, string>> = {+ ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp",+ ".mp4": "video/mp4", ".webm": "video/webm", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf", ".otf": "font/otf",+};++async function readProject(source: string, html: string, resources: FileResourceStore): Promise<HyperframesHtmlProject> {+ const assets = [];+ const base = /^https?:/u.test(source) ? new URL(source) : pathToFileURL(source);+ for (const url of hyperframesHtmlAssetUrls(html)) {+ const address = new URL(url, base);+ let mediaType: string | undefined;+ let stream: Readable;+ if (address.protocol === "file:") {+ if (base.protocol !== "file:") throw new Error(`Network HTML cannot read local asset ${url}`);+ const path = fileURLToPath(address);+ mediaType = MEDIA_TYPES[extname(path).toLowerCase()];+ if (mediaType === undefined) throw new Error(`Unsupported snapshot asset ${url}; use compiled HTML with inline scripts and styles`);+ stream = createReadStream(path);+ } else if (address.protocol === "http:" || address.protocol === "https:") {+ const response = await fetch(address);+ if (!response.ok || response.body === null) throw new Error(`Snapshot asset ${url}: HTTP ${response.status}`);+ mediaType = response.headers.get("content-type")?.split(";")[0]?.trim();+ if (mediaType === undefined || !Object.values(MEDIA_TYPES).includes(mediaType)) {+ await response.body.cancel();+ throw new Error(`Unsupported snapshot asset ${url} (${mediaType}); use compiled HTML with inline scripts and styles`);+ }+ stream = Readable.fromWeb(response.body as NodeReadableStream<Uint8Array>);+ } else throw new Error(`Unsupported snapshot asset protocol ${address.protocol}`);+ try { assets.push({ url, artifact: await resources.putStream(stream, mediaType) }); }+ finally { stream.destroy(); }+ }+ return { html, assets };+}++const OPTIONS = ["--studio", "--to", "--at-frame", "--start-frame", "--end-frame-exclusive", "--step-frames", "--grid", "--cell", "--runtime", "--workspace"];++export function writeSnapshotHelp(io: CliIo): void {+ io.write(`hypit snapshot\nCapture exact frames from an existing compiled HyperFrames HTML programme through the selected Runtime Profile.\n\n`+ + ` hypit snapshot --studio <studio-url> --at-frame <n[,n,…]> --to <directory>\n`+ + ` hypit snapshot <index.html|HTML-URL> --at-frame <n[,n,…]> --to <directory>\n`+ + ` hypit snapshot <index.html|HTML-URL> --start-frame <n> --end-frame-exclusive <n> [--step-frames <n>] --to <directory>\n`+ + ` [--grid <columns>x<rows>] [--cell <pixels>] [--runtime <profile>] [--workspace <project>] [--json]\n\n`+ + `Frame indices are zero-based on the original programme clock. Ranges exclude the end.\n`+ + `Writes full-size PNGs and optional paginated grids. --cell controls grid image width (default 480).\n`+ + `Uses render-frames, one immediate request. Browser preparation belongs to the selected Provider.\n`+ + `HTML carries the compiled frame clock and media/font URLs; scripts and styles are inline.\nStudio exposes its current programme at http://<host>:<port>/__studio/visual.html.\n`);+}++export async function runSnapshotCli(argv: readonly string[], io: CliIo, environment: CreationEnvironment = creationEnvironment()): Promise<void> {+ if (argv.includes("--help")) { writeSnapshotHelp(io); return; }+ const options = new Map<string, string>();+ const positionals = [];+ const json = argv.includes("--json");+ for (let index = 1; index < argv.length; index++) {+ const arg = argv[index]!;+ if (["--json", "--debug", "--verbose", "--no-color"].includes(arg)) continue;+ if (arg === "--color") { index++; continue; }+ if (!arg.startsWith("--")) { positionals.push(arg); continue; }+ if (!OPTIONS.includes(arg)) throw new Error(`Unknown snapshot option ${arg}`);+ if (options.has(arg)) throw new Error(`${arg} cannot be repeated`);+ const value = argv[++index];+ if (!value || value.startsWith("--")) throw new Error(`${arg} requires a value`);+ options.set(arg, value);+ }+ const studio = options.get("--studio");+ if (positionals.length !== (studio === undefined ? 1 : 0) || !options.has("--to")) throw new Error("snapshot takes one HTML input or --studio <url>, and --to <directory>");+ const integer = (raw: string | undefined, label: string, minimum = 0): number => {+ if (raw === undefined || !/^\d+$/u.test(raw) || !Number.isSafeInteger(Number(raw)) || Number(raw) < minimum) throw new Error(`${label} needs an integer >= ${minimum}`);+ return Number(raw);+ };+ const source = studio === undefined+ ? /^https?:\/\//u.test(positionals[0]!) ? positionals[0]! : resolve(environment.cwd, positionals[0]!)+ : new URL("/__studio/document", studio).href;+ let document: HyperframesDocument | undefined;+ let html: string;+ if (studio !== undefined) {+ const response = await fetch(source);+ if (!response.ok) throw new Error(`Studio programme: HTTP ${response.status} ${await response.text()}`);+ document = await response.json() as HyperframesDocument;+ assertHyperframesDocument(document);+ html = document.html;+ } else if (/^https?:/u.test(source)) {+ const response = await fetch(source);+ if (!response.ok) throw new Error(`Snapshot HTML: HTTP ${response.status} ${await response.text()}`);+ html = await response.text();+ } else html = await readFile(source, "utf8");+ const domain = document ?? hyperframesHtmlDomain(html);+ const explicit = options.get("--at-frame");+ let frames: number[];+ if (explicit !== undefined) {+ if (["--start-frame", "--end-frame-exclusive", "--step-frames"].some(key => options.has(key))) throw new Error("Choose --at-frame or a frame range");+ frames = explicit.split(",").map(value => integer(value, "--at-frame"));+ } else {+ const start = integer(options.get("--start-frame"), "--start-frame");+ const end = integer(options.get("--end-frame-exclusive"), "--end-frame-exclusive");+ const step = integer(options.get("--step-frames") ?? "1", "--step-frames", 1);+ if (end <= start || end > domain.frameCount) throw new Error(`The frame range must satisfy 0 <= start < end <= ${domain.frameCount}`);+ frames = Array.from({ length: Math.ceil((end - start) / step) }, (_, index) => start + index * step);+ }+ const grid = options.get("--grid")?.split("x");+ if (grid !== undefined && grid.length !== 2) throw new Error("--grid needs columns x rows, for example 4x3");+ const columns = grid === undefined ? undefined : integer(grid[0], "grid columns", 1);+ const rows = grid === undefined ? undefined : integer(grid[1], "grid rows", 1);+ if (options.has("--cell") && grid === undefined) throw new Error("--cell requires --grid");+ const cell = integer(options.get("--cell") ?? "480", "--cell", 32);+ const to = resolve(environment.cwd, options.get("--to")!);+ if (await stat(to).then(() => true, () => false)) throw new Error(`Destination ${to} already exists`);+ const temporary = await mkdtemp(join(tmpdir(), "hypit-snapshot-"));+ let staging: string | undefined;+ try {+ const resources = new FileResourceStore(temporary);+ let input: { document: HyperframesDocument } | { project: HyperframesHtmlProject };+ if (document !== undefined) {+ for (const artifact of document.artifacts) {+ const response = await fetch(new URL(`/__studio/material/${artifact.resource}`, studio));+ if (!response.ok || response.body === null) throw new Error(`Studio material ${artifact.resource}: HTTP ${response.status}`);+ const stream = Readable.fromWeb(response.body as NodeReadableStream<Uint8Array>);+ try { await resources.writeStream(artifact, stream); }+ finally { stream.destroy(); }+ }+ input = { document };+ } else input = { project: await readProject(source, html, resources) };+ const need: Need = { id: "need:hypit-snapshot", capability: renderHyperframesCapabilities.renderFrames,+ returns: renderHyperframesTypes.frames, result: "record:hypit-snapshot", constraints: hyperframesFramesRequest({ ...input, frames }) };+ const { host, profile } = await environment.openHost(options.get("--runtime"), options.get("--workspace"));+ const provider = await selectedProvider(host, need, profile);+ if (!json) io.write(`Capturing ${frames.length} frames through ${providerLine(provider)}\n`);+ const report = json ? io.writeProgress : io.writeProgress ?? io.write;+ const fulfilled = await host.invoke(need, resources, {+ reportProgress: async progress => { report?.(` · ${progress.phase}\n`); },+ reportDiagnostic: async diagnostic => { report?.(` · ${diagnostic.message}\n`); },+ });+ if (fulfilled.value.kind !== "inline") throw new Error("The frame list came back by reference");+ verifyHyperframesFrames(fulfilled.value.value);+ const images = fulfilled.value.value;+ if (images.length !== frames.length) throw new Error(`Requested ${frames.length} frames, received ${images.length}`);+ await mkdir(dirname(to), { recursive: true });+ staging = await mkdtemp(join(dirname(to), ".hypit-snapshot-"));+ const files = [];+ for (const [index, image] of images.entries()) {+ const frame = frames[index]!;+ const name = `frame-${String(frame).padStart(9, "0")}.png`;+ const stream = await resources.open(image.resource);+ if (stream === undefined) throw new Error(`Snapshot frame ${frame} is unavailable`);+ await pipeline(stream, createWriteStream(join(staging, name), { flags: "wx" }));+ files.push({ frame, seconds: frame * domain.frameRate.denominator / domain.frameRate.numerator, path: join(to, name) });+ }+ const grids: string[] = [];+ if (columns !== undefined && rows !== undefined) {+ const count = columns * rows;+ for (let offset = 0; offset < files.length; offset += count) {+ const page = [];+ for (const file of files.slice(offset, offset + count)) page.push({ path: join(staging, `frame-${String(file.frame).padStart(9, "0")}.png`),+ label: await snapshotFrameLabel(file.frame, file.seconds, cell) });+ const name = `grid-${String(grids.length + 1).padStart(3, "0")}.jpg`;+ await writeFrameGrid(page, join(staging, name), cell, columns);+ grids.push(join(to, name));+ }+ }+ await rename(staging, to);+ staging = undefined;+ if (json) io.write(`${JSON.stringify({ format: "hypit.video-cli-snapshot@1", source, ...providerView(provider), frames: files, grids }, null, 2)}\n`);+ else io.write(`Captured ${files.length} PNGs${grids.length === 0 ? "" : ` and ${grids.length} grid${grids.length === 1 ? "" : "s"}`}\n ${to}\n`);+ } finally {+ await rm(temporary, { recursive: true, force: true });+ if (staging !== undefined) await rm(staging, { recursive: true, force: true });+ }+}diff --git a/packages/video-cli/test/media-frames.test.ts b/packages/video-cli/test/media-frames.test.tsnew file mode 100644index 00000000..06556ce0--- /dev/null+++ b/packages/video-cli/test/media-frames.test.ts@@ -0,0 +1,34 @@+import assert from "node:assert/strict";+import test from "node:test";+import { spawnSync } from "node:child_process";+import { mkdtemp, readdir, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { decodeMediaFrames } from "../src/media-frames.js";+import { runMediaCli } from "../src/media.js";++test("native evidence preserves variable-rate timestamps and half-open bounds across grid pages", async () => {+ const directory = await mkdtemp(join(tmpdir(), "hypit-native-frames-test-"));+ try {+ const source = join(directory, "vfr.mkv");+ const encoded = spawnSync("ffmpeg", ["-v", "error", "-f", "lavfi", "-i", "testsrc2=size=96x64:rate=10:duration=0.4",+ "-vf", "setpts=if(lt(N\\,2)\\,N\\,N*2-1)/(10*TB)", "-fps_mode", "vfr", "-c:v", "libx264", source], { encoding: "utf8" });+ assert.equal(encoded.status, 0, encoded.stderr);+ const all = await decodeMediaFrames(source, 0, 0.6, join(directory, "all"));+ assert.deepEqual(all.map(frame => frame.at), [0, 0.1, 0.3, 0.5]);+ const selected = await decodeMediaFrames(source, 0.05, 0.5, join(directory, "selected"));+ assert.deepEqual(selected.map(frame => frame.at), [0.1, 0.3]);+ assert.equal((await readdir(join(directory, "selected"))).length, 2);+ let output = "";+ await runMediaCli(["media", "tiles", source, "--start", "0", "--end", "0.6", "--every-frame", "--columns", "2", "--rows", "1",+ "--to", "grids", "--json"], { write: text => { output += text; } }, directory);+ const grids = JSON.parse(output).grids;+ assert.deepEqual(grids.map((grid: { frames: { at: number }[] }) => grid.frames.map(frame => frame.at)), [[0, 0.1], [0.3, 0.5]]);+ assert.equal((await readdir(join(directory, "grids"))).length, 2);+ output = "";+ await runMediaCli(["media", "frames", source, "--start", "0.05", "--end", "0.5", "--every-frame", "--to", "files", "--json"],+ { write: text => { output += text; } }, directory);+ assert.deepEqual(JSON.parse(output).frames.map((frame: { at: number }) => frame.at), [0.1, 0.3]);+ await assert.rejects(runMediaCli(["media", "tiles", source, "--every-frame", "--every", "0.1", "--to", "bad"], { write() {} }, directory), /cannot be combined/u);+ } finally { await rm(directory, { recursive: true, force: true }); }+});diff --git a/packages/video-cli/test/media.test.ts b/packages/video-cli/test/media.test.tsindex 7c8ff357..62da110b 100644--- a/packages/video-cli/test/media.test.ts+++ b/packages/video-cli/test/media.test.ts@@ -8,7 +8,7 @@ import sharp from "sharp";import type { CliIo } from "@hypit/cli";-import { probeMedia, runMediaCli, tileFrameCount, tileSampleTimes, visualBoundaries } from "../src/media.js";+import { cutFrame, probeMedia, runMediaCli, tileFrameCount, tileSampleTimes, visualBoundaries } from "../src/media.js";const ffmpeg = spawnSync("ffmpeg", ["-version"], { stdio: "ignore" }).status === 0&& spawnSync("ffprobe", ["-version"], { stdio: "ignore" }).status === 0;@@ -49,11 +49,12 @@ test("tile frame counts follow the measured bounds", () => {assert.deepEqual(tileSampleTimes(1, 2, 4), [1.125, 1.375, 1.625, 1.875]);});-test("media help names every command and no state", () => {+test("media help names the available commands and both cut forms", () => {const out = io();runMediaCli(["media"], out.io);for (const name of ["probe", "cut", "frames", "tile", "tiles", "boundaries", "fetch"]) assert.match(out.text(), new RegExp(`hypit media ${name}`));- assert.match(out.text(), /no state/);+ assert.match(out.text(), /--start <s> --end <s> \| --keep <start:end>/);+ assert.match(out.text(), /--label-time/);});test("media evidence keeps source times and sub-second visual changes", { skip: !ffmpeg && "ffmpeg is not installed" }, async () => {@@ -61,6 +62,8 @@ test("media evidence keeps source times and sub-second visual changes", { skip:try {const source = await sample(work);const info = await probeMedia(source);+ assert.equal(info.hasVideo, true);+ if (!info.hasVideo) throw new Error("sample has no video stream");assert.equal(info.width, 320);assert.equal(info.height, 240);assert.equal(info.hasAudio, false);@@ -132,6 +135,69 @@ test("fetch refuses anything but an http link and an explicit video destination"await assert.rejects(runMediaCli(["media", "fetch", "https://example.com/v", "--to", "x.txt"], io().io, tmpdir()), /must end in/);});+test("cut prepares recorded audio and joined video without changing the existing evidence cut", { skip: !ffmpeg && "ffmpeg is not installed" }, async () => {+ const work = await mkdtemp(join(tmpdir(), "hypit-recorded-cut-"));+ try {+ const silentVideo = await sample(work);+ const audio = join(work, "source.wav");+ const tone = spawnSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=440:duration=4", "-c:a", "pcm_s16le", audio], { encoding: "utf8" });+ assert.equal(tone.status, 0, tone.stderr);+ const audioProbe = await probeMedia(audio);+ assert.equal(audioProbe.hasVideo, false);+ assert.equal(audioProbe.hasAudio, true);+ const probe = io();+ await runMediaCli(["media", "probe", audio], probe.io, work);+ assert.match(probe.text(), /audio only/);++ const audioCut = io();+ await runMediaCli(["media", "cut", audio, "--keep", "0.25:1", "--keep", "2.5:3", "--to", "spoken.wav", "--json"], audioCut.io, work);+ const audioResult = JSON.parse(audioCut.text()) as { spans: { start: number; end: number }[];+ mapping: { nominalOutputStart: number; nominalOutputEnd: number }[]; actualSeconds: number; hasVideo: boolean; hasAudio: boolean };+ assert.deepEqual(audioResult.spans, [{ start: 0.25, end: 1 }, { start: 2.5, end: 3 }]);+ assert.deepEqual(audioResult.mapping.map((item) => [item.nominalOutputStart, item.nominalOutputEnd]), [[0, 0.75], [0.75, 1.25]]);+ assert.ok(Math.abs(audioResult.actualSeconds - 1.25) < 0.03, `audio duration ${audioResult.actualSeconds}`);+ assert.equal(audioResult.hasVideo, false);+ assert.equal(audioResult.hasAudio, true);+ await runMediaCli(["media", "cut", audio, "--start", "2.5", "--end", "3", "--to", "late.wav"], io().io, work);+ assert.ok(Math.abs((await probeMedia(join(work, "late.wav"))).duration - 0.5) < 0.03,+ "a late single interval lands on the requested audio time");+ await assert.rejects(runMediaCli(["media", "cut", audio, "--start", "0", "--end", "1", "--to", "spoken.wav"], io().io, work), /already exists/);+ await assert.rejects(runMediaCli(["media", "cut", audio, "--start", "0", "--end", "1", "--label-time", "--to", "labeled.wav"], io().io, work), /needs one video interval/);++ const withAudio = join(work, "source-av.mp4");+ const mux = spawnSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", "-i", silentVideo, "-i", audio,+ "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "aac", "-shortest", withAudio], { encoding: "utf8" });+ assert.equal(mux.status, 0, mux.stderr);+ const videoCut = io();+ await runMediaCli(["media", "cut", withAudio, "--keep", "0:0.5", "--keep", "1:1.5", "--to", "joined.mp4", "--json"], videoCut.io, work);+ const joined = await probeMedia(join(work, "joined.mp4"));+ assert.equal(joined.hasVideo, true);+ assert.equal(joined.hasAudio, true);+ assert.ok(Math.abs(joined.duration - 1) < 0.08, `joined duration ${joined.duration}`);+ const first = join(work, "first.jpg");+ const second = join(work, "second.jpg");+ await cutFrame(join(work, "joined.mp4"), 0.2, first);+ await cutFrame(join(work, "joined.mp4"), 0.7, second);+ const firstPixel = await sharp(first).extract({ left: 160, top: 120, width: 1, height: 1 }).raw().toBuffer();+ const secondPixel = await sharp(second).extract({ left: 160, top: 120, width: 1, height: 1 }).raw().toBuffer();+ assert.ok(firstPixel[0]! > firstPixel[1]! * 2, `first frame should be red: ${firstPixel}`);+ assert.ok(secondPixel[1]! > secondPixel[0]! * 2, `second frame should be green: ${secondPixel}`);++ await runMediaCli(["media", "cut", withAudio, "--start", "2.1", "--end", "2.8", "--to", "late.mp4"], io().io, work);+ const lateVideo = await probeMedia(join(work, "late.mp4"));+ assert.equal(lateVideo.hasAudio, true);+ assert.ok(Math.abs(lateVideo.duration - 0.7) < 0.08, `late video duration ${lateVideo.duration}`);+ await runMediaCli(["media", "cut", withAudio, "--start", "0", "--end", "0.5", "--to", "clip.mov"], io().io, work);+ assert.equal((await probeMedia(join(work, "clip.mov"))).hasAudio, true);++ const silentCut = join(work, "silent-cut.mp4");+ await runMediaCli(["media", "cut", silentVideo, "--keep", "0:0.5", "--keep", "1:1.5", "--to", silentCut], io().io, work);+ assert.equal((await probeMedia(silentCut)).hasAudio, false);+ } finally {+ await rm(work, { recursive: true, force: true });+ }+});+test("word-located grids paginate dense samples without covering the source picture", { skip: !ffmpeg && "ffmpeg is not installed" }, async () => {const work = await mkdtemp(join(tmpdir(), "hypit-word-grids-"));try {diff --git a/packages/video-cli/test/snapshot.test.ts b/packages/video-cli/test/snapshot.test.tsnew file mode 100644index 00000000..7eb7b7a3--- /dev/null+++ b/packages/video-cli/test/snapshot.test.ts@@ -0,0 +1,101 @@+import assert from "node:assert/strict";+import test from "node:test";+import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import sharp from "sharp";+import { canonicalize } from "@hypit/protocol";+import { verifyHyperframesFramesRequest } from "@hypit/render-hyperframes";+import { runSnapshotCli } from "../src/snapshot.js";+import type { CreationEnvironment } from "../src/creation.js";++const html = '<!doctype html><div data-composition-id="test" data-fps="30000/1001" data-hypit-frame-count="12" data-width="96" data-height="64"><img src="still.png"></div>';++test("snapshot invokes the selected Profile once and writes original-frame PNGs and paginated grids", async () => {+ const directory = await mkdtemp(join(tmpdir(), "hypit-snapshot-cli-"));+ const bytes = await sharp({ create: { width: 96, height: 64, channels: 3, background: "#264a71" } }).png().toBuffer();+ let calls = 0;+ let output = "";+ try {+ await writeFile(join(directory, "index.html"), html);+ await writeFile(join(directory, "still.png"), bytes);+ const environment: CreationEnvironment = { cwd: directory, openHost: async (profile, workspace) => {+ assert.equal(profile, "selected.json");+ assert.equal(workspace, "project");+ return { profile: "selected.json", host: {+ providers: async requests => requests.map(request => ({ request: request.request, capability: request.capability,+ status: "resolved", endpoint: "chosen.frames", use: "@example/frames", pricing: { kind: "local" } })),+ invoke: async (need, resources) => {+ calls++;+ assert.equal(need.capability.name, "render-frames");+ verifyHyperframesFramesRequest(need.constraints);+ assert.deepEqual(need.constraints.frames, [3, 5, 7, 9, 11]);+ assert.ok("project" in need.constraints);+ const asset = need.constraints.project.assets[0]!;+ assert.deepEqual(Buffer.from((await resources.get(asset.artifact.resource))!), bytes);+ return { value: { kind: "inline", value: canonicalize(await Promise.all(need.constraints.frames.map(() => resources.put(bytes, "image/png")))) } };+ },+ } };+ } };+ await runSnapshotCli(["snapshot", "index.html", "--start-frame", "3", "--end-frame-exclusive", "12", "--step-frames", "2",+ "--grid", "2x2", "--cell", "96", "--to", "evidence", "--runtime", "selected.json", "--workspace", "project", "--json"], {+ write: text => { output += text; },+ }, environment);+ assert.equal(calls, 1);+ const view = JSON.parse(output);+ assert.equal(view.endpoint, "chosen.frames");+ assert.equal(view.frames[0].seconds, 3 * 1001 / 30000);+ assert.equal(view.grids.length, 2);+ assert.equal((await readdir(join(directory, "evidence"))).length, 7);+ assert.deepEqual(await readFile(view.frames[0].path), bytes);+ assert.equal((await sharp(view.grids[0]).metadata()).width, 216);+ await assert.rejects(runSnapshotCli(["snapshot", "index.html", "--at-frame", "12", "--to", "bad"], { write() {} }, environment), /\[0, 12\)/u);+ await assert.rejects(runSnapshotCli(["snapshot", "index.html", "--at-frame", "3,3", "--to", "bad"], { write() {} }, environment), /strictly increasing/u);+ assert.equal(calls, 1);+ } finally { await rm(directory, { recursive: true, force: true }); }+});++test("snapshot reports a missing binding before invocation and preserves existing output", async () => {+ const directory = await mkdtemp(join(tmpdir(), "hypit-snapshot-error-"));+ try {+ await writeFile(join(directory, "index.html"), html.replace('<img src="still.png">', ""));+ const environment: CreationEnvironment = { cwd: directory, openHost: async () => ({ profile: "empty.json", host: {+ providers: async () => [], invoke: async () => { throw new Error("must not run"); },+ } }) };+ await assert.rejects(runSnapshotCli(["snapshot", "index.html", "--at-frame", "0", "--to", "new"], { write() {} }, environment), /No Endpoint/u);+ await assert.rejects(runSnapshotCli(["snapshot", "index.html", "--at-frame", "0", "--to", "index.html"], { write() {} }, environment), /already exists/u);+ assert.deepEqual(await readdir(directory), ["index.html"]);+ } finally { await rm(directory, { recursive: true, force: true }); }+});++test("Studio snapshots carry declared resources used only inside JavaScript data", async t => {+ const directory = await mkdtemp(join(tmpdir(), "hypit-studio-snapshot-"));+ const bytes = await sharp({ create: { width: 96, height: 64, channels: 3, background: "red" } }).png().toBuffer();+ const artifact = { kind: "blob" as const, resource: "res_program_image" as const, size: bytes.length, mediaType: "image/png" };+ const document = { visualIr: "hypit.visual-ir@1", frameRate: { numerator: 30000, denominator: 1001 }, frameCount: 12,+ canvas: { width: 96, height: 64 }, artifacts: [artifact], surfaces: [],+ html: html.replace('<img src="still.png">', '<script>const input="hypit-resource://res_program_image";</script>') };+ const fetched: string[] = [];+ t.mock.method(globalThis, "fetch", async (input: string | URL) => {+ const url = String(input);+ fetched.push(url);+ if (url.endsWith("/__studio/document")) return Response.json(document);+ if (url.endsWith("/__studio/material/res_program_image")) return new Response(bytes);+ throw new Error(`Unexpected read ${url}`);+ });+ try {+ const environment: CreationEnvironment = { cwd: directory, openHost: async () => ({ profile: "selected.json", host: {+ providers: async requests => requests.map(request => ({ request: request.request, capability: request.capability,+ status: "resolved", endpoint: "frames", use: "@example/frames" })),+ invoke: async (need, resources) => {+ verifyHyperframesFramesRequest(need.constraints);+ assert.ok("document" in need.constraints);+ assert.deepEqual(need.constraints.document, document);+ assert.deepEqual(Buffer.from((await resources.get(artifact.resource))!), bytes);+ return { value: { kind: "inline", value: canonicalize([await resources.put(bytes, "image/png")]) } };+ },+ } }) };+ await runSnapshotCli(["snapshot", "--studio", "http://studio.example:5191/#comments", "--at-frame", "3", "--to", "evidence"], { write() {} }, environment);+ assert.deepEqual(fetched, ["http://studio.example:5191/__studio/document", "http://studio.example:5191/__studio/material/res_program_image"]);+ } finally { await rm(directory, { recursive: true, force: true }); }+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8a3b97a8..e379f8b4 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3584,6 +3584,9 @@ importers:'@hypit/generation':specifier: workspace:*version: link:../generation+ '@hypit/hyperframes':+ specifier: workspace:*+ version: link:../hyperframes'@hypit/markup':specifier: workspace:*version: link:../markup@@ -3614,6 +3617,12 @@ importers:'@hypit/provider-tokendance':specifier: workspace:*version: link:../provider-tokendance+ '@hypit/render-hyperframes':+ specifier: workspace:*+ version: link:../render-hyperframes+ '@hypit/resource-store-fs':+ specifier: workspace:*+ version: link:../resource-store-fs'@hypit/runtime':specifier: workspace:*version: link:../runtime