cheapgen 0.1.1 → 0.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/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "cheapgen",
3
- "version": "0.1.1",
4
- "description": "Send each AI video or image generation request to the cheapest connected provider (Kie, Replicate, WaveSpeed, fal).",
5
- "keywords": ["ai", "video", "image", "generation", "cli", "seedance", "seedream", "kie", "replicate", "wavespeed", "fal", "claude-code"],
3
+ "version": "0.2.0",
4
+ "description": "Send each AI video or image generation request to the cheapest connected provider (Kie, Replicate, WaveSpeed, fal, Higgsfield).",
5
+ "keywords": ["ai", "video", "image", "generation", "cli", "seedance", "seedream", "kie", "replicate", "wavespeed", "fal", "higgsfield", "claude-code", "mcp", "mcp-server",
6
+ "agent-skills", "codex", "github-copilot", "cursor"],
6
7
  "license": "MIT",
7
8
  "author": "jzr-supove (https://github.com/jzr-supove)",
8
9
  "repository": {
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: cheapgen
3
- description: Generate AI videos (Seedance 2.0 / 2.5) and images (Seedream 5, Nano Banana, FLUX 2 Pro) through the cheapest provider the user has a key for (Kie, Replicate, WaveSpeed, fal), using the cheapgen CLI. Use when the user asks to make, generate or price a video or image with one of these models, or asks what a generation would cost.
3
+ description: Generate AI videos (Seedance 2.0 / 2.5) and images (Seedream 5, Nano Banana, FLUX 2 Pro) through the cheapest provider the user has a key for (Kie, Replicate, WaveSpeed, fal, Higgsfield), using the cheapgen CLI. Use when the user asks to make, generate or price a video or image with one of these models, or asks what a generation would cost.
4
4
  ---
5
5
 
6
6
  # cheapgen
@@ -8,6 +8,10 @@ description: Generate AI videos (Seedance 2.0 / 2.5) and images (Seedream 5, Nan
8
8
  `cheapgen` is a CLI that prices a request on every provider and sends it to the cheapest
9
9
  connected one. Every real run spends the user's money, so follow these rules exactly.
10
10
 
11
+ If the `cheapgen` command isn't found (for example when it came with a plugin), run it as
12
+ `npx -y cheapgen@latest` with the same arguments. If cheapgen's MCP tools are available (`quote`,
13
+ `run`, `wait_job` and others), you can use them instead; the same rules apply.
14
+
11
15
  ## Rules
12
16
 
13
17
  1. **Quote before every run.** Run `cheapgen quote <model> [params] --json` and tell the user
@@ -23,9 +27,10 @@ connected one. Every real run spends the user's money, so follow these rules exa
23
27
  another provider. Tell the user to check that provider's dashboard and let them decide.
24
28
  5. **Keys are the user's.** Never ask for a key in the chat, and never put one in a command.
25
29
  If no provider is connected (exit 3, `no_keys`), tell the user to set `KIE_API_KEY`,
26
- `REPLICATE_API_TOKEN`, `WAVESPEED_API_KEY` or `FAL_KEY`, or to run
30
+ `REPLICATE_API_TOKEN`, `WAVESPEED_API_KEY`, `FAL_KEY` or `HIGGSFIELD_API_KEY`, or to run
27
31
  `cheapgen config set-key <provider>` themselves in a terminal (it asks for
28
- the key and hides it).
32
+ the key and hides it). A Higgsfield key has the form `KEY_ID:KEY_SECRET` and is for the
33
+ Higgsfield API, which has its own balance; a higgsfield.ai subscription doesn't pay for it.
29
34
  6. **Don't change the user's config** (`cheapgen config set ...`) unless they ask.
30
35
 
31
36
  ## Models
@@ -38,11 +43,43 @@ Video: `seedance-2.0-mini` (cheapest), `seedance-2.0-fast`, `seedance-2.0`,
38
43
  ## Parameters
39
44
 
40
45
  - `--prompt TEXT`: what to generate. Quote it for the shell; prefer single quotes.
41
- - `--image FILE|URL`: first frame, which makes it image-to-video. Local files are uploaded.
42
- - Video: `--res 480p|720p|1080p` (default 720p), `--duration SECONDS` (default 5),
46
+ - `--image FILE|URL`: on a video model, the first frame, which makes it image-to-video (one
47
+ only). On an image model, an image to edit; repeat it to combine several, in the order given.
48
+ PNG, JPEG or WebP, up to 30 MB each. Local files are uploaded to the provider that runs the job,
49
+ so tell the user before sending a file they haven't asked you to send.
50
+ - `--last-image FILE|URL`: video only, with `--image`: the last frame. The video runs from the
51
+ first frame to the last.
52
+ - `--ref-image FILE|URL` and `--ref-audio FILE|URL`: video only, each repeatable: reference
53
+ images (a character, product or style) and reference audio (a voice or music), which makes it
54
+ reference-to-video. They can't be combined with `--image` or `--last-image`.
55
+ - Name them in the prompt by position: `@image1` is the first `--ref-image`, `@audio1` the
56
+ first `--ref-audio`. cheapgen rewrites the names for the provider that gets the job.
57
+ - Limits: 9 images and 3 audio files on the `seedance-2.0` models, 30 and 10 on
58
+ `seedance-2.5`, 10 and 5 on `seedance-2.5-flash` (`cheapgen models --json` has them under
59
+ `references`). Audio is WAV or MP3, at least 2 seconds, and at most 15 seconds in total on
60
+ the 2.0 models or 30 on the 2.5 models. The 2.0 models need at least one image with audio.
61
+ - Frames and reference images are PNG, JPEG or WebP, up to 30 MB, 300 to 6000 pixels a side.
62
+ - The model rejects reference images that show a real person's face. Tell the user before
63
+ they pay for a run that is likely to be rejected.
64
+ - A last frame or references don't change the price. If a provider's price for references is
65
+ unknown (`usd: null`), rule 2 applies.
66
+ - The quote lists providers that can't take the inputs under `unavailable`, with the reason
67
+ (for example, reference audio with no image).
68
+ - Video: `--res 480p|720p|1080p|4k` (default 720p; 4k only on `seedance-2.0` and `seedance-2.5`,
69
+ as a 10-bit H.265/HEVC file that some players can't open), `--duration SECONDS` (default 5),
43
70
  `--aspect 16:9|9:16|1:1|4:3|3:4|21:9` (default 16:9), `--audio` / `--no-audio` (default on).
71
+ - 1080p and 4k on `seedance-2.0-mini`, `seedance-2.0-fast` and `seedance-2.5-flash` exist only as
72
+ WaveSpeed's upscaled 720p, and only when the user has turned on the `allowVariants` setting.
73
+ Without it they are a usage error that says so. Don't turn the setting on yourself (rule 6):
74
+ tell the user what it means and let them decide. When it is on, the quote has
75
+ `"variant": "wavespeed-upscaled"` and a warning; pass that on to the user.
44
76
  - Image: `--size` (default 1K, or the model's smallest; `cheapgen models` lists each model's
45
- sizes, such as 1.5K or 3K), `--aspect`.
77
+ sizes, such as 1.5K or 3K), `--aspect`. With `--image` the result follows the first input's
78
+ shape (`--aspect auto`, the default when editing); set a ratio to change it.
79
+ - Editing: input images can add to the price and providers differ in how many they take. The
80
+ quote already includes this. In `--json` it lists providers that can't take the request under
81
+ `unavailable` (`provider`, `reason`); if a reason says the provider needs `--aspect`, adding
82
+ one brings it back.
46
83
  - Don't use `--duration auto`: the cost is only known afterwards. If the user insists, it needs
47
84
  `--allow-auto-duration`, and the quote shows the maximum cost.
48
85
 
package/src/catalog.js CHANGED
@@ -15,6 +15,34 @@ function readJson(file) {
15
15
  }
16
16
  }
17
17
 
18
+ /**
19
+ * A provider's entry for a model, as the request needs it: for an image edit the provider's edit
20
+ * block (endpoint, image field, limits) is attached as `edit`. Null when the provider doesn't
21
+ * list the model.
22
+ */
23
+ export function entryFor(catalog, providerId, request) {
24
+ const model = catalog.models[request.model];
25
+ const entry = model?.providers?.[providerId];
26
+ if (!entry) return null;
27
+ if (request.mode !== 'image-edit') return entry;
28
+ const edit = model.edit?.providers?.[providerId];
29
+ return edit ? { ...entry, edit } : entry;
30
+ }
31
+
32
+ /**
33
+ * The variant that sells `resolution` for a model which doesn't list it itself: something one
34
+ * provider offers under the model's name that may differ in quality (an upscaled resolution,
35
+ * for example). Null when the model lists the resolution, or no variant has it.
36
+ * @returns {{ id: string, provider: string, resolutions: string[], label: string, note: string } | null}
37
+ */
38
+ export function variantFor(model, resolution) {
39
+ if (!resolution || model?.resolutions?.includes(resolution)) return null;
40
+ for (const [id, v] of Object.entries(model?.variants ?? {})) {
41
+ if (v.resolutions?.includes(resolution)) return { id, ...v };
42
+ }
43
+ return null;
44
+ }
45
+
18
46
  /**
19
47
  * @param {string} [dataDir]
20
48
  * @returns {{ models: object, prices: { schemaVersion: number, entries: object[] }, frameSizes: object }}
@@ -1,6 +1,6 @@
1
1
  // `cheapgen config list | show | path | set <key> <value> | set-key <provider> | get-key <provider>`.
2
2
  import { EXIT, usageError } from '../../errors.js';
3
- import { PROVIDER_IDS, ENV_VARS, storeKey, storeSetting } from '../../config.js';
3
+ import { PROVIDER_IDS, storeKey, storeSetting, envNameOf, keyParts } from '../../config.js';
4
4
  import { ADAPTERS } from '../../providers/index.js';
5
5
  import { notConnectedError } from '../../router.js';
6
6
  import { table } from '../output.js';
@@ -13,7 +13,7 @@ const mask = (key) => (key.length < MIN_LENGTH_TO_SHOW_END ? '****' : `****${key
13
13
 
14
14
  function keyInfo(app, id) {
15
15
  const key = app.keys[id];
16
- return { provider: id, envVar: ENV_VARS[id], set: Boolean(key), source: app.keySources[id], masked: key ? mask(key) : null };
16
+ return { provider: id, envVar: envNameOf(app, id), set: Boolean(key), source: app.keySources[id], masked: key ? mask(key) : null };
17
17
  }
18
18
 
19
19
  const sourceText = (info) => (info.source === 'env' ? info.envVar : 'config file');
@@ -59,7 +59,7 @@ function getKey(app, rest) {
59
59
  function show(app, rest) {
60
60
  if (rest.length) throw usageError(`too many arguments. Usage: ${USAGE}`);
61
61
  const keys = Object.fromEntries(PROVIDER_IDS.map((id) => [id,
62
- app.keySources[id] === 'env' ? `set (${ENV_VARS[id]})` : app.keySources[id] === 'file' ? 'set (config file)' : 'not set']));
62
+ app.keySources[id] === 'env' ? `set (${envNameOf(app, id)})` : app.keySources[id] === 'file' ? 'set (config file)' : 'not set']));
63
63
  const obj = { files: app.configFiles, settings: app.config, keys };
64
64
  app.out.result(obj, JSON.stringify(obj, null, 2));
65
65
  return EXIT.OK;
@@ -90,8 +90,9 @@ async function setKey(app, rest) {
90
90
  }
91
91
  const id = rest[0];
92
92
  checkProvider(id);
93
+ const format = ADAPTERS[id].keyFormat;
93
94
  const answer = app.io.promptSecret
94
- ? await app.io.promptSecret(`${ADAPTERS[id].displayName} API key (hidden): `)
95
+ ? await app.io.promptSecret(format?.prompt ?? `${ADAPTERS[id].displayName} API key (hidden): `)
95
96
  : await app.io.readStdin();
96
97
  if (answer === null) throw usageError('cancelled, nothing was stored');
97
98
  const input = String(answer ?? '');
@@ -100,10 +101,12 @@ async function setKey(app, rest) {
100
101
  throw usageError(app.io.promptSecret ? 'no key entered, nothing was stored'
101
102
  : `no key on standard input. Run \`cheapgen config set-key ${id}\` in a terminal, or pipe the key in.`);
102
103
  }
103
- app.secrets.push(key);
104
+ app.secrets.push(key, ...keyParts(id, key));
105
+ // The message never repeats the input: a mistyped key is still mostly a key.
106
+ if (format && !format.pattern.test(key)) throw usageError(format.hint);
104
107
  const { file, warnings } = storeKey(app.io, id, key);
105
108
  for (const w of warnings) app.out.warn(w);
106
- if (app.keySources[id] === 'env') app.out.warn(`${ENV_VARS[id]} is set in your environment and takes precedence over the stored key`);
109
+ if (app.keySources[id] === 'env') app.out.warn(`${envNameOf(app, id)} is set in your environment and takes precedence over the stored key`);
107
110
  app.out.result({ stored: true, provider: id, file }, `Stored the ${id} key in ${file}.`);
108
111
  return EXIT.OK;
109
112
  }
@@ -3,8 +3,10 @@ import { run } from './run.js';
3
3
  import { status, wait } from './jobs.js';
4
4
  import { providers, models, spend, prices } from './info.js';
5
5
  import { config } from './config.js';
6
+ import { skill } from './skill.js';
7
+ import { mcp } from './mcp.js';
6
8
 
7
- export const COMMANDS = { providers, models, quote, run, status, wait, spend, prices, config };
9
+ export const COMMANDS = { providers, models, quote, run, status, wait, spend, prices, config, skill, mcp };
8
10
 
9
11
  export const HELP = `cheapgen: send each AI video or image request to the cheapest connected provider.
10
12
 
@@ -21,13 +23,29 @@ Usage:
21
23
  cheapgen config get-key <provider> show whether a key is set (last 4 characters)
22
24
  cheapgen config list list keys and settings
23
25
  cheapgen config show | path | set <key> <value>
26
+ cheapgen skill install [--agent claude|codex|cursor|copilot|opencode] [--project]
27
+ add the agent skill (also: skill uninstall, skill path)
28
+ cheapgen mcp run the MCP server on stdin/stdout, for AI agents
24
29
 
25
30
  Parameters:
26
31
  --prompt TEXT what to generate
27
- --image FILE|URL first frame (image-to-video)
28
- --res 480p|720p|1080p (default 720p) --size 1K|2K|4K|... (images; default 1K, or the model's smallest)
32
+ --image FILE|URL video models: the first frame (image-to-video)
33
+ image models: an image to edit; repeat it to combine several
34
+ (PNG, JPEG or WebP, up to 30 MB each; local files are uploaded)
35
+ --last-image FILE|URL video: the last frame, together with --image
36
+ --ref-image FILE|URL video: a reference image (a character, product or style); repeat it
37
+ --ref-audio FILE|URL video: reference audio (WAV or MP3, 2 to 15 seconds; 30 on the 2.5 models)
38
+ References can't be combined with --image. Name them in the prompt as
39
+ @image1, @audio1. \`cheapgen models --json\` shows how many a model takes.
40
+ Local files are uploaded to the provider that runs the job. The model
41
+ rejects reference images that show a real person's face.
42
+ --res 480p|720p|1080p|4k (default 720p) --size 1K|2K|4K|... (images; default 1K, or the model's smallest)
29
43
  --duration SECONDS (default 5) --aspect 16:9|9:16|1:1|... (default 16:9)
44
+ --aspect auto: follow the first input image (the
45
+ default when editing an image)
30
46
  --audio | --no-audio (default on) --allow-auto-duration (accept the maximum cost)
47
+ 1080p and 4k on seedance-2.0-mini, -fast and seedance-2.5-flash are WaveSpeed's upscaled 720p,
48
+ off by default. Allow them with: cheapgen config set allowVariants true
31
49
 
32
50
  Run options:
33
51
  --provider ID use this provider only --exclude ID skip a provider for this run
@@ -37,6 +55,7 @@ Run options:
37
55
  --download DIR where to save results (default ./cheapgen-out) --no-download
38
56
  --json machine-readable output
39
57
 
40
- Keys: set KIE_API_KEY, REPLICATE_API_TOKEN, WAVESPEED_API_KEY or FAL_KEY, or store one with
41
- \`cheapgen config set-key <provider>\`, which asks for the key and hides it.
58
+ Keys: set KIE_API_KEY, REPLICATE_API_TOKEN, WAVESPEED_API_KEY, FAL_KEY or HIGGSFIELD_API_KEY, or
59
+ store one with \`cheapgen config set-key <provider>\`, which asks for the key and hides it.
60
+ A Higgsfield key is KEY_ID:KEY_SECRET.
42
61
  `;
@@ -1,6 +1,6 @@
1
1
  // Read-only commands: `providers`, `models`, `spend`, `prices`.
2
2
  import { EXIT, usageError } from '../../errors.js';
3
- import { PROVIDER_IDS, ENV_VARS } from '../../config.js';
3
+ import { PROVIDER_IDS, envNameOf } from '../../config.js';
4
4
  import { ADAPTERS } from '../../providers/index.js';
5
5
  import { connectedIds, noKeysError, isEnabled, balanceOf } from '../../router.js';
6
6
  import { readSpend, joinJobs } from '../../spend-log.js';
@@ -16,7 +16,7 @@ export async function providers(app) {
16
16
  for (const id of PROVIDER_IDS) {
17
17
  const connected = Boolean(app.keys[id]);
18
18
  const enabled = isEnabled(app, id);
19
- list.push({ id, name: ADAPTERS[id].displayName, envVar: ENV_VARS[id], connected, keySource: app.keySources[id],
19
+ list.push({ id, name: ADAPTERS[id].displayName, envVar: envNameOf(app, id), connected, keySource: app.keySources[id],
20
20
  enabled, balance: connected && enabled ? await balanceOf(app, id) : null });
21
21
  }
22
22
  const rows = list.map((p) => [p.id,
@@ -36,10 +36,18 @@ export async function models(app) {
36
36
  id, kind: m.kind, modes: m.modes,
37
37
  ...(m.kind === 'video' ? { resolutions: m.resolutions, durations: m.durations } : { sizes: m.sizes ?? [] }),
38
38
  aspectRatios: m.aspectRatios,
39
+ ...(m.references ? { references: { maxImages: m.references.maxImages, maxAudio: m.references.maxAudio,
40
+ audioAlone: m.references.audioAlone } } : {}),
41
+ ...(m.variants ? { variants: Object.entries(m.variants)
42
+ .map(([vid, v]) => ({ id: vid, provider: v.provider, resolutions: v.resolutions, note: v.note })) } : {}),
39
43
  providers: Object.keys(m.providers ?? {}).filter((p) => PROVIDER_IDS.includes(p))
40
44
  .map((p) => ({ id: p, connected: Boolean(app.keys[p]) })),
41
45
  }));
42
- const rows = list.map((m) => [m.id, m.kind, (m.resolutions ?? m.sizes).join('/'),
46
+ // With variants allowed, their resolutions are shown next to the model's own, with the first
47
+ // word of the variant's label ("upscaled") saying what kind they are.
48
+ const extra = (m) => (app.config.allowVariants ? Object.values(app.catalog.models[m.id].variants ?? {}) : [])
49
+ .map((v) => ` (+${v.resolutions.join('/')} ${v.label.split(' ')[0]})`).join('');
50
+ const rows = list.map((m) => [m.id, m.kind, (m.resolutions ?? m.sizes).join('/') + extra(m),
43
51
  m.providers.map((p) => (p.connected ? `${p.id}*` : p.id)).join(', ')]);
44
52
  const text = list.length ? `${table(rows)}\n(* = connected)` : `no model matches "${app.flags.search}"`;
45
53
  app.out.result({ models: list }, text);
@@ -0,0 +1,21 @@
1
+ // `cheapgen mcp`: run the MCP server on stdin and stdout, for agents that start it themselves.
2
+ import { EXIT } from '../../errors.js';
3
+ import { serveStdio } from '../../mcp/stdio.js';
4
+ import { noExtraArgs } from './shared.js';
5
+
6
+ /** Redacts every string inside a message, so the line stays valid JSON. */
7
+ function redactDeep(value, redact) {
8
+ if (typeof value === 'string') return redact(value);
9
+ if (Array.isArray(value)) return value.map((v) => redactDeep(v, redact));
10
+ if (value && typeof value === 'object') {
11
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [redact(k), redactDeep(v, redact)]));
12
+ }
13
+ return value;
14
+ }
15
+
16
+ export async function mcp(app) {
17
+ noExtraArgs(app, 0, 'cheapgen mcp');
18
+ const input = app.io.mcpInput ?? process.stdin;
19
+ await serveStdio({ io: app.io, input, write: (msg) => app.io.stdout.write(`${JSON.stringify(redactDeep(msg, app.redact))}\n`) });
20
+ return EXIT.OK;
21
+ }
@@ -5,7 +5,7 @@ import { PROVIDER_IDS } from '../../config.js';
5
5
  import { supports } from '../../providers/index.js';
6
6
  import { rankCandidates, priceOf, compareQuotes, isEnabled } from '../../router.js';
7
7
  import { staleWarnings } from '../../pricing/index.js';
8
- import { describeRequest, logParams } from '../../request.js';
8
+ import { describeRequest, logParams, variantWarning } from '../../request.js';
9
9
  import { usd, table } from '../output.js';
10
10
  import { requestFrom, excludeList, providerFlag } from './shared.js';
11
11
 
@@ -25,16 +25,27 @@ export async function quote(app) {
25
25
  }
26
26
 
27
27
  const quotes = [];
28
+ // Providers that carry the model but can't take this request, with the reason.
29
+ const unavailable = [];
28
30
  for (const id of PROVIDER_IDS) {
29
- if (!supports(app.catalog, id, request).ok) continue;
30
31
  const connected = Boolean(app.keys[id]);
32
+ const s = supports(app.catalog, id, request);
33
+ if (!s.ok) {
34
+ const listed = Boolean(app.catalog.models[request.model].providers?.[id]);
35
+ if (listed && (connected || app.config.showUnconnected)) {
36
+ unavailable.push({ provider: id, reason: s.reason.replace(`${id} `, '') });
37
+ }
38
+ continue;
39
+ }
31
40
  if (!connected && !app.config.showUnconnected) continue;
32
41
  const p = await priceOf(app, id, request);
33
42
  quotes.push({ provider: id, usd: p.usd, source: p.source, verifiedOn: p.verifiedOn ?? null, ageDays: p.ageDays ?? null,
34
- connected, enabled: isEnabled(app, id), chosen: id === chosen, ...(p.reason ? { reason: p.reason } : {}) });
43
+ connected, enabled: isEnabled(app, id), chosen: id === chosen, ...(p.reason ? { reason: p.reason } : {}),
44
+ ...(request.variant ? { variant: request.variant.id } : {}) });
35
45
  }
36
46
  quotes.sort((a, b) => compareQuotes(a, b, { prefer: app.config.prefer }));
37
47
  const warnings = staleWarnings(quotes);
48
+ if (request.variant) warnings.push(variantWarning(request));
38
49
  if (request.autoDuration) warnings.push(`auto duration: prices assume the maximum of ${request.maxDuration} seconds`);
39
50
  for (const w of warnings) app.out.warn(w);
40
51
 
@@ -42,13 +53,15 @@ export async function quote(app) {
42
53
  ` ${q.provider}`,
43
54
  usd(q.usd),
44
55
  q.source ? `${q.source} ${q.verifiedOn}` : '',
45
- [q.chosen ? '← run would use this' : '', !q.connected ? '(not connected)' : '', q.connected && !q.enabled ? '(disabled)' : '']
56
+ [q.chosen ? '← run would use this' : '', !q.connected ? '(not connected)' : '', q.connected && !q.enabled ? '(disabled)' : '',
57
+ q.variant ? `(${request.variant.label})` : '']
46
58
  .filter(Boolean).join(' '),
47
59
  ]);
48
60
  const text = [describeRequest(request), quotes.length ? table(rows) : ' no provider offers this request',
61
+ ...unavailable.map((u) => ` ${u.provider} can't take this request: it ${u.reason}`),
49
62
  ...(note && !chosen ? [` ${note}`] : [])].join('\n');
50
63
 
51
64
  app.out.result({ model: request.model, mode: request.mode, params: logParams(request), quotes, chosen, warnings,
52
- ...(note ? { note } : {}) }, text);
65
+ ...(unavailable.length ? { unavailable } : {}), ...(note ? { note } : {}) }, text);
53
66
  return EXIT.OK;
54
67
  }
@@ -7,13 +7,16 @@ import { pendingUpload } from '../../providers/common.js';
7
7
  import { rankCandidates, ctxFor } from '../../router.js';
8
8
  import { TIMEOUT_MS } from '../../jobs.js';
9
9
  import { appendSpend } from '../../spend-log.js';
10
- import { describeRequest, logParams } from '../../request.js';
10
+ import { describeRequest, logParams, variantWarning } from '../../request.js';
11
+ import { IMAGE_MIME, AUDIO_MIME } from '../../media.js';
11
12
  import { usd } from '../output.js';
12
13
  import { requestFrom, excludeList, providerFlag, maxCostFlag, timeoutFlag } from './shared.js';
13
14
  import { finishJob, describeFinished, downloadDirFrom } from './jobs.js';
14
15
 
15
16
  const EPS = 1e-9;
16
17
 
18
+ export const HEVC_NOTE = '4k video comes as 10-bit H.265/HEVC, which some players can\'t play. VLC and mpv can.';
19
+
17
20
  export async function run(app) {
18
21
  const { flags, out } = app;
19
22
  const request = requestFrom(app, { requirePrompt: true });
@@ -24,6 +27,9 @@ export async function run(app) {
24
27
  const timeoutMs = timeoutFlag(app) ?? TIMEOUT_MS[request.kind];
25
28
 
26
29
  const { ranked, pinned } = await rankCandidates(app, request, { provider, exclude });
30
+ // The codec note describes ByteDance's own 4k; a provider's upscaled variant may differ.
31
+ if (request.kind === 'video' && request.resolution === '4k' && !request.variant) out.notice(`Note: ${HEVC_NOTE}`);
32
+ if (request.variant) out.warn(variantWarning(request));
27
33
  const first = ranked[0];
28
34
  const overLimit = first.usd !== null && first.usd > limit + EPS;
29
35
 
@@ -54,9 +60,7 @@ export async function run(app) {
54
60
 
55
61
  let accepted;
56
62
  try {
57
- const imageUrl = !request.image ? undefined
58
- : request.imageIsLocal ? await adapter.upload(request.image, ctx) : request.image;
59
- accepted = await adapter.submit(request, ctx, { entry: c.entry, imageUrl });
63
+ accepted = await adapter.submit(request, ctx, { entry: c.entry, ...(await sendInputs(request, adapter, ctx)) });
60
64
  } catch (err) {
61
65
  if (err instanceof SubmitRejected) {
62
66
  lastRejection = { provider: c.provider, message: err.message };
@@ -69,6 +73,9 @@ export async function run(app) {
69
73
  continue;
70
74
  }
71
75
  if (err instanceof SubmitUnknown) {
76
+ // No job id, but a record of the attempt (and anything that identifies it) helps find the job later.
77
+ appendSpend(app, { event: 'submit_unknown', provider: c.provider, model: request.model, mode: request.mode,
78
+ params: logParams(request), estimateUsd: c.usd, ...(err.details ?? {}) });
72
79
  throw new CliError(EXIT.UNKNOWN_OUTCOME, 'unknown_outcome', `the outcome of the submit to ${c.provider} is unknown `
73
80
  + `(${err.message}). A job may have been created and billed, so no other provider was tried. Check your `
74
81
  + `${adapter.displayName} dashboard before running again.`, { provider: c.provider });
@@ -80,7 +87,7 @@ export async function run(app) {
80
87
  appendSpend(app, { event: 'submitted', job, provider: c.provider, model: request.model, mode: request.mode,
81
88
  params: logParams(request), estimateUsd: c.usd, priceSource: c.source, ...(accepted.meta ? { meta: accepted.meta } : {}) });
82
89
  const base = { job, provider: c.provider, model: request.model, estimateUsd: c.usd, priceSource: c.source,
83
- verifiedOn: c.verifiedOn };
90
+ verifiedOn: c.verifiedOn, ...(request.variant ? { variant: request.variant.id } : {}) };
84
91
 
85
92
  if (!flags.wait) {
86
93
  out.result({ ...base, state: 'submitted' }, `Submitted to ${c.provider}: ${job}\n`
@@ -118,10 +125,42 @@ export async function run(app) {
118
125
  + `${lastRejection.provider}, said: ${lastRejection.message}`, { provider: lastRejection.provider });
119
126
  }
120
127
 
128
+ /**
129
+ * The addresses of the request's input files on this provider: local files are uploaded to it,
130
+ * in the order given, and URLs are passed through.
131
+ */
132
+ async function sendInputs(request, adapter, ctx) {
133
+ // One at a time, so the provider receives the files in the order given. A file whose type was
134
+ // read from its bytes is uploaded as that type, whatever its name says.
135
+ const send = async (files) => {
136
+ const urls = [];
137
+ for (const f of files) urls.push(f.isLocal ? await adapter.upload(f.source, ctx, mimeOf(f)) : f.source);
138
+ return urls;
139
+ };
140
+ if (request.images) return { imageUrls: await send(request.images) };
141
+ if (request.mode === 'reference-to-video') {
142
+ const refImageUrls = await send(request.refImages);
143
+ return { refImageUrls, refAudioUrls: await send(request.refAudio) };
144
+ }
145
+ if (!request.image) return {};
146
+ const imageUrl = request.imageIsLocal ? await adapter.upload(request.image, ctx) : request.image;
147
+ return { imageUrl, ...(request.lastImage ? { lastImageUrl: (await send([request.lastImage]))[0] } : {}) };
148
+ }
149
+
150
+ /** The content type of an input whose type was read from its bytes. */
151
+ const mimeOf = (file) => AUDIO_MIME[file.type] ?? IMAGE_MIME[file.type];
152
+
153
+ /** What a dry run shows for each input: its address, or a placeholder for a local file. */
154
+ const shown = (files) => files.map((f) => (f.isLocal ? pendingUpload(f.source) : f.source));
155
+
121
156
  function dryRun(app, request, ranked, { limit, overLimit }) {
122
157
  const first = ranked[0];
123
158
  const imageUrl = !request.image ? undefined : request.imageIsLocal ? pendingUpload(request.image) : request.image;
124
- const built = ADAPTERS[first.provider].buildRequest(request, { entry: first.entry, imageUrl });
159
+ const built = ADAPTERS[first.provider].buildRequest(request, { entry: first.entry, imageUrl,
160
+ imageUrls: request.images && shown(request.images),
161
+ lastImageUrl: request.lastImage && shown([request.lastImage])[0],
162
+ refImageUrls: request.refImages && shown(request.refImages),
163
+ refAudioUrls: request.refAudio && shown(request.refAudio) });
125
164
  const fallbacks = ranked.slice(1).map((c) => ({ provider: c.provider, estimateUsd: c.usd }));
126
165
  const text = [
127
166
  `Dry run: nothing was sent.`,
@@ -134,6 +173,6 @@ function dryRun(app, request, ranked, { limit, overLimit }) {
134
173
  ].join('\n');
135
174
  app.out.result({ dryRun: true, provider: first.provider, estimateUsd: first.usd, priceSource: first.source,
136
175
  verifiedOn: first.verifiedOn, limitUsd: limit, overLimit, needsConfirmation: overLimit || first.usd === null,
137
- request: built, fallbacks }, text);
176
+ ...(request.variant ? { variant: request.variant.id } : {}), request: built, fallbacks }, text);
138
177
  return EXIT.OK;
139
178
  }
@@ -10,7 +10,8 @@ export function noExtraArgs(app, max, usage) {
10
10
  /** The canonical request from `<model>` and the shared flags. */
11
11
  export function requestFrom(app, { requirePrompt }) {
12
12
  noExtraArgs(app, 1, `cheapgen ${requirePrompt ? 'run' : 'quote'} <model> [options]`);
13
- return buildCanonicalRequest(app.args[0], app.flags, app.catalog, { cwd: app.io.cwd, requirePrompt });
13
+ return buildCanonicalRequest(app.args[0], app.flags, app.catalog,
14
+ { cwd: app.io.cwd, requirePrompt, allowVariants: app.config.allowVariants });
14
15
  }
15
16
 
16
17
  /** --exclude, repeatable and comma-separated. */
@@ -0,0 +1,141 @@
1
+ // `cheapgen skill install|uninstall|path`: copy the bundled agent skill into the folders that
2
+ // Claude Code, Codex, Cursor, GitHub Copilot, OpenCode and other Agent Skills clients read.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { EXIT, usageError } from '../../errors.js';
7
+
8
+ export const BUNDLED_SKILL = fileURLToPath(new URL('../../../skills/cheapgen/', import.meta.url)).replace(/[\\/]$/, '');
9
+ const NAME = 'cheapgen';
10
+
11
+ /** Where each agent reads skills, relative to the home folder and to the project folder. */
12
+ const TARGETS = {
13
+ claude: { home: path.join('.claude', 'skills'), project: path.join('.claude', 'skills') },
14
+ codex: { home: path.join('.agents', 'skills'), project: path.join('.agents', 'skills') },
15
+ cursor: { home: path.join('.cursor', 'skills'), project: path.join('.cursor', 'skills') },
16
+ // VS Code reads project skills only from .github/skills; the Copilot CLI reads that too.
17
+ copilot: { home: path.join('.copilot', 'skills'), project: path.join('.github', 'skills') },
18
+ // OpenCode reads the shared .agents/skills folder, the same one as Codex.
19
+ opencode: { home: path.join('.agents', 'skills'), project: path.join('.agents', 'skills') },
20
+ };
21
+ const AGENTS = Object.keys(TARGETS);
22
+ const CHOICES = `--agent ${AGENTS.join('|')}`;
23
+ const USAGE = `cheapgen skill install|uninstall|path [${CHOICES}] [--project]`;
24
+
25
+ export async function skill(app) {
26
+ const [sub, ...rest] = app.args;
27
+ if (rest.length) throw usageError(`too many arguments. Usage: ${USAGE}`);
28
+ if (sub === 'path') return showPath(app);
29
+ if (sub === 'install') return install(app);
30
+ if (sub === 'uninstall') return uninstall(app);
31
+ throw usageError(`${sub ? `unknown skill command "${sub}"` : 'missing a skill command'}. Usage: ${USAGE}`);
32
+ }
33
+
34
+ function showPath(app) {
35
+ app.out.result({ path: BUNDLED_SKILL }, BUNDLED_SKILL);
36
+ return EXIT.OK;
37
+ }
38
+
39
+ /** The agents named with --agent (repeatable, comma-separated), or null when none were given. */
40
+ function namedAgents(app) {
41
+ const raw = [app.flags.agent ?? []].flat();
42
+ if (!raw.length) return null;
43
+ const names = raw.flatMap((v) => String(v).split(',')).map((s) => s.trim().toLowerCase()).filter(Boolean);
44
+ const bad = names.filter((n) => !AGENTS.includes(n));
45
+ if (bad.length || !names.length) {
46
+ throw usageError(`unknown agent "${bad[0] ?? ''}". Choose ${AGENTS.join(', ')} (${CHOICES}).`);
47
+ }
48
+ return [...new Set(names)];
49
+ }
50
+
51
+ /** Agents to act on: the named ones, or the ones whose folders exist. */
52
+ function chosenAgents(app) {
53
+ const named = namedAgents(app);
54
+ if (named) return named;
55
+ if (app.flags.project) return ['claude', 'codex'];
56
+ const home = app.io.homedir;
57
+ const has = (dir) => fs.existsSync(path.join(home, dir));
58
+ const found = [];
59
+ if (has('.claude')) found.push('claude');
60
+ if (has('.codex') || has('.agents') || has('.cursor')) found.push('codex');
61
+ if (has('.copilot')) found.push('copilot');
62
+ if (has(path.join('.config', 'opencode'))) found.push('opencode');
63
+ if (!found.length) {
64
+ throw usageError('no agent folder found (~/.claude, ~/.codex, ~/.agents, ~/.cursor, ~/.copilot or ~/.config/opencode). '
65
+ + `Choose one with ${CHOICES}.`);
66
+ }
67
+ return found;
68
+ }
69
+
70
+ const targetOf = (app, agent) => (app.flags.project
71
+ ? path.join(app.io.cwd, TARGETS[agent].project, NAME)
72
+ : path.join(app.io.homedir, TARGETS[agent].home, NAME));
73
+
74
+ /** Each chosen agent's folder, once: agents that share a folder get one entry, named after the first. */
75
+ function planFor(app) {
76
+ const seen = new Set();
77
+ const plan = [];
78
+ for (const agent of chosenAgents(app)) {
79
+ const dir = targetOf(app, agent);
80
+ const key = path.resolve(dir).toLowerCase();
81
+ if (seen.has(key)) continue;
82
+ seen.add(key);
83
+ plan.push({ agent, dir, state: inspect(dir) });
84
+ }
85
+ return plan;
86
+ }
87
+
88
+ /** 'missing' | 'link' | 'ours' | 'other' */
89
+ function inspect(dir) {
90
+ let st;
91
+ try { st = fs.lstatSync(dir); } catch { return 'missing'; }
92
+ if (st.isSymbolicLink()) return 'link';
93
+ if (!st.isDirectory()) return 'other';
94
+ return isCheapgenSkill(path.join(dir, 'SKILL.md')) ? 'ours' : 'other';
95
+ }
96
+
97
+ function isCheapgenSkill(file) {
98
+ let text;
99
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return false; }
100
+ const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] ?? '';
101
+ return /^name:\s*["']?cheapgen["']?\s*$/m.test(front);
102
+ }
103
+
104
+ function refuse(dir, state) {
105
+ const why = state === 'link' ? 'is a link, which cheapgen won\'t follow or replace'
106
+ : 'already exists and isn\'t a cheapgen skill';
107
+ return usageError(`${dir} ${why}. Nothing was changed; move it away first.`);
108
+ }
109
+
110
+ function install(app) {
111
+ const plan = planFor(app);
112
+ // All or nothing: check every target before writing any.
113
+ for (const p of plan) if (p.state === 'link' || p.state === 'other') throw refuse(p.dir, p.state);
114
+
115
+ const installed = [];
116
+ for (const { agent, dir, state } of plan) {
117
+ if (state === 'ours') fs.rmSync(dir, { recursive: true, force: true });
118
+ fs.mkdirSync(path.dirname(dir), { recursive: true });
119
+ fs.cpSync(BUNDLED_SKILL, dir, { recursive: true });
120
+ installed.push({ agent, path: dir, replaced: state === 'ours' });
121
+ }
122
+ const text = installed.map((i) => `${i.replaced ? 'replaced' : 'installed'} ${i.agent} skill: ${i.path}`).join('\n');
123
+ app.out.result({ installed }, text);
124
+ return EXIT.OK;
125
+ }
126
+
127
+ function uninstall(app) {
128
+ const plan = planFor(app);
129
+ for (const p of plan) if (p.state === 'link' || p.state === 'other') throw refuse(p.dir, p.state);
130
+
131
+ const removed = [];
132
+ for (const { agent, dir, state } of plan) {
133
+ if (state !== 'ours') continue;
134
+ fs.rmSync(dir, { recursive: true, force: true });
135
+ removed.push({ agent, path: dir });
136
+ }
137
+ const text = removed.length ? removed.map((r) => `removed ${r.agent} skill: ${r.path}`).join('\n')
138
+ : 'No cheapgen skill was installed there.';
139
+ app.out.result({ removed }, text);
140
+ return EXIT.OK;
141
+ }