@aicopycoders/exodus 2026.11.1100-beta.2 → 2026.11.1100-beta.3

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.
@@ -0,0 +1,812 @@
1
+ import path from "node:path";
2
+ import { formatApiError } from "../lib/format.js";
3
+ import { missingRouteLine } from "../lib/route-support.js";
4
+ import { customerAnswer } from "./video-customer.js";
5
+ import { describeFetchFailure, startedThenWait } from "./video.js";
6
+ export const SWIPE_BREAKDOWNS_PATH = "/api/v2/video/breakdowns";
7
+ export const SWIPE_UPLOAD_URL_PATH = "/api/v2/video/breakdowns/upload-url";
8
+ export const SWIPE_TEMPLATE_PATH = "/api/v2/video/swipe-template";
9
+ export const SWIPE_PRODUCTS_PATH = "/api/v2/video/swipe-products";
10
+ export const SWIPES_PATH = "/api/v2/video/swipes";
11
+ export const SWIPE_RUNS_PATH = "/api/v2/video/swipe-runs";
12
+ export const SWIPE_MODES = [
13
+ { flag: "whole-ad", mode: "whole", label: "Whole ad", helper: "Every part of their ad, rewritten for your brand." },
14
+ { flag: "hook-only", mode: "hook", label: "Hook only", helper: "Their opening hook. The rest is new, written for your product." },
15
+ { flag: "their-format", mode: "their-format", label: "Their format, my script", helper: "Your own words, made the way their ad is made." },
16
+ { flag: "new-look", mode: "new-look", label: "Their script, a new look", helper: "Their ad rewritten for your brand, in a look you pick." },
17
+ ];
18
+ export const SWIPE_CLOSENESS = [
19
+ { step: 1, flag: "mirror", name: "Mirror", line: "Same lines in the same order. Only your brand, product and claims change." },
20
+ { step: 2, flag: "close", name: "Close", line: "Same parts in the same order, each line said in new words." },
21
+ { step: 3, flag: "same-beats", name: "Same beats", line: "Same job for each part, in the same order. New words and new examples." },
22
+ {
23
+ step: 4,
24
+ flag: "same-arc",
25
+ name: "Same arc",
26
+ line: "Same kind of hook and the same story arc. Parts can join, split or move to suit your product.",
27
+ },
28
+ { step: 5, flag: "pattern-only", name: "Pattern only", line: "Same format and structure, with a new story." },
29
+ ];
30
+ export const DEFAULT_CLOSENESS = 2;
31
+ const modeOf = (mode) => SWIPE_MODES.find((m) => m.mode === mode);
32
+ const closenessOf = (step) => SWIPE_CLOSENESS.find((c) => c.step === step);
33
+ export const NO_PRICE = "The CLI prints no price for this step.";
34
+ const MEMBER_LLM_KEY = "The member's own Anthropic or OpenRouter key.";
35
+ export const PAID = {
36
+ breakdown: {
37
+ buys: "A breakdown of the ad: its video read shot by shot, every word written down, and a picture of each shot.",
38
+ paidBy: "The team's keys. Nothing is charged to the member's keys.",
39
+ },
40
+ template: {
41
+ buys: "One model call that matches the ad to the closest kind of ad and look we make.",
42
+ paidBy: MEMBER_LLM_KEY,
43
+ },
44
+ write: {
45
+ buys: "The brand's version of the ad's script, written and checked. Several model calls; a refusal is paid for too.",
46
+ paidBy: MEMBER_LLM_KEY,
47
+ },
48
+ start: {
49
+ buys: "A video run up to its storyboard: the storyboard and its pictures. The voices and clips are bought only when the storyboard is approved.",
50
+ paidBy: "The member's own keys, as for any video run.",
51
+ },
52
+ "start-one-shot": {
53
+ buys: "The whole video with no stop: the storyboard, its pictures, the voices and the clips. It stops only when a check finds a problem.",
54
+ paidBy: "The member's own keys, as for any video run.",
55
+ },
56
+ };
57
+ export function needsYesResult(step, json, choice = []) {
58
+ const { buys, paidBy } = PAID[step];
59
+ if (json)
60
+ return { code: 0, lines: [JSON.stringify({ ok: false, needsYes: true, buys, paidBy, price: null })] };
61
+ return {
62
+ code: 0,
63
+ lines: [
64
+ "This step costs money, so nothing was sent.",
65
+ ...choice,
66
+ `It buys: ${buys}`,
67
+ `Who pays: ${paidBy}`,
68
+ NO_PRICE,
69
+ "Ask the member. On their yes, run the same command with --yes.",
70
+ ],
71
+ };
72
+ }
73
+ const VERBS = ["status", "template", "products", "write", "show", "list", "start"];
74
+ export function parseSwipeMode(value) {
75
+ return SWIPE_MODES.find((m) => m.flag === value.trim().toLowerCase())?.mode ?? null;
76
+ }
77
+ export function parseCloseness(value) {
78
+ const word = value.trim().toLowerCase();
79
+ return SWIPE_CLOSENESS.find((c) => String(c.step) === word || c.flag === word)?.step ?? null;
80
+ }
81
+ const OFF_WORDS = new Set(["false", "no", "off", "0"]);
82
+ const ON_WORDS = new Set(["true", "yes", "on", "1"]);
83
+ const SWITCHES = ["json", "yes", "wait", "full", "music", "one-shot"];
84
+ export function planSwipeCommand(rest, occurrences) {
85
+ const last = (name) => occurrences.filter((o) => o.flag === name || o.flag === `no-${name}`).at(-1);
86
+ const switchState = (name) => {
87
+ const typed = last(name);
88
+ if (typed?.flag !== name)
89
+ return false;
90
+ const given = typed.value;
91
+ if (given === undefined || given.startsWith("--"))
92
+ return true;
93
+ const word = given.trim().toLowerCase();
94
+ if (OFF_WORDS.has(word))
95
+ return false;
96
+ if (ON_WORDS.has(word) || given === "swipe" || rest.includes(given))
97
+ return true;
98
+ return `video swipe --${name} takes true or false, or no value at all (got "${given}").`;
99
+ };
100
+ const switches = new Map(SWITCHES.map((name) => [name, switchState(name)]));
101
+ const refusedSwitch = [...switches.values()].find((state) => typeof state === "string");
102
+ if (refusedSwitch)
103
+ return { kind: "usage", line: refusedSwitch };
104
+ const on = (name) => switches.get(name) === true;
105
+ const value = (name) => {
106
+ const typed = last(name);
107
+ if (!typed || typed.flag !== name)
108
+ return undefined;
109
+ return typed.value !== undefined && !typed.value.startsWith("--") && typed.value.trim() ? typed.value : null;
110
+ };
111
+ const opts = { json: on("json"), yes: on("yes"), wait: on("wait") };
112
+ const usage = (line) => ({ kind: "usage", line });
113
+ const [verb, id] = rest;
114
+ if (verb === undefined) {
115
+ const given = ["file", "url", "ad"].filter((name) => value(name) !== undefined);
116
+ if (given.length !== 1) {
117
+ return usage("video swipe needs one ad: --file <ad.mp4>, --url <link> or --ad <swipeAdId>.");
118
+ }
119
+ const name = given[0];
120
+ const text = value(name);
121
+ if (!text)
122
+ return usage(`video swipe --${name} needs ${name === "file" ? "a video file" : name === "url" ? "a link" : "an ad id"}.`);
123
+ const source = name === "file" ? { kind: "file", file: text } : name === "url" ? { kind: "url", url: text.trim() } : { kind: "ad", swipeAdId: text.trim() };
124
+ return { kind: "breakdown", source, opts };
125
+ }
126
+ if (!VERBS.includes(verb)) {
127
+ return usage(`video swipe ${verb} is not a swipe command. Use one of: ${VERBS.join(", ")}, or --file, --url or --ad to start.`);
128
+ }
129
+ if (verb === "products")
130
+ return { kind: "products", opts };
131
+ if (verb === "list")
132
+ return { kind: "list", opts };
133
+ if (!id) {
134
+ const named = verb === "show" || verb === "start" ? "swipeId" : "breakdownId";
135
+ return usage(`video swipe ${verb} needs a ${named === "swipeId" ? "swipe" : "breakdown"} id: exodus video swipe ${verb} <${named}>`);
136
+ }
137
+ if (verb === "status")
138
+ return { kind: "status", breakdownId: id, full: on("full"), opts };
139
+ if (verb === "template")
140
+ return { kind: "template", breakdownId: id, opts };
141
+ if (verb === "show")
142
+ return { kind: "show", swipeId: id, opts };
143
+ if (verb === "start") {
144
+ const style = value("style");
145
+ const title = value("title");
146
+ if (style === null)
147
+ return usage("video swipe start --style needs a look's slug.");
148
+ if (title === null)
149
+ return usage('video swipe start --title needs a name: --title "<name>".');
150
+ return {
151
+ kind: "start",
152
+ swipeId: id,
153
+ ask: {
154
+ ...(style ? { style: style.trim() } : {}),
155
+ ...(title ? { title: title.trim() } : {}),
156
+ music: on("music"),
157
+ oneShot: on("one-shot"),
158
+ },
159
+ opts,
160
+ };
161
+ }
162
+ const product = value("product");
163
+ if (!product)
164
+ return usage("video swipe write needs --product <id>. exodus video swipe products lists them.");
165
+ const modeWord = value("mode");
166
+ if (modeWord === null)
167
+ return usage("video swipe write --mode needs whole-ad, hook-only, their-format or new-look.");
168
+ const mode = modeWord === undefined ? "whole" : parseSwipeMode(modeWord);
169
+ if (!mode)
170
+ return usage(`video swipe write --mode must be whole-ad, hook-only, their-format or new-look, not "${modeWord}".`);
171
+ const closenessWord = value("closeness");
172
+ if (closenessWord === null)
173
+ return usage("video swipe write --closeness needs 1 to 5, or mirror, close, same-beats, same-arc or pattern-only.");
174
+ if (mode === "their-format" && closenessWord !== undefined) {
175
+ return usage("video swipe write --closeness does not apply to their-format: your own words stay as they are.");
176
+ }
177
+ const closeness = closenessWord === undefined ? DEFAULT_CLOSENESS : parseCloseness(closenessWord);
178
+ if (closeness === null) {
179
+ return usage(`video swipe write --closeness must be 1 to 5, or mirror, close, same-beats, same-arc or pattern-only, not "${closenessWord}".`);
180
+ }
181
+ const look = value("look");
182
+ if (look === null || (look === undefined && mode === "new-look")) {
183
+ return usage("video swipe write --mode new-look needs --look <slug>, the new look.");
184
+ }
185
+ if (look !== undefined && mode !== "new-look")
186
+ return usage("video swipe write --look is only for --mode new-look.");
187
+ const script = value("script");
188
+ if (script === null || (script === undefined && mode === "their-format")) {
189
+ return usage("video swipe write --mode their-format needs --script <file>, your own script.");
190
+ }
191
+ if (script !== undefined && mode !== "their-format")
192
+ return usage("video swipe write --script is only for --mode their-format.");
193
+ return {
194
+ kind: "write",
195
+ breakdownId: id,
196
+ ask: {
197
+ productId: product.trim(),
198
+ mode,
199
+ closeness,
200
+ ...(look ? { look: look.trim() } : {}),
201
+ ...(script ? { scriptFile: script } : {}),
202
+ },
203
+ opts,
204
+ };
205
+ }
206
+ const SWIPE_NOT_FOUND = "Not found on this brand. The id is wrong or is another brand's, video isn't switched on for your dashboard " +
207
+ "user, or this is not the brand you meant (exodus brand current). Check the id first.";
208
+ function isRecord(value) {
209
+ return typeof value === "object" && value !== null && !Array.isArray(value);
210
+ }
211
+ function swipeErrorLine(res) {
212
+ return missingRouteLine(res, "exodus video swipe") ?? (res.status === 404 ? SWIPE_NOT_FOUND : formatApiError(res));
213
+ }
214
+ function swipeError(res, json) {
215
+ const error = swipeErrorLine(res);
216
+ return { code: 1, lines: json ? [JSON.stringify({ ok: false, status: res.status, error })] : [error] };
217
+ }
218
+ function failed(line, json, extra = {}) {
219
+ return { code: 1, lines: json ? [JSON.stringify({ ok: false, error: line, ...extra })] : [line] };
220
+ }
221
+ function progress(opts) {
222
+ const kept = [];
223
+ return {
224
+ say(line) {
225
+ if (opts.json)
226
+ return;
227
+ if (opts.onProgressLine)
228
+ opts.onProgressLine(line);
229
+ else
230
+ kept.push(line);
231
+ },
232
+ kept,
233
+ };
234
+ }
235
+ const POLL_MS = 5000;
236
+ const MAX_MISSES = 3;
237
+ const missed = (res) => res.status >= 500 || res.status === 429;
238
+ async function poll(read, step, maxPolls, deps) {
239
+ let misses = 0;
240
+ for (let i = 0; i < maxPolls; i++) {
241
+ if (i > 0)
242
+ await deps.sleep(POLL_MS);
243
+ const res = await read().catch(() => null);
244
+ if (!res || missed(res)) {
245
+ if (++misses >= MAX_MISSES)
246
+ return { lost: true };
247
+ continue;
248
+ }
249
+ misses = 0;
250
+ const answer = step(res);
251
+ if (answer)
252
+ return answer;
253
+ }
254
+ return { timedOut: true };
255
+ }
256
+ const usd = (value) => `$${value.toFixed(2)}`;
257
+ const LOST = "The server did not answer three times in a row while we waited.";
258
+ function waitRefused(res, hint, json) {
259
+ if (res.status === 404)
260
+ return swipeError(res, json);
261
+ const error = swipeErrorLine(res);
262
+ return { code: 1, lines: json ? [JSON.stringify({ ok: false, status: res.status, error, mayStillFinish: hint })] : [error, hint] };
263
+ }
264
+ const MAX_FILE_BYTES = 300 * 1024 * 1024;
265
+ const VIDEO_TYPES = {
266
+ ".mp4": "video/mp4",
267
+ ".m4v": "video/x-m4v",
268
+ ".mov": "video/quicktime",
269
+ ".webm": "video/webm",
270
+ };
271
+ const BREAKDOWN_MAX_POLLS = 300;
272
+ export async function swipeBreakdownFlow(source, opts, deps) {
273
+ const { json } = opts;
274
+ let file = null;
275
+ if (source.kind === "file") {
276
+ const stat = deps.statFile(source.file);
277
+ if (!stat)
278
+ return failed(`Can't read ${source.file}. Check the path.`, json);
279
+ if (stat.size === 0)
280
+ return failed("That file is empty. Pick the video file again.", json);
281
+ if (stat.size > MAX_FILE_BYTES)
282
+ return failed("That file is too big. Pick a video of at most 300 MB.", json);
283
+ const contentType = VIDEO_TYPES[path.extname(source.file).toLowerCase()];
284
+ if (!contentType)
285
+ return failed("That file is not a video. Pick an MP4, MOV, M4V or WebM file.", json);
286
+ file = { contentType, size: stat.size };
287
+ }
288
+ if (!opts.yes)
289
+ return needsYesResult("breakdown", json);
290
+ let started;
291
+ if (source.kind === "url") {
292
+ const earlier = await deps.get(`${SWIPE_BREAKDOWNS_PATH}?url=${encodeURIComponent(source.url)}`);
293
+ if (!earlier.ok)
294
+ return swipeError(earlier, json);
295
+ const found = isRecord(earlier.data) && isRecord(earlier.data.earlier) ? earlier.data.earlier.breakdownId : undefined;
296
+ if (typeof found === "string")
297
+ started = { breakdownId: found, existing: true };
298
+ else {
299
+ const res = await deps.post(SWIPE_BREAKDOWNS_PATH, { url: source.url });
300
+ if (!res.ok)
301
+ return swipeError(res, json);
302
+ started = startedOf(res.data);
303
+ }
304
+ }
305
+ else if (source.kind === "ad") {
306
+ const res = await deps.post(SWIPE_BREAKDOWNS_PATH, { swipeAdId: source.swipeAdId });
307
+ if (!res.ok)
308
+ return swipeError(res, json);
309
+ started = startedOf(res.data);
310
+ }
311
+ else {
312
+ const minted = await deps.post(SWIPE_UPLOAD_URL_PATH, {});
313
+ if (!minted.ok)
314
+ return swipeError(minted, json);
315
+ const slot = isRecord(minted.data) ? minted.data : {};
316
+ if (typeof slot.url !== "string" || typeof slot.receiptId !== "string") {
317
+ return failed("The server did not give an upload URL. Nothing was paid for.", json);
318
+ }
319
+ let stored;
320
+ try {
321
+ stored = await deps.uploadBytes(slot.url, file.contentType, deps.readFileBytes(source.file));
322
+ }
323
+ catch (err) {
324
+ return failed(`Upload failed while sending the file to storage: ${describeFetchFailure(err)}. Nothing was paid for. Run the same command again.`, json);
325
+ }
326
+ if (!stored.ok || !stored.storageId) {
327
+ return failed(`Upload failed (HTTP ${stored.status}). Nothing was paid for. Run the same command again.`, json);
328
+ }
329
+ const res = await deps.post(SWIPE_BREAKDOWNS_PATH, {
330
+ storageId: stored.storageId,
331
+ receiptId: slot.receiptId,
332
+ fileName: path.basename(source.file),
333
+ });
334
+ if (!res.ok)
335
+ return swipeError(res, json);
336
+ started = startedOf(res.data);
337
+ }
338
+ if (!started.breakdownId)
339
+ return failed("The server did not say which breakdown it started.", json);
340
+ const { breakdownId, existing } = started;
341
+ const head = existing
342
+ ? [`This ad already has a breakdown: ${breakdownId}. It cost nothing.`]
343
+ : [`Breakdown ${breakdownId} started. It reads the ad on the team's keys, in a few minutes.`];
344
+ if (!opts.wait) {
345
+ return {
346
+ code: 0,
347
+ lines: json
348
+ ? [JSON.stringify({ ok: true, breakdownId, existing })]
349
+ : [...head, `Follow it: exodus video swipe status ${breakdownId} --wait`],
350
+ };
351
+ }
352
+ const out = progress(opts);
353
+ for (const line of head)
354
+ out.say(line);
355
+ const waited = await waitForBreakdown(breakdownId, opts, deps, out.say);
356
+ if (json)
357
+ return { code: waited.code, lines: [JSON.stringify({ ok: waited.code === 0, breakdownId, existing, ...waited.json })] };
358
+ return { code: waited.code, lines: [...out.kept, ...waited.lines] };
359
+ }
360
+ function startedOf(data) {
361
+ const d = isRecord(data) ? data : {};
362
+ return { breakdownId: typeof d.breakdownId === "string" ? d.breakdownId : "", existing: d.existing === true };
363
+ }
364
+ function breakdownReadOf(data) {
365
+ if (!isRecord(data) || !isRecord(data.breakdown) || !Array.isArray(data.breakdown.steps))
366
+ return null;
367
+ return { breakdown: data.breakdown, template: isRecord(data.template) ? data.template : null };
368
+ }
369
+ async function waitForBreakdown(breakdownId, opts, deps, say) {
370
+ const said = new Set();
371
+ const ended = await poll(() => deps.get(`${SWIPE_BREAKDOWNS_PATH}?id=${encodeURIComponent(breakdownId)}`), (res) => {
372
+ if (!res.ok)
373
+ return { done: { refused: res } };
374
+ const read = breakdownReadOf(res.data);
375
+ if (!read)
376
+ return null;
377
+ for (const step of read.breakdown.steps) {
378
+ if (step.status === "waiting" || said.has(step.id))
379
+ continue;
380
+ said.add(step.id);
381
+ say(` ${step.label}`);
382
+ }
383
+ return read.breakdown.status === "done" || read.breakdown.status === "failed" ? { done: { read } } : null;
384
+ }, BREAKDOWN_MAX_POLLS, deps);
385
+ const hint = `The breakdown may still finish: exodus video swipe status ${breakdownId}`;
386
+ if ("lost" in ended) {
387
+ const error = `${LOST} ${hint}`;
388
+ return { code: 1, lines: [error], json: { error } };
389
+ }
390
+ if ("timedOut" in ended) {
391
+ const line = `Still reading after 25 minutes. Check later: exodus video swipe status ${breakdownId}`;
392
+ return { code: 0, lines: [line], json: { stillRunning: true } };
393
+ }
394
+ if ("refused" in ended.done) {
395
+ const { refused } = ended.done;
396
+ const error = swipeErrorLine(refused);
397
+ if (refused.status === 404)
398
+ return { code: 1, lines: [error], json: { error } };
399
+ return { code: 1, lines: [error, hint], json: { error, mayStillFinish: hint } };
400
+ }
401
+ const { read } = ended.done;
402
+ return { code: read.breakdown.status === "failed" ? 1 : 0, lines: breakdownEndLines(read), json: { breakdown: read.breakdown, template: read.template } };
403
+ }
404
+ function breakdownEndLines({ breakdown, template }) {
405
+ if (breakdown.status === "failed") {
406
+ return [
407
+ `The breakdown failed: ${breakdown.error ?? "no reason was given."}`,
408
+ "Reading the ad again is paid too: run the same exodus video swipe command with --yes, after the member's yes.",
409
+ ];
410
+ }
411
+ return ["The breakdown is done.", ...spentLines(breakdown), ...nextAfterBreakdown(breakdown._id, template)];
412
+ }
413
+ function spentLines(breakdown) {
414
+ if (breakdown.reused)
415
+ return ["It reused answers bought before, so it cost nothing."];
416
+ if (breakdown.spentUsd === null || breakdown.spentUsd <= 0)
417
+ return [];
418
+ return [`It cost ${usd(breakdown.spentUsd)}${breakdown.costIsEstimate ? " (partly an estimate)" : ""}, on the team's keys.`];
419
+ }
420
+ function nextAfterBreakdown(breakdownId, template) {
421
+ if (template)
422
+ return [...templateLines(template), ...nextAfterTemplate(breakdownId)];
423
+ return [`Next, the template (paid, on the member's key; ask first): exodus video swipe template ${breakdownId} --yes`];
424
+ }
425
+ const STATUS_WORD = {
426
+ queued: "waiting to start",
427
+ running: "reading the ad",
428
+ done: "done",
429
+ failed: "failed",
430
+ };
431
+ export async function swipeStatusFlow(breakdownId, opts, deps, full = false) {
432
+ const readPath = `${SWIPE_BREAKDOWNS_PATH}?id=${encodeURIComponent(breakdownId)}`;
433
+ if (opts.wait) {
434
+ const out = progress(opts);
435
+ out.say(`Waiting for breakdown ${breakdownId}.`);
436
+ const waited = await waitForBreakdown(breakdownId, opts, deps, out.say);
437
+ const done = waited.json.breakdown && waited.json.breakdown.status === "done";
438
+ const extra = full && done ? await deps.get(`${readPath}&full=1`).catch(() => null) : null;
439
+ const fullPart = extra?.ok && isRecord(extra.data) ? extra.data : {};
440
+ if (opts.json) {
441
+ return {
442
+ code: waited.code,
443
+ lines: [
444
+ JSON.stringify({
445
+ ok: waited.code === 0,
446
+ breakdownId,
447
+ ...waited.json,
448
+ ...("full" in fullPart ? { full: fullPart.full } : {}),
449
+ ...("fullProblem" in fullPart ? { fullProblem: fullPart.fullProblem } : {}),
450
+ }),
451
+ ],
452
+ };
453
+ }
454
+ const fullText = !full || !done ? [] : extra?.ok ? fullLines(fullPart) : ["", "What the breakdown read could not be fetched. Ask again: exodus video swipe status " + breakdownId + " --full"];
455
+ return { code: waited.code, lines: [...out.kept, ...waited.lines, ...fullText] };
456
+ }
457
+ const res = await deps.get(full ? `${readPath}&full=1` : readPath);
458
+ if (!res.ok)
459
+ return swipeError(res, opts.json);
460
+ const read = breakdownReadOf(res.data);
461
+ if (!read)
462
+ return failed("The server's answer about this breakdown could not be read.", opts.json);
463
+ if (opts.json)
464
+ return { code: 0, lines: [JSON.stringify(res.data)] };
465
+ const { breakdown } = read;
466
+ const width = Math.max(...breakdown.steps.map((step) => step.status.length));
467
+ const lines = [
468
+ `Breakdown ${breakdown._id}: ${STATUS_WORD[breakdown.status]}`,
469
+ `The ad: ${breakdown.sourceUrl ?? breakdown.fileName ?? "an uploaded file"}`,
470
+ ...breakdown.steps.map((step) => ` ${step.status.padEnd(width)} ${step.label}`),
471
+ ];
472
+ if (breakdown.status === "done" || breakdown.status === "failed")
473
+ lines.push(...breakdownEndLines(read));
474
+ else
475
+ lines.push(`Wait for it: exodus video swipe status ${breakdown._id} --wait`);
476
+ if (full)
477
+ lines.push(...fullLines(isRecord(res.data) ? res.data : {}));
478
+ return { code: 0, lines };
479
+ }
480
+ const seconds = (start, end) => `${start.toFixed(1)}-${end.toFixed(1)} s`;
481
+ const EMBODIMENT = {
482
+ "on-screen": "on screen",
483
+ "voice-only": "voice only",
484
+ "behind-camera": "behind the camera",
485
+ };
486
+ export function fullLines(data) {
487
+ if (!isRecord(data.full)) {
488
+ const why = typeof data.fullProblem === "string" ? data.fullProblem : "This server sent nothing it read.";
489
+ return ["", why];
490
+ }
491
+ const full = data.full;
492
+ const { shots } = full.footage;
493
+ const { cast, script } = full.buildSheet;
494
+ const nameOf = new Map(cast.map((member) => [member.characterId, member.name || member.characterId]));
495
+ const about = [full.source.advertiser, `${Math.round(full.source.durationSec)} s`, full.source.aspectRatio].filter(Boolean).join(", ");
496
+ const lines = ["", `What Exodus read from the ad (${about}):`, "", `Shots (${shots.length}):`];
497
+ for (const shot of shots) {
498
+ const number = shot.id.replace(/^s/, "");
499
+ lines.push(` ${number.padStart(2)} ${seconds(shot.start, shot.end)} ${shot.kind === "aroll" ? "a-roll" : "cutaway"}, ${shot.shotSize}, ${shot.camera}`);
500
+ lines.push(` ${shot.description}`);
501
+ }
502
+ lines.push("", "Script (who says each line):");
503
+ for (const line of script) {
504
+ const who = line.speakerId === null ? "Narrator (voice-over)" : (nameOf.get(line.speakerId) ?? line.speakerId);
505
+ lines.push(` ${line.lineId.padEnd(4)}${seconds(line.start, line.end)} ${who}: ${line.text}`);
506
+ }
507
+ lines.push("", "Cast:");
508
+ if (cast.length === 0)
509
+ lines.push(" No cast listed.");
510
+ for (const member of cast) {
511
+ lines.push(` ${member.name || member.characterId} (${member.characterId}), ${EMBODIMENT[member.embodiment] ?? member.embodiment}`);
512
+ lines.push(` Look: ${member.look}`, ` Voice: ${member.voice}`);
513
+ }
514
+ if (full.warnings.length > 0)
515
+ lines.push("", "What it was not sure about:", ...full.warnings.map((warning) => ` - ${warning}`));
516
+ return lines;
517
+ }
518
+ const TEMPLATE_MAX_POLLS = 120;
519
+ function templateLines(template) {
520
+ return [
521
+ `Kind of ad: ${template.kind.label} (${template.kind.key})`,
522
+ ` ${template.kind.why}`,
523
+ `Look: ${template.look.label} (${template.look.slug})`,
524
+ ` ${template.look.why}`,
525
+ `Their ad: ${template.lines} lines, about ${Math.round(template.seconds)} s.`,
526
+ ];
527
+ }
528
+ function nextAfterTemplate(breakdownId) {
529
+ return [
530
+ "The swipe writes this kind of ad and no other. If the member wants another kind, say so before writing.",
531
+ "Next: pick a product (exodus video swipe products), then write (paid, on the member's key; ask first):",
532
+ ` exodus video swipe write ${breakdownId} --product <productId> --mode whole-ad --closeness 2 --yes`,
533
+ ];
534
+ }
535
+ export async function swipeTemplateFlow(breakdownId, opts, deps) {
536
+ const { json } = opts;
537
+ if (!opts.yes)
538
+ return needsYesResult("template", json);
539
+ const res = await deps.post(SWIPE_TEMPLATE_PATH, { breakdownId });
540
+ if (!res.ok)
541
+ return swipeError(res, json);
542
+ const answer = isRecord(res.data) ? res.data : {};
543
+ const done = (template, costFree, kept = []) => ({
544
+ code: 0,
545
+ lines: json
546
+ ? [JSON.stringify({ ok: true, breakdownId, template, costFree })]
547
+ : [
548
+ ...kept,
549
+ ...templateLines(template),
550
+ ...(costFree ? ["This template was already made, so it cost nothing."] : []),
551
+ ...nextAfterTemplate(breakdownId),
552
+ ],
553
+ });
554
+ if (answer.status === "stored" && isRecord(answer.template))
555
+ return done(answer.template, true);
556
+ if (answer.status !== "making" || typeof answer.job !== "string") {
557
+ return failed("The server's answer about the template could not be read.", json);
558
+ }
559
+ const job = answer.job;
560
+ const out = progress(opts);
561
+ out.say("Making the template on the member's key. It takes up to six minutes.");
562
+ const ended = await poll(() => deps.get(`${SWIPE_TEMPLATE_PATH}?breakdownId=${encodeURIComponent(breakdownId)}&job=${encodeURIComponent(job)}`), (polled) => {
563
+ if (!polled.ok)
564
+ return { done: { refused: polled } };
565
+ const state = isRecord(polled.data) ? polled.data : {};
566
+ if (state.status === "stored" && isRecord(state.template))
567
+ return { done: { template: state.template } };
568
+ if (state.status === "failed")
569
+ return { done: { error: typeof state.error === "string" ? state.error : "no reason was given." } };
570
+ return null;
571
+ }, TEMPLATE_MAX_POLLS, deps);
572
+ const hint = `The template may still be made: exodus video swipe status ${breakdownId}`;
573
+ if ("lost" in ended)
574
+ return failed(`${LOST} ${hint}`, json);
575
+ if ("timedOut" in ended) {
576
+ return failed(`Still making the template after 10 minutes. Waiting costs nothing more. Check later: exodus video swipe status ${breakdownId}`, json);
577
+ }
578
+ const result = ended.done;
579
+ if ("refused" in result)
580
+ return waitRefused(result.refused, hint, json);
581
+ if ("error" in result)
582
+ return failed(`The template could not be made: ${result.error}`, json, { breakdownId });
583
+ return done(result.template, false, out.kept);
584
+ }
585
+ export async function swipeProductsFlow(opts, deps) {
586
+ const res = await deps.get(SWIPE_PRODUCTS_PATH);
587
+ if (!res.ok)
588
+ return swipeError(res, opts.json);
589
+ const products = isRecord(res.data) && Array.isArray(res.data.products) ? res.data.products : [];
590
+ if (opts.json)
591
+ return { code: 0, lines: [JSON.stringify({ ok: true, products })] };
592
+ if (products.length === 0)
593
+ return { code: 0, lines: ["This brand has no products yet. Add one in the dashboard first."] };
594
+ const width = Math.max(...products.map((p) => p.id.length));
595
+ return {
596
+ code: 0,
597
+ lines: [
598
+ "The brand's products. Write for one with --product <id>:",
599
+ ...products.map((p) => ` ${p.id.padEnd(width)} ${p.name}${p.description ? ` — ${p.description}` : ""}`),
600
+ ],
601
+ };
602
+ }
603
+ const WRITE_MAX_POLLS = 180;
604
+ function choiceLines(ask) {
605
+ const mode = modeOf(ask.mode);
606
+ const lines = [`Mode: ${mode.label}. ${mode.helper}`];
607
+ if (ask.mode !== "their-format") {
608
+ const step = closenessOf(ask.closeness);
609
+ lines.push(`Closeness: ${step.step}, ${step.name}. ${step.line}`);
610
+ }
611
+ if (ask.look)
612
+ lines.push(`New look: ${ask.look}`);
613
+ return lines;
614
+ }
615
+ function requestOf(ask, memberScript) {
616
+ switch (ask.mode) {
617
+ case "their-format":
618
+ return { mode: ask.mode, memberScript };
619
+ case "new-look":
620
+ return { mode: ask.mode, closeness: ask.closeness, look: ask.look };
621
+ default:
622
+ return { mode: ask.mode, closeness: ask.closeness };
623
+ }
624
+ }
625
+ function costLine(swipe) {
626
+ return swipe.costUsd !== null
627
+ ? `It cost ${usd(swipe.costUsd)} on the member's key.`
628
+ : "What it cost is unknown: the provider reported no usage for it.";
629
+ }
630
+ function swipeLines(swipe, after) {
631
+ if (swipe.outcome.kind === "refused") {
632
+ return [
633
+ `The writer refused: ${swipe.outcome.why}`,
634
+ ...(swipe.checksFound?.length ? ["What the checks found:", ...swipe.checksFound.map((p) => ` - ${p}`)] : []),
635
+ `Swipe ${swipe._id} keeps this refusal: exodus video swipe show ${swipe._id}`,
636
+ costLine(swipe),
637
+ "Nothing was started.",
638
+ ...(after === "write" ? ["Writing again is paid too: the same exodus video swipe write line, after the member's yes."] : []),
639
+ ];
640
+ }
641
+ const { draft } = swipe.outcome;
642
+ return [
643
+ `Swipe ${swipe._id} written.`,
644
+ `Kind of ad: ${draft.conceit}`,
645
+ `Look: ${draft.style}`,
646
+ "",
647
+ draft.script,
648
+ "",
649
+ ...(draft.direction.trim() ? [`Direction: ${draft.direction}`] : []),
650
+ `Kept: ${draft.note.kept}`,
651
+ `Changed: ${draft.note.changed}`,
652
+ ...(draft.lengthGap ? [`Length: ours is about ${draft.lengthGap.ours} s, theirs about ${draft.lengthGap.theirs} s.`] : []),
653
+ costLine(swipe),
654
+ "",
655
+ swipe.workflowRunId
656
+ ? `It started run ${swipe.workflowRunId}: exodus video status ${swipe.workflowRunId}. Another start is a second, paid video.`
657
+ : `Start the video (paid; ask first): exodus video swipe start ${swipe._id} --yes`,
658
+ ];
659
+ }
660
+ export async function swipeWriteFlow(breakdownId, ask, opts, deps) {
661
+ const { json } = opts;
662
+ let memberScript;
663
+ if (ask.scriptFile !== undefined) {
664
+ try {
665
+ memberScript = deps.readFile(ask.scriptFile);
666
+ }
667
+ catch {
668
+ return failed(`Can't read --script ${ask.scriptFile}. Check the path.`, json);
669
+ }
670
+ if (!memberScript.trim())
671
+ return failed(`--script ${ask.scriptFile} is empty.`, json);
672
+ }
673
+ if (!opts.yes)
674
+ return needsYesResult("write", json, choiceLines(ask));
675
+ const res = await deps.post(SWIPES_PATH, { breakdownId, productId: ask.productId, request: requestOf(ask, memberScript) });
676
+ if (!res.ok)
677
+ return swipeError(res, json);
678
+ const job = isRecord(res.data) ? res.data.job : undefined;
679
+ if (typeof job !== "string")
680
+ return failed("The server did not say which write it started.", json);
681
+ const out = progress(opts);
682
+ out.say("Writing the brand's version on the member's key. It takes four to nine minutes.");
683
+ const ended = await poll(() => deps.get(`${SWIPES_PATH}?job=${encodeURIComponent(job)}`), (polled) => {
684
+ if (!polled.ok)
685
+ return { done: { refused: polled } };
686
+ const state = isRecord(polled.data) ? polled.data : {};
687
+ if (state.status === "done" && isRecord(state.swipe))
688
+ return { done: { swipe: state.swipe } };
689
+ if (state.status === "failed")
690
+ return { done: { error: typeof state.error === "string" ? state.error : "no reason was given." } };
691
+ return null;
692
+ }, WRITE_MAX_POLLS, deps);
693
+ const hint = "The write may still finish: exodus video swipe list";
694
+ if ("lost" in ended)
695
+ return failed(`${LOST} ${hint}`, json);
696
+ if ("timedOut" in ended) {
697
+ return failed("Still writing after 15 minutes. Waiting costs nothing more. See it later: exodus video swipe list", json);
698
+ }
699
+ const result = ended.done;
700
+ if ("refused" in result)
701
+ return waitRefused(result.refused, hint, json);
702
+ if ("error" in result)
703
+ return failed(`The write stopped: ${result.error} Nothing was started.`, json);
704
+ const { swipe } = result;
705
+ const written = swipe.outcome.kind === "written";
706
+ if (json) {
707
+ return { code: written ? 0 : 1, lines: [JSON.stringify(written ? { ok: true, swipe } : { ok: false, refused: true, swipe })] };
708
+ }
709
+ return { code: written ? 0 : 1, lines: [...out.kept, ...swipeLines(swipe, "write")] };
710
+ }
711
+ export async function swipeShowFlow(swipeId, opts, deps) {
712
+ const res = await deps.get(`${SWIPES_PATH}?id=${encodeURIComponent(swipeId)}`);
713
+ if (!res.ok)
714
+ return swipeError(res, opts.json);
715
+ const swipe = isRecord(res.data) && isRecord(res.data.swipe) ? res.data.swipe : null;
716
+ if (!swipe)
717
+ return failed("The server's answer about this swipe could not be read.", opts.json);
718
+ if (opts.json)
719
+ return { code: 0, lines: [JSON.stringify({ ok: true, swipe })] };
720
+ return { code: 0, lines: swipeLines(swipe, "show") };
721
+ }
722
+ export async function swipeListFlow(opts, deps) {
723
+ const res = await deps.get(SWIPES_PATH);
724
+ if (!res.ok)
725
+ return swipeError(res, opts.json);
726
+ const swipes = isRecord(res.data) && Array.isArray(res.data.swipes) ? res.data.swipes : [];
727
+ if (opts.json)
728
+ return { code: 0, lines: [JSON.stringify({ ok: true, swipes })] };
729
+ if (swipes.length === 0)
730
+ return { code: 0, lines: ["This brand has no swipes yet."] };
731
+ return {
732
+ code: 0,
733
+ lines: swipes.map((row) => {
734
+ const mode = modeOf(row.request.mode);
735
+ const step = row.request.closeness !== undefined ? closenessOf(row.request.closeness) : undefined;
736
+ const ad = row.source?.sourceUrl ?? row.source?.fileName ?? "an ad";
737
+ return [
738
+ row._id,
739
+ `${mode.label}${step ? `, ${step.step} ${step.name}` : ""}`,
740
+ ad,
741
+ ...(row.workflowRunId ? [`run ${row.workflowRunId}`] : []),
742
+ ...(row.outcome?.kind === "refused"
743
+ ? [`refused, ${typeof row.costUsd === "number" ? `cost ${usd(row.costUsd)}` : "cost unknown"}, nothing started`]
744
+ : []),
745
+ ].join(" ");
746
+ }),
747
+ };
748
+ }
749
+ export async function swipeStartFlow(swipeId, ask, opts, deps) {
750
+ const { json } = opts;
751
+ if (!opts.yes)
752
+ return needsYesResult(ask.oneShot ? "start-one-shot" : "start", json);
753
+ const res = await deps.post(SWIPE_RUNS_PATH, {
754
+ swipeId,
755
+ ...(ask.style ? { style: ask.style } : {}),
756
+ ...(ask.title ? { title: ask.title } : {}),
757
+ ...(ask.music ? { music: true } : {}),
758
+ ...(ask.oneShot ? {} : { reviewStoryboard: true }),
759
+ });
760
+ if (!res.ok)
761
+ return swipeError(res, json);
762
+ const customer = customerAnswer(res.data);
763
+ const data = isRecord(res.data) ? res.data : {};
764
+ const runId = customer?.runId ?? (typeof data.runId === "string" ? data.runId : "");
765
+ const url = customer?.dashboardUrl ?? (typeof data.url === "string" ? data.url : "");
766
+ if (!runId)
767
+ return failed("The server started the ad but did not say which run it is.", json);
768
+ const card = isRecord(data.card) ? data.card : null;
769
+ const label = (value) => (isRecord(value) && typeof value.label === "string" ? value.label : null);
770
+ const head = [
771
+ `Started ad run ${runId} from swipe ${swipeId}`,
772
+ ...(label(card?.conceit) ? [`Kind of ad: ${label(card?.conceit)}`] : []),
773
+ ...(label(card?.style) ? [`Look: ${label(card?.style)}`] : []),
774
+ `Watch it: ${url}`,
775
+ ];
776
+ if (opts.wait)
777
+ return startedThenWait(runId, head, { json, url, onProgressLine: opts.onProgressLine }, deps);
778
+ if (json)
779
+ return { code: 0, lines: [JSON.stringify({ ok: true, runId, url })] };
780
+ return {
781
+ code: 0,
782
+ lines: [
783
+ ...head,
784
+ "",
785
+ ask.oneShot
786
+ ? "The app approves the storyboard itself if its checks pass. It only stops for you if they find a problem."
787
+ : "It stops at the storyboard for the member's yes. Nothing else is bought before then.",
788
+ `Check in whenever: exodus video status ${runId}`,
789
+ ],
790
+ };
791
+ }
792
+ export async function runSwipePlan(plan, deps, onProgressLine) {
793
+ const opts = { ...plan.opts, ...(onProgressLine ? { onProgressLine } : {}) };
794
+ switch (plan.kind) {
795
+ case "breakdown":
796
+ return swipeBreakdownFlow(plan.source, opts, deps);
797
+ case "status":
798
+ return swipeStatusFlow(plan.breakdownId, opts, deps, plan.full);
799
+ case "template":
800
+ return swipeTemplateFlow(plan.breakdownId, opts, deps);
801
+ case "products":
802
+ return swipeProductsFlow(opts, deps);
803
+ case "write":
804
+ return swipeWriteFlow(plan.breakdownId, plan.ask, opts, deps);
805
+ case "show":
806
+ return swipeShowFlow(plan.swipeId, opts, deps);
807
+ case "list":
808
+ return swipeListFlow(opts, deps);
809
+ case "start":
810
+ return swipeStartFlow(plan.swipeId, plan.ask, opts, deps);
811
+ }
812
+ }