egaki 0.0.1 → 0.0.2

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.ts ADDED
@@ -0,0 +1,679 @@
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 { generateImage as aiGenerateImage, generateText } from 'ai'
14
+ import fs from 'node:fs'
15
+ import path from 'node:path'
16
+ import pc from 'picocolors'
17
+ import pkg from '../package.json' with { type: 'json' }
18
+ import { injectCredentialsToEnv, PROVIDERS } from './credentials.js'
19
+ import {
20
+ IMAGE_MODELS,
21
+ DEFAULT_MODEL,
22
+ getModelConfig,
23
+ createImageModel,
24
+ createTextModel,
25
+ } from './models.js'
26
+ import type { ModelCost } from './model-catalog.js'
27
+ import {
28
+ loginInteractive,
29
+ loginNonInteractive,
30
+ showLoginStatus,
31
+ removeLogin,
32
+ readKeyFromStdin,
33
+ } from './login.js'
34
+ import {
35
+ subscribeInteractive,
36
+ subscribeNonInteractive,
37
+ unsubscribe,
38
+ showUsage,
39
+ } from './subscription.js'
40
+
41
+ const cli = goke('egaki')
42
+
43
+ process.title = 'egaki'
44
+
45
+ // Print clean error output for unhandled rejections (e.g. AI SDK APICallError).
46
+ // The AI SDK errors include request bodies, response headers, and other noisy
47
+ // properties that get dumped by Node's default handler. We strip those and just
48
+ // print the message + stack trace.
49
+ process.on('uncaughtException', (err) => {
50
+ console.error(pc.red(err.message))
51
+ if (err.stack) {
52
+ const lines = err.stack.split('\n')
53
+ const stackOnly = lines.filter((l) => l.trimStart().startsWith('at '))
54
+ if (stackOnly.length > 0) {
55
+ console.error(pc.dim(stackOnly.join('\n')))
56
+ }
57
+ }
58
+ process.exit(1)
59
+ })
60
+
61
+ // ─── login command ───────────────────────────────────────────────────────────
62
+
63
+ cli
64
+ .command(
65
+ 'login',
66
+ dedent`
67
+ Configure API keys for image generation providers.
68
+ Interactive mode: shows a provider picker and secure key input.
69
+ Non-interactive mode: pass --provider and --key flags, or pipe key via stdin.
70
+ Keys are saved to ~/.config/egaki/credentials.json (mode 0600).
71
+ `,
72
+ )
73
+ .option(
74
+ '-p, --provider [name]',
75
+ z
76
+ .string()
77
+ .describe(
78
+ `Provider name for non-interactive login (${Object.keys(PROVIDERS).join(', ')})`,
79
+ ),
80
+ )
81
+ .option(
82
+ '-k, --key [key]',
83
+ z.string().describe('API key value for non-interactive login'),
84
+ )
85
+ .option('--show', 'Show which providers are configured and their status')
86
+ .option(
87
+ '--remove [provider]',
88
+ z.string().describe('Remove the stored key for a provider'),
89
+ )
90
+ .example('# Interactive login (pick provider, paste key)')
91
+ .example('egaki login')
92
+ .example('# Non-interactive login with flags')
93
+ .example('egaki login --provider google --key AIza...')
94
+ .example('# Pipe key from stdin (useful in CI/scripts)')
95
+ .example('echo "AIza..." | egaki login --provider google')
96
+ .example('# Show configured providers')
97
+ .example('egaki login --show')
98
+ .example('# Remove a stored key')
99
+ .example('egaki login --remove google')
100
+ .action(async (options) => {
101
+ if (options.show) {
102
+ showLoginStatus()
103
+ return
104
+ }
105
+
106
+ if (options.remove) {
107
+ removeLogin(options.remove)
108
+ return
109
+ }
110
+
111
+ // Non-interactive: --provider + --key or stdin
112
+ if (options.provider) {
113
+ const key = options.key || (await readKeyFromStdin())
114
+ loginNonInteractive({ provider: options.provider, key })
115
+ return
116
+ }
117
+
118
+ // Interactive mode
119
+ await loginInteractive()
120
+ })
121
+
122
+ // ─── subscribe command ───────────────────────────────────────────────────────
123
+
124
+ cli
125
+ .command(
126
+ 'subscribe',
127
+ dedent`
128
+ Subscribe to Egaki for access to all image models with a single API key.
129
+ You can also use your own provider keys (Google/OpenAI/Replicate/Fal)
130
+ via 'egaki login --provider <name> --key <key>' if you prefer BYOK.
131
+ Egaki subscription avoids managing one key per provider.
132
+ Three plans: Starter ($9/mo, 100 credits), Pro ($29/mo, 500 credits),
133
+ Unlimited ($99/mo, 2000 credits). One credit ≈ one standard image.
134
+ Interactive mode: pick a plan, enter email, get checkout URL.
135
+ Non-interactive: pass --email to get the checkout URL directly.
136
+ `,
137
+ )
138
+ .option(
139
+ '-e, --email [email]',
140
+ z.string().describe('Email for the subscription (skips interactive prompt)'),
141
+ )
142
+ .option(
143
+ '--plan [plan]',
144
+ z.string().describe('Plan ID: starter, pro, or unlimited (default: pro)'),
145
+ )
146
+ .example('# Interactive subscribe')
147
+ .example('egaki subscribe')
148
+ .example('# Non-interactive (for agents)')
149
+ .example('egaki subscribe --email user@example.com --plan pro')
150
+ .action(async (options) => {
151
+ const isTTY = process.stdout.isTTY && process.stdin.isTTY
152
+ if (!isTTY || options.email || options.plan) {
153
+ subscribeNonInteractive(options.email, options.plan)
154
+ return
155
+ }
156
+ await subscribeInteractive()
157
+ })
158
+
159
+ // ─── unsubscribe command ─────────────────────────────────────────────────────
160
+
161
+ cli
162
+ .command(
163
+ 'unsubscribe',
164
+ dedent`
165
+ Cancel your Egaki subscription. Uses the stored API key to identify
166
+ the subscription. You can resubscribe anytime with 'egaki subscribe'.
167
+ `,
168
+ )
169
+ .example('egaki unsubscribe')
170
+ .action(async () => {
171
+ await unsubscribe()
172
+ })
173
+
174
+ // ─── usage command ───────────────────────────────────────────────────────────
175
+
176
+ cli
177
+ .command(
178
+ 'usage',
179
+ dedent`
180
+ Show your current Egaki credit usage for this billing period.
181
+ Displays plan, credits used, credits remaining, and period info.
182
+ `,
183
+ )
184
+ .example('egaki usage')
185
+ .action(async () => {
186
+ await showUsage()
187
+ })
188
+
189
+ // ─── image command ───────────────────────────────────────────────────────────
190
+
191
+ cli
192
+ .command(
193
+ 'image <prompt>',
194
+ dedent`
195
+ Generate images from a text prompt using AI models.
196
+ Supports Imagen models (dedicated image generation) and Gemini
197
+ multimodal models (text+image output). The model type is auto-detected
198
+ from the model ID: imagen-* uses the image API, everything else uses
199
+ the text API with image output enabled.
200
+ `,
201
+ )
202
+ .option(
203
+ '-m, --model [model]',
204
+ z.enum(IMAGE_MODELS).default(DEFAULT_MODEL).describe('Model ID for generation'),
205
+ )
206
+ .option(
207
+ '-o, --output [path]',
208
+ z
209
+ .string()
210
+ .default('egaki-output.png')
211
+ .describe('Output file path (index suffix added when generating multiple)'),
212
+ )
213
+ .option(
214
+ '-n, --count [n]',
215
+ z.number().default(1).describe('Number of images to generate'),
216
+ )
217
+ .option(
218
+ '--aspect-ratio [ratio]',
219
+ z
220
+ .string()
221
+ .describe(
222
+ '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',
223
+ ),
224
+ )
225
+ .option(
226
+ '--seed [seed]',
227
+ z.number().describe('Seed for reproducible generation. Same seed + same prompt = same image'),
228
+ )
229
+ .option(
230
+ '--image-size [size]',
231
+ z
232
+ .enum(['1K', '2K', '4K'])
233
+ .describe(
234
+ 'Output resolution for Gemini text-model image generation. Only applies to gemini-*-image* models',
235
+ ),
236
+ )
237
+ .option(
238
+ '-i, --input [file]',
239
+ z
240
+ .array(z.string())
241
+ .describe(
242
+ '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',
243
+ ),
244
+ )
245
+ .option(
246
+ '--mask [file]',
247
+ z
248
+ .string()
249
+ .describe(
250
+ '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',
251
+ ),
252
+ )
253
+ .option(
254
+ '--allow-people',
255
+ 'Allow generating images of people (Imagen blocks people by default)',
256
+ )
257
+ .option(
258
+ '--json',
259
+ 'Output result metadata as JSON to stdout (model, usage, warnings, file paths)',
260
+ )
261
+ .option(
262
+ '--stdout',
263
+ 'Write raw image bytes to stdout instead of saving to a file. Useful for piping to other tools',
264
+ )
265
+ .example('# Generate a simple image')
266
+ .example('egaki image "a sunset over mars"')
267
+ .example('# Use a specific model with aspect ratio')
268
+ .example('egaki image "cyberpunk city at night" -m imagen-4.0-ultra-generate-001 --aspect-ratio 16:9')
269
+ .example('# Edit an existing image')
270
+ .example('egaki image "add a wizard hat to the cat" --input cat.jpg -o cat-wizard.png')
271
+ .example('# Edit an image from a URL')
272
+ .example('egaki image "make it pop art" --input https://example.com/photo.jpg')
273
+ .example('# Inpainting with a mask')
274
+ .example('egaki image "fill with flowers" --input photo.jpg --mask mask.png')
275
+ .example('# Generate with Gemini multimodal at 4K')
276
+ .example('egaki image "dreamy landscape" -m gemini-2.5-flash-image --image-size 4K')
277
+ .example('# Generate multiple images')
278
+ .example('egaki image "abstract art" -n 4 -o art.png')
279
+ .example('# Pipe to another tool')
280
+ .example('egaki image "logo design" --stdout | convert - -resize 512x512 logo.png')
281
+ .action(async (prompt, options) => {
282
+ // Inject stored API keys as env vars before calling the AI SDK
283
+ injectCredentialsToEnv()
284
+
285
+ const model = options.model
286
+ const outputPath = options.output
287
+ const config = getModelConfig(model)
288
+
289
+ if (!options.stdout) {
290
+ console.error(pc.dim(`Model: ${model}`))
291
+ console.error(pc.dim(`Prompt: ${prompt}`))
292
+ console.error(
293
+ pc.dim(
294
+ config.strategy === 'image'
295
+ ? 'Mode: Image API (generateImage)'
296
+ : 'Mode: Text+Image (generateText)',
297
+ ),
298
+ )
299
+ }
300
+
301
+ const inputImages = await readInputImages(options.input)
302
+ const maskImage = options.mask
303
+ ? await readInputSource(options.mask)
304
+ : undefined
305
+
306
+ if (config.strategy === 'image') {
307
+ await generateWithImageModel({
308
+ prompt,
309
+ model,
310
+ outputPath,
311
+ count: options.count,
312
+ aspectRatio: options.aspectRatio as `${number}:${number}` | undefined,
313
+ seed: options.seed,
314
+ inputImages,
315
+ maskImage,
316
+ allowPeople: options.allowPeople || false,
317
+ json: options.json || false,
318
+ stdout: options.stdout || false,
319
+ })
320
+ } else {
321
+ await generateWithTextModel({
322
+ prompt,
323
+ model,
324
+ outputPath,
325
+ inputImages,
326
+ imageSize: options.imageSize,
327
+ aspectRatio: options.aspectRatio,
328
+ json: options.json || false,
329
+ stdout: options.stdout || false,
330
+ })
331
+ }
332
+ })
333
+
334
+ // ─── models command ──────────────────────────────────────────────────────────
335
+
336
+ cli
337
+ .command(
338
+ 'models',
339
+ dedent`
340
+ List all supported image generation models with pricing, features,
341
+ and provider info. Output is YAML for easy reading and piping.
342
+ `,
343
+ )
344
+ .option(
345
+ '-p, --provider [provider]',
346
+ z.string().describe('Filter models by provider name (e.g. google, openai, replicate, fal)'),
347
+ )
348
+ .option('--json', 'Output as JSON instead of YAML')
349
+ .action(async (options) => {
350
+ const { CATALOG } = await import('./model-catalog.js')
351
+ const yaml = await import('js-yaml')
352
+
353
+ let models = CATALOG
354
+ if (options.provider) {
355
+ models = models.filter((m) => m.provider === options.provider)
356
+ if (models.length === 0) {
357
+ console.error(pc.red(`No models found for provider: ${options.provider}`))
358
+ process.exit(1)
359
+ }
360
+ }
361
+
362
+ const output = models.map((m) => ({
363
+ id: m.id,
364
+ name: m.name,
365
+ ...(m.description ? { description: m.description } : {}),
366
+ provider: m.provider,
367
+ strategy: m.strategy,
368
+ released: m.released,
369
+ cost:
370
+ m.cost.type === 'per-image'
371
+ ? `$${m.cost.perImage}/image`
372
+ : `$${m.cost.inputPerM}/M input, $${m.cost.outputPerM}/M output`,
373
+ features: {
374
+ editing: m.features.editing,
375
+ inpainting: m.features.inpainting,
376
+ seed: m.features.seed,
377
+ multipleImages: m.features.multipleImages,
378
+ aspectRatios: m.features.aspectRatios.join(', ') || 'none',
379
+ ...(m.features.sizes ? { sizes: m.features.sizes.join(', ') } : {}),
380
+ },
381
+ }))
382
+
383
+ if (options.json) {
384
+ console.log(JSON.stringify(output, null, 2))
385
+ } else {
386
+ console.log(yaml.dump(output, { lineWidth: 120, noRefs: true }))
387
+ }
388
+ })
389
+
390
+ cli.help()
391
+ cli.version(pkg.version)
392
+ cli.parse()
393
+
394
+ function isUrl(input: string): boolean {
395
+ return /^https?:\/\//i.test(input)
396
+ }
397
+
398
+ async function readInputSource(input: string): Promise<Uint8Array> {
399
+ if (isUrl(input)) {
400
+ console.error(pc.dim(`Fetching ${input}...`))
401
+ const res = await fetch(input)
402
+ if (!res.ok) {
403
+ console.error(pc.red(`Failed to fetch ${input}: ${res.status} ${res.statusText}`))
404
+ process.exit(1)
405
+ }
406
+ return new Uint8Array(await res.arrayBuffer())
407
+ }
408
+ const resolved = path.resolve(input)
409
+ if (!fs.existsSync(resolved)) {
410
+ console.error(pc.red(`File not found: ${resolved}`))
411
+ process.exit(1)
412
+ }
413
+ return new Uint8Array(fs.readFileSync(resolved))
414
+ }
415
+
416
+ async function readInputImages(
417
+ inputs: string[] | undefined,
418
+ ): Promise<Uint8Array[]> {
419
+ if (!inputs || inputs.length === 0) {
420
+ return []
421
+ }
422
+ return Promise.all(inputs.map((f) => readInputSource(f)))
423
+ }
424
+
425
+ // Generate using the dedicated generateImage API (Imagen models)
426
+ async function generateWithImageModel({
427
+ prompt,
428
+ model,
429
+ outputPath,
430
+ count,
431
+ aspectRatio,
432
+ seed,
433
+ inputImages,
434
+ maskImage,
435
+ allowPeople,
436
+ json,
437
+ stdout,
438
+ }: {
439
+ prompt: string
440
+ model: string
441
+ outputPath: string
442
+ count: number
443
+ aspectRatio?: `${number}:${number}`
444
+ seed?: number
445
+ inputImages: Uint8Array[]
446
+ maskImage?: Uint8Array
447
+ allowPeople: boolean
448
+ json: boolean
449
+ stdout: boolean
450
+ }) {
451
+ // Build the prompt: plain string or multimodal with reference images
452
+ const imagePrompt = inputImages.length > 0
453
+ ? { text: prompt, images: inputImages, ...(maskImage ? { mask: maskImage } : {}) }
454
+ : prompt
455
+
456
+ const imageModel = await createImageModel(model)
457
+
458
+ if (!stdout) {
459
+ console.error(pc.cyan('Generating...'))
460
+ }
461
+
462
+ const result = await aiGenerateImage({
463
+ model: imageModel,
464
+ prompt: imagePrompt,
465
+ n: count,
466
+ ...(aspectRatio ? { aspectRatio } : {}),
467
+ ...(seed !== undefined ? { seed } : {}),
468
+ providerOptions: {
469
+ google: {
470
+ ...(allowPeople ? { personGeneration: 'allow_all' } : {}),
471
+ ...(aspectRatio ? { aspectRatio } : {}),
472
+ },
473
+ },
474
+ })
475
+
476
+ if (stdout) {
477
+ // Write first image to stdout for piping
478
+ const image = result.images[0]
479
+ if (image) {
480
+ process.stdout.write(Buffer.from(image.uint8Array))
481
+ }
482
+ return
483
+ }
484
+
485
+ const savedFiles: string[] = []
486
+ for (let i = 0; i < result.images.length; i++) {
487
+ const image = result.images[i]!
488
+ const ext = extensionFromMediaType(image.mediaType)
489
+ const filePath =
490
+ result.images.length === 1
491
+ ? ensureExtension(outputPath, ext)
492
+ : insertIndex(outputPath, i, ext)
493
+
494
+ fs.writeFileSync(filePath, image.uint8Array)
495
+ console.error(pc.green(`Saved: ${filePath}`))
496
+ savedFiles.push(filePath)
497
+ }
498
+
499
+ const config = getModelConfig(model)
500
+ const cost = calculateCost(config.cost, result.usage, result.images.length)
501
+ if (cost != null) {
502
+ console.error(pc.dim(`Cost: ${formatCost(cost)}`))
503
+ }
504
+
505
+ if (json) {
506
+ const output = {
507
+ model,
508
+ files: savedFiles,
509
+ count: result.images.length,
510
+ cost,
511
+ usage: result.usage,
512
+ warnings: result.warnings,
513
+ }
514
+ console.log(JSON.stringify(output, null, 2))
515
+ }
516
+ }
517
+
518
+ // Generate using generateText with responseModalities (Gemini multimodal models)
519
+ async function generateWithTextModel({
520
+ prompt,
521
+ model,
522
+ outputPath,
523
+ inputImages,
524
+ imageSize,
525
+ aspectRatio,
526
+ json,
527
+ stdout,
528
+ }: {
529
+ prompt: string
530
+ model: string
531
+ outputPath: string
532
+ inputImages: Uint8Array[]
533
+ imageSize?: '1K' | '2K' | '4K'
534
+ aspectRatio?: string
535
+ json: boolean
536
+ stdout: boolean
537
+ }) {
538
+ const textModel = await createTextModel(model)
539
+
540
+ if (!stdout) {
541
+ console.error(pc.cyan('Generating...'))
542
+ }
543
+
544
+ // Build messages: if we have input images, create a multimodal prompt
545
+ const messages = inputImages.length > 0
546
+ ? [
547
+ {
548
+ role: 'user' as const,
549
+ content: [
550
+ { type: 'text' as const, text: prompt },
551
+ ...inputImages.map((img) => ({
552
+ type: 'image' as const,
553
+ image: img,
554
+ })),
555
+ ],
556
+ },
557
+ ]
558
+ : undefined
559
+
560
+ const result = await generateText({
561
+ model: textModel,
562
+ ...(messages ? { messages } : { prompt }),
563
+ providerOptions: {
564
+ google: {
565
+ responseModalities: ['TEXT', 'IMAGE'],
566
+ ...(imageSize || aspectRatio
567
+ ? {
568
+ imageConfig: {
569
+ ...(imageSize ? { imageSize } : {}),
570
+ ...(aspectRatio ? { aspectRatio } : {}),
571
+ },
572
+ }
573
+ : {}),
574
+ },
575
+ },
576
+ })
577
+
578
+ const imageFiles = result.files.filter((f) => {
579
+ return f.mediaType.startsWith('image/')
580
+ })
581
+
582
+ if (imageFiles.length === 0) {
583
+ console.error(pc.red('No images generated.'))
584
+ process.exit(1)
585
+ }
586
+
587
+ if (stdout) {
588
+ const file = imageFiles[0]
589
+ if (file) {
590
+ process.stdout.write(Buffer.from(file.uint8Array))
591
+ }
592
+ return
593
+ }
594
+
595
+ const savedFiles: string[] = []
596
+ for (let i = 0; i < imageFiles.length; i++) {
597
+ const file = imageFiles[i]!
598
+ const ext = extensionFromMediaType(file.mediaType)
599
+ const filePath =
600
+ imageFiles.length === 1
601
+ ? ensureExtension(outputPath, ext)
602
+ : insertIndex(outputPath, i, ext)
603
+
604
+ fs.writeFileSync(filePath, file.uint8Array)
605
+ console.error(pc.green(`Saved: ${filePath}`))
606
+ savedFiles.push(filePath)
607
+ }
608
+
609
+ const config = getModelConfig(model)
610
+ const cost = calculateCost(config.cost, result.usage, imageFiles.length)
611
+ if (cost != null) {
612
+ console.error(pc.dim(`Cost: ${formatCost(cost)}`))
613
+ }
614
+
615
+ if (result.text && !json) {
616
+ console.error(pc.dim(result.text))
617
+ }
618
+
619
+ if (json) {
620
+ const output = {
621
+ model,
622
+ files: savedFiles,
623
+ count: imageFiles.length,
624
+ text: result.text || null,
625
+ cost,
626
+ usage: result.usage,
627
+ }
628
+ console.log(JSON.stringify(output, null, 2))
629
+ }
630
+ }
631
+
632
+ // ─── cost helpers ────────────────────────────────────────────────────────────
633
+
634
+ function calculateCost(
635
+ cost: ModelCost,
636
+ usage: { inputTokens?: number; outputTokens?: number; imagesGenerated?: number },
637
+ imageCount: number,
638
+ ): number | null {
639
+ if (cost.type === 'per-image') {
640
+ return cost.perImage * imageCount
641
+ }
642
+ if (cost.type === 'per-token' && usage.inputTokens != null && usage.outputTokens != null) {
643
+ return (
644
+ (usage.inputTokens * cost.inputPerM + usage.outputTokens * cost.outputPerM) / 1_000_000
645
+ )
646
+ }
647
+ return null
648
+ }
649
+
650
+ function formatCost(dollars: number): string {
651
+ if (dollars < 0.01) {
652
+ return `$${dollars.toFixed(4)}`
653
+ }
654
+ return `$${dollars.toFixed(2)}`
655
+ }
656
+
657
+ function extensionFromMediaType(mediaType: string): string {
658
+ const map: Record<string, string> = {
659
+ 'image/png': '.png',
660
+ 'image/jpeg': '.jpg',
661
+ 'image/webp': '.webp',
662
+ 'image/gif': '.gif',
663
+ }
664
+ return map[mediaType] || '.png'
665
+ }
666
+
667
+ function ensureExtension(filePath: string, ext: string): string {
668
+ const parsed = path.parse(filePath)
669
+ if (parsed.ext) {
670
+ return filePath
671
+ }
672
+ return filePath + ext
673
+ }
674
+
675
+ function insertIndex(filePath: string, index: number, ext: string): string {
676
+ const parsed = path.parse(filePath)
677
+ const finalExt = parsed.ext || ext
678
+ return path.join(parsed.dir, `${parsed.name}-${index}${finalExt}`)
679
+ }