@mediaruntime/cli 1.0.0 → 1.2.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/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.0 — 2026-08-19
4
+
5
+ - Add hosted recipe discovery, inspection, creation, immutable versioning, and archive
6
+ commands.
7
+ - Add `run --recipe <name[@version]>` with local-file upload, waiting, and safe ZIP
8
+ download behavior identical to inline output jobs.
9
+ - Keep recipe submission mutually exclusive with `--output` and `--preset`.
10
+ - Upgrade to `@mediaruntime/node` 1.2.0.
11
+
12
+ ## 1.1.0 — 2026-08-18
13
+
14
+ - Add unauthenticated `capabilities` and `presets list` discovery commands backed by the
15
+ live gateway contract.
16
+ - Add repeated `--preset <public-preset>` execution while preserving `-o` and `--output`
17
+ for the six frozen aliases.
18
+ - Resolve preset output types from the gateway's ordered public catalog instead of
19
+ copying engine preset metadata into the CLI.
20
+ - Upgrade to `@mediaruntime/node` 1.1.1 capability contracts.
21
+
3
22
  ## 1.0.0 — 2026-08-16
4
23
 
5
24
  - Declare the documented CLI surface stable under semantic versioning, including command
package/README.md CHANGED
@@ -4,7 +4,7 @@ Official command-line client for MediaRuntime. It submits media, waits for jobs,
4
4
  the canonical ZIP output bundle, inspects account jobs, and sends correctly signed
5
5
  synthetic webhooks to a local receiver.
6
6
 
7
- Status: stable `1.0.0`. The documented `1.x` command names, flags, JSON envelopes, exit
7
+ Status: stable `1.2.0`. The documented `1.x` command names, flags, JSON envelopes, exit
8
8
  codes, and credential precedence follow semantic versioning. Breaking changes require a
9
9
  new major version; additive commands and fields may ship in minor releases.
10
10
 
@@ -69,6 +69,51 @@ Supported frozen output aliases:
69
69
  - `audio.transcription`
70
70
  - `image.web`
71
71
 
72
+ Discover the live public catalog without signing in, then select an explicit preset when
73
+ an alias is not specific enough:
74
+
75
+ ```bash
76
+ mediaruntime capabilities
77
+ mediaruntime presets list
78
+ mediaruntime presets list --json
79
+
80
+ mediaruntime run ./launch.mp4 \
81
+ --preset dash_ladder_v1 \
82
+ --preset webm_vp9_1080p \
83
+ --download ./adaptive-and-vp9.zip
84
+ ```
85
+
86
+ `--preset` accepts only IDs in the gateway's current `publicPresets` catalog. The CLI
87
+ retrieves the catalog and supplies the preset's required output type automatically. Alias
88
+ and preset selections may be mixed and repeated in one command.
89
+
90
+ ## Hosted recipes
91
+
92
+ Hosted recipes are immutable account-scoped versions of a complete outputs, moderation,
93
+ and watermark policy. Discover the built-ins and your team's custom recipes, then run one
94
+ without copying configuration:
95
+
96
+ ```bash
97
+ mediaruntime recipes list
98
+ mediaruntime recipes get team-video --version 3
99
+ mediaruntime run ./launch.mp4 \
100
+ --recipe team-video@3 \
101
+ --download ./launch.zip
102
+ ```
103
+
104
+ Owners and admins can manage custom recipes from JSON files:
105
+
106
+ ```bash
107
+ mediaruntime recipes create --file ./recipe.json
108
+ mediaruntime recipes version team-video --file ./recipe-v2.json --expected 1
109
+ mediaruntime recipes archive team-video
110
+ ```
111
+
112
+ `recipe.json` contains `name`, optional `description`, and `template`; a version file may
113
+ contain either a complete object with `template` or the template itself. Versions are
114
+ immutable, and `--expected` prevents concurrent editors from silently overwriting one
115
+ another. `--recipe` cannot be combined with `--output` or `--preset`.
116
+
72
117
  Use `--json` for one compact, URL-redacted machine-readable result. A caller-provided
73
118
  `--idempotency-key` remains the durable deduplication mechanism across process restarts;
74
119
  the SDK-generated invocation key only protects retries inside one live command.
package/dist/cli.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ListJobsParams, JobPage, JobDetails, CreateJobParams, JobReceiptData, WaitForJobOptions } from '@mediaruntime/node';
1
+ import { Capabilities, ListJobsParams, JobPage, JobDetails, CreateJobParams, JobReceiptData, WaitForJobOptions, HostedRecipe, CreateRecipeParams, CreateRecipeVersionParams } from '@mediaruntime/node';
2
2
 
3
3
  interface StoredCredential {
4
4
  apiKey: string;
@@ -13,6 +13,10 @@ interface CredentialStore {
13
13
  delete(baseUrl: string): Promise<void>;
14
14
  }
15
15
 
16
+ interface CapabilitiesReadClient {
17
+ retrieve(): Promise<Capabilities>;
18
+ }
19
+
16
20
  interface JobsReadClient {
17
21
  list(params?: ListJobsParams): Promise<JobPage>;
18
22
  get(jobId: string): Promise<JobDetails>;
@@ -25,6 +29,16 @@ interface RunJobsClient {
25
29
  create(params: CreateJobParams): Promise<SubmittedJob>;
26
30
  }
27
31
 
32
+ interface RecipesClient {
33
+ list(): Promise<HostedRecipe[]>;
34
+ get(name: string, options?: {
35
+ version?: number;
36
+ }): Promise<HostedRecipe>;
37
+ create(params: CreateRecipeParams): Promise<HostedRecipe>;
38
+ createVersion(name: string, params: CreateRecipeVersionParams): Promise<HostedRecipe>;
39
+ archive(name: string): Promise<void>;
40
+ }
41
+
28
42
  declare const SUPPORTED_TRIGGER_EVENTS: readonly ["job.completed", "job.failed", "job.rejected"];
29
43
  type TriggerEventType = (typeof SUPPORTED_TRIGGER_EVENTS)[number];
30
44
  interface SyntheticEventOptions {
@@ -87,6 +101,8 @@ declare function runAuthCommand(args: string[], baseUrl: string, dependencies?:
87
101
  type CliJobsClient = RunJobsClient & JobsReadClient;
88
102
  interface CliClient {
89
103
  jobs: CliJobsClient;
104
+ capabilities: CapabilitiesReadClient;
105
+ recipes?: RecipesClient;
90
106
  }
91
107
  interface CliDependencies {
92
108
  createClient?(options: {
package/dist/cli.js CHANGED
@@ -358,6 +358,93 @@ async function runAuthCommand(args, baseUrl, dependencies = {}) {
358
358
  return runAuthStatusCommand(args.slice(1), baseUrl, dependencies);
359
359
  }
360
360
 
361
+ // src/commands/capabilities.ts
362
+ function cell(value) {
363
+ return value || "-";
364
+ }
365
+ function table(headings, rows) {
366
+ const widths = headings.map(
367
+ (heading, index) => Math.max(heading.length, ...rows.map((row) => row[index]?.length ?? 0))
368
+ );
369
+ const render = (row) => row.map((value, index) => value.padEnd(widths[index] ?? value.length)).join(" ").trimEnd();
370
+ return `${[
371
+ render(headings),
372
+ render(widths.map((width) => "-".repeat(width))),
373
+ ...rows.map(render)
374
+ ].join("\n")}
375
+ `;
376
+ }
377
+ function publicPresetRows(capabilities) {
378
+ return capabilities.publicPresets.map((name) => {
379
+ const preset = capabilities.presets[name];
380
+ if (!preset) {
381
+ throw new Error(`Gateway capability contract is missing public preset metadata for ${name}`);
382
+ }
383
+ return {
384
+ name,
385
+ outputType: preset.outputType,
386
+ tier: preset.baseTier,
387
+ sourceKinds: preset.sourceKinds,
388
+ artifacts: preset.artifacts,
389
+ description: preset.description,
390
+ codec: preset.codec ?? null,
391
+ container: preset.container ?? null
392
+ };
393
+ });
394
+ }
395
+ function parseJsonOnly(args, command) {
396
+ let json = false;
397
+ for (const argument of args) {
398
+ if (argument === "--json") json = true;
399
+ else throw new UsageError(`Unknown ${command} option: ${argument}`);
400
+ }
401
+ return json;
402
+ }
403
+ async function runCapabilitiesCommand(args, dependencies) {
404
+ const json = parseJsonOnly(args, "capabilities");
405
+ const capabilities = await dependencies.capabilities.retrieve();
406
+ if (json) {
407
+ dependencies.writeStdout(`${JSON.stringify(capabilities)}
408
+ `);
409
+ return 0;
410
+ }
411
+ const aliases = Object.entries(capabilities.outputAliases).map(([name, value]) => [
412
+ name,
413
+ value.type,
414
+ value.preset,
415
+ value.tier
416
+ ]);
417
+ dependencies.writeStdout(
418
+ `Public presets: ${capabilities.publicPresets.length}
419
+ Optional features: ${Object.keys(capabilities.features).sort().join(", ") || "none"}
420
+
421
+ ` + table(["ALIAS", "TYPE", "PRESET", "TIER"], aliases) + "\nRun `mediaruntime presets list` for the complete public preset catalog.\n"
422
+ );
423
+ return 0;
424
+ }
425
+ async function runPresetsCommand(args, dependencies) {
426
+ const subcommand = args[0];
427
+ if (subcommand !== "list") throw new UsageError("Usage: mediaruntime presets list [--json]");
428
+ const json = parseJsonOnly(args.slice(1), "presets list");
429
+ const capabilities = await dependencies.capabilities.retrieve();
430
+ const presets = publicPresetRows(capabilities);
431
+ if (json) dependencies.writeStdout(`${JSON.stringify({ presets })}
432
+ `);
433
+ else {
434
+ dependencies.writeStdout(table(
435
+ ["PRESET", "TYPE", "TIER", "INPUTS", "ARTIFACTS"],
436
+ presets.map((preset) => [
437
+ preset.name,
438
+ cell(preset.outputType),
439
+ cell(preset.tier),
440
+ preset.sourceKinds.join(","),
441
+ preset.artifacts.join(", ")
442
+ ])
443
+ ));
444
+ }
445
+ return 0;
446
+ }
447
+
361
448
  // src/commands/jobs.ts
362
449
  var UNSUCCESSFUL_TERMINAL_STATUSES = /* @__PURE__ */ new Set(["FAILED", "REJECTED", "PARTIAL"]);
363
450
  function optionValue(args, index, option) {
@@ -380,6 +467,7 @@ function detailsProjection(job) {
380
467
  retentionDays: job.bundle.retentionDays
381
468
  },
382
469
  media: job.media,
470
+ recipe: job.recipe,
383
471
  metadata: job.metadata,
384
472
  error: job.error,
385
473
  createdAt: job.createdAt,
@@ -400,7 +488,7 @@ function humanDetails(job) {
400
488
  return `${lines.join("\n")}
401
489
  `;
402
490
  }
403
- function cell(value) {
491
+ function cell2(value) {
404
492
  if (value === null || value === void 0 || value === "") return "-";
405
493
  return String(value);
406
494
  }
@@ -408,10 +496,10 @@ function humanList(page) {
408
496
  const rows = page.jobs.map((job) => [
409
497
  job.id,
410
498
  job.status,
411
- cell(job.tierBilled),
412
- cell(job.unitsTotal),
499
+ cell2(job.tierBilled),
500
+ cell2(job.unitsTotal),
413
501
  job.bundleAvailable ? "yes" : "no",
414
- cell(job.updatedAt)
502
+ cell2(job.updatedAt)
415
503
  ]);
416
504
  const headings = ["ID", "STATUS", "TIER", "UNITS", "BUNDLE", "UPDATED"];
417
505
  const widths = headings.map(
@@ -549,6 +637,7 @@ function parseRunOptions(args) {
549
637
  let source;
550
638
  const outputs = [];
551
639
  let metadata;
640
+ let recipe;
552
641
  let idempotencyKey;
553
642
  let wait = false;
554
643
  let timeoutMs;
@@ -558,7 +647,13 @@ function parseRunOptions(args) {
558
647
  for (let index = 0; index < args.length; index += 1) {
559
648
  const argument = args[index];
560
649
  if (argument === "--output" || argument === "-o") {
561
- outputs.push(optionValue2(args, index, argument));
650
+ outputs.push({ kind: "alias", value: optionValue2(args, index, argument) });
651
+ index += 1;
652
+ } else if (argument === "--preset") {
653
+ outputs.push({ kind: "preset", value: optionValue2(args, index, argument) });
654
+ index += 1;
655
+ } else if (argument === "--recipe") {
656
+ recipe = optionValue2(args, index, argument);
562
657
  index += 1;
563
658
  } else if (argument === "--metadata") {
564
659
  metadata = parseMetadata(optionValue2(args, index, argument));
@@ -591,15 +686,21 @@ function parseRunOptions(args) {
591
686
  throw new UsageError("run accepts exactly one source");
592
687
  }
593
688
  }
594
- if (!source) throw new UsageError("Usage: mediaruntime run <source> --output <alias> [--wait]");
595
- if (outputs.length === 0) throw new UsageError("run requires at least one --output");
596
- const unsupported = outputs.find((output) => !OUTPUT_ALIASES.has(output));
597
- if (unsupported) throw new UsageError(`Unsupported output alias: ${unsupported}`);
689
+ if (!source) {
690
+ throw new UsageError("Usage: mediaruntime run <source> (--recipe <name[@version]> | --output <alias> | --preset <name>) [--wait]");
691
+ }
692
+ if (recipe && outputs.length > 0) throw new UsageError("--recipe cannot be combined with --output or --preset");
693
+ if (!recipe && outputs.length === 0) throw new UsageError("run requires --recipe or at least one --output or --preset");
694
+ const unsupported = outputs.find(
695
+ (output2) => output2.kind === "alias" && !OUTPUT_ALIASES.has(output2.value)
696
+ );
697
+ if (unsupported) throw new UsageError(`Unsupported output alias: ${unsupported.value}`);
598
698
  if (force && !download) throw new UsageError("--force requires --download");
599
699
  if (timeoutMs !== void 0 && !wait) throw new UsageError("--timeout-ms requires --wait or --download");
600
700
  return {
601
701
  source,
602
702
  outputs,
703
+ ...recipe === void 0 ? {} : { recipe },
603
704
  ...metadata === void 0 ? {} : { metadata },
604
705
  ...idempotencyKey === void 0 ? {} : { idempotencyKey },
605
706
  wait,
@@ -609,6 +710,21 @@ function parseRunOptions(args) {
609
710
  json
610
711
  };
611
712
  }
713
+ async function resolveOutputs(selections, capabilitiesClient) {
714
+ if (!selections.some((selection) => selection.kind === "preset")) {
715
+ return selections.map((selection) => selection.value);
716
+ }
717
+ const capabilities = await capabilitiesClient.retrieve();
718
+ const publicPresets = new Set(capabilities.publicPresets);
719
+ return selections.map((selection) => {
720
+ if (selection.kind === "alias") return selection.value;
721
+ const preset = capabilities.presets[selection.value];
722
+ if (!publicPresets.has(selection.value) || !preset) {
723
+ throw new UsageError(`Unknown or non-public preset: ${selection.value}`);
724
+ }
725
+ return { type: preset.outputType, preset: selection.value };
726
+ });
727
+ }
612
728
  function receiptProjection(job) {
613
729
  return {
614
730
  id: job.id,
@@ -616,6 +732,7 @@ function receiptProjection(job) {
616
732
  tier: job.tier,
617
733
  requiredTier: job.requiredTier,
618
734
  outputs: job.outputs,
735
+ recipe: job.recipe,
619
736
  message: job.message
620
737
  };
621
738
  }
@@ -634,6 +751,7 @@ function detailsProjection2(job) {
634
751
  retentionDays: job.bundle.retentionDays
635
752
  },
636
753
  media: job.media,
754
+ recipe: job.recipe,
637
755
  metadata: job.metadata,
638
756
  error: job.error,
639
757
  createdAt: job.createdAt,
@@ -660,9 +778,11 @@ Bundle: ${job.bundle.available ? "available" : "unavailable"}${error}
660
778
  }
661
779
  async function runCommand(args, dependencies) {
662
780
  const options = parseRunOptions(args);
781
+ const outputs = options.recipe ? void 0 : await resolveOutputs(options.outputs, dependencies.capabilities);
663
782
  const params = {
664
783
  source: options.source,
665
- outputs: options.outputs,
784
+ ...outputs === void 0 ? {} : { outputs },
785
+ ...options.recipe === void 0 ? {} : { recipe: options.recipe },
666
786
  ...options.metadata === void 0 ? {} : { metadata: options.metadata },
667
787
  ...options.idempotencyKey === void 0 ? {} : { idempotencyKey: options.idempotencyKey }
668
788
  };
@@ -721,9 +841,145 @@ async function runCommand(args, dependencies) {
721
841
  }
722
842
  }
723
843
 
844
+ // src/commands/recipes.ts
845
+ import { readFile } from "fs/promises";
846
+ function optionValue3(args, index, option) {
847
+ const value = args[index + 1];
848
+ if (!value || value.startsWith("--")) throw new UsageError(`${option} requires a value`);
849
+ return value;
850
+ }
851
+ function positiveInteger(value, option) {
852
+ const parsed = Number(value);
853
+ if (!Number.isSafeInteger(parsed) || parsed < 1) {
854
+ throw new UsageError(`${option} must be a positive integer`);
855
+ }
856
+ return parsed;
857
+ }
858
+ async function recipeFile(path) {
859
+ let raw;
860
+ try {
861
+ raw = await readFile(path, "utf8");
862
+ } catch (error) {
863
+ throw new UsageError(`Could not read recipe file: ${path}`, { cause: error });
864
+ }
865
+ try {
866
+ const parsed = JSON.parse(raw);
867
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error();
868
+ return parsed;
869
+ } catch {
870
+ throw new UsageError("Recipe file must contain one JSON object");
871
+ }
872
+ }
873
+ function humanRecipe(recipe) {
874
+ const kind = recipe.builtIn ? "built-in" : "custom";
875
+ return `${recipe.reference}
876
+ ${recipe.description || "No description"}
877
+ Type: ${kind}
878
+ Status: ${recipe.status}
879
+ `;
880
+ }
881
+ function humanList2(recipes) {
882
+ const headings = ["REFERENCE", "TYPE", "DESCRIPTION"];
883
+ const rows = recipes.map((recipe) => [
884
+ recipe.reference,
885
+ recipe.builtIn ? "built-in" : "custom",
886
+ recipe.description || "-"
887
+ ]);
888
+ const widths = headings.map(
889
+ (heading, index) => Math.max(heading.length, ...rows.map((row) => row[index]?.length ?? 0))
890
+ );
891
+ const render = (row) => row.map((value, index) => value.padEnd(widths[index] ?? value.length)).join(" ").trimEnd();
892
+ return `${[render(headings), render(widths.map((width) => "-".repeat(width))), ...rows.map(render)].join("\n")}
893
+ `;
894
+ }
895
+ function output(recipe, json, write) {
896
+ write(json ? `${JSON.stringify(recipe)}
897
+ ` : humanRecipe(recipe));
898
+ }
899
+ async function runRecipesCommand(args, dependencies) {
900
+ const subcommand = args[0];
901
+ const rest = args.slice(1);
902
+ const json = rest.includes("--json");
903
+ if (subcommand === "list") {
904
+ if (rest.some((value) => value !== "--json")) throw new UsageError("Usage: mediaruntime recipes list [--json]");
905
+ const recipes = await dependencies.recipes.list();
906
+ dependencies.writeStdout(json ? `${JSON.stringify({ recipes })}
907
+ ` : humanList2(recipes));
908
+ return 0;
909
+ }
910
+ if (subcommand === "get") {
911
+ let name;
912
+ let version;
913
+ for (let index = 0; index < rest.length; index += 1) {
914
+ const value = rest[index];
915
+ if (value === "--version") {
916
+ version = positiveInteger(optionValue3(rest, index, value), value);
917
+ index += 1;
918
+ } else if (value !== "--json" && !name) name = value;
919
+ else if (value !== "--json") throw new UsageError("recipes get accepts one name");
920
+ }
921
+ if (!name) throw new UsageError("Usage: mediaruntime recipes get <name> [--version <n>]");
922
+ output(await dependencies.recipes.get(name, version ? { version } : {}), json, dependencies.writeStdout);
923
+ return 0;
924
+ }
925
+ if (subcommand === "create") {
926
+ let file;
927
+ for (let index = 0; index < rest.length; index += 1) {
928
+ if (rest[index] === "--file") {
929
+ file = optionValue3(rest, index, "--file");
930
+ index += 1;
931
+ } else if (rest[index] !== "--json") throw new UsageError(`Unknown recipes create option: ${rest[index]}`);
932
+ }
933
+ if (!file) throw new UsageError("Usage: mediaruntime recipes create --file <recipe.json>");
934
+ const value = await recipeFile(file);
935
+ if (typeof value.name !== "string" || typeof value.template !== "object") {
936
+ throw new UsageError("Recipe JSON requires name and template");
937
+ }
938
+ output(await dependencies.recipes.create(value), json, dependencies.writeStdout);
939
+ return 0;
940
+ }
941
+ if (subcommand === "version") {
942
+ let name;
943
+ let file;
944
+ let expected;
945
+ for (let index = 0; index < rest.length; index += 1) {
946
+ const value2 = rest[index];
947
+ if (value2 === "--file") {
948
+ file = optionValue3(rest, index, value2);
949
+ index += 1;
950
+ } else if (value2 === "--expected") {
951
+ expected = positiveInteger(optionValue3(rest, index, value2), value2);
952
+ index += 1;
953
+ } else if (value2 !== "--json" && !name) name = value2;
954
+ else if (value2 !== "--json") throw new UsageError(`Unknown recipes version option: ${value2}`);
955
+ }
956
+ if (!name || !file || !expected) {
957
+ throw new UsageError("Usage: mediaruntime recipes version <name> --file <recipe.json> --expected <n>");
958
+ }
959
+ const value = await recipeFile(file);
960
+ const template = value.template ?? value;
961
+ output(await dependencies.recipes.createVersion(name, {
962
+ expectedLatestVersion: expected,
963
+ ...typeof value.description === "string" ? { description: value.description } : {},
964
+ template
965
+ }), json, dependencies.writeStdout);
966
+ return 0;
967
+ }
968
+ if (subcommand === "archive") {
969
+ const values = rest.filter((value) => value !== "--json");
970
+ if (values.length !== 1) throw new UsageError("Usage: mediaruntime recipes archive <name>");
971
+ await dependencies.recipes.archive(values[0] ?? "");
972
+ dependencies.writeStdout(json ? `${JSON.stringify({ name: values[0], status: "archived" })}
973
+ ` : `Archived recipe ${values[0]}
974
+ `);
975
+ return 0;
976
+ }
977
+ throw new UsageError("Usage: mediaruntime recipes <list|get|create|version|archive>");
978
+ }
979
+
724
980
  // src/commands/trigger.ts
725
981
  import { randomBytes as randomBytes2, randomUUID } from "crypto";
726
- import { readFile } from "fs/promises";
982
+ import { readFile as readFile2 } from "fs/promises";
727
983
 
728
984
  // src/trigger/destination.ts
729
985
  function isLoopbackDestination(value) {
@@ -951,7 +1207,7 @@ async function runTriggerCommand(args, dependencies = {}) {
951
1207
  now: dependencies.now ?? Date.now,
952
1208
  randomUUID: dependencies.randomUUID ?? randomUUID,
953
1209
  randomBytes: dependencies.randomBytes ?? randomBytes2,
954
- readFile: dependencies.readFile ?? readFile,
1210
+ readFile: dependencies.readFile ?? readFile2,
955
1211
  writeStdout: dependencies.writeStdout ?? ((text) => process.stdout.write(text))
956
1212
  };
957
1213
  const secret = await resolveSecret(parsed, deps);
@@ -1040,13 +1296,16 @@ function createActivityIndicator(write, enabled) {
1040
1296
  }
1041
1297
 
1042
1298
  // src/cli.ts
1043
- var VERSION = "1.0.0";
1299
+ var VERSION = "1.2.0";
1044
1300
  var HELP = `MediaRuntime CLI
1045
1301
 
1046
1302
  Usage:
1047
- mediaruntime run <source> --output <alias> [--output <alias>] [--wait]
1303
+ mediaruntime run <source> (--recipe <name[@version]> | --output <alias> | --preset <name>) [...] [--wait]
1304
+ mediaruntime capabilities [--json]
1305
+ mediaruntime presets list [--json]
1048
1306
  mediaruntime jobs list [--status <status>] [--limit <n>] [--cursor <cursor>]
1049
1307
  mediaruntime jobs get <job_id> [--download <bundle.zip>] [--force]
1308
+ mediaruntime recipes <list|get|create|version|archive>
1050
1309
  mediaruntime trigger <job.completed|job.failed|job.rejected> --to <local-url>
1051
1310
  mediaruntime login [--no-browser]
1052
1311
  mediaruntime auth status
@@ -1228,12 +1487,24 @@ async function executeCli(argv, dependencies = {}) {
1228
1487
  if (command === "login") return await runLoginCommand(global.args.slice(1), authBaseUrl, authDependencies);
1229
1488
  if (command === "auth") return await runAuthCommand(global.args.slice(1), authBaseUrl, authDependencies);
1230
1489
  if (command === "logout") return await runLogoutCommand(global.args.slice(1), authBaseUrl, authDependencies);
1490
+ if (command === "capabilities" || command === "presets") {
1491
+ const publicClient = dependencies.createClient?.({
1492
+ ...baseUrl === void 0 ? {} : { baseUrl }
1493
+ }) ?? new MediaRuntime({
1494
+ ...baseUrl === void 0 ? {} : { baseUrl }
1495
+ });
1496
+ const publicDependencies = { capabilities: publicClient.capabilities, writeStdout };
1497
+ if (command === "capabilities") {
1498
+ return await runCapabilitiesCommand(global.args.slice(1), publicDependencies);
1499
+ }
1500
+ return await runPresetsCommand(global.args.slice(1), publicDependencies);
1501
+ }
1231
1502
  let apiKey = process.env.MEDIARUNTIME_API_KEY?.trim();
1232
1503
  if (!apiKey && (!dependencies.createClient || dependencies.credentialStore)) {
1233
1504
  apiKey = (await resolveCredential(authBaseUrl, authDependencies))?.apiKey;
1234
1505
  }
1235
1506
  if (!dependencies.createClient && !apiKey) {
1236
- throw new UsageError("Run mediaruntime login or set MEDIARUNTIME_API_KEY before using run or jobs");
1507
+ throw new UsageError("Run mediaruntime login or set MEDIARUNTIME_API_KEY before using this command");
1237
1508
  }
1238
1509
  const client = dependencies.createClient?.({
1239
1510
  ...baseUrl === void 0 ? {} : { baseUrl },
@@ -1245,6 +1516,7 @@ async function executeCli(argv, dependencies = {}) {
1245
1516
  const downloadBundle = dependencies.downloadBundle ?? downloadBundleAtomically;
1246
1517
  const commandDependencies = {
1247
1518
  jobs: client.jobs,
1519
+ capabilities: client.capabilities,
1248
1520
  writeStdout,
1249
1521
  downloadBundle,
1250
1522
  activity: createActivityIndicator(writeStderr, isStderrTTY && !json)
@@ -1253,6 +1525,13 @@ async function executeCli(argv, dependencies = {}) {
1253
1525
  if (command === "jobs") {
1254
1526
  return await runJobsCommand(global.args.slice(1), commandDependencies);
1255
1527
  }
1528
+ if (command === "recipes") {
1529
+ if (!client.recipes) throw new UsageError("This MediaRuntime client does not support hosted recipes");
1530
+ return await runRecipesCommand(global.args.slice(1), {
1531
+ recipes: client.recipes,
1532
+ writeStdout
1533
+ });
1534
+ }
1256
1535
  throw new UsageError(`Unknown command: ${command}`);
1257
1536
  } catch (error) {
1258
1537
  const exitCode = exitCodeFor(error);
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/errors.ts","../src/auth/api.ts","../src/commands/auth.ts","../src/auth/browser.ts","../src/auth/credential-store.ts","../src/commands/jobs.ts","../src/commands/run.ts","../src/commands/trigger.ts","../src/trigger/destination.ts","../src/trigger/event.ts","../src/trigger/signature.ts","../src/ui/activity.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { constants, realpathSync } from \"node:fs\";\nimport {\n access,\n link,\n rename,\n rm,\n} from \"node:fs/promises\";\nimport { createWriteStream } from \"node:fs\";\nimport { basename, dirname, resolve } from \"node:path\";\nimport { Readable, Transform } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { ReadableStream as NodeReadableStream } from \"node:stream/web\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n JobWaitTimeoutError,\n MediaRuntime,\n MediaRuntimeApiError,\n MediaRuntimeConnectionError,\n} from \"@mediaruntime/node\";\nimport { PRODUCTION_ORIGIN } from \"./auth/api.js\";\nimport type { CredentialStore } from \"./auth/credential-store.js\";\nimport {\n resolveCredential,\n runAuthCommand,\n runLoginCommand,\n runLogoutCommand,\n type AuthCommandDependencies,\n} from \"./commands/auth.js\";\nimport {\n runJobsCommand,\n type JobsReadClient,\n} from \"./commands/jobs.js\";\nimport {\n runCommand,\n type RunJobsClient,\n} from \"./commands/run.js\";\nimport { runTriggerCommand } from \"./commands/trigger.js\";\nimport { BundleDownloadError, CliError, UsageError } from \"./errors.js\";\nimport { isLoopbackDestination } from \"./trigger/destination.js\";\nimport { createActivityIndicator } from \"./ui/activity.js\";\n\nexport { parseTriggerArguments, runTriggerCommand } from \"./commands/trigger.js\";\nexport { createSyntheticTerminalEvent } from \"./trigger/event.js\";\nexport { signSyntheticWebhook } from \"./trigger/signature.js\";\nexport {\n resolveCredential,\n runAuthCommand,\n runAuthStatusCommand,\n runLoginCommand,\n runLogoutCommand,\n} from \"./commands/auth.js\";\n\nconst VERSION = \"1.0.0\";\nconst HELP = `MediaRuntime CLI\n\nUsage:\n mediaruntime run <source> --output <alias> [--output <alias>] [--wait]\n mediaruntime jobs list [--status <status>] [--limit <n>] [--cursor <cursor>]\n mediaruntime jobs get <job_id> [--download <bundle.zip>] [--force]\n mediaruntime trigger <job.completed|job.failed|job.rejected> --to <local-url>\n mediaruntime login [--no-browser]\n mediaruntime auth status\n mediaruntime logout [--local-only]\n\nGlobal options:\n --base-url <url> Developer override; normally leave unset\n --help Show help\n --version Show version\n\nRun/jobs options:\n --json Machine-readable, URL-redacted output\n\nAuthentication uses a secure login or MEDIARUNTIME_API_KEY.\n`;\n\ntype CliJobsClient = RunJobsClient & JobsReadClient;\n\nexport interface CliClient {\n jobs: CliJobsClient;\n}\n\nexport interface CliDependencies {\n createClient?(options: { baseUrl?: string; apiKey?: string }): CliClient;\n downloadBundle?(\n url: string,\n destination: string,\n options: {\n force: boolean;\n expectedSizeBytes?: number | null;\n expectedSha256?: string | null;\n },\n ): Promise<void>;\n writeStdout?(text: string): void;\n writeStderr?(text: string): void;\n isStderrTTY?: boolean;\n credentialStore?: CredentialStore;\n openBrowser?(url: string): Promise<void>;\n sleep?(milliseconds: number): Promise<void>;\n now?(): number;\n randomVerifier?(): string;\n}\n\nfunction isFileExistsError(error: unknown): boolean {\n return error instanceof Error && \"code\" in error && error.code === \"EEXIST\";\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function downloadBundleAtomically(\n url: string,\n destination: string,\n options: {\n force: boolean;\n expectedSizeBytes?: number | null;\n expectedSha256?: string | null;\n },\n): Promise<void> {\n const target = resolve(destination);\n if (!options.force && await exists(target)) {\n throw new BundleDownloadError(`Refusing to overwrite existing file: ${destination}`);\n }\n const temporary = resolve(\n dirname(target),\n `.${basename(target)}.${randomUUID()}.part`,\n );\n\n try {\n let response: Response;\n try {\n response = await fetch(url);\n } catch (error) {\n throw new BundleDownloadError(\"Bundle download failed before receiving a response\", { cause: error });\n }\n if (!response.ok) {\n await response.body?.cancel();\n throw new BundleDownloadError(`Bundle download failed with HTTP ${response.status}`);\n }\n if (!response.body) throw new BundleDownloadError(\"Bundle download returned an empty response body\");\n const hash = createHash(\"sha256\");\n let sizeBytes = 0;\n const integrity = new Transform({\n transform(chunk: Buffer, _encoding, callback) {\n sizeBytes += chunk.length;\n hash.update(chunk);\n callback(null, chunk);\n },\n });\n await pipeline(\n Readable.fromWeb(response.body as unknown as NodeReadableStream<Uint8Array>),\n integrity,\n createWriteStream(temporary, { flags: \"wx\", mode: 0o600 }),\n );\n const sha256 = hash.digest(\"hex\");\n if (options.expectedSizeBytes !== undefined && options.expectedSizeBytes !== null &&\n sizeBytes !== options.expectedSizeBytes) {\n throw new BundleDownloadError(\n `Bundle size mismatch: expected ${options.expectedSizeBytes} bytes, received ${sizeBytes}`,\n );\n }\n if (options.expectedSha256 && sha256 !== options.expectedSha256.toLowerCase()) {\n throw new BundleDownloadError(\"Bundle SHA-256 mismatch\");\n }\n\n if (options.force) {\n await rename(temporary, target);\n } else {\n try {\n // A hard link publishes the completed same-filesystem temporary file atomically\n // and fails rather than replacing a destination created during the download.\n await link(temporary, target);\n } catch (error) {\n if (isFileExistsError(error)) {\n throw new BundleDownloadError(`Refusing to overwrite existing file: ${destination}`);\n }\n throw error;\n }\n await rm(temporary);\n }\n } catch (error) {\n await rm(temporary, { force: true });\n if (error instanceof BundleDownloadError) throw error;\n throw new BundleDownloadError(`Could not write bundle to ${destination}`, { cause: error });\n }\n}\n\nfunction normalizeBaseUrl(raw: string): string {\n let value: URL;\n try {\n value = new URL(raw);\n } catch {\n throw new UsageError(\"--base-url must be an absolute HTTP(S) origin\");\n }\n if (value.username || value.password || value.search || value.hash || value.pathname !== \"/\") {\n throw new UsageError(\"--base-url must be an origin without credentials, path, query, or fragment\");\n }\n if (value.protocol !== \"https:\" && !(value.protocol === \"http:\" && isLoopbackDestination(value))) {\n throw new UsageError(\"--base-url must use HTTPS unless it points to loopback\");\n }\n return value.origin;\n}\n\nfunction extractGlobalOptions(argv: string[]): { baseUrl?: string; args: string[] } {\n const args = [...argv];\n let baseUrl: string | undefined;\n while (args[0] === \"--base-url\") {\n const value = args[1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(\"--base-url requires a value\");\n baseUrl = normalizeBaseUrl(value);\n args.splice(0, 2);\n }\n return { ...(baseUrl === undefined ? {} : { baseUrl }), args };\n}\n\nfunction safeApiError(error: MediaRuntimeApiError): Record<string, unknown> {\n return {\n name: error.name,\n message: error.message,\n code: error.code,\n status: error.status,\n retryable: error.retryable,\n requestId: error.requestId ?? null,\n field: error.field ?? null,\n };\n}\n\nfunction exitCodeFor(error: unknown): number {\n if (error instanceof CliError) return error.exitCode;\n if (error instanceof JobWaitTimeoutError) return 7;\n if (error instanceof MediaRuntimeConnectionError) return 5;\n if (error instanceof MediaRuntimeApiError) {\n if ([401, 402, 403].includes(error.status)) return 3;\n if (error.status >= 500) return 5;\n return 4;\n }\n if (error instanceof DOMException && error.name === \"AbortError\") return 130;\n if (error instanceof TypeError && /fetch|network|socket|connect/i.test(error.message)) return 5;\n return 1;\n}\n\nfunction safeError(error: unknown, exitCode: number): Record<string, unknown> {\n if (error instanceof MediaRuntimeApiError) return { ...safeApiError(error), exitCode };\n return {\n code: error instanceof CliError ? error.code : \"cli_error\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n exitCode,\n };\n}\n\nexport async function executeCli(\n argv: string[],\n dependencies: CliDependencies = {},\n): Promise<number> {\n const writeStdout = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const writeStderr = dependencies.writeStderr ?? ((text: string) => process.stderr.write(text));\n const json = argv.includes(\"--json\");\n const isStderrTTY = dependencies.isStderrTTY ??\n (dependencies.writeStderr === undefined && process.stderr.isTTY === true);\n try {\n const global = extractGlobalOptions(argv);\n const command = global.args[0];\n if (!command || command === \"--help\" || command === \"-h\") {\n writeStdout(HELP);\n return 0;\n }\n if (command === \"--version\" || command === \"-v\") {\n writeStdout(`${VERSION}\\n`);\n return 0;\n }\n if (command === \"trigger\") {\n return await runTriggerCommand(global.args.slice(1), { writeStdout });\n }\n\n const configuredBaseUrl = global.baseUrl ?? process.env.MEDIARUNTIME_API_URL;\n const baseUrl = configuredBaseUrl ? normalizeBaseUrl(configuredBaseUrl) : undefined;\n const authBaseUrl = baseUrl ?? PRODUCTION_ORIGIN;\n const authDependencies: AuthCommandDependencies = {\n ...(dependencies.credentialStore ? { credentialStore: dependencies.credentialStore } : {}),\n ...(dependencies.openBrowser ? { openBrowser: dependencies.openBrowser } : {}),\n ...(dependencies.sleep ? { sleep: dependencies.sleep } : {}),\n ...(dependencies.now ? { now: dependencies.now } : {}),\n ...(dependencies.randomVerifier ? { randomVerifier: dependencies.randomVerifier } : {}),\n writeStdout,\n };\n if (command === \"login\") return await runLoginCommand(global.args.slice(1), authBaseUrl, authDependencies);\n if (command === \"auth\") return await runAuthCommand(global.args.slice(1), authBaseUrl, authDependencies);\n if (command === \"logout\") return await runLogoutCommand(global.args.slice(1), authBaseUrl, authDependencies);\n\n let apiKey = process.env.MEDIARUNTIME_API_KEY?.trim();\n if (!apiKey && (!dependencies.createClient || dependencies.credentialStore)) {\n apiKey = (await resolveCredential(authBaseUrl, authDependencies))?.apiKey;\n }\n if (!dependencies.createClient && !apiKey) {\n throw new UsageError(\"Run mediaruntime login or set MEDIARUNTIME_API_KEY before using run or jobs\");\n }\n const client = dependencies.createClient?.({\n ...(baseUrl === undefined ? {} : { baseUrl }),\n ...(apiKey === undefined ? {} : { apiKey }),\n }) ?? new MediaRuntime({\n ...(baseUrl === undefined ? {} : { baseUrl }),\n ...(apiKey === undefined ? {} : { apiKey }),\n });\n const downloadBundle = dependencies.downloadBundle ?? downloadBundleAtomically;\n const commandDependencies = {\n jobs: client.jobs,\n writeStdout,\n downloadBundle,\n activity: createActivityIndicator(writeStderr, isStderrTTY && !json),\n };\n if (command === \"run\") return await runCommand(global.args.slice(1), commandDependencies);\n if (command === \"jobs\") {\n return await runJobsCommand(global.args.slice(1), commandDependencies);\n }\n throw new UsageError(`Unknown command: ${command}`);\n } catch (error) {\n const exitCode = exitCodeFor(error);\n if (json) {\n writeStderr(`${JSON.stringify({ error: safeError(error, exitCode) })}\\n`);\n } else {\n const requestId = error instanceof MediaRuntimeApiError && error.requestId\n ? ` (request ${error.requestId})`\n : \"\";\n writeStderr(`Error: ${error instanceof Error ? error.message : \"Unknown error\"}${requestId}\\n`);\n }\n return exitCode;\n }\n}\n\nlet isEntrypoint = false;\nif (process.argv[1] !== undefined) {\n try {\n // npm exposes binaries through a symlink. Resolve both sides so the installed command\n // executes while importing dist/cli.js in tests remains side-effect free.\n isEntrypoint = realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));\n } catch {\n isEntrypoint = false;\n }\n}\nif (isEntrypoint) process.exitCode = await executeCli(process.argv.slice(2));\n","export class CliError extends Error {\n readonly code: string;\n readonly exitCode: number;\n\n constructor(code: string, message: string, exitCode: number, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"CliError\";\n this.code = code;\n this.exitCode = exitCode;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class UsageError extends CliError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(\"usage_error\", message, 2, options);\n this.name = \"UsageError\";\n }\n}\n\nexport class TriggerDeliveryError extends CliError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(\"trigger_delivery_error\", message, 8, options);\n this.name = \"TriggerDeliveryError\";\n }\n}\n\nexport class BundleDownloadError extends CliError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(\"bundle_download_error\", message, 9, options);\n this.name = \"BundleDownloadError\";\n }\n}\n","import { CliError } from \"../errors.js\";\n\nexport const PRODUCTION_ORIGIN = \"https://mediaruntime.com\";\n\ninterface ErrorPayload {\n error?: unknown;\n detail?: unknown;\n}\n\nexport interface DeviceAuthorization {\n deviceCode: string;\n userCode: string;\n verificationUri: string;\n verificationUriComplete: string;\n expiresIn: number;\n interval: number;\n}\n\nexport interface IssuedCredential {\n apiKey: string;\n accountId: string;\n keyId: string;\n credentialType: \"cli\";\n}\n\nexport interface CredentialStatus {\n status: \"authenticated\";\n accountId: string;\n keyId: string;\n credentialType: \"cli\" | \"api_key\";\n}\n\nexport class AuthApiError extends CliError {\n readonly status: number;\n\n constructor(code: string, message: string, status: number) {\n super(code, message, status >= 500 ? 5 : 3);\n this.name = \"AuthApiError\";\n this.status = status;\n }\n}\n\nfunction endpoint(baseUrl: string, path: string): string {\n return `${baseUrl.replace(/\\/+$/, \"\")}/api/cli/auth/${path}`;\n}\n\nasync function responsePayload(response: Response): Promise<Record<string, unknown>> {\n try {\n const value: unknown = await response.json();\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? value as Record<string, unknown>\n : {};\n } catch {\n return {};\n }\n}\n\nasync function post(\n baseUrl: string,\n path: string,\n body: Record<string, unknown>,\n apiKey?: string,\n): Promise<Record<string, unknown>> {\n let response: Response;\n try {\n response = await fetch(endpoint(baseUrl, path), {\n method: \"POST\",\n redirect: \"error\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(apiKey ? { \"X-API-Key\": apiKey } : {}),\n },\n body: JSON.stringify(body),\n });\n } catch (error) {\n throw new CliError(\"auth_connection_error\", \"Could not reach MediaRuntime authentication\", 5, { cause: error });\n }\n const payload = await responsePayload(response);\n if (!response.ok) {\n const errorPayload = payload as ErrorPayload;\n throw new AuthApiError(\n typeof errorPayload.error === \"string\" ? errorPayload.error : \"authorization_failed\",\n typeof errorPayload.detail === \"string\" ? errorPayload.detail : `Authentication failed with HTTP ${response.status}`,\n response.status,\n );\n }\n return payload;\n}\n\nfunction requireString(payload: Record<string, unknown>, key: string): string {\n const value = payload[key];\n if (typeof value !== \"string\" || !value) throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned an invalid authentication response\", 5);\n return value;\n}\n\nexport async function startAuthorization(baseUrl: string, codeChallenge: string): Promise<DeviceAuthorization> {\n const payload = await post(baseUrl, \"start\", { codeChallenge, clientName: \"MediaRuntime CLI\" });\n return {\n deviceCode: requireString(payload, \"deviceCode\"),\n userCode: requireString(payload, \"userCode\"),\n verificationUri: requireString(payload, \"verificationUri\"),\n verificationUriComplete: requireString(payload, \"verificationUriComplete\"),\n expiresIn: Number(payload.expiresIn),\n interval: Number(payload.interval),\n };\n}\n\nexport async function exchangeAuthorization(baseUrl: string, deviceCode: string, codeVerifier: string): Promise<IssuedCredential> {\n const payload = await post(baseUrl, \"token\", { deviceCode, codeVerifier });\n const credentialType = requireString(payload, \"credentialType\");\n if (credentialType !== \"cli\") throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned the wrong credential type\", 5);\n return {\n apiKey: requireString(payload, \"apiKey\"),\n accountId: requireString(payload, \"accountId\"),\n keyId: requireString(payload, \"keyId\"),\n credentialType,\n };\n}\n\nexport async function inspectCredential(baseUrl: string, apiKey: string): Promise<CredentialStatus> {\n const payload = await post(baseUrl, \"status\", {}, apiKey);\n const credentialType = requireString(payload, \"credentialType\");\n if (credentialType !== \"cli\" && credentialType !== \"api_key\") {\n throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned the wrong credential type\", 5);\n }\n return {\n status: \"authenticated\",\n accountId: requireString(payload, \"accountId\"),\n keyId: requireString(payload, \"keyId\"),\n credentialType,\n };\n}\n\nexport async function revokeCredential(baseUrl: string, apiKey: string): Promise<void> {\n await post(baseUrl, \"revoke\", {}, apiKey);\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport {\n AuthApiError,\n exchangeAuthorization,\n inspectCredential,\n revokeCredential,\n startAuthorization,\n} from \"../auth/api.js\";\nimport { openBrowser } from \"../auth/browser.js\";\nimport {\n OsCredentialStore,\n type CredentialStore,\n type StoredCredential,\n} from \"../auth/credential-store.js\";\nimport { CliError, UsageError } from \"../errors.js\";\n\nexport interface AuthCommandDependencies {\n credentialStore?: CredentialStore;\n openBrowser?: (url: string) => Promise<void>;\n sleep?: (milliseconds: number) => Promise<void>;\n now?: () => number;\n randomVerifier?: () => string;\n writeStdout?: (text: string) => void;\n}\n\nconst defaultSleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));\n\nfunction verifierChallenge(verifier: string): string {\n return createHash(\"sha256\").update(verifier).digest(\"base64url\");\n}\n\nfunction defaultVerifier(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\nfunction store(dependencies: AuthCommandDependencies): CredentialStore {\n return dependencies.credentialStore ?? new OsCredentialStore();\n}\n\nfunction assertOnly(args: string[], allowed: string[]): void {\n const unexpected = args.find((arg) => !allowed.includes(arg));\n if (unexpected) throw new UsageError(`Unknown authentication option: ${unexpected}`);\n}\n\nexport async function resolveCredential(\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<{ apiKey: string; source: \"environment\" | \"keychain\"; stored?: StoredCredential } | null> {\n const environment = process.env.MEDIARUNTIME_API_KEY?.trim();\n if (environment) return { apiKey: environment, source: \"environment\" };\n const stored = await store(dependencies).get(baseUrl);\n return stored ? { apiKey: stored.apiKey, source: \"keychain\", stored } : null;\n}\n\nexport async function runLoginCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n assertOnly(args, [\"--no-browser\"]);\n const noBrowser = args.includes(\"--no-browser\");\n const write = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const existing = await store(dependencies).get(baseUrl);\n if (existing) {\n try {\n await inspectCredential(baseUrl, existing.apiKey);\n write(`Already logged in to ${baseUrl} (account ${existing.accountId}).\\n`);\n return 0;\n } catch (error) {\n if (!(error instanceof AuthApiError) || error.status >= 500) throw error;\n }\n }\n\n const verifier = dependencies.randomVerifier?.() ?? defaultVerifier();\n if (verifier.length < 43 || verifier.length > 128) {\n throw new CliError(\"invalid_verifier\", \"Generated PKCE verifier is invalid\", 1);\n }\n const authorization = await startAuthorization(baseUrl, verifierChallenge(verifier));\n if (!Number.isFinite(authorization.expiresIn) || authorization.expiresIn <= 0 ||\n !Number.isFinite(authorization.interval) || authorization.interval < 1) {\n throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned invalid authorization timing\", 5);\n }\n\n write(`Open this URL to authorize MediaRuntime CLI:\\n${authorization.verificationUriComplete}\\n\\n`);\n write(`Confirm code: ${authorization.userCode}\\n`);\n if (!noBrowser) await (dependencies.openBrowser ?? openBrowser)(authorization.verificationUriComplete);\n write(\"Waiting for browser approval…\\n\");\n\n const now = dependencies.now ?? Date.now;\n const sleep = dependencies.sleep ?? defaultSleep;\n const deadline = now() + authorization.expiresIn * 1000;\n let credential;\n while (now() < deadline) {\n try {\n credential = await exchangeAuthorization(baseUrl, authorization.deviceCode, verifier);\n break;\n } catch (error) {\n if (error instanceof AuthApiError && error.code === \"authorization_pending\") {\n await sleep(authorization.interval * 1000);\n continue;\n }\n throw error;\n }\n }\n if (!credential) throw new CliError(\"authorization_timeout\", \"Browser authorization expired; run mediaruntime login again\", 7);\n\n try {\n await inspectCredential(baseUrl, credential.apiKey);\n await store(dependencies).set({\n apiKey: credential.apiKey,\n accountId: credential.accountId,\n keyId: credential.keyId,\n baseUrl,\n createdAt: new Date(now()).toISOString(),\n });\n } catch (error) {\n await revokeCredential(baseUrl, credential.apiKey).catch(() => undefined);\n throw error;\n }\n\n write(`Logged in to ${baseUrl} (account ${credential.accountId}).\\n`);\n if (process.env.MEDIARUNTIME_API_KEY?.trim()) {\n write(\"MEDIARUNTIME_API_KEY is set and will take precedence over this login.\\n\");\n }\n return 0;\n}\n\nexport async function runAuthStatusCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n assertOnly(args, [\"--json\"]);\n const json = args.includes(\"--json\");\n const write = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const resolved = await resolveCredential(baseUrl, dependencies);\n if (!resolved) throw new CliError(\"authentication_required\", \"Run mediaruntime login or set MEDIARUNTIME_API_KEY\", 3);\n const status = await inspectCredential(baseUrl, resolved.apiKey);\n if (json) {\n write(`${JSON.stringify({ authenticated: true, source: resolved.source, ...status })}\\n`);\n } else {\n write(`Authenticated via ${resolved.source} (account ${status.accountId}, key ${status.keyId}).\\n`);\n }\n return 0;\n}\n\nexport async function runLogoutCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n assertOnly(args, [\"--local-only\"]);\n const localOnly = args.includes(\"--local-only\");\n const write = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const credentialStore = store(dependencies);\n const credential = await credentialStore.get(baseUrl);\n if (!credential) {\n write(`No stored login for ${baseUrl}.\\n`);\n if (process.env.MEDIARUNTIME_API_KEY?.trim()) write(\"MEDIARUNTIME_API_KEY remains active in this shell.\\n\");\n return 0;\n }\n if (!localOnly) await revokeCredential(baseUrl, credential.apiKey);\n await credentialStore.delete(baseUrl);\n write(localOnly ? \"Removed the local CLI login without server revocation.\\n\" : \"Logged out and revoked the CLI credential.\\n\");\n if (process.env.MEDIARUNTIME_API_KEY?.trim()) write(\"MEDIARUNTIME_API_KEY remains active in this shell.\\n\");\n return 0;\n}\n\nexport async function runAuthCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n const subcommand = args[0];\n if (subcommand !== \"status\") throw new UsageError(\"Usage: mediaruntime auth status [--json]\");\n return runAuthStatusCommand(args.slice(1), baseUrl, dependencies);\n}\n","import { spawn } from \"node:child_process\";\nimport { CliError } from \"../errors.js\";\n\nexport async function openBrowser(url: string): Promise<void> {\n const command = process.platform === \"darwin\"\n ? { executable: \"open\", args: [url] }\n : process.platform === \"win32\"\n ? { executable: \"rundll32\", args: [\"url.dll,FileProtocolHandler\", url] }\n : { executable: \"xdg-open\", args: [url] };\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command.executable, command.args, {\n detached: true,\n stdio: \"ignore\",\n });\n child.once(\"error\", (error) => reject(new CliError(\n \"browser_open_failed\",\n \"Could not open a browser; rerun with --no-browser and open the printed URL\",\n 2,\n { cause: error },\n )));\n child.once(\"spawn\", () => {\n child.unref();\n resolve();\n });\n });\n}\n","import { CliError } from \"../errors.js\";\n\nconst SERVICE = \"mediaruntime-cli\";\n\nexport interface StoredCredential {\n apiKey: string;\n accountId: string;\n keyId: string;\n baseUrl: string;\n createdAt: string;\n}\n\nexport interface CredentialStore {\n get(baseUrl: string): Promise<StoredCredential | null>;\n set(credential: StoredCredential): Promise<void>;\n delete(baseUrl: string): Promise<void>;\n}\n\nfunction vaultAccount(baseUrl: string): string {\n return new URL(baseUrl).host.toLowerCase();\n}\n\nfunction validCredential(value: unknown): value is StoredCredential {\n if (!value || typeof value !== \"object\") return false;\n const item = value as Record<string, unknown>;\n return typeof item.apiKey === \"string\" && item.apiKey.startsWith(\"sk_\") &&\n typeof item.accountId === \"string\" && item.accountId.length > 0 &&\n typeof item.keyId === \"string\" && item.keyId.length > 0 &&\n typeof item.baseUrl === \"string\" && item.baseUrl.length > 0 &&\n typeof item.createdAt === \"string\" && item.createdAt.length > 0;\n}\n\nasync function entry(baseUrl: string) {\n try {\n const { Entry } = await import(\"@napi-rs/keyring\");\n return new Entry(SERVICE, vaultAccount(baseUrl));\n } catch (error) {\n throw new CliError(\n \"credential_store_unavailable\",\n \"The operating-system credential vault is unavailable; use MEDIARUNTIME_API_KEY on this machine\",\n 2,\n { cause: error },\n );\n }\n}\n\nexport class OsCredentialStore implements CredentialStore {\n async get(baseUrl: string): Promise<StoredCredential | null> {\n try {\n const raw = (await entry(baseUrl)).getPassword();\n if (!raw) return null;\n const parsed: unknown = JSON.parse(raw);\n if (!validCredential(parsed) || parsed.baseUrl !== baseUrl) {\n throw new Error(\"Stored credential has an invalid shape\");\n }\n return parsed;\n } catch (error) {\n if (error instanceof SyntaxError || (error instanceof Error && error.message.includes(\"invalid shape\"))) {\n throw new CliError(\"credential_store_invalid\", \"The stored MediaRuntime credential is invalid; run mediaruntime logout --local-only\", 3);\n }\n if (error instanceof CliError) throw error;\n // Keyring implementations return a not-found error rather than null on some platforms.\n if (error instanceof Error && /not found|no entry|no matching|item.*exist/i.test(error.message)) return null;\n throw new CliError(\"credential_store_error\", \"Could not read the operating-system credential vault\", 2, { cause: error });\n }\n }\n\n async set(credential: StoredCredential): Promise<void> {\n try {\n (await entry(credential.baseUrl)).setPassword(JSON.stringify(credential));\n } catch (error) {\n if (error instanceof CliError) throw error;\n throw new CliError(\"credential_store_error\", \"Could not save the login in the operating-system credential vault\", 2, { cause: error });\n }\n }\n\n async delete(baseUrl: string): Promise<void> {\n try {\n (await entry(baseUrl)).deletePassword();\n } catch (error) {\n if (error instanceof CliError) throw error;\n if (error instanceof Error && /not found|no entry|no matching|item.*exist/i.test(error.message)) return;\n throw new CliError(\"credential_store_error\", \"Could not remove the login from the operating-system credential vault\", 2, { cause: error });\n }\n }\n}\n","import type { JobDetails, JobPage, JobStatus, ListJobsParams } from \"@mediaruntime/node\";\nimport { BundleDownloadError, UsageError } from \"../errors.js\";\n\nconst UNSUCCESSFUL_TERMINAL_STATUSES = new Set([\"FAILED\", \"REJECTED\", \"PARTIAL\"]);\n\nexport interface JobsReadClient {\n list(params?: ListJobsParams): Promise<JobPage>;\n get(jobId: string): Promise<JobDetails>;\n}\n\nexport interface JobsCommandDependencies {\n jobs: JobsReadClient;\n writeStdout(text: string): void;\n downloadBundle(\n url: string,\n destination: string,\n options: { force: boolean; expectedSizeBytes?: number | null; expectedSha256?: string | null },\n ): Promise<void>;\n}\n\nfunction optionValue(args: string[], index: number, option: string): string {\n const value = args[index + 1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(`${option} requires a value`);\n return value;\n}\n\nfunction detailsProjection(job: JobDetails): Record<string, unknown> {\n return {\n id: job.id,\n status: job.status,\n tier: job.tier,\n usage: job.usage,\n billing: job.billing,\n bundle: {\n available: job.bundle.available,\n expiresAt: job.bundle.expiresAt,\n sizeBytes: job.bundle.sizeBytes,\n sha256: job.bundle.sha256,\n retentionDays: job.bundle.retentionDays,\n },\n media: job.media,\n metadata: job.metadata,\n error: job.error,\n createdAt: job.createdAt,\n updatedAt: job.updatedAt,\n startedAt: job.startedAt,\n completedAt: job.completedAt,\n };\n}\n\nfunction humanDetails(job: JobDetails): string {\n const lines = [\n `Job: ${job.id}`,\n `Status: ${job.status}`,\n `Tier: ${job.tier.billed ?? job.tier.effective ?? job.tier.requested ?? \"-\"}`,\n `Bundle: ${job.bundle.available ? \"available\" : \"unavailable\"}`,\n ];\n if (job.bundle.sizeBytes !== null) lines.push(`Bundle size: ${job.bundle.sizeBytes} bytes`);\n if (job.error) lines.push(`Error: ${job.error}`);\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction cell(value: unknown): string {\n if (value === null || value === undefined || value === \"\") return \"-\";\n return String(value);\n}\n\nfunction humanList(page: JobPage): string {\n const rows = page.jobs.map((job) => [\n job.id,\n job.status,\n cell(job.tierBilled),\n cell(job.unitsTotal),\n job.bundleAvailable ? \"yes\" : \"no\",\n cell(job.updatedAt),\n ]);\n const headings = [\"ID\", \"STATUS\", \"TIER\", \"UNITS\", \"BUNDLE\", \"UPDATED\"];\n const widths = headings.map((heading, index) =>\n Math.max(heading.length, ...rows.map((row) => row[index]?.length ?? 0)),\n );\n const render = (row: string[]): string =>\n row.map((value, index) => value.padEnd(widths[index] ?? value.length)).join(\" \").trimEnd();\n const lines = [render(headings), render(widths.map((width) => \"-\".repeat(width))), ...rows.map(render)];\n if (page.nextCursor) lines.push(`Next cursor: ${page.nextCursor}`);\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nasync function listCommand(args: string[], dependencies: JobsCommandDependencies): Promise<number> {\n let status: string | undefined;\n let limit: number | undefined;\n let cursor: string | undefined;\n let json = false;\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--status\") {\n status = optionValue(args, index, argument).toUpperCase();\n index += 1;\n } else if (argument === \"--limit\") {\n const value = Number(optionValue(args, index, argument));\n if (!Number.isSafeInteger(value) || value < 1 || value > 100) {\n throw new UsageError(\"--limit must be an integer between 1 and 100\");\n }\n limit = value;\n index += 1;\n } else if (argument === \"--cursor\") {\n cursor = optionValue(args, index, argument);\n index += 1;\n } else if (argument === \"--json\") {\n json = true;\n } else {\n throw new UsageError(`Unknown jobs list option: ${argument}`);\n }\n }\n const params: ListJobsParams = {\n ...(status === undefined ? {} : { status: status as JobStatus }),\n ...(limit === undefined ? {} : { limit }),\n ...(cursor === undefined ? {} : { cursor }),\n };\n const page = await dependencies.jobs.list(params);\n dependencies.writeStdout(json ? `${JSON.stringify(page)}\\n` : humanList(page));\n return 0;\n}\n\nasync function getCommand(args: string[], dependencies: JobsCommandDependencies): Promise<number> {\n let jobId: string | undefined;\n let download: string | undefined;\n let force = false;\n let json = false;\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--download\") {\n download = optionValue(args, index, argument);\n index += 1;\n } else if (argument === \"--force\") {\n force = true;\n } else if (argument === \"--json\") {\n json = true;\n } else if (argument?.startsWith(\"-\")) {\n throw new UsageError(`Unknown jobs get option: ${argument}`);\n } else if (!jobId) {\n jobId = argument;\n } else {\n throw new UsageError(\"jobs get accepts exactly one job ID\");\n }\n }\n if (!jobId) throw new UsageError(\"Usage: mediaruntime jobs get <job_id>\");\n if (force && !download) throw new UsageError(\"--force requires --download\");\n const job = await dependencies.jobs.get(jobId);\n if (!json) dependencies.writeStdout(humanDetails(job));\n\n if (UNSUCCESSFUL_TERMINAL_STATUSES.has(String(job.status).toUpperCase())) {\n if (json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(job))}\\n`);\n return 6;\n }\n if (download) {\n if (String(job.status).toUpperCase() !== \"COMPLETED\" ||\n !job.bundle.available || !job.bundle.downloadUrl) {\n throw new BundleDownloadError(\"Bundle download requires a COMPLETED job with an available canonical bundle\");\n }\n try {\n await dependencies.downloadBundle(job.bundle.downloadUrl, download, {\n force,\n expectedSizeBytes: job.bundle.sizeBytes,\n expectedSha256: job.bundle.sha256,\n });\n } catch (error) {\n if (error instanceof BundleDownloadError) throw error;\n throw new BundleDownloadError(`Could not download bundle to ${download}`, { cause: error });\n }\n if (!json) dependencies.writeStdout(`Downloaded bundle to ${download}\\n`);\n }\n if (json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(job))}\\n`);\n return 0;\n}\n\nexport async function runJobsCommand(\n args: string[],\n dependencies: JobsCommandDependencies,\n): Promise<number> {\n const subcommand = args[0];\n if (subcommand === \"list\") return listCommand(args.slice(1), dependencies);\n if (subcommand === \"get\") return getCommand(args.slice(1), dependencies);\n throw new UsageError(\"Usage: mediaruntime jobs <list|get>\");\n}\n","import type {\n CreateJobParams,\n JobDetails,\n JobOutput,\n JobReceiptData,\n Metadata,\n OutputAlias,\n WaitForJobOptions,\n} from \"@mediaruntime/node\";\nimport { BundleDownloadError, UsageError } from \"../errors.js\";\nimport type { ActivityIndicator } from \"../ui/activity.js\";\n\nconst UNSUCCESSFUL_TERMINAL_STATUSES = new Set([\"FAILED\", \"REJECTED\", \"PARTIAL\"]);\nconst OUTPUT_ALIASES = new Set([\n \"video.web\",\n \"video.streaming\",\n \"video.social\",\n \"audio.web\",\n \"audio.transcription\",\n \"image.web\",\n]);\n\ninterface SubmittedJob extends JobReceiptData {\n wait(options?: WaitForJobOptions): Promise<JobDetails>;\n}\n\nexport interface RunJobsClient {\n create(params: CreateJobParams): Promise<SubmittedJob>;\n}\n\nexport interface RunCommandDependencies {\n jobs: RunJobsClient;\n writeStdout(text: string): void;\n activity: ActivityIndicator;\n downloadBundle(\n url: string,\n destination: string,\n options: { force: boolean; expectedSizeBytes?: number | null; expectedSha256?: string | null },\n ): Promise<void>;\n}\n\ninterface RunOptions {\n source: string;\n outputs: string[];\n metadata?: Metadata;\n idempotencyKey?: string;\n wait: boolean;\n timeoutMs?: number;\n download?: string;\n force: boolean;\n json: boolean;\n}\n\nfunction optionValue(args: string[], index: number, option: string): string {\n const value = args[index + 1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(`${option} requires a value`);\n return value;\n}\n\nfunction parseMetadata(value: string): Metadata {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value) as unknown;\n } catch {\n throw new UsageError(\"--metadata must be a valid JSON object\");\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new UsageError(\"--metadata must be a JSON object\");\n }\n return parsed as Metadata;\n}\n\nfunction parseRunOptions(args: string[]): RunOptions {\n let source: string | undefined;\n const outputs: string[] = [];\n let metadata: Metadata | undefined;\n let idempotencyKey: string | undefined;\n let wait = false;\n let timeoutMs: number | undefined;\n let download: string | undefined;\n let force = false;\n let json = false;\n\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--output\" || argument === \"-o\") {\n outputs.push(optionValue(args, index, argument));\n index += 1;\n } else if (argument === \"--metadata\") {\n metadata = parseMetadata(optionValue(args, index, argument));\n index += 1;\n } else if (argument === \"--idempotency-key\") {\n idempotencyKey = optionValue(args, index, argument);\n index += 1;\n } else if (argument === \"--wait\") {\n wait = true;\n } else if (argument === \"--timeout-ms\") {\n const value = Number(optionValue(args, index, argument));\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new UsageError(\"--timeout-ms must be a positive integer\");\n }\n timeoutMs = value;\n index += 1;\n } else if (argument === \"--download\") {\n download = optionValue(args, index, argument);\n wait = true;\n index += 1;\n } else if (argument === \"--force\") {\n force = true;\n } else if (argument === \"--json\") {\n json = true;\n } else if (argument?.startsWith(\"-\")) {\n throw new UsageError(`Unknown run option: ${argument}`);\n } else if (source === undefined) {\n source = argument;\n } else {\n throw new UsageError(\"run accepts exactly one source\");\n }\n }\n\n if (!source) throw new UsageError(\"Usage: mediaruntime run <source> --output <alias> [--wait]\");\n if (outputs.length === 0) throw new UsageError(\"run requires at least one --output\");\n const unsupported = outputs.find((output) => !OUTPUT_ALIASES.has(output));\n if (unsupported) throw new UsageError(`Unsupported output alias: ${unsupported}`);\n if (force && !download) throw new UsageError(\"--force requires --download\");\n if (timeoutMs !== undefined && !wait) throw new UsageError(\"--timeout-ms requires --wait or --download\");\n return {\n source,\n outputs,\n ...(metadata === undefined ? {} : { metadata }),\n ...(idempotencyKey === undefined ? {} : { idempotencyKey }),\n wait,\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n ...(download === undefined ? {} : { download }),\n force,\n json,\n };\n}\n\nfunction receiptProjection(job: SubmittedJob): JobReceiptData {\n return {\n id: job.id,\n status: job.status,\n tier: job.tier,\n requiredTier: job.requiredTier,\n outputs: job.outputs,\n message: job.message,\n };\n}\n\nfunction detailsProjection(job: JobDetails): Record<string, unknown> {\n return {\n id: job.id,\n status: job.status,\n tier: job.tier,\n usage: job.usage,\n billing: job.billing,\n bundle: {\n available: job.bundle.available,\n expiresAt: job.bundle.expiresAt,\n sizeBytes: job.bundle.sizeBytes,\n sha256: job.bundle.sha256,\n retentionDays: job.bundle.retentionDays,\n },\n media: job.media,\n metadata: job.metadata,\n error: job.error,\n createdAt: job.createdAt,\n updatedAt: job.updatedAt,\n startedAt: job.startedAt,\n completedAt: job.completedAt,\n };\n}\n\nfunction writeHumanReceipt(job: SubmittedJob, write: (text: string) => void): void {\n write(`Job: ${job.id}\\nStatus: ${job.status}\\nTier: ${job.tier || \"-\"}\\n`);\n}\n\nfunction writeHumanDetails(job: JobDetails, write: (text: string) => void): void {\n const error = job.error ? `\\nError: ${job.error}` : \"\";\n write(\n `Job: ${job.id}\\nStatus: ${job.status}\\n` +\n `Bundle: ${job.bundle.available ? \"available\" : \"unavailable\"}${error}\\n`,\n );\n}\n\nexport async function runCommand(\n args: string[],\n dependencies: RunCommandDependencies,\n): Promise<number> {\n const options = parseRunOptions(args);\n const params: CreateJobParams = {\n source: options.source,\n outputs: options.outputs as Array<OutputAlias | JobOutput>,\n ...(options.metadata === undefined ? {} : { metadata: options.metadata }),\n ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),\n };\n const isLocalSource = !/^(?:https?|gs):\\/\\//i.test(options.source);\n dependencies.activity.start(\n isLocalSource ? \"Uploading local source and creating job…\" : \"Creating job…\",\n );\n\n try {\n const submitted = await dependencies.jobs.create(params);\n\n if (!options.wait) {\n dependencies.activity.stop();\n if (options.json) dependencies.writeStdout(`${JSON.stringify(receiptProjection(submitted))}\\n`);\n else writeHumanReceipt(submitted, dependencies.writeStdout);\n return UNSUCCESSFUL_TERMINAL_STATUSES.has(String(submitted.status).toUpperCase()) ? 6 : 0;\n }\n\n dependencies.activity.update(`Waiting for job ${submitted.id} to complete…`);\n const details = await submitted.wait(\n options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs },\n );\n if (String(details.status).toUpperCase() !== \"COMPLETED\") {\n dependencies.activity.stop();\n if (!options.json) writeHumanDetails(details, dependencies.writeStdout);\n if (options.json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(details))}\\n`);\n return 6;\n }\n if (options.download) {\n const url = details.bundle.downloadUrl;\n if (!details.bundle.available || !url) {\n throw new BundleDownloadError(\"Completed job does not have an available canonical bundle\");\n }\n dependencies.activity.update(\"Downloading and verifying ZIP bundle…\");\n try {\n await dependencies.downloadBundle(url, options.download, {\n force: options.force,\n expectedSizeBytes: details.bundle.sizeBytes,\n expectedSha256: details.bundle.sha256,\n });\n } catch (error) {\n if (error instanceof BundleDownloadError) throw error;\n throw new BundleDownloadError(`Could not download bundle to ${options.download}`, { cause: error });\n }\n }\n dependencies.activity.stop();\n if (!options.json) {\n writeHumanDetails(details, dependencies.writeStdout);\n if (options.download) dependencies.writeStdout(`Downloaded bundle to ${options.download}\\n`);\n }\n if (options.json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(details))}\\n`);\n return 0;\n } finally {\n dependencies.activity.stop();\n }\n}\n","import { randomBytes, randomUUID } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\n\nimport { parseLocalDestination } from \"../trigger/destination.js\";\nimport {\n SUPPORTED_TRIGGER_EVENTS,\n createSyntheticTerminalEvent,\n isTriggerEventType,\n type TriggerEventType,\n} from \"../trigger/event.js\";\nimport { signSyntheticWebhook } from \"../trigger/signature.js\";\nimport { TriggerDeliveryError, UsageError } from \"../errors.js\";\n\nexport interface TriggerCommandDependencies {\n env?: Readonly<Record<string, string | undefined>>;\n fetch?: typeof globalThis.fetch;\n now?: () => number;\n randomUUID?: () => string;\n randomBytes?: (size: number) => Uint8Array;\n readFile?: (path: string, encoding: \"utf8\") => Promise<string>;\n writeStdout?: (text: string) => void;\n}\n\ninterface TriggerArguments {\n type: TriggerEventType;\n destination: URL;\n secretFile?: string;\n generateSecret: boolean;\n jobId?: string;\n accountId?: string;\n json: boolean;\n}\n\nfunction requireOptionValue(args: string[], index: number, option: string): string {\n const value = args[index + 1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(`${option} requires a value`);\n return value;\n}\n\nexport function parseTriggerArguments(args: string[]): TriggerArguments {\n const typeValue = args[0];\n if (!typeValue || typeValue.startsWith(\"--\")) {\n throw new UsageError(\n `trigger requires an event type: ${SUPPORTED_TRIGGER_EVENTS.join(\", \")}`,\n );\n }\n if (!isTriggerEventType(typeValue)) {\n throw new UsageError(\n `Unsupported trigger event ${JSON.stringify(typeValue)}; expected ${SUPPORTED_TRIGGER_EVENTS.join(\", \")}`,\n );\n }\n\n let to: string | undefined;\n let secretFile: string | undefined;\n let generateSecret = false;\n let jobId: string | undefined;\n let accountId: string | undefined;\n let json = false;\n for (let index = 1; index < args.length; index += 1) {\n const option = args[index];\n if (!option) continue;\n if (option === \"--generate-secret\") {\n generateSecret = true;\n continue;\n }\n if (option === \"--json\") {\n json = true;\n continue;\n }\n if ([\"--to\", \"--secret-file\", \"--job-id\", \"--account-id\"].includes(option)) {\n const value = requireOptionValue(args, index, option);\n index += 1;\n if (option === \"--to\") to = value;\n else if (option === \"--secret-file\") secretFile = value;\n else if (option === \"--job-id\") jobId = value;\n else accountId = value;\n continue;\n }\n throw new UsageError(`Unknown trigger option: ${option}`);\n }\n\n if (!to) throw new UsageError(\"trigger requires an explicit --to local URL\");\n if (generateSecret && secretFile) {\n throw new UsageError(\"--generate-secret and --secret-file are mutually exclusive\");\n }\n if (generateSecret && json) {\n throw new UsageError(\"--generate-secret and --json are mutually exclusive\");\n }\n if (jobId !== undefined && !jobId.trim()) throw new UsageError(\"--job-id must not be empty\");\n if (accountId !== undefined && !accountId.trim()) {\n throw new UsageError(\"--account-id must not be empty\");\n }\n return {\n type: typeValue,\n destination: parseLocalDestination(to),\n ...(secretFile === undefined ? {} : { secretFile }),\n generateSecret,\n ...(jobId === undefined ? {} : { jobId: jobId.trim() }),\n ...(accountId === undefined ? {} : { accountId: accountId.trim() }),\n json,\n };\n}\n\nasync function resolveSecret(\n args: TriggerArguments,\n dependencies: Required<\n Pick<TriggerCommandDependencies, \"env\" | \"randomBytes\" | \"readFile\" | \"writeStdout\">\n >,\n): Promise<string> {\n if (args.generateSecret) {\n const generated = Buffer.from(dependencies.randomBytes(32)).toString(\"base64url\");\n dependencies.writeStdout(\n `Generated webhook secret (configure the local receiver with this value): ${generated}\\n`,\n );\n return generated;\n }\n let secret: string | undefined;\n if (args.secretFile) {\n try {\n secret = await dependencies.readFile(args.secretFile, \"utf8\");\n } catch (error) {\n throw new UsageError(`Could not read webhook secret file: ${args.secretFile}`, { cause: error });\n }\n } else {\n secret = dependencies.env.MEDIARUNTIME_WEBHOOK_SECRET;\n }\n const normalized = secret?.trim();\n if (!normalized) {\n throw new UsageError(\n \"Set MEDIARUNTIME_WEBHOOK_SECRET, pass --secret-file, or explicitly use --generate-secret\",\n );\n }\n return normalized;\n}\n\nexport async function runTriggerCommand(\n args: string[],\n dependencies: TriggerCommandDependencies = {},\n): Promise<number> {\n const parsed = parseTriggerArguments(args);\n const deps = {\n env: dependencies.env ?? process.env,\n fetch: dependencies.fetch ?? globalThis.fetch,\n now: dependencies.now ?? Date.now,\n randomUUID: dependencies.randomUUID ?? randomUUID,\n randomBytes: dependencies.randomBytes ?? randomBytes,\n readFile: dependencies.readFile ?? readFile,\n writeStdout: dependencies.writeStdout ?? ((text: string) => process.stdout.write(text)),\n };\n const secret = await resolveSecret(parsed, deps);\n const timestamp = Math.floor(deps.now() / 1000);\n const unique = deps.randomUUID();\n const eventId = `evt_cli_${unique}`;\n const jobId = parsed.jobId ?? `job_cli_${unique}`;\n const accountId = parsed.accountId ?? \"acc_cli_local\";\n const payload = createSyntheticTerminalEvent(parsed.type, {\n eventId,\n jobId,\n accountId,\n timestamp,\n });\n const signed = signSyntheticWebhook(payload, { eventId, timestamp, secret });\n\n const response = await deps.fetch(parsed.destination, {\n method: \"POST\",\n headers: signed.headers,\n body: signed.body,\n redirect: \"manual\",\n signal: AbortSignal.timeout(10_000),\n });\n if (!response.ok) {\n throw new TriggerDeliveryError(\n `Local webhook endpoint returned HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : \"\"}`,\n );\n }\n if (parsed.json) {\n deps.writeStdout(`${JSON.stringify({\n eventId,\n type: parsed.type,\n jobId,\n status: payload.status,\n destination: parsed.destination.href,\n httpStatus: response.status,\n })}\\n`);\n } else {\n deps.writeStdout(\n `Sent synthetic ${parsed.type} event ${eventId} to ${parsed.destination.href} (HTTP ${response.status})\\n`,\n );\n }\n return 0;\n}\n","import { UsageError } from \"../errors.js\";\n\nexport function isLoopbackDestination(value: URL): boolean {\n let hostname = value.hostname.toLowerCase();\n if (hostname.endsWith(\".\")) hostname = hostname.slice(0, -1);\n if (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n hostname = hostname.slice(1, -1);\n }\n if (hostname === \"localhost\" || hostname === \"::1\" || hostname === \"0:0:0:0:0:0:0:1\") {\n return true;\n }\n\n const octets = hostname.split(\".\");\n if (octets.length !== 4 || octets.some((part) => !/^\\d{1,3}$/.test(part))) return false;\n const numbers = octets.map(Number);\n return numbers[0] === 127 && numbers.every((part) => part >= 0 && part <= 255);\n}\n\nexport function parseLocalDestination(raw: string): URL {\n let destination: URL;\n try {\n destination = new URL(raw);\n } catch {\n throw new UsageError(\"--to must be an absolute local HTTP(S) URL\");\n }\n if (destination.protocol !== \"http:\" && destination.protocol !== \"https:\") {\n throw new UsageError(\"--to must use http:// or https://\");\n }\n if (destination.username || destination.password) {\n throw new UsageError(\"--to must not contain URL credentials\");\n }\n if (!isLoopbackDestination(destination)) {\n throw new UsageError(\n \"trigger only sends to loopback destinations (localhost, 127.0.0.0/8, or ::1)\",\n );\n }\n return destination;\n}\n","export const SUPPORTED_TRIGGER_EVENTS = [\n \"job.completed\",\n \"job.failed\",\n \"job.rejected\",\n] as const;\n\nexport type TriggerEventType = (typeof SUPPORTED_TRIGGER_EVENTS)[number];\n\nexport function isTriggerEventType(value: string): value is TriggerEventType {\n return (SUPPORTED_TRIGGER_EVENTS as readonly string[]).includes(value);\n}\n\nexport interface SyntheticEventOptions {\n eventId: string;\n jobId: string;\n accountId: string;\n timestamp: number;\n}\n\nexport function createSyntheticTerminalEvent(\n type: TriggerEventType,\n options: SyntheticEventOptions,\n): Record<string, unknown> {\n const status = type.slice(\"job.\".length).toUpperCase();\n const occurredAt = new Date(options.timestamp * 1000).toISOString();\n const base = {\n event_id: options.eventId,\n job_id: options.jobId,\n account_id: options.accountId,\n status,\n };\n\n if (type === \"job.completed\") {\n const expiresAt = new Date((options.timestamp + 7 * 24 * 60 * 60) * 1000).toISOString();\n return {\n ...base,\n completedAt: occurredAt,\n delivery: {\n mode: \"PULL\",\n retentionDays: 7,\n expiresAt,\n bundle: {\n type: \"zip\",\n filename: `${options.jobId}_outputs.zip`,\n size_bytes: 0,\n sha256: \"0\".repeat(64),\n download: {\n url: `http://127.0.0.1/__mediaruntime_synthetic__/${encodeURIComponent(options.jobId)}.zip`,\n expiresAt,\n },\n },\n layout: \"bundle_relative_v1\",\n deliverables: [],\n manifests: {},\n },\n billing: { status: \"PAID\" },\n usage: { units_total: 0 },\n meta: { synthetic: true, request_metadata: {} },\n };\n }\n\n const failed = type === \"job.failed\";\n return {\n ...base,\n [failed ? \"failedAt\" : \"rejectedAt\"]: occurredAt,\n delivery: { mode: \"NONE\" },\n billing: { status: \"RELEASED\" },\n error: {\n code: failed ? \"SYNTHETIC_ENGINE_FAILED\" : \"SYNTHETIC_REJECTED\",\n message: `Synthetic ${type} event from the MediaRuntime CLI`,\n },\n meta: { synthetic: true, request_metadata: {} },\n };\n}\n","import { createHmac } from \"node:crypto\";\n\nexport const WEBHOOK_HEADERS = {\n id: \"X-Transcoder-Id\",\n timestamp: \"X-Transcoder-Timestamp\",\n signature: \"X-Transcoder-Signature\",\n} as const;\n\nexport interface SignedWebhook {\n body: string;\n headers: Record<string, string>;\n}\n\nexport function signSyntheticWebhook(\n payload: Readonly<Record<string, unknown>>,\n options: { eventId: string; timestamp: number; secret: string },\n): SignedWebhook {\n if (!options.eventId.trim()) throw new Error(\"Webhook event ID must not be empty\");\n if (!Number.isInteger(options.timestamp) || options.timestamp < 0) {\n throw new Error(\"Webhook timestamp must be a non-negative integer\");\n }\n if (!options.secret) throw new Error(\"Webhook secret must not be empty\");\n\n // JSON is serialized once. These exact bytes are both signed and sent.\n const body = JSON.stringify(payload);\n const bodyBytes = Buffer.from(body, \"utf8\");\n const prefix = Buffer.from(`${options.timestamp}.${options.eventId}.`, \"utf8\");\n const digest = createHmac(\"sha256\", options.secret)\n .update(prefix)\n .update(bodyBytes)\n .digest(\"hex\");\n\n return {\n body,\n headers: {\n \"Content-Type\": \"application/json\",\n [WEBHOOK_HEADERS.id]: options.eventId,\n [WEBHOOK_HEADERS.timestamp]: String(options.timestamp),\n [WEBHOOK_HEADERS.signature]: `t=${options.timestamp},v1=${digest}`,\n },\n };\n}\n","const FRAMES = [\"⣋\", \"⣙\", \"⣹\", \"⣸\", \"⣼\", \"⣴\", \"⣦\", \"⣧\", \"⣇\", \"⣏\"];\nconst CLEAR_LINE = \"\\r\\u001b[2K\";\n\nexport interface ActivityIndicator {\n start(message: string): void;\n update(message: string): void;\n stop(): void;\n}\n\nexport function createActivityIndicator(\n write: (text: string) => void,\n enabled: boolean,\n): ActivityIndicator {\n let timer: ReturnType<typeof setInterval> | undefined;\n let frameIndex = 0;\n let message = \"\";\n let startedAt = 0;\n\n const render = (): void => {\n if (!timer && startedAt === 0) return;\n const elapsedSeconds = Math.max(0, Math.floor((Date.now() - startedAt) / 1000));\n const elapsed = elapsedSeconds > 0 ? ` (${elapsedSeconds}s)` : \"\";\n write(`${CLEAR_LINE}${FRAMES[frameIndex % FRAMES.length]} ${message}${elapsed}`);\n frameIndex += 1;\n };\n\n return {\n start(nextMessage) {\n if (!enabled) return;\n if (timer) clearInterval(timer);\n message = nextMessage;\n startedAt = Date.now();\n frameIndex = 0;\n render();\n timer = setInterval(render, 80);\n timer.unref?.();\n },\n update(nextMessage) {\n if (!enabled || startedAt === 0) return;\n message = nextMessage;\n render();\n },\n stop() {\n if (!enabled || startedAt === 0) return;\n if (timer) clearInterval(timer);\n timer = undefined;\n startedAt = 0;\n write(CLEAR_LINE);\n },\n };\n}\n"],"mappings":";;;AAAA,SAAS,cAAAA,aAAY,cAAAC,mBAAkB;AACvC,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB;AAClC,SAAS,UAAU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AAe,aAAa,QAAQ,KAAK,CAAC,CAAC,MAAM,aAAa,cAAc,YAAY,GAAG,CAAC;AAAA,EAC9F,QAAQ;AACN,mBAAe;AAAA,EACjB;AACF;AACA,IAAI,aAAc,SAAQ,WAAW,MAAM,WAAW,QAAQ,KAAK,MAAM,CAAC,CAAC;","names":["createHash","randomUUID","resolve","resolve","UNSUCCESSFUL_TERMINAL_STATUSES","optionValue","detailsProjection","randomBytes","randomBytes","randomUUID","createHash"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/errors.ts","../src/auth/api.ts","../src/commands/auth.ts","../src/auth/browser.ts","../src/auth/credential-store.ts","../src/commands/capabilities.ts","../src/commands/jobs.ts","../src/commands/run.ts","../src/commands/recipes.ts","../src/commands/trigger.ts","../src/trigger/destination.ts","../src/trigger/event.ts","../src/trigger/signature.ts","../src/ui/activity.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { constants, realpathSync } from \"node:fs\";\nimport {\n access,\n link,\n rename,\n rm,\n} from \"node:fs/promises\";\nimport { createWriteStream } from \"node:fs\";\nimport { basename, dirname, resolve } from \"node:path\";\nimport { Readable, Transform } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport type { ReadableStream as NodeReadableStream } from \"node:stream/web\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n JobWaitTimeoutError,\n MediaRuntime,\n MediaRuntimeApiError,\n MediaRuntimeConnectionError,\n} from \"@mediaruntime/node\";\nimport { PRODUCTION_ORIGIN } from \"./auth/api.js\";\nimport type { CredentialStore } from \"./auth/credential-store.js\";\nimport {\n resolveCredential,\n runAuthCommand,\n runLoginCommand,\n runLogoutCommand,\n type AuthCommandDependencies,\n} from \"./commands/auth.js\";\nimport {\n runCapabilitiesCommand,\n runPresetsCommand,\n type CapabilitiesReadClient,\n} from \"./commands/capabilities.js\";\nimport {\n runJobsCommand,\n type JobsReadClient,\n} from \"./commands/jobs.js\";\nimport {\n runCommand,\n type RunJobsClient,\n} from \"./commands/run.js\";\nimport { runRecipesCommand, type RecipesClient } from \"./commands/recipes.js\";\nimport { runTriggerCommand } from \"./commands/trigger.js\";\nimport { BundleDownloadError, CliError, UsageError } from \"./errors.js\";\nimport { isLoopbackDestination } from \"./trigger/destination.js\";\nimport { createActivityIndicator } from \"./ui/activity.js\";\n\nexport { parseTriggerArguments, runTriggerCommand } from \"./commands/trigger.js\";\nexport { createSyntheticTerminalEvent } from \"./trigger/event.js\";\nexport { signSyntheticWebhook } from \"./trigger/signature.js\";\nexport {\n resolveCredential,\n runAuthCommand,\n runAuthStatusCommand,\n runLoginCommand,\n runLogoutCommand,\n} from \"./commands/auth.js\";\n\nconst VERSION = \"1.2.0\";\nconst HELP = `MediaRuntime CLI\n\nUsage:\n mediaruntime run <source> (--recipe <name[@version]> | --output <alias> | --preset <name>) [...] [--wait]\n mediaruntime capabilities [--json]\n mediaruntime presets list [--json]\n mediaruntime jobs list [--status <status>] [--limit <n>] [--cursor <cursor>]\n mediaruntime jobs get <job_id> [--download <bundle.zip>] [--force]\n mediaruntime recipes <list|get|create|version|archive>\n mediaruntime trigger <job.completed|job.failed|job.rejected> --to <local-url>\n mediaruntime login [--no-browser]\n mediaruntime auth status\n mediaruntime logout [--local-only]\n\nGlobal options:\n --base-url <url> Developer override; normally leave unset\n --help Show help\n --version Show version\n\nRun/jobs options:\n --json Machine-readable, URL-redacted output\n\nAuthentication uses a secure login or MEDIARUNTIME_API_KEY.\n`;\n\ntype CliJobsClient = RunJobsClient & JobsReadClient;\n\nexport interface CliClient {\n jobs: CliJobsClient;\n capabilities: CapabilitiesReadClient;\n recipes?: RecipesClient;\n}\n\nexport interface CliDependencies {\n createClient?(options: { baseUrl?: string; apiKey?: string }): CliClient;\n downloadBundle?(\n url: string,\n destination: string,\n options: {\n force: boolean;\n expectedSizeBytes?: number | null;\n expectedSha256?: string | null;\n },\n ): Promise<void>;\n writeStdout?(text: string): void;\n writeStderr?(text: string): void;\n isStderrTTY?: boolean;\n credentialStore?: CredentialStore;\n openBrowser?(url: string): Promise<void>;\n sleep?(milliseconds: number): Promise<void>;\n now?(): number;\n randomVerifier?(): string;\n}\n\nfunction isFileExistsError(error: unknown): boolean {\n return error instanceof Error && \"code\" in error && error.code === \"EEXIST\";\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function downloadBundleAtomically(\n url: string,\n destination: string,\n options: {\n force: boolean;\n expectedSizeBytes?: number | null;\n expectedSha256?: string | null;\n },\n): Promise<void> {\n const target = resolve(destination);\n if (!options.force && await exists(target)) {\n throw new BundleDownloadError(`Refusing to overwrite existing file: ${destination}`);\n }\n const temporary = resolve(\n dirname(target),\n `.${basename(target)}.${randomUUID()}.part`,\n );\n\n try {\n let response: Response;\n try {\n response = await fetch(url);\n } catch (error) {\n throw new BundleDownloadError(\"Bundle download failed before receiving a response\", { cause: error });\n }\n if (!response.ok) {\n await response.body?.cancel();\n throw new BundleDownloadError(`Bundle download failed with HTTP ${response.status}`);\n }\n if (!response.body) throw new BundleDownloadError(\"Bundle download returned an empty response body\");\n const hash = createHash(\"sha256\");\n let sizeBytes = 0;\n const integrity = new Transform({\n transform(chunk: Buffer, _encoding, callback) {\n sizeBytes += chunk.length;\n hash.update(chunk);\n callback(null, chunk);\n },\n });\n await pipeline(\n Readable.fromWeb(response.body as unknown as NodeReadableStream<Uint8Array>),\n integrity,\n createWriteStream(temporary, { flags: \"wx\", mode: 0o600 }),\n );\n const sha256 = hash.digest(\"hex\");\n if (options.expectedSizeBytes !== undefined && options.expectedSizeBytes !== null &&\n sizeBytes !== options.expectedSizeBytes) {\n throw new BundleDownloadError(\n `Bundle size mismatch: expected ${options.expectedSizeBytes} bytes, received ${sizeBytes}`,\n );\n }\n if (options.expectedSha256 && sha256 !== options.expectedSha256.toLowerCase()) {\n throw new BundleDownloadError(\"Bundle SHA-256 mismatch\");\n }\n\n if (options.force) {\n await rename(temporary, target);\n } else {\n try {\n // A hard link publishes the completed same-filesystem temporary file atomically\n // and fails rather than replacing a destination created during the download.\n await link(temporary, target);\n } catch (error) {\n if (isFileExistsError(error)) {\n throw new BundleDownloadError(`Refusing to overwrite existing file: ${destination}`);\n }\n throw error;\n }\n await rm(temporary);\n }\n } catch (error) {\n await rm(temporary, { force: true });\n if (error instanceof BundleDownloadError) throw error;\n throw new BundleDownloadError(`Could not write bundle to ${destination}`, { cause: error });\n }\n}\n\nfunction normalizeBaseUrl(raw: string): string {\n let value: URL;\n try {\n value = new URL(raw);\n } catch {\n throw new UsageError(\"--base-url must be an absolute HTTP(S) origin\");\n }\n if (value.username || value.password || value.search || value.hash || value.pathname !== \"/\") {\n throw new UsageError(\"--base-url must be an origin without credentials, path, query, or fragment\");\n }\n if (value.protocol !== \"https:\" && !(value.protocol === \"http:\" && isLoopbackDestination(value))) {\n throw new UsageError(\"--base-url must use HTTPS unless it points to loopback\");\n }\n return value.origin;\n}\n\nfunction extractGlobalOptions(argv: string[]): { baseUrl?: string; args: string[] } {\n const args = [...argv];\n let baseUrl: string | undefined;\n while (args[0] === \"--base-url\") {\n const value = args[1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(\"--base-url requires a value\");\n baseUrl = normalizeBaseUrl(value);\n args.splice(0, 2);\n }\n return { ...(baseUrl === undefined ? {} : { baseUrl }), args };\n}\n\nfunction safeApiError(error: MediaRuntimeApiError): Record<string, unknown> {\n return {\n name: error.name,\n message: error.message,\n code: error.code,\n status: error.status,\n retryable: error.retryable,\n requestId: error.requestId ?? null,\n field: error.field ?? null,\n };\n}\n\nfunction exitCodeFor(error: unknown): number {\n if (error instanceof CliError) return error.exitCode;\n if (error instanceof JobWaitTimeoutError) return 7;\n if (error instanceof MediaRuntimeConnectionError) return 5;\n if (error instanceof MediaRuntimeApiError) {\n if ([401, 402, 403].includes(error.status)) return 3;\n if (error.status >= 500) return 5;\n return 4;\n }\n if (error instanceof DOMException && error.name === \"AbortError\") return 130;\n if (error instanceof TypeError && /fetch|network|socket|connect/i.test(error.message)) return 5;\n return 1;\n}\n\nfunction safeError(error: unknown, exitCode: number): Record<string, unknown> {\n if (error instanceof MediaRuntimeApiError) return { ...safeApiError(error), exitCode };\n return {\n code: error instanceof CliError ? error.code : \"cli_error\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n exitCode,\n };\n}\n\nexport async function executeCli(\n argv: string[],\n dependencies: CliDependencies = {},\n): Promise<number> {\n const writeStdout = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const writeStderr = dependencies.writeStderr ?? ((text: string) => process.stderr.write(text));\n const json = argv.includes(\"--json\");\n const isStderrTTY = dependencies.isStderrTTY ??\n (dependencies.writeStderr === undefined && process.stderr.isTTY === true);\n try {\n const global = extractGlobalOptions(argv);\n const command = global.args[0];\n if (!command || command === \"--help\" || command === \"-h\") {\n writeStdout(HELP);\n return 0;\n }\n if (command === \"--version\" || command === \"-v\") {\n writeStdout(`${VERSION}\\n`);\n return 0;\n }\n if (command === \"trigger\") {\n return await runTriggerCommand(global.args.slice(1), { writeStdout });\n }\n\n const configuredBaseUrl = global.baseUrl ?? process.env.MEDIARUNTIME_API_URL;\n const baseUrl = configuredBaseUrl ? normalizeBaseUrl(configuredBaseUrl) : undefined;\n const authBaseUrl = baseUrl ?? PRODUCTION_ORIGIN;\n const authDependencies: AuthCommandDependencies = {\n ...(dependencies.credentialStore ? { credentialStore: dependencies.credentialStore } : {}),\n ...(dependencies.openBrowser ? { openBrowser: dependencies.openBrowser } : {}),\n ...(dependencies.sleep ? { sleep: dependencies.sleep } : {}),\n ...(dependencies.now ? { now: dependencies.now } : {}),\n ...(dependencies.randomVerifier ? { randomVerifier: dependencies.randomVerifier } : {}),\n writeStdout,\n };\n if (command === \"login\") return await runLoginCommand(global.args.slice(1), authBaseUrl, authDependencies);\n if (command === \"auth\") return await runAuthCommand(global.args.slice(1), authBaseUrl, authDependencies);\n if (command === \"logout\") return await runLogoutCommand(global.args.slice(1), authBaseUrl, authDependencies);\n\n if (command === \"capabilities\" || command === \"presets\") {\n const publicClient = dependencies.createClient?.({\n ...(baseUrl === undefined ? {} : { baseUrl }),\n }) ?? new MediaRuntime({\n ...(baseUrl === undefined ? {} : { baseUrl }),\n });\n const publicDependencies = { capabilities: publicClient.capabilities, writeStdout };\n if (command === \"capabilities\") {\n return await runCapabilitiesCommand(global.args.slice(1), publicDependencies);\n }\n return await runPresetsCommand(global.args.slice(1), publicDependencies);\n }\n\n let apiKey = process.env.MEDIARUNTIME_API_KEY?.trim();\n if (!apiKey && (!dependencies.createClient || dependencies.credentialStore)) {\n apiKey = (await resolveCredential(authBaseUrl, authDependencies))?.apiKey;\n }\n if (!dependencies.createClient && !apiKey) {\n throw new UsageError(\"Run mediaruntime login or set MEDIARUNTIME_API_KEY before using this command\");\n }\n const client = dependencies.createClient?.({\n ...(baseUrl === undefined ? {} : { baseUrl }),\n ...(apiKey === undefined ? {} : { apiKey }),\n }) ?? new MediaRuntime({\n ...(baseUrl === undefined ? {} : { baseUrl }),\n ...(apiKey === undefined ? {} : { apiKey }),\n });\n const downloadBundle = dependencies.downloadBundle ?? downloadBundleAtomically;\n const commandDependencies = {\n jobs: client.jobs,\n capabilities: client.capabilities,\n writeStdout,\n downloadBundle,\n activity: createActivityIndicator(writeStderr, isStderrTTY && !json),\n };\n if (command === \"run\") return await runCommand(global.args.slice(1), commandDependencies);\n if (command === \"jobs\") {\n return await runJobsCommand(global.args.slice(1), commandDependencies);\n }\n if (command === \"recipes\") {\n if (!client.recipes) throw new UsageError(\"This MediaRuntime client does not support hosted recipes\");\n return await runRecipesCommand(global.args.slice(1), {\n recipes: client.recipes,\n writeStdout,\n });\n }\n throw new UsageError(`Unknown command: ${command}`);\n } catch (error) {\n const exitCode = exitCodeFor(error);\n if (json) {\n writeStderr(`${JSON.stringify({ error: safeError(error, exitCode) })}\\n`);\n } else {\n const requestId = error instanceof MediaRuntimeApiError && error.requestId\n ? ` (request ${error.requestId})`\n : \"\";\n writeStderr(`Error: ${error instanceof Error ? error.message : \"Unknown error\"}${requestId}\\n`);\n }\n return exitCode;\n }\n}\n\nlet isEntrypoint = false;\nif (process.argv[1] !== undefined) {\n try {\n // npm exposes binaries through a symlink. Resolve both sides so the installed command\n // executes while importing dist/cli.js in tests remains side-effect free.\n isEntrypoint = realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));\n } catch {\n isEntrypoint = false;\n }\n}\nif (isEntrypoint) process.exitCode = await executeCli(process.argv.slice(2));\n","export class CliError extends Error {\n readonly code: string;\n readonly exitCode: number;\n\n constructor(code: string, message: string, exitCode: number, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"CliError\";\n this.code = code;\n this.exitCode = exitCode;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class UsageError extends CliError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(\"usage_error\", message, 2, options);\n this.name = \"UsageError\";\n }\n}\n\nexport class TriggerDeliveryError extends CliError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(\"trigger_delivery_error\", message, 8, options);\n this.name = \"TriggerDeliveryError\";\n }\n}\n\nexport class BundleDownloadError extends CliError {\n constructor(message: string, options?: { cause?: unknown }) {\n super(\"bundle_download_error\", message, 9, options);\n this.name = \"BundleDownloadError\";\n }\n}\n","import { CliError } from \"../errors.js\";\n\nexport const PRODUCTION_ORIGIN = \"https://mediaruntime.com\";\n\ninterface ErrorPayload {\n error?: unknown;\n detail?: unknown;\n}\n\nexport interface DeviceAuthorization {\n deviceCode: string;\n userCode: string;\n verificationUri: string;\n verificationUriComplete: string;\n expiresIn: number;\n interval: number;\n}\n\nexport interface IssuedCredential {\n apiKey: string;\n accountId: string;\n keyId: string;\n credentialType: \"cli\";\n}\n\nexport interface CredentialStatus {\n status: \"authenticated\";\n accountId: string;\n keyId: string;\n credentialType: \"cli\" | \"api_key\";\n}\n\nexport class AuthApiError extends CliError {\n readonly status: number;\n\n constructor(code: string, message: string, status: number) {\n super(code, message, status >= 500 ? 5 : 3);\n this.name = \"AuthApiError\";\n this.status = status;\n }\n}\n\nfunction endpoint(baseUrl: string, path: string): string {\n return `${baseUrl.replace(/\\/+$/, \"\")}/api/cli/auth/${path}`;\n}\n\nasync function responsePayload(response: Response): Promise<Record<string, unknown>> {\n try {\n const value: unknown = await response.json();\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? value as Record<string, unknown>\n : {};\n } catch {\n return {};\n }\n}\n\nasync function post(\n baseUrl: string,\n path: string,\n body: Record<string, unknown>,\n apiKey?: string,\n): Promise<Record<string, unknown>> {\n let response: Response;\n try {\n response = await fetch(endpoint(baseUrl, path), {\n method: \"POST\",\n redirect: \"error\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...(apiKey ? { \"X-API-Key\": apiKey } : {}),\n },\n body: JSON.stringify(body),\n });\n } catch (error) {\n throw new CliError(\"auth_connection_error\", \"Could not reach MediaRuntime authentication\", 5, { cause: error });\n }\n const payload = await responsePayload(response);\n if (!response.ok) {\n const errorPayload = payload as ErrorPayload;\n throw new AuthApiError(\n typeof errorPayload.error === \"string\" ? errorPayload.error : \"authorization_failed\",\n typeof errorPayload.detail === \"string\" ? errorPayload.detail : `Authentication failed with HTTP ${response.status}`,\n response.status,\n );\n }\n return payload;\n}\n\nfunction requireString(payload: Record<string, unknown>, key: string): string {\n const value = payload[key];\n if (typeof value !== \"string\" || !value) throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned an invalid authentication response\", 5);\n return value;\n}\n\nexport async function startAuthorization(baseUrl: string, codeChallenge: string): Promise<DeviceAuthorization> {\n const payload = await post(baseUrl, \"start\", { codeChallenge, clientName: \"MediaRuntime CLI\" });\n return {\n deviceCode: requireString(payload, \"deviceCode\"),\n userCode: requireString(payload, \"userCode\"),\n verificationUri: requireString(payload, \"verificationUri\"),\n verificationUriComplete: requireString(payload, \"verificationUriComplete\"),\n expiresIn: Number(payload.expiresIn),\n interval: Number(payload.interval),\n };\n}\n\nexport async function exchangeAuthorization(baseUrl: string, deviceCode: string, codeVerifier: string): Promise<IssuedCredential> {\n const payload = await post(baseUrl, \"token\", { deviceCode, codeVerifier });\n const credentialType = requireString(payload, \"credentialType\");\n if (credentialType !== \"cli\") throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned the wrong credential type\", 5);\n return {\n apiKey: requireString(payload, \"apiKey\"),\n accountId: requireString(payload, \"accountId\"),\n keyId: requireString(payload, \"keyId\"),\n credentialType,\n };\n}\n\nexport async function inspectCredential(baseUrl: string, apiKey: string): Promise<CredentialStatus> {\n const payload = await post(baseUrl, \"status\", {}, apiKey);\n const credentialType = requireString(payload, \"credentialType\");\n if (credentialType !== \"cli\" && credentialType !== \"api_key\") {\n throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned the wrong credential type\", 5);\n }\n return {\n status: \"authenticated\",\n accountId: requireString(payload, \"accountId\"),\n keyId: requireString(payload, \"keyId\"),\n credentialType,\n };\n}\n\nexport async function revokeCredential(baseUrl: string, apiKey: string): Promise<void> {\n await post(baseUrl, \"revoke\", {}, apiKey);\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport {\n AuthApiError,\n exchangeAuthorization,\n inspectCredential,\n revokeCredential,\n startAuthorization,\n} from \"../auth/api.js\";\nimport { openBrowser } from \"../auth/browser.js\";\nimport {\n OsCredentialStore,\n type CredentialStore,\n type StoredCredential,\n} from \"../auth/credential-store.js\";\nimport { CliError, UsageError } from \"../errors.js\";\n\nexport interface AuthCommandDependencies {\n credentialStore?: CredentialStore;\n openBrowser?: (url: string) => Promise<void>;\n sleep?: (milliseconds: number) => Promise<void>;\n now?: () => number;\n randomVerifier?: () => string;\n writeStdout?: (text: string) => void;\n}\n\nconst defaultSleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));\n\nfunction verifierChallenge(verifier: string): string {\n return createHash(\"sha256\").update(verifier).digest(\"base64url\");\n}\n\nfunction defaultVerifier(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\nfunction store(dependencies: AuthCommandDependencies): CredentialStore {\n return dependencies.credentialStore ?? new OsCredentialStore();\n}\n\nfunction assertOnly(args: string[], allowed: string[]): void {\n const unexpected = args.find((arg) => !allowed.includes(arg));\n if (unexpected) throw new UsageError(`Unknown authentication option: ${unexpected}`);\n}\n\nexport async function resolveCredential(\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<{ apiKey: string; source: \"environment\" | \"keychain\"; stored?: StoredCredential } | null> {\n const environment = process.env.MEDIARUNTIME_API_KEY?.trim();\n if (environment) return { apiKey: environment, source: \"environment\" };\n const stored = await store(dependencies).get(baseUrl);\n return stored ? { apiKey: stored.apiKey, source: \"keychain\", stored } : null;\n}\n\nexport async function runLoginCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n assertOnly(args, [\"--no-browser\"]);\n const noBrowser = args.includes(\"--no-browser\");\n const write = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const existing = await store(dependencies).get(baseUrl);\n if (existing) {\n try {\n await inspectCredential(baseUrl, existing.apiKey);\n write(`Already logged in to ${baseUrl} (account ${existing.accountId}).\\n`);\n return 0;\n } catch (error) {\n if (!(error instanceof AuthApiError) || error.status >= 500) throw error;\n }\n }\n\n const verifier = dependencies.randomVerifier?.() ?? defaultVerifier();\n if (verifier.length < 43 || verifier.length > 128) {\n throw new CliError(\"invalid_verifier\", \"Generated PKCE verifier is invalid\", 1);\n }\n const authorization = await startAuthorization(baseUrl, verifierChallenge(verifier));\n if (!Number.isFinite(authorization.expiresIn) || authorization.expiresIn <= 0 ||\n !Number.isFinite(authorization.interval) || authorization.interval < 1) {\n throw new CliError(\"invalid_auth_response\", \"MediaRuntime returned invalid authorization timing\", 5);\n }\n\n write(`Open this URL to authorize MediaRuntime CLI:\\n${authorization.verificationUriComplete}\\n\\n`);\n write(`Confirm code: ${authorization.userCode}\\n`);\n if (!noBrowser) await (dependencies.openBrowser ?? openBrowser)(authorization.verificationUriComplete);\n write(\"Waiting for browser approval…\\n\");\n\n const now = dependencies.now ?? Date.now;\n const sleep = dependencies.sleep ?? defaultSleep;\n const deadline = now() + authorization.expiresIn * 1000;\n let credential;\n while (now() < deadline) {\n try {\n credential = await exchangeAuthorization(baseUrl, authorization.deviceCode, verifier);\n break;\n } catch (error) {\n if (error instanceof AuthApiError && error.code === \"authorization_pending\") {\n await sleep(authorization.interval * 1000);\n continue;\n }\n throw error;\n }\n }\n if (!credential) throw new CliError(\"authorization_timeout\", \"Browser authorization expired; run mediaruntime login again\", 7);\n\n try {\n await inspectCredential(baseUrl, credential.apiKey);\n await store(dependencies).set({\n apiKey: credential.apiKey,\n accountId: credential.accountId,\n keyId: credential.keyId,\n baseUrl,\n createdAt: new Date(now()).toISOString(),\n });\n } catch (error) {\n await revokeCredential(baseUrl, credential.apiKey).catch(() => undefined);\n throw error;\n }\n\n write(`Logged in to ${baseUrl} (account ${credential.accountId}).\\n`);\n if (process.env.MEDIARUNTIME_API_KEY?.trim()) {\n write(\"MEDIARUNTIME_API_KEY is set and will take precedence over this login.\\n\");\n }\n return 0;\n}\n\nexport async function runAuthStatusCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n assertOnly(args, [\"--json\"]);\n const json = args.includes(\"--json\");\n const write = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const resolved = await resolveCredential(baseUrl, dependencies);\n if (!resolved) throw new CliError(\"authentication_required\", \"Run mediaruntime login or set MEDIARUNTIME_API_KEY\", 3);\n const status = await inspectCredential(baseUrl, resolved.apiKey);\n if (json) {\n write(`${JSON.stringify({ authenticated: true, source: resolved.source, ...status })}\\n`);\n } else {\n write(`Authenticated via ${resolved.source} (account ${status.accountId}, key ${status.keyId}).\\n`);\n }\n return 0;\n}\n\nexport async function runLogoutCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n assertOnly(args, [\"--local-only\"]);\n const localOnly = args.includes(\"--local-only\");\n const write = dependencies.writeStdout ?? ((text: string) => process.stdout.write(text));\n const credentialStore = store(dependencies);\n const credential = await credentialStore.get(baseUrl);\n if (!credential) {\n write(`No stored login for ${baseUrl}.\\n`);\n if (process.env.MEDIARUNTIME_API_KEY?.trim()) write(\"MEDIARUNTIME_API_KEY remains active in this shell.\\n\");\n return 0;\n }\n if (!localOnly) await revokeCredential(baseUrl, credential.apiKey);\n await credentialStore.delete(baseUrl);\n write(localOnly ? \"Removed the local CLI login without server revocation.\\n\" : \"Logged out and revoked the CLI credential.\\n\");\n if (process.env.MEDIARUNTIME_API_KEY?.trim()) write(\"MEDIARUNTIME_API_KEY remains active in this shell.\\n\");\n return 0;\n}\n\nexport async function runAuthCommand(\n args: string[],\n baseUrl: string,\n dependencies: AuthCommandDependencies = {},\n): Promise<number> {\n const subcommand = args[0];\n if (subcommand !== \"status\") throw new UsageError(\"Usage: mediaruntime auth status [--json]\");\n return runAuthStatusCommand(args.slice(1), baseUrl, dependencies);\n}\n","import { spawn } from \"node:child_process\";\nimport { CliError } from \"../errors.js\";\n\nexport async function openBrowser(url: string): Promise<void> {\n const command = process.platform === \"darwin\"\n ? { executable: \"open\", args: [url] }\n : process.platform === \"win32\"\n ? { executable: \"rundll32\", args: [\"url.dll,FileProtocolHandler\", url] }\n : { executable: \"xdg-open\", args: [url] };\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command.executable, command.args, {\n detached: true,\n stdio: \"ignore\",\n });\n child.once(\"error\", (error) => reject(new CliError(\n \"browser_open_failed\",\n \"Could not open a browser; rerun with --no-browser and open the printed URL\",\n 2,\n { cause: error },\n )));\n child.once(\"spawn\", () => {\n child.unref();\n resolve();\n });\n });\n}\n","import { CliError } from \"../errors.js\";\n\nconst SERVICE = \"mediaruntime-cli\";\n\nexport interface StoredCredential {\n apiKey: string;\n accountId: string;\n keyId: string;\n baseUrl: string;\n createdAt: string;\n}\n\nexport interface CredentialStore {\n get(baseUrl: string): Promise<StoredCredential | null>;\n set(credential: StoredCredential): Promise<void>;\n delete(baseUrl: string): Promise<void>;\n}\n\nfunction vaultAccount(baseUrl: string): string {\n return new URL(baseUrl).host.toLowerCase();\n}\n\nfunction validCredential(value: unknown): value is StoredCredential {\n if (!value || typeof value !== \"object\") return false;\n const item = value as Record<string, unknown>;\n return typeof item.apiKey === \"string\" && item.apiKey.startsWith(\"sk_\") &&\n typeof item.accountId === \"string\" && item.accountId.length > 0 &&\n typeof item.keyId === \"string\" && item.keyId.length > 0 &&\n typeof item.baseUrl === \"string\" && item.baseUrl.length > 0 &&\n typeof item.createdAt === \"string\" && item.createdAt.length > 0;\n}\n\nasync function entry(baseUrl: string) {\n try {\n const { Entry } = await import(\"@napi-rs/keyring\");\n return new Entry(SERVICE, vaultAccount(baseUrl));\n } catch (error) {\n throw new CliError(\n \"credential_store_unavailable\",\n \"The operating-system credential vault is unavailable; use MEDIARUNTIME_API_KEY on this machine\",\n 2,\n { cause: error },\n );\n }\n}\n\nexport class OsCredentialStore implements CredentialStore {\n async get(baseUrl: string): Promise<StoredCredential | null> {\n try {\n const raw = (await entry(baseUrl)).getPassword();\n if (!raw) return null;\n const parsed: unknown = JSON.parse(raw);\n if (!validCredential(parsed) || parsed.baseUrl !== baseUrl) {\n throw new Error(\"Stored credential has an invalid shape\");\n }\n return parsed;\n } catch (error) {\n if (error instanceof SyntaxError || (error instanceof Error && error.message.includes(\"invalid shape\"))) {\n throw new CliError(\"credential_store_invalid\", \"The stored MediaRuntime credential is invalid; run mediaruntime logout --local-only\", 3);\n }\n if (error instanceof CliError) throw error;\n // Keyring implementations return a not-found error rather than null on some platforms.\n if (error instanceof Error && /not found|no entry|no matching|item.*exist/i.test(error.message)) return null;\n throw new CliError(\"credential_store_error\", \"Could not read the operating-system credential vault\", 2, { cause: error });\n }\n }\n\n async set(credential: StoredCredential): Promise<void> {\n try {\n (await entry(credential.baseUrl)).setPassword(JSON.stringify(credential));\n } catch (error) {\n if (error instanceof CliError) throw error;\n throw new CliError(\"credential_store_error\", \"Could not save the login in the operating-system credential vault\", 2, { cause: error });\n }\n }\n\n async delete(baseUrl: string): Promise<void> {\n try {\n (await entry(baseUrl)).deletePassword();\n } catch (error) {\n if (error instanceof CliError) throw error;\n if (error instanceof Error && /not found|no entry|no matching|item.*exist/i.test(error.message)) return;\n throw new CliError(\"credential_store_error\", \"Could not remove the login from the operating-system credential vault\", 2, { cause: error });\n }\n }\n}\n","import type { Capabilities } from \"@mediaruntime/node\";\nimport { UsageError } from \"../errors.js\";\n\nexport interface CapabilitiesReadClient {\n retrieve(): Promise<Capabilities>;\n}\n\nexport interface CapabilitiesCommandDependencies {\n capabilities: CapabilitiesReadClient;\n writeStdout(text: string): void;\n}\n\nexport interface PublicPresetRow {\n name: string;\n outputType: string;\n tier: string;\n sourceKinds: string[];\n artifacts: string[];\n description: string;\n codec: string | null;\n container: string | null;\n}\n\nfunction cell(value: string): string {\n return value || \"-\";\n}\n\nfunction table(headings: string[], rows: string[][]): string {\n const widths = headings.map((heading, index) =>\n Math.max(heading.length, ...rows.map((row) => row[index]?.length ?? 0)),\n );\n const render = (row: string[]): string =>\n row.map((value, index) => value.padEnd(widths[index] ?? value.length)).join(\" \").trimEnd();\n return `${[\n render(headings),\n render(widths.map((width) => \"-\".repeat(width))),\n ...rows.map(render),\n ].join(\"\\n\")}\\n`;\n}\n\nexport function publicPresetRows(capabilities: Capabilities): PublicPresetRow[] {\n return capabilities.publicPresets.map((name) => {\n const preset = capabilities.presets[name];\n if (!preset) {\n throw new Error(`Gateway capability contract is missing public preset metadata for ${name}`);\n }\n return {\n name,\n outputType: preset.outputType,\n tier: preset.baseTier,\n sourceKinds: preset.sourceKinds,\n artifacts: preset.artifacts,\n description: preset.description,\n codec: preset.codec ?? null,\n container: preset.container ?? null,\n };\n });\n}\n\nfunction parseJsonOnly(args: string[], command: string): boolean {\n let json = false;\n for (const argument of args) {\n if (argument === \"--json\") json = true;\n else throw new UsageError(`Unknown ${command} option: ${argument}`);\n }\n return json;\n}\n\nexport async function runCapabilitiesCommand(\n args: string[],\n dependencies: CapabilitiesCommandDependencies,\n): Promise<number> {\n const json = parseJsonOnly(args, \"capabilities\");\n const capabilities = await dependencies.capabilities.retrieve();\n if (json) {\n dependencies.writeStdout(`${JSON.stringify(capabilities)}\\n`);\n return 0;\n }\n\n const aliases = Object.entries(capabilities.outputAliases).map(([name, value]) => [\n name,\n value.type,\n value.preset,\n value.tier,\n ]);\n dependencies.writeStdout(\n `Public presets: ${capabilities.publicPresets.length}\\n` +\n `Optional features: ${Object.keys(capabilities.features).sort().join(\", \") || \"none\"}\\n\\n` +\n table([\"ALIAS\", \"TYPE\", \"PRESET\", \"TIER\"], aliases) +\n \"\\nRun `mediaruntime presets list` for the complete public preset catalog.\\n\",\n );\n return 0;\n}\n\nexport async function runPresetsCommand(\n args: string[],\n dependencies: CapabilitiesCommandDependencies,\n): Promise<number> {\n const subcommand = args[0];\n if (subcommand !== \"list\") throw new UsageError(\"Usage: mediaruntime presets list [--json]\");\n const json = parseJsonOnly(args.slice(1), \"presets list\");\n const capabilities = await dependencies.capabilities.retrieve();\n const presets = publicPresetRows(capabilities);\n if (json) dependencies.writeStdout(`${JSON.stringify({ presets })}\\n`);\n else {\n dependencies.writeStdout(table(\n [\"PRESET\", \"TYPE\", \"TIER\", \"INPUTS\", \"ARTIFACTS\"],\n presets.map((preset) => [\n preset.name,\n cell(preset.outputType),\n cell(preset.tier),\n preset.sourceKinds.join(\",\"),\n preset.artifacts.join(\", \"),\n ]),\n ));\n }\n return 0;\n}\n","import type { JobDetails, JobPage, JobStatus, ListJobsParams } from \"@mediaruntime/node\";\nimport { BundleDownloadError, UsageError } from \"../errors.js\";\n\nconst UNSUCCESSFUL_TERMINAL_STATUSES = new Set([\"FAILED\", \"REJECTED\", \"PARTIAL\"]);\n\nexport interface JobsReadClient {\n list(params?: ListJobsParams): Promise<JobPage>;\n get(jobId: string): Promise<JobDetails>;\n}\n\nexport interface JobsCommandDependencies {\n jobs: JobsReadClient;\n writeStdout(text: string): void;\n downloadBundle(\n url: string,\n destination: string,\n options: { force: boolean; expectedSizeBytes?: number | null; expectedSha256?: string | null },\n ): Promise<void>;\n}\n\nfunction optionValue(args: string[], index: number, option: string): string {\n const value = args[index + 1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(`${option} requires a value`);\n return value;\n}\n\nfunction detailsProjection(job: JobDetails): Record<string, unknown> {\n return {\n id: job.id,\n status: job.status,\n tier: job.tier,\n usage: job.usage,\n billing: job.billing,\n bundle: {\n available: job.bundle.available,\n expiresAt: job.bundle.expiresAt,\n sizeBytes: job.bundle.sizeBytes,\n sha256: job.bundle.sha256,\n retentionDays: job.bundle.retentionDays,\n },\n media: job.media,\n recipe: job.recipe,\n metadata: job.metadata,\n error: job.error,\n createdAt: job.createdAt,\n updatedAt: job.updatedAt,\n startedAt: job.startedAt,\n completedAt: job.completedAt,\n };\n}\n\nfunction humanDetails(job: JobDetails): string {\n const lines = [\n `Job: ${job.id}`,\n `Status: ${job.status}`,\n `Tier: ${job.tier.billed ?? job.tier.effective ?? job.tier.requested ?? \"-\"}`,\n `Bundle: ${job.bundle.available ? \"available\" : \"unavailable\"}`,\n ];\n if (job.bundle.sizeBytes !== null) lines.push(`Bundle size: ${job.bundle.sizeBytes} bytes`);\n if (job.error) lines.push(`Error: ${job.error}`);\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction cell(value: unknown): string {\n if (value === null || value === undefined || value === \"\") return \"-\";\n return String(value);\n}\n\nfunction humanList(page: JobPage): string {\n const rows = page.jobs.map((job) => [\n job.id,\n job.status,\n cell(job.tierBilled),\n cell(job.unitsTotal),\n job.bundleAvailable ? \"yes\" : \"no\",\n cell(job.updatedAt),\n ]);\n const headings = [\"ID\", \"STATUS\", \"TIER\", \"UNITS\", \"BUNDLE\", \"UPDATED\"];\n const widths = headings.map((heading, index) =>\n Math.max(heading.length, ...rows.map((row) => row[index]?.length ?? 0)),\n );\n const render = (row: string[]): string =>\n row.map((value, index) => value.padEnd(widths[index] ?? value.length)).join(\" \").trimEnd();\n const lines = [render(headings), render(widths.map((width) => \"-\".repeat(width))), ...rows.map(render)];\n if (page.nextCursor) lines.push(`Next cursor: ${page.nextCursor}`);\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nasync function listCommand(args: string[], dependencies: JobsCommandDependencies): Promise<number> {\n let status: string | undefined;\n let limit: number | undefined;\n let cursor: string | undefined;\n let json = false;\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--status\") {\n status = optionValue(args, index, argument).toUpperCase();\n index += 1;\n } else if (argument === \"--limit\") {\n const value = Number(optionValue(args, index, argument));\n if (!Number.isSafeInteger(value) || value < 1 || value > 100) {\n throw new UsageError(\"--limit must be an integer between 1 and 100\");\n }\n limit = value;\n index += 1;\n } else if (argument === \"--cursor\") {\n cursor = optionValue(args, index, argument);\n index += 1;\n } else if (argument === \"--json\") {\n json = true;\n } else {\n throw new UsageError(`Unknown jobs list option: ${argument}`);\n }\n }\n const params: ListJobsParams = {\n ...(status === undefined ? {} : { status: status as JobStatus }),\n ...(limit === undefined ? {} : { limit }),\n ...(cursor === undefined ? {} : { cursor }),\n };\n const page = await dependencies.jobs.list(params);\n dependencies.writeStdout(json ? `${JSON.stringify(page)}\\n` : humanList(page));\n return 0;\n}\n\nasync function getCommand(args: string[], dependencies: JobsCommandDependencies): Promise<number> {\n let jobId: string | undefined;\n let download: string | undefined;\n let force = false;\n let json = false;\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--download\") {\n download = optionValue(args, index, argument);\n index += 1;\n } else if (argument === \"--force\") {\n force = true;\n } else if (argument === \"--json\") {\n json = true;\n } else if (argument?.startsWith(\"-\")) {\n throw new UsageError(`Unknown jobs get option: ${argument}`);\n } else if (!jobId) {\n jobId = argument;\n } else {\n throw new UsageError(\"jobs get accepts exactly one job ID\");\n }\n }\n if (!jobId) throw new UsageError(\"Usage: mediaruntime jobs get <job_id>\");\n if (force && !download) throw new UsageError(\"--force requires --download\");\n const job = await dependencies.jobs.get(jobId);\n if (!json) dependencies.writeStdout(humanDetails(job));\n\n if (UNSUCCESSFUL_TERMINAL_STATUSES.has(String(job.status).toUpperCase())) {\n if (json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(job))}\\n`);\n return 6;\n }\n if (download) {\n if (String(job.status).toUpperCase() !== \"COMPLETED\" ||\n !job.bundle.available || !job.bundle.downloadUrl) {\n throw new BundleDownloadError(\"Bundle download requires a COMPLETED job with an available canonical bundle\");\n }\n try {\n await dependencies.downloadBundle(job.bundle.downloadUrl, download, {\n force,\n expectedSizeBytes: job.bundle.sizeBytes,\n expectedSha256: job.bundle.sha256,\n });\n } catch (error) {\n if (error instanceof BundleDownloadError) throw error;\n throw new BundleDownloadError(`Could not download bundle to ${download}`, { cause: error });\n }\n if (!json) dependencies.writeStdout(`Downloaded bundle to ${download}\\n`);\n }\n if (json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(job))}\\n`);\n return 0;\n}\n\nexport async function runJobsCommand(\n args: string[],\n dependencies: JobsCommandDependencies,\n): Promise<number> {\n const subcommand = args[0];\n if (subcommand === \"list\") return listCommand(args.slice(1), dependencies);\n if (subcommand === \"get\") return getCommand(args.slice(1), dependencies);\n throw new UsageError(\"Usage: mediaruntime jobs <list|get>\");\n}\n","import type {\n Capabilities,\n CreateJobParams,\n JobDetails,\n JobOutput,\n JobReceiptData,\n Metadata,\n OutputAlias,\n WaitForJobOptions,\n} from \"@mediaruntime/node\";\nimport type { CapabilitiesReadClient } from \"./capabilities.js\";\nimport { BundleDownloadError, UsageError } from \"../errors.js\";\nimport type { ActivityIndicator } from \"../ui/activity.js\";\n\nconst UNSUCCESSFUL_TERMINAL_STATUSES = new Set([\"FAILED\", \"REJECTED\", \"PARTIAL\"]);\nconst OUTPUT_ALIASES = new Set([\n \"video.web\",\n \"video.streaming\",\n \"video.social\",\n \"audio.web\",\n \"audio.transcription\",\n \"image.web\",\n]);\n\ninterface SubmittedJob extends JobReceiptData {\n wait(options?: WaitForJobOptions): Promise<JobDetails>;\n}\n\nexport interface RunJobsClient {\n create(params: CreateJobParams): Promise<SubmittedJob>;\n}\n\nexport interface RunCommandDependencies {\n jobs: RunJobsClient;\n capabilities: CapabilitiesReadClient;\n writeStdout(text: string): void;\n activity: ActivityIndicator;\n downloadBundle(\n url: string,\n destination: string,\n options: { force: boolean; expectedSizeBytes?: number | null; expectedSha256?: string | null },\n ): Promise<void>;\n}\n\ninterface RunOptions {\n source: string;\n outputs: Array<{ kind: \"alias\" | \"preset\"; value: string }>;\n recipe?: string;\n metadata?: Metadata;\n idempotencyKey?: string;\n wait: boolean;\n timeoutMs?: number;\n download?: string;\n force: boolean;\n json: boolean;\n}\n\nfunction optionValue(args: string[], index: number, option: string): string {\n const value = args[index + 1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(`${option} requires a value`);\n return value;\n}\n\nfunction parseMetadata(value: string): Metadata {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value) as unknown;\n } catch {\n throw new UsageError(\"--metadata must be a valid JSON object\");\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new UsageError(\"--metadata must be a JSON object\");\n }\n return parsed as Metadata;\n}\n\nfunction parseRunOptions(args: string[]): RunOptions {\n let source: string | undefined;\n const outputs: RunOptions[\"outputs\"] = [];\n let metadata: Metadata | undefined;\n let recipe: string | undefined;\n let idempotencyKey: string | undefined;\n let wait = false;\n let timeoutMs: number | undefined;\n let download: string | undefined;\n let force = false;\n let json = false;\n\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--output\" || argument === \"-o\") {\n outputs.push({ kind: \"alias\", value: optionValue(args, index, argument) });\n index += 1;\n } else if (argument === \"--preset\") {\n outputs.push({ kind: \"preset\", value: optionValue(args, index, argument) });\n index += 1;\n } else if (argument === \"--recipe\") {\n recipe = optionValue(args, index, argument);\n index += 1;\n } else if (argument === \"--metadata\") {\n metadata = parseMetadata(optionValue(args, index, argument));\n index += 1;\n } else if (argument === \"--idempotency-key\") {\n idempotencyKey = optionValue(args, index, argument);\n index += 1;\n } else if (argument === \"--wait\") {\n wait = true;\n } else if (argument === \"--timeout-ms\") {\n const value = Number(optionValue(args, index, argument));\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new UsageError(\"--timeout-ms must be a positive integer\");\n }\n timeoutMs = value;\n index += 1;\n } else if (argument === \"--download\") {\n download = optionValue(args, index, argument);\n wait = true;\n index += 1;\n } else if (argument === \"--force\") {\n force = true;\n } else if (argument === \"--json\") {\n json = true;\n } else if (argument?.startsWith(\"-\")) {\n throw new UsageError(`Unknown run option: ${argument}`);\n } else if (source === undefined) {\n source = argument;\n } else {\n throw new UsageError(\"run accepts exactly one source\");\n }\n }\n\n if (!source) {\n throw new UsageError(\"Usage: mediaruntime run <source> (--recipe <name[@version]> | --output <alias> | --preset <name>) [--wait]\");\n }\n if (recipe && outputs.length > 0) throw new UsageError(\"--recipe cannot be combined with --output or --preset\");\n if (!recipe && outputs.length === 0) throw new UsageError(\"run requires --recipe or at least one --output or --preset\");\n const unsupported = outputs.find(\n (output) => output.kind === \"alias\" && !OUTPUT_ALIASES.has(output.value),\n );\n if (unsupported) throw new UsageError(`Unsupported output alias: ${unsupported.value}`);\n if (force && !download) throw new UsageError(\"--force requires --download\");\n if (timeoutMs !== undefined && !wait) throw new UsageError(\"--timeout-ms requires --wait or --download\");\n return {\n source,\n outputs,\n ...(recipe === undefined ? {} : { recipe }),\n ...(metadata === undefined ? {} : { metadata }),\n ...(idempotencyKey === undefined ? {} : { idempotencyKey }),\n wait,\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n ...(download === undefined ? {} : { download }),\n force,\n json,\n };\n}\n\nasync function resolveOutputs(\n selections: RunOptions[\"outputs\"],\n capabilitiesClient: CapabilitiesReadClient,\n): Promise<Array<OutputAlias | JobOutput>> {\n if (!selections.some((selection) => selection.kind === \"preset\")) {\n return selections.map((selection) => selection.value as OutputAlias);\n }\n const capabilities: Capabilities = await capabilitiesClient.retrieve();\n const publicPresets = new Set(capabilities.publicPresets);\n return selections.map((selection) => {\n if (selection.kind === \"alias\") return selection.value as OutputAlias;\n const preset = capabilities.presets[selection.value];\n if (!publicPresets.has(selection.value) || !preset) {\n throw new UsageError(`Unknown or non-public preset: ${selection.value}`);\n }\n return { type: preset.outputType, preset: selection.value };\n });\n}\n\nfunction receiptProjection(job: SubmittedJob): JobReceiptData {\n return {\n id: job.id,\n status: job.status,\n tier: job.tier,\n requiredTier: job.requiredTier,\n outputs: job.outputs,\n recipe: job.recipe,\n message: job.message,\n };\n}\n\nfunction detailsProjection(job: JobDetails): Record<string, unknown> {\n return {\n id: job.id,\n status: job.status,\n tier: job.tier,\n usage: job.usage,\n billing: job.billing,\n bundle: {\n available: job.bundle.available,\n expiresAt: job.bundle.expiresAt,\n sizeBytes: job.bundle.sizeBytes,\n sha256: job.bundle.sha256,\n retentionDays: job.bundle.retentionDays,\n },\n media: job.media,\n recipe: job.recipe,\n metadata: job.metadata,\n error: job.error,\n createdAt: job.createdAt,\n updatedAt: job.updatedAt,\n startedAt: job.startedAt,\n completedAt: job.completedAt,\n };\n}\n\nfunction writeHumanReceipt(job: SubmittedJob, write: (text: string) => void): void {\n write(`Job: ${job.id}\\nStatus: ${job.status}\\nTier: ${job.tier || \"-\"}\\n`);\n}\n\nfunction writeHumanDetails(job: JobDetails, write: (text: string) => void): void {\n const error = job.error ? `\\nError: ${job.error}` : \"\";\n write(\n `Job: ${job.id}\\nStatus: ${job.status}\\n` +\n `Bundle: ${job.bundle.available ? \"available\" : \"unavailable\"}${error}\\n`,\n );\n}\n\nexport async function runCommand(\n args: string[],\n dependencies: RunCommandDependencies,\n): Promise<number> {\n const options = parseRunOptions(args);\n const outputs = options.recipe ? undefined : await resolveOutputs(options.outputs, dependencies.capabilities);\n const params: CreateJobParams = {\n source: options.source,\n ...(outputs === undefined ? {} : { outputs }),\n ...(options.recipe === undefined ? {} : { recipe: options.recipe }),\n ...(options.metadata === undefined ? {} : { metadata: options.metadata }),\n ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),\n };\n const isLocalSource = !/^(?:https?|gs):\\/\\//i.test(options.source);\n dependencies.activity.start(\n isLocalSource ? \"Uploading local source and creating job…\" : \"Creating job…\",\n );\n\n try {\n const submitted = await dependencies.jobs.create(params);\n\n if (!options.wait) {\n dependencies.activity.stop();\n if (options.json) dependencies.writeStdout(`${JSON.stringify(receiptProjection(submitted))}\\n`);\n else writeHumanReceipt(submitted, dependencies.writeStdout);\n return UNSUCCESSFUL_TERMINAL_STATUSES.has(String(submitted.status).toUpperCase()) ? 6 : 0;\n }\n\n dependencies.activity.update(`Waiting for job ${submitted.id} to complete…`);\n const details = await submitted.wait(\n options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs },\n );\n if (String(details.status).toUpperCase() !== \"COMPLETED\") {\n dependencies.activity.stop();\n if (!options.json) writeHumanDetails(details, dependencies.writeStdout);\n if (options.json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(details))}\\n`);\n return 6;\n }\n if (options.download) {\n const url = details.bundle.downloadUrl;\n if (!details.bundle.available || !url) {\n throw new BundleDownloadError(\"Completed job does not have an available canonical bundle\");\n }\n dependencies.activity.update(\"Downloading and verifying ZIP bundle…\");\n try {\n await dependencies.downloadBundle(url, options.download, {\n force: options.force,\n expectedSizeBytes: details.bundle.sizeBytes,\n expectedSha256: details.bundle.sha256,\n });\n } catch (error) {\n if (error instanceof BundleDownloadError) throw error;\n throw new BundleDownloadError(`Could not download bundle to ${options.download}`, { cause: error });\n }\n }\n dependencies.activity.stop();\n if (!options.json) {\n writeHumanDetails(details, dependencies.writeStdout);\n if (options.download) dependencies.writeStdout(`Downloaded bundle to ${options.download}\\n`);\n }\n if (options.json) dependencies.writeStdout(`${JSON.stringify(detailsProjection(details))}\\n`);\n return 0;\n } finally {\n dependencies.activity.stop();\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport type {\n CreateRecipeParams,\n CreateRecipeVersionParams,\n HostedRecipe,\n} from \"@mediaruntime/node\";\nimport { UsageError } from \"../errors.js\";\n\nexport interface RecipesClient {\n list(): Promise<HostedRecipe[]>;\n get(name: string, options?: { version?: number }): Promise<HostedRecipe>;\n create(params: CreateRecipeParams): Promise<HostedRecipe>;\n createVersion(name: string, params: CreateRecipeVersionParams): Promise<HostedRecipe>;\n archive(name: string): Promise<void>;\n}\n\nexport interface RecipesCommandDependencies {\n recipes: RecipesClient;\n writeStdout(text: string): void;\n}\n\nfunction optionValue(args: string[], index: number, option: string): string {\n const value = args[index + 1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(`${option} requires a value`);\n return value;\n}\n\nfunction positiveInteger(value: string, option: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 1) {\n throw new UsageError(`${option} must be a positive integer`);\n }\n return parsed;\n}\n\nasync function recipeFile(path: string): Promise<Record<string, unknown>> {\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch (error) {\n throw new UsageError(`Could not read recipe file: ${path}`, { cause: error });\n }\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) throw new Error();\n return parsed as Record<string, unknown>;\n } catch {\n throw new UsageError(\"Recipe file must contain one JSON object\");\n }\n}\n\nfunction humanRecipe(recipe: HostedRecipe): string {\n const kind = recipe.builtIn ? \"built-in\" : \"custom\";\n return `${recipe.reference}\\n${recipe.description || \"No description\"}\\nType: ${kind}\\nStatus: ${recipe.status}\\n`;\n}\n\nfunction humanList(recipes: HostedRecipe[]): string {\n const headings = [\"REFERENCE\", \"TYPE\", \"DESCRIPTION\"];\n const rows = recipes.map((recipe) => [\n recipe.reference,\n recipe.builtIn ? \"built-in\" : \"custom\",\n recipe.description || \"-\",\n ]);\n const widths = headings.map((heading, index) =>\n Math.max(heading.length, ...rows.map((row) => row[index]?.length ?? 0)),\n );\n const render = (row: string[]): string =>\n row.map((value, index) => value.padEnd(widths[index] ?? value.length)).join(\" \").trimEnd();\n return `${[render(headings), render(widths.map((width) => \"-\".repeat(width))), ...rows.map(render)].join(\"\\n\")}\\n`;\n}\n\nfunction output(recipe: HostedRecipe, json: boolean, write: (text: string) => void): void {\n write(json ? `${JSON.stringify(recipe)}\\n` : humanRecipe(recipe));\n}\n\nexport async function runRecipesCommand(\n args: string[],\n dependencies: RecipesCommandDependencies,\n): Promise<number> {\n const subcommand = args[0];\n const rest = args.slice(1);\n const json = rest.includes(\"--json\");\n\n if (subcommand === \"list\") {\n if (rest.some((value) => value !== \"--json\")) throw new UsageError(\"Usage: mediaruntime recipes list [--json]\");\n const recipes = await dependencies.recipes.list();\n dependencies.writeStdout(json ? `${JSON.stringify({ recipes })}\\n` : humanList(recipes));\n return 0;\n }\n\n if (subcommand === \"get\") {\n let name: string | undefined;\n let version: number | undefined;\n for (let index = 0; index < rest.length; index += 1) {\n const value = rest[index];\n if (value === \"--version\") {\n version = positiveInteger(optionValue(rest, index, value), value);\n index += 1;\n } else if (value !== \"--json\" && !name) name = value;\n else if (value !== \"--json\") throw new UsageError(\"recipes get accepts one name\");\n }\n if (!name) throw new UsageError(\"Usage: mediaruntime recipes get <name> [--version <n>]\");\n output(await dependencies.recipes.get(name, version ? { version } : {}), json, dependencies.writeStdout);\n return 0;\n }\n\n if (subcommand === \"create\") {\n let file: string | undefined;\n for (let index = 0; index < rest.length; index += 1) {\n if (rest[index] === \"--file\") {\n file = optionValue(rest, index, \"--file\");\n index += 1;\n } else if (rest[index] !== \"--json\") throw new UsageError(`Unknown recipes create option: ${rest[index]}`);\n }\n if (!file) throw new UsageError(\"Usage: mediaruntime recipes create --file <recipe.json>\");\n const value = await recipeFile(file);\n if (typeof value.name !== \"string\" || typeof value.template !== \"object\") {\n throw new UsageError(\"Recipe JSON requires name and template\");\n }\n output(await dependencies.recipes.create(value as unknown as CreateRecipeParams), json, dependencies.writeStdout);\n return 0;\n }\n\n if (subcommand === \"version\") {\n let name: string | undefined;\n let file: string | undefined;\n let expected: number | undefined;\n for (let index = 0; index < rest.length; index += 1) {\n const value = rest[index];\n if (value === \"--file\") {\n file = optionValue(rest, index, value);\n index += 1;\n } else if (value === \"--expected\") {\n expected = positiveInteger(optionValue(rest, index, value), value);\n index += 1;\n } else if (value !== \"--json\" && !name) name = value;\n else if (value !== \"--json\") throw new UsageError(`Unknown recipes version option: ${value}`);\n }\n if (!name || !file || !expected) {\n throw new UsageError(\"Usage: mediaruntime recipes version <name> --file <recipe.json> --expected <n>\");\n }\n const value = await recipeFile(file);\n const template = value.template ?? value;\n output(await dependencies.recipes.createVersion(name, {\n expectedLatestVersion: expected,\n ...(typeof value.description === \"string\" ? { description: value.description } : {}),\n template: template as CreateRecipeVersionParams[\"template\"],\n }), json, dependencies.writeStdout);\n return 0;\n }\n\n if (subcommand === \"archive\") {\n const values = rest.filter((value) => value !== \"--json\");\n if (values.length !== 1) throw new UsageError(\"Usage: mediaruntime recipes archive <name>\");\n await dependencies.recipes.archive(values[0] ?? \"\");\n dependencies.writeStdout(json\n ? `${JSON.stringify({ name: values[0], status: \"archived\" })}\\n`\n : `Archived recipe ${values[0]}\\n`);\n return 0;\n }\n\n throw new UsageError(\"Usage: mediaruntime recipes <list|get|create|version|archive>\");\n}\n","import { randomBytes, randomUUID } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\n\nimport { parseLocalDestination } from \"../trigger/destination.js\";\nimport {\n SUPPORTED_TRIGGER_EVENTS,\n createSyntheticTerminalEvent,\n isTriggerEventType,\n type TriggerEventType,\n} from \"../trigger/event.js\";\nimport { signSyntheticWebhook } from \"../trigger/signature.js\";\nimport { TriggerDeliveryError, UsageError } from \"../errors.js\";\n\nexport interface TriggerCommandDependencies {\n env?: Readonly<Record<string, string | undefined>>;\n fetch?: typeof globalThis.fetch;\n now?: () => number;\n randomUUID?: () => string;\n randomBytes?: (size: number) => Uint8Array;\n readFile?: (path: string, encoding: \"utf8\") => Promise<string>;\n writeStdout?: (text: string) => void;\n}\n\ninterface TriggerArguments {\n type: TriggerEventType;\n destination: URL;\n secretFile?: string;\n generateSecret: boolean;\n jobId?: string;\n accountId?: string;\n json: boolean;\n}\n\nfunction requireOptionValue(args: string[], index: number, option: string): string {\n const value = args[index + 1];\n if (!value || value.startsWith(\"--\")) throw new UsageError(`${option} requires a value`);\n return value;\n}\n\nexport function parseTriggerArguments(args: string[]): TriggerArguments {\n const typeValue = args[0];\n if (!typeValue || typeValue.startsWith(\"--\")) {\n throw new UsageError(\n `trigger requires an event type: ${SUPPORTED_TRIGGER_EVENTS.join(\", \")}`,\n );\n }\n if (!isTriggerEventType(typeValue)) {\n throw new UsageError(\n `Unsupported trigger event ${JSON.stringify(typeValue)}; expected ${SUPPORTED_TRIGGER_EVENTS.join(\", \")}`,\n );\n }\n\n let to: string | undefined;\n let secretFile: string | undefined;\n let generateSecret = false;\n let jobId: string | undefined;\n let accountId: string | undefined;\n let json = false;\n for (let index = 1; index < args.length; index += 1) {\n const option = args[index];\n if (!option) continue;\n if (option === \"--generate-secret\") {\n generateSecret = true;\n continue;\n }\n if (option === \"--json\") {\n json = true;\n continue;\n }\n if ([\"--to\", \"--secret-file\", \"--job-id\", \"--account-id\"].includes(option)) {\n const value = requireOptionValue(args, index, option);\n index += 1;\n if (option === \"--to\") to = value;\n else if (option === \"--secret-file\") secretFile = value;\n else if (option === \"--job-id\") jobId = value;\n else accountId = value;\n continue;\n }\n throw new UsageError(`Unknown trigger option: ${option}`);\n }\n\n if (!to) throw new UsageError(\"trigger requires an explicit --to local URL\");\n if (generateSecret && secretFile) {\n throw new UsageError(\"--generate-secret and --secret-file are mutually exclusive\");\n }\n if (generateSecret && json) {\n throw new UsageError(\"--generate-secret and --json are mutually exclusive\");\n }\n if (jobId !== undefined && !jobId.trim()) throw new UsageError(\"--job-id must not be empty\");\n if (accountId !== undefined && !accountId.trim()) {\n throw new UsageError(\"--account-id must not be empty\");\n }\n return {\n type: typeValue,\n destination: parseLocalDestination(to),\n ...(secretFile === undefined ? {} : { secretFile }),\n generateSecret,\n ...(jobId === undefined ? {} : { jobId: jobId.trim() }),\n ...(accountId === undefined ? {} : { accountId: accountId.trim() }),\n json,\n };\n}\n\nasync function resolveSecret(\n args: TriggerArguments,\n dependencies: Required<\n Pick<TriggerCommandDependencies, \"env\" | \"randomBytes\" | \"readFile\" | \"writeStdout\">\n >,\n): Promise<string> {\n if (args.generateSecret) {\n const generated = Buffer.from(dependencies.randomBytes(32)).toString(\"base64url\");\n dependencies.writeStdout(\n `Generated webhook secret (configure the local receiver with this value): ${generated}\\n`,\n );\n return generated;\n }\n let secret: string | undefined;\n if (args.secretFile) {\n try {\n secret = await dependencies.readFile(args.secretFile, \"utf8\");\n } catch (error) {\n throw new UsageError(`Could not read webhook secret file: ${args.secretFile}`, { cause: error });\n }\n } else {\n secret = dependencies.env.MEDIARUNTIME_WEBHOOK_SECRET;\n }\n const normalized = secret?.trim();\n if (!normalized) {\n throw new UsageError(\n \"Set MEDIARUNTIME_WEBHOOK_SECRET, pass --secret-file, or explicitly use --generate-secret\",\n );\n }\n return normalized;\n}\n\nexport async function runTriggerCommand(\n args: string[],\n dependencies: TriggerCommandDependencies = {},\n): Promise<number> {\n const parsed = parseTriggerArguments(args);\n const deps = {\n env: dependencies.env ?? process.env,\n fetch: dependencies.fetch ?? globalThis.fetch,\n now: dependencies.now ?? Date.now,\n randomUUID: dependencies.randomUUID ?? randomUUID,\n randomBytes: dependencies.randomBytes ?? randomBytes,\n readFile: dependencies.readFile ?? readFile,\n writeStdout: dependencies.writeStdout ?? ((text: string) => process.stdout.write(text)),\n };\n const secret = await resolveSecret(parsed, deps);\n const timestamp = Math.floor(deps.now() / 1000);\n const unique = deps.randomUUID();\n const eventId = `evt_cli_${unique}`;\n const jobId = parsed.jobId ?? `job_cli_${unique}`;\n const accountId = parsed.accountId ?? \"acc_cli_local\";\n const payload = createSyntheticTerminalEvent(parsed.type, {\n eventId,\n jobId,\n accountId,\n timestamp,\n });\n const signed = signSyntheticWebhook(payload, { eventId, timestamp, secret });\n\n const response = await deps.fetch(parsed.destination, {\n method: \"POST\",\n headers: signed.headers,\n body: signed.body,\n redirect: \"manual\",\n signal: AbortSignal.timeout(10_000),\n });\n if (!response.ok) {\n throw new TriggerDeliveryError(\n `Local webhook endpoint returned HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : \"\"}`,\n );\n }\n if (parsed.json) {\n deps.writeStdout(`${JSON.stringify({\n eventId,\n type: parsed.type,\n jobId,\n status: payload.status,\n destination: parsed.destination.href,\n httpStatus: response.status,\n })}\\n`);\n } else {\n deps.writeStdout(\n `Sent synthetic ${parsed.type} event ${eventId} to ${parsed.destination.href} (HTTP ${response.status})\\n`,\n );\n }\n return 0;\n}\n","import { UsageError } from \"../errors.js\";\n\nexport function isLoopbackDestination(value: URL): boolean {\n let hostname = value.hostname.toLowerCase();\n if (hostname.endsWith(\".\")) hostname = hostname.slice(0, -1);\n if (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n hostname = hostname.slice(1, -1);\n }\n if (hostname === \"localhost\" || hostname === \"::1\" || hostname === \"0:0:0:0:0:0:0:1\") {\n return true;\n }\n\n const octets = hostname.split(\".\");\n if (octets.length !== 4 || octets.some((part) => !/^\\d{1,3}$/.test(part))) return false;\n const numbers = octets.map(Number);\n return numbers[0] === 127 && numbers.every((part) => part >= 0 && part <= 255);\n}\n\nexport function parseLocalDestination(raw: string): URL {\n let destination: URL;\n try {\n destination = new URL(raw);\n } catch {\n throw new UsageError(\"--to must be an absolute local HTTP(S) URL\");\n }\n if (destination.protocol !== \"http:\" && destination.protocol !== \"https:\") {\n throw new UsageError(\"--to must use http:// or https://\");\n }\n if (destination.username || destination.password) {\n throw new UsageError(\"--to must not contain URL credentials\");\n }\n if (!isLoopbackDestination(destination)) {\n throw new UsageError(\n \"trigger only sends to loopback destinations (localhost, 127.0.0.0/8, or ::1)\",\n );\n }\n return destination;\n}\n","export const SUPPORTED_TRIGGER_EVENTS = [\n \"job.completed\",\n \"job.failed\",\n \"job.rejected\",\n] as const;\n\nexport type TriggerEventType = (typeof SUPPORTED_TRIGGER_EVENTS)[number];\n\nexport function isTriggerEventType(value: string): value is TriggerEventType {\n return (SUPPORTED_TRIGGER_EVENTS as readonly string[]).includes(value);\n}\n\nexport interface SyntheticEventOptions {\n eventId: string;\n jobId: string;\n accountId: string;\n timestamp: number;\n}\n\nexport function createSyntheticTerminalEvent(\n type: TriggerEventType,\n options: SyntheticEventOptions,\n): Record<string, unknown> {\n const status = type.slice(\"job.\".length).toUpperCase();\n const occurredAt = new Date(options.timestamp * 1000).toISOString();\n const base = {\n event_id: options.eventId,\n job_id: options.jobId,\n account_id: options.accountId,\n status,\n };\n\n if (type === \"job.completed\") {\n const expiresAt = new Date((options.timestamp + 7 * 24 * 60 * 60) * 1000).toISOString();\n return {\n ...base,\n completedAt: occurredAt,\n delivery: {\n mode: \"PULL\",\n retentionDays: 7,\n expiresAt,\n bundle: {\n type: \"zip\",\n filename: `${options.jobId}_outputs.zip`,\n size_bytes: 0,\n sha256: \"0\".repeat(64),\n download: {\n url: `http://127.0.0.1/__mediaruntime_synthetic__/${encodeURIComponent(options.jobId)}.zip`,\n expiresAt,\n },\n },\n layout: \"bundle_relative_v1\",\n deliverables: [],\n manifests: {},\n },\n billing: { status: \"PAID\" },\n usage: { units_total: 0 },\n meta: { synthetic: true, request_metadata: {} },\n };\n }\n\n const failed = type === \"job.failed\";\n return {\n ...base,\n [failed ? \"failedAt\" : \"rejectedAt\"]: occurredAt,\n delivery: { mode: \"NONE\" },\n billing: { status: \"RELEASED\" },\n error: {\n code: failed ? \"SYNTHETIC_ENGINE_FAILED\" : \"SYNTHETIC_REJECTED\",\n message: `Synthetic ${type} event from the MediaRuntime CLI`,\n },\n meta: { synthetic: true, request_metadata: {} },\n };\n}\n","import { createHmac } from \"node:crypto\";\n\nexport const WEBHOOK_HEADERS = {\n id: \"X-Transcoder-Id\",\n timestamp: \"X-Transcoder-Timestamp\",\n signature: \"X-Transcoder-Signature\",\n} as const;\n\nexport interface SignedWebhook {\n body: string;\n headers: Record<string, string>;\n}\n\nexport function signSyntheticWebhook(\n payload: Readonly<Record<string, unknown>>,\n options: { eventId: string; timestamp: number; secret: string },\n): SignedWebhook {\n if (!options.eventId.trim()) throw new Error(\"Webhook event ID must not be empty\");\n if (!Number.isInteger(options.timestamp) || options.timestamp < 0) {\n throw new Error(\"Webhook timestamp must be a non-negative integer\");\n }\n if (!options.secret) throw new Error(\"Webhook secret must not be empty\");\n\n // JSON is serialized once. These exact bytes are both signed and sent.\n const body = JSON.stringify(payload);\n const bodyBytes = Buffer.from(body, \"utf8\");\n const prefix = Buffer.from(`${options.timestamp}.${options.eventId}.`, \"utf8\");\n const digest = createHmac(\"sha256\", options.secret)\n .update(prefix)\n .update(bodyBytes)\n .digest(\"hex\");\n\n return {\n body,\n headers: {\n \"Content-Type\": \"application/json\",\n [WEBHOOK_HEADERS.id]: options.eventId,\n [WEBHOOK_HEADERS.timestamp]: String(options.timestamp),\n [WEBHOOK_HEADERS.signature]: `t=${options.timestamp},v1=${digest}`,\n },\n };\n}\n","const FRAMES = [\"⣋\", \"⣙\", \"⣹\", \"⣸\", \"⣼\", \"⣴\", \"⣦\", \"⣧\", \"⣇\", \"⣏\"];\nconst CLEAR_LINE = \"\\r\\u001b[2K\";\n\nexport interface ActivityIndicator {\n start(message: string): void;\n update(message: string): void;\n stop(): void;\n}\n\nexport function createActivityIndicator(\n write: (text: string) => void,\n enabled: boolean,\n): ActivityIndicator {\n let timer: ReturnType<typeof setInterval> | undefined;\n let frameIndex = 0;\n let message = \"\";\n let startedAt = 0;\n\n const render = (): void => {\n if (!timer && startedAt === 0) return;\n const elapsedSeconds = Math.max(0, Math.floor((Date.now() - startedAt) / 1000));\n const elapsed = elapsedSeconds > 0 ? ` (${elapsedSeconds}s)` : \"\";\n write(`${CLEAR_LINE}${FRAMES[frameIndex % FRAMES.length]} ${message}${elapsed}`);\n frameIndex += 1;\n };\n\n return {\n start(nextMessage) {\n if (!enabled) return;\n if (timer) clearInterval(timer);\n message = nextMessage;\n startedAt = Date.now();\n frameIndex = 0;\n render();\n timer = setInterval(render, 80);\n timer.unref?.();\n },\n update(nextMessage) {\n if (!enabled || startedAt === 0) return;\n message = nextMessage;\n render();\n },\n stop() {\n if (!enabled || startedAt === 0) return;\n if (timer) clearInterval(timer);\n timer = undefined;\n startedAt = 0;\n write(CLEAR_LINE);\n },\n };\n}\n"],"mappings":";;;AAAA,SAAS,cAAAA,aAAY,cAAAC,mBAAkB;AACvC,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB;AAClC,SAAS,UAAU,SAAS,eAAe;AAC3C,SAAS,UAAU,iBAAiB;AACpC,SAAS,gBAAgB;AAEzB,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACnBA,IAAM,WAAN,cAAuB,MAAM;AAAA,EACzB;AAAA,EACA;AAAA,EAET,YAAY,MAAc,SAAiB,UAAkB,SAA+B;AAC1F,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;AAEO,IAAM,aAAN,cAAyB,SAAS;AAAA,EACvC,YAAY,SAAiB,SAA+B;AAC1D,UAAM,eAAe,SAAS,GAAG,OAAO;AACxC,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,uBAAN,cAAmC,SAAS;AAAA,EACjD,YAAY,SAAiB,SAA+B;AAC1D,UAAM,0BAA0B,SAAS,GAAG,OAAO;AACnD,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,sBAAN,cAAkC,SAAS;AAAA,EAChD,YAAY,SAAiB,SAA+B;AAC1D,UAAM,yBAAyB,SAAS,GAAG,OAAO;AAClD,SAAK,OAAO;AAAA,EACd;AACF;;;AC9BO,IAAM,oBAAoB;AA8B1B,IAAM,eAAN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AAM,eAAe,OAAO,KAAK,MAAM,CAAC,GAAG,mBAAmB;AAAA,IACvE;AACA,QAAI,YAAY,WAAW;AACzB,UAAI,CAAC,OAAO,QAAS,OAAM,IAAI,WAAW,0DAA0D;AACpG,aAAO,MAAM,kBAAkB,OAAO,KAAK,MAAM,CAAC,GAAG;AAAA,QACnD,SAAS,OAAO;AAAA,QAChB;AAAA,MACF,CAAC;AAAA,IACH;AACA,UAAM,IAAI,WAAW,oBAAoB,OAAO,EAAE;AAAA,EACpD,SAAS,OAAO;AACd,UAAM,WAAW,YAAY,KAAK;AAClC,QAAI,MAAM;AACR,kBAAY,GAAG,KAAK,UAAU,EAAE,OAAO,UAAU,OAAO,QAAQ,EAAE,CAAC,CAAC;AAAA,CAAI;AAAA,IAC1E,OAAO;AACL,YAAM,YAAY,iBAAiB,wBAAwB,MAAM,YAC7D,aAAa,MAAM,SAAS,MAC5B;AACJ,kBAAY,UAAU,iBAAiB,QAAQ,MAAM,UAAU,eAAe,GAAG,SAAS;AAAA,CAAI;AAAA,IAChG;AACA,WAAO;AAAA,EACT;AACF;AAEA,IAAI,eAAe;AACnB,IAAI,QAAQ,KAAK,CAAC,MAAM,QAAW;AACjC,MAAI;AAGF,mBAAe,aAAa,QAAQ,KAAK,CAAC,CAAC,MAAM,aAAa,cAAc,YAAY,GAAG,CAAC;AAAA,EAC9F,QAAQ;AACN,mBAAe;AAAA,EACjB;AACF;AACA,IAAI,aAAc,SAAQ,WAAW,MAAM,WAAW,QAAQ,KAAK,MAAM,CAAC,CAAC;","names":["createHash","randomUUID","resolve","resolve","cell","UNSUCCESSFUL_TERMINAL_STATUSES","optionValue","output","detailsProjection","optionValue","humanList","value","randomBytes","readFile","randomBytes","readFile","randomUUID","createHash"]}
package/docs/CLI_SDD.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # MediaRuntime CLI software design
2
2
 
3
- Status: stable public contract released as `1.0.0`
3
+ Status: stable public contract released as `1.2.0`
4
4
 
5
5
  Package: `@mediaruntime/cli`
6
6
 
@@ -15,6 +15,14 @@ ships the media commands plus an interactive authentication surface:
15
15
 
16
16
  ```text
17
17
  mediaruntime run <source> --output <alias>
18
+ mediaruntime run <source> --preset <public-preset>
19
+ mediaruntime capabilities
20
+ mediaruntime presets list
21
+ mediaruntime recipes list
22
+ mediaruntime recipes get <name>
23
+ mediaruntime recipes create --file <recipe.json>
24
+ mediaruntime recipes version <name> --file <recipe.json> --expected <version>
25
+ mediaruntime recipes archive <name>
18
26
  mediaruntime jobs list
19
27
  mediaruntime jobs get <job_id>
20
28
  mediaruntime trigger job.completed --to http://127.0.0.1:3000/webhooks/mediaruntime
@@ -53,9 +61,10 @@ engine directory layout.
53
61
  authenticated connections, event ownership, expiry, rate limits, and an abuse model.
54
62
  - Named multi-account profiles are deferred. Browser login stores one credential per API
55
63
  origin; an explicit environment key remains the account override.
56
- - Batch submission, explicit output recipe editing, moderation, watermark management,
64
+ - Batch submission, arbitrary inline output-object editing, moderation, watermark management,
57
65
  webhook registration, media-report retrieval, and moderation-result retrieval remain
58
- available through the SDK/API but are not CLI v1 commands.
66
+ available through the SDK/API but are not CLI v1 commands. Named public presets are
67
+ supported through `--preset`; arbitrary output objects remain deferred.
59
68
  - The CLI does not accept a per-job webhook URL. Terminal events go to the account-level
60
69
  destination configured in the MediaRuntime profile.
61
70
  - ZIP extraction, artifact selectors, HLS serving, and indefinite bundle retention are
@@ -67,6 +76,7 @@ The implementation depends on the released Node SDK and must not copy its HTTP c
67
76
  The following published contracts govern the CLI:
68
77
 
69
78
  - Node SDK `MediaRuntime`, `jobs.create`, `jobs.list`, `jobs.get`, and `Job.wait`.
79
+ - Node SDK `capabilities.retrieve()` and its ordered `publicPresets` catalog.
70
80
  - Gateway `contracts/v1/openapi.json` and `contracts/v1/conformance.json`.
71
81
  - Frozen output aliases: `video.web`, `video.streaming`, `video.social`, `audio.web`,
72
82
  `audio.transcription`, and `image.web`.
@@ -85,7 +95,7 @@ Authenticated commands resolve configuration once before doing file or network w
85
95
 
86
96
  | Setting | Highest precedence | Environment | Default |
87
97
  |---|---|---|---|
88
- | API key | `MEDIARUNTIME_API_KEY` | OS-vault browser login | required for `run` and `jobs` |
98
+ | API key | `MEDIARUNTIME_API_KEY` | OS-vault browser login | required for `run` and `jobs`; not required for capability discovery |
89
99
  | API base URL | `--base-url <url>` | `MEDIARUNTIME_API_URL` | `https://mediaruntime.com` |
90
100
  | Webhook signing secret | `--secret-file <path>` | `MEDIARUNTIME_WEBHOOK_SECRET` | required by `trigger`, unless explicitly generated |
91
101
 
@@ -110,7 +120,8 @@ mediaruntime --base-url http://127.0.0.1:8001 jobs list
110
120
  ### 5.1 `run`
111
121
 
112
122
  ```text
113
- mediaruntime run <source> --output <alias> [--output <alias> ...]
123
+ mediaruntime run <source>
124
+ (--output <alias> | --preset <public-preset>) [...]
114
125
  [--metadata <json-object>]
115
126
  [--idempotency-key <key>]
116
127
  [--wait]
@@ -119,12 +130,14 @@ mediaruntime run <source> --output <alias> [--output <alias> ...]
119
130
  [--json]
120
131
  ```
121
132
 
122
- `-o` is the short spelling of `--output`. Exactly one source and at least one output are
133
+ `-o` is the short spelling of `--output`. Exactly one source and at least one output or preset are
123
134
  required. `<source>` may be an HTTP(S) URL, `gs://` URI, local path, or `file://` URL. The
124
135
  CLI passes it to the SDK so local inputs use the SDK's signed-upload flow.
125
136
 
126
- Each `--output` must be one of the six frozen aliases. Repeating the option preserves the
127
- caller order. Explicit output objects and batch inputs are intentionally deferred from
137
+ Each `--output` must be one of the six frozen aliases. Each `--preset` must appear in the
138
+ gateway's ordered `publicPresets` catalog; the CLI retrieves its output type and submits
139
+ the corresponding explicit output object. Repeating and mixing both options preserves
140
+ caller order. Custom output objects and batch inputs remain intentionally deferred from
128
141
  the quick CLI; use an SDK when that control is required.
129
142
 
130
143
  `--metadata` is one JSON object, for example:
@@ -152,9 +165,38 @@ mediaruntime run ./launch.mp4 \
152
165
  --metadata '{"asset_id":"launch-01"}' \
153
166
  --idempotency-key 'asset:launch-01:v1' \
154
167
  --download ./launch-01.zip
168
+
169
+ mediaruntime run ./launch.mp4 \
170
+ --preset dash_ladder_v1 --preset webm_vp9_1080p \
171
+ --download ./adaptive-and-vp9.zip
172
+
173
+ mediaruntime run ./launch.mp4 \
174
+ --recipe team-video@3 \
175
+ --download ./launch.zip
155
176
  ```
156
177
 
157
- ### 5.2 `jobs list`
178
+ ### 5.2 Capability and preset discovery
179
+
180
+ ```text
181
+ mediaruntime capabilities [--json]
182
+ mediaruntime presets list [--json]
183
+ ```
184
+
185
+ Both commands call the unauthenticated capability endpoint and therefore do not require
186
+ a browser login or `MEDIARUNTIME_API_KEY`. Human output summarizes aliases, optional
187
+ features, and the ordered public preset table. JSON uses the Node SDK's camelCase contract;
188
+ `presets list --json` returns `{presets: [...]}` in gateway order. Neither command infers
189
+ public availability from the broader internal preset map.
190
+
191
+ ### 5.3 Hosted recipes
192
+
193
+ `recipes list/get/create/version/archive` delegates to the Node SDK recipe resource.
194
+ Create and version commands read explicit JSON files; secrets are never accepted in a
195
+ recipe or printed. `version --expected` is the optimistic-lock precondition. `run
196
+ --recipe` is mutually exclusive with aliases and public presets, and a resolved recipe
197
+ uses the same job wait, exit, spinner, and atomic ZIP path as any other job.
198
+
199
+ ### 5.4 `jobs list`
158
200
 
159
201
  ```text
160
202
  mediaruntime jobs list
@@ -173,7 +215,7 @@ The human table columns are `ID`, `STATUS`, `TIER`, `UNITS`, `BUNDLE`, and `UPDA
173
215
  List rows intentionally have no bundle download URL; `jobs get` is the download-aware
174
216
  surface.
175
217
 
176
- ### 5.3 `jobs get`
218
+ ### 5.5 `jobs get`
177
219
 
178
220
  ```text
179
221
  mediaruntime jobs get <job_id>
@@ -320,6 +362,8 @@ surface.
320
362
  - `run --wait` and `jobs get`: curated job details, with bundle availability,
321
363
  `expiresAt`, `sizeBytes`, `sha256`, and `retentionDays`, but no `downloadUrl`.
322
364
  - `jobs list`: `{jobs, nextCursor}` from the SDK.
365
+ - `capabilities`: the complete SDK capability projection.
366
+ - `presets list`: `{presets: [...]}` containing only ordered public preset rows.
323
367
  - `trigger`: `{eventId, type, jobId, status, destination, httpStatus}`.
324
368
 
325
369
  If `--download` is used, a successful atomic download is required before exit `0`. The
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mediaruntime/cli",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Official command-line client for MediaRuntime",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -32,7 +32,7 @@
32
32
  },
33
33
  "dependencies": {
34
34
  "@napi-rs/keyring": "^1.3.0",
35
- "@mediaruntime/node": "^1.0.0"
35
+ "@mediaruntime/node": "^1.2.0"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@types/node": "^24.3.0",