@aicopycoders/exodus 2026.11.500-beta.1 → 2026.11.1000-beta.1

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.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: exodus-video
3
- description: Make a video ad with Exodus from the terminal. The main path is script-first: run a saved video workflow with `npx @aicopycoders/exodus workflow run`. You read and approve the storyboard, pull every finished piece (per-scene clips, the narration track and per-scene voice, keyframes, cast identity stills, word timings, the music bed) into a folder with `exodus video pull`, and upload a finished cut for approval. Exodus makes the pieces; the cut is made outside it, in whatever editor the user wants — this skill hands over the pieces and the facts about them, it does not prescribe an editor. Use it whenever the user has invoked Exodus and wants anything to do with a video ad, an ad run's clips or storyboard, "pull the pieces", "stitch it together", "make the cut", "upload my cut", or checking on a video run ("exodus, make a video ad from this script", "exodus, is my video run done", "exodus, pull the clips for run X and cut them", "exodus, what's wrong with scene 3", "exodus video status"). Also use it when the user ran an `npx @aicopycoders/exodus video` command or the `exodus` hub skill routed here. Admins get every video command; beta testers with video switched on get start, status, storyboard, approve, voices, retry-frame, pull and upload on their own brands (see "Beta testers"). "video isn't enabled for this key" means the run id is wrong, the command is admin-only, or video isn't switched on for that dashboard user, so check the id and then say so; do not retry. Never claim generic video-editing asks ("edit this mp4", "add captions to my reel") without Exodus context; in shared folders those belong to the user's other tools. Running or authoring workflows generally is `exodus-workflow`; static image ads are `exodus-image`; copy is `exodus-write`.
3
+ description: Make a video ad with Exodus from the terminal. One sentence ("swipe this ad as a microdrama for my brand", "make this a UGC video") is walked through the template door stop by stop, with a yes asked before each paid step. The main path is script-first: run a saved video workflow with `npx @aicopycoders/exodus workflow run`. You read and approve the storyboard, pull every finished piece (per-scene clips, the narration track and per-scene voice, keyframes, cast identity stills, word timings, the music bed) into a folder with `exodus video pull`, and upload a finished cut for approval. Exodus makes the pieces; the cut is made outside it, in whatever editor the user wants — this skill hands over the pieces and the facts about them, it does not prescribe an editor. Use it whenever the user has invoked Exodus and wants anything to do with a video ad, an ad run's clips or storyboard, "pull the pieces", "stitch it together", "make the cut", "upload my cut", or checking on a video run ("exodus, make a video ad from this script", "exodus, is my video run done", "exodus, pull the clips for run X and cut them", "exodus, what's wrong with scene 3", "exodus video status"). Also use it when the user ran an `npx @aicopycoders/exodus video` command or the `exodus` hub skill routed here. Admins get every video command; beta testers with video switched on get start, status, storyboard, approve, voices, retry-frame, pull and upload on their own brands (see "Beta testers"). "video isn't enabled for this key" means the run id is wrong, the command is admin-only, or video isn't switched on for that dashboard user, so check the id and then say so; do not retry. Never claim generic video-editing asks ("edit this mp4", "add captions to my reel") without Exodus context; in shared folders those belong to the user's other tools. Running or authoring workflows generally is `exodus-workflow`; static image ads are `exodus-image`; copy is `exodus-write`.
4
4
  ---
5
5
 
6
6
  # Video: make the pieces, cut the ad, hand it back
@@ -69,11 +69,229 @@ not on the menu by name; Custom is the way to them. A narrator-only script fits
69
69
  Custom alone. If the refusal lists different keys from this table, the server
70
70
  is right and this table is stale.
71
71
 
72
+ The template door is a second menu, `exodus video start --input-options`. The
73
+ Golden Six formats start there. "From one sentence to a film" walks it.
74
+
72
75
  The Rig box on that workflow is where the run's Conceit and Style come from.
73
76
  Conceit is the family plus Wrapper, Narrator Person, and Delivery. Style is the
74
77
  look. Narrated Story is the voice-over family and Acted Story is the dialogue
75
78
  family (`familyTree.ts`). Those family names stay the code's names.
76
79
 
80
+ ## From one sentence to a film
81
+
82
+ The member types one sentence, such as "swipe this ad as a microdrama for my
83
+ brand". You drive the run through its stops and wait for the member at each
84
+ one. The Golden Six formats start on the template door, which needs
85
+ Templates switched on for the member's account. Without it the CLI answers
86
+ "video isn't enabled for this key" or "Templates aren't available on your
87
+ account. Ask an admin if you need it." Tell the member that and stop. A beta
88
+ tester's key refuses the template flags and `retry-clip` with a sentence
89
+ naming what it refused ("Beta testers"): tell the member and stop. Do not retry.
90
+
91
+ Two rules hold at every stop:
92
+
93
+ - **The run page link.** The start prints `Watch it: <link>`. Keep it and give
94
+ it to the member at every stop: the faces, rooms, pictures, voice samples
95
+ and clips open there. `status` leaves it out at the storyboard stop.
96
+ - **A yes before every paid step.** Tell the member what the step buys
97
+ and its price, then wait for their yes. The price is the one the CLI
98
+ printed: `maximumUsd` and `estimatedUsd` under `preparationQuote` from
99
+ `--quote-preparation`, or the total from `video quote`. Where the CLI prints
100
+ no price, say that it prints none. A quote covers only its phase, never the
101
+ whole video: say so. A saved quote that has expired or no
102
+ longer matches is refused with nothing spent: quote again and ask again.
103
+ Reads cost nothing and need no yes.
104
+
105
+ **The Golden Six.** `exodus video start --input-options` lists the templates
106
+ this account may start, the Golden Six first, one line each:
107
+ `<key> — <label> — <description> — <n> structures`. Use the key it prints.
108
+ `--style` takes the template's own look, from this table.
109
+
110
+ | The member asks for | `--conceit` | `--style` |
111
+ |---|---|---|
112
+ | UGC, a creator talking to camera | `ugc-template` | `raw-iphone-ugc-template` |
113
+ | an authority yapper, an expert explaining | `authority-yapper-template` | `realistic-template` |
114
+ | a microdrama, a short acted scene | `microdrama-template` | `realistic-template` |
115
+ | a skeleton timeline | `skeleton-timeline-template` | `pixar-3d-template` |
116
+ | a song ad, a Suno song, a jingle | `pixar-song-template` | `pixar-3d-template` |
117
+ | personification, the product or a body part talking | `personification-template` | none of its own: ask the member to pick one of the looks the server offers |
118
+
119
+ A `--style` the server does not offer is refused with the list of looks it
120
+ does offer, and nothing is spent.
121
+
122
+ ### Start
123
+
124
+ 1. Find three things in the sentence, and ask one question for whatever is
125
+ missing:
126
+ - the source ad: pasted text or a file, as it is, or the words of an ad in
127
+ Exodus or behind a link (the `swipe` skill's section 1 gets them). Save
128
+ the words to `source.txt`.
129
+ - the format: the table above.
130
+ - the brand: `exodus brand current`.
131
+ 2. `exodus video start --input-options --conceit <key>` prints the template's
132
+ story structures, its reference ads, the saved references and the account
133
+ voices. It writes, quotes and starts nothing. Name the structures to the
134
+ member, one line each. A structure they pick goes on the stop 1 lines as
135
+ `--structure <key>`.
136
+ 3. A template run always stops at the storyboard. The CLI refuses `--one-shot`
137
+ on a template start before anything is sent ("Template preparation requires
138
+ storyboard review; do not combine it with --one-shot. Nothing has
139
+ started."), and the server never approves a template's storyboard by
140
+ itself. A member who asks for no stops still gets each paid step named, with
141
+ its price or the fact that the CLI prints none, and a yes asked before it
142
+ runs.
143
+
144
+ ### Stop 1: the script and the cast
145
+
146
+ 1. Quote the script:
147
+
148
+ ```
149
+ exodus video start --script source.txt --conceit <key> --style <look> \
150
+ --adapt "<what may change, in the member's words>" --stop-at-script \
151
+ --quote-preparation --json > script-quote.json
152
+ ```
153
+
154
+ Add `--product <brandProductId>` only when the member gives a saved
155
+ product's id; the CLI lists no products. Give the member the price.
156
+ 2. On their yes, run the same line with `--authorize-preparation
157
+ script-quote.json` in place of `--quote-preparation`, into `stop1.json`. It
158
+ writes the script and starts no run.
159
+ 3. Write the script out byte for byte:
160
+ `node -e 'process.stdout.write(require("./stop1.json").script)' > script.txt`.
161
+ Show the member the source and `script.txt` side by side, and the cast:
162
+ each name that speaks a line. Ask: go on, change a line, or stop.
163
+ - Go on: "The run starts" below.
164
+ - Change a line: copy `script.txt` to `edited.txt` and make their change.
165
+ An edited script is checked and approved again, at a price of its own.
166
+ The first line quotes; the second waits for their yes:
167
+
168
+ ```
169
+ exodus video start --resume-script stop1.json --script edited.txt \
170
+ --conceit <key> --style <look> --stop-at-script --quote-preparation --json > edit-quote.json
171
+ exodus video start --resume-script stop1.json --script edited.txt \
172
+ --conceit <key> --style <look> --stop-at-script --authorize-preparation edit-quote.json --json > stop1b.json
173
+ ```
174
+
175
+ From here `stop1b.json` is the stop file. Write its script over
176
+ `script.txt` the same way and show it again.
177
+ - Stop: nothing more is spent.
178
+
179
+ ### The run starts
180
+
181
+ `<stop file>` is the latest one: `stop1.json`, or `stop1b.json` after an edit.
182
+ Use it with `script.txt` written out from it, unchanged. A different script,
183
+ product, voice or reference is refused, and nothing starts.
184
+
185
+ ```
186
+ exodus video start --resume-script <stop file> --script script.txt \
187
+ --conceit <key> --style <look> --quote-preparation --json > board-quote.json
188
+ ```
189
+
190
+ That quotes the storyboard. On the member's yes:
191
+
192
+ ```
193
+ exodus video start --resume-script <stop file> --script script.txt \
194
+ --conceit <key> --style <look> --authorize-preparation board-quote.json --wait
195
+ ```
196
+
197
+ It prints the run id and `Watch it: <link>`, then waits until the run needs
198
+ the member.
199
+
200
+ ### Stop 2: the picks (arrives with the next server update)
201
+
202
+ Today a run goes from the script straight to the storyboard. Run this stop
203
+ only when `status` says the run is waiting for picks.
204
+
205
+ 1. `exodus video picks <runId>` lists, for each person, four faces and the
206
+ voices; for each place, four rooms; on a microdrama, the camera styles and
207
+ a map in metres. Each face, room and voice sample has its own link. Show it
208
+ all with the run page link.
209
+ 2. Ask for one face and one voice per person, one room per place, and on a
210
+ microdrama a style. Send the answers as:
211
+
212
+ ```
213
+ exodus video pick <runId> --face <who>=<n> --voice <who>=<n|voice name|voice id> \
214
+ --room <place>=<n> [--style <key>] [--move <who>=<x>,<y>] [--note "<text>"]
215
+ ```
216
+
217
+ `<who>` is the name the script uses. `--face`, `--voice` and `--room`
218
+ repeat once per person or place. `--style` (the camera style) and `--move`
219
+ are for the microdrama; `--move` takes metres on the printed map. The run goes on only
220
+ when every slot has a pick. A pick that leaves a slot open prints the open
221
+ slots: ask for those.
222
+ 3. "Show me other faces": `exodus video picks <runId> --redo face:<who> --note
223
+ "<what to change>"`, or `room:<place>` for rooms. It draws four new
224
+ pictures. The CLI prints no price for them: say so and wait for their yes.
225
+ The second redo of a slot needs the note.
226
+
227
+ When `picks` answers that the server does not support it yet, the run has no
228
+ picks stop: go to stop 3. When it answers `Unknown subcommand: "picks"`, this
229
+ CLI is older than the server: run `npx @aicopycoders/exodus@latest update`,
230
+ then `picks` again.
231
+
232
+ ### Stop 3: the storyboard
233
+
234
+ `status` says "Parked: the storyboard is waiting for your yes."
235
+ `exodus video storyboard <runId>` prints each scene's line and picture, and who
236
+ speaks with which voice ("Reading the storyboard gate" has the detail). Show it
237
+ with the run page link, then ask: approve, redo a picture, change a voice, or
238
+ stop.
239
+
240
+ - Approve: `exodus video approve <runId>`. It buys the voices and the clips
241
+ (with the pilot stop, the pilot first), the expensive part. The CLI prints
242
+ no price for them at this stop: say so, and approve on their yes. A storyboard the app's check stopped is
243
+ refused with the reason. Tell the member, and on their yes approve again
244
+ with `--accept-findings`.
245
+ - Redo a picture: `exodus video retry-frame <runId> --node <nodeId> --scene <n>
246
+ --note "<what is wrong>"`, with the node id from the `Redo one frame:` line
247
+ `status` printed. It redraws one picture. The CLI prints no price for it:
248
+ say so and wait for their yes.
249
+ - Change a voice: `exodus video voices <runId> --set <who>=<voice>` ("Giving
250
+ the characters voices").
251
+ - Stop: `exodus workflow cancel <runId>`.
252
+
253
+ **The song format** waits twice more. `exodus video song <runId>` prints the
254
+ Song master, its listen link and its sha256 once one is ready. The member
255
+ listens; on their yes,
256
+ `exodus video song approve <runId> --master <masterSha256>`. Before its clips
257
+ the run parks with "Parked: final provider requests are prepared".
258
+ `exodus video quote <runId>` prints each request's price and the total; on
259
+ their yes, `exodus video approve <runId> --request-quote <reviewSha256>`.
260
+
261
+ ### Stop 4: the pilot clip (arrives with the next server update)
262
+
263
+ Today approving the storyboard makes every clip, and the next stop is the end.
264
+ With the pilot stop, the run makes one clip after the storyboard, checks it and
265
+ parks. `status` then says it "made its pilot clip (scene <n>)" and whether the
266
+ words heard match. On UGC and the authority yapper the pilot is two clips, one
267
+ talking and one listening in silence. Show the pilot on the run page and the
268
+ words line, then ask: keep it, or redo it.
269
+
270
+ - Keep it: `exodus video approve <runId>` makes the other clips, the expensive
271
+ part. The CLI prints no price for it: say so, and approve on their yes.
272
+ - Redo it: `exodus video retry-clip <runId> --scene <n> --note "<what is
273
+ wrong>"`. One new clip. The CLI prints no price for it: say so and wait for
274
+ their yes. The note steers the motion,
275
+ never the words.
276
+
277
+ ### End: watch and approve
278
+
279
+ At the final watch, follow the block `status` prints ("Where a run can
280
+ stop"). When the cut is already uploaded, give the member the run page to
281
+ watch it. When the run waits for a cut: `exodus video pull <runId> --out ./ad-<runId>`, make the
282
+ cut ("Cutting the ad"), `exodus video upload <runId> --file <cut.mp4>`, and
283
+ give the member the run page. Ask: approve, redo a clip, or stop here.
284
+
285
+ - Approve: `exodus video approve <runId>` makes the cut the ad. It is one-way.
286
+ - Redo a clip: `retry-clip` as at stop 4, after their yes. Then pull, cut
287
+ and upload again.
288
+
289
+ **On the song format**, tell the member this before they approve: "The song
290
+ made here is for review. Before this video runs as a paid ad, make the same
291
+ lyrics and style again in the Suno app while on a Pro or Premier plan, download
292
+ it there and use that file: Suno's terms allow commercial use only of songs made
293
+ on those plans and downloaded from Suno."
294
+
77
295
  ## Before anything
78
296
 
79
297
  - `npx @aicopycoders/exodus video --help` and `workflow --help` are the
@@ -191,13 +409,88 @@ exodus video director <runId> on|off|follow the trial director for
191
409
  what it is doing and its last three notes
192
410
  ```
193
411
 
412
+ **Starting from a template.** The Golden Six start here; "From one sentence to
413
+ a film" walks them. Each paid template phase, the script and then the
414
+ storyboard, is quoted first: run the line with `--quote-preparation --json`,
415
+ give the member `maximumUsd`, and run it again with `--authorize-preparation
416
+ <saved-quote.json>` in its place only on their yes. A template line with
417
+ neither is refused, and nothing is spent. The template flags, as `exodus video
418
+ --help` prints them:
419
+
420
+ ```operator-guide
421
+ exodus video start --script <file> --conceit <kind> --style <look> [--direction "<note>"] [--frame pov] [--pacing <jump-cuts|long-take|montage>] [--voice-path <path>] [--video-model <id>] [--voice <native|voice-first>] [--source-record <file.json>] [--adaptation-plan <file|original>] [--music] [--broll] [--one-shot] [--director] [--wait] [--json]
422
+ Template starts also accept: [--requested-seconds <seconds>] [--pictures-per-scene <1|3>] [--product <brandProductId>] [--elements <json|@file>] [--voices <json|@file>] [--resume-script <saved-stop-response.json>]
423
+ With --describe: [--product-context <text>] [--audience <text>] [--offer <text>] [--mechanism <text>]
424
+ exodus video start --input-options [--conceit <template>] [--voice <native|voice-first>] [--voice-path <path>] [--video-model <id>] [--json]
425
+
426
+ --describe Template: explicitly write from the brief in --script.
427
+ Review the returned script before preparing a storyboard.
428
+ Cannot be combined with --adapt or --resume-script
429
+ --adapt <intent> Template: adapt the exact pasted text in --script to the
430
+ selected structure. State what may change; no new claims,
431
+ identities or consent are inferred. Review original and
432
+ changed text before continuing. Not --adaptation-plan
433
+ --keep-original With --adapt, intentionally review the exact original
434
+ instead of generating changes. Guards and billable checks
435
+ still require a quote; no adaptation is claimed
436
+ --quote-preparation Request only the current script or storyboard phase quote.
437
+ No writer/audio/image/video work. Save --json and review
438
+ estimatedUsd (approximate), maximumUsd (phase bound), scope
439
+ and expiry; this is not a whole-video price
440
+ --authorize-preparation <saved-quote.json>
441
+ Explicitly accept that quote's maximumUsd for its exact
442
+ phase/input. Never upgrades input Automatic to paid consent.
443
+ Keep the same file for recovery; no silent new quote/retry
444
+ --stop-at-script Print the script the run would start on, and start no
445
+ storyboard/video run (start, with --conceit). Preparation
446
+ may still be paid. For templates, use
447
+ --json to save the approval, source and choices; edit only
448
+ a separate script file, then continue with --resume-script
449
+ --resume-script <saved-stop-response.json>
450
+ Continue a template's saved --stop-at-script --json
451
+ response with --script <edited.txt>, --conceit and
452
+ --style. Keep the server-issued approval, approved source,
453
+ brief, product, selected video model, signed references and voice map.
454
+ V2 also retains input intent/subject/structure/reference,
455
+ direction, sound/story choices and declared source/adaptation
456
+ records; material edits need a new quoted script review.
457
+ Explicit length, picture, --voice, --voice-path and
458
+ --video-model flags override their matching saved choices.
459
+ Changed or cleared --elements and --voices require
460
+ explicit --stop-at-script --json with
461
+ --resume-script to check the edited script and issue a new
462
+ approval; then resume that returned response to start.
463
+ Keep your original description and edited script files.
464
+ A different product still needs fresh writing and approval
465
+ without --resume-script.
466
+ Not for --show
467
+ --input-options List your templates: Golden Six first, then more templates.
468
+ Add --conceit <template> for structures, capabilities,
469
+ identity locks, references and account voices.
470
+ GET only: writes, quotes and starts nothing. Optional
471
+ --voice, --voice-path and --video-model require --conceit.
472
+ Reports unsupported, unavailable and empty separately;
473
+ use the returned IDs with --elements and --voices
474
+ ```
475
+
476
+ The other template flags (`--input-mode`, `--structure`, `--reference`,
477
+ `--subject`, `--template-brief`, `--song-controls`, `--mechanism-plan`,
478
+ `--requested-seconds`, `--pictures-per-scene`, `--product`, `--elements`,
479
+ `--voices`) are in `exodus video --help`.
480
+
194
481
  **From the storyboard on.**
195
482
 
196
483
  ```operator-guide
197
484
  exodus video storyboard <runId> read the scene cards
198
485
  exodus video voices <runId> who speaks and with whose voice
199
486
  exodus video voices <runId> --set <character>=<voiceId> give a character a voice
487
+ exodus video quote <runId> a quoting format: the exact prepared requests and prices
488
+ before any clip; approve them with --request-quote <reviewSha256>
200
489
  exodus video approve <runId> keep going
490
+ exodus video song <runId> a song-first run: the Song master to listen to
491
+ exodus video song approve <runId> --master <sha256> approve the master you listened to
492
+ exodus video song import <runId> --file <audio> --lyric <text|@file> --rights "…" [--from <s> --to <s>]
493
+ use the member's own recording as the Song
201
494
  exodus video retry-frame <runId> --node <nodeId> --scene <n> redo one still at the pixel gate
202
495
  (a beta tester leaves --node off)
203
496
  exodus video broll <runId> B-roll run: the shots, and the script lines by id
@@ -212,6 +505,8 @@ exodus video retry-clip <runId> --scene <n> [--node <nodeId>] [--note "…"] [--
212
505
  exodus video revoice <runId> --all | --scene <n> redo only the voice; no new video
213
506
  … make the cut (your choice of tool)
214
507
  exodus video upload <runId> --file ./ad-<runId>/cut.mp4 attach it
508
+ exodus video review <runId> --file ./ad-<runId>/cut.mp4 --accept | --reject
509
+ a final-review format: YOUR review of that exact final cut
215
510
  exodus video approve <runId> make it the ad
216
511
  ```
217
512
 
@@ -296,6 +591,10 @@ started.
296
591
  `status` prints "the app checks the storyboard and approves it itself if the
297
592
  checks pass" on a run headed that way. `--review-storyboard` is the default
298
593
  and changes nothing.
594
+ - A template run (the Golden Six, "From one sentence to a film") quotes the
595
+ script and the storyboard before it spends (`--quote-preparation`, then
596
+ `--authorize-preparation`), and always stops at the storyboard. `--one-shot`
597
+ is refused on a template start, and nothing is sent.
299
598
  - A Show run (`video start --show`) and a saved workflow run (`workflow run`)
300
599
  still pause at the storyboard for approval. Approving is what releases the
301
600
  voices and the clips. `status` prints "This run will pause for your approval
@@ -911,6 +1210,14 @@ dropped[] B-roll scene numbers the app left out
911
1210
  They have no clip on purpose: cut with
912
1211
  `--skip` and stay on the speaker
913
1212
  narration { file, timing }, or null on a per-scene run
1213
+ clipAudio keep | discard, on template-video pulls.
1214
+ Native talking keeps the clip's dialogue.
1215
+ Voice-first narration and song discard ALL
1216
+ embedded clip audio, including wordless
1217
+ pictures and reactions; use only the approved
1218
+ voice/song track. The bundled first-cut reads
1219
+ this policy for hand-run and automatic cuts.
1220
+ Absent on other models: existing cut rules apply.
914
1221
  cast[] one per identity still
915
1222
  characterId, name from the run's cast lock; null for an
916
1223
  unclaimed ledger still
@@ -0,0 +1,190 @@
1
+ import { createHash } from "node:crypto";
2
+ import { spawnSync } from "node:child_process";
3
+ import { readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import path from "node:path";
5
+
6
+ const literal = (lines) => {
7
+ if (!Array.isArray(lines) || lines.some((line) => typeof line !== "string" || /[{}\\\r\n]/.test(line))) {
8
+ throw new Error("Text contains ASS controls or invalid literal lines");
9
+ }
10
+ return lines.join("\\N");
11
+ };
12
+ /** ASS centiseconds select exactly the SAME delivered frames as the heard
13
+ * interval. Never round a boundary onto an extra frame or lose its last one.
14
+ * Heard seconds themselves stay unchanged in the plan and evidence. */
15
+ export function textFrameWindow(start, end) {
16
+ const startFrame = Math.ceil(start * 24 - 1e-6);
17
+ const endFrame = Math.ceil(end * 24 - 1e-6);
18
+ return { startFrame, frames: endFrame - startFrame, startCs: Math.floor(startFrame * 100 / 24), endCs: Math.floor(endFrame * 100 / 24) };
19
+ }
20
+ const assTime = (cs) => `${Math.floor(cs / 360000)}:${String(Math.floor(cs / 6000) % 60).padStart(2, "0")}:${String(Math.floor(cs / 100) % 60).padStart(2, "0")}.${String(cs % 100).padStart(2, "0")}`;
21
+ const anchor = (box, W, H) => [Math.round((box[0] + box[2]) * W / 2), Math.round((box[1] + box[3]) * H / 2)];
22
+
23
+ /** Same literal serializer, styles and geometry for measurement and final burn. */
24
+ export function measuredTextAss(directives, { W = 1080, H = 1920, style = "" } = {}) {
25
+ const thick = /thick black outline/i.test(style);
26
+ const events = [];
27
+ const event = (s, e, name, x, y, fs, lines) => {
28
+ if (!(Number.isFinite(s) && Number.isFinite(e) && e > s && fs > 0)) throw new Error("Invalid text interval or font size");
29
+ const window = textFrameWindow(s, e);
30
+ if (window.frames <= 0) throw new Error("Text interval contains no delivered video frame");
31
+ events.push(`Dialogue: 0,${assTime(window.startCs)},${assTime(window.endCs)},${name},,0,0,0,,{\\q2\\pos(${x},${y})\\fs${fs}}${literal(lines)}`);
32
+ };
33
+ for (const c of directives.captions ?? []) event(c.s, c.e, "Cap", Math.round(c.xShare * W), Math.round(c.yShare * H), c.fs, c.lines);
34
+ for (const c of [...(directives.cards ?? []), directives.hook, directives.endCard].filter(Boolean)) {
35
+ const [x, y] = anchor(c.renderBox, W, H);
36
+ event(c.in, c.out, c.kind === "end" ? "End" : "Card", x, y, c.fs, c.lines);
37
+ }
38
+ return [
39
+ "[Script Info]", "ScriptType: v4.00+", `PlayResX: ${W}`, `PlayResY: ${H}`, "WrapStyle: 2", "ScaledBorderAndShadow: yes", "",
40
+ "[V4+ Styles]",
41
+ "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",
42
+ `Style: Cap,Helvetica,60,&H00FFFFFF,&H00FFFFFF,&H00000000,&H90000000,-1,0,0,0,100,100,0,0,1,${thick ? 7 : 1.5},${thick ? 4 : 2},5,0,0,0,1`,
43
+ "Style: Card,Helvetica,60,&H00141414,&H00141414,&H00FFFFFF,&H50000000,-1,0,0,0,100,100,0,0,3,18,4,5,0,0,0,1",
44
+ "Style: End,Helvetica,60,&H00FFFFFF,&H00FFFFFF,&H20101010,&H00000000,-1,0,0,0,100,100,2,0,3,40,0,5,0,0,0,1", "",
45
+ "[Events]", "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text", ...events, "",
46
+ ].join("\n");
47
+ }
48
+
49
+ /** Resolve an observed renderer face, never a fontconfig-only guess. Some
50
+ * providers report -1 instead of a collection index; the exact observed file
51
+ * and a UNIQUE PostScript name across ALL its physical faces still prove it. */
52
+ export function fontSelectionEvidence(stderr, { file, index, faces }) {
53
+ if (!faces.length || faces.some((face) => !Number.isSafeInteger(face.index) || face.index < 0 || typeof face.postscriptName !== "string" || !/^[^\s,|]+$/.test(face.postscriptName))) return null;
54
+ const selected = faces.filter((face) => face.index === index);
55
+ if (selected.length !== 1 || faces.filter((face) => face.postscriptName === selected[0].postscriptName).length !== 1) return null;
56
+ const lines = stderr.split("\n").filter((line) => line.includes("fontselect:"));
57
+ if (!lines.length) return null;
58
+ const evidence = [];
59
+ for (const line of lines) {
60
+ const observed = / -> (.*), (-?\d+), ([^,\r\n]+)\s*$/.exec(line);
61
+ if (!observed || observed[1] !== file || observed[3].trim() !== selected[0].postscriptName) return null;
62
+ const reportedIndex = Number(observed[2]);
63
+ if (reportedIndex !== index && reportedIndex !== -1) return null;
64
+ evidence.push({ reportedIndex, physicalIndex: index, postscriptName: selected[0].postscriptName });
65
+ }
66
+ return evidence;
67
+ }
68
+
69
+ /** Real fontconfig + libass raster measurements. No guessed glyph widths or fallback bands. */
70
+ export function createTextRenderer({ dir, W = 1080, H = 1920 }) {
71
+ const run = (bin, args, extra = {}) => spawnSync(bin, args, { cwd: dir, maxBuffer: W * H * 3 + (1 << 20), ...extra });
72
+ const version = run("ffmpeg", ["-version"]).stdout?.toString().split("\n")[0] ?? "";
73
+ const filters = run("ffmpeg", ["-hide_banner", "-filters"]).stdout?.toString() ?? "";
74
+ const libass = /^\s*\S+\s+subtitles\s/m.test(filters);
75
+ const fontQuery = ["-f", "%{family}|%{file}|%{style}|%{index}", "Helvetica:weight=bold"];
76
+ const face = run("fc-match", fontQuery);
77
+ let font = null;
78
+ let fontFile = null;
79
+ let fontIndex = null;
80
+ let charset = [];
81
+ let faces = [];
82
+ if (face.status === 0) {
83
+ const resolved = face.stdout.toString().trim();
84
+ const file = resolved.split("|")[1];
85
+ const index = resolved.split("|")[3];
86
+ try {
87
+ const hash = createHash("sha256").update(readFileSync(file)).digest("hex");
88
+ if (!/^\d+$/.test(index ?? "")) throw new Error("The resolved font has no measured face index");
89
+ const chars = run("fc-query", ["-i", index, "-f", "%{charset}", file]);
90
+ const allFaces = run("fc-query", ["-f", "%{index}|%{postscriptname}\n", file]);
91
+ if (allFaces.status === 0) faces = allFaces.stdout.toString().trim().split("\n").map((row) => {
92
+ const [faceIndex, postscriptName = ""] = row.trim().split("|");
93
+ return { index: Number(faceIndex), postscriptName };
94
+ });
95
+ if (chars.status === 0) {
96
+ charset = chars.stdout.toString().trim().split(/\s+/).map((entry) => {
97
+ const [a, b] = entry.split("-").map((x) => Number.parseInt(x, 16));
98
+ return [a, b ?? a];
99
+ }).filter(([a, b]) => Number.isFinite(a) && Number.isFinite(b));
100
+ if (charset.length) font = { requested: "Helvetica", resolved: `${resolved}|sha256:${hash}` };
101
+ if (font) fontFile = file;
102
+ if (font) fontIndex = index;
103
+ }
104
+ } catch { /* Missing font file is missing measurement, not permission to substitute one. */ }
105
+ }
106
+ const cache = new Map();
107
+ const backgrounds = new Map();
108
+ let n = 0;
109
+ const measureText = (request) => {
110
+ const key = JSON.stringify(request);
111
+ if (cache.has(key)) return cache.get(key);
112
+ const measure = () => {
113
+ if (!version || !libass || !font || request.W !== W || request.H !== H) return null;
114
+ const missingGlyphs = [...new Set(Array.from(request.lines.join("")))].filter((char) => {
115
+ if (/\s/u.test(char)) return false;
116
+ const cp = char.codePointAt(0);
117
+ return !charset.some(([a, b]) => cp >= a && cp <= b);
118
+ });
119
+ if (missingGlyphs.length) return null;
120
+ const caption = request.kind === "caption";
121
+ const entry = { kind: request.kind, lines: request.lines, fs: request.fs, renderBox: request.box, in: 0, out: 1 };
122
+ const directives = caption
123
+ ? { captions: [{ ...entry, xShare: request.xShare, yShare: request.yShare, s: 0, e: 1 }] }
124
+ : { cards: [entry] };
125
+ const name = `.text-measure-${process.pid}-${++n}.ass`;
126
+ const file = path.join(dir, name);
127
+ const bounds = { x: W, y: H, right: -1, bottom: -1 };
128
+ const selections = [];
129
+ try {
130
+ // Decode the blank raster through the same filter/conversion as the
131
+ // text. Limited-range YUV white can become RGB 253, not nominal 255.
132
+ // Cache only its proven uniform RGB, never a guessed tolerance.
133
+ if (backgrounds.size < 2) {
134
+ writeFileSync(file, measuredTextAss({}, { W, H }));
135
+ for (const color of ["black", "white"]) {
136
+ const blank = run("ffmpeg", [
137
+ "-hide_banner", "-loglevel", "error", "-filter_threads", "1", "-f", "lavfi", "-i", `color=c=${color}:s=${W}x${H}:r=24:d=1`,
138
+ "-vf", `subtitles=filename=${name}`, "-frames:v", "1", "-pix_fmt", "rgb24", "-f", "rawvideo", "pipe:1",
139
+ ]);
140
+ if (blank.status !== 0 || blank.stdout?.length !== W * H * 3) return null;
141
+ const rgb = [blank.stdout[0], blank.stdout[1], blank.stdout[2]];
142
+ for (let at = 0; at < blank.stdout.length; at++) {
143
+ if (blank.stdout[at] !== rgb[at % 3]) return null;
144
+ }
145
+ backgrounds.set(color, rgb);
146
+ }
147
+ }
148
+ writeFileSync(file, measuredTextAss(directives, { W, H, style: request.style }));
149
+ for (const color of ["black", "white"]) {
150
+ const res = run("ffmpeg", [
151
+ "-hide_banner", "-loglevel", "verbose", "-filter_threads", "1", "-f", "lavfi", "-i", `color=c=${color}:s=${W}x${H}:r=24:d=1`,
152
+ "-vf", `subtitles=filename=${name}`, "-frames:v", "1", "-pix_fmt", "rgb24", "-f", "rawvideo", "pipe:1",
153
+ ]);
154
+ if (res.status !== 0 || res.stdout?.length !== W * H * 3 || /Glyph .* not found|failed to find.*font/iu.test(res.stderr?.toString() ?? "")) return null;
155
+ const observed = fontSelectionEvidence(res.stderr?.toString() ?? "", { file: fontFile, index: Number(fontIndex), faces });
156
+ if (!observed) return null;
157
+ selections.push(...observed);
158
+ const pixels = res.stdout;
159
+ const bg = backgrounds.get(color);
160
+ for (let y = 0, at = 0; y < H; y++) {
161
+ for (let x = 0; x < W; x++, at += 3) {
162
+ if (pixels[at] === bg[0] && pixels[at + 1] === bg[1] && pixels[at + 2] === bg[2]) continue;
163
+ bounds.x = Math.min(bounds.x, x); bounds.y = Math.min(bounds.y, y);
164
+ bounds.right = Math.max(bounds.right, x); bounds.bottom = Math.max(bounds.bottom, y);
165
+ }
166
+ }
167
+ }
168
+ } finally { rmSync(file, { force: true }); }
169
+ if (bounds.right < bounds.x || bounds.bottom < bounds.y) return null;
170
+ return {
171
+ renderer: { ffmpeg: version, libass: "present" },
172
+ font: { ...font, resolved: `${font.resolved}|libass:${JSON.stringify([...new Map(selections.map((entry) => [JSON.stringify(entry), entry])).values()])}` },
173
+ lines: [...request.lines],
174
+ inkRect: { x: bounds.x, y: bounds.y, w: bounds.right - bounds.x + 1, h: bounds.bottom - bounds.y + 1 }, coverage: { missingGlyphs: [] },
175
+ };
176
+ };
177
+ const value = measure();
178
+ cache.set(key, value);
179
+ return value;
180
+ };
181
+ const assertFont = () => {
182
+ if (!font || !fontFile) return false;
183
+ const current = run("fc-match", fontQuery);
184
+ if (current.status !== 0) return false;
185
+ try {
186
+ return `${current.stdout.toString().trim()}|sha256:${createHash("sha256").update(readFileSync(fontFile)).digest("hex")}` === font.resolved;
187
+ } catch { return false; }
188
+ };
189
+ return { measureText, libass, font, version, assertFont };
190
+ }