@1aboveio/content-skills 0.0.0-stage → 0.1.1

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.
Files changed (53) hide show
  1. package/README.md +24 -2
  2. package/package.json +34 -4
  3. package/skills/article-review/LICENSE +3 -0
  4. package/skills/article-review/SKILL.md +66 -0
  5. package/skills/article-review/references/report-format.md +68 -0
  6. package/skills/article-review/references/template-guide.md +79 -0
  7. package/skills/article-review/references/template-wechat-payments.md +125 -0
  8. package/skills/article-review/release-check.mjs +93 -0
  9. package/skills/article-to-image/LICENSE +3 -0
  10. package/skills/article-to-image/SKILL.md +91 -0
  11. package/skills/article-to-image/references/formats.md +53 -0
  12. package/skills/article-to-image/release-check.mjs +93 -0
  13. package/skills/flowchart-svg/LICENSE +3 -0
  14. package/skills/flowchart-svg/SKILL.md +43 -0
  15. package/skills/flowchart-svg/release-check.mjs +93 -0
  16. package/skills/flowchart-svg/scripts/export_png.sh +8 -0
  17. package/skills/image-gen/LICENSE +3 -0
  18. package/skills/image-gen/SKILL.md +192 -0
  19. package/skills/image-gen/release-check.mjs +93 -0
  20. package/skills/image-gen/scripts/credentials.mjs +217 -0
  21. package/skills/image-gen/scripts/credentials.test.mjs +212 -0
  22. package/skills/image-gen/scripts/generate.mjs +240 -0
  23. package/skills/image-gen/scripts/options.mjs +293 -0
  24. package/skills/image-gen/scripts/options.test.mjs +245 -0
  25. package/skills/mermaid/LICENSE +3 -0
  26. package/skills/mermaid/SKILL.md +635 -0
  27. package/skills/mermaid/release-check.mjs +93 -0
  28. package/skills/wechat-article-writer/LICENSE +3 -0
  29. package/skills/wechat-article-writer/SKILL.md +92 -0
  30. package/skills/wechat-article-writer/references/style-selector.md +133 -0
  31. package/skills/wechat-article-writer/references/writing-rules.md +152 -0
  32. package/skills/wechat-article-writer/release-check.mjs +93 -0
  33. package/skills/wechat-article-writer/templates/wechat-comparison.md +52 -0
  34. package/skills/wechat-article-writer/templates/wechat-howto.md +51 -0
  35. package/skills/wechat-article-writer/templates/wechat-insight.md +50 -0
  36. package/skills/wechat-article-writer/templates/wechat-pitfall.md +52 -0
  37. package/skills/wechat-publisher/LICENSE +3 -0
  38. package/skills/wechat-publisher/SKILL.md +171 -0
  39. package/skills/wechat-publisher/references/api.md +105 -0
  40. package/skills/wechat-publisher/references/layout-rules.md +57 -0
  41. package/skills/wechat-publisher/references/wechat-safe-template.html +86 -0
  42. package/skills/wechat-publisher/release-check.mjs +93 -0
  43. package/skills/wechat-publisher/scripts/md_to_wechat_html.py +194 -0
  44. package/skills/wechat-publisher/scripts/publish.py +239 -0
  45. package/skills/wechat-search/LICENSE +3 -0
  46. package/skills/wechat-search/SKILL.md +211 -0
  47. package/skills/wechat-search/release-check.mjs +93 -0
  48. package/skills/wechat-search/scripts/start-chrome.sh +83 -0
  49. package/skills/xai-search/LICENSE +3 -0
  50. package/skills/xai-search/SKILL.md +79 -0
  51. package/skills/xai-search/release-check.mjs +93 -0
  52. package/skills/xai-search/scripts/xai_search.sh +187 -0
  53. package/skills/xai-search/tests/smoke_test.sh +36 -0
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Credential resolution for the image providers.
3
+ *
4
+ * Environment variables win. When OPENAI_API_KEY is absent we fall back to the
5
+ * pi harness config, which stores provider entries as
6
+ * `providers.<name> = { baseUrl, apiKey }` in `<agent dir>/models.json`
7
+ * (default `~/.pi/agent`, overridable with PI_CODING_AGENT_DIR).
8
+ *
9
+ * pi config values are NOT plain literals. They are templates resolved against
10
+ * the environment — `$VAR`, `${VAR}`, with `$$` and `$!` escaping a literal `$`
11
+ * and `!`, and a leading `!` marking a shell command. A value that is not
12
+ * expanded is a bearer token reading `$OPENAI_API_KEY`, which authenticates
13
+ * against nothing. The grammar below mirrors pi's own
14
+ * `core/resolve-config-value.js`.
15
+ */
16
+
17
+ import { readFile } from 'node:fs/promises';
18
+ import { homedir } from 'node:os';
19
+ import { join } from 'node:path';
20
+
21
+ export const DEFAULT_OPENAI_BASE_URL = 'https://api.openai.com/v1';
22
+
23
+ const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
24
+ const ENV_NAME_PREFIX_RE = /^[A-Za-z_][A-Za-z0-9_]*/;
25
+
26
+ export function piModelsPath(env = process.env) {
27
+ const agentDir = env.PI_CODING_AGENT_DIR || join(homedir(), '.pi', 'agent');
28
+ return join(agentDir, 'models.json');
29
+ }
30
+
31
+ const stripTrailingSlashes = (url) => url.replace(/\/+$/, '');
32
+
33
+ function parseTemplate(config) {
34
+ const parts = [];
35
+ const appendLiteral = (value) => {
36
+ if (!value) return;
37
+ const previous = parts[parts.length - 1];
38
+ if (previous?.type === 'literal') previous.value += value;
39
+ else parts.push({ type: 'literal', value });
40
+ };
41
+
42
+ let index = 0;
43
+ while (index < config.length) {
44
+ const dollar = config.indexOf('$', index);
45
+ if (dollar < 0) {
46
+ appendLiteral(config.slice(index));
47
+ break;
48
+ }
49
+ appendLiteral(config.slice(index, dollar));
50
+
51
+ const next = config[dollar + 1];
52
+ if (next === '$' || next === '!') {
53
+ appendLiteral(next);
54
+ index = dollar + 2;
55
+ continue;
56
+ }
57
+
58
+ if (next === '{') {
59
+ const end = config.indexOf('}', dollar + 2);
60
+ if (end < 0) {
61
+ appendLiteral('$');
62
+ index = dollar + 1;
63
+ continue;
64
+ }
65
+ const name = config.slice(dollar + 2, end);
66
+ if (ENV_NAME_RE.test(name)) parts.push({ type: 'env', name });
67
+ else appendLiteral(config.slice(dollar, end + 1));
68
+ index = end + 1;
69
+ continue;
70
+ }
71
+
72
+ const match = config.slice(dollar + 1).match(ENV_NAME_PREFIX_RE);
73
+ if (match) {
74
+ parts.push({ type: 'env', name: match[0] });
75
+ index = dollar + 1 + match[0].length;
76
+ continue;
77
+ }
78
+
79
+ appendLiteral('$');
80
+ index = dollar + 1;
81
+ }
82
+
83
+ return parts;
84
+ }
85
+
86
+ /**
87
+ * Expand one pi config value.
88
+ *
89
+ * @returns {{value?: string, missing: string[], command?: string}}
90
+ * `value` is set only when every referenced variable resolved. `missing`
91
+ * names the variables that did not. `command` is set for `!shell` values,
92
+ * which this script reports rather than executes.
93
+ */
94
+ export function expandPiValue(raw, env = process.env) {
95
+ if (typeof raw !== 'string' || raw === '') return { missing: [] };
96
+ if (raw.startsWith('!')) return { missing: [], command: raw.slice(1) };
97
+
98
+ const missing = [];
99
+ let expanded = '';
100
+ for (const part of parseTemplate(raw)) {
101
+ if (part.type === 'literal') {
102
+ expanded += part.value;
103
+ continue;
104
+ }
105
+ // pi resolves with `||`, so an empty string counts as unset.
106
+ const value = env[part.name] || undefined;
107
+ if (value === undefined) {
108
+ if (!missing.includes(part.name)) missing.push(part.name);
109
+ continue;
110
+ }
111
+ expanded += value;
112
+ }
113
+
114
+ if (missing.length) return { missing };
115
+ return { value: expanded, missing: [] };
116
+ }
117
+
118
+ async function readPiProvider(name, configPath) {
119
+ let parsed;
120
+ try {
121
+ parsed = JSON.parse(await readFile(configPath, 'utf8'));
122
+ } catch {
123
+ // Missing, unreadable, or malformed — no fallback available.
124
+ return null;
125
+ }
126
+ return parsed?.providers?.[name] ?? null;
127
+ }
128
+
129
+ const asVarList = (names) => names.map((name) => `$${name}`).join(', ');
130
+
131
+ /**
132
+ * Resolve the OpenAI key and base URL.
133
+ *
134
+ * @returns {Promise<{ok: true, apiKey: string, baseUrl: string, source: string}
135
+ * | {ok: false, reason: string}>}
136
+ */
137
+ export async function resolveOpenAI({ env = process.env, configPath } = {}) {
138
+ if (env.OPENAI_API_KEY) {
139
+ return {
140
+ ok: true,
141
+ apiKey: env.OPENAI_API_KEY,
142
+ baseUrl: stripTrailingSlashes(env.OPENAI_BASE_URL || DEFAULT_OPENAI_BASE_URL),
143
+ source: 'env (OPENAI_API_KEY)',
144
+ };
145
+ }
146
+
147
+ const path = configPath || piModelsPath(env);
148
+ const provider = await readPiProvider('openai', path);
149
+ if (!provider || !provider.apiKey) {
150
+ return {
151
+ ok: false,
152
+ reason: `OPENAI_API_KEY is not set, and ${path} has no providers.openai.apiKey to fall back to.`,
153
+ };
154
+ }
155
+
156
+ const key = expandPiValue(provider.apiKey, env);
157
+ if (key.command) {
158
+ return {
159
+ ok: false,
160
+ reason:
161
+ `${path} resolves providers.openai.apiKey by running a shell command ` +
162
+ `(!${key.command}). This script does not execute config commands — set OPENAI_API_KEY instead.`,
163
+ };
164
+ }
165
+ if (!key.value) {
166
+ return {
167
+ ok: false,
168
+ reason:
169
+ `${path} sets providers.openai.apiKey to a template referencing ${asVarList(key.missing)}, ` +
170
+ `which ${key.missing.length > 1 ? 'are' : 'is'} not set. Note that a pi entry pointing at ` +
171
+ `$OPENAI_API_KEY can never satisfy this fallback: the fallback only runs when that variable ` +
172
+ `is absent. Point it at a different variable, or store the key literally.`,
173
+ };
174
+ }
175
+
176
+ // Key and base URL come from the same source deliberately. Pairing the pi key
177
+ // with an OPENAI_BASE_URL pointing at some other gateway would send the key to
178
+ // a service it does not authenticate against — so an unresolvable pi baseUrl
179
+ // fails here rather than quietly falling back to api.openai.com.
180
+ let baseUrl = DEFAULT_OPENAI_BASE_URL;
181
+ if (provider.baseUrl) {
182
+ const resolved = expandPiValue(provider.baseUrl, env);
183
+ if (resolved.command) {
184
+ return {
185
+ ok: false,
186
+ reason: `${path} resolves providers.openai.baseUrl by running a shell command, which this script does not execute.`,
187
+ };
188
+ }
189
+ if (!resolved.value) {
190
+ return {
191
+ ok: false,
192
+ reason: `${path} sets providers.openai.baseUrl to a template referencing ${asVarList(resolved.missing)}, which ${resolved.missing.length > 1 ? 'are' : 'is'} not set.`,
193
+ };
194
+ }
195
+ baseUrl = resolved.value;
196
+ }
197
+
198
+ return {
199
+ ok: true,
200
+ apiKey: key.value,
201
+ baseUrl: stripTrailingSlashes(baseUrl),
202
+ source: `pi config (${path})`,
203
+ };
204
+ }
205
+
206
+ /**
207
+ * Resolve the Gemini key. Env only — pi has no Gemini provider convention to
208
+ * fall back to.
209
+ *
210
+ * @returns {{ok: true, apiKey: string, source: string} | {ok: false, reason: string}}
211
+ */
212
+ export function resolveGemini({ env = process.env } = {}) {
213
+ if (!env.GEMINI_API_KEY) {
214
+ return { ok: false, reason: 'GEMINI_API_KEY environment variable is required.' };
215
+ }
216
+ return { ok: true, apiKey: env.GEMINI_API_KEY, source: 'env (GEMINI_API_KEY)' };
217
+ }
@@ -0,0 +1,212 @@
1
+ import assert from 'node:assert/strict';
2
+ import { mkdtemp, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { describe, it } from 'node:test';
6
+
7
+ import {
8
+ DEFAULT_OPENAI_BASE_URL,
9
+ expandPiValue,
10
+ piModelsPath,
11
+ resolveGemini,
12
+ resolveOpenAI,
13
+ } from './credentials.mjs';
14
+
15
+ async function writeConfig(contents) {
16
+ const dir = await mkdtemp(join(tmpdir(), 'image-gen-creds-'));
17
+ const path = join(dir, 'models.json');
18
+ await writeFile(path, typeof contents === 'string' ? contents : JSON.stringify(contents));
19
+ return path;
20
+ }
21
+
22
+ const piConfig = (openai) => ({ providers: { openai } });
23
+
24
+ // A literal key, the case where the pi fallback can actually produce one.
25
+ const LITERAL = { baseUrl: 'https://pi-gateway.example/v1', apiKey: 'pi-key' };
26
+
27
+ describe('expandPiValue', () => {
28
+ it('passes literals through', () => {
29
+ assert.equal(expandPiValue('sk-literal', {}).value, 'sk-literal');
30
+ });
31
+
32
+ it('expands $VAR and ${VAR}', () => {
33
+ assert.equal(expandPiValue('$KEY', { KEY: 'v' }).value, 'v');
34
+ assert.equal(expandPiValue('${KEY}', { KEY: 'v' }).value, 'v');
35
+ });
36
+
37
+ it('expands variables embedded in surrounding text', () => {
38
+ const resolved = expandPiValue('https://$HOST/v1', { HOST: 'gw.example' });
39
+
40
+ assert.equal(resolved.value, 'https://gw.example/v1');
41
+ });
42
+
43
+ it('reports every unresolved variable instead of expanding partially', () => {
44
+ const resolved = expandPiValue('$A-$B', { A: 'a' });
45
+
46
+ assert.equal(resolved.value, undefined);
47
+ assert.deepEqual(resolved.missing, ['B']);
48
+ });
49
+
50
+ it('treats an empty variable as unset, as pi does', () => {
51
+ assert.deepEqual(expandPiValue('$KEY', { KEY: '' }).missing, ['KEY']);
52
+ });
53
+
54
+ it('honors the $$ and $! escapes', () => {
55
+ assert.equal(expandPiValue('$$KEY', { KEY: 'v' }).value, '$KEY');
56
+ assert.equal(expandPiValue('$!cmd', {}).value, '!cmd');
57
+ });
58
+
59
+ it('keeps a dangling $ or unterminated ${ literal', () => {
60
+ assert.equal(expandPiValue('pre$', {}).value, 'pre$');
61
+ assert.equal(expandPiValue('${unterminated', {}).value, '${unterminated');
62
+ assert.equal(expandPiValue('$ {KEY}', {}).value, '$ {KEY}');
63
+ });
64
+
65
+ it('flags !command values rather than executing them', () => {
66
+ const resolved = expandPiValue('!security find-generic-password -w', {});
67
+
68
+ assert.equal(resolved.value, undefined);
69
+ assert.equal(resolved.command, 'security find-generic-password -w');
70
+ });
71
+ });
72
+
73
+ describe('resolveOpenAI', () => {
74
+ it('prefers the environment over the pi config', async () => {
75
+ const configPath = await writeConfig(piConfig(LITERAL));
76
+ const resolved = await resolveOpenAI({
77
+ env: { OPENAI_API_KEY: 'env-key', OPENAI_BASE_URL: 'https://env-gateway.example/v1' },
78
+ configPath,
79
+ });
80
+
81
+ assert.equal(resolved.ok, true);
82
+ assert.equal(resolved.apiKey, 'env-key');
83
+ assert.equal(resolved.baseUrl, 'https://env-gateway.example/v1');
84
+ });
85
+
86
+ it('defaults the base URL when only the env key is set', async () => {
87
+ const resolved = await resolveOpenAI({ env: { OPENAI_API_KEY: 'k' }, configPath: '/nope' });
88
+
89
+ assert.equal(resolved.baseUrl, DEFAULT_OPENAI_BASE_URL);
90
+ });
91
+
92
+ it('strips trailing slashes so the path join stays well formed', async () => {
93
+ const resolved = await resolveOpenAI({
94
+ env: { OPENAI_API_KEY: 'k', OPENAI_BASE_URL: 'https://gw.example/v1///' },
95
+ configPath: '/nope',
96
+ });
97
+
98
+ assert.equal(resolved.baseUrl, 'https://gw.example/v1');
99
+ });
100
+
101
+ it('falls back to a literal pi key, taking pi\'s base URL with it', async () => {
102
+ const configPath = await writeConfig(piConfig(LITERAL));
103
+ const resolved = await resolveOpenAI({ env: {}, configPath });
104
+
105
+ assert.equal(resolved.ok, true);
106
+ assert.equal(resolved.apiKey, 'pi-key');
107
+ assert.equal(resolved.baseUrl, 'https://pi-gateway.example/v1');
108
+ assert.match(resolved.source, /^pi config/);
109
+ });
110
+
111
+ it('expands a pi key that references another variable', async () => {
112
+ const configPath = await writeConfig(piConfig({ ...LITERAL, apiKey: '$GAPSEE_KEY' }));
113
+ const resolved = await resolveOpenAI({ env: { GAPSEE_KEY: 'sk-real' }, configPath });
114
+
115
+ assert.equal(resolved.ok, true);
116
+ assert.equal(resolved.apiKey, 'sk-real');
117
+ });
118
+
119
+ it('never sends an unexpanded template as the bearer token', async () => {
120
+ // The bug this guards: `$OPENAI_API_KEY` reaching the API verbatim.
121
+ const configPath = await writeConfig(piConfig({ ...LITERAL, apiKey: '$SOME_KEY' }));
122
+ const resolved = await resolveOpenAI({ env: {}, configPath });
123
+
124
+ assert.equal(resolved.ok, false);
125
+ assert.match(resolved.reason, /\$SOME_KEY/);
126
+ });
127
+
128
+ it('explains why a pi entry pointing at $OPENAI_API_KEY can never satisfy the fallback', async () => {
129
+ const configPath = await writeConfig(piConfig({ ...LITERAL, apiKey: '$OPENAI_API_KEY' }));
130
+ const resolved = await resolveOpenAI({ env: {}, configPath });
131
+
132
+ assert.equal(resolved.ok, false);
133
+ assert.match(resolved.reason, /can never satisfy this fallback/);
134
+ });
135
+
136
+ it('expands a templated pi base URL', async () => {
137
+ const configPath = await writeConfig(piConfig({ apiKey: 'pi-key', baseUrl: 'https://$GW/v1' }));
138
+ const resolved = await resolveOpenAI({ env: { GW: 'gw.example' }, configPath });
139
+
140
+ assert.equal(resolved.baseUrl, 'https://gw.example/v1');
141
+ });
142
+
143
+ it('fails rather than silently retargeting when the pi base URL cannot expand', async () => {
144
+ // Falling back to api.openai.com here would send a gateway key to OpenAI.
145
+ const configPath = await writeConfig(piConfig({ apiKey: 'pi-key', baseUrl: 'https://$GW/v1' }));
146
+ const resolved = await resolveOpenAI({ env: {}, configPath });
147
+
148
+ assert.equal(resolved.ok, false);
149
+ assert.match(resolved.reason, /\$GW/);
150
+ });
151
+
152
+ it('defaults the base URL when the pi provider omits one', async () => {
153
+ const configPath = await writeConfig(piConfig({ apiKey: 'pi-key' }));
154
+ const resolved = await resolveOpenAI({ env: {}, configPath });
155
+
156
+ assert.equal(resolved.baseUrl, DEFAULT_OPENAI_BASE_URL);
157
+ });
158
+
159
+ it('reports !command keys as unsupported instead of running them', async () => {
160
+ const configPath = await writeConfig(piConfig({ ...LITERAL, apiKey: '!echo sk-x' }));
161
+ const resolved = await resolveOpenAI({ env: {}, configPath });
162
+
163
+ assert.equal(resolved.ok, false);
164
+ assert.match(resolved.reason, /does not execute config commands/);
165
+ });
166
+
167
+ it('ignores OPENAI_BASE_URL when the key comes from pi', async () => {
168
+ const configPath = await writeConfig(piConfig(LITERAL));
169
+ const resolved = await resolveOpenAI({
170
+ env: { OPENAI_BASE_URL: 'https://env-gateway.example/v1' },
171
+ configPath,
172
+ });
173
+
174
+ assert.equal(resolved.baseUrl, 'https://pi-gateway.example/v1');
175
+ });
176
+
177
+ it('fails with the config path when there is nothing to fall back to', async () => {
178
+ const missing = await resolveOpenAI({ env: {}, configPath: '/definitely/not/here.json' });
179
+ const malformed = await resolveOpenAI({ env: {}, configPath: await writeConfig('{ not json') });
180
+ const noKey = await writeConfig(piConfig({ baseUrl: 'https://x.example/v1' }));
181
+ const otherProvider = await writeConfig({ providers: { deepseek: { apiKey: 'k' } } });
182
+
183
+ assert.equal(missing.ok, false);
184
+ assert.match(missing.reason, /definitely\/not\/here\.json/);
185
+ assert.equal(malformed.ok, false);
186
+ assert.equal((await resolveOpenAI({ env: {}, configPath: noKey })).ok, false);
187
+ assert.equal((await resolveOpenAI({ env: {}, configPath: otherProvider })).ok, false);
188
+ });
189
+ });
190
+
191
+ describe('piModelsPath', () => {
192
+ it('honors PI_CODING_AGENT_DIR', () => {
193
+ assert.equal(piModelsPath({ PI_CODING_AGENT_DIR: '/custom/agent' }), '/custom/agent/models.json');
194
+ });
195
+
196
+ it('defaults to the pi agent directory under $HOME', () => {
197
+ assert.match(piModelsPath({}), /[/\\]\.pi[/\\]agent[/\\]models\.json$/);
198
+ });
199
+ });
200
+
201
+ describe('resolveGemini', () => {
202
+ it('reads the env key', () => {
203
+ assert.equal(resolveGemini({ env: { GEMINI_API_KEY: 'g-key' } }).apiKey, 'g-key');
204
+ });
205
+
206
+ it('fails with a reason without one', () => {
207
+ const resolved = resolveGemini({ env: {} });
208
+
209
+ assert.equal(resolved.ok, false);
210
+ assert.match(resolved.reason, /GEMINI_API_KEY/);
211
+ });
212
+ });
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Image generation script supporting OpenAI gpt-image-2 and Google Gemini.
5
+ *
6
+ * OpenAI: OPENAI_API_KEY + optional OPENAI_BASE_URL, falling back to the pi
7
+ * harness config. See scripts/credentials.mjs.
8
+ * Gemini: Requires GEMINI_API_KEY.
9
+ */
10
+
11
+ import { writeFile, mkdir } from 'node:fs/promises';
12
+ import { dirname, resolve } from 'node:path';
13
+
14
+ import { resolveGemini, resolveOpenAI } from './credentials.mjs';
15
+ import {
16
+ GEMINI_ASPECT_RATIOS,
17
+ OPENAI_SIZES,
18
+ QUALITIES,
19
+ describeSizeMismatch,
20
+ geminiAspectRatio,
21
+ imageDimensions,
22
+ openAiSize,
23
+ parseArgs,
24
+ resolveOutputPath,
25
+ } from './options.mjs';
26
+
27
+ // Image generation is slow — tens of seconds is normal — but an unbounded fetch
28
+ // hangs forever on a stalled gateway with nothing on screen to explain why.
29
+ const REQUEST_TIMEOUT_MS = 180_000;
30
+
31
+ function usage() {
32
+ console.error('Usage: node generate.mjs "prompt" [options]');
33
+ console.error('');
34
+ console.error('Options:');
35
+ console.error(' --provider <openai|gemini> Image provider (default: openai)');
36
+ console.error(' --model <model> Model name (provider-specific)');
37
+ console.error(` --size <size> OpenAI: ${OPENAI_SIZES.join(', ')}`);
38
+ console.error(' Gemini: WxH or an aspect ratio');
39
+ console.error(` (${GEMINI_ASPECT_RATIOS.join(', ')})`);
40
+ console.error(` --quality <quality> OpenAI only: ${QUALITIES.join(', ')}`);
41
+ console.error(' --output <path> Output file path');
42
+ }
43
+
44
+ const { prompt, flags, errors, warnings } = parseArgs(process.argv.slice(2));
45
+
46
+ for (const warning of warnings) console.warn(`Note: ${warning}`);
47
+
48
+ if (errors.length) {
49
+ for (const error of errors) console.error(`Error: ${error}`);
50
+ process.exit(1);
51
+ }
52
+
53
+ if (!prompt) {
54
+ usage();
55
+ process.exit(1);
56
+ }
57
+
58
+ const provider = flags.provider || 'openai';
59
+ const defaultOutputBase = `./generated-${Date.now()}`;
60
+
61
+ async function postJson(url, { headers = {}, body }) {
62
+ try {
63
+ return await fetch(url, {
64
+ method: 'POST',
65
+ headers: { 'Content-Type': 'application/json', ...headers },
66
+ body: JSON.stringify(body),
67
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
68
+ });
69
+ } catch (err) {
70
+ if (err.name === 'TimeoutError' || err.name === 'AbortError') {
71
+ console.error(`Error: no response within ${REQUEST_TIMEOUT_MS / 1000}s — the endpoint may be unreachable or overloaded.`);
72
+ process.exit(1);
73
+ }
74
+ throw err;
75
+ }
76
+ }
77
+
78
+ async function failOnBadResponse(response) {
79
+ if (response.ok) return;
80
+ console.error(`API Error (${response.status}): ${await response.text()}`);
81
+ process.exit(1);
82
+ }
83
+
84
+ // ─── OpenAI provider ───
85
+
86
+ async function generateOpenAI() {
87
+ const credentials = await resolveOpenAI();
88
+ if (!credentials.ok) {
89
+ console.error(`Error: no usable OpenAI credentials. ${credentials.reason}`);
90
+ process.exit(1);
91
+ }
92
+
93
+ const { apiKey, baseUrl, source } = credentials;
94
+ const model = flags.model || 'gpt-image-2';
95
+ const quality = flags.quality || 'auto';
96
+
97
+ const size = openAiSize(flags.size);
98
+ if (size.error) {
99
+ console.error(`Error: ${size.error}`);
100
+ process.exit(1);
101
+ }
102
+
103
+ console.log(`Generating image with ${model}...`);
104
+ console.log(`Provider: OpenAI`);
105
+ console.log(`Endpoint: ${baseUrl} (credentials from ${source})`);
106
+ console.log(`Prompt: "${prompt}"`);
107
+ console.log(`Size: ${size.value}, Quality: ${quality}`);
108
+
109
+ const response = await postJson(`${baseUrl}/images/generations`, {
110
+ headers: { Authorization: `Bearer ${apiKey}` },
111
+ body: { model, prompt, n: 1, size: size.value, quality },
112
+ });
113
+ await failOnBadResponse(response);
114
+
115
+ const data = await response.json();
116
+ const imageData = data?.data?.[0];
117
+ if (!imageData) {
118
+ console.error('Error: no image data in response');
119
+ console.error(JSON.stringify(data, null, 2));
120
+ process.exit(1);
121
+ }
122
+
123
+ let buffer;
124
+ let mimeType = 'image/png';
125
+
126
+ if (imageData.b64_json) {
127
+ buffer = Buffer.from(imageData.b64_json, 'base64');
128
+ if (imageData.output_format) mimeType = `image/${imageData.output_format}`;
129
+ } else if (imageData.url) {
130
+ console.log('Downloading from URL...');
131
+ const download = await fetch(imageData.url, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
132
+ if (!download.ok) {
133
+ console.error(`Failed to download image: ${download.status}`);
134
+ process.exit(1);
135
+ }
136
+ mimeType = download.headers.get('content-type') || mimeType;
137
+ buffer = Buffer.from(await download.arrayBuffer());
138
+ } else {
139
+ console.error('Error: response contains neither b64_json nor url');
140
+ process.exit(1);
141
+ }
142
+
143
+ await saveImage(buffer, mimeType, { requestedSize: flags.size });
144
+
145
+ if (imageData.revised_prompt) {
146
+ console.log(`\nšŸ“ Revised prompt: ${imageData.revised_prompt}`);
147
+ }
148
+ }
149
+
150
+ // ─── Gemini provider ───
151
+
152
+ async function generateGemini() {
153
+ const credentials = resolveGemini();
154
+ if (!credentials.ok) {
155
+ console.error(`Error: ${credentials.reason}`);
156
+ process.exit(1);
157
+ }
158
+
159
+ const model = flags.model || 'gemini-3-pro-image-preview';
160
+
161
+ // Gemini takes a ratio, not pixel dimensions, so a WxH --size is snapped to the
162
+ // nearest supported ratio. It used to be accepted and discarded entirely.
163
+ const aspect = geminiAspectRatio(flags.size);
164
+ if (aspect.error) {
165
+ console.error(`Error: ${aspect.error}`);
166
+ process.exit(1);
167
+ }
168
+
169
+ console.log(`Generating image with ${model}...`);
170
+ console.log(`Provider: Gemini (Nano Banana)`);
171
+ console.log(`Prompt: "${prompt}"`);
172
+ if (aspect.value) {
173
+ const from = aspect.snappedFrom ? ` (nearest ratio to ${aspect.snappedFrom})` : '';
174
+ console.log(`Aspect ratio: ${aspect.value}${from}`);
175
+ }
176
+
177
+ const generationConfig = { responseModalities: ['IMAGE', 'TEXT'] };
178
+ if (aspect.value) generationConfig.imageConfig = { aspectRatio: aspect.value };
179
+
180
+ const response = await postJson(
181
+ `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${credentials.apiKey}`,
182
+ { body: { contents: [{ parts: [{ text: prompt }] }], generationConfig } },
183
+ );
184
+ await failOnBadResponse(response);
185
+
186
+ const data = await response.json();
187
+ const parts = data?.candidates?.[0]?.content?.parts;
188
+ if (!parts) {
189
+ console.error('Error: no content in response');
190
+ console.error(JSON.stringify(data, null, 2));
191
+ process.exit(1);
192
+ }
193
+
194
+ const imagePart = parts.find((part) => part.inlineData?.mimeType?.startsWith('image/'));
195
+ if (!imagePart) {
196
+ console.error('Error: no image found in response parts');
197
+ console.error('Available parts:', parts.map((part) => Object.keys(part)).join(', '));
198
+ process.exit(1);
199
+ }
200
+
201
+ await saveImage(Buffer.from(imagePart.inlineData.data, 'base64'), imagePart.inlineData.mimeType, {
202
+ aspectRatio: aspect.value,
203
+ });
204
+
205
+ const textPart = parts.find((part) => part.text);
206
+ if (textPart) console.log(`\nšŸ“ Model response: ${textPart.text}`);
207
+ }
208
+
209
+ // ─── Helpers ───
210
+
211
+ async function saveImage(buffer, mimeType, expected = {}) {
212
+ const { path, warning } = resolveOutputPath({
213
+ requested: flags.output,
214
+ defaultBase: defaultOutputBase,
215
+ mimeType,
216
+ });
217
+ const outputPath = resolve(path);
218
+
219
+ await mkdir(dirname(outputPath), { recursive: true });
220
+ await writeFile(outputPath, buffer);
221
+
222
+ if (warning) console.warn(`Note: ${warning}`);
223
+ console.log(`\nāœ… Image saved to: ${outputPath}`);
224
+
225
+ const actual = imageDimensions(buffer);
226
+ const dimensions = actual ? `${actual.width}x${actual.height}, ` : '';
227
+ console.log(` ${dimensions}${(buffer.length / 1024).toFixed(1)} KB`);
228
+
229
+ const mismatch = describeSizeMismatch({ ...expected, actual });
230
+ if (mismatch) console.warn(`Note: ${mismatch} Proxies and models do not always honor the requested size.`);
231
+ }
232
+
233
+ // ─── Main ───
234
+
235
+ const generators = { openai: generateOpenAI, gemini: generateGemini };
236
+
237
+ generators[provider]().catch((err) => {
238
+ console.error('Generation failed:', err.message);
239
+ process.exit(1);
240
+ });