@clipwright/cli 0.85.0 → 0.87.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6,41 +6,71 @@ import { isDeepStrictEqual } from "node:util";
6
6
  import { Command, Option } from "commander";
7
7
  import { ACTOR_GENDERS_ACCEPTED, ACTOR_QUALITIES_ACCEPTED, apiBaseUrlFromEnv, ASPECT_RATIOS, CATALOG_GENDERS, CATALOG_LANGUAGES, CANDIDATE_CHARGE_TEXT, DEFAULT_FACELESS_VOICE, editDocumentRead, FEEDBACK_KINDS, FAILED_STATE, MODEL_VOICE_MODEL, PUBLIC_APP_BASE_URL, RESOLUTIONS, REVISION_CHARGE_TEXT, TTS_MODELS, UPLOAD_MAX_BYTES, VOICE_NAME_PATTERN, VOICE_PRESET_NAMES, VOICE_SKILLS, sniffUploadMediaType, } from "@clipwright/core";
8
8
  import { ClipwrightApiError, ClipwrightClient, ClipwrightResponseError, } from "@clipwright/sdk";
9
- import { formatApiError, formatDraftNotes, formatRun, formatRunShots, formatSchemaError, formatVoices, } from "./format.js";
9
+ import { formatApiError, formatDraftNotes, formatRun, formatRunShots, formatVoices, } from "./format.js";
10
+ import { guidedPlan, GUIDE_PATHS } from "./guided.js";
11
+ import { attemptOf, confirmDestructive, registerNativeCommands, sameCommand, withAttemptOption } from "./native.js";
12
+ import { apiFailure as apiFailureOf, commandLine, commanderFailure, emitFailure, fail, failureOf, note, outputMode, scrubKeys, unverifiedFailure, warn, } from "./output.js";
13
+ import { startWithResend } from "./retry.js";
14
+ import { failIfFailed, saveFile, waitUntilDone, withWaitOptions } from "./wait.js";
10
15
  import { registerWorkflowCommands, WorkflowFileError } from './workflows.js';
11
16
  const { version } = createRequire(import.meta.url)("../package.json");
12
17
  const program = new Command();
13
18
  program.name("clipwright").description("UGC video platform CLI").version(version);
19
+ program
20
+ .configureOutput({
21
+ outputError: (text, write) => { if (outputMode() === "text")
22
+ write(text); },
23
+ writeErr: (text) => { if (outputMode() === "text")
24
+ process.stderr.write(text); },
25
+ })
26
+ .exitOverride((error) => {
27
+ if (error.exitCode !== 0 && outputMode() === "json")
28
+ emitFailure(commanderFailure(error));
29
+ });
14
30
  function client() {
15
31
  const apiKey = process.env.CLIPWRIGHT_API_KEY;
16
32
  if (!apiKey) {
17
- console.error(`CLIPWRIGHT_API_KEY is not set. Create a key at ${PUBLIC_APP_BASE_URL}/api-keys, ` +
18
- "then export it: export CLIPWRIGHT_API_KEY=cw_...");
19
- process.exit(1);
33
+ fail({ code: "api_key_missing", message: `CLIPWRIGHT_API_KEY is not set. Create a key at ${PUBLIC_APP_BASE_URL}/api-keys, ` +
34
+ "then export it: export CLIPWRIGHT_API_KEY=cw_...",
35
+ fix: [`Create a key at ${PUBLIC_APP_BASE_URL}/api-keys.`, "Export it: export CLIPWRIGHT_API_KEY=cw_...",
36
+ "Then run clipwright account, which is free, to confirm."] });
37
+ }
38
+ if (!/^cw_[\x21-\x7e]+$/.test(apiKey)) {
39
+ fail({ code: "api_key_invalid", message: "CLIPWRIGHT_API_KEY is not a cw_ key on one line: it does not start with cw_, " +
40
+ "or it holds a space, a line break or another character a key never has. Nothing was sent.",
41
+ fix: [`Copy the key again at ${PUBLIC_APP_BASE_URL}/api-keys and export it on one line: export CLIPWRIGHT_API_KEY=cw_...`,
42
+ "Then run clipwright account, which is free, to confirm."] });
20
43
  }
21
44
  let baseUrl;
22
45
  try {
23
46
  baseUrl = apiBaseUrlFromEnv(process.env.CLIPWRIGHT_API_URL);
24
47
  }
25
48
  catch (error) {
26
- console.error(error instanceof Error ? error.message : String(error));
27
- process.exit(1);
49
+ fail({ code: "invalid_api_url", message: error instanceof Error ? error.message : String(error),
50
+ fix: ["Unset CLIPWRIGHT_API_URL to use the public API, or set it to an https address."] });
28
51
  }
29
52
  return new ClipwrightClient({ apiKey, baseUrl });
30
53
  }
31
54
  async function uploadFile(path) {
32
- const bytes = new Uint8Array(readFileSync(path));
55
+ let bytes;
56
+ try {
57
+ bytes = new Uint8Array(readFileSync(path));
58
+ }
59
+ catch (error) {
60
+ fail({ code: "file_unreadable", message: `${path} cannot be read: ${error instanceof Error ? error.message : String(error)}`,
61
+ fix: ["Pass a readable PNG or JPEG file."] });
62
+ }
33
63
  const mediaType = sniffUploadMediaType(bytes);
34
64
  if (mediaType === null) {
35
- console.error(`${path} is not a PNG or JPEG file (checked by signature, not by extension)`);
36
- process.exit(1);
65
+ fail({ code: "invalid_value", message: `${path} is not a PNG or JPEG file (checked by signature, not by extension)`,
66
+ fix: ["Pass a PNG or JPEG file."] });
37
67
  }
38
68
  if (bytes.byteLength > UPLOAD_MAX_BYTES) {
39
- console.error(`${path} is ${bytes.byteLength} bytes; the ceiling is ${UPLOAD_MAX_BYTES}`);
40
- process.exit(1);
69
+ fail({ code: "invalid_value", message: `${path} is ${bytes.byteLength} bytes; the ceiling is ${UPLOAD_MAX_BYTES}`,
70
+ fix: [`Pass a picture of at most ${UPLOAD_MAX_BYTES} bytes.`] });
41
71
  }
42
72
  const upload = await client().uploadImage(bytes, mediaType);
43
- console.error(`uploaded ${upload.width}x${upload.height} ${upload.media_type}; url expires ${upload.expires_at}`);
73
+ note(`uploaded ${upload.width}x${upload.height} ${upload.media_type}; url expires ${upload.expires_at}`);
44
74
  return upload;
45
75
  }
46
76
  async function resolveImage(opts) {
@@ -60,20 +90,39 @@ function withSourceOptions(command) {
60
90
  const parseWholeNumber = (flag) => (raw) => {
61
91
  const parsed = Number.parseInt(raw, 10);
62
92
  if (!/^[1-9]\d*$/.test(raw) || !Number.isSafeInteger(parsed)) {
63
- console.error(`${flag} expects a whole number of 1 or more, got ${raw}`);
64
- process.exit(1);
93
+ fail({ code: "invalid_value", message: `${flag} expects a whole number of 1 or more, got ${raw}`,
94
+ fix: [`Pass ${flag} a whole number of 1 or more.`] });
65
95
  }
66
96
  return parsed;
67
97
  };
68
- const parseRetry = parseWholeNumber("--retry");
69
- const maxCreditsOption = () => new Option("--max-credits <n>", "the most credits this call may cost; a call that reserves more is refused and nothing is charged").argParser((raw) => {
98
+ const parseMaxCredits = (raw) => {
70
99
  const parsed = Number.parseInt(raw, 10);
71
100
  if (!/^(0|[1-9]\d*)$/.test(raw) || !Number.isSafeInteger(parsed)) {
72
- console.error(`--max-credits expects a whole number of 0 or more, got ${raw}`);
73
- process.exit(1);
101
+ fail({ code: "invalid_value", message: `--max-credits expects a whole number of 0 or more, got ${raw}`,
102
+ fix: ["Pass --max-credits the credits the quote shows, a whole number of 0 or more."] });
74
103
  }
75
104
  return parsed;
76
- });
105
+ };
106
+ const maxCreditsOption = () => new Option("--max-credits <n>", "the most credits this call may cost; a call that reserves more is refused and nothing is charged").argParser(parseMaxCredits);
107
+ async function startKeyed(start, resume = sameCommand()) {
108
+ try {
109
+ return await startWithResend(start);
110
+ }
111
+ catch (error) {
112
+ if (!(error instanceof ClipwrightResponseError))
113
+ throw error;
114
+ fail(unverifiedFailure(error, resume, true), [`error: ${error.message}`]);
115
+ }
116
+ }
117
+ function resumeWithImage(url) {
118
+ const words = process.argv.slice(2);
119
+ if (url === undefined)
120
+ return commandLine(words);
121
+ const at = words.findIndex((word) => word === "--image-file" || word.startsWith("--image-file="));
122
+ if (at >= 0)
123
+ words.splice(at, words[at] === "--image-file" ? 2 : 1, "--image", url);
124
+ return commandLine(words);
125
+ }
77
126
  const ceilingOf = (opts) => opts.maxCredits === undefined ? {} : { max_credits: opts.maxCredits };
78
127
  program
79
128
  .command("upload <path>")
@@ -111,23 +160,27 @@ withSourceOptions(program
111
160
  .option("--captions", "burn in word-synced captions")
112
161
  .option("--voice <name>", `voice name from "clipwright voices" (presets: ${VOICE_PRESET_NAMES.join(", ")})`, (raw) => {
113
162
  if (!VOICE_NAME_PATTERN.test(raw)) {
114
- console.error(`--voice expects a voice name (letters, digits, "_" or "-"), got ${JSON.stringify(raw)}; ` +
115
- 'run "clipwright voices" for the catalog');
116
- process.exit(1);
163
+ fail({ code: "invalid_value", message: `--voice expects a voice name (letters, digits, "_" or "-"), got ${JSON.stringify(raw)}; ` +
164
+ 'run "clipwright voices" for the catalog',
165
+ fix: ["Run clipwright voices for the catalog, then pass one of its names to --voice."] });
117
166
  }
118
167
  return raw;
119
168
  })
120
169
  .addOption(new Option("--voice-id <id>", "raw vendor voice id, for voices outside the catalog").conflicts("voice"))
121
170
  .addOption(new Option("--tts-model <model>", "speech model; omitted = the voice's default model").choices(TTS_MODELS))
122
- .option("--retry <n>", "retry attempt number (forces a fresh run)", parseRetry)
123
171
  .addOption(maxCreditsOption())
172
+ .addOption(new Option("--timeout <seconds>", "how long to wait for the video (default 600); the run goes on after it")
173
+ .argParser(parseWholeNumber("--timeout")));
174
+ withAttemptOption(program.commands.at(-1), parseWholeNumber)
124
175
  .action(async (opts) => {
125
- const run = await client().makeUgc({
176
+ const image = await resolveImage(opts);
177
+ const sdk = client();
178
+ const input = {
126
179
  script: opts.script,
127
180
  actor_id: opts.actorId,
128
181
  actor_gender: opts.actorGender,
129
182
  person: opts.person,
130
- image: await resolveImage(opts),
183
+ image,
131
184
  aspect_ratio: opts.aspectRatio,
132
185
  resolution: opts.resolution,
133
186
  captions: opts.captions ?? false,
@@ -135,18 +188,33 @@ withSourceOptions(program
135
188
  voice_id: opts.voiceId,
136
189
  tts_model: opts.ttsModel,
137
190
  ...ceilingOf(opts),
138
- }, { attempt: opts.retry }, (r) => console.error(`state: ${r.state}`));
139
- for (const warning of run.warnings) {
140
- console.error(`warning: ${warning}`);
141
- }
191
+ };
192
+ const attempt = attemptOf(opts);
193
+ const started = await startKeyed(() => sdk.startUgc(input, { attempt }), resumeWithImage(opts.imageFile === undefined ? undefined : image));
194
+ note(`state: ${started.state}`);
195
+ const run = await waitUntilDone(sdk, "run", started.run_id, started, opts.timeout);
196
+ for (const warning of run.warnings)
197
+ warn(warning);
198
+ failIfFailed(run.run_id, run, `To try again, ask the user, then run the same command with --attempt ${(attempt ?? 1) + 1}: that is a new paid run.`);
142
199
  console.log(run.final_output?.video_url);
143
200
  });
144
- program
201
+ withWaitOptions(program
145
202
  .command("runs <id>")
146
- .description("check the status of a run")
147
- .action(async (id) => {
148
- const run = await client().getRun(id);
203
+ .description("check the status of a run; --wait waits until it succeeds or fails"), true)
204
+ .action(async (id, opts) => {
205
+ const sdk = client();
206
+ let run = await sdk.getRun(id);
207
+ if (opts.wait === true || opts.output !== undefined)
208
+ run = await waitUntilDone(sdk, "run", id, run, opts.timeout);
149
209
  console.log(formatRun(run));
210
+ if (opts.wait === true || opts.output !== undefined)
211
+ failIfFailed(id, run, "Read the error above; to try again, start it anew after the user agrees.");
212
+ if (opts.output !== undefined) {
213
+ const url = run.final_output?.video_url ?? run.generation?.url;
214
+ if (url === undefined)
215
+ fail({ code: "no_file", message: `${id} succeeded without a file to save`, fix: [`Read it with ${commandLine(["get-run", id])}.`] });
216
+ await saveFile(url, opts.output, commandLine(["runs", id, "--output", opts.output]));
217
+ }
150
218
  });
151
219
  program
152
220
  .command("shots <run>")
@@ -156,7 +224,7 @@ program
156
224
  });
157
225
  function printDraft(draft) {
158
226
  for (const line of formatDraftNotes(draft))
159
- console.error(line);
227
+ note(line);
160
228
  console.log(JSON.stringify(draft, null, 2));
161
229
  }
162
230
  program
@@ -166,14 +234,15 @@ program
166
234
  printDraft(await client().getRunEdit(run));
167
235
  });
168
236
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
237
+ const readFailure = (error) => error instanceof SyntaxError ? "it is not JSON" : error instanceof Error ? error.message : String(error);
169
238
  function readDraftFile(path) {
170
239
  let parsed;
171
240
  try {
172
241
  parsed = JSON.parse(readFileSync(path, "utf8"));
173
242
  }
174
243
  catch (error) {
175
- console.error(`${path} cannot be read as JSON: ${error instanceof Error ? error.message : String(error)}`);
176
- process.exit(1);
244
+ fail({ code: "file_unreadable", message: `${path} cannot be read as JSON: ${readFailure(error)}`,
245
+ fix: [`Write the draft with clipwright edit-show <run> > ${path}, edit it, then save it.`] });
177
246
  }
178
247
  const file = isRecord(parsed) ? parsed : {};
179
248
  const { version, document } = file;
@@ -184,9 +253,8 @@ function readDraftFile(path) {
184
253
  ...(isRecord(document) ? [] : ["document (an object)"]),
185
254
  ];
186
255
  if (missing.length > 0) {
187
- console.error(`${path} is not a draft as "clipwright edit-show" prints it: it lacks ${missing.join(" and ")}. ` +
188
- "Nothing was sent.");
189
- process.exit(1);
256
+ fail({ code: "file_unreadable", message: `${path} is not a draft as "clipwright edit-show" prints it: it lacks ${missing.join(" and ")}. ` +
257
+ "Nothing was sent.", fix: ["Save what clipwright edit-show <run> prints, edit its document, then pass that file."] });
190
258
  }
191
259
  return { version: version, document: document };
192
260
  }
@@ -200,21 +268,20 @@ async function settleConflict(sdk, run, sent, storedVersion) {
200
268
  stored = await sdk.getRunEdit(run);
201
269
  }
202
270
  catch (error) {
203
- console.error(`conflict: the draft is at version ${storedVersion}, and the file was written against version ` +
204
- `${sent.version}. Whether the draft already holds this document could not be checked: ` +
205
- `${error instanceof Error ? error.message : String(error)}. ` +
206
- `Run "clipwright edit-show ${run}" and compare.`);
207
- process.exit(1);
271
+ fail({ code: "edit_conflict", message: `conflict: the draft is at version ${storedVersion}, and the file was written against version ` +
272
+ `${sent.version}. Whether the draft already holds this document could not be checked: ` +
273
+ `${error instanceof Error ? error.message : String(error)}. ` +
274
+ `Run "clipwright edit-show ${run}" and compare.`, fix: [`Run clipwright edit-show ${run} and compare it with the file.`] });
208
275
  }
209
276
  if (stored.version === sent.version + 1 && sameDocument(stored.document, sent.document)) {
210
- console.error(`saved: the draft already holds this document at version ${stored.version}; ` +
277
+ note(`saved: the draft already holds this document at version ${stored.version}; ` +
211
278
  "an earlier save of it went through.");
212
279
  return stored;
213
280
  }
214
- console.error(`conflict: the draft is at version ${stored.version}, and the file was written against version ` +
215
- `${sent.version}. Nothing was stored. Run "clipwright edit-show ${run}" again, apply your change ` +
216
- "to that draft and save it.");
217
- process.exit(1);
281
+ fail({ code: "edit_conflict", details: { version: stored.version }, message: `conflict: the draft is at version ${stored.version}, and the file was written against version ` +
282
+ `${sent.version}. Nothing was stored. Run "clipwright edit-show ${run}" again, apply your change ` +
283
+ "to that draft and save it.",
284
+ fix: [`Run clipwright edit-show ${run} again, apply your change to that draft and save it.`] });
218
285
  }
219
286
  program
220
287
  .command("edit-save <run>")
@@ -250,21 +317,20 @@ function revisionInput(opts) {
250
317
  parsed = JSON.parse(readFileSync(opts.document, "utf8"));
251
318
  }
252
319
  catch (error) {
253
- console.error(`${opts.document} cannot be read as JSON: ${error instanceof Error ? error.message : String(error)}`);
254
- process.exit(1);
320
+ fail({ code: "file_unreadable", message: `${opts.document} cannot be read as JSON: ${readFailure(error)}`,
321
+ fix: ["Pass --document the file clipwright edit-show <run> prints, edited."] });
255
322
  }
256
323
  const document = isRecord(parsed) ? parsed.document : undefined;
257
324
  if (!isRecord(document)) {
258
- console.error(`${opts.document} is not a draft as "clipwright edit-show" prints it: it lacks document (an object). ` +
259
- "Nothing was sent.");
260
- process.exit(1);
325
+ fail({ code: "file_unreadable", message: `${opts.document} is not a draft as "clipwright edit-show" prints it: it lacks document (an object). ` +
326
+ "Nothing was sent.", fix: ["Pass --document the file clipwright edit-show <run> prints, edited."] });
261
327
  }
262
328
  return { document };
263
329
  }
264
330
  const chosen = GENERATE_FLAGS.filter((flag) => opts[flag] !== undefined);
265
331
  if (opts.shot === undefined || chosen.length !== 1) {
266
- console.error("pass --shot <id> with one of --retake, --new-picture or --animate, or --document <path>. Nothing was sent.");
267
- process.exit(1);
332
+ fail({ code: "missing_input", message: "pass --shot <id> with one of --retake, --new-picture or --animate, or --document <path>. Nothing was sent.",
333
+ fix: ["Pass --shot <id> with one of --retake, --new-picture or --animate, or --document <path>; clipwright shots <run> lists the shots."] });
268
334
  }
269
335
  const operation = opts.retake === true ? { mode: "retake" }
270
336
  : opts.newPicture !== undefined ? { mode: "new_picture", description: opts.newPicture }
@@ -277,42 +343,40 @@ withReviseOptions(program.command("revise-quote <run>")
277
343
  });
278
344
  withReviseOptions(program.command("revise <run>")
279
345
  .description(`start a revision of a run (paid): a new run, editable in its turn; prints the run. ${REVISION_CHARGE_TEXT}`))
280
- .option("--retry <n>", "attempt number: the same request with another number starts another revision", parseRetry)
281
- .addOption(maxCreditsOption())
346
+ .addOption(maxCreditsOption());
347
+ withAttemptOption(program.commands.at(-1), parseWholeNumber)
282
348
  .action(async (run, opts) => {
283
349
  const request = { ...revisionInput(opts), ...ceilingOf(opts) };
350
+ const attempt = attemptOf(opts);
351
+ const sdk = client();
284
352
  let started;
285
353
  try {
286
- started = await client().startRevision(run, request, { attempt: opts.retry });
354
+ started = await startKeyed(() => sdk.startRevision(run, request, { attempt }));
287
355
  }
288
356
  catch (error) {
289
357
  if (!(error instanceof ClipwrightApiError))
290
358
  throw error;
291
359
  const failure = error.failure;
360
+ const commands = commandNames();
292
361
  if (failure.kind === "edit_ceiling_reached") {
293
- console.error(formatApiError(error));
294
- if (failure.limit === "in_flight") {
295
- for (const id of failure.runIds)
296
- console.error(`running: ${id}; follow it with "clipwright runs ${id}"`);
297
- }
298
- else {
299
- console.error(`${failure.counted} of ${failure.allowed} revisions of ${failure.rootRunId} are counted; ask support to raise the limit.`);
300
- }
301
- process.exit(1);
362
+ const lines = failure.limit === "in_flight"
363
+ ? failure.runIds.map((id) => `running: ${id}; follow it with "clipwright runs ${id}"`)
364
+ : [`${failure.counted} of ${failure.allowed} revisions of ${failure.rootRunId} are counted; ask support to raise the limit.`];
365
+ fail({ ...apiFailureOf(error, commands), fix: lines }, [formatApiError(error), ...lines]);
302
366
  }
303
367
  if (failure.kind === "run_not_editable" && "changes" in request) {
304
- console.error(formatApiError(error));
305
- console.error('if you started this revision before, find it with "clipwright runs"');
306
- process.exit(1);
368
+ const line = 'if you started this revision before, find it with "clipwright runs"';
369
+ fail({ ...apiFailureOf(error, commands), fix: [line] }, [formatApiError(error), line]);
307
370
  }
308
371
  throw error;
309
372
  }
310
373
  console.log(JSON.stringify(started, null, 2));
311
374
  if (started.state === FAILED_STATE) {
312
- console.error(`run ${started.run_id} is ${started.state}; to try again, pass --retry ${(opts.retry ?? 1) + 1}`);
313
- process.exit(1);
375
+ fail({ code: "run_failed", message: `run ${started.run_id} is ${started.state}; to try again, pass --attempt ${(attempt ?? 1) + 1}`,
376
+ run: started, details: { id: started.run_id, credits_charged: started.credits_charged },
377
+ fix: [`To try again, ask the user, then pass --attempt ${(attempt ?? 1) + 1}: that is a new paid revision.`] });
314
378
  }
315
- console.error(`follow it with "clipwright runs ${started.run_id}"`);
379
+ note(`follow it with "clipwright runs ${started.run_id}"`);
316
380
  });
317
381
  const withCandidateOptions = (command) => command
318
382
  .option("--shot <id>", "the shot to make a candidate for, with one of --retake, --new-picture or --animate")
@@ -324,8 +388,8 @@ const withCandidateOptions = (command) => command
324
388
  function candidateInput(opts) {
325
389
  const chosen = GENERATE_FLAGS.filter((flag) => opts[flag] !== undefined);
326
390
  if (opts.shot === undefined || chosen.length !== 1) {
327
- console.error("pass --shot <id> with one of --retake, --new-picture or --animate. Nothing was sent.");
328
- process.exit(1);
391
+ fail({ code: "missing_input", message: "pass --shot <id> with one of --retake, --new-picture or --animate. Nothing was sent.",
392
+ fix: ["Pass --shot <id> with one of --retake, --new-picture or --animate; clipwright shots <run> lists the shots."] });
329
393
  }
330
394
  const operation = opts.retake === true ? { mode: "retake" }
331
395
  : opts.newPicture !== undefined ? { mode: "new_picture", description: opts.newPicture }
@@ -343,48 +407,46 @@ withCandidateOptions(program.command("candidate <run>")
343
407
  .addOption(maxCreditsOption())
344
408
  .action(async (run, opts) => {
345
409
  const request = candidateInput(opts);
346
- const quote = await client().quoteCandidate(run, request);
347
- console.error(`candidate of shot ${quote.shot_id} (${quote.unit}, take ${request.take}): ${quote.credits} credits; ` +
410
+ const sdk = client();
411
+ const quote = await sdk.quoteCandidate(run, request);
412
+ note(`candidate of shot ${quote.shot_id} (${quote.unit}, take ${request.take}): ${quote.credits} credits; ` +
348
413
  `usable in a revision until ${quote.usable_until}`);
349
414
  for (const warning of quote.warnings)
350
- console.error(`warning: ${warning}`);
415
+ warn(warning);
351
416
  if (opts.yes !== true) {
352
- console.error("Nothing was started; pass --yes to start it.");
353
- process.exit(1);
417
+ fail({ code: "confirmation_required", message: "Nothing was started; pass --yes to start it.", details: { credits: quote.credits },
418
+ resume: `${sameCommand()} --yes`,
419
+ fix: [`Show the user the ${quote.credits} credits; with their go-ahead, run the same command with --yes.`] });
354
420
  }
355
421
  let created;
356
422
  try {
357
- created = await client().createCandidate(run, { ...request, ...ceilingOf(opts) });
423
+ created = await startKeyed(() => sdk.createCandidate(run, { ...request, ...ceilingOf(opts) }));
358
424
  }
359
425
  catch (error) {
360
426
  if (!(error instanceof ClipwrightApiError))
361
427
  throw error;
362
428
  const failure = error.failure;
429
+ const commands = commandNames();
363
430
  if (failure.kind === "edit_ceiling_reached") {
364
- console.error(formatApiError(error));
365
- if (failure.limit === "in_flight") {
366
- for (const id of failure.runIds)
367
- console.error(`running: ${id}; follow it with "clipwright runs ${id}"`);
368
- }
369
- else {
370
- console.error(`${failure.counted} of ${failure.allowed} candidates of ${failure.rootRunId} are counted; ` +
371
- "no candidate of it can start, and support cannot raise this limit yet.");
372
- }
373
- process.exit(1);
431
+ const lines = failure.limit === "in_flight"
432
+ ? failure.runIds.map((id) => `running: ${id}; follow it with "clipwright runs ${id}"`)
433
+ : [`${failure.counted} of ${failure.allowed} candidates of ${failure.rootRunId} are counted; ` +
434
+ "no candidate of it can start, and support cannot raise this limit yet."];
435
+ fail({ ...apiFailureOf(error, commands), fix: lines }, [formatApiError(error), ...lines]);
374
436
  }
375
437
  if (failure.kind === "run_not_editable") {
376
- console.error(formatApiError(error));
377
- console.error(`if you made this candidate before, find it with "clipwright candidates ${run}"`);
378
- process.exit(1);
438
+ const line = `if you made this candidate before, find it with "clipwright candidates ${run}"`;
439
+ fail({ ...apiFailureOf(error, commands), fix: [line] }, [formatApiError(error), line]);
379
440
  }
380
441
  throw error;
381
442
  }
382
443
  console.log(JSON.stringify(created, null, 2));
383
444
  if (created.state === FAILED_STATE) {
384
- console.error(`run ${created.run_id} is ${created.state}; to try again, pass --take ${request.take + 1}`);
385
- process.exit(1);
445
+ fail({ code: "run_failed", message: `run ${created.run_id} is ${created.state}; to try again, pass --take ${request.take + 1}`,
446
+ run: created, details: { id: created.run_id, credits_charged: created.credits_charged },
447
+ fix: [`To try again, ask the user, then pass --take ${request.take + 1}: that is a new paid candidate.`] });
386
448
  }
387
- console.error(`follow it with "clipwright runs ${created.run_id}"; once it succeeded, "clipwright candidates ${run}" shows its preview`);
449
+ note(`follow it with "clipwright runs ${created.run_id}"; once it succeeded, "clipwright candidates ${run}" shows its preview`);
388
450
  });
389
451
  program.command("candidates <run>")
390
452
  .description("list the shot candidates of a run's family, oldest first, with state, charge and preview; free")
@@ -420,7 +482,9 @@ withActorOptions(program.command("quote-actor").description("estimate credits fo
420
482
  console.log(JSON.stringify(await client().quoteActor(actorInput(opts)), null, 2));
421
483
  });
422
484
  withActorOptions(program.command("create-actor").description("create a personal actor from a description (paid)")).addOption(maxCreditsOption()).action(async (opts) => {
423
- console.log(JSON.stringify(await client().createActor({ ...actorInput(opts), ...ceilingOf(opts) }), null, 2));
485
+ const sdk = client();
486
+ const input = { ...actorInput(opts), ...ceilingOf(opts) };
487
+ console.log(JSON.stringify(await startKeyed(() => sdk.createActor(input)), null, 2));
424
488
  });
425
489
  const withFacelessOptions = (command) => command
426
490
  .addOption(new Option("--script <text>", "narration, read as written").conflicts(["scriptFile", "brief"]))
@@ -428,7 +492,7 @@ const withFacelessOptions = (command) => command
428
492
  .option("--brief <text>", "what the video is about; the narration is written from it")
429
493
  .requiredOption("--duration <seconds>", "target length, 30 to 90 seconds")
430
494
  .option("--no-captions", "turn off burned-in captions (on by default)")
431
- .option("--voice <name>", `narration voice from "clipwright voices --skill make_faceless"; omitted = ${DEFAULT_FACELESS_VOICE}`)
495
+ .option("--voice <name>", `narration voice from "clipwright voices --skill make_faceless"; omitted = a voice of the script's language, else ${DEFAULT_FACELESS_VOICE}`)
432
496
  .option("--style-reference <url>", "public https image whose visual style the scenes follow")
433
497
  .option("--character-reference <url>", "public https image of a person or figure to keep across scenes");
434
498
  function facelessInput(opts) {
@@ -441,10 +505,19 @@ function facelessInput(opts) {
441
505
  };
442
506
  if (opts.brief !== undefined)
443
507
  return { ...common, input_mode: "brief", brief: opts.brief };
444
- const script = opts.scriptFile === undefined ? opts.script : readFileSync(opts.scriptFile, "utf8");
508
+ let script = opts.script;
509
+ if (opts.scriptFile !== undefined) {
510
+ try {
511
+ script = readFileSync(opts.scriptFile, "utf8");
512
+ }
513
+ catch (error) {
514
+ fail({ code: "file_unreadable", message: `${opts.scriptFile} cannot be read: ${error instanceof Error ? error.message : String(error)}`,
515
+ fix: ["Pass --script-file a readable text file."] });
516
+ }
517
+ }
445
518
  if (script === undefined) {
446
- console.error("pass one of --script, --script-file or --brief");
447
- process.exit(1);
519
+ fail({ code: "missing_input", message: "pass one of --script, --script-file or --brief",
520
+ fix: ["Pass the narration with --script or --script-file, or what the video is about with --brief."] });
448
521
  }
449
522
  return { ...common, input_mode: "script", script };
450
523
  }
@@ -452,16 +525,33 @@ withFacelessOptions(program.command("quote-faceless").description("estimate cred
452
525
  console.log(JSON.stringify(await client().quoteFaceless(facelessInput(opts)), null, 2));
453
526
  });
454
527
  withFacelessOptions(program.command("make-faceless").description("start a faceless video (paid); ends with its narration, 25 s to duration + 25%; prints the run"))
455
- .option("--retry <n>", "retry attempt number (forces a fresh run)", parseRetry)
456
- .addOption(maxCreditsOption())
528
+ .addOption(maxCreditsOption());
529
+ withWaitOptions(withAttemptOption(program.commands.at(-1), parseWholeNumber), true)
457
530
  .action(async (opts) => {
458
- const run = await client().startFaceless({ ...facelessInput(opts), ...ceilingOf(opts) }, { attempt: opts.retry });
531
+ const sdk = client();
532
+ const input = { ...facelessInput(opts), ...ceilingOf(opts) };
533
+ const attempt = attemptOf(opts);
534
+ const started = await startKeyed(() => sdk.startFaceless(input, { attempt }));
535
+ if (opts.wait !== true && opts.output === undefined) {
536
+ console.log(JSON.stringify(started, null, 2));
537
+ return;
538
+ }
539
+ const run = await waitUntilDone(sdk, "run", started.run_id, started, opts.timeout);
459
540
  console.log(JSON.stringify(run, null, 2));
541
+ failIfFailed(run.run_id, run, `To try again, ask the user, then run the same command with --attempt ${(attempt ?? 1) + 1}: that is a new paid run.`);
542
+ if (opts.output !== undefined) {
543
+ const url = run.final_output?.video_url;
544
+ if (url === undefined)
545
+ fail({ code: "no_file", message: `${run.run_id} succeeded without a file to save`, fix: [`Read it with clipwright get-run ${run.run_id}.`] });
546
+ await saveFile(url, opts.output, commandLine(["get-run", run.run_id, "--output", opts.output]));
547
+ }
460
548
  });
461
549
  program
462
550
  .command("delete-actor <id>")
463
- .description("delete a personal actor of this account")
464
- .action(async (id) => {
551
+ .description("delete a personal actor of this account; asks first at a terminal, needs --yes anywhere else")
552
+ .option("--yes", "confirm the deletion; it cannot be undone")
553
+ .action(async (id, opts) => {
554
+ await confirmDestructive(opts, `Delete the actor ${id}?`, ["delete-actor", id]);
465
555
  await client().deleteActor(id);
466
556
  console.log(JSON.stringify({ deleted: id }, null, 2));
467
557
  });
@@ -504,6 +594,16 @@ program
504
594
  console.log(formatVoices(voices));
505
595
  });
506
596
  registerWorkflowCommands(program, client);
597
+ const templates = new Map();
598
+ registerNativeCommands(program, { client, parse: parseWholeNumber, parseCredits: parseMaxCredits, templates });
599
+ program.command("guided")
600
+ .description("pick the way to make what the goal describes and print its quote and start commands (free, offline, no key)")
601
+ .requiredOption("--goal <text>", "what to make, in the user's words")
602
+ .addOption(new Option("--path <path>", "take this way instead of picking one from the goal").choices(GUIDE_PATHS))
603
+ .action((opts) => {
604
+ console.log(scrubKeys(JSON.stringify(guidedPlan(opts.goal, opts.path), null, 2)));
605
+ });
606
+ const commandNames = () => new Set(program.commands.map((command) => command.name()));
507
607
  export { program };
508
608
  const isDirectRun = () => {
509
609
  const entry = process.argv[1];
@@ -519,28 +619,22 @@ const isDirectRun = () => {
519
619
  if (isDirectRun())
520
620
  run();
521
621
  function run() {
522
- program.parseAsync().catch((error) => {
622
+ void main(process.argv);
623
+ }
624
+ export async function main(argv) {
625
+ try {
626
+ await program.parseAsync(argv);
627
+ }
628
+ catch (error) {
523
629
  if (error instanceof WorkflowFileError) {
524
- console.error(`error: ${error.message}`);
630
+ emitFailure({ code: "file_unreadable", message: error.message, retryable: false, fix: [error.message] }, [`error: ${error.message}`]);
525
631
  process.exitCode = 1;
526
632
  return;
527
633
  }
528
- if (error instanceof ClipwrightApiError) {
529
- console.error(formatApiError(error));
530
- process.exitCode = 1;
531
- return;
532
- }
533
- if (error instanceof ClipwrightResponseError) {
534
- console.error(`error: ${error.message}`);
535
- process.exitCode = 1;
536
- return;
537
- }
538
- const schema = formatSchemaError(error);
539
- if (schema !== undefined) {
540
- console.error(schema);
541
- process.exitCode = 1;
542
- return;
543
- }
544
- throw error;
545
- });
634
+ const known = failureOf(error, commandNames());
635
+ if (known === undefined)
636
+ throw error;
637
+ emitFailure(known.failure, known.prose);
638
+ process.exitCode = 1;
639
+ }
546
640
  }