egaki 0.0.1 → 0.1.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +239 -0
  3. package/dist/antigravity-auth.d.ts +15 -0
  4. package/dist/antigravity-auth.d.ts.map +1 -0
  5. package/dist/antigravity-auth.js +544 -0
  6. package/dist/antigravity-image.d.ts +11 -0
  7. package/dist/antigravity-image.d.ts.map +1 -0
  8. package/dist/antigravity-image.js +285 -0
  9. package/dist/chatgpt-auth.js +294 -0
  10. package/dist/cli.d.ts +3 -0
  11. package/dist/cli.d.ts.map +1 -0
  12. package/dist/cli.js +666 -0
  13. package/dist/credentials.d.ts +18 -0
  14. package/dist/credentials.d.ts.map +1 -0
  15. package/dist/credentials.js +107 -0
  16. package/dist/gateway-model-candidates.generated.d.ts +11 -0
  17. package/dist/gateway-model-candidates.generated.d.ts.map +1 -0
  18. package/dist/gateway-model-candidates.generated.js +64 -0
  19. package/dist/login.d.ts +9 -0
  20. package/dist/login.d.ts.map +1 -0
  21. package/dist/login.js +112 -0
  22. package/dist/model-catalog.d.ts +42 -0
  23. package/dist/model-catalog.d.ts.map +1 -0
  24. package/dist/model-catalog.js +898 -0
  25. package/dist/models.d.ts +15 -0
  26. package/dist/models.d.ts.map +1 -0
  27. package/dist/models.js +196 -0
  28. package/dist/open-browser.d.ts +2 -0
  29. package/dist/open-browser.d.ts.map +1 -0
  30. package/dist/open-browser.js +37 -0
  31. package/dist/subscription.d.ts +5 -0
  32. package/dist/subscription.d.ts.map +1 -0
  33. package/dist/subscription.js +216 -0
  34. package/dist/video-model-catalog.d.ts +52 -0
  35. package/dist/video-model-catalog.d.ts.map +1 -0
  36. package/dist/video-model-catalog.js +245 -0
  37. package/package.json +68 -5
  38. package/src/cli.ts +998 -0
  39. package/src/credentials.ts +126 -0
  40. package/src/login.ts +163 -0
  41. package/src/model-catalog.ts +968 -0
  42. package/src/models.ts +258 -0
  43. package/src/open-browser.ts +48 -0
  44. package/src/subscription.ts +298 -0
  45. package/src/video-model-catalog.ts +302 -0
  46. package/index.js +0 -1
package/src/cli.ts ADDED
@@ -0,0 +1,998 @@
1
+ #!/usr/bin/env node
2
+ // Main CLI entrypoint for egaki - AI image and video generation.
3
+ // Uses the Vercel AI SDK for image generation across multiple providers.
4
+ // Designed to be called by agents and humans alike.
5
+ //
6
+ // Two generation paths depending on model:
7
+ // - imagen-* models → generateImage() with google.image()
8
+ // - all other models → generateText() with responseModalities: ['IMAGE']
9
+ // The CLI auto-detects which path to use based on model ID prefix.
10
+ import { goke } from 'goke'
11
+ import { z } from 'zod'
12
+ import dedent from 'string-dedent'
13
+ import {
14
+ generateImage as aiGenerateImage,
15
+ generateText,
16
+ experimental_generateVideo as aiGenerateVideo,
17
+ } from 'ai'
18
+ import fs from 'node:fs'
19
+ import path from 'node:path'
20
+ import pc from 'picocolors'
21
+ import pkg from '../package.json' with { type: 'json' }
22
+ import { injectCredentialsToEnv, PROVIDERS } from './credentials.js'
23
+ import {
24
+ IMAGE_MODELS,
25
+ VIDEO_MODELS,
26
+ DEFAULT_MODEL,
27
+ DEFAULT_VIDEO_MODEL,
28
+ getModelConfig,
29
+ createImageModel,
30
+ createTextModel,
31
+ createVideoModel,
32
+ } from './models.js'
33
+ import { VIDEO_CATALOG } from './video-model-catalog.js'
34
+ import {
35
+ loginInteractive,
36
+ loginNonInteractive,
37
+ showLoginStatus,
38
+ removeLogin,
39
+ readKeyFromStdin,
40
+ } from './login.js'
41
+ import {
42
+ subscribeInteractive,
43
+ subscribeNonInteractive,
44
+ unsubscribe,
45
+ showUsage,
46
+ } from './subscription.js'
47
+
48
+ const cli = goke('egaki')
49
+
50
+ process.title = 'egaki'
51
+
52
+ // Print clean error output for unhandled rejections (e.g. AI SDK APICallError).
53
+ // The AI SDK errors include request bodies, response headers, and other noisy
54
+ // properties that get dumped by Node's default handler. We strip those and just
55
+ // print the message + stack trace.
56
+ process.on('uncaughtException', (err) => {
57
+ console.error(pc.red(err.message))
58
+ if (err.stack) {
59
+ const lines = err.stack.split('\n')
60
+ const stackOnly = lines.filter((l) => l.trimStart().startsWith('at '))
61
+ if (stackOnly.length > 0) {
62
+ console.error(pc.dim(stackOnly.join('\n')))
63
+ }
64
+ }
65
+ process.exit(1)
66
+ })
67
+
68
+ // ─── login command ───────────────────────────────────────────────────────────
69
+
70
+ cli
71
+ .command(
72
+ 'login',
73
+ dedent`
74
+ Configure API keys for image generation providers.
75
+ Interactive mode: shows a provider picker and secure key input.
76
+ Non-interactive mode: pass --provider and --key flags, or pipe key via stdin.
77
+ Keys are saved to ~/.config/egaki/credentials.json (mode 0600).
78
+ `,
79
+ )
80
+ .option(
81
+ '-p, --provider [name]',
82
+ z
83
+ .string()
84
+ .describe(
85
+ `Provider name for non-interactive login (${Object.keys(PROVIDERS).join(', ')})`,
86
+ ),
87
+ )
88
+ .option(
89
+ '-k, --key [key]',
90
+ z.string().describe('API key value for non-interactive login'),
91
+ )
92
+ .option('--show', 'Show which providers are configured and their status')
93
+ .option(
94
+ '--remove [provider]',
95
+ z.string().describe('Remove the stored key for a provider'),
96
+ )
97
+ .example('# Interactive login (pick provider, paste key)')
98
+ .example('egaki login')
99
+ .example('# Non-interactive login with flags')
100
+ .example('egaki login --provider google --key AIza...')
101
+ .example('# Pipe key from stdin (useful in CI/scripts)')
102
+ .example('echo "AIza..." | egaki login --provider google')
103
+ .example('# Show configured providers')
104
+ .example('egaki login --show')
105
+ .example('# Remove a stored key')
106
+ .example('egaki login --remove google')
107
+ .action(async (options) => {
108
+ if (options.show) {
109
+ showLoginStatus()
110
+ return
111
+ }
112
+
113
+ if (options.remove) {
114
+ removeLogin(options.remove)
115
+ return
116
+ }
117
+
118
+ // Non-interactive: --provider + --key or stdin
119
+ if (options.provider) {
120
+ const key = options.key || (await readKeyFromStdin())
121
+ loginNonInteractive({ provider: options.provider, key })
122
+ return
123
+ }
124
+
125
+ // Interactive mode
126
+ await loginInteractive()
127
+ })
128
+
129
+ // ─── subscribe command ───────────────────────────────────────────────────────
130
+
131
+ cli
132
+ .command(
133
+ 'subscribe',
134
+ dedent`
135
+ Subscribe to Egaki for access to all image models with a single API key.
136
+ You can also use your own provider keys (Google/OpenAI/Replicate/Fal)
137
+ via 'egaki login --provider <name> --key <key>' if you prefer BYOK.
138
+ Egaki subscription avoids managing one key per provider.
139
+ Three plans: Starter ($9/mo, 100 credits), Pro ($29/mo, 500 credits),
140
+ Unlimited ($99/mo, 2000 credits). One credit ≈ one standard image.
141
+ Interactive mode: pick a plan and get a checkout URL (email prefill optional).
142
+ Non-interactive: --email is optional and only pre-fills checkout.
143
+ `,
144
+ )
145
+ .option(
146
+ '-e, --email [email]',
147
+ z.string().describe('Optional email prefill for checkout (skips interactive prompt)'),
148
+ )
149
+ .option(
150
+ '--plan [plan]',
151
+ z.string().describe('Plan ID: starter, pro, or unlimited (default: pro)'),
152
+ )
153
+ .example('# Interactive subscribe')
154
+ .example('egaki subscribe')
155
+ .example('# Non-interactive (for agents)')
156
+ .example('egaki subscribe --email user@example.com --plan pro')
157
+ .example('# Non-interactive without email prefill')
158
+ .example('egaki subscribe --plan pro')
159
+ .action(async (options) => {
160
+ const isTTY = process.stdout.isTTY && process.stdin.isTTY
161
+ if (!isTTY || options.email || options.plan) {
162
+ subscribeNonInteractive(options.email, options.plan)
163
+ return
164
+ }
165
+ await subscribeInteractive()
166
+ })
167
+
168
+ // ─── unsubscribe command ─────────────────────────────────────────────────────
169
+
170
+ cli
171
+ .command(
172
+ 'unsubscribe',
173
+ dedent`
174
+ Cancel your Egaki subscription. Uses the stored API key to identify
175
+ the subscription. You can resubscribe anytime with 'egaki subscribe'.
176
+ `,
177
+ )
178
+ .example('egaki unsubscribe')
179
+ .action(async () => {
180
+ await unsubscribe()
181
+ })
182
+
183
+ // ─── usage command ───────────────────────────────────────────────────────────
184
+
185
+ cli
186
+ .command(
187
+ 'usage',
188
+ dedent`
189
+ Show your current Egaki credit usage for this billing period.
190
+ Displays plan, credits used, credits remaining, and period info.
191
+ `,
192
+ )
193
+ .example('egaki usage')
194
+ .action(async () => {
195
+ await showUsage()
196
+ })
197
+
198
+ // ─── image command ───────────────────────────────────────────────────────────
199
+
200
+ cli
201
+ .command(
202
+ 'image <prompt>',
203
+ dedent`
204
+ Generate images from a text prompt using AI models.
205
+ Supports Imagen models (dedicated image generation) and Gemini
206
+ multimodal models (text+image output). The model type is auto-detected
207
+ from the model ID: imagen-* uses the image API, everything else uses
208
+ the text API with image output enabled.
209
+ `,
210
+ )
211
+ .option(
212
+ '-m, --model [model]',
213
+ z.enum(IMAGE_MODELS).default(DEFAULT_MODEL).describe('Model ID for generation'),
214
+ )
215
+ .option(
216
+ '-o, --output [path]',
217
+ z
218
+ .string()
219
+ .default('egaki-output.png')
220
+ .describe('Output file path (index suffix added when generating multiple)'),
221
+ )
222
+ .option(
223
+ '-n, --count [n]',
224
+ z.number().default(1).describe('Number of images to generate'),
225
+ )
226
+ .option(
227
+ '--aspect-ratio [ratio]',
228
+ z
229
+ .string()
230
+ .describe(
231
+ 'Aspect ratio for the generated image. Imagen supports: 1:1, 3:4, 4:3, 9:16, 16:9. Gemini supports additional ratios: 2:3, 3:2, 4:5, 5:4, 21:9',
232
+ ),
233
+ )
234
+ .option(
235
+ '--seed [seed]',
236
+ z.number().describe('Seed for reproducible generation. Same seed + same prompt = same image'),
237
+ )
238
+ .option(
239
+ '--image-size [size]',
240
+ z
241
+ .enum(['1K', '2K', '4K'])
242
+ .describe(
243
+ 'Output resolution for Gemini text-model image generation. Only applies to gemini-*-image* models',
244
+ ),
245
+ )
246
+ .option(
247
+ '-i, --input [file]',
248
+ z
249
+ .array(z.string())
250
+ .describe(
251
+ 'Reference image for editing or variations (repeatable). Accepts local file paths or URLs (http/https). Pass one or more images along with a text prompt to edit them',
252
+ ),
253
+ )
254
+ .option(
255
+ '--mask [file]',
256
+ z
257
+ .string()
258
+ .describe(
259
+ 'Mask image for inpainting. Accepts a local file path or URL (http/https). White areas in the mask are replaced with generated content. Used together with --input',
260
+ ),
261
+ )
262
+ .option(
263
+ '--allow-people',
264
+ 'Allow generating images of people (Imagen blocks people by default)',
265
+ )
266
+ .option(
267
+ '--json',
268
+ 'Output result metadata as JSON to stdout (model, usage, warnings, file paths)',
269
+ )
270
+ .option(
271
+ '--stdout',
272
+ 'Write raw image bytes to stdout instead of saving to a file. Useful for piping to other tools',
273
+ )
274
+ .example('# Generate a simple image')
275
+ .example('egaki image "a sunset over mars"')
276
+ .example('# Use a specific model with aspect ratio')
277
+ .example('egaki image "cyberpunk city at night" -m imagen-4.0-ultra-generate-001 --aspect-ratio 16:9')
278
+ .example('# Edit an existing image')
279
+ .example('egaki image "add a wizard hat to the cat" --input cat.jpg -o cat-wizard.png')
280
+ .example('# Edit an image from a URL')
281
+ .example('egaki image "make it pop art" --input https://example.com/photo.jpg')
282
+ .example('# Inpainting with a mask')
283
+ .example('egaki image "fill with flowers" --input photo.jpg --mask mask.png')
284
+ .example('# Generate with Gemini multimodal at 4K')
285
+ .example('egaki image "dreamy landscape" -m gemini-2.5-flash-image --image-size 4K')
286
+ .example('# Generate multiple images')
287
+ .example('egaki image "abstract art" -n 4 -o art.png')
288
+ .example('# Pipe to another tool')
289
+ .example('egaki image "logo design" --stdout | convert - -resize 512x512 logo.png')
290
+ .action(async (prompt, options) => {
291
+ // Inject stored API keys as env vars before calling the AI SDK
292
+ injectCredentialsToEnv()
293
+
294
+ const model = options.model
295
+ const outputPath = options.output
296
+ const config = getModelConfig(model)
297
+
298
+ if (!options.stdout) {
299
+ console.error(pc.dim(`Model: ${model}`))
300
+ console.error(pc.dim(`Prompt: ${prompt}`))
301
+ console.error(
302
+ pc.dim(
303
+ config.strategy === 'image'
304
+ ? 'Mode: Image API (generateImage)'
305
+ : 'Mode: Text+Image (generateText)',
306
+ ),
307
+ )
308
+ }
309
+
310
+ const inputImages = await readInputImages(options.input)
311
+ const maskImage = options.mask
312
+ ? await readInputSource(options.mask)
313
+ : undefined
314
+
315
+ if (config.strategy === 'image') {
316
+ await generateWithImageModel({
317
+ prompt,
318
+ model,
319
+ outputPath,
320
+ count: options.count,
321
+ aspectRatio: options.aspectRatio as `${number}:${number}` | undefined,
322
+ seed: options.seed,
323
+ inputImages,
324
+ maskImage,
325
+ allowPeople: options.allowPeople || false,
326
+ json: options.json || false,
327
+ stdout: options.stdout || false,
328
+ })
329
+ } else {
330
+ await generateWithTextModel({
331
+ prompt,
332
+ model,
333
+ outputPath,
334
+ inputImages,
335
+ imageSize: options.imageSize,
336
+ aspectRatio: options.aspectRatio,
337
+ json: options.json || false,
338
+ stdout: options.stdout || false,
339
+ })
340
+ }
341
+ })
342
+
343
+ // ─── video command ───────────────────────────────────────────────────────────
344
+
345
+ cli
346
+ .command(
347
+ 'video <prompt>',
348
+ dedent`
349
+ Generate videos from a text prompt (or image+text prompt for models that
350
+ support image-to-video). Uses AI SDK experimental_generateVideo under the hood.
351
+
352
+ Agent note: video generation can be slow. When invoking this command from
353
+ automation, use a command timeout of at least 5 minutes.
354
+ `,
355
+ )
356
+ .option(
357
+ '-m, --model [model]',
358
+ z.enum(VIDEO_MODELS).default(DEFAULT_VIDEO_MODEL).describe('Video model ID for generation'),
359
+ )
360
+ .option(
361
+ '-o, --output [path]',
362
+ z
363
+ .string()
364
+ .default('egaki-output.mp4')
365
+ .describe('Output file path (index suffix added when generating multiple)'),
366
+ )
367
+ .option(
368
+ '-n, --count [n]',
369
+ z.number().default(1).describe('Number of videos to generate'),
370
+ )
371
+ .option(
372
+ '--aspect-ratio [ratio]',
373
+ z.string().describe('Video aspect ratio in WIDTH:HEIGHT format (e.g. 16:9, 9:16)'),
374
+ )
375
+ .option(
376
+ '--resolution [resolution]',
377
+ z
378
+ .string()
379
+ .describe('Video resolution in WIDTHxHEIGHT or provider format (e.g. 1280x720, 720p)'),
380
+ )
381
+ .option(
382
+ '--duration [seconds]',
383
+ z.number().describe('Video duration in seconds (provider/model-specific limits apply)'),
384
+ )
385
+ .option(
386
+ '--fps [fps]',
387
+ z.number().describe('Frames per second for video models that support fps override'),
388
+ )
389
+ .option(
390
+ '--seed [seed]',
391
+ z.number().describe('Seed for reproducible video generation (model support varies)'),
392
+ )
393
+ .option(
394
+ '-i, --input [file]',
395
+ z
396
+ .string()
397
+ .describe(
398
+ 'Optional reference image for image-to-video. Accepts local file path or URL (http/https)',
399
+ ),
400
+ )
401
+ .option(
402
+ '--json',
403
+ 'Output result metadata as JSON to stdout (model, usage, warnings, file paths)',
404
+ )
405
+ .option(
406
+ '--stdout',
407
+ 'Write raw video bytes to stdout instead of saving to a file. Useful for piping to other tools',
408
+ )
409
+ .example('# Generate a video')
410
+ .example('egaki video "A paper airplane gliding through clouds" -o airplane.mp4')
411
+ .example('# Generate with Veo model + duration')
412
+ .example('egaki video "cinematic rainy street at night" -m veo-3.1-fast-generate-001 --duration 6')
413
+ .example('# Image-to-video (model support required)')
414
+ .example('egaki video "animate subtle camera pan" --model luma-ray-2 --input frame.png -o animated.mp4')
415
+ .example('# Generate multiple videos')
416
+ .example('egaki video "waves crashing on cliffs" -n 2 -o waves.mp4')
417
+ .action(async (prompt, options) => {
418
+ injectCredentialsToEnv()
419
+
420
+ const model = options.model
421
+ const outputPath = options.output
422
+ const config = getModelConfig(model)
423
+
424
+ if (config.strategy !== 'video') {
425
+ console.error(pc.red(`Model ${model} is not a video model`))
426
+ process.exit(1)
427
+ }
428
+
429
+ if (!options.stdout) {
430
+ console.error(pc.dim(`Model: ${model}`))
431
+ console.error(pc.dim(`Prompt: ${prompt}`))
432
+ console.error(pc.dim('Mode: Video API (experimental_generateVideo)'))
433
+ }
434
+
435
+ const inputImage = options.input
436
+ ? await readInputSource(options.input)
437
+ : undefined
438
+
439
+ await generateWithVideoModel({
440
+ prompt,
441
+ model,
442
+ outputPath,
443
+ count: options.count,
444
+ aspectRatio: options.aspectRatio,
445
+ resolution: options.resolution,
446
+ duration: options.duration,
447
+ fps: options.fps,
448
+ seed: options.seed,
449
+ inputImage,
450
+ json: options.json || false,
451
+ stdout: options.stdout || false,
452
+ })
453
+ })
454
+
455
+ // ─── models command ──────────────────────────────────────────────────────────
456
+
457
+ cli
458
+ .command(
459
+ 'models',
460
+ dedent`
461
+ List all supported image generation models with pricing, features,
462
+ and provider info. Output is YAML for easy reading and piping.
463
+ `,
464
+ )
465
+ .option(
466
+ '-p, --provider [provider]',
467
+ z.string().describe('Filter models by provider name (e.g. google, openai, replicate, fal)'),
468
+ )
469
+ .option(
470
+ '--type [type]',
471
+ z
472
+ .enum(['all', 'image', 'video'])
473
+ .default('all')
474
+ .describe('Filter by model type: image (image+text-image), video, or all'),
475
+ )
476
+ .option('--json', 'Output as JSON instead of YAML')
477
+ .action(async (options) => {
478
+ const { CATALOG } = await import('./model-catalog.js')
479
+ const yaml = await import('js-yaml')
480
+
481
+ let models = options.type === 'video'
482
+ ? VIDEO_CATALOG
483
+ : options.type === 'image'
484
+ ? CATALOG
485
+ : [...CATALOG, ...VIDEO_CATALOG]
486
+
487
+ if (options.provider) {
488
+ models = models.filter((m) => m.provider === options.provider)
489
+ if (models.length === 0) {
490
+ console.error(pc.red(`No models found for provider: ${options.provider}`))
491
+ process.exit(1)
492
+ }
493
+ }
494
+
495
+ const output = models.map((m) => ({
496
+ id: m.id,
497
+ name: m.name,
498
+ ...(m.description ? { description: m.description } : {}),
499
+ provider: m.provider,
500
+ strategy: m.strategy,
501
+ released: m.released,
502
+ cost: formatCatalogCost(m.cost),
503
+ features:
504
+ m.strategy === 'video'
505
+ ? {
506
+ textToVideo: m.features.textToVideo,
507
+ imageToVideo: m.features.imageToVideo,
508
+ capabilities: m.features.capabilities.join(', ') || 'none',
509
+ seed: m.features.seed,
510
+ multipleVideos: m.features.multipleVideos,
511
+ aspectRatios: m.features.aspectRatios?.join(', ') || 'none',
512
+ resolutions: m.features.resolutions?.join(', ') || 'unknown',
513
+ durationRangeSec: m.features.durationRangeSec
514
+ ? `${m.features.durationRangeSec.min}-${m.features.durationRangeSec.max}`
515
+ : 'unknown',
516
+ }
517
+ : {
518
+ editing: m.features.editing,
519
+ inpainting: m.features.inpainting,
520
+ seed: m.features.seed,
521
+ multipleImages: m.features.multipleImages,
522
+ aspectRatios: m.features.aspectRatios.join(', ') || 'none',
523
+ ...(m.features.sizes ? { sizes: m.features.sizes.join(', ') } : {}),
524
+ },
525
+ }))
526
+
527
+ if (options.json) {
528
+ console.log(JSON.stringify(output, null, 2))
529
+ } else {
530
+ console.log(yaml.dump(output, { lineWidth: 120, noRefs: true }))
531
+ }
532
+ })
533
+
534
+ cli.help()
535
+ cli.version(pkg.version)
536
+ cli.parse()
537
+
538
+ function isUrl(input: string): boolean {
539
+ return /^https?:\/\//i.test(input)
540
+ }
541
+
542
+ async function readInputSource(input: string): Promise<Uint8Array> {
543
+ if (isUrl(input)) {
544
+ console.error(pc.dim(`Fetching ${input}...`))
545
+ const res = await fetch(input)
546
+ if (!res.ok) {
547
+ console.error(pc.red(`Failed to fetch ${input}: ${res.status} ${res.statusText}`))
548
+ process.exit(1)
549
+ }
550
+ return new Uint8Array(await res.arrayBuffer())
551
+ }
552
+ const resolved = path.resolve(input)
553
+ if (!fs.existsSync(resolved)) {
554
+ console.error(pc.red(`File not found: ${resolved}`))
555
+ process.exit(1)
556
+ }
557
+ return new Uint8Array(fs.readFileSync(resolved))
558
+ }
559
+
560
+ async function readInputImages(
561
+ inputs: string[] | undefined,
562
+ ): Promise<Uint8Array[]> {
563
+ if (!inputs || inputs.length === 0) {
564
+ return []
565
+ }
566
+ return Promise.all(inputs.map((f) => readInputSource(f)))
567
+ }
568
+
569
+ // Generate using the dedicated generateImage API (Imagen models)
570
+ async function generateWithImageModel({
571
+ prompt,
572
+ model,
573
+ outputPath,
574
+ count,
575
+ aspectRatio,
576
+ seed,
577
+ inputImages,
578
+ maskImage,
579
+ allowPeople,
580
+ json,
581
+ stdout,
582
+ }: {
583
+ prompt: string
584
+ model: string
585
+ outputPath: string
586
+ count: number
587
+ aspectRatio?: `${number}:${number}`
588
+ seed?: number
589
+ inputImages: Uint8Array[]
590
+ maskImage?: Uint8Array
591
+ allowPeople: boolean
592
+ json: boolean
593
+ stdout: boolean
594
+ }) {
595
+ // Build the prompt: plain string or multimodal with reference images
596
+ const imagePrompt = inputImages.length > 0
597
+ ? { text: prompt, images: inputImages, ...(maskImage ? { mask: maskImage } : {}) }
598
+ : prompt
599
+
600
+ const imageModel = await createImageModel(model)
601
+
602
+ if (!stdout) {
603
+ console.error(pc.cyan('Generating...'))
604
+ }
605
+
606
+ const result = await aiGenerateImage({
607
+ model: imageModel,
608
+ prompt: imagePrompt,
609
+ n: count,
610
+ ...(aspectRatio ? { aspectRatio } : {}),
611
+ ...(seed !== undefined ? { seed } : {}),
612
+ providerOptions: {
613
+ google: {
614
+ ...(allowPeople ? { personGeneration: 'allow_all' } : {}),
615
+ ...(aspectRatio ? { aspectRatio } : {}),
616
+ },
617
+ },
618
+ })
619
+
620
+ if (stdout) {
621
+ // Write first image to stdout for piping
622
+ const image = result.images[0]
623
+ if (image) {
624
+ process.stdout.write(Buffer.from(image.uint8Array))
625
+ }
626
+ return
627
+ }
628
+
629
+ const savedFiles: string[] = []
630
+ for (let i = 0; i < result.images.length; i++) {
631
+ const image = result.images[i]!
632
+ const ext = extensionFromMediaType(image.mediaType)
633
+ const filePath =
634
+ result.images.length === 1
635
+ ? ensureExtension(outputPath, ext)
636
+ : insertIndex(outputPath, i, ext)
637
+
638
+ fs.writeFileSync(filePath, image.uint8Array)
639
+ console.error(pc.green(`Saved: ${filePath}`))
640
+ savedFiles.push(filePath)
641
+ }
642
+
643
+ const config = getModelConfig(model)
644
+ const cost = calculateCost(config.cost, result.usage, result.images.length)
645
+ if (cost != null) {
646
+ console.error(pc.dim(`Cost: ${formatCost(cost)}`))
647
+ }
648
+
649
+ if (json) {
650
+ const output = {
651
+ model,
652
+ files: savedFiles,
653
+ count: result.images.length,
654
+ cost,
655
+ usage: result.usage,
656
+ warnings: result.warnings,
657
+ }
658
+ console.log(JSON.stringify(output, null, 2))
659
+ }
660
+ }
661
+
662
+ // Generate using generateText with responseModalities (Gemini multimodal models)
663
+ async function generateWithTextModel({
664
+ prompt,
665
+ model,
666
+ outputPath,
667
+ inputImages,
668
+ imageSize,
669
+ aspectRatio,
670
+ json,
671
+ stdout,
672
+ }: {
673
+ prompt: string
674
+ model: string
675
+ outputPath: string
676
+ inputImages: Uint8Array[]
677
+ imageSize?: '1K' | '2K' | '4K'
678
+ aspectRatio?: string
679
+ json: boolean
680
+ stdout: boolean
681
+ }) {
682
+ const textModel = await createTextModel(model)
683
+
684
+ if (!stdout) {
685
+ console.error(pc.cyan('Generating...'))
686
+ }
687
+
688
+ // Build messages: if we have input images, create a multimodal prompt
689
+ const messages = inputImages.length > 0
690
+ ? [
691
+ {
692
+ role: 'user' as const,
693
+ content: [
694
+ { type: 'text' as const, text: prompt },
695
+ ...inputImages.map((img) => ({
696
+ type: 'image' as const,
697
+ image: img,
698
+ })),
699
+ ],
700
+ },
701
+ ]
702
+ : undefined
703
+
704
+ const result = await generateText({
705
+ model: textModel,
706
+ ...(messages ? { messages } : { prompt }),
707
+ providerOptions: {
708
+ google: {
709
+ responseModalities: ['TEXT', 'IMAGE'],
710
+ ...(imageSize || aspectRatio
711
+ ? {
712
+ imageConfig: {
713
+ ...(imageSize ? { imageSize } : {}),
714
+ ...(aspectRatio ? { aspectRatio } : {}),
715
+ },
716
+ }
717
+ : {}),
718
+ },
719
+ },
720
+ })
721
+
722
+ const imageFiles = result.files.filter((f) => {
723
+ return f.mediaType.startsWith('image/')
724
+ })
725
+
726
+ if (imageFiles.length === 0) {
727
+ console.error(pc.red('No images generated.'))
728
+ process.exit(1)
729
+ }
730
+
731
+ if (stdout) {
732
+ const file = imageFiles[0]
733
+ if (file) {
734
+ process.stdout.write(Buffer.from(file.uint8Array))
735
+ }
736
+ return
737
+ }
738
+
739
+ const savedFiles: string[] = []
740
+ for (let i = 0; i < imageFiles.length; i++) {
741
+ const file = imageFiles[i]!
742
+ const ext = extensionFromMediaType(file.mediaType)
743
+ const filePath =
744
+ imageFiles.length === 1
745
+ ? ensureExtension(outputPath, ext)
746
+ : insertIndex(outputPath, i, ext)
747
+
748
+ fs.writeFileSync(filePath, file.uint8Array)
749
+ console.error(pc.green(`Saved: ${filePath}`))
750
+ savedFiles.push(filePath)
751
+ }
752
+
753
+ const config = getModelConfig(model)
754
+ const cost = calculateCost(config.cost, result.usage, imageFiles.length)
755
+ if (cost != null) {
756
+ console.error(pc.dim(`Cost: ${formatCost(cost)}`))
757
+ }
758
+
759
+ if (result.text && !json) {
760
+ console.error(pc.dim(result.text))
761
+ }
762
+
763
+ if (json) {
764
+ const output = {
765
+ model,
766
+ files: savedFiles,
767
+ count: imageFiles.length,
768
+ text: result.text || null,
769
+ cost,
770
+ usage: result.usage,
771
+ }
772
+ console.log(JSON.stringify(output, null, 2))
773
+ }
774
+ }
775
+
776
+ // Generate using experimental_generateVideo (video models)
777
+ async function generateWithVideoModel({
778
+ prompt,
779
+ model,
780
+ outputPath,
781
+ count,
782
+ aspectRatio,
783
+ resolution,
784
+ duration,
785
+ fps,
786
+ seed,
787
+ inputImage,
788
+ json,
789
+ stdout,
790
+ }: {
791
+ prompt: string
792
+ model: string
793
+ outputPath: string
794
+ count: number
795
+ aspectRatio?: string
796
+ resolution?: string
797
+ duration?: number
798
+ fps?: number
799
+ seed?: number
800
+ inputImage?: Uint8Array
801
+ json: boolean
802
+ stdout: boolean
803
+ }) {
804
+ const videoModel = await createVideoModel(model)
805
+
806
+ if (!stdout) {
807
+ console.error(pc.cyan('Generating...'))
808
+ }
809
+
810
+ const result = await aiGenerateVideo({
811
+ model: videoModel,
812
+ prompt: inputImage
813
+ ? { image: inputImage, text: prompt }
814
+ : prompt,
815
+ n: count,
816
+ ...(aspectRatio ? { aspectRatio: aspectRatio as `${number}:${number}` } : {}),
817
+ ...(resolution ? { resolution: resolution as `${number}x${number}` } : {}),
818
+ ...(duration != null ? { duration } : {}),
819
+ ...(fps != null ? { fps } : {}),
820
+ ...(seed != null ? { seed } : {}),
821
+ })
822
+
823
+ if (stdout) {
824
+ const video = result.videos[0]
825
+ if (video) {
826
+ process.stdout.write(Buffer.from(video.uint8Array))
827
+ }
828
+ return
829
+ }
830
+
831
+ const savedFiles: string[] = []
832
+ for (let i = 0; i < result.videos.length; i++) {
833
+ const video = result.videos[i]!
834
+ const ext = extensionFromMediaType(video.mediaType)
835
+ const filePath =
836
+ result.videos.length === 1
837
+ ? ensureExtension(outputPath, ext)
838
+ : insertIndex(outputPath, i, ext)
839
+
840
+ fs.writeFileSync(filePath, video.uint8Array)
841
+ console.error(pc.green(`Saved: ${filePath}`))
842
+ savedFiles.push(filePath)
843
+ }
844
+
845
+ const config = getModelConfig(model)
846
+ const cost = calculateCost(config.cost, {
847
+ videosGenerated: result.videos.length,
848
+ durationSeconds: duration,
849
+ resolution,
850
+ }, result.videos.length)
851
+ if (cost != null) {
852
+ console.error(pc.dim(`Cost: ${formatCost(cost)}`))
853
+ }
854
+
855
+ if (json) {
856
+ const output = {
857
+ model,
858
+ files: savedFiles,
859
+ count: result.videos.length,
860
+ cost,
861
+ warnings: result.warnings,
862
+ responses: result.responses,
863
+ }
864
+ console.log(JSON.stringify(output, null, 2))
865
+ }
866
+ }
867
+
868
+ // ─── cost helpers ────────────────────────────────────────────────────────────
869
+
870
+ function calculateCost(
871
+ cost: {
872
+ type: 'per-image'
873
+ perImage: number
874
+ } | {
875
+ type: 'per-token'
876
+ inputPerM: number
877
+ outputPerM: number
878
+ } | {
879
+ type: 'per-video-second'
880
+ defaultDurationSec: number
881
+ tiers: Array<{ resolution?: string; costPerSecond: number }>
882
+ } | {
883
+ type: 'unknown'
884
+ },
885
+ usage: {
886
+ inputTokens?: number
887
+ outputTokens?: number
888
+ imagesGenerated?: number
889
+ videosGenerated?: number
890
+ durationSeconds?: number
891
+ resolution?: string
892
+ },
893
+ count: number = 1,
894
+ ): number | null {
895
+ if (cost.type === 'per-image') {
896
+ return cost.perImage * count
897
+ }
898
+ if (cost.type === 'per-token' && usage.inputTokens != null && usage.outputTokens != null) {
899
+ return (
900
+ (usage.inputTokens * cost.inputPerM + usage.outputTokens * cost.outputPerM) / 1_000_000
901
+ )
902
+ }
903
+ if (cost.type === 'per-video-second') {
904
+ const durationSec = usage.durationSeconds ?? cost.defaultDurationSec
905
+ const resolution = normalizeResolutionKey(usage.resolution)
906
+ const tier =
907
+ cost.tiers.find((t) => normalizeResolutionKey(t.resolution) === resolution) ??
908
+ cost.tiers[0]
909
+ if (!tier) {
910
+ return null
911
+ }
912
+ return tier.costPerSecond * durationSec * count
913
+ }
914
+ return null
915
+ }
916
+
917
+ function formatCatalogCost(
918
+ cost: {
919
+ type: 'per-image'
920
+ perImage: number
921
+ } | {
922
+ type: 'per-token'
923
+ inputPerM: number
924
+ outputPerM: number
925
+ } | {
926
+ type: 'per-video-second'
927
+ defaultDurationSec: number
928
+ tiers: Array<{ resolution?: string; mode?: string; audio?: boolean; costPerSecond: number }>
929
+ } | {
930
+ type: 'unknown'
931
+ },
932
+ ): string {
933
+ if (cost.type === 'per-image') {
934
+ return `$${cost.perImage}/image`
935
+ }
936
+ if (cost.type === 'per-token') {
937
+ return `$${cost.inputPerM}/M input, $${cost.outputPerM}/M output`
938
+ }
939
+ if (cost.type === 'per-video-second') {
940
+ const tierText = cost.tiers
941
+ .map((t) => {
942
+ const parts = [
943
+ t.resolution,
944
+ t.mode ? `mode=${t.mode}` : undefined,
945
+ t.audio != null ? `audio=${t.audio}` : undefined,
946
+ ].filter(Boolean)
947
+ return parts.length > 0
948
+ ? `$${t.costPerSecond}/s (${parts.join(', ')})`
949
+ : `$${t.costPerSecond}/s`
950
+ })
951
+ .join('; ')
952
+ return `${tierText} (default duration ${cost.defaultDurationSec}s)`
953
+ }
954
+ return 'unknown'
955
+ }
956
+
957
+ function formatCost(dollars: number): string {
958
+ if (dollars < 0.01) {
959
+ return `$${dollars.toFixed(4)}`
960
+ }
961
+ return `$${dollars.toFixed(2)}`
962
+ }
963
+
964
+ function extensionFromMediaType(mediaType: string): string {
965
+ const map: Record<string, string> = {
966
+ 'image/png': '.png',
967
+ 'image/jpeg': '.jpg',
968
+ 'image/webp': '.webp',
969
+ 'image/gif': '.gif',
970
+ 'video/mp4': '.mp4',
971
+ 'video/webm': '.webm',
972
+ 'video/quicktime': '.mov',
973
+ }
974
+ return map[mediaType] || (mediaType.startsWith('video/') ? '.mp4' : '.png')
975
+ }
976
+
977
+ function normalizeResolutionKey(input?: string): string | undefined {
978
+ if (!input) return undefined
979
+ const normalized = input.trim().toLowerCase()
980
+ if (normalized === '1920x1080') return '1080p'
981
+ if (normalized === '1280x720') return '720p'
982
+ if (normalized === '854x480' || normalized === '848x480') return '480p'
983
+ return normalized
984
+ }
985
+
986
+ function ensureExtension(filePath: string, ext: string): string {
987
+ const parsed = path.parse(filePath)
988
+ if (parsed.ext) {
989
+ return filePath
990
+ }
991
+ return filePath + ext
992
+ }
993
+
994
+ function insertIndex(filePath: string, index: number, ext: string): string {
995
+ const parsed = path.parse(filePath)
996
+ const finalExt = parsed.ext || ext
997
+ return path.join(parsed.dir, `${parsed.name}-${index}${finalExt}`)
998
+ }