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/src/cli/main.js CHANGED
@@ -3,7 +3,7 @@
3
3
  import { parseArgs } from 'node:util';
4
4
  import { CliError, EXIT, usageError } from '../errors.js';
5
5
  import { loadCatalog, DEFAULT_DATA_DIR } from '../catalog.js';
6
- import { loadConfig } from '../config.js';
6
+ import { loadConfig, keyParts } from '../config.js';
7
7
  import { createPriceCache } from '../pricing/cache.js';
8
8
  import { redact } from '../http.js';
9
9
  import { createOutput } from './output.js';
@@ -12,7 +12,10 @@ import { COMMANDS, HELP } from './commands/index.js';
12
12
 
13
13
  const OPTIONS = {
14
14
  prompt: { type: 'string' },
15
- image: { type: 'string' },
15
+ image: { type: 'string', multiple: true },
16
+ 'last-image': { type: 'string', multiple: true },
17
+ 'ref-image': { type: 'string', multiple: true },
18
+ 'ref-audio': { type: 'string', multiple: true },
16
19
  res: { type: 'string' },
17
20
  size: { type: 'string' },
18
21
  duration: { type: 'string' },
@@ -33,6 +36,8 @@ const OPTIONS = {
33
36
  search: { type: 'string' },
34
37
  since: { type: 'string' },
35
38
  check: { type: 'boolean' },
39
+ agent: { type: 'string', multiple: true },
40
+ project: { type: 'boolean' },
36
41
  help: { type: 'boolean', short: 'h' },
37
42
  version: { type: 'boolean' },
38
43
  };
@@ -71,12 +76,13 @@ export async function main(argv, io = {}) {
71
76
  if (!command) throw usageError(`unknown command "${name}". Run \`cheapgen --help\` for the list.`);
72
77
 
73
78
  const loaded = loadConfig(io);
74
- secrets.push(...Object.values(loaded.keys));
79
+ for (const [id, key] of Object.entries(loaded.keys)) secrets.push(key, ...keyParts(id, key));
75
80
  for (const w of loaded.warnings) out.warn(w);
76
81
 
77
82
  const app = {
78
83
  io, out, flags, args, secrets,
79
- config: loaded.config, keys: loaded.keys, keySources: loaded.keySources, configFiles: loaded.files,
84
+ config: loaded.config, keys: loaded.keys, keySources: loaded.keySources, keyEnvVars: loaded.keyEnvVars,
85
+ configFiles: loaded.files,
80
86
  get catalog() { return (this._catalog ??= loadCatalog(io.dataDir)); },
81
87
  priceCache: createPriceCache(io.homedir),
82
88
  priceMemo: new Map(),
@@ -113,6 +119,7 @@ async function withDefaults(io) {
113
119
  sleep: io.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))),
114
120
  dataDir: io.dataDir ?? DEFAULT_DATA_DIR,
115
121
  platform: io.platform ?? process.platform,
122
+ mcpInput: io.mcpInput,
116
123
  };
117
124
  }
118
125
 
package/src/config.js CHANGED
@@ -5,8 +5,24 @@ import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { CliError, EXIT, usageError } from './errors.js';
7
7
 
8
- export const PROVIDER_IDS = ['kie', 'replicate', 'wavespeed', 'fal'];
9
- export const ENV_VARS = { kie: 'KIE_API_KEY', replicate: 'REPLICATE_API_TOKEN', wavespeed: 'WAVESPEED_API_KEY', fal: 'FAL_KEY' };
8
+ export const PROVIDER_IDS = ['kie', 'replicate', 'wavespeed', 'fal', 'higgsfield'];
9
+ export const ENV_VARS = { kie: 'KIE_API_KEY', replicate: 'REPLICATE_API_TOKEN', wavespeed: 'WAVESPEED_API_KEY', fal: 'FAL_KEY',
10
+ higgsfield: 'HIGGSFIELD_API_KEY' };
11
+
12
+ /**
13
+ * A key split over two variables, used when the provider's own variable is unset. Higgsfield's
14
+ * docs name the key id and secret HF_API_KEY_ID and HF_API_KEY_SECRET; the stored key joins them.
15
+ */
16
+ export const ENV_PAIRS = { higgsfield: ['HF_API_KEY_ID', 'HF_API_KEY_SECRET'] };
17
+
18
+ /** The variable(s) a key from the environment came from, for messages. */
19
+ export const envNameOf = (app, id) => app.keyEnvVars?.[id] ?? ENV_VARS[id];
20
+
21
+ /** Parts of a key worth redacting on their own (a provider may echo one half), besides the whole key. */
22
+ export function keyParts(id, key) {
23
+ if (!ENV_PAIRS[id] || typeof key !== 'string') return [];
24
+ return key.split(':').filter((part) => part.length >= 8);
25
+ }
10
26
 
11
27
  export const DEFAULTS = Object.freeze({
12
28
  providers: Object.fromEntries(PROVIDER_IDS.map((id) => [id, { enabled: true }])),
@@ -106,7 +122,7 @@ function splitKeys(layer) {
106
122
 
107
123
  /**
108
124
  * @returns {{ config: object, keys: Record<string, string>, keySources: Record<string, 'env'|'file'|null>,
109
- * warnings: string[], files: { user: string, project: string } }}
125
+ * keyEnvVars: Record<string, string>, warnings: string[], files: { user: string, project: string } }}
110
126
  */
111
127
  export function loadConfig(io) {
112
128
  const warnings = [];
@@ -124,17 +140,27 @@ export function loadConfig(io) {
124
140
  Object.assign(fileKeys, keys);
125
141
  }
126
142
 
143
+ // An app that starts cheapgen can pass an unset setting as its unfilled placeholder
144
+ // (`${user_config.x}`, `$VAR`). That is not a key, so it must not hide a stored one.
145
+ const envValue = (name) => {
146
+ const v = io.env[name];
147
+ if (typeof v !== 'string' || !v.trim() || /^\$(\{[^}]*\}|[A-Za-z_]\w*)$/.test(v.trim())) return null;
148
+ return v.trim();
149
+ };
127
150
  const keys = {};
128
151
  const keySources = {};
152
+ const keyEnvVars = {};
129
153
  for (const id of PROVIDER_IDS) {
130
- const fromEnv = io.env[ENV_VARS[id]];
131
- if (typeof fromEnv === 'string' && fromEnv.trim()) { keys[id] = fromEnv.trim(); keySources[id] = 'env'; }
154
+ const fromEnv = envValue(ENV_VARS[id]);
155
+ const pair = ENV_PAIRS[id]?.map(envValue);
156
+ if (fromEnv) { keys[id] = fromEnv; keySources[id] = 'env'; keyEnvVars[id] = ENV_VARS[id]; }
157
+ else if (pair?.every(Boolean)) { keys[id] = pair.join(':'); keySources[id] = 'env'; keyEnvVars[id] = ENV_PAIRS[id].join(' + '); }
132
158
  else if (fileKeys[id]) { keys[id] = fileKeys[id]; keySources[id] = 'file'; }
133
159
  else keySources[id] = null;
134
160
  }
135
161
 
136
162
  // Keys live outside the config object, so printing the config can't include them.
137
- return { config: deepFreeze(structuredClone(config)), keys: Object.freeze(keys), keySources, warnings, files };
163
+ return { config: deepFreeze(structuredClone(config)), keys: Object.freeze(keys), keySources, keyEnvVars, warnings, files };
138
164
  }
139
165
 
140
166
  /**
package/src/http.js CHANGED
@@ -8,7 +8,7 @@ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
8
8
 
9
9
  const PATTERNS = [
10
10
  [/\bBearer\s+[^\s"',;)]+/gi, 'Bearer [redacted]'],
11
- [/\bKey\s+[\w.-]+:[\w.-]+/g, 'Key [redacted]'],
11
+ [/\bKey\s+[^\s:"',;)]+:[^\s"',;)]+/g, 'Key [redacted]'],
12
12
  [/\br8_[A-Za-z0-9]{8,}/g, '[redacted]'],
13
13
  ];
14
14
 
@@ -0,0 +1,8 @@
1
+ /** A JSON-RPC error to send back for a request. */
2
+ export class RpcError extends Error {
3
+ constructor(code, message, data) {
4
+ super(message);
5
+ this.rpcCode = code;
6
+ this.data = data;
7
+ }
8
+ }
@@ -0,0 +1,144 @@
1
+ // MCP server: JSON-RPC message handling for both protocol eras. Legacy clients open with
2
+ // `initialize`; modern clients (2026-07-28) send the version and their capabilities in each
3
+ // request's `_meta`. No transport here: `receive` takes parsed messages, `send` writes them.
4
+ import crypto from 'node:crypto';
5
+ import fs from 'node:fs';
6
+ import { TOOL_DEFINITIONS, callTool } from './tools.js';
7
+ import { RpcError } from './errors.js';
8
+
9
+ export { RpcError };
10
+
11
+ export const MODERN = '2026-07-28';
12
+ export const LEGACY = ['2025-11-25', '2025-06-18', '2025-03-26'];
13
+ export const SUPPORTED = [MODERN, ...LEGACY];
14
+ const META = {
15
+ version: 'io.modelcontextprotocol/protocolVersion',
16
+ capabilities: 'io.modelcontextprotocol/clientCapabilities',
17
+ serverInfo: 'io.modelcontextprotocol/serverInfo',
18
+ };
19
+ const CLIENT_REQUEST_TIMEOUT_MS = 5 * 60_000;
20
+
21
+ export const INSTRUCTIONS = 'cheapgen prices AI video and image generations on every connected provider and runs them '
22
+ + 'on the cheapest. Call `quote` first and tell the user the provider and price. `run` spends the user\'s money: '
23
+ + 'call it only after the user agreed to that price, with the quoteId from `quote`. Above the user\'s cost limit, '
24
+ + 'the server asks the user itself when the app supports it. Never resubmit after an unknown_outcome error. '
25
+ + '`run` returns a job id; collect the result with `wait_job`.';
26
+
27
+ let serverVersion;
28
+ function serverInfo() {
29
+ serverVersion ??= JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
30
+ return { name: 'cheapgen', version: serverVersion };
31
+ }
32
+
33
+ /**
34
+ * @param {{ io: object, send: (message: object) => void }} options
35
+ * @returns {{ receive(message: object): Promise<void>, close(): void }}
36
+ */
37
+ export function createMcpServer({ io, send }) {
38
+ const state = {
39
+ legacy: null, // { version, capabilities } after `initialize`
40
+ quotes: new Map(),
41
+ pending: new Map(),
42
+ nextId: 1,
43
+ stateKey: crypto.randomBytes(32),
44
+ };
45
+
46
+ /** A request from the server to the client (legacy elicitation). Resolves with its result. */
47
+ function requestClient(method, params) {
48
+ const id = `cheapgen-${state.nextId++}`;
49
+ return new Promise((resolve, reject) => {
50
+ const timer = setTimeout(() => {
51
+ state.pending.delete(id);
52
+ reject(new Error(`no answer to ${method}`));
53
+ }, CLIENT_REQUEST_TIMEOUT_MS);
54
+ timer.unref?.();
55
+ state.pending.set(id, { resolve, reject, timer });
56
+ send({ jsonrpc: '2.0', id, method, params });
57
+ });
58
+ }
59
+
60
+ const ctx = { io, state, requestClient };
61
+
62
+ async function dispatch(msg) {
63
+ const params = msg.params ?? {};
64
+ const meta = params._meta ?? {};
65
+ const modern = meta[META.version] !== undefined;
66
+ if (modern && !SUPPORTED.includes(meta[META.version])) {
67
+ throw new RpcError(-32022, 'Unsupported protocol version', { supported: SUPPORTED, requested: meta[META.version] });
68
+ }
69
+ const call = {
70
+ modern,
71
+ capabilities: modern ? (meta[META.capabilities] ?? {}) : (state.legacy?.capabilities ?? {}),
72
+ legacyVersion: modern ? null : (state.legacy?.version ?? null),
73
+ };
74
+ let result;
75
+ switch (msg.method) {
76
+ case 'initialize': {
77
+ const version = LEGACY.includes(params.protocolVersion) ? params.protocolVersion : LEGACY[0];
78
+ state.legacy = { version, capabilities: params.capabilities ?? {} };
79
+ return { protocolVersion: version, capabilities: { tools: {} }, serverInfo: serverInfo(), instructions: INSTRUCTIONS };
80
+ }
81
+ case 'notifications/initialized':
82
+ case 'notifications/cancelled':
83
+ return undefined;
84
+ case 'ping':
85
+ result = {};
86
+ break;
87
+ case 'server/discover':
88
+ result = { supportedVersions: SUPPORTED, capabilities: { tools: {} }, instructions: INSTRUCTIONS };
89
+ break;
90
+ case 'tools/list':
91
+ result = { tools: TOOL_DEFINITIONS };
92
+ if (modern) Object.assign(result, { ttlMs: 3_600_000, cacheScope: 'private' });
93
+ break;
94
+ case 'tools/call':
95
+ result = await callTool(ctx, params, call);
96
+ break;
97
+ default:
98
+ throw new RpcError(-32601, `Method not found: ${msg.method}`);
99
+ }
100
+ if (modern || msg.method === 'server/discover') {
101
+ result = { resultType: 'complete', ...result, _meta: { ...(result._meta ?? {}), [META.serverInfo]: serverInfo() } };
102
+ }
103
+ return result;
104
+ }
105
+
106
+ async function receive(msg) {
107
+ if (!msg || typeof msg !== 'object' || Array.isArray(msg)) {
108
+ send({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid request' } });
109
+ return;
110
+ }
111
+ // A reply to one of our own requests.
112
+ if (msg.method === undefined && msg.id !== undefined && ('result' in msg || 'error' in msg)) {
113
+ const p = state.pending.get(msg.id);
114
+ if (!p) return;
115
+ state.pending.delete(msg.id);
116
+ clearTimeout(p.timer);
117
+ if ('error' in msg) p.reject(new Error(msg.error?.message ?? 'client error'));
118
+ else p.resolve(msg.result);
119
+ return;
120
+ }
121
+ const isNotification = msg.id === undefined;
122
+ try {
123
+ if (typeof msg.method !== 'string') throw new RpcError(-32600, 'Invalid request');
124
+ const result = await dispatch(msg);
125
+ if (!isNotification && result !== undefined) send({ jsonrpc: '2.0', id: msg.id, result });
126
+ } catch (err) {
127
+ if (isNotification) return;
128
+ const code = err instanceof RpcError ? err.rpcCode : -32603;
129
+ const message = err instanceof RpcError ? err.message : `Internal error: ${err?.message ?? err}`;
130
+ send({ jsonrpc: '2.0', id: msg.id ?? null, error: { code, message, ...(err?.data ? { data: err.data } : {}) } });
131
+ }
132
+ }
133
+
134
+ /** Ends any wait for the client, e.g. when its input closes. */
135
+ function close() {
136
+ for (const [id, p] of state.pending) {
137
+ clearTimeout(p.timer);
138
+ p.reject(new Error('connection closed'));
139
+ state.pending.delete(id);
140
+ }
141
+ }
142
+
143
+ return { receive, close };
144
+ }
@@ -0,0 +1,41 @@
1
+ // stdio transport: newline-delimited JSON-RPC in; each outgoing message goes to `write`, which
2
+ // prints it as one line. Only protocol messages go to stdout.
3
+ import { StringDecoder } from 'node:string_decoder';
4
+ import { createMcpServer } from './server.js';
5
+
6
+ /**
7
+ * Serves MCP over a stream of input chunks until it ends.
8
+ * @param {{ io: object, input: AsyncIterable<string|Buffer>, write: (message: object) => void }} options
9
+ */
10
+ export async function serveStdio({ io, input, write }) {
11
+ const server = createMcpServer({ io, send: write });
12
+ const inFlight = new Set();
13
+ const decoder = new StringDecoder('utf8');
14
+ let buffer = '';
15
+
16
+ const handle = (raw) => {
17
+ const text = raw.replace(/\r$/, '');
18
+ if (!text.trim()) return;
19
+ let msg;
20
+ try { msg = JSON.parse(text); } catch {
21
+ write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
22
+ return;
23
+ }
24
+ // Not awaited: a tool call can wait for the client's answer, which arrives on a later line.
25
+ const p = server.receive(msg).catch(() => {}).finally(() => inFlight.delete(p));
26
+ inFlight.add(p);
27
+ };
28
+
29
+ for await (const chunk of input) {
30
+ buffer += typeof chunk === 'string' ? chunk : decoder.write(chunk);
31
+ let nl;
32
+ while ((nl = buffer.indexOf('\n')) !== -1) {
33
+ handle(buffer.slice(0, nl));
34
+ buffer = buffer.slice(nl + 1);
35
+ }
36
+ }
37
+ buffer += decoder.end();
38
+ handle(buffer);
39
+ server.close();
40
+ while (inFlight.size) await Promise.all([...inFlight]);
41
+ }