@aicopycoders/exodus 2026.11.700-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,4 +1,4 @@
1
- import { createHash } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { apiGet, apiPost, getDashboardUrl } from "../lib/client.js";
@@ -6,7 +6,8 @@ import { displayRunStatus, formatApiError } from "../lib/format.js";
6
6
  import { isWorkerStoppedPark } from "../lib/runStatus.js";
7
7
  import { missingRouteLine } from "../lib/route-support.js";
8
8
  import { probeDurationSec } from "../lib/preflight.js";
9
- import { ASSET_UPLOAD_POLICY, pauseAheadLine, } from "./workflow.js";
9
+ import { composeTemplateBrief } from "../lib/templateBrief.js";
10
+ import { ASSET_UPLOAD_POLICY, pauseAheadLine, parseVoicesFlag, } from "./workflow.js";
10
11
  import { HELPER_LEDGER_BASE, SET_OPTION_LEDGER_BASE } from "../lib/helperLedgerBase.js";
11
12
  import { customerAnswer, customerRunPage, customerStageIsWorking, customerStageLines, customerStatusLines, customerStoryboardLines, customerVoicesLines, } from "./video-customer.js";
12
13
  const VOICE_MODES = ["native", "voice-first"];
@@ -163,6 +164,9 @@ Usage:
163
164
  exodus video pull <runId> --out <dir> [--json]
164
165
  exodus video upload <runId> --file <cut.mp4> [--duration <sec>] [--json]
165
166
  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]
167
+ 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>]
168
+ With --describe: [--product-context <text>] [--audience <text>] [--offer <text>] [--mechanism <text>]
169
+ exodus video start --input-options [--conceit <template>] [--voice <native|voice-first>] [--voice-path <path>] [--video-model <id>] [--json]
166
170
  exodus video director <runId> <on|off|follow> [--json]
167
171
 
168
172
  Options:
@@ -213,6 +217,45 @@ Options:
213
217
  the server can't tell who says a line, it asks and
214
218
  starts nothing. If a description is too thin to write
215
219
  from, it says what is missing and starts nothing
220
+ --describe Template: explicitly write from the brief in --script.
221
+ Review the returned script before preparing a storyboard.
222
+ Cannot be combined with --adapt or --resume-script
223
+ --adapt <intent> Template: adapt the exact pasted text in --script to the
224
+ selected structure. State what may change; no new claims,
225
+ identities or consent are inferred. Review original and
226
+ changed text before continuing. Not --adaptation-plan
227
+ --keep-original With --adapt, intentionally review the exact original
228
+ instead of generating changes. Guards and billable checks
229
+ still require a quote; no adaptation is claimed
230
+ --input-mode <automatic|manual|hybrid>
231
+ Template INPUT assistance only, never --one-shot.
232
+ Explicit selections survive every mode. In Hybrid, blank
233
+ supported fields resolve automatically; locks still apply
234
+ --structure <key> A supported structure published for the selected template.
235
+ Unknown or incompatible structures are refused
236
+ --reference <key> A template's reference-ad inspiration, not a production
237
+ element, actor identity, soundtrack or voice permission
238
+ --subject <product|service|non-product>
239
+ Explicit subject, never guessed from the absence of
240
+ --product. Service/non-product cannot select a saved product
241
+ --template-brief <json|@file>
242
+ Template creative pins: { "cards": { "<layer>": "<card>" },
243
+ "settings": { "<name>": "<value>" } }. Discover supported
244
+ controls first; the server validates capabilities and locks
245
+ --song-controls <json|@file>
246
+ --mechanism-plan <json|@file>
247
+ Supported template song/story controls. JSON objects only;
248
+ server schema, capabilities and locks remain authoritative
249
+ Song controls require published songControls:true support;
250
+ {} or all-blank text controls explicitly clear saved Song pins
251
+ --quote-preparation Request only the current script or storyboard phase quote.
252
+ No writer/audio/image/video work. Save --json and review
253
+ estimatedUsd (approximate), maximumUsd (phase bound), scope
254
+ and expiry; this is not a whole-video price
255
+ --authorize-preparation <saved-quote.json>
256
+ Explicitly accept that quote's maximumUsd for its exact
257
+ phase/input. Never upgrades input Automatic to paid consent.
258
+ Keep the same file for recovery; no silent new quote/retry
216
259
  --source-record <file.json>
217
260
  A real ad's source record (start, with --conceit), for
218
261
  a kind of ad that copies an ad shot for shot. Without
@@ -223,9 +266,49 @@ Options:
223
266
  for a template that keeps its source's roles and beats,
224
267
  or "original" for a brief with no source ad. Any other
225
268
  kind refuses it
226
- --stop-at-script Print the script the run would start on, and start
227
- nothing (start, with --conceit). To read a written or
228
- laid-out script first; send it back with --script
269
+ --stop-at-script Print the script the run would start on, and start no
270
+ storyboard/video run (start, with --conceit). Preparation
271
+ may still be paid. For templates, use
272
+ --json to save the approval, source and choices; edit only
273
+ a separate script file, then continue with --resume-script
274
+ --resume-script <saved-stop-response.json>
275
+ Continue a template's saved --stop-at-script --json
276
+ response with --script <edited.txt>, --conceit and
277
+ --style. Keep the server-issued approval, approved source,
278
+ brief, product, selected video model, signed references and voice map.
279
+ V2 also retains input intent/subject/structure/reference,
280
+ direction, sound/story choices and declared source/adaptation
281
+ records; material edits need a new quoted script review.
282
+ Explicit length, picture, --voice, --voice-path and
283
+ --video-model flags override their matching saved choices.
284
+ Changed or cleared --elements and --voices require
285
+ explicit --stop-at-script --json with
286
+ --resume-script to check the edited script and issue a new
287
+ approval; then resume that returned response to start.
288
+ Keep your original description and edited script files.
289
+ A different product still needs fresh writing and approval
290
+ without --resume-script.
291
+ Not for --show
292
+ --input-options List your templates: Golden Six first, then more templates.
293
+ Add --conceit <template> for structures, capabilities,
294
+ identity locks, references and account voices.
295
+ GET only: writes, quotes and starts nothing. Optional
296
+ --voice, --voice-path and --video-model require --conceit.
297
+ Reports unsupported, unavailable and empty separately;
298
+ use the returned IDs with --elements and --voices
299
+ --elements <json|@file>
300
+ Template saved references: [{"handle":"host","elementId":"<id>"}].
301
+ Only authorized saved character/location IDs are supported;
302
+ this does not upload images. [] means no saved references
303
+ --voices <json|@file>
304
+ Template voices keyed by canonical SCRIPT speaker name:
305
+ {"HOST":"<voiceId>","NARRATOR":{"voiceId":"<id>","label":"Name"},"GUEST":null}.
306
+ A string pins, an object pins with an optional label,
307
+ null clears that speaker. {} means no selected voices.
308
+ Repeated --elements or --voices: last value wins.
309
+ Empty selections are omitted; the server checks IDs,
310
+ template support and approval again before starting.
311
+ --voice and --voice-path keep their existing meanings
229
312
  --rewrite-to-fit If the script doesn't fit the kind of ad (more speakers
230
313
  than it takes, or a rule it has), write a new script for
231
314
  it from yours, print it, and start on it (start, with
@@ -236,6 +319,26 @@ Options:
236
319
  --conceit <kind> Kind of ad (start)
237
320
  --style <look> Look (start)
238
321
  The server lists the kinds and looks it offers. An unknown word prints them.
322
+ --product-context <text>
323
+ Product facts for a template's --describe brief.
324
+ This is text, not the saved-product ID used by --product.
325
+ --audience <text> Audience for a template's --describe brief
326
+ --offer <text> Approved offer for a template's --describe brief
327
+ --mechanism <text> Supported mechanism for a template's --describe brief.
328
+ Brief fields combine with --script file text, not with
329
+ --adapt, --keep-original, --resume-script or non-template starts.
330
+ --requested-seconds <seconds>
331
+ Requested template length: a positive finite number,
332
+ including fractional seconds. Sent as requested, not
333
+ clamped to a preset. The server may refuse an unsupported
334
+ length before starting. Not an upload's --duration
335
+ --pictures-per-scene <1|3>
336
+ Template scene-picture candidates: 1 (default) or 3
337
+ --product <brandProductId>
338
+ Existing product from this brand for a template start.
339
+ Uses its authorized product photos as references, never
340
+ a URL, image-ad reference, actor identity or style pick.
341
+ These three options do not work with --show
239
342
  --direction "<note>" Note for the whole ad (start)
240
343
  --frame pov Camera-as-character POV: the camera is a person in the
241
344
  scene (start, with --conceit). Leave it off for a
@@ -810,6 +913,7 @@ function clipFromArtifact(sceneIndex, artifact) {
810
913
  voicePitchHz: artifact.voicePitchHz ?? null,
811
914
  voicePitchMethod: artifact.voicePitchMethod ?? null,
812
915
  replannedIdea: artifact.replannedIdea ?? null,
916
+ ...(artifact.voiceLock !== undefined ? { voiceLock: artifact.voiceLock } : {}),
813
917
  };
814
918
  }
815
919
  function keyframeDownload(sceneIndex, imageUrl) {
@@ -987,6 +1091,10 @@ function withReplannedPrompts(raw, replanned) {
987
1091
  }
988
1092
  export function planPull(run, items, opts) {
989
1093
  const texts = [];
1094
+ const clipAudio = run.videoChoice?.videoModel === "template-video"
1095
+ ? run.songAsVoice || run.videoChoice.voiceMode === "voice-first" ? "discard"
1096
+ : run.videoChoice.voiceMode === "native" ? "keep" : undefined
1097
+ : undefined;
990
1098
  const storyboardArtifact = run.nodes
991
1099
  .flatMap((n) => n.outputs ?? [])
992
1100
  .find((a) => a.type === "storyboard");
@@ -1200,6 +1308,7 @@ export function planPull(run, items, opts) {
1200
1308
  voiceFirstBlockedBy: clip ? clip.voiceFirstBlockedBy : null,
1201
1309
  voicePitchHz: clip ? clip.voicePitchHz : null,
1202
1310
  voicePitchMethod: clip ? clip.voicePitchMethod : null,
1311
+ ...(clip?.voiceLock !== undefined ? { voiceLock: clip.voiceLock } : {}),
1203
1312
  clipStatus: item?.status ?? "missing",
1204
1313
  error: item?.error ?? null,
1205
1314
  flagged: item?.flagged === true,
@@ -1259,6 +1368,7 @@ export function planPull(run, items, opts) {
1259
1368
  },
1260
1369
  }
1261
1370
  : {}),
1371
+ ...(clipAudio ? { clipAudio } : {}),
1262
1372
  ...(run.shots?.frame || run.shots?.pacing ? { shots: run.shots } : {}),
1263
1373
  },
1264
1374
  };
@@ -1301,6 +1411,7 @@ export function markPullFailure(manifest, failure) {
1301
1411
  scene.voiceFirstBlockedBy = null;
1302
1412
  scene.voicePitchHz = null;
1303
1413
  scene.voicePitchMethod = null;
1414
+ delete scene.voiceLock;
1304
1415
  }
1305
1416
  if (scene.voice === failure.file)
1306
1417
  scene.voice = null;
@@ -1487,6 +1598,24 @@ function planValueFlag(occurrences, name) {
1487
1598
  }
1488
1599
  return { ok: true, value };
1489
1600
  }
1601
+ function planTemplateValue(occurrences, name, exactText = false) {
1602
+ let value;
1603
+ for (const occurrence of occurrences) {
1604
+ if (occurrence.flag !== name)
1605
+ continue;
1606
+ const given = occurrence.value?.trim();
1607
+ if (!given || given.startsWith("--")) {
1608
+ return { ok: false, line: `video start --${name} needs a value.` };
1609
+ }
1610
+ const choice = exactText ? occurrence.value : given;
1611
+ if (value !== undefined && value !== choice) {
1612
+ return { ok: false, line: `video start --${name} has conflicting values. Pass one choice.` };
1613
+ }
1614
+ value = choice;
1615
+ }
1616
+ return { ok: true, value };
1617
+ }
1618
+ const TEMPLATE_WRITER_BRIEF_USAGE = "--product-context, --audience, --offer and --mechanism require a template start with --describe; not --adapt, --keep-original or --resume-script.";
1490
1619
  export function planVideoStart(flags, occurrences) {
1491
1620
  const showId = nonBlank(flagString(flags, "show"));
1492
1621
  const scriptFile = nonBlank(flagString(flags, "script"));
@@ -1525,6 +1654,121 @@ export function planVideoStart(flags, occurrences) {
1525
1654
  const planFlag = planValueFlag(occurrences, "adaptation-plan");
1526
1655
  if (!planFlag.ok)
1527
1656
  return { kind: "usage", line: planFlag.line };
1657
+ const resumeFlag = planTemplateValue(occurrences, "resume-script");
1658
+ if (!resumeFlag.ok)
1659
+ return { kind: "usage", line: resumeFlag.line };
1660
+ if (showId && resumeFlag.value !== undefined) {
1661
+ return { kind: "usage", line: "--resume-script is a template input, not a --show choice." };
1662
+ }
1663
+ const secondsFlag = planTemplateValue(occurrences, "requested-seconds");
1664
+ if (!secondsFlag.ok)
1665
+ return { kind: "usage", line: secondsFlag.line };
1666
+ const picturesFlag = planTemplateValue(occurrences, "pictures-per-scene");
1667
+ if (!picturesFlag.ok)
1668
+ return { kind: "usage", line: picturesFlag.line };
1669
+ const productFlag = planTemplateValue(occurrences, "product");
1670
+ if (!productFlag.ok)
1671
+ return { kind: "usage", line: productFlag.line };
1672
+ const elementsFlag = planValueFlag(occurrences, "elements");
1673
+ if (!elementsFlag.ok)
1674
+ return { kind: "usage", line: elementsFlag.line };
1675
+ const voicesFlag = planValueFlag(occurrences, "voices");
1676
+ if (!voicesFlag.ok)
1677
+ return { kind: "usage", line: voicesFlag.line };
1678
+ const inputModeFlag = planTemplateValue(occurrences, "input-mode");
1679
+ if (!inputModeFlag.ok)
1680
+ return { kind: "usage", line: inputModeFlag.line };
1681
+ if (inputModeFlag.value !== undefined
1682
+ && inputModeFlag.value !== "automatic" && inputModeFlag.value !== "manual" && inputModeFlag.value !== "hybrid") {
1683
+ return { kind: "usage", line: "video start --input-mode must be automatic, manual or hybrid." };
1684
+ }
1685
+ const structureFlag = planTemplateValue(occurrences, "structure");
1686
+ if (!structureFlag.ok)
1687
+ return { kind: "usage", line: structureFlag.line };
1688
+ const referenceFlag = planTemplateValue(occurrences, "reference");
1689
+ if (!referenceFlag.ok)
1690
+ return { kind: "usage", line: referenceFlag.line };
1691
+ const subjectFlag = planTemplateValue(occurrences, "subject");
1692
+ if (!subjectFlag.ok)
1693
+ return { kind: "usage", line: subjectFlag.line };
1694
+ if (subjectFlag.value !== undefined
1695
+ && subjectFlag.value !== "product" && subjectFlag.value !== "service" && subjectFlag.value !== "non-product") {
1696
+ return { kind: "usage", line: "video start --subject must be product, service or non-product." };
1697
+ }
1698
+ const adaptFlag = planTemplateValue(occurrences, "adapt", true);
1699
+ if (!adaptFlag.ok)
1700
+ return { kind: "usage", line: adaptFlag.line };
1701
+ const briefFlag = planTemplateValue(occurrences, "template-brief");
1702
+ if (!briefFlag.ok)
1703
+ return { kind: "usage", line: briefFlag.line };
1704
+ const songFlag = planTemplateValue(occurrences, "song-controls");
1705
+ if (!songFlag.ok)
1706
+ return { kind: "usage", line: songFlag.line };
1707
+ const mechanismFlag = planTemplateValue(occurrences, "mechanism-plan");
1708
+ if (!mechanismFlag.ok)
1709
+ return { kind: "usage", line: mechanismFlag.line };
1710
+ const authorizationFlag = planTemplateValue(occurrences, "authorize-preparation");
1711
+ if (!authorizationFlag.ok)
1712
+ return { kind: "usage", line: authorizationFlag.line };
1713
+ const quoteFlags = occurrences.filter(({ flag }) => flag === "quote-preparation");
1714
+ if (quoteFlags.some(({ value }) => value !== undefined && !value.startsWith("--"))) {
1715
+ return { kind: "usage", line: "--quote-preparation takes no value. It requests a phase quote, not paid preparation." };
1716
+ }
1717
+ const quotePreparation = quoteFlags.length > 0;
1718
+ if (quotePreparation && authorizationFlag.value !== undefined) {
1719
+ return { kind: "usage", line: "Pass --quote-preparation to review the quote, or --authorize-preparation <saved-quote.json> to accept that exact quote, not both." };
1720
+ }
1721
+ const describeFlags = occurrences.filter(({ flag }) => flag === "describe");
1722
+ if (describeFlags.some(({ value }) => value !== undefined && !value.startsWith("--"))) {
1723
+ return { kind: "usage", line: "--describe takes no value. It writes from the brief in --script." };
1724
+ }
1725
+ const describe = describeFlags.length > 0;
1726
+ const keepFlags = occurrences.filter(({ flag }) => flag === "keep-original");
1727
+ if (keepFlags.some(({ value }) => value !== undefined && !value.startsWith("--"))) {
1728
+ return { kind: "usage", line: "--keep-original takes no value. It requests guarded review of the exact original, not new adaptation." };
1729
+ }
1730
+ const keepOriginal = keepFlags.length > 0;
1731
+ const writerBrief = {};
1732
+ for (const [flag, field] of [
1733
+ ["product-context", "product"], ["audience", "audience"], ["offer", "offer"], ["mechanism", "mechanism"],
1734
+ ]) {
1735
+ const choice = planTemplateValue(occurrences, flag);
1736
+ if (!choice.ok)
1737
+ return { kind: "usage", line: choice.line };
1738
+ if (choice.value !== undefined)
1739
+ writerBrief[field] = choice.value;
1740
+ }
1741
+ if (Object.keys(writerBrief).length
1742
+ && (!describe || showId || keepOriginal || adaptFlag.value !== undefined || resumeFlag.value !== undefined)) {
1743
+ return { kind: "usage", line: TEMPLATE_WRITER_BRIEF_USAGE };
1744
+ }
1745
+ if (describe && keepOriginal) {
1746
+ return { kind: "usage", line: "Pass --describe to write from a brief or --keep-original to review unchanged copy, not both." };
1747
+ }
1748
+ if (describe && adaptFlag.value !== undefined) {
1749
+ return { kind: "usage", line: "Pass --describe to write from a brief or --adapt <intent> to adapt pasted text, not both." };
1750
+ }
1751
+ if (resumeFlag.value !== undefined && (describe || adaptFlag.value !== undefined)) {
1752
+ return { kind: "usage", line: "--resume-script retains the original source and adaptation intent; do not combine it with --describe or --adapt." };
1753
+ }
1754
+ if (showId && (inputModeFlag.value !== undefined || structureFlag.value !== undefined
1755
+ || referenceFlag.value !== undefined || subjectFlag.value !== undefined
1756
+ || adaptFlag.value !== undefined || briefFlag.value !== undefined || songFlag.value !== undefined
1757
+ || mechanismFlag.value !== undefined || quotePreparation || authorizationFlag.value !== undefined || keepOriginal || describe)) {
1758
+ return { kind: "usage", line: "V2 input and preparation flags are template inputs, not --show choices." };
1759
+ }
1760
+ const requestedSeconds = secondsFlag.value === undefined ? undefined : Number(secondsFlag.value);
1761
+ if (requestedSeconds !== undefined && (!Number.isFinite(requestedSeconds) || requestedSeconds <= 0)) {
1762
+ return { kind: "usage", line: "video start --requested-seconds must be a positive finite number of seconds." };
1763
+ }
1764
+ if (picturesFlag.value !== undefined && picturesFlag.value !== "1" && picturesFlag.value !== "3") {
1765
+ return { kind: "usage", line: "video start --pictures-per-scene must be 1 or 3." };
1766
+ }
1767
+ const hasTemplateInputs = requestedSeconds !== undefined || picturesFlag.value !== undefined
1768
+ || productFlag.value !== undefined || elementsFlag.value !== undefined || voicesFlag.value !== undefined;
1769
+ if (showId && hasTemplateInputs) {
1770
+ return { kind: "usage", line: "--requested-seconds, --pictures-per-scene, --product, --elements and --voices are template inputs, not --show choices." };
1771
+ }
1528
1772
  const videoModel = videoModelFlag.value;
1529
1773
  const voiceMode = voiceFlag.value;
1530
1774
  const reviewStoryboardFlag = occurrences.some((o) => o.flag === "review-storyboard");
@@ -1697,6 +1941,46 @@ export function planVideoStart(flags, occurrences) {
1697
1941
  opts.sourceRecordFile = recordFlag.value;
1698
1942
  if (planFlag.value)
1699
1943
  opts.adaptationPlanFile = planFlag.value;
1944
+ if (resumeFlag.value)
1945
+ opts.resumeScriptFile = resumeFlag.value;
1946
+ if (requestedSeconds !== undefined)
1947
+ opts.requestedSeconds = requestedSeconds;
1948
+ if (picturesFlag.value !== undefined)
1949
+ opts.picturesPerScene = picturesFlag.value === "3" ? 3 : 1;
1950
+ if (productFlag.value !== undefined)
1951
+ opts.productId = productFlag.value;
1952
+ if (elementsFlag.value !== undefined)
1953
+ opts.elementsInput = elementsFlag.value;
1954
+ if (voicesFlag.value !== undefined)
1955
+ opts.voicesInput = voicesFlag.value;
1956
+ if (inputModeFlag.value === "automatic" || inputModeFlag.value === "manual" || inputModeFlag.value === "hybrid") {
1957
+ opts.inputMode = inputModeFlag.value;
1958
+ }
1959
+ if (structureFlag.value !== undefined)
1960
+ opts.structure = structureFlag.value;
1961
+ if (referenceFlag.value !== undefined)
1962
+ opts.reference = referenceFlag.value;
1963
+ if (subjectFlag.value === "product" || subjectFlag.value === "service" || subjectFlag.value === "non-product") {
1964
+ opts.subject = subjectFlag.value;
1965
+ }
1966
+ if (adaptFlag.value !== undefined)
1967
+ opts.adaptationIntent = adaptFlag.value;
1968
+ if (briefFlag.value !== undefined)
1969
+ opts.templateBriefInput = briefFlag.value;
1970
+ if (songFlag.value !== undefined)
1971
+ opts.songControlsInput = songFlag.value;
1972
+ if (mechanismFlag.value !== undefined)
1973
+ opts.mechanismPlanInput = mechanismFlag.value;
1974
+ if (quotePreparation)
1975
+ opts.quotePreparation = true;
1976
+ if (authorizationFlag.value !== undefined)
1977
+ opts.authorizePreparationFile = authorizationFlag.value;
1978
+ if (describe)
1979
+ opts.describe = true;
1980
+ if (keepOriginal)
1981
+ opts.keepOriginal = true;
1982
+ if (Object.keys(writerBrief).length)
1983
+ opts.writerBrief = writerBrief;
1700
1984
  if (frameFlag.value || pacingFlag.value) {
1701
1985
  opts.shots = {
1702
1986
  ...(frameFlag.value ? { frame: frameFlag.value } : {}),
@@ -1708,15 +1992,24 @@ export function planVideoStart(flags, occurrences) {
1708
1992
  function isRecord(value) {
1709
1993
  return typeof value === "object" && value !== null && !Array.isArray(value);
1710
1994
  }
1711
- function scriptRunOptionsOf(data) {
1712
- if (!isRecord(data) || !Array.isArray(data.conceits) || !Array.isArray(data.styles)) {
1995
+ function scriptRunOptionsOf(data, door = "script") {
1996
+ const rows = isRecord(data) ? data[door === "template" ? "templates" : "conceits"] : undefined;
1997
+ if (!isRecord(data) || !Array.isArray(rows) || !Array.isArray(data.styles)) {
1713
1998
  return null;
1714
1999
  }
1715
2000
  const conceits = [];
1716
- for (const row of data.conceits) {
2001
+ for (const row of rows) {
1717
2002
  if (!isRecord(row) || typeof row.key !== "string" || typeof row.label !== "string")
1718
2003
  return null;
1719
- conceits.push({ key: row.key, label: row.label });
2004
+ if (door === "template" && row.style !== undefined) {
2005
+ if (!isRecord(row.style) || typeof row.style.slug !== "string" || row.style.slug.trim() === ""
2006
+ || typeof row.style.label !== "string")
2007
+ return null;
2008
+ conceits.push({ key: row.key, label: row.label, style: { slug: row.style.slug, label: row.style.label } });
2009
+ }
2010
+ else {
2011
+ conceits.push({ key: row.key, label: row.label });
2012
+ }
1720
2013
  }
1721
2014
  const styles = [];
1722
2015
  for (const row of data.styles) {
@@ -1726,6 +2019,181 @@ function scriptRunOptionsOf(data) {
1726
2019
  }
1727
2020
  return { conceits, styles };
1728
2021
  }
2022
+ const GOLDEN_TEMPLATE_KEYS = [
2023
+ "ugc-template", "authority-yapper-template", "microdrama-template",
2024
+ "skeleton-timeline-template", "pixar-song-template", "personification-template",
2025
+ ];
2026
+ function templateListingResult(menu, data, json) {
2027
+ const rows = isRecord(data) && Array.isArray(data.templates) ? data.templates : [];
2028
+ const templates = menu.conceits.map(({ key, label }) => {
2029
+ const row = rows.find((entry) => isRecord(entry) && entry.key === key);
2030
+ const experience = isRecord(row) && isRecord(row.templateExperience) ? row.templateExperience : undefined;
2031
+ return {
2032
+ key, label,
2033
+ description: isRecord(row) && typeof row.description === "string" ? row.description.replace(/\s+/g, " ").trim() : "",
2034
+ structureCount: Array.isArray(experience?.structures) ? experience.structures.length : 0,
2035
+ };
2036
+ });
2037
+ const golden = GOLDEN_TEMPLATE_KEYS.flatMap((key) => templates.filter((row) => row.key === key));
2038
+ const extras = templates.filter(({ key }) => !GOLDEN_TEMPLATE_KEYS.some((goldenKey) => goldenKey === key));
2039
+ if (json)
2040
+ return { code: 0, lines: [JSON.stringify({ templates: [
2041
+ ...golden.map((row) => ({ ...row, group: "golden-six" })),
2042
+ ...extras.map((row) => ({ ...row, group: "more" })),
2043
+ ] })] };
2044
+ return { code: 0, lines: templates.length === 0 ? ["No templates are available."] : [
2045
+ { label: "Golden Six", templates: golden },
2046
+ { label: `${extras.length} more ${extras.length === 1 ? "template" : "templates"}`, templates: extras },
2047
+ ].flatMap((group) => group.templates.length ? [
2048
+ group.label,
2049
+ ...group.templates.map((row) => ` ${row.key} — ${row.label} — ${row.description} — ${row.structureCount} ${row.structureCount === 1 ? "structure" : "structures"}`),
2050
+ ] : []) };
2051
+ }
2052
+ async function templateInputOptionsFlow(occurrences, json, deps) {
2053
+ const allowed = {
2054
+ conceit: true, "input-options": true, voice: true, "voice-path": true, "video-model": true, json: true,
2055
+ };
2056
+ const unsupported = occurrences.find(({ flag }) => !Object.hasOwn(allowed, flag));
2057
+ if (unsupported) {
2058
+ return { code: 1, usage: true, lines: [`--input-options is read-only; --${unsupported.flag} is not a discovery option.`] };
2059
+ }
2060
+ if (occurrences.some(({ flag, value }) => flag === "input-options" && value !== undefined && !value.startsWith("--"))) {
2061
+ return { code: 1, usage: true, lines: ["--input-options takes no value. Choose the template with --conceit <template>."] };
2062
+ }
2063
+ const template = planTemplateValue(occurrences, "conceit");
2064
+ if (!template.ok)
2065
+ return { code: 1, usage: true, lines: [template.line] };
2066
+ if (!template.value && occurrences.some(({ flag }) => flag === "voice" || flag === "voice-path" || flag === "video-model")) {
2067
+ return { code: 1, usage: true, lines: ["Choose --conceit <template> to inspect voice and video route options."] };
2068
+ }
2069
+ const query = new URLSearchParams({ door: "template" });
2070
+ if (template.value)
2071
+ query.set("template", template.value);
2072
+ for (const [flag, field] of [["voice", "voiceMode"], ["voice-path", "voicePath"], ["video-model", "videoModel"]]) {
2073
+ const choice = planValueFlag(occurrences, flag);
2074
+ if (!choice.ok)
2075
+ return { code: 1, usage: true, lines: [choice.line] };
2076
+ if (choice.value !== undefined) {
2077
+ if (flag === "voice" && !isVoiceMode(choice.value)) {
2078
+ return { code: 1, usage: true, lines: [`video start --voice must be native or voice-first (got "${choice.value}").`] };
2079
+ }
2080
+ query.set(field, choice.value);
2081
+ }
2082
+ }
2083
+ const response = await deps.get(`${SCRIPT_RUNS_PATH}?${query}`).catch(() => null);
2084
+ if (!response)
2085
+ return adminOnlyResult("Template input options could not be read. Nothing has started.", json);
2086
+ if (!response.ok)
2087
+ return errorResult(response, json);
2088
+ const menu = scriptRunOptionsOf(response.data, "template");
2089
+ if (!menu)
2090
+ return adminOnlyResult("This server did not publish a readable template catalog. Nothing has started.", json);
2091
+ if (!template.value)
2092
+ return templateListingResult(menu, response.data, json);
2093
+ const options = isRecord(response.data) ? response.data.inputOptions : undefined;
2094
+ if (!menu?.conceits.some(({ key }) => key === template.value)
2095
+ || !isRecord(options) || !isRecord(options.selectors)
2096
+ || typeof options.selectors.elements !== "boolean" || typeof options.selectors.voices !== "boolean"
2097
+ || !Array.isArray(options.elements) || !Array.isArray(options.voices)
2098
+ || typeof options.voicesUnavailable !== "boolean") {
2099
+ return adminOnlyResult("This server did not publish readable input options for that template. Nothing has started.", json);
2100
+ }
2101
+ const rows = isRecord(response.data) && Array.isArray(response.data.templates) ? response.data.templates : [];
2102
+ const selected = rows.find((row) => isRecord(row) && row.key === template.value);
2103
+ const experience = isRecord(selected) && isRecord(selected.templateExperience) ? selected.templateExperience : undefined;
2104
+ const capabilities = isRecord(selected) && isRecord(selected.templateCapabilities) ? selected.templateCapabilities : undefined;
2105
+ const metadata = {
2106
+ ...(experience ? { templateExperience: experience } : {}),
2107
+ ...(capabilities ? { templateCapabilities: capabilities } : {}),
2108
+ };
2109
+ const experienceLines = [];
2110
+ if (experience) {
2111
+ if (isRecord(experience.identity)) {
2112
+ experienceLines.push(`Identity: ${String(experience.identity.summary ?? "")}`, ...stringsOf(experience.identity.locks).flatMap((lock) => {
2113
+ const lines = [];
2114
+ let remaining = lock.replace(/\s+/g, " ").trim();
2115
+ while (remaining.length > 90) {
2116
+ const space = remaining.lastIndexOf(" ", 90);
2117
+ const end = space > 0 ? space : 90;
2118
+ lines.push(`${lines.length ? " " : " Locked: "}${remaining.slice(0, end)}`);
2119
+ remaining = remaining.slice(end).trimStart();
2120
+ }
2121
+ lines.push(`${lines.length ? " " : " Locked: "}${remaining}`);
2122
+ return lines;
2123
+ }), ...stringsOf(experience.identity.flexible).map((choice) => ` Supported variation: ${choice}`));
2124
+ }
2125
+ if (Array.isArray(experience.structures)) {
2126
+ experienceLines.push("Story structures (select with --structure):");
2127
+ let structureNumber = 0;
2128
+ for (const structure of experience.structures) {
2129
+ if (!isRecord(structure) || typeof structure.key !== "string" || typeof structure.label !== "string")
2130
+ continue;
2131
+ experienceLines.push(` ${++structureNumber}. ${structure.label} (${structure.key})${structure.key === experience.defaultStructureKey ? " (template-default)" : ""}`, ...(typeof structure.description === "string" ? [` ${structure.description}`] : []), ...(Array.isArray(structure.beats) ? [` Beats: ${structure.beats
2132
+ .filter((beat) => isRecord(beat) && typeof beat.label === "string")
2133
+ .map((beat, index) => `${index + 1}. ${beat.label}`).join(" → ")}`] : []), ...(typeof structure.exampleScript === "string" ? [
2134
+ " Example:",
2135
+ ...structure.exampleScript.split(/\r?\n/).map((line) => ` ${line}`),
2136
+ ] : []));
2137
+ }
2138
+ }
2139
+ if (Array.isArray(experience.references)) {
2140
+ experienceLines.push("Reference examples — production rights are not granted:");
2141
+ for (const reference of experience.references) {
2142
+ if (!isRecord(reference) || typeof reference.key !== "string" || typeof reference.label !== "string")
2143
+ continue;
2144
+ const playable = reference.availability === "playable" && reference.previewRights !== "restricted"
2145
+ && isRecord(reference.media) && reference.media.kind === "video" && typeof reference.media.url === "string"
2146
+ && reference.media.url.trim().length > 0;
2147
+ const unavailable = reference.previewRights === "restricted" ? "preview restricted"
2148
+ : reference.availability === "playable" ? "no video preview"
2149
+ : String(reference.availability ?? "unavailable");
2150
+ experienceLines.push(` ${reference.label} (${reference.key}): ${playable ? "playable" : `not playable — ${unavailable}`}`, ...(typeof reference.unavailableReason === "string" ? [` ${reference.unavailableReason}`] : []), ...(isRecord(reference.source) && typeof reference.source.label === "string" ? [` Source: ${reference.source.label}`] : []), ...(isRecord(reference.source) && typeof reference.source.url === "string" ? [` URL: ${reference.source.url}`] : []));
2151
+ }
2152
+ }
2153
+ }
2154
+ const references = [];
2155
+ for (const row of options.elements) {
2156
+ if (!isRecord(row) || typeof row.elementId !== "string" || typeof row.handle !== "string"
2157
+ || (row.kind !== "character" && row.kind !== "location")
2158
+ || typeof row.name !== "string" || typeof row.look !== "string" || typeof row.imageUrl !== "string") {
2159
+ return adminOnlyResult("This server returned unreadable saved references. Nothing has started.", json);
2160
+ }
2161
+ references.push(` ${row.name} (${row.kind}) — handle: ${row.handle}; elementId: ${row.elementId}`, ` Look: ${row.look}`, ` Image: ${row.imageUrl}`);
2162
+ }
2163
+ const voices = [];
2164
+ for (const row of options.voices) {
2165
+ if (!isRecord(row) || typeof row.voiceId !== "string" || typeof row.name !== "string"
2166
+ || (row.description !== undefined && typeof row.description !== "string")
2167
+ || (row.previewUrl !== undefined && typeof row.previewUrl !== "string")) {
2168
+ return adminOnlyResult("This server returned unreadable account voices. Nothing has started.", json);
2169
+ }
2170
+ voices.push(` ${row.name} — voiceId: ${row.voiceId}`, ...(row.description ? [` ${row.description}`] : []), ...(row.previewUrl ? [` Preview: ${row.previewUrl}`] : []));
2171
+ }
2172
+ if (json)
2173
+ return { code: 0, lines: [JSON.stringify({ ...options, ...metadata })] };
2174
+ return {
2175
+ code: 0,
2176
+ lines: [
2177
+ `Template input options: ${template.value}`,
2178
+ ...experienceLines,
2179
+ ...(capabilities ? [
2180
+ "Server-supported creative controls (template-default values are not intelligent automatic choices):",
2181
+ JSON.stringify(capabilities, null, 2),
2182
+ "Use --template-brief for supported pins. Server locks, dependencies and paid approval still apply.",
2183
+ ] : ["V2 creative capabilities are not published by this server; no local catalog or fallback choices are supplied."]),
2184
+ ...(!options.selectors.elements
2185
+ ? ["Saved references are not supported for this template and selected route."]
2186
+ : references.length === 0 ? ["No supported saved references are available."]
2187
+ : ["Saved references:", ...references]),
2188
+ ...(!options.selectors.voices
2189
+ ? ["Account voices are not supported for this template and selected route."]
2190
+ : options.voicesUnavailable
2191
+ ? ["Account voices are unavailable right now; this is not an empty catalog. No fallback voices are offered."]
2192
+ : voices.length === 0 ? ["No account voices are available."]
2193
+ : ["Account voices:", ...voices]),
2194
+ ],
2195
+ };
2196
+ }
1729
2197
  function isResolvedCard(value) {
1730
2198
  if (!isRecord(value))
1731
2199
  return false;
@@ -1877,16 +2345,57 @@ function scriptStartRefused(res, json) {
1877
2345
  ],
1878
2346
  };
1879
2347
  }
1880
- function stoppedAtScriptResult(data, json) {
2348
+ function stoppedAtScriptResult(data, json, templateStart, voices, selections, templateIntent, context, intentResolution) {
1881
2349
  const script = typeof data.script === "string" ? data.script : "";
1882
2350
  const tidied = data.tidied === undefined ? null : scriptTidiedOf(data.tidied);
1883
2351
  const written = writtenOf(data.written);
1884
2352
  const rewritten = writtenOf(data.rewritten);
2353
+ if (templateIntent) {
2354
+ const retained = scriptResumeOf(data);
2355
+ if (!retained?.templateIntent
2356
+ || !sameJsonValue(retained.templateIntent, templateIntent)
2357
+ || !sameTemplateBrief(retained.templateBrief, context?.templateBrief)
2358
+ || retained.productId !== context?.productId || retained.videoModel !== context?.videoModel
2359
+ || (data.direction !== undefined && retained.direction !== context?.direction)
2360
+ || (data.music !== undefined && retained.music !== context?.music)
2361
+ || (data.shots !== undefined && !sameJsonValue(retained.shots, context?.shots))
2362
+ || (data.songControls !== undefined && !sameJsonValue(retained.songControls, context?.songControls))
2363
+ || (data.mechanismPlan !== undefined && !sameJsonValue(retained.mechanismPlan, context?.mechanismPlan))) {
2364
+ return adminOnlyResult("The server did not return a signed script review with the exact original input, mode, structure and adaptation intent. Do not resume this response; request a fresh review.", json);
2365
+ }
2366
+ }
2367
+ const { voiceMode: serverVoiceMode, voicePath: serverVoicePath, elements: serverElements, voices: serverVoices, ...templateData } = data;
2368
+ if (templateStart && ((voices.voiceMode !== undefined && serverVoiceMode !== undefined && voices.voiceMode !== serverVoiceMode)
2369
+ || (voices.voicePath !== undefined && serverVoicePath !== undefined && voices.voicePath !== serverVoicePath))) {
2370
+ return adminOnlyResult("The server returned different voice choices from those selected. Nothing has started. Check the choices and write the script again before resuming.", json);
2371
+ }
2372
+ if (templateStart) {
2373
+ const elements = serverElements === undefined ? [] : scriptElementsOf(serverElements);
2374
+ const voiceMap = serverVoices === undefined ? {} : scriptVoicesOf(serverVoices);
2375
+ if (elements === null || voiceMap === null
2376
+ || !sameScriptSelections(selections, { elements, voices: voiceMap })) {
2377
+ return adminOnlyResult("The server did not retain the selected references and voices in its script approval response. Nothing has started. Write and approve the script again before resuming.", json);
2378
+ }
2379
+ }
1885
2380
  if (json) {
1886
2381
  return {
1887
2382
  code: 0,
1888
2383
  lines: [
1889
2384
  JSON.stringify({
2385
+ ...(templateStart ? {
2386
+ ...templateData,
2387
+ ...selections,
2388
+ ...(voices.voiceMode !== undefined ? { voiceMode: voices.voiceMode } : {}),
2389
+ ...(voices.voicePath !== undefined ? { voicePath: voices.voicePath } : {}),
2390
+ ...(templateIntent && context?.direction !== undefined ? { direction: context.direction } : {}),
2391
+ ...(templateIntent && context?.music !== undefined ? { music: context.music } : {}),
2392
+ ...(templateIntent && context?.shots !== undefined ? { shots: context.shots } : {}),
2393
+ ...(templateIntent && context?.songControls !== undefined ? { songControls: context.songControls } : {}),
2394
+ ...(templateIntent && context?.mechanismPlan !== undefined ? { mechanismPlan: context.mechanismPlan } : {}),
2395
+ ...(templateIntent && context?.sourceRecord !== undefined ? { sourceRecord: context.sourceRecord } : {}),
2396
+ ...(templateIntent && context?.adaptationPlan !== undefined ? { adaptationPlan: context.adaptationPlan } : {}),
2397
+ ...(intentResolution !== undefined ? { intentResolution } : {}),
2398
+ } : {}),
1890
2399
  stoppedAtScript: true,
1891
2400
  script,
1892
2401
  ...(tidied ? { tidied } : {}),
@@ -1900,15 +2409,47 @@ function stoppedAtScriptResult(data, json) {
1900
2409
  code: 0,
1901
2410
  lines: [
1902
2411
  ...scriptTidiedHead(tidied),
1903
- rewritten !== null
1904
- ? "Your script didn't fit this kind of ad, so we wrote a new one from it. Nothing has started."
1905
- : written !== null
1906
- ? "Your file described the ad, so we wrote this script from it. Nothing has started."
1907
- : "This is the script the run would start on. Nothing has started.",
2412
+ ...(templateIntent ? [
2413
+ `Input assistance: ${templateIntent.mode === "auto" ? "automatic" : templateIntent.mode}`,
2414
+ ...(templateIntent.structureKey ? [`Structure: ${templateIntent.structureKey}`] : []),
2415
+ ...(templateIntent.referenceKey ? [`Reference inspiration: ${templateIntent.referenceKey} (not production rights)`] : []),
2416
+ "",
2417
+ ] : []),
2418
+ ...(templateIntent ? intentResolution ? [
2419
+ "Effective creative brief (server-resolved; raw pins remain separate):",
2420
+ JSON.stringify(intentResolution.effectiveBrief, null, 2),
2421
+ "Choice provenance (template-default / resolved / pinned):",
2422
+ JSON.stringify(intentResolution.provenance, null, 2),
2423
+ "",
2424
+ ] : ["This server did not publish resolved-choice provenance for this draft.", ""] : []),
2425
+ ...(templateIntent?.input.kind === "adapt" ? [
2426
+ "Original pasted text (retained exactly in --json):",
2427
+ templateIntent.input.originalText,
2428
+ "",
2429
+ "Adaptation intent:",
2430
+ templateIntent.input.adaptationIntent,
2431
+ "",
2432
+ templateIntent.input.originalText === script
2433
+ ? "No text changed. The original was kept; no adaptation is claimed."
2434
+ : "Changed text — compare the original above with the complete resulting script below:",
2435
+ "",
2436
+ ] : []),
2437
+ templateIntent
2438
+ ? "Script preparation finished; no storyboard or video run has started. Review this exact resulting script before continuing:"
2439
+ : rewritten !== null
2440
+ ? "Your script didn't fit this kind of ad, so we wrote a new one from it. Nothing has started."
2441
+ : written !== null
2442
+ ? "Your file described the ad, so we wrote this script from it. Nothing has started."
2443
+ : "This is the script the run would start on. Nothing has started.",
1908
2444
  "",
1909
2445
  ...script.split("\n").map((line) => (line ? ` ${line}` : "")),
1910
2446
  "",
1911
- "To start it, save it to a file and run the same command with --script <that file> and without --stop-at-script.",
2447
+ ...(templateStart ? [
2448
+ "Use --stop-at-script --json to save the server-issued approval, original source and template choices as a JSON file.",
2449
+ "Edit only a separate script file, then repeat --conceit and --style with --resume-script <saved-stop-response.json> --script <edited.txt>, without --stop-at-script.",
2450
+ ] : [
2451
+ "To start it, save it to a file and run the same command with --script <that file> and without --stop-at-script.",
2452
+ ]),
1912
2453
  ],
1913
2454
  };
1914
2455
  }
@@ -1946,6 +2487,391 @@ function waitJsonWith(waited, facts) {
1946
2487
  lines: [JSON.stringify({ ...parsed, ...facts })],
1947
2488
  };
1948
2489
  }
2490
+ function scriptElementsOf(value) {
2491
+ if (!Array.isArray(value))
2492
+ return null;
2493
+ const elements = [];
2494
+ for (const row of value) {
2495
+ if (!isRecord(row) || Object.keys(row).some((key) => key !== "handle" && key !== "elementId")
2496
+ || typeof row.handle !== "string" || row.handle.trim() === ""
2497
+ || typeof row.elementId !== "string" || row.elementId.trim() === "")
2498
+ return null;
2499
+ elements.push({ handle: row.handle, elementId: row.elementId });
2500
+ }
2501
+ return elements;
2502
+ }
2503
+ function scriptVoicesOf(value) {
2504
+ if (!isRecord(value))
2505
+ return null;
2506
+ const entries = [];
2507
+ for (const [who, choice] of Object.entries(value)) {
2508
+ if (choice === null) {
2509
+ entries.push([who, null]);
2510
+ continue;
2511
+ }
2512
+ const voiceId = typeof choice === "string" ? choice : isRecord(choice) ? choice.voiceId : undefined;
2513
+ if (typeof voiceId !== "string" || voiceId.trim() === "" || /\s/.test(voiceId.trim()))
2514
+ return null;
2515
+ entries.push([who, typeof choice === "string" ? choice : {
2516
+ voiceId,
2517
+ ...(isRecord(choice) && typeof choice.label === "string" ? { label: choice.label } : {}),
2518
+ }]);
2519
+ }
2520
+ return Object.fromEntries(entries);
2521
+ }
2522
+ function sameScriptSelections(left, right) {
2523
+ const facts = [left, right].map((selection) => ({
2524
+ elements: [...(selection.elements ?? [])].sort((a, b) => a.handle.localeCompare(b.handle)),
2525
+ voices: Object.entries(selection.voices ?? {})
2526
+ .map(([who, choice]) => {
2527
+ const voiceId = typeof choice === "string" ? choice : choice?.voiceId;
2528
+ const label = typeof choice === "object" && choice !== null ? choice.label?.trim() : undefined;
2529
+ return {
2530
+ who: who.trim(),
2531
+ choice: voiceId === undefined ? null : {
2532
+ voiceId: voiceId.trim(), ...(label ? { label } : {}),
2533
+ },
2534
+ };
2535
+ })
2536
+ .sort((a, b) => a.who.localeCompare(b.who)),
2537
+ }));
2538
+ return JSON.stringify(facts[0]) === JSON.stringify(facts[1]);
2539
+ }
2540
+ function scriptTemplateBriefOf(value) {
2541
+ if (!isRecord(value) || Object.keys(value).some((key) => key !== "cards" && key !== "settings"))
2542
+ return null;
2543
+ if (value.cards !== undefined
2544
+ && (!isRecord(value.cards) || !Object.values(value.cards).every((card) => typeof card === "string")))
2545
+ return null;
2546
+ if (value.settings !== undefined
2547
+ && (!isRecord(value.settings) || !Object.values(value.settings).every((setting) => typeof setting === "string" || typeof setting === "boolean"
2548
+ || (typeof setting === "number" && Number.isFinite(setting)))))
2549
+ return null;
2550
+ return value;
2551
+ }
2552
+ function withoutBlankTemplatePins(pins) {
2553
+ if (pins === undefined)
2554
+ return undefined;
2555
+ let result = pins;
2556
+ for (const [key, value] of Object.entries(pins)) {
2557
+ if (typeof value !== "string" || value.trim() !== "")
2558
+ continue;
2559
+ if (result === pins)
2560
+ result = { ...pins };
2561
+ delete result[key];
2562
+ }
2563
+ return Object.keys(result).length ? result : undefined;
2564
+ }
2565
+ function templateIntentOf(value) {
2566
+ if (!isRecord(value) || Object.keys(value).some((key) => !["mode", "structureKey", "referenceKey", "input"].includes(key))
2567
+ || (value.mode !== "auto" && value.mode !== "manual" && value.mode !== "hybrid"))
2568
+ return null;
2569
+ for (const field of ["structureKey", "referenceKey"]) {
2570
+ if (value[field] !== undefined && (typeof value[field] !== "string" || value[field].trim() === ""))
2571
+ return null;
2572
+ }
2573
+ const input = value.input;
2574
+ if (!isRecord(input) || Object.keys(input).some((key) => !["kind", "subject", "originalText", "adaptationIntent"].includes(key))
2575
+ || (input.kind !== "brief" && input.kind !== "adapt")
2576
+ || typeof input.originalText !== "string" || input.originalText.trim() === "")
2577
+ return null;
2578
+ if (input.subject !== undefined && input.subject !== "product" && input.subject !== "service" && input.subject !== "non-product")
2579
+ return null;
2580
+ if (input.kind === "adapt"
2581
+ ? typeof input.adaptationIntent !== "string" || input.adaptationIntent.trim() === ""
2582
+ : input.adaptationIntent !== undefined)
2583
+ return null;
2584
+ return {
2585
+ mode: value.mode,
2586
+ ...(value.structureKey !== undefined ? { structureKey: value.structureKey } : {}),
2587
+ ...(value.referenceKey !== undefined ? { referenceKey: value.referenceKey } : {}),
2588
+ input: {
2589
+ kind: input.kind, originalText: input.originalText,
2590
+ ...(input.subject !== undefined ? { subject: input.subject } : {}),
2591
+ ...(input.kind === "adapt" ? { adaptationIntent: input.adaptationIntent } : {}),
2592
+ },
2593
+ };
2594
+ }
2595
+ function sameTemplateBrief(left, right) {
2596
+ for (const field of ["cards", "settings"]) {
2597
+ const a = left?.[field] ?? {};
2598
+ const b = right?.[field] ?? {};
2599
+ if (Object.keys(a).length !== Object.keys(b).length
2600
+ || Object.entries(a).some(([key, value]) => !Object.hasOwn(b, key) || b[key] !== value))
2601
+ return false;
2602
+ }
2603
+ return true;
2604
+ }
2605
+ function sameJsonValue(left, right) {
2606
+ if (left === right)
2607
+ return true;
2608
+ if (Array.isArray(left) && Array.isArray(right)) {
2609
+ return left.length === right.length && left.every((value, index) => sameJsonValue(value, right[index]));
2610
+ }
2611
+ if (!isRecord(left) || !isRecord(right))
2612
+ return false;
2613
+ return Object.keys(left).length === Object.keys(right).length
2614
+ && Object.entries(left).every(([key, value]) => Object.hasOwn(right, key) && sameJsonValue(value, right[key]));
2615
+ }
2616
+ function preparationQuoteOf(value) {
2617
+ if (!isRecord(value) || typeof value.quoteId !== "string" || !value.quoteId.trim()
2618
+ || (value.phase !== "script" && value.phase !== "storyboard")
2619
+ || typeof value.contextHash !== "string" || !value.contextHash.trim()
2620
+ || typeof value.expiresAt !== "number" || !Number.isFinite(new Date(value.expiresAt).getTime())
2621
+ || (value.estimatedUsd !== null && (typeof value.estimatedUsd !== "number" || !Number.isFinite(value.estimatedUsd) || value.estimatedUsd < 0))
2622
+ || typeof value.maximumUsd !== "number" || !Number.isFinite(value.maximumUsd) || value.maximumUsd <= 0
2623
+ || typeof value.scope !== "string" || !value.scope.trim())
2624
+ return null;
2625
+ return {
2626
+ quoteId: value.quoteId, phase: value.phase, contextHash: value.contextHash, expiresAt: value.expiresAt,
2627
+ estimatedUsd: value.estimatedUsd, maximumUsd: value.maximumUsd, scope: value.scope,
2628
+ };
2629
+ }
2630
+ function preparationInputOf(body, phase) {
2631
+ const input = {};
2632
+ for (const field of [
2633
+ "script", "conceit", "style", "templateBrief", "productId", "elements", "voiceMode", "voicePath",
2634
+ "videoModel", "scriptApproval", "approvedSource", "adaptationPlan", "direction", "templateIntent",
2635
+ "music", "shots", "songControls", "mechanismPlan",
2636
+ ]) {
2637
+ if (body[field] !== undefined)
2638
+ input[field] = body[field];
2639
+ }
2640
+ if (body.voices !== undefined) {
2641
+ input.voices = Object.entries(body.voices).map(([who, choice]) => {
2642
+ const voiceId = typeof choice === "string" ? choice.trim() : choice?.voiceId.trim();
2643
+ const label = typeof choice === "object" && choice !== null ? choice.label?.trim() : undefined;
2644
+ return {
2645
+ who: who.trim(),
2646
+ choice: voiceId === undefined ? { kind: "clear" } : {
2647
+ kind: "pin", voiceId, ...(label ? { label } : {}),
2648
+ },
2649
+ };
2650
+ });
2651
+ }
2652
+ if (phase === "script") {
2653
+ input.operation = body.rewriteToFit === true ? "rewrite" : body.describe === true ? "write" : "reapprove";
2654
+ if (body.describe !== undefined)
2655
+ input.describe = body.describe;
2656
+ }
2657
+ else {
2658
+ for (const field of ["reviewStoryboard", "director", "broll", "sourceRecord"]) {
2659
+ if (body[field] !== undefined)
2660
+ input[field] = body[field];
2661
+ }
2662
+ input.launchedVia = "cli";
2663
+ }
2664
+ return input;
2665
+ }
2666
+ async function templateResolutionFlow(template, templateIntent, templateBrief, route, deps) {
2667
+ const query = new URLSearchParams({ door: "template", template, templateIntent: JSON.stringify(templateIntent) });
2668
+ if (templateBrief !== undefined)
2669
+ query.set("templateBrief", JSON.stringify(templateBrief));
2670
+ for (const field of ["voiceMode", "voicePath", "videoModel"]) {
2671
+ const value = route[field];
2672
+ if (value !== undefined)
2673
+ query.set(field, value);
2674
+ }
2675
+ const response = await deps.get(`${SCRIPT_RUNS_PATH}?${query}`).catch(() => null);
2676
+ const refused = (line) => ({ kind: "result", result: adminOnlyResult(line, route.json) });
2677
+ if (!response)
2678
+ return refused("Current template input options could not be read. No paid preparation was requested.");
2679
+ if (!response.ok)
2680
+ return { kind: "result", result: errorResult(response, route.json) };
2681
+ const options = isRecord(response.data) ? response.data.inputOptions : undefined;
2682
+ if (!isRecord(options))
2683
+ return refused("The server did not return selected template input options. No paid preparation was requested.");
2684
+ if (route.songControls !== undefined) {
2685
+ const rows = isRecord(response.data) && Array.isArray(response.data.templates) ? response.data.templates : [];
2686
+ const selected = rows.find((row) => isRecord(row) && row.key === template);
2687
+ const capabilities = isRecord(selected) && isRecord(selected.templateCapabilities) ? selected.templateCapabilities : undefined;
2688
+ if (capabilities?.songControls !== true) {
2689
+ return refused("The server does not advertise Song controls for this template. Your pins were not discarded. Remove them explicitly with --song-controls '{}' or select a supported template and request fresh review. No paid preparation was requested.");
2690
+ }
2691
+ }
2692
+ if (options.intentResolution === undefined)
2693
+ return { kind: "resolution" };
2694
+ const raw = options.intentResolution;
2695
+ const intent = isRecord(raw) ? templateIntentOf(raw.intent) : null;
2696
+ if (!isRecord(raw) || !intent || !sameJsonValue(intent, templateIntent) || typeof raw.ok !== "boolean"
2697
+ || !isRecord(raw.effectiveBrief) || !isRecord(raw.provenance) || !Array.isArray(raw.holds)) {
2698
+ return refused("The server returned unreadable or stale template input resolution. No paid preparation was requested.");
2699
+ }
2700
+ const holds = [];
2701
+ for (const hold of raw.holds) {
2702
+ if (!isRecord(hold) || typeof hold.code !== "string" || typeof hold.field !== "string" || typeof hold.message !== "string") {
2703
+ return refused("The server returned unreadable template input holds. No paid preparation was requested.");
2704
+ }
2705
+ holds.push({ code: hold.code, field: hold.field, message: hold.message });
2706
+ }
2707
+ const value = {
2708
+ ok: raw.ok, intent, effectiveBrief: raw.effectiveBrief, provenance: raw.provenance, holds,
2709
+ ...(raw.structure !== undefined ? { structure: raw.structure } : {}),
2710
+ ...(raw.reference !== undefined ? { reference: raw.reference } : {}),
2711
+ ...(raw.capabilities !== undefined ? { capabilities: raw.capabilities } : {}),
2712
+ };
2713
+ if (!raw.ok || holds.length > 0) {
2714
+ const error = holds.length ? holds.map(({ field, message }) => `${field}: ${message}`).join("\n") : "The current template input is held.";
2715
+ return {
2716
+ kind: "result",
2717
+ result: { code: 1, lines: route.json ? [JSON.stringify({ ok: false, error, intentResolution: value })] : [error, "No paid preparation was requested."] },
2718
+ };
2719
+ }
2720
+ return { kind: "resolution", value };
2721
+ }
2722
+ async function preparationFlow(phase, input, opts, deps, intentResolution, reviewedControls) {
2723
+ const result = (line) => ({ kind: "result", result: adminOnlyResult(line, opts.json) });
2724
+ let saved;
2725
+ if (opts.authorizePreparationFile !== undefined) {
2726
+ try {
2727
+ const value = JSON.parse(deps.readFile(opts.authorizePreparationFile));
2728
+ const quote = isRecord(value) ? preparationQuoteOf(value.preparationQuote) : null;
2729
+ if (!isRecord(value) || !quote || typeof value.requestId !== "string" || !value.requestId.trim()
2730
+ || !isRecord(value.input))
2731
+ throw new Error("expected an unchanged --quote-preparation --json response");
2732
+ saved = { preparationQuote: quote, requestId: value.requestId, input: value.input };
2733
+ }
2734
+ catch (error) {
2735
+ return result(`Can't read --authorize-preparation: ${error instanceof Error ? error.message : String(error)}. No paid preparation was requested.`);
2736
+ }
2737
+ if (saved.preparationQuote.phase !== phase) {
2738
+ return result("The saved preparation quote belongs to a different phase or input. Review a new quote for this exact draft; an old quote cannot authorize changed text or context. No paid preparation was requested.");
2739
+ }
2740
+ }
2741
+ else if (!opts.quotePreparation) {
2742
+ return result("Template preparation requires a reviewed phase quote. Repeat this command with --quote-preparation --json, save and review the response, then explicitly accept it with --authorize-preparation <saved-quote.json>. Input mode never approves spending. No paid preparation was requested.");
2743
+ }
2744
+ const requestId = saved?.requestId ?? randomUUID();
2745
+ const response = await deps.post("/api/v2/video/template-preparation", { phase, requestId, input }).catch(() => null);
2746
+ if (!response)
2747
+ return result("The preparation quote could not be read. Keep the same saved quote for recovery; no paid preparation was requested.");
2748
+ if (!response.ok && response.status === 404)
2749
+ return result("The preparation quote endpoint is unavailable for this key or server. No paid preparation was requested.");
2750
+ if (!response.ok)
2751
+ return { kind: "result", result: errorResult(response, opts.json) };
2752
+ const quote = preparationQuoteOf(response.data);
2753
+ if (!quote || quote.phase !== phase)
2754
+ return result("This server did not return a usable quote for the requested phase. No paid preparation was requested.");
2755
+ const canonicalInput = isRecord(response.data) && isRecord(response.data.canonicalInput) ? response.data.canonicalInput : null;
2756
+ if (!canonicalInput || canonicalInput.script !== input.script
2757
+ || !sameJsonValue(canonicalInput.templateIntent, input.templateIntent)
2758
+ || !sameJsonValue(canonicalInput.approvedSource, input.approvedSource)
2759
+ || canonicalInput.operation !== input.operation || canonicalInput.describe !== input.describe
2760
+ || (canonicalInput.songControls !== undefined && !isRecord(canonicalInput.songControls))
2761
+ || (canonicalInput.mechanismPlan !== undefined && !isRecord(canonicalInput.mechanismPlan))) {
2762
+ return result("The server did not return canonical preparation input for the same exact source and operation. No paid preparation was requested.");
2763
+ }
2764
+ if (reviewedControls && (!sameJsonValue(canonicalInput.songControls, reviewedControls.songControls)
2765
+ || !sameJsonValue(canonicalInput.mechanismPlan, reviewedControls.mechanismPlan))) {
2766
+ return result("The script or template context changed after review. Resume with --stop-at-script --json to review the current controls before starting. No paid preparation was requested.");
2767
+ }
2768
+ if (saved) {
2769
+ if (!sameJsonValue(quote, saved.preparationQuote)) {
2770
+ return result("The server returned different preparation authority. The saved approval was not replayed and the new quote was not accepted. Review current authority explicitly; no paid preparation was requested.");
2771
+ }
2772
+ if (!sameJsonValue(canonicalInput, saved.input)) {
2773
+ return result("The saved preparation quote belongs to a different phase or input. Review a new quote for this exact draft; an old quote cannot authorize changed text or context. No paid preparation was requested.");
2774
+ }
2775
+ return { kind: "authorized", authorization: { quoteId: quote.quoteId, maximumUsd: saved.preparationQuote.maximumUsd }, canonicalInput };
2776
+ }
2777
+ const envelope = { preparationQuote: quote, requestId, input: canonicalInput, ...(intentResolution ? { intentResolution } : {}) };
2778
+ return {
2779
+ kind: "result",
2780
+ result: {
2781
+ code: 0,
2782
+ lines: opts.json ? [JSON.stringify(envelope)] : [
2783
+ `${phase === "script" ? "Script" : "Storyboard"} preparation quote (no paid preparation requested)`,
2784
+ quote.estimatedUsd === null
2785
+ ? "Actual cost unknown; only the maximum allowance is available."
2786
+ : `Approximate estimate: $${quote.estimatedUsd}`,
2787
+ `Maximum for this phase: $${quote.maximumUsd}`,
2788
+ `Scope: ${quote.scope}`,
2789
+ `Expires: ${new Date(quote.expiresAt).toISOString()}`,
2790
+ ...(intentResolution ? [
2791
+ "Effective creative brief and provenance (server):",
2792
+ JSON.stringify({ effectiveBrief: intentResolution.effectiveBrief, provenance: intentResolution.provenance }, null, 2),
2793
+ ] : ["This server did not publish resolved-choice provenance for this draft."]),
2794
+ "This is not a whole-video price or approval.",
2795
+ "Save this command's --quote-preparation --json response. After reviewing it, repeat the exact draft with --authorize-preparation <saved-quote.json> instead of --quote-preparation.",
2796
+ ],
2797
+ },
2798
+ };
2799
+ }
2800
+ function scriptJsonObjectInput(input, deps) {
2801
+ const raw = input.trim();
2802
+ const value = JSON.parse(raw.startsWith("@") ? deps.readFile(raw.slice(1)) : raw);
2803
+ if (!isRecord(value))
2804
+ throw new Error("expected a JSON object");
2805
+ return value;
2806
+ }
2807
+ function scriptResumeOf(value) {
2808
+ if (!isRecord(value) || value.stoppedAtScript !== true
2809
+ || typeof value.script !== "string" || value.script.trim() === "")
2810
+ return null;
2811
+ if (typeof value.scriptApproval !== "string" || value.scriptApproval.trim() === "")
2812
+ return null;
2813
+ const source = value.approvedSource;
2814
+ if (!isRecord(source) || Object.keys(source).some((key) => key !== "mode" && key !== "text")
2815
+ || (source.mode !== "verbatim" && source.mode !== "description")
2816
+ || typeof source.text !== "string" || source.text.trim() === "")
2817
+ return null;
2818
+ const brief = value.templateBrief === undefined ? undefined : scriptTemplateBriefOf(value.templateBrief);
2819
+ if (brief === null)
2820
+ return null;
2821
+ const templateIntent = value.templateIntent === undefined ? undefined : templateIntentOf(value.templateIntent);
2822
+ if (templateIntent === null)
2823
+ return null;
2824
+ if (templateIntent && value.direction !== undefined && typeof value.direction !== "string")
2825
+ return null;
2826
+ if (templateIntent) {
2827
+ if (value.music !== undefined && typeof value.music !== "boolean")
2828
+ return null;
2829
+ if (value.shots !== undefined && (!isRecord(value.shots)
2830
+ || Object.keys(value.shots).some((key) => key !== "frame" && key !== "pacing")
2831
+ || !Object.values(value.shots).every((field) => typeof field === "string")))
2832
+ return null;
2833
+ if (value.songControls !== undefined && !isRecord(value.songControls))
2834
+ return null;
2835
+ if (value.mechanismPlan !== undefined && !isRecord(value.mechanismPlan))
2836
+ return null;
2837
+ }
2838
+ if (value.productId !== undefined
2839
+ && (typeof value.productId !== "string" || value.productId.trim() === ""))
2840
+ return null;
2841
+ if (value.voiceMode !== undefined
2842
+ && (typeof value.voiceMode !== "string" || !isVoiceMode(value.voiceMode)))
2843
+ return null;
2844
+ if (value.voicePath !== undefined
2845
+ && (typeof value.voicePath !== "string" || value.voicePath.trim() === ""))
2846
+ return null;
2847
+ if (value.videoModel !== undefined
2848
+ && (typeof value.videoModel !== "string" || value.videoModel.trim() === ""))
2849
+ return null;
2850
+ const elements = value.elements === undefined ? undefined : scriptElementsOf(value.elements);
2851
+ const voices = value.voices === undefined ? undefined : scriptVoicesOf(value.voices);
2852
+ if (elements === null || voices === null)
2853
+ return null;
2854
+ return {
2855
+ reviewedScript: value.script,
2856
+ ...(templateIntent !== undefined ? { templateIntent } : {}),
2857
+ ...(templateIntent && typeof value.direction === "string" ? { direction: value.direction } : {}),
2858
+ ...(templateIntent && value.music !== undefined ? { music: value.music } : {}),
2859
+ ...(templateIntent && value.shots !== undefined ? { shots: value.shots } : {}),
2860
+ ...(templateIntent && value.songControls !== undefined ? { songControls: value.songControls } : {}),
2861
+ ...(templateIntent && value.mechanismPlan !== undefined ? { mechanismPlan: value.mechanismPlan } : {}),
2862
+ ...(templateIntent && value.sourceRecord !== undefined ? { sourceRecord: value.sourceRecord } : {}),
2863
+ ...(templateIntent && value.adaptationPlan !== undefined ? { adaptationPlan: value.adaptationPlan } : {}),
2864
+ scriptApproval: value.scriptApproval,
2865
+ approvedSource: { mode: source.mode, text: source.text },
2866
+ ...(brief !== undefined ? { templateBrief: brief } : {}),
2867
+ ...(value.productId !== undefined ? { productId: value.productId } : {}),
2868
+ ...(value.voiceMode !== undefined ? { voiceMode: value.voiceMode } : {}),
2869
+ ...(value.voicePath !== undefined ? { voicePath: value.voicePath } : {}),
2870
+ ...(value.videoModel !== undefined ? { videoModel: value.videoModel } : {}),
2871
+ ...(elements !== undefined ? { elements } : {}),
2872
+ ...(voices !== undefined ? { voices } : {}),
2873
+ };
2874
+ }
1949
2875
  export async function startScriptFlow(opts, deps) {
1950
2876
  let script;
1951
2877
  try {
@@ -1962,7 +2888,127 @@ export async function startScriptFlow(opts, deps) {
1962
2888
  if (script.trim().length === 0) {
1963
2889
  return { code: 1, lines: [`The script file "${opts.scriptFile}" is empty.`] };
1964
2890
  }
1965
- let sourceRecord;
2891
+ if (opts.writerBrief)
2892
+ script = composeTemplateBrief({ ...opts.writerBrief, about: script });
2893
+ let resume;
2894
+ if (opts.resumeScriptFile) {
2895
+ let saved;
2896
+ try {
2897
+ saved = JSON.parse(deps.readFile(opts.resumeScriptFile));
2898
+ }
2899
+ catch (error) {
2900
+ return { code: 1, lines: [`Can't read the saved script response "${opts.resumeScriptFile}" as JSON: ${String(error)}`] };
2901
+ }
2902
+ const parsed = scriptResumeOf(saved);
2903
+ if (!parsed) {
2904
+ return {
2905
+ code: 1,
2906
+ lines: ["--resume-script needs a saved stoppedAtScript:true response with a nonempty script and server-issued scriptApproval, approvedSource { mode: \"verbatim\" | \"description\", text }, and valid templateBrief/productId/voiceMode/voicePath/videoModel/elements/voices if supplied. Write and explicitly approve a fresh script with --stop-at-script --json before resuming."],
2907
+ };
2908
+ }
2909
+ resume = parsed;
2910
+ }
2911
+ if (resume && opts.productId !== undefined && opts.productId !== resume.productId) {
2912
+ return {
2913
+ code: 1,
2914
+ lines: ["The selected product differs from the saved script's approved product. Write and explicitly approve a fresh script for that product with --stop-at-script --json, without --resume-script. Nothing has started."],
2915
+ };
2916
+ }
2917
+ const hasIntentInputs = opts.inputMode !== undefined || opts.structure !== undefined || opts.reference !== undefined
2918
+ || opts.subject !== undefined || opts.adaptationIntent !== undefined || opts.describe === true || opts.keepOriginal === true
2919
+ || opts.templateBriefInput !== undefined || opts.songControlsInput !== undefined || opts.mechanismPlanInput !== undefined;
2920
+ const hasPreparationConsent = opts.quotePreparation === true || opts.authorizePreparationFile !== undefined;
2921
+ if (resume && resume.templateIntent === undefined && hasIntentInputs) {
2922
+ return adminOnlyResult("This saved review has no V2 original-input context. Start a fresh --describe or --adapt review using the original source file, without --resume-script. Nothing has started.", opts.json);
2923
+ }
2924
+ const templateIntent = resume?.templateIntent || hasIntentInputs
2925
+ ? {
2926
+ mode: opts.inputMode === "automatic" ? "auto" : opts.inputMode ?? resume?.templateIntent?.mode ?? "auto",
2927
+ ...(opts.structure !== undefined || resume?.templateIntent?.structureKey !== undefined
2928
+ ? { structureKey: opts.structure ?? resume?.templateIntent?.structureKey } : {}),
2929
+ ...(opts.reference !== undefined || resume?.templateIntent?.referenceKey !== undefined
2930
+ ? { referenceKey: opts.reference ?? resume?.templateIntent?.referenceKey } : {}),
2931
+ input: {
2932
+ ...(resume?.templateIntent?.input ?? {
2933
+ kind: opts.adaptationIntent !== undefined ? "adapt" : "brief",
2934
+ originalText: script,
2935
+ ...(opts.adaptationIntent !== undefined ? { adaptationIntent: opts.adaptationIntent } : {}),
2936
+ }),
2937
+ ...(opts.subject !== undefined ? { subject: opts.subject } : {}),
2938
+ },
2939
+ }
2940
+ : undefined;
2941
+ let stopAtScript = opts.stopAtScript === true || opts.keepOriginal === true
2942
+ || (templateIntent !== undefined && (resume === undefined || opts.rewriteToFit === true));
2943
+ if (templateIntent && opts.rewriteToFit && resume === undefined) {
2944
+ return adminOnlyResult("A V2 rewrite needs a previously reviewed --resume-script response. For an initial adaptation, use --adapt <intent>; write and review before rewriting. Nothing has started.", opts.json);
2945
+ }
2946
+ if (opts.keepOriginal && script !== templateIntent?.input.originalText) {
2947
+ return adminOnlyResult("--keep-original requires --script to contain the exact original text, not an edited result. Nothing has started.", opts.json);
2948
+ }
2949
+ if (templateIntent && opts.reviewStoryboard !== true) {
2950
+ return adminOnlyResult("V2 template inputs require storyboard review; do not combine them with --one-shot. Nothing has started.", opts.json);
2951
+ }
2952
+ if (templateIntent && resume === undefined && !opts.describe && opts.adaptationIntent === undefined) {
2953
+ return adminOnlyResult("Choose an explicit initial V2 script path: --describe to write from a brief, --adapt <intent> to adapt copy, or --adapt <intent> --keep-original for guarded unchanged review. Input mode alone never rewrites text. No paid preparation was requested.", opts.json);
2954
+ }
2955
+ const music = opts.music ?? (templateIntent ? resume?.music : undefined);
2956
+ const shots = templateIntent && (resume?.shots || opts.shots)
2957
+ ? { ...resume?.shots, ...opts.shots }
2958
+ : opts.shots;
2959
+ let songControls = templateIntent ? resume?.songControls : undefined;
2960
+ let mechanismPlan = templateIntent ? resume?.mechanismPlan : undefined;
2961
+ try {
2962
+ if (opts.songControlsInput !== undefined)
2963
+ songControls = withoutBlankTemplatePins(scriptJsonObjectInput(opts.songControlsInput, deps));
2964
+ if (opts.mechanismPlanInput !== undefined)
2965
+ mechanismPlan = scriptJsonObjectInput(opts.mechanismPlanInput, deps);
2966
+ }
2967
+ catch (error) {
2968
+ return adminOnlyResult(`Can't read template sound/story controls: ${error instanceof Error ? error.message : String(error)}`, opts.json);
2969
+ }
2970
+ let suppliedBrief;
2971
+ if (opts.templateBriefInput !== undefined) {
2972
+ try {
2973
+ const raw = opts.templateBriefInput.trim();
2974
+ const parsed = scriptTemplateBriefOf(JSON.parse(raw.startsWith("@") ? deps.readFile(raw.slice(1)) : raw));
2975
+ if (parsed === null)
2976
+ throw new Error("expected { cards?: { layer: card }, settings?: { name: primitive } }");
2977
+ suppliedBrief = parsed;
2978
+ }
2979
+ catch (error) {
2980
+ return adminOnlyResult(`Can't read --template-brief: ${error instanceof Error ? error.message : String(error)}`, opts.json);
2981
+ }
2982
+ }
2983
+ let elements = resume?.elements;
2984
+ let selectedVoices = resume?.voices;
2985
+ try {
2986
+ if (opts.elementsInput !== undefined) {
2987
+ let text = opts.elementsInput.trim();
2988
+ if (text.startsWith("@"))
2989
+ text = deps.readFile(text.slice(1));
2990
+ const parsed = scriptElementsOf(JSON.parse(text));
2991
+ if (parsed === null)
2992
+ throw new Error("--elements must be an array of { handle, elementId } with nonempty strings.");
2993
+ elements = parsed;
2994
+ }
2995
+ if (opts.voicesInput !== undefined) {
2996
+ const parsed = scriptVoicesOf(parseVoicesFlag([{ flag: "voices", value: opts.voicesInput }], deps.readFile));
2997
+ if (parsed === null)
2998
+ throw new Error("--voices must map script speaker names to a nonempty voice ID without spaces, { voiceId, label? }, or null.");
2999
+ selectedVoices = parsed;
3000
+ }
3001
+ }
3002
+ catch (error) {
3003
+ return { code: 1, lines: [`Can't read template selections: ${error instanceof Error ? error.message : String(error)}`] };
3004
+ }
3005
+ if (resume && !opts.stopAtScript && !sameScriptSelections(resume, { elements, voices: selectedVoices })) {
3006
+ return {
3007
+ code: 1,
3008
+ lines: ["The selected references or voices differ from the saved script's approved selections. Keep your original description and edited script files. Use --stop-at-script --json with --resume-script to explicitly check and approve the edited script with these selections, then resume the returned approval response to start. Nothing has started."],
3009
+ };
3010
+ }
3011
+ let sourceRecord = templateIntent ? resume?.sourceRecord : undefined;
1966
3012
  if (opts.sourceRecordFile) {
1967
3013
  try {
1968
3014
  sourceRecord = JSON.parse(deps.readFile(opts.sourceRecordFile));
@@ -1976,7 +3022,7 @@ export async function startScriptFlow(opts, deps) {
1976
3022
  };
1977
3023
  }
1978
3024
  }
1979
- let adaptationPlan;
3025
+ let adaptationPlan = templateIntent ? resume?.adaptationPlan : undefined;
1980
3026
  if (opts.adaptationPlanFile) {
1981
3027
  try {
1982
3028
  adaptationPlan = opts.adaptationPlanFile === "original"
@@ -1987,39 +3033,173 @@ export async function startScriptFlow(opts, deps) {
1987
3033
  return { code: 1, lines: [`Can't read semantic adaptation JSON: ${String(error)}`] };
1988
3034
  }
1989
3035
  }
1990
- const listed = await deps.get(SCRIPT_RUNS_PATH).catch(() => null);
3036
+ let templateStart = resume !== undefined || opts.requestedSeconds !== undefined
3037
+ || opts.picturesPerScene !== undefined || opts.productId !== undefined
3038
+ || opts.elementsInput !== undefined || opts.voicesInput !== undefined || templateIntent !== undefined || hasPreparationConsent;
3039
+ const templateMenuPath = `${SCRIPT_RUNS_PATH}?door=template`;
3040
+ let templateDefaultStyle;
3041
+ const listed = await deps.get(templateStart ? templateMenuPath : SCRIPT_RUNS_PATH).catch(() => null);
3042
+ if (templateStart && !listed?.ok) {
3043
+ return listed
3044
+ ? errorResult(listed, opts.json)
3045
+ : adminOnlyResult("Template preflight could not be read. Nothing has started.", opts.json);
3046
+ }
1991
3047
  if (listed?.ok) {
1992
- const options = scriptRunOptionsOf(listed.data);
3048
+ let options = scriptRunOptionsOf(listed.data, templateStart ? "template" : "script");
1993
3049
  if (!options) {
1994
- return adminOnlyResult("The server's list of kinds and looks could not be read.", opts.json);
3050
+ return adminOnlyResult(templateStart
3051
+ ? "This server did not publish a readable template menu. Nothing has started."
3052
+ : "The server's list of kinds and looks could not be read.", opts.json);
3053
+ }
3054
+ if (!templateStart && !options.conceits.some((row) => row.key === opts.conceit)) {
3055
+ const templates = await deps.get(templateMenuPath).catch(() => null);
3056
+ const offered = templates?.ok ? scriptRunOptionsOf(templates.data, "template") : null;
3057
+ if (offered?.conceits.some((row) => row.key === opts.conceit)) {
3058
+ options = offered;
3059
+ templateStart = true;
3060
+ }
1995
3061
  }
1996
3062
  const problem = scriptRunPickProblem(options, opts.conceit, opts.style);
3063
+ if (opts.writerBrief && !options.conceits.some((row) => row.key === opts.conceit)) {
3064
+ const line = `${TEMPLATE_WRITER_BRIEF_USAGE} ${problem}`;
3065
+ return opts.json ? adminOnlyResult(line, true) : { code: 1, usage: true, lines: [line] };
3066
+ }
1997
3067
  if (problem) {
1998
3068
  return opts.json ? adminOnlyResult(problem, true) : { code: 1, lines: [problem], usage: true };
1999
3069
  }
3070
+ if (templateStart) {
3071
+ templateDefaultStyle = options.conceits.find((row) => row.key === opts.conceit)?.style?.slug;
3072
+ }
2000
3073
  }
2001
- const res = await deps.post(SCRIPT_RUNS_PATH, {
3074
+ if (templateStart) {
3075
+ if (opts.reviewStoryboard !== true) {
3076
+ return adminOnlyResult("Template preparation requires storyboard review; do not combine it with --one-shot. Nothing has started.", opts.json);
3077
+ }
3078
+ if (opts.rewriteToFit && resume === undefined) {
3079
+ return adminOnlyResult("A template rewrite needs a previously reviewed --resume-script response. Review the initial script before quoting a rewrite. Nothing has started.", opts.json);
3080
+ }
3081
+ stopAtScript ||= resume === undefined || opts.rewriteToFit === true;
3082
+ }
3083
+ let baseBrief = suppliedBrief === undefined ? resume?.templateBrief : {
3084
+ ...resume?.templateBrief,
3085
+ ...(suppliedBrief.cards !== undefined ? { cards: { ...resume?.templateBrief?.cards, ...suppliedBrief.cards } } : {}),
3086
+ ...(suppliedBrief.settings !== undefined ? { settings: { ...resume?.templateBrief?.settings, ...suppliedBrief.settings } } : {}),
3087
+ };
3088
+ if (templateIntent && baseBrief) {
3089
+ const cards = withoutBlankTemplatePins(baseBrief.cards);
3090
+ const settings = withoutBlankTemplatePins(baseBrief.settings);
3091
+ if (cards !== baseBrief.cards || settings !== baseBrief.settings) {
3092
+ baseBrief = { ...(cards !== undefined ? { cards } : {}), ...(settings !== undefined ? { settings } : {}) };
3093
+ }
3094
+ }
3095
+ const hasBriefOverrides = opts.requestedSeconds !== undefined || opts.picturesPerScene !== undefined;
3096
+ let templateBrief = hasBriefOverrides
3097
+ ? {
3098
+ ...baseBrief,
3099
+ settings: {
3100
+ ...baseBrief?.settings,
3101
+ ...(opts.requestedSeconds !== undefined ? { planningSeconds: opts.requestedSeconds } : {}),
3102
+ ...(opts.picturesPerScene !== undefined ? { sceneFrameCandidates: opts.picturesPerScene } : {}),
3103
+ },
3104
+ }
3105
+ : baseBrief;
3106
+ if (templateIntent && (opts.style !== templateDefaultStyle || templateBrief?.cards?.style !== undefined)) {
3107
+ templateBrief = { ...templateBrief, cards: { ...templateBrief?.cards, style: opts.style } };
3108
+ }
3109
+ else if (templateDefaultStyle !== undefined
3110
+ && (opts.style !== templateDefaultStyle || templateBrief?.cards?.style !== undefined)) {
3111
+ const cards = { ...templateBrief?.cards };
3112
+ delete cards.style;
3113
+ if (opts.style !== templateDefaultStyle)
3114
+ cards.style = opts.style;
3115
+ templateBrief = {
3116
+ ...(Object.keys(cards).length > 0 ? { cards } : {}),
3117
+ ...(templateBrief?.settings !== undefined ? { settings: templateBrief.settings } : {}),
3118
+ };
3119
+ if (Object.keys(templateBrief).length === 0)
3120
+ templateBrief = undefined;
3121
+ }
3122
+ const productId = opts.productId ?? resume?.productId;
3123
+ const videoModel = opts.videoModel ?? resume?.videoModel;
3124
+ const voices = {
3125
+ voiceMode: opts.voiceMode ?? resume?.voiceMode,
3126
+ voicePath: opts.voicePath ?? resume?.voicePath,
3127
+ };
3128
+ const direction = opts.direction ?? (templateIntent ? resume?.direction : undefined);
3129
+ if (resume?.templateIntent && !stopAtScript && (script !== resume.reviewedScript
3130
+ || !sameJsonValue(templateIntent, resume.templateIntent)
3131
+ || !sameTemplateBrief(templateBrief, resume.templateBrief)
3132
+ || videoModel !== resume.videoModel || voices.voiceMode !== resume.voiceMode || voices.voicePath !== resume.voicePath
3133
+ || direction !== resume.direction
3134
+ || music !== resume.music || !sameJsonValue(shots, resume.shots)
3135
+ || (!(opts.quotePreparation || opts.authorizePreparationFile)
3136
+ && (!sameJsonValue(songControls, resume.songControls) || !sameJsonValue(mechanismPlan, resume.mechanismPlan)))
3137
+ || !sameJsonValue(sourceRecord, resume.sourceRecord)
3138
+ || !sameJsonValue(adaptationPlan, resume.adaptationPlan))) {
3139
+ return adminOnlyResult("The script or template context changed after review. Keep the original source and edited script. Resume with --stop-at-script --json, review the exact returned text and context, then resume that new response without --stop-at-script. Nothing has started.", opts.json);
3140
+ }
3141
+ const selections = {
3142
+ ...(elements?.length ? { elements } : {}),
3143
+ ...(selectedVoices && Object.keys(selectedVoices).length ? { voices: selectedVoices } : {}),
3144
+ };
3145
+ const body = {
2002
3146
  script,
2003
3147
  conceit: opts.conceit,
2004
3148
  style: opts.style,
2005
- ...(opts.direction ? { direction: opts.direction } : {}),
2006
- ...(opts.voicePath ? { voicePath: opts.voicePath } : {}),
2007
- ...(opts.videoModel ? { videoModel: opts.videoModel } : {}),
2008
- ...(opts.voiceMode ? { voiceMode: opts.voiceMode } : {}),
2009
- ...(opts.music === true ? { music: true } : {}),
3149
+ ...(direction ? { direction } : {}),
3150
+ ...(voices.voicePath !== undefined ? { voicePath: voices.voicePath } : {}),
3151
+ ...(videoModel !== undefined ? { videoModel } : {}),
3152
+ ...(voices.voiceMode !== undefined ? { voiceMode: voices.voiceMode } : {}),
3153
+ ...(templateIntent ? (music !== undefined ? { music } : {}) : music === true ? { music: true } : {}),
2010
3154
  ...(opts.reviewStoryboard ? { reviewStoryboard: true } : {}),
2011
3155
  ...(opts.director ? { director: true } : {}),
2012
3156
  ...(opts.broll ? { broll: true } : {}),
2013
- ...(opts.shots ? { shots: opts.shots } : {}),
2014
- ...(opts.stopAtScript ? { stopAtScript: true } : {}),
3157
+ ...(shots ? { shots } : {}),
3158
+ ...(templateIntent && songControls !== undefined ? { songControls } : {}),
3159
+ ...(templateIntent && mechanismPlan !== undefined ? { mechanismPlan } : {}),
3160
+ ...(stopAtScript ? { stopAtScript: true } : {}),
2015
3161
  ...(opts.rewriteToFit ? { rewriteToFit: true } : {}),
2016
3162
  ...(sourceRecord !== undefined ? { sourceRecord } : {}),
2017
3163
  ...(adaptationPlan !== undefined ? { adaptationPlan } : {}),
2018
- });
3164
+ ...(resume ? { approvedSource: resume.approvedSource, scriptApproval: resume.scriptApproval } : {}),
3165
+ ...(templateIntent !== undefined ? { templateIntent } : {}),
3166
+ ...(templateIntent !== undefined && resume === undefined && !opts.keepOriginal
3167
+ && (opts.describe || opts.adaptationIntent !== undefined) ? { describe: true } : {}),
3168
+ ...(templateStart && templateBrief !== undefined ? { templateBrief } : {}),
3169
+ ...(templateStart && productId !== undefined ? { productId } : {}),
3170
+ ...selections,
3171
+ };
3172
+ let intentResolution;
3173
+ if (templateIntent) {
3174
+ const resolution = await templateResolutionFlow(opts.conceit, templateIntent, templateBrief, { ...voices, videoModel, json: opts.json, songControls }, deps);
3175
+ if (resolution.kind === "result")
3176
+ return resolution.result;
3177
+ intentResolution = resolution.value;
3178
+ }
3179
+ if (templateStart) {
3180
+ const preparation = await preparationFlow(stopAtScript ? "script" : "storyboard", preparationInputOf(body, stopAtScript ? "script" : "storyboard"), opts, deps, intentResolution, resume?.templateIntent && !stopAtScript ? resume : undefined);
3181
+ if (preparation.kind === "result")
3182
+ return preparation.result;
3183
+ body.preparationAuthorization = preparation.authorization;
3184
+ songControls = isRecord(preparation.canonicalInput.songControls) ? preparation.canonicalInput.songControls : undefined;
3185
+ mechanismPlan = isRecord(preparation.canonicalInput.mechanismPlan) ? preparation.canonicalInput.mechanismPlan : undefined;
3186
+ if (songControls === undefined)
3187
+ delete body.songControls;
3188
+ else
3189
+ body.songControls = songControls;
3190
+ if (mechanismPlan === undefined)
3191
+ delete body.mechanismPlan;
3192
+ else
3193
+ body.mechanismPlan = mechanismPlan;
3194
+ }
3195
+ const res = await deps.post(SCRIPT_RUNS_PATH, body);
2019
3196
  if (!res.ok)
2020
3197
  return scriptNeedsCallerResult(res, opts.json) ?? scriptStartRefused(res, opts.json);
2021
3198
  if (isRecord(res.data) && res.data.stoppedAtScript === true) {
2022
- return stoppedAtScriptResult(res.data, opts.json);
3199
+ return stoppedAtScriptResult(res.data, opts.json, templateStart || scriptResumeOf(res.data) !== null, voices, selections, templateIntent, { templateBrief, productId, videoModel, direction, music, shots, songControls, mechanismPlan, sourceRecord, adaptationPlan }, intentResolution);
3200
+ }
3201
+ if (templateStart && stopAtScript) {
3202
+ return adminOnlyResult("The server did not return the requested script-review stop. Do not retry automatically; inspect the response/server run before continuing.", opts.json);
2023
3203
  }
2024
3204
  const customerStart = customerAnswer(res.data);
2025
3205
  if (customerStart)
@@ -4067,17 +5247,24 @@ export async function reviewFlow(runId, opts, deps) {
4067
5247
  }
4068
5248
  async function readSongListen(runId, deps) {
4069
5249
  const res = await deps.get(`${SONG_PATH}?runId=${encodeURIComponent(runId)}`);
4070
- return { res, song: res.ok ? (res.data.song ?? null) : null };
5250
+ const data = res.ok ? res.data : null;
5251
+ return { res, song: data?.song ?? null, hold: data?.hold ?? null };
4071
5252
  }
4072
5253
  const SONG_NOT_ON_THIS_SERVER = "This Exodus server does not hold Song masters for approval yet.";
4073
5254
  export async function songListenFlow(runId, json, deps) {
4074
- const { res, song } = await readSongListen(runId, deps);
5255
+ const { res, song, hold } = await readSongListen(runId, deps);
4075
5256
  if (missingRouteLine(res, "exodus video song"))
4076
5257
  return { code: 1, lines: [SONG_NOT_ON_THIS_SERVER] };
4077
5258
  if (!res.ok)
4078
5259
  return errorResult(res, json);
4079
5260
  if (json)
4080
- return { code: 0, lines: [JSON.stringify({ runId, song })] };
5261
+ return { code: 0, lines: [JSON.stringify({ runId, song, ...(hold ? { hold } : {}) })] };
5262
+ if (hold)
5263
+ return { code: 0, lines: [
5264
+ `SONG HELD — ad run ${runId}`,
5265
+ ` ${hold.reason}`,
5266
+ ` No master is ready to approve. Try again on step ${hold.nodeId} to resume the retained song, not a new run.`,
5267
+ ] };
4081
5268
  if (!song)
4082
5269
  return { code: 0, lines: ["This run holds no Song master yet, so there is nothing to listen to."] };
4083
5270
  const heard = song.coverage.status === "full" ? "every lyric line heard" : `lyric ${song.coverage.status}${song.coverage.unheardLines.length ? `; no word heard on line ${song.coverage.unheardLines.map((n) => n + 1).join(", ")}` : ""}`;
@@ -4098,11 +5285,13 @@ export async function songListenFlow(runId, json, deps) {
4098
5285
  };
4099
5286
  }
4100
5287
  export async function songApproveFlow(runId, masterSha256, json, deps) {
4101
- const { res, song } = await readSongListen(runId, deps);
5288
+ const { res, song, hold } = await readSongListen(runId, deps);
4102
5289
  if (missingRouteLine(res, "exodus video song approve"))
4103
5290
  return { code: 1, lines: [SONG_NOT_ON_THIS_SERVER] };
4104
5291
  if (!res.ok)
4105
5292
  return errorResult(res, json);
5293
+ if (hold)
5294
+ return { code: 1, lines: [`No Song master is ready to approve: ${hold.reason}`] };
4106
5295
  if (!song)
4107
5296
  return { code: 1, lines: ["This run holds no Song master yet, so there is nothing to approve."] };
4108
5297
  if (song.identity.masterSha256 !== masterSha256) {
@@ -4191,6 +5380,25 @@ const VALUE_FLAGS = new Set([
4191
5380
  "pacing",
4192
5381
  "source-record",
4193
5382
  "adaptation-plan",
5383
+ "resume-script",
5384
+ "requested-seconds",
5385
+ "pictures-per-scene",
5386
+ "product",
5387
+ "product-context",
5388
+ "audience",
5389
+ "offer",
5390
+ "mechanism",
5391
+ "elements",
5392
+ "voices",
5393
+ "input-mode",
5394
+ "structure",
5395
+ "reference",
5396
+ "subject",
5397
+ "adapt",
5398
+ "template-brief",
5399
+ "song-controls",
5400
+ "mechanism-plan",
5401
+ "authorize-preparation",
4194
5402
  "note",
4195
5403
  "out",
4196
5404
  "file",
@@ -4249,6 +5457,12 @@ export async function run(flags, occurrences) {
4249
5457
  if (sub === "shows")
4250
5458
  return printResult(await showsFlow(json, defaultDeps));
4251
5459
  if (sub === "start") {
5460
+ if (occurrences.some(({ flag }) => flag === "input-options")) {
5461
+ const options = await templateInputOptionsFlow(occurrences, json, defaultDeps);
5462
+ if (options.usage)
5463
+ usage(options.lines[0] ?? "");
5464
+ return printResult(options);
5465
+ }
4252
5466
  const plan = planVideoStart(flags, occurrences);
4253
5467
  if (plan.kind === "usage")
4254
5468
  usage(plan.line);