@melite/models-h3 0.0.0-stage → 0.1.4-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/actions.js ADDED
@@ -0,0 +1,1366 @@
1
+ import { saveAudio } from '@melite/comfyui-card-kit';
2
+ import { FAMILIES, paramSchema, wireList, H3_RECOMMENDED_SAMPLERS } from "./schema.js";
3
+ import { H3_LORA_ROWS } from '@melite/models-h3/mods/loras';
4
+ import { SAMPLER_OPTIONS, SCHEDULER_OPTIONS } from '@melite/comfyui-card-kit/vocab';
5
+ import { computeFilmMix, parseFilmMixClips, stanzaSecs } from "./filmMix.js";
6
+ import { GRID_REMAINDER, GRID_STEP_FRAMES, IMAGE_BUS_SLOTS, REF_CAPS, assertGridLength, assertSpanGrid, imageReferenceCap, mergeDeclaredRefs, spanStanzaFrames, transitionOverlap, } from "./timelineContract.js";
7
+
8
+ // built from the family lora CATALOG (mods/loras.ts — the one owner
9
+ // of every lora filename and default strength; the value was
10
+ // restated as a literal here, which is how a catalog edit would
11
+ // have silently missed the default). The wire shape matches a
12
+ // resolved bag row: on, lora (filename), str (default_strength),
13
+ // plus the four fixed mode flags. A missing catalog row refuses at
14
+ // load — the default would have no source.
15
+ const loraStackDefault = () => {
16
+ const row = H3_LORA_ROWS.find((r) => r.id === 'h3_lightx2v_turbo');
17
+ if (row === undefined) {
18
+ throw new Error("h3 action: the lora catalog has no 'h3_lightx2v_turbo' row — the absent-bag default has no source; fix the catalog row id");
19
+ }
20
+ return JSON.stringify([{ on: true, lora: row.filename, str: row.default_strength, v: 1, a: 1, t: 1 }]);
21
+ };
22
+ // His 17k+5 grid, in-graph (ComfyMathExpression): snap latent steps to 2 mod 5
23
+ // (the card's own principles row: "Length snaps to the 17k+5 frame grid
24
+ // at 24fps" — the principles).
25
+ const MATH_STEPS_GOLD = `max(${GRID_REMAINDER}, round(a * 24)) + (${GRID_REMAINDER} - (max(${GRID_REMAINDER}, round(a * 24)) % ${GRID_STEP_FRAMES})) % ${GRID_STEP_FRAMES}`;
26
+
27
+ // finding #4): MiniMaxH3ImageToVideo exists in the serialized graph
28
+ // ONLY as the t4r family marker (finalizeH3 keys on it to skip the
29
+ // t4 autofill strip). It is FULLY ORPHANED — no switch consumes it,
30
+ // so no switch can ever select it. The old dead branch carried a
31
+ // 700-char sprinting-city gold prompt through every request sidecar:
32
+ // an off-topic injection-shaped blob and a live hazard the day a
33
+ // switch flipped. Orphan + stub prompt = the marker law kept, the
34
+ // hazard structurally dead.
35
+ const I2V_MARKER_PROMPT = 'i2v marker branch — orphaned, never executed (r2v is the only lane)';
36
+ // ImageSharpenKJ's grouped-widget defaults (the rcas block the python
37
+ // builds when no sharpen leaf is injected; the card exposes only the
38
+ // strength leaf — sharpen_strength).
39
+ const SHARPEN_DEFAULTS = { method: 'rcas', strength: 0.3, radius: 1.0, threshold: 0.05, iterations: 10 };
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+ const LANE_FILES = {
53
+ clip: 'qwen3vl_32b_minimax_h3_int8_convrot.safetensors',
54
+ vae_video: 'minimax_h3_video_vae_int8_convrot.safetensors',
55
+ vae_audio: 'minimax_h3_audio_vae_fp32.safetensors',
56
+ sr_vae: 'ema_vae_fp16.safetensors',
57
+ };
58
+
59
+
60
+
61
+
62
+
63
+
64
+ const FILM_BIT_DEPTH = 8;
65
+ export function parseH3Facts(raw) {
66
+ const lane = (raw ?? {});
67
+ const unet = lane.unet;
68
+ // CARVE (F4 verification D5): stricter than requireText on purpose —
69
+ // this lane refuses whitespace-only unets (trim), the kit helper
70
+ // refuses only ''. Consolidating onto the helper would silently
71
+ // relax this law.
72
+ if (typeof unet !== 'string' || unet.trim() === '') {
73
+ throw new Error(`h3 film: lane_inputs.unet = ${JSON.stringify(unet)} — a non-empty string is required`);
74
+ }
75
+ return { unet, clip: LANE_FILES.clip, vae_video: LANE_FILES.vae_video, vae_audio: LANE_FILES.vae_audio };
76
+ }
77
+ /** The overlay re-check the film loop voices per stanza (the same
78
+ * carrier the card's compose gate walks — ONE schema, imported).
79
+ * Exported so the card's single-call lift judges through the same
80
+ * re-check (the h3-b duplicate is gone: one owner). */
81
+ export const assertOverlayGated = (doc, where) => {
82
+ try {
83
+ paramSchema(doc);
84
+ }
85
+ catch (e) {
86
+ throw new Error(`${where}: ${String(e)}`);
87
+ }
88
+ };
89
+ /** THE MERGED FILM: ONE prompt, N windows under `window${k}_`
90
+ * scopes (GraphBuilder.scoped), with real seam edges between scopes
91
+ * (the executor orders windows off the graph) and per-window
92
+ * stanzas in the renderer vocabulary (k, ctx_save_clip_index, the
93
+ * per-call knobs REPLACE, the span rider per window). The seam is
94
+ * the studio's document law (docModel): transition 'extend' (absent
95
+ * = extend) chains the previous LATENT; 'cut' is a fresh window, and
96
+ * 'cut' + first_frame_prev_sec opens from the previous VIDEO tail
97
+ * (the node's context_frames arm). prev_sec scales the carry:
98
+ * picture snapped to the node's legal context lengths (5/22/39/56
99
+ * frames — only whole latent steps), audio at 24 frames/second. */
100
+ function renderH3Film(p, g, facts) {
101
+ // (the compose dispatch guarantees calls is a non-empty array here)
102
+ const calls = p.calls;
103
+ const str = (v) => (typeof v === 'string' ? v : '');
104
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
105
+ let prev;
106
+ // every window's SaveVideo passthrough, in film order — the film
107
+
108
+ // last-save-only boundary left cut windows' saves unordered)
109
+ const windowSaves = [];
110
+
111
+ // composition — the ENGINE'S job, never a harness-side ffmpeg).
112
+
113
+ // MotionContext seam exists): ONE mechanic, automatic — the
114
+ // TimelineDirector drift-control continuation. Every window k≥2
115
+ // carries the previous window's sampled latent through
116
+ // MiniMaxH3FiniteLatentContinuation (schedule-matched prefix noise
117
+ // + Soft AV audio release); a 'cut' call is their overlap-0 arm
118
+ // (independent windows, no guidance). No seam vocabulary, no
119
+ // modes — the film accumulates through their finalize chain
120
+ // (video: the previous window owns the overlap; audio: the
121
+ // incoming soft-released head owns the join). §20, THREE ACTS
122
+
123
+ // window's tensors until the final CreateVideo — the OOM signature
124
+ // that killed positioned-clips films 3× (a 43h engine); (2) the
125
+ // one-day disk-side valve (estate ffmpeg) died of the operator's
126
+ // provenance law — every artifact traces to a composition of
127
+ // cards, never a harness side-effect; (3) the FILE FORM now below:
128
+ // each window saves its own clip, an unload boundary orders +
129
+ // flushes, and a file-decoding tail assembles the film IN-GRAPH —
130
+ // no tensor ever spans the boundary. The mix math lives in
131
+ // filmMix.ts — one owner, stamps and overlay both.
132
+ // THE CONDITIONING stamps below stay in-graph per-window (what
133
+ // each window HEARS at generation — lip sync lives here). The
134
+ // overlay half (positions, duck spans, the music bus) rides the
135
+ // post-generation MeliteFilmAudioMix for clips-carrying films
136
+ // (the valve's second arm) and the clips-free file tail otherwise
137
+ // — both driven by the same filmMix.ts manifest.
138
+
139
+ // per-window CONDITIONING stamps (the model hears the dialogue:
140
+ // lip sync) read THIS list — parseFilmMixClips (filmMix.ts) is
141
+ // the one law for what a clip IS, shared with the post-generation
142
+ // mix node (its clips_json rows carry the parsed seats verbatim).
143
+
144
+ // clip rides one CLASS — dialogue | sfx | music — one H3 audio
145
+ // input each. Every class runs the SAME machinery (stamp → pin →
146
+ // prompt field → overlay); only the prompt field and the duck
147
+ // relationships differ. Default: a text-carrying row is dialogue
148
+ // (the words law), a textless row is music (the historical
149
+ // Music-row behavior, byte-identical for existing docs).
150
+ const clips = parseFilmMixClips(Array.isArray(p.audio_clips) ? p.audio_clips : []);
151
+ // THE FILM DOC'S SPANS — the clock's own rows, one per call, doc
152
+ // frames with the seam word (filmMix.ts owns the law). The stanza
153
+ // snap rides these (spanStanzaFrames): the render loop below and
154
+ // the film manifest at the tail read the SAME snap from the SAME
155
+ // rows — the two-clocks law, one owner.
156
+ const spans = calls.map((c) => ({
157
+ // the shot-law loop above pins every row's int spans (loud
158
+ // refusals upstream) — no defensive fallback arms to keep alive
159
+ start: c.start_frame,
160
+ end: c.end_frame,
161
+ // the seam word rides RAW — filmMix's spanOverlap owns the one
162
+ // meaningful comparison ('cut' = overlap 0; every other spelling
163
+ // including absent IS extend); no card-side re-encoding
164
+ transition: str(c.transition),
165
+ }));
166
+ // (the clip text law lives where the text is consumed: THE
167
+ // TRANSCRIPT — dialogue words ride the <d> prompt tag, sfx text
168
+ // the soundscape field, music text non_diegetic_music. In every
169
+ // class the text tells the model WHAT the audio is.)
170
+
171
+ // adapter is married to its step count — one lora for four steps,
172
+ // another for eight — so the resolved bag rows carry `steps` and
173
+ // the windows honor it. LAYERING: a call's own knobs > the lora
174
+ // entry's steps > this steps row (the row is the no-distill
175
+ // default; a user-stacked pair runs at the HIGHER count — 8 steps
176
+ // on a 4-step distill is fine, 4 on an 8-step is undercooked).
177
+ const loraRows = Array.isArray(p.loras) ? p.loras : [];
178
+ const loraStepsList = loraRows
179
+ .map((r) => r.steps)
180
+ .filter((v) => typeof v === 'number' && Number.isFinite(v));
181
+ const loraStepsApplied = loraStepsList.length > 0 ? Math.max(...loraStepsList) : null;
182
+ calls.forEach((call, i) => {
183
+ const k = i + 1;
184
+ const guide = str(call.image ?? call.ref_image ?? call.image_name);
185
+ // A CALL OWNS ITS TEXT (the operator's no-fallbacks law, enforced
186
+
187
+ // a source substitution, the exact crime class the law bans). The
188
+ // directing skill's own contract says it: "A call needs text (or
189
+ // beats — prompt segments WITHIN the call)". The film-level prompt
190
+ // is the single-window shape's text face (lifted there by the
191
+ // single-call mapping) — NEVER a per-call substitute.
192
+ let text = typeof call.text === 'string' ? call.text.trim() : '';
193
+ if (text === '') {
194
+ throw new Error(`calls[${i}]: a call needs its own text — the film-level prompt is not a fallback (write the shot's text on the call)`);
195
+ }
196
+
197
+ // call is the director's overlap-0 arm (independent windows — no
198
+ // continuation, no guidance, nothing carried); every other seam
199
+ // rides the drift-control continuation at their proven default
200
+ // (22 frames ≈ 0.92s). first_frame_prev_sec retired with the
201
+ // MotionContext seam — cross-run continuity is the FL2VA anchor
202
+ // (set the first-frame square to the previous film's last frame).
203
+ const overlap = transitionOverlap(typeof call.transition === 'string' ? call.transition : undefined);
204
+ const knobs = (call.knobs ?? {});
205
+ // refs are a LAYER B (per-call) property — the reference bundle
206
+ // rides the stanza; a refs-carrying call is t4r EVEN without a
207
+ // guide still (the bundle IS the r2v input). The DECLARED input
208
+ // surface (ref_images/ref_videos/ref_audios — Layer A, the
209
+ // card's own params) implies t4r by the same law.
210
+ const rb = (call.refs ?? {});
211
+ const declaredRefCount = wireList(p.ref_images).length + wireList(p.ref_videos).length + wireList(p.ref_audios).length;
212
+ const hasRefs = declaredRefCount + wireList(rb.images).length + wireList(rb.videos).length + wireList(rb.audios).length > 0;
213
+ const chainLike = i > 0 && overlap > 0;
214
+ const sf = num(call.start_frame);
215
+ const ef = num(call.end_frame);
216
+ const stamps = {};
217
+ if (sf !== null && ef !== null && Number.isFinite(sf) && Number.isFinite(ef) && ef > sf) {
218
+ const carry = i > 0 ? overlap : 0;
219
+ const genStart = sf - carry;
220
+ for (let ci = 0; ci < clips.length; ci++) {
221
+ const clip = clips[ci];
222
+ if (clip.dur <= 0)
223
+ continue;
224
+ if (stamps[clip.cls] !== undefined)
225
+ continue; // one lane per class per window
226
+ const lo = Math.max(clip.start, genStart);
227
+ const hi = Math.min(clip.start + clip.dur, ef);
228
+ if (hi - lo < 2.4)
229
+ continue; // below the slice node's 0.1s floor
230
+ const ms = (frames) => Math.round((frames / 24) * 1000) / 1000;
231
+ stamps[clip.cls] = {
232
+ src: clip.src,
233
+ slice_start_seconds: ms(Math.max(0, genStart - clip.start)),
234
+ slice_duration_seconds: ms(hi - lo),
235
+ delay_seconds: ms(Math.max(0, clip.start - genStart)),
236
+ text: clip.text,
237
+ };
238
+ // (§20: the conditioned set moved to filmMix.ts — the
239
+ // post-generation mix node derives it from the same stamp
240
+ // law. The stamps themselves stay: THIS window hears them.)
241
+ }
242
+ }
243
+ // THE PROMPT FIELDS (the guide's law, one per lane): dialogue
244
+ // rides <d> tags — the exact words at the stamp's LOCAL time
245
+ // (MM:SS.mmm, the window's own clock), never translated or
246
+ // rewritten; this is the half the audio-only conditioning
247
+ // lacked: the audio pins the voice, the tag moves the mouth.
248
+ // SFX rides the soundscape field at its onset time (the model
249
+ // HEARS the blast and times the visual to it); music rides
250
+ // non_diegetic_music. Same delay number, same clock.
251
+ const stampClock = (t) => {
252
+ const mm = String(Math.floor(t / 60)).padStart(2, '0');
253
+ const ss = String(Math.floor(t % 60)).padStart(2, '0');
254
+ const mmm = String(Math.round((t % 1) * 1000)).padStart(3, '0');
255
+ return `${mm}:${ss}.${mmm}`;
256
+ };
257
+ // ONE overall_soundscape FIELD per window (finding 11,
258
+
259
+ // stamp and an sfx stamp once composed TWO fields with separate
260
+ // `At MM:SS.mmm` clocks in one prompt — the format admits one
261
+ // field, and no authoring move avoided it short of dropping a
262
+ // lane. The sentences collect in lane order (dialogue first,
263
+ // then sfx — the historical append order) and ride a single
264
+ // field; each sentence keeps its own lane clock (the one-clock
265
+ // law trims a doubled clock off ONE text, never across lanes).
266
+ const soundscapeSentences = [];
267
+ if (stamps.dialogue !== undefined && stamps.dialogue.text !== '') {
268
+ const t = stampClock(stamps.dialogue.delay_seconds);
269
+ // SPEAKER-NEUTRAL (attempt-019 maker finding): the stamp once
270
+ // hard-coded "She says" — a plainly male harbourmaster got a
271
+ // female pronoun in his own mouth. The speaker is whoever the
272
+ // window shows; the stamp never genders them.
273
+ soundscapeSentences.push(`At ${t}, the on-screen speaker says the line below, mouth visible and articulating the words; room tone continues underneath.\nThe line: <d>[English] ${stamps.dialogue.text}</d>`);
274
+ }
275
+ if (stamps.sfx !== undefined && stamps.sfx.text !== '') {
276
+
277
+ // opens with its own "At MM:SS.mmm," clock must not carry two clocks —
278
+ // the stamp's clock is canonical, the authored one is trimmed.
279
+ const sfxText = stamps.sfx.text
280
+ .replace(/^\s*at\s+\d{1,2}:\d{2}(?:\.\d{1,3})?\s*[,-]\s*/i, '');
281
+ soundscapeSentences.push(`At ${stampClock(stamps.sfx.delay_seconds)}, ${sfxText}`);
282
+ }
283
+ if (soundscapeSentences.length > 0) {
284
+ text = text.replace(/\s+$/, '') + '\n\noverall_soundscape:\n' + soundscapeSentences.join('\n');
285
+ }
286
+ if (stamps.music !== undefined && stamps.music.text !== '') {
287
+ text = text.replace(/\s+$/, '') +
288
+ `\n\nnon_diegetic_music:\n${stamps.music.text}`;
289
+ }
290
+
291
+ // law, paid for on the BRIEF9 films): unless the model is told
292
+ // 'no speech' OR given speech-carrying audio, it INVENTS random
293
+ // gibberish dialogue. A window with no dialogue stamp and no
294
+ // live ref audios is exactly that window — an sfx/music bed does
295
+ // NOT count (the first BRIEF9 window carried the bed on the sfx
296
+ // lane and still gibberished; only the dialogue-conditioned
297
+ // window came out clean). The card stamps the indicator itself:
298
+ // model memory is not a seat. Ref audios count as audio input
299
+ // only when the door guard leaves them live (an unstamped
300
+ // window); an authored indication of any spelling ('no speech',
301
+ // 'no dialogue', 'no voice') is honored, never doubled.
302
+ const voicePinnedHere = stamps.dialogue !== undefined || stamps.sfx !== undefined;
303
+ const hearsRefAudio = !voicePinnedHere
304
+ && (wireList(p.ref_audios).length > 0 || wireList(rb.audios).length > 0);
305
+ if (stamps.dialogue === undefined && !hearsRefAudio && !/\bno[\s_-]*(speech|dialogue|voice)/i.test(text)) {
306
+ text = text.replace(/\s+$/, '') +
307
+ '\n\noverall_soundscape:\nNo speech or dialogue in this shot — ambient and effects only; nobody speaks on screen and there is no voice-over.';
308
+ }
309
+ const stanza = { ...p, ...knobs, prompt: text, k };
310
+ const anyStamp = stamps.dialogue !== undefined || stamps.sfx !== undefined || stamps.music !== undefined;
311
+ stanza.variant = (guide !== '' || hasRefs || anyStamp) ? 't4r' : chainLike ? 't4_chain' : 't4_open';
312
+ // the distill's steps apply unless this call's knobs pinned steps
313
+ if (knobs.steps === undefined && loraStepsApplied !== null)
314
+ stanza.steps = loraStepsApplied;
315
+ // THE DOOR GUARD, voice arm: a dialogue/sfx-pinned window mutes
316
+ // the user ref audios (film-level and per-call) — the pins own
317
+ // that window's audio conditioning; the ref doors reopen on
318
+ // unstamped windows.
319
+ const voicePinned = stamps.dialogue !== undefined || stamps.sfx !== undefined;
320
+ if (voicePinned)
321
+ delete stanza.ref_audios;
322
+ if (hasRefs)
323
+ stanza.refs = voicePinned && Array.isArray(call.refs?.audios)
324
+ ? { ...call.refs, audios: undefined }
325
+ : call.refs;
326
+ if (guide !== '')
327
+ stanza.image = guide;
328
+ else
329
+ delete stanza.image;
330
+ if (sf !== null && ef !== null && ef > sf) {
331
+ // THE UNIFORM SPAN GATE, second door: a stale or hand-built
332
+ // document re-rides the same law the walk admitted under, so
333
+ // the compose carrier refuses an off-grid span before any node
334
+ // is built (zero GPU) instead of trusting the render snap.
335
+ assertSpanGrid(spans[i], `h3-timeline window ${k}`, chainLike ? overlap : 0);
336
+ }
337
+ // per-window length: the span rider law, unless the call's knobs pin one
338
+ if (sf !== null && ef !== null && ef > sf && knobs.length === undefined) {
339
+
340
+ // covers carry + span — the finalize trims the carried head
341
+ // off the SAVED clip, so the span's tail must exist inside
342
+ // the generation. chainLike is the render's own carry law
343
+ // (i>0 and a non-cut seam) — the same number filmMix's
344
+ // stanzaSecs states (the two-clocks law, still one owner).
345
+ stanza.length = spanStanzaFrames(spans[i], chainLike ? overlap : 0);
346
+
347
+ // film): the window's VIDEO length derives from fps_seconds
348
+ // (the builder's ComfyMathExpression reads it; the length
349
+ // param alone only feeds the film clock's accounting). A doc
350
+ // whose spans disagree with the stale fps_seconds renders
351
+ // uniform 10s windows while the clock books doc spans — the
352
+ // film clock and the render MUST state the same window.
353
+ // (The snap itself is filmMix's spanStanzaFrames — the ONE
354
+ // law the render loop and the film manifest share; the old
355
+ // inline 22+17k twin died here.)
356
+ if (knobs.fps_seconds === undefined) {
357
+ stanza.fps_seconds = Math.round((stanza.length / 24) * 1000) / 1000;
358
+ }
359
+ }
360
+ // THE GRID GATE (§26): a knob-pinned length bypassed the snap
361
+ // above — validate, never trust. Refuses at compose (zero GPU)
362
+ // with the span, the nearest legal length, and the proven
363
+ // geometry in the message.
364
+ assertGridLength(stanza.length, `h3-timeline window ${k} (span ${sf}→${ef})`);
365
+ if (i > 0) {
366
+ stanza.__iteration = k - 1;
367
+ stanza.__overlap = overlap;
368
+ }
369
+ if (prev !== undefined)
370
+ stanza.__prev = prev;
371
+
372
+ // bed arm retired with the bed the same day): a pinned window
373
+ // owns its audio conditioning — the normal inputs stand down for
374
+ // THAT window so nothing double-feeds the same generation. The
375
+ // dialogue/sfx arm strips the user's ref_audios on stamped
376
+ // windows (the pins own those lanes); the music arm has nothing
377
+ // left to guard since the bed left. Per-window, never film-wide.
378
+ assertOverlayGated(stanza, `h3-timeline window ${k} knobs`);
379
+
380
+ // nodes, nothing holds a prior window's tensors — each window
381
+ // frees after its own SaveVideo. The film tail below assembles
382
+ // from the SAVED FILES (decode after every save), never from
383
+ // window tensors.
384
+ // the conditioning stamps ride the stanza (what THIS window
385
+ // hears at generation — the Slice → pin chain reads them).
386
+ if (stamps.dialogue !== undefined)
387
+ stanza.dialogue_slice = stamps.dialogue;
388
+ if (stamps.sfx !== undefined)
389
+ stanza.sfx_slice = stamps.sfx;
390
+ if (stamps.music !== undefined)
391
+ stanza.music_slice = stamps.music;
392
+ const h = g.scoped(`window${k}_`, (w) => renderH3Window(stanza, w, facts));
393
+ prev = h;
394
+ /* v8 ignore next 1 -- both family arms assign the passthrough (every path saves); a future arm that forgets is refused loud at the film tail */
395
+ if (h.savePassthrough !== undefined)
396
+ windowSaves.push(h.savePassthrough);
397
+ });
398
+
399
+ // operator's provenance law: every artifact traces to a
400
+ // composition of cards, never a harness side-effect) ──────────────
401
+ //
402
+ // The ORIGINAL tail consumed every window's tensors as graph data
403
+ // (the scheduler kept the whole film's backlog alive while later
404
+ // windows sampled — the 43h-OOM signature). The disk-side valve
405
+ // that replaced it died the same day (out-of-band ffmpeg). THIS
406
+ // tail inverts the memory law while staying in-graph, in TWO arms:
407
+ //
408
+ // CLIPS-FREE films (the 27-film precedent — never OOM'd):
409
+ // 1. every window SAVES its own clip (h3_t4_w<k>) — its tensors
410
+ // die at that SaveVideo (nothing downstream consumes them);
411
+ // 2. ONE MeliteUnload boundary PER window save, token-chained
412
+
413
+ // single boundary on the last save assumed "windows chain, so
414
+ // the last save is downstream of them all" — FALSE for cut
415
+ // films, which chain nothing; window 2's save was an unordered
416
+ // island and the loader could beat it) — every boundary flushes
417
+ // the allocator WITHOUT dropping model weights (the next run
418
+ // pays no reload), and the chain's final token provably waits
419
+ // for EVERY save;
420
+ // 3. MeliteConcatVideos decodes the saved FILES back in
421
+ // (IMAGE+AUDIO+fps) — CPU-side, strictly after every save;
422
+ // 4. CreateVideo → SaveVideo h3_t4_film. The film is a graph
423
+ // output; the estate's engineFilmName presents it first.
424
+ //
425
+
426
+ // VRAM-leak fix, operator law: WE USE COMFYUI, NEVER FFMPEG for
427
+ // the mix; GAP 1 CLOSED same night — the arm delivers the film
428
+ // mp4): the retired in-graph film stitch (film-time Delay/Mix/
429
+ // Duck over live window tensors) held every window resident
430
+ // until the final save — the accumulation that OOM'd a
431
+ // two-window BRIEF9 film at 20.57 GiB. These films take the valve
432
+ // path (windows save per-window and free behind the same chained
433
+ // boundaries — steps 1–2 above) PLUS one post-generation
434
+ // MeliteFilmAudioMix (Layer C, torch, the estate's own node):
435
+ // window audio files + the manifest's clips/duck law in,
436
+ // SaveAudio h3_t4_film_audio stem out — AND the same file-tail
437
+ // video join (MeliteConcatVideos → CreateVideo → SaveVideo
438
+ // h3_t4_film) with the MIXED audio wired in. No film-time
439
+ // Delay/Mix/Duck/LoadAudio — the graph holds windows only
440
+ // during generation.
441
+ //
442
+ // (Single-window docs never reach this tail — the compose
443
+ // dispatch keeps the frozen single-window shape byte-identical;
444
+ // the film is a MULTI-call property, and the single-call mapping
445
+ // refuses clips loudly downstream of the dispatch.)
446
+ /* v8 ignore next 1 -- both family arms assign the passthrough (every path saves); a future arm that forgets refuses here, loudly */
447
+ if (windowSaves.length === 0) {
448
+ throw new Error('[h3-timeline] a family arm saved no clip to pass the film boundary — the film tail cannot order its loads');
449
+ }
450
+ const manifest = computeFilmMix({
451
+ spans,
452
+ clips,
453
+ windowSecs: stanzaSecs(spans),
454
+ // the knob's declared default (−14) walks through the schema
455
+ // door; computeFilmMix owns the fallback for the absent key
456
+ duckDb: p.duck_depth_db,
457
+ });
458
+
459
+ // cut-film ordering fix — receipts run-1057a53c4252 (stale-file
460
+ // stitch: 960×576 leftovers globbed as windows) and
461
+ // run-18ea8c810104 (loud no-match refusal on h3_t4_w2): cut
462
+ // windows chain NOTHING and even chained windows' SAVE nodes are
463
+ // not downstream of one another, so the old single boundary on
464
+ // the LAST save rode a scheduler tie-break — window 2's save was
465
+ // an unordered island the loader could beat). Every window's
466
+ // SaveVideo passthrough feeds its OWN boundary; each boundary's
467
+ // optional 'after' wires the prior boundary's token, so the final
468
+ // token (the concat's 'after') transitively depends on EVERY
469
+ // save — and each window's passthrough tensor still dies at its
470
+ // own boundary (the §20 law; the flush is idempotent, weights
471
+ // stay resident).
472
+ let boundaryAfter;
473
+ for (const save of windowSaves) {
474
+ boundaryAfter = g.node('MeliteUnload', {
475
+ video: save, unload_models: false,
476
+ ...(boundaryAfter !== undefined ? { after: boundaryAfter } : {}),
477
+ }).out(0);
478
+ }
479
+ const after = boundaryAfter;
480
+ if (clips.length > 0) {
481
+
482
+
483
+ // delivers the film mp4 too): ONE MeliteFilmAudioMix composes
484
+ // the film's audio post-generation from the saved window files
485
+ // + the manifest's clips/duck law (the SAME Delay/Mix/Duck
486
+ // methods the retired tail called, in the SAME order — now
487
+ // torch-side inside the estate's own node, never ffmpeg).
488
+ // SaveAudio emits the stem; the VIDEO join is the clips-free
489
+ // arm's own machinery (MeliteConcatVideos decodes the saved
490
+ // files CPU-side strictly after every save — windows' tensors
491
+ // died at their SaveVideos, so no accumulation returns) with
492
+ // the MIXED audio wired into CreateVideo — the film mp4 carries
493
+ // the mix, not the raw concat audio. Early return: the
494
+ // clips-free arm below stays byte-frozen.
495
+ const mix = g.node('MeliteFilmAudioMix', {
496
+ videos: calls.map((_c, i) => `h3_t4_w${i + 1}`).join(','),
497
+ after,
498
+ // the manifest rendered verbatim: every placement's source,
499
+ // film seat, duration, and class — doc order kept (the node's
500
+ // two loops read the same order the retired tail did)
501
+ clips_json: JSON.stringify(manifest.placements.map((pl) => {
502
+ const clip = clips[pl.clip];
503
+ return { src: clip.src, start_sec: pl.filmSec, dur_sec: pl.durSec, class: pl.cls };
504
+ })),
505
+ duck_spans: manifest.duckSpanString,
506
+ music_duck_spans: manifest.musicDuckSpanString,
507
+ duck_db: manifest.duckDb,
508
+ film_seconds: manifest.filmSec,
509
+ });
510
+
511
+ // passthrough tap between the mix and its consumers — the film's
512
+ // integrated loudness (BS.1770-4, K-weighted + gated) rides the
513
+ // history UI dict as loudness_lufs, so every surface REPORTS the
514
+ // number instead of re-deriving it from the encoded file. The
515
+ // AUDIO dict rides out unchanged (meter taps, never transforms);
516
+ // calibrated against ffmpeg's ebur128 to within 0.1 LU on tones,
517
+ // noise, gating, and mono.
518
+ const meter = g.node('MeliteLoudness', { audio: mix.out(0) });
519
+ saveAudio(g, meter.out(0), 'h3_t4_film_audio');
520
+ // THE FILM MP4 (GAP 1): the same file-tail video join the
521
+ // clips-free arm rides — container mux only (CreateVideo +
522
+ // SaveVideo h264/mp4 on the decoded window files), never the
523
+ // mix. The mix rides it: audio carries the node's output.
524
+ const join = g.node('MeliteConcatVideos', {
525
+ videos: calls.map((_c, i) => `h3_t4_w${i + 1}`).join(','),
526
+ after,
527
+ });
528
+ const filmCreated = g.node('CreateVideo', {
529
+ images: join.out(0), audio: meter.out(0), fps: join.out(2), bit_depth: FILM_BIT_DEPTH,
530
+ });
531
+ return g.node('SaveVideo', {
532
+ video: filmCreated.out(), filename_prefix: 'h3_t4_film',
533
+ format: 'mp4', codec: 'h264',
534
+ }).out();
535
+ }
536
+ const concat = g.node('MeliteConcatVideos', {
537
+ videos: calls.map((_c, i) => `h3_t4_w${i + 1}`).join(','),
538
+ after,
539
+ });
540
+ const filmCreated = g.node('CreateVideo', {
541
+ images: concat.out(0), audio: concat.out(1), fps: concat.out(2), bit_depth: FILM_BIT_DEPTH,
542
+ });
543
+ return g.node('SaveVideo', {
544
+ video: filmCreated.out(), filename_prefix: 'h3_t4_film',
545
+ format: 'mp4', codec: 'h264',
546
+ }).out();
547
+ }
548
+ function renderH3Window(p, g, facts) {
549
+ // REFS IMPLY THE R2V LANE (the bundle IS the r2v input): a
550
+ // refs-carrying window is t4r even without a guide still — the
551
+ // same law the film renderer applies per call. The DECLARED input
552
+ // surface (ref_images/ref_videos/ref_audios — the typed fields)
553
+ // implies t4r by the same law.
554
+ const rb0 = (p.refs ?? {});
555
+ const declaredCount = wireList(p.ref_images).length + wireList(p.ref_videos).length + wireList(p.ref_audios).length;
556
+ const hasRefs = declaredCount + wireList(rb0.images).length + wireList(rb0.videos).length + wireList(rb0.audios).length > 0;
557
+ if (hasRefs && p.variant !== 't4r')
558
+ p = { ...p, variant: 't4r' };
559
+ const family = p.variant;
560
+ if (!FAMILIES.includes(family)) {
561
+ throw new Error(`unknown window family '${String(p.variant)}' (known: ${[...FAMILIES].sort().join(', ')})`);
562
+ }
563
+ const k = (p.k ?? 1);
564
+ // THE GRID GATE (§26, defense in depth): no window renders
565
+ // off-grid — the film loop's pin check voices the call span, this
566
+ // one catches the single-call path and any direct caller.
567
+ assertGridLength(p.length, `h3-timeline window ${k}`);
568
+ const isT4r = family === 't4r';
569
+ const isChain = family === 't4_chain';
570
+
571
+ // is the fresh-card admission, not a fallback crime. The window
572
+ // shape's text face is p.prompt (declared required=True, "optional
573
+
574
+ // card.spec.ts "a fresh press composes") admits an absent/blank
575
+ // prompt as empty conditioning — the fresh-card one-shot document
576
+ // renders. The film path refuses textless calls instead (the
577
+ // no-fallbacks law at the calls walk); the single-call LIFT may
578
+ // lawfully write p.prompt from call text because in the one-window
579
+ // shape p.prompt IS the text owner — never a substitute.)
580
+ const prompt = (p.prompt ?? '');
581
+ // card knob first (image), renderer alias second.
582
+ const guideImage = (p.image ?? p.image_name ?? '');
583
+ // ── the model chain (family-conditional defaults;
584
+ // absent = absent on wire) ──
585
+ const stabilize = p.sla_stabilize_motion ?? (isT4r ? false : true);
586
+ const unet = g.node('UNETLoader', { unet_name: facts.unet, weight_dtype: 'default' }).out();
587
+ const sla = g.node('H3SLAAttention', {
588
+ model: unet,
589
+ sparsity_ratio: p.sla_sparsity,
590
+ block_size: p.sla_block_size,
591
+ min_seq_len: p.sla_min_seq_len,
592
+ dense_last_steps: p.sla_dense_last_steps,
593
+ protect_audio: p.sla_protect_audio,
594
+ enabled: true,
595
+ dense_steps: p.sla_dense_steps,
596
+ dense_backend: p.sla_dense_backend,
597
+ disable_fp16_accum: p.sla_disable_fp16_accum,
598
+ stabilize_motion: stabilize,
599
+ reference_protection: p.sla_reference_protection,
600
+ }).out();
601
+ const chunked = g.node('MiniMaxChunkFeedForward', {
602
+ model: g.node('MiniMaxLowVRAMAttention', { model: sla, head_chunks: 4 }).out(),
603
+ chunks: 2, seq_threshold: 4096,
604
+ }).out();
605
+
606
+
607
+ // `lora_stack` string field is DEAD): the studio/agent surface
608
+ // writes the mod bag `loras` — [{id, strength}] rows the service
609
+ // resolves to {name, strength} filenames against the family's
610
+ // flavor catalog. Those rows build the upstream stack verbatim
611
+ // ({on, lora, str, v:1, a:1, t:1}); an empty bag rides the
612
+ // family catalog's turbo row (the mod plane's own default, built
613
+ // from the catalog so the value has one owner). ONE surface, one
614
+ // owner.
615
+ const loraStack = Array.isArray(p.loras) && p.loras.length > 0
616
+ ? JSON.stringify(p.loras.map((r) => ({
617
+ // the service resolves every row against the family catalog
618
+ // (unknown ids refuse LOUD upstream) — {name, strength} is
619
+ // the guaranteed wire shape, read directly
620
+ on: true,
621
+ lora: r.name,
622
+ str: r.strength,
623
+ v: 1, a: 1, t: 1,
624
+ })))
625
+ : loraStackDefault();
626
+ // t4r templates carry shift_video 8.0; the t4 family carries the INT
627
+ // NO SILENT RESOLUTION LAW: the walked shift_video IS the value
628
+ // (declared default 8; the family literals retired with the
629
+ // nulling that fed them — 8.0 and 8 serialize identically anyway)
630
+ const shiftVideo = p.shift_video;
631
+ const clip = g.node('CLIPLoader', {
632
+ clip_name: facts.clip, type: 'minimax',
633
+ ...(isT4r ? { device: 'default' } : {}), // t4 templates OMIT it
634
+ }).out();
635
+ const vaeVideo = g.node('VAELoader', { vae_name: facts.vae_video }).out();
636
+ const vaeAudio = g.node('VAELoader', { vae_name: facts.vae_audio }).out();
637
+ let cond;
638
+ let latent;
639
+ let sigmaModel;
640
+ let fpsInput;
641
+ if (isT4r) {
642
+ // opener: switch(SLABool) picks SLA-direct vs chunked; lora rides
643
+ // the switch; preview override wired to the in-graph step count.
644
+ // Inject semantics: an injected SCALAR replaces the bool NODE
645
+ // (template link severed, node orphaned) — mirrored by passing the
646
+ // scalar straight when sla_switch is set. sla_enabled=false
647
+ // forces the chunked (SLA-off) path; otherwise the legacy
648
+ // sla_switch spelling rides untouched.
649
+ const fpsNode = g.node('PrimitiveFloat', { value: 24.0 }).out(); // id .0 — CreateVideo.fps walks first
650
+ let slaSel = p.sla_enabled === false
651
+ ? true
652
+ : (p.sla_switch ?? null);
653
+ if (slaSel === null)
654
+ slaSel = g.node('PrimitiveBoolean', { value: false }).out();
655
+ const picked = g.node('ComfySwitchNode', { switch: slaSel, on_true: chunked, on_false: sla }).out();
656
+ const loraModel = g.node('LTX_lora_loader', {
657
+ model: picked, mode: 'minimax', stack_data: loraStack, lora_ui: '',
658
+ }).out();
659
+ const seconds = g.node('PrimitiveFloat', { value: p.fps_seconds }).out(); // id .1
660
+ const lengthNode = g.node('ComfyMathExpression', {
661
+ expression: MATH_STEPS_GOLD, 'values.a': seconds,
662
+ }).out(1);
663
+ const previewed = g.node('ModelPreviewOverrideKJ', {
664
+ max_resolution: 512, jpeg_quality: 80,
665
+ suppress_default_preview: true, preview_frames: lengthNode,
666
+ preview_fps: 8, tiny_vae: 'none', model: loraModel,
667
+ }).out();
668
+ const adaln = g.node('H3AdaLNLoRAFix', { model: previewed, mode: 'port' }).out();
669
+ sigmaModel = g.node('MiniMaxH3SigmaShift', {
670
+ model: adaln, shift_video: shiftVideo, shift_audio: p.shift_audio,
671
+ }).out();
672
+ // THE ANCHOR + THE REFERENCE BUNDLE (the operator's distinction,
673
+
674
+ // the frozen served shape); `refs` is the call's REFERENCE bundle
675
+ // — the upstream "Extra References" subgraph's own vocabulary
676
+ // (LoadImage → the ref resizer; LoadVideo → GetVideoComponents →
677
+ // the image+audio component pair; LoadAudio). Bundle layout (the
678
+ // slot map): inputs 1-9 images (anchor first), 10/12/14
679
+ // video image streams, 11/13/15 video audio streams, 16-18
680
+ // audios. RESIZER ORDER IS PINNED: the serialized walk reaches
681
+ // the reference resizer (bundle → r2v refs) before the geometry
682
+ // resizer (i2v) — creation mirrors the walk.
683
+ const refBag = (p.refs ?? {});
684
+ // THE DECLARED-SURFACE MERGE (the input rail's law): the typed
685
+ // fields (ref_images/ref_videos/ref_audios — Layer A, stamped
686
+ // onto every stanza) are PRIMARY; the legacy stanza bag's
687
+ // entries append, deduped. One wire form, one reader.
688
+ const declaredImages = wireList(p.ref_images);
689
+ const declaredVideos = wireList(p.ref_videos);
690
+ const declaredAudios = wireList(p.ref_audios);
691
+ // THE 9-SLOT IMAGE BUS (the bundle's own topology — the compose
692
+ // and the UI agree or they lie): inputs 1-9 are IMAGE slots —
693
+ // the anchor at 1, the FL2VA pair's END anchor at 2 when
694
+ // last_frame is set, references at 3..9 (7 with an end anchor,
695
+ // 8 riding input_2..9 without one); input_10 begins the video
696
+ // lanes. A 9th ref would land ON input_10 — the first video's
697
+ // image stream — and be silently clobbered; the law refuses
698
+ // LOUD instead.
699
+ const lastFrame = (p.last_frame ?? '');
700
+ const refImagesAll = mergeDeclaredRefs(declaredImages, wireList(refBag.images));
701
+ const imageCap = imageReferenceCap(lastFrame !== '');
702
+ if (lastFrame !== '' && refImagesAll.length > imageCap) {
703
+ throw new Error(`[h3-timeline] the image bus is full: a last frame (input 2) + ${String(refImagesAll.length)} references exceeds the ${IMAGE_BUS_SLOTS}-slot bus — keep references ≤ ${imageCap} with an end anchor (≤ ${REF_CAPS.images} without)`);
704
+ }
705
+ const refImages = refImagesAll.slice(0, imageCap);
706
+ const refVideos = mergeDeclaredRefs(declaredVideos, wireList(refBag.videos)).slice(0, REF_CAPS.videos);
707
+ const refAudios = mergeDeclaredRefs(declaredAudios, wireList(refBag.audios)).slice(0, REF_CAPS.audios);
708
+ const bundleInputs = {};
709
+
710
+ // it all"): a '$name' value names a WIRED STAGE INPUT, never a
711
+ // file on disk — the merge (rewriteSpells) lands the upstream
712
+ // producer's tensor link wherever the spell rides, and ROW-4
713
+ // refuses producer links in Load* file slots. So a spelled
714
+ // anchor/last-frame/reference rides its TENSOR slot verbatim
715
+ // and NEVER builds a loader; files/URLs/estate paths keep the
716
+ // Load* disk handoff (the per-stage path owns those). Before
717
+ // this arm the ports validated green at the lattice and died
718
+ // at the merge — the validate-said-nothing disease.
719
+ const isSpell = (s) => s.startsWith('$');
720
+ const imageRef = (src) => isSpell(src) ? src : g.node('LoadImage', { image: src }).out();
721
+ let anchorRaw;
722
+ if (guideImage !== '') {
723
+ anchorRaw = imageRef(guideImage);
724
+ bundleInputs.input_1 = g.node('UnifiedResizeImageMask', {
725
+ image: anchorRaw, scale_mode: 'Shorter Side',
726
+ aspect_ratio: 'Auto (Input Image)', long_side_target: 1024.0,
727
+ short_side_target: 2048.0, width: 1024.0, height: 1024.0,
728
+ multiplier: 1.0, megapixels: 1.0, upscale_method: 'lanczos',
729
+ crop: 'center', divisible_by: 32.0, maintain_aspect: false,
730
+ }).out();
731
+ }
732
+ // THE FL2VA END ANCHOR: input_2 is the pair's second seat — the
733
+ // i2v branch reads out(0)/out(1) as first/last frame verbatim.
734
+ // Without an end anchor, refs ride from input_2 (legacy shelf).
735
+ const resizeRef = (src) => g.node('UnifiedResizeImageMask', {
736
+ image: imageRef(src), scale_mode: 'Shorter Side',
737
+ aspect_ratio: 'Auto (Input Image)', long_side_target: 1024.0,
738
+ short_side_target: 2048.0, width: 1024.0, height: 1024.0,
739
+ multiplier: 1.0, megapixels: 1.0, upscale_method: 'lanczos',
740
+ crop: 'center', divisible_by: 32.0, maintain_aspect: false,
741
+ }).out();
742
+ if (lastFrame !== '')
743
+ bundleInputs.input_2 = resizeRef(lastFrame);
744
+ const firstFreeSlot = lastFrame !== '' ? 3 : 2;
745
+ refImages.forEach((src, i) => {
746
+ const img = imageRef(src);
747
+ if (anchorRaw === undefined && i === 0)
748
+ anchorRaw = img;
749
+ bundleInputs[`input_${firstFreeSlot + i}`] = g.node('UnifiedResizeImageMask', {
750
+ image: img, scale_mode: 'Shorter Side',
751
+ aspect_ratio: 'Auto (Input Image)', long_side_target: 1024.0,
752
+ short_side_target: 2048.0, width: 1024.0, height: 1024.0,
753
+ multiplier: 1.0, megapixels: 1.0, upscale_method: 'lanczos',
754
+ crop: 'center', divisible_by: 32.0, maintain_aspect: false,
755
+ }).out();
756
+ });
757
+ refVideos.forEach((src, i) => {
758
+ // the spelled motion guide rides GetVideoComponents' tensor
759
+ // input directly (the producer's pre-save video tensor); a
760
+ // path keeps the LoadVideo disk handoff.
761
+ const vid = isSpell(src) ? src : g.node('LoadVideo', { file: src }).out();
762
+ const comp = g.node('GetVideoComponents', { video: vid });
763
+ bundleInputs[`input_${10 + 2 * i}`] = comp.out(0);
764
+ bundleInputs[`input_${11 + 2 * i}`] = comp.out(1);
765
+ });
766
+ refAudios.forEach((src, i) => {
767
+ // the spelled sound reference rides the bundle's audio seat
768
+ // directly (the producer's audio tensor); a path keeps
769
+ // LoadAudio.
770
+ bundleInputs[`input_${16 + i}`] = isSpell(src)
771
+ ? src
772
+ : g.node('LoadAudio', { audio: src }).out();
773
+ });
774
+ // the geometry resizer (i2v's dead branch): fed by the anchor, or
775
+ // the first ref image, or — anchorless and imageless — pinned to
776
+ // the literals the geo node's own defaults produce (the branch is
777
+ // never selected; r2vBool pins true below).
778
+ const geoSrc = anchorRaw ?? bundleInputs.input_2;
779
+ let geoW = 768.0;
780
+ let geoH = 1344.0;
781
+ if (geoSrc !== undefined) {
782
+ const geo = g.node('UnifiedResizeImageMask', {
783
+ image: geoSrc, scale_mode: 'Total Pixels (MP)',
784
+ aspect_ratio: '3:4 (Portrait Standard)', long_side_target: 1280.0,
785
+ short_side_target: 768.0, width: 768.0, height: 1344.0,
786
+ multiplier: 1.0, megapixels: 0.98, upscale_method: 'lanczos',
787
+ crop: 'center', divisible_by: 32.0, maintain_aspect: false,
788
+ });
789
+ geoW = geo.out(2);
790
+ geoH = geo.out(3);
791
+ }
792
+ const bundle = g.node('PlagueKindBundleIn', bundleInputs).out();
793
+ const bout = g.node('PlagueKindBundleOut', { bundle });
794
+ // declared knobs hoisted: the compose walk fills their defaults
795
+
796
+ const refSize = p.ref_image_size;
797
+ const r2vInputs = {
798
+ prompt, width: p.width, height: p.height,
799
+ length: lengthNode, ref_image_size: refSize,
800
+ clip, vae: vaeVideo, audio_vae: vaeAudio,
801
+ };
802
+ for (let i = 0; i <= 8; i++)
803
+ r2vInputs[`ref_images.ref_image_${i}`] = bout.out(i);
804
+ for (let i = 0; i < 3; i++) {
805
+ r2vInputs[`ref_videos.ref_video_${i}`] = bout.out(9 + 2 * i);
806
+ r2vInputs[`ref_video_audios.ref_video_audio_${i}`] = bout.out(10 + 2 * i);
807
+ r2vInputs[`ref_audios.ref_audio_${i}`] = bout.out(15 + i);
808
+ }
809
+
810
+ // their natural lanes above — no slice, no shift, no fourth
811
+ // anything.)
812
+ let dialogueAudio;
813
+ let dialogueFrameIdx = 0;
814
+ let sfxAudio;
815
+ let sfxFrameIdx = 0;
816
+ let musicAudio;
817
+ let musicFrameIdx = 0;
818
+
819
+ // film loop stamped on THIS window conditions it — the model
820
+ // HEARS the dialogue (the lip-sync mechanism; the generated
821
+ // voice tracks it, the overlay stays the audible authority and
822
+ // the mix DUCKS the generated voice under the real clip at film
823
+ // time). THE BUS LAW, TOLD LOUD: 3 audio lanes total. Bed +
824
+
825
+ // operator caught the dead lane): the bare ref_audios lane is a
826
+ // soft prior this checkpoint ignores — measured zero correlation
827
+ // on two rendered films. The PINNING lane is MiniMaxH3AddGuide
828
+ // with an audio-only keyframe: the clip's true source segment is
829
+ // anchored INTO the model's own timeline at its generation-frame
830
+ // index (the audio latent rides pinned rows; the video around it
831
+ // generates to match — the inpainting-grade prior). Dialogue no
832
+ // longer consumes a ref lane: bed + user audios keep the full
833
+ // 3-lane budget, and the guide is the dialogue's one owner.
834
+ {
835
+ const read = (key) => (p[key] ?? null);
836
+ const stamp = read('dialogue_slice');
837
+ if (stamp !== null) {
838
+ dialogueAudio = g.node('MeliteAudioSlice', {
839
+ audio: stamp.src,
840
+ start_seconds: stamp.slice_start_seconds,
841
+ duration_seconds: stamp.slice_duration_seconds,
842
+ }).out(0);
843
+ dialogueFrameIdx = Math.round(stamp.delay_seconds * 24);
844
+ }
845
+ const sfxStamp = read('sfx_slice');
846
+ if (sfxStamp !== null) {
847
+ sfxAudio = g.node('MeliteAudioSlice', {
848
+ audio: sfxStamp.src,
849
+ start_seconds: sfxStamp.slice_start_seconds,
850
+ duration_seconds: sfxStamp.slice_duration_seconds,
851
+ }).out(0);
852
+ sfxFrameIdx = Math.round(sfxStamp.delay_seconds * 24);
853
+ }
854
+ const musicStamp = read('music_slice');
855
+ if (musicStamp !== null) {
856
+ musicAudio = g.node('MeliteAudioSlice', {
857
+ audio: musicStamp.src,
858
+ start_seconds: musicStamp.slice_start_seconds,
859
+ duration_seconds: musicStamp.slice_duration_seconds,
860
+ }).out(0);
861
+ musicFrameIdx = Math.round(musicStamp.delay_seconds * 24);
862
+ }
863
+ }
864
+ const r2v = g.node('MiniMaxH3ReferenceToVideo', r2vInputs);
865
+
866
+ // serialized graph carries the t4r family key (finalizeH3's
867
+ // marker), wired to the geometry/anchor slots it always read —
868
+ // but consumed by NOTHING. The old shape routed r2v through a
869
+ // hardcoded-true ComfySwitchNode whose on_false arm was this
870
+ // node: never selected, yet a flipped switch would have run the
871
+ // gold prompt. Direct wiring + an orphan = one lane, one truth.
872
+ g.node('MiniMaxH3ImageToVideo', {
873
+
874
+ // node declares clip/first_frame/height/last_frame/length/
875
+ // prompt/vae/width — context_steps and audio_context_steps
876
+ // are gone from the declaration, and the input wall walks
877
+ // orphans too, so wiring them refused the whole graph
878
+ // (BRIEF15: card_compose unknown-input on this node).
879
+ prompt: I2V_MARKER_PROMPT, width: geoW, height: geoH,
880
+ length: lengthNode,
881
+ clip, vae: vaeVideo, first_frame: bout.out(0), last_frame: bout.out(1),
882
+ });
883
+ cond = r2v.out(0);
884
+ latent = r2v.out(1);
885
+ fpsInput = fpsNode;
886
+
887
+ // its slice into the window's own AV latent at its generation-
888
+ // frame index — the model generates the video (and its own
889
+ // sound) around the pinned audio instead of merely glancing at
890
+ // a soft reference. Guides CHAIN (positive flows through): the
891
+ // dialogue pin lands first (the measured law), then sfx (the
892
+ // model times the blast to the heard transient), then music.
893
+ if (dialogueAudio !== undefined) {
894
+ cond = g.node('MiniMaxH3AddGuide', {
895
+ positive: cond, latent,
896
+ frame_idx: dialogueFrameIdx,
897
+ audio_vae: vaeAudio, audio: dialogueAudio,
898
+ }).out(0);
899
+ }
900
+ if (sfxAudio !== undefined) {
901
+ cond = g.node('MiniMaxH3AddGuide', {
902
+ positive: cond, latent,
903
+ frame_idx: sfxFrameIdx,
904
+ audio_vae: vaeAudio, audio: sfxAudio,
905
+ }).out(0);
906
+ }
907
+ if (musicAudio !== undefined) {
908
+ cond = g.node('MiniMaxH3AddGuide', {
909
+ positive: cond, latent,
910
+ frame_idx: musicFrameIdx,
911
+ audio_vae: vaeAudio, audio: musicAudio,
912
+ }).out(0);
913
+ }
914
+ }
915
+ else {
916
+ // t4 families: the SLA/attention switch rides ABOVE the LoRA
917
+ // loader (the t4r mirror — L1: the old order stacked the loader
918
+ // under the chunked branch only, so sla_enabled=true (the
919
+ // default) picked the bare SLA model and every bagged LoRA
920
+ // silently did nothing while the steps marriage still fired).
921
+ // The switch picks the attention strategy — SLA-direct vs the
922
+ // backend-pinned chunked chain — and ONE loader applies the bag
923
+ // over the pick; the fix-up + shift ride the loaded model on
924
+ // both arms, so no arm bypasses the loader. The backend node
925
+ // stays on the dense branch (pre-switch): it configures that
926
+ // branch's attention implementation, and routing the
927
+ // SLA-patched model through it would risk clobbering the sparse
928
+ // kernels — the switch selects the strategy, the loader samples
929
+ // whichever won. The pin autofills the builder adds (lora_ui,
930
+ // the SeedVR2 tile/offload inputs) are stripped by the finalize
931
+ // pass — the python's _T4_AUTOFILL_STRIP mirror.
932
+ const mab = g.node('ModelAttentionBackend', {
933
+ model: chunked,
934
+ // schema-defaulted knob (the vocabulary door guarantees the
935
+ // field — 'comfy kitchen attention' when the caller stays
936
+ // silent; no compose-side fallback arm to keep alive)
937
+ attention: p.attention_backend,
938
+ }).out();
939
+ const picked = g.node('ComfySwitchNode', {
940
+
941
+ // the dense arm; absent = on (every existing doc). The legacy
942
+
943
+ // no-silent-resolution law: sla_enabled is DECLARED with
944
+ // .default(true), so the walk always delivers a boolean and
945
+ // the fallback arms were unreachable lies.
946
+ switch: p.sla_enabled, on_true: sla, on_false: mab,
947
+ }).out();
948
+ const loraModel = g.node('LTX_lora_loader', {
949
+ model: picked, mode: 'minimax', stack_data: loraStack,
950
+ }).out();
951
+ const adaln = g.node('H3AdaLNLoRAFix', { model: loraModel, mode: 'port' }).out();
952
+ sigmaModel = g.node('MiniMaxH3SigmaShift', {
953
+ model: adaln, shift_video: shiftVideo, shift_audio: p.shift_audio,
954
+ }).out();
955
+
956
+ // readout said 7s — the doc's totalFrames, last end_frame @24 —
957
+ // and the render came back 3, this hardcoded 90 budget). The
958
+ // window's render length derives from the TIMELINE the calls
959
+ // author: last end_frame − first start_frame, SNAPPED TO THE
960
+ // 17k+5 GRID the engine's latent math lawfully renders (22+17k,
961
+ // clamped [22,362] — the same set the length param's own
962
+ // min/step admits; the first 168-span probe died inside
963
+
964
+ // retired 90/56 budgets remain the fallback ONLY for docs that
965
+ // (the length source of truth is UPSTREAM of this renderer: the
966
+ // schema's span rider serializes single-call spans as EXPLICIT
967
+ // length, and the merged film computes per-window lengths — this
968
+ // arm only falls back to the family budgets)
969
+ // NO SILENT RESOLUTION LAW: the walked/stanza length IS the value
970
+ // (single-call: the span rider's explicit span; multi-call: the
971
+ // film total; fresh: the walked default; the 90/56 family budgets
972
+ // retired with the nulling that fed them)
973
+ const length = p.length;
974
+ const r2v = g.node('MiniMaxH3ReferenceToVideo', {
975
+ prompt, width: p.width,
976
+ height: p.height, length: length,
977
+ ref_image_size: p.ref_image_size,
978
+ clip, vae: vaeVideo, audio_vae: vaeAudio,
979
+ });
980
+ cond = r2v.out(0);
981
+ latent = r2v.out(1);
982
+ fpsInput = 24;
983
+ }
984
+ // ── sampler stack ──────────────────────────────────────────────────
985
+ // card knob first (seed), renderer alias second.
986
+ const noise = g.node('RandomNoise', { noise_seed: (p.noise_seed ?? p.seed) }).out();
987
+ const samplerSel = g.node('KSamplerSelect', { sampler_name: p.sampler_name }).out();
988
+ let sampler;
989
+ if (isT4r) {
990
+ sampler = samplerSel;
991
+ }
992
+ else {
993
+ const ersde = g.node('SamplerER_SDE', {
994
+ solver_type: 'ODE', max_stage: 3, eta: 0.0, s_noise: 1.0,
995
+ }).out();
996
+ // template carries switch=false as a LITERAL, not a bool node
997
+ sampler = g.node('ComfySwitchNode', { switch: false, on_true: ersde, on_false: samplerSel }).out();
998
+ }
999
+ const schedName = p.sched_name;
1000
+ const denoiseVal = p.denoise;
1001
+ const sched = g.node('BasicScheduler', {
1002
+ model: sigmaModel, scheduler: schedName,
1003
+ steps: p.steps, denoise: denoiseVal,
1004
+ }).out();
1005
+ let guider = g.node('BasicGuider', { model: sigmaModel, conditioning: cond }).out();
1006
+ let targetLatent = latent;
1007
+
1008
+ // seam is FORGOTTEN — the TimelineDirector drift-control
1009
+ // continuation is the one way, automatic): window k≥2 with a
1010
+ // carried seam rides MiniMaxH3FiniteLatentContinuation — the
1011
+ // previous window's RAW sampled latent becomes this window's
1012
+ // drift-controlled opening (schedule-matched prefix noise: the
1013
+ // carried tail's noise level walks down the sampler's own sigma
1014
+ // schedule, so the model never fights the anchor — the anti-drift
1015
+ // core for unbounded chains), the audio latent rides the Soft AV
1016
+ // half-cosine release (no seam pops), and the MODEL comes back
1017
+ // PATCHED — the guider rebinds to it and the sampler's target is
1018
+ // the MASKED latent. A 'cut' call (overlap 0) and every opener
1019
+ // never mount this block: a true fresh window.
1020
+
1021
+ // t4_chain-only, and the dialogue stamp routes stamped windows to
1022
+ // t4r — a stamped film silently lost the continuation AND the
1023
+ // carried-head trim (two independent windows hard-concatenated:
1024
+ // the broken seam the operator caught on the proof film). The
1025
+ // continuation is latent-level (wraps the sampler's model and
1026
+ // conditioning — family-agnostic); the trim is decode-level.
1027
+ // Every film window k>=2 chains, t4r included. THE WALL: a
1028
+ // stamped window with no Continuation node is a broken seam —
1029
+ // card-gap pins it ("the stamped seam wall").
1030
+ if (isChain || isT4r) {
1031
+ const prev = p.__prev;
1032
+ /* v8 ignore next 1 -- the film loop stamps __iteration on every window k≥2 before the render (the seam block mounts only when it did) */
1033
+ const iteration = p.__iteration ?? 0;
1034
+ /* v8 ignore next 1 -- the film loop stamps __overlap on every window k≥2 before the render (the seam block mounts only when it did) */
1035
+ const overlap = p.__overlap ?? 0;
1036
+ if (prev !== undefined && overlap > 0) {
1037
+ const cont = g.node('MiniMaxH3FiniteLatentContinuation', {
1038
+ positive: cond, target_latent: targetLatent,
1039
+ iteration, overlap_frames: overlap,
1040
+ continue_audio_latent: true,
1041
+ model: sigmaModel, sigmas: sched,
1042
+ previous_latent: prev.latOut,
1043
+ });
1044
+ cond = cont.out(0);
1045
+ targetLatent = cont.out(1);
1046
+ guider = g.node('BasicGuider', { model: cont.out(3), conditioning: cont.out(0) }).out();
1047
+ }
1048
+ }
1049
+ const sampled = g.node('SamplerCustomAdvanced', {
1050
+ noise, guider, sampler, sigmas: sched, latent_image: targetLatent,
1051
+ });
1052
+ let latOut = sampled.out(0);
1053
+ // ── THE T3 REFINE RIDER (roadmap item 2 — the crowd's third
1054
+ // tier, formalized): a short CLOSING pass over the window's
1055
+ // output latent — the refiner lora on its OWN loader (the
1056
+ // primary stack above NEVER changes), full-denoise short
1057
+ // schedule from the same noise seed, riding the doc's own
1058
+ // sampler/scheduler (the rider owns NO solver of its own — one
1059
+ // owner per knob). Mounted ONLY when the service resolved a
1060
+ // refine row; absent = the graph renders exactly as before.
1061
+ // The TaoMate refiner thread's mechanics: pass A full, pass B
1062
+ // closes. The rider sits UPSTREAM of decode AND of the film's
1063
+ // seam handles — the chained texture is the refined one.
1064
+
1065
+ // the only door to the whole post chain — sharpen, interp, VSR,
1066
+ // refine each AND it with their own switch (legacy docs with
1067
+ // leaves set but no master render the plain pass, byte-stable).
1068
+ const secondPassOn = p.second_pass_enabled === true;
1069
+ const refine = secondPassOn ? p.refine : undefined;
1070
+ if (refine !== undefined) {
1071
+ const refineModel = g.node('LTX_lora_loader', {
1072
+ model: sigmaModel, mode: 'minimax',
1073
+ stack_data: JSON.stringify([{ on: true, lora: refine.name, str: refine.strength, v: 1, a: 1, t: 1 }]),
1074
+ lora_ui: '',
1075
+ }).out();
1076
+ const refineSched = g.node('BasicScheduler', {
1077
+ model: refineModel, scheduler: schedName,
1078
+ steps: refine.steps, denoise: 1.0,
1079
+ }).out();
1080
+ const refineGuider = g.node('BasicGuider', { model: refineModel, conditioning: cond }).out();
1081
+ const refined = g.node('SamplerCustomAdvanced', {
1082
+ noise, guider: refineGuider, sampler: samplerSel, sigmas: refineSched, latent_image: latOut,
1083
+ });
1084
+ latOut = refined.out(0);
1085
+ }
1086
+ // ── decode + save ──────────────────────────────────────────────────
1087
+ let vdec = g.node('VAEDecode', { samples: latOut, vae: vaeVideo }).out();
1088
+ let vadec = g.node('VAEDecodeAudio', { samples: latOut, vae: vaeAudio }).out();
1089
+ // the RAW audio head is the soft seam's currency — the film's join
1090
+ // takes the incoming window's UNTRIMMED opening (it owns the seam);
1091
+ // captured BEFORE the clip finalize trims the overlap off
1092
+ let vadecRaw;
1093
+ // `delivered` fills at the save branches (both families save)
1094
+ let delivered = null;
1095
+ const rawHandles = { latOut, vdec, vadec, filmImages: latOut, filmAudio: latOut };
1096
+ if (isChain || isT4r) {
1097
+ const prev = p.__prev;
1098
+ /* v8 ignore next 1 -- the film loop stamps __overlap on every window k≥2 before the render (the block mounts only when it did) */
1099
+ const overlap = p.__overlap ?? 0;
1100
+ if (prev !== undefined && overlap > 0) {
1101
+ vadecRaw = vadec;
1102
+ // the window's OWN clip: the carried overlap leaves picture AND
1103
+ // sound by the same duration (their finalize, hard audio trim —
1104
+ // a clip never replays the seam it grew from)
1105
+ const fin = g.node('MiniMaxH3FiniteSegmentFinalize', {
1106
+ sampled_latent: latOut, images: vdec, audio: vadec,
1107
+ iteration: 1, overlap_frames: overlap, trim_audio_head: true,
1108
+ });
1109
+ vdec = fin.out(1);
1110
+ vadec = fin.out(2);
1111
+ }
1112
+ }
1113
+ if (isT4r) {
1114
+ const created = g.node('CreateVideo', {
1115
+ images: vdec, audio: vadec, fps: fpsInput, bit_depth: FILM_BIT_DEPTH,
1116
+ // color_space: pin autofill "sRGB"
1117
+ });
1118
+
1119
+ // every window saves under h3_t4_w<k> — the t4r arm's legacy
1120
+ // 'video/ComfyUI' prefix died (multi-window anchored films were
1121
+ // unaddressable: every window collided on one prefix, and the
1122
+ // file tail's loader could not name them).
1123
+ const saved = g.node('SaveVideo', {
1124
+ video: created.out(), filename_prefix: `h3_t4_w${k}`,
1125
+ format: 'auto', codec: 'h264',
1126
+ 'codec.encoding': 're-encode', 'codec.encoding.crf': 10.0,
1127
+ });
1128
+ rawHandles.savePassthrough = saved.out(0);
1129
+ delivered = { images: vdec, audio: vadec };
1130
+ }
1131
+ else {
1132
+ // sharpen leaves: only the EXPLICITLY-set ones patch the grouped
1133
+ // dict (absent leaves keep ImageSharpenKJ's own defaults). The old
1134
+ // card knob (sharpen_strength) rides the leaf loop like
1135
+ // the renderer alias does.
1136
+ const method = { ...SHARPEN_DEFAULTS };
1137
+ const sharpenLeaves = [
1138
+ ['sharpen_method', 'method'], ['sharpen_strength', 'strength'],
1139
+ ['sharpen_radius', 'radius'], ['sharpen_threshold', 'threshold'],
1140
+ ['sharpen_iterations', 'iterations'],
1141
+ ];
1142
+ for (const [src, dst] of sharpenLeaves) {
1143
+ const val = p[src];
1144
+ if (val !== null && val !== undefined)
1145
+ method[dst] = val;
1146
+ }
1147
+
1148
+ // upstream moved sharpen LAST: interp → VSR → sharpen → CreateVideo
1149
+ // (V7/ours sharpened FIRST — before the upscaler could soften the
1150
+ // detail away). Sharpen rcas 0.3 after upscale "looks natural"
1151
+ // (his V9 notes). The switches stay ours; the ORDER is his.
1152
+ const film = g.node('FrameInterpolationModelLoader', {
1153
+ model_name: p.interp_model,
1154
+ }).out();
1155
+ const interpMultVal = p.interp_multiplier;
1156
+ const interp = g.node('FrameInterpolate', {
1157
+ interp_model: film, images: vdec, multiplier: interpMultVal,
1158
+ }).out();
1159
+
1160
+ // (declared default false). The legacy interp_switch alias is
1161
+ // retired — post-declaration the walk materializes the primary,
1162
+ // so the alias arm was unreachable dead law.
1163
+ const interpSwOn = secondPassOn && p.interpolate_enabled;
1164
+ const interpSw = g.node('ComfySwitchNode', {
1165
+ switch: interpSwOn, on_true: interp, on_false: vdec,
1166
+ }).out();
1167
+ const srRes = p.sr_resolution;
1168
+ const sr = g.node('SeedVR2VideoUpscaler', {
1169
+ image: interpSw,
1170
+ dit: g.node('SeedVR2LoadDiTModel', {
1171
+ model: p.sr_model, device: 'cuda:0',
1172
+ }).out(),
1173
+ vae: g.node('SeedVR2LoadVAEModel', {
1174
+ model: LANE_FILES.sr_vae, device: 'cuda:0',
1175
+ }).out(),
1176
+ seed: 42, resolution: srRes,
1177
+ max_resolution: 0, batch_size: 5, uniform_batch_size: false,
1178
+ color_correction: 'lab',
1179
+ }).out();
1180
+ const srSwOn = secondPassOn && p.sr_switch;
1181
+ const srSw = g.node('ComfySwitchNode', {
1182
+ switch: srSwOn, on_true: sr, on_false: interpSw,
1183
+ }).out();
1184
+ // sharpen LAST (V9): the upscaler softens; rcas after it restores.
1185
+ // Renderer alias second (sharpen_* leaves above build the method).
1186
+ const sharpened = g.node('ImageSharpenKJ', { image: srSw, method }).out();
1187
+ const sharpSw = g.node('ComfySwitchNode', {
1188
+ switch: secondPassOn && p.sharpen_enabled, on_true: sharpened, on_false: srSw,
1189
+ }).out();
1190
+
1191
+ // CreateVideo.fps = base × interp multiplier (his Enhancements:
1192
+ // PrimitiveFloat 24 → ComfyMathExpression "a * 2" → fps). Without
1193
+ // it every interp-on window plays at HALF speed — the frames
1194
+ // double, the fps doesn't. Byte-stable at defaults (interp off →
1195
+ // the served literal 24).
1196
+ const interpOn = secondPassOn && p.interpolate_enabled;
1197
+ const interpMult = p.interp_multiplier;
1198
+ const created = g.node('CreateVideo', {
1199
+ images: sharpSw, audio: vadec, fps: interpOn ? 24 * interpMult : 24, bit_depth: FILM_BIT_DEPTH,
1200
+ // color_space: pin autofill "sRGB"
1201
+ });
1202
+ const saved = g.node('SaveVideo', {
1203
+ video: created.out(), filename_prefix: `h3_t4_w${k}`,
1204
+ format: 'mp4', codec: 'h264',
1205
+ });
1206
+ rawHandles.savePassthrough = saved.out(0);
1207
+ delivered = { images: sharpSw, audio: vadec };
1208
+ }
1209
+ // (every family path delivers — both arms save the window's clip;
1210
+ // no null arm: the family dispatch is exhaustive over FAMILIES.
1211
+ // The old MotionContextSaveLatent persistence died with the seam —
1212
+ // cross-run continuity is the FL2VA anchor: set the first-frame
1213
+ // square to the previous film's last frame, latent-true.)
1214
+ rawHandles.filmImages = delivered.images;
1215
+ // THE FILM'S AUDIO SEAM CURRENCY: a carried window hands the film
1216
+ // its UNTRIMMED opening (the soft-released head owns the join);
1217
+ // every other window hands its delivered audio
1218
+ rawHandles.filmAudio = vadecRaw !== undefined
1219
+ ? vadecRaw
1220
+ : delivered.audio;
1221
+ return rawHandles;
1222
+ }
1223
+ /** The film action — the h3 family's whole compose segment. The
1224
+ * doc arrives gated + lifted from the card; the build owns the
1225
+ * lane admissions and both renderers (this module is their only
1226
+ * seat). */
1227
+ /** The sampler row the h3 schema itself serves: the ONE engine
1228
+ * vocabulary read through the family's recommended subset (the
1229
+ * schema's own filter law — a retyped list would be a second
1230
+ * SSOT). */
1231
+ const H3_SAMPLER_OPTIONS = SAMPLER_OPTIONS.filter((n) => H3_RECOMMENDED_SAMPLERS.includes(n));
1232
+ export const film = {
1233
+ id: 'film',
1234
+ inputs: [],
1235
+ outputs: [{ name: 'video', kind: 'VIDEO' }],
1236
+ // GATE S (the seed sentinel — the estate's one-mint law): the
1237
+ // schema's default is 42 and explicit seeds ride verbatim; an
1238
+ // explicit -1 (the ComfyUI randomize idiom) mints CLIENT-SIDE
1239
+ // through the one helper instead of leaving the choice to the
1240
+
1241
+ // family port (the card's legacy else still passes -1 through;
1242
+ // the action oracle pins that one deliberate divergence).
1243
+ // THE DECLARED SURFACE (the write plane, phase 2): the h3 card
1244
+ // schema's own types and bounds — the family door judges defaults
1245
+ // and variant presets against this row. The sampler row resolves
1246
+ // from the ONE engine vocabulary read through the family's
1247
+ // recommended subset (the schema's own filter); the scheduler row
1248
+ // reads the whole vocabulary. The timeline's own JSON row params
1249
+ // (calls, audio_clips) ride the timeline contract's validators,
1250
+ // not this surface; the per-window rows (k, noise_seed,
1251
+ // fps_seconds) are internal. ref_image_size is the schema's
1252
+ // const-or-WxH pattern tier — typed as its string spine.
1253
+ params: [
1254
+ { name: "prompt", type: "string" },
1255
+ { name: "image", type: "string" },
1256
+ { name: "last_frame", type: "string" },
1257
+ { name: "ref_images", type: "image_list" },
1258
+ { name: "ref_videos", type: "image_list" },
1259
+ { name: "ref_audios", type: "image_list" },
1260
+ { name: "duck_depth_db", type: "number", bounds: [-48, 0] },
1261
+ { name: "seed", type: "number", rule: "seed-sentinel" },
1262
+ { name: "width", type: "number", bounds: [448, 1344] },
1263
+ { name: "height", type: "number", bounds: [448, 768] },
1264
+ { name: "length", type: "number", bounds: [22, 362] },
1265
+ { name: "steps", type: "number", bounds: [4, 30] },
1266
+ { name: "second_pass_enabled", type: "boolean" },
1267
+ { name: "sharpen_enabled", type: "boolean" },
1268
+ { name: "sharpen_strength", type: "number", bounds: [0, 1] },
1269
+ { name: "sharpen_method", type: "enum", options: ["rcas", "adaptive_usm", "high_pass", "deconvolution"] },
1270
+ { name: "sharpen_radius", type: "number", bounds: [0.5, 5] },
1271
+ { name: "sharpen_threshold", type: "number", bounds: [0, 1] },
1272
+ { name: "sharpen_iterations", type: "number", bounds: [1, 100] },
1273
+ { name: "interpolate_enabled", type: "boolean" },
1274
+ { name: "interp_model", type: "enum", options: ["film_net_fp16.safetensors", "rife47.pth"] },
1275
+ { name: "interp_multiplier", type: "number", bounds: [2, 4] },
1276
+ { name: "denoise", type: "number", bounds: [0, 1] },
1277
+ { name: "sampler_name", type: "enum", options: H3_SAMPLER_OPTIONS },
1278
+ { name: "sched_name", type: "enum", options: SCHEDULER_OPTIONS },
1279
+ { name: "refine_lora", type: "string" },
1280
+ { name: "refine_strength", type: "number", bounds: [0, 2] },
1281
+ { name: "refine_steps", type: "number", bounds: [1, 10] },
1282
+ { name: "attention_backend", type: "enum", options: ["comfy kitchen attention", "pytorch attention"] },
1283
+ { name: "sr_switch", type: "boolean" },
1284
+ { name: "sr_resolution", type: "number", bounds: [720, 2160] },
1285
+ { name: "sr_model", type: "enum", options: ["seedvr2_ema_3b_fp16.safetensors", "seedvr2_ema_3b_fp8_e4m3fn.safetensors"] },
1286
+ { name: "ref_image_size", type: "string" },
1287
+ { name: "shift_video", type: "number", bounds: [1, 20] },
1288
+ { name: "shift_audio", type: "number", bounds: [1, 10] },
1289
+ { name: "sla_enabled", type: "boolean" },
1290
+ { name: "sla_sparsity", type: "number", bounds: [0, 0.95] },
1291
+ { name: "sla_block_size", type: "enum", options: ["32", "64", "128"] },
1292
+ { name: "sla_min_seq_len", type: "number", bounds: [512, Number.MAX_SAFE_INTEGER] },
1293
+ { name: "sla_dense_last_steps", type: "number", bounds: [0, 10] },
1294
+ { name: "sla_dense_steps", type: "string" },
1295
+ { name: "sla_dense_backend", type: "enum", options: ["comfy_kitchen", "pytorch", "auto"] },
1296
+ { name: "sla_reference_protection", type: "enum", options: ["Off", "Light", "Heavy Enforcement"] },
1297
+ { name: "sla_protect_audio", type: "boolean" },
1298
+ { name: "sla_stabilize_motion", type: "boolean" },
1299
+ { name: "sla_disable_fp16_accum", type: "boolean" },
1300
+ { name: "interp_switch", type: "boolean" },
1301
+ { name: "sharpen_switch", type: "boolean" },
1302
+ { name: "sla_switch", type: "boolean" },
1303
+ { name: "image_name", type: "string" },
1304
+ ],
1305
+ facts: parseH3Facts,
1306
+ build({ p: docIn, facts, g }) {
1307
+ const p = { ...docIn };
1308
+ const guideImage = (p.image ?? p.image_name ?? '');
1309
+ if (p.variant === 't4r' && !guideImage) {
1310
+ // (refs-implied t4r windows carry no anchor — the bundle IS
1311
+ // the r2v input; the guard admits them via the refs law — the
1312
+ // legacy stanza bag AND the declared input surface (the rail's
1313
+ // fields) count; the bed rides the audio lane guideless too)
1314
+ const rbRef = (p.refs ?? {});
1315
+ const refsCarry = wireList(rbRef.images).length + wireList(rbRef.videos).length + wireList(rbRef.audios).length
1316
+ + wireList(p.ref_images).length + wireList(p.ref_videos).length + wireList(p.ref_audios).length > 0
1317
+ || (typeof p.last_frame === 'string' && p.last_frame.trim() !== '');
1318
+ if (!refsCarry) {
1319
+ throw new Error('h3_window(t4r): image-anchored window without a staged guide image — ' +
1320
+ 'compose always injects LoadImage.0.image on this family');
1321
+ }
1322
+ }
1323
+ // THE FILM DISPATCH: a multi-call chain doc with no per-window
1324
+ // stanza markers (k absent — the stanza vocabulary) composes
1325
+ // the MERGED film; everything else is the frozen single-window
1326
+ // shape (served byte-identical).
1327
+ const docCalls = Array.isArray(p.calls) ? p.calls : null;
1328
+ const isFilm = docCalls !== null && docCalls.length > 1
1329
+ && p.k === undefined && (p.variant === undefined || p.variant === 't4_chain');
1330
+ if (isFilm)
1331
+ return renderH3Film(p, g, facts);
1332
+
1333
+ // FILM-path consumer (it rides the accumulated film audio).
1334
+ // On the frozen single-window shape it would be a silent
1335
+ // skip — the crime class this estate refuses. Loud, with the
1336
+ // fix in the message (the studio's own doc always carries
1337
+ // calls; a second short call unlocks the film path).
1338
+ const clips = (p.audio_clips ?? []);
1339
+ if (clips.some((c) => c !== null && typeof c === 'object'
1340
+ && typeof c.src === 'string' && c.src.trim() !== '')) {
1341
+ throw new Error('h3-timeline: audio clips ride the FILM path — this single-window doc has clips but no film to mix over ' +
1342
+ '(add a second call to author a film, or clear the Music row)');
1343
+ }
1344
+
1345
+ // honors the distill bag's steps — ONE STEPS LAW for both
1346
+ // window paths (007 L3, the film path's verbatim): the marriage
1347
+ // fires only when the caller pinned no steps of their own. The
1348
+ // doc face reads the schema's __steps_pinned stamp (a walked
1349
+ // default is not a pin); the call face reads the single call's
1350
+ // knobs (the film path's own `knobs.steps === undefined` arm).
1351
+ // An explicit count is the user's word — the distill default
1352
+ // never overwrites it.
1353
+ if (Array.isArray(p.loras)) {
1354
+ const rows = p.loras;
1355
+ const applied = rows.map((r) => r.steps).filter((v) => typeof v === 'number' && Number.isFinite(v));
1356
+ const singleKnobs = docCalls !== null && docCalls.length === 1
1357
+ ? (docCalls[0].knobs ?? {})
1358
+ : {};
1359
+ if (applied.length > 0 && p.__steps_pinned !== true && singleKnobs.steps === undefined) {
1360
+ p.steps = Math.max(...applied);
1361
+ }
1362
+ }
1363
+ return renderH3Window(p, g, facts).savePassthrough;
1364
+ },
1365
+ };
1366
+ //# sourceMappingURL=actions.js.map