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/dist/cli.js ADDED
@@ -0,0 +1,471 @@
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 { IMAGE_MODELS, DEFAULT_MODEL, getModelConfig, createImageModel, createTextModel, } from './models.js';
20
+ import { loginInteractive, loginNonInteractive, showLoginStatus, removeLogin, readKeyFromStdin, } from './login.js';
21
+ import { subscribeInteractive, subscribeNonInteractive, unsubscribe, showUsage, } from './subscription.js';
22
+ const cli = goke('egaki');
23
+ process.title = 'egaki';
24
+ // Print clean error output for unhandled rejections (e.g. AI SDK APICallError).
25
+ // The AI SDK errors include request bodies, response headers, and other noisy
26
+ // properties that get dumped by Node's default handler. We strip those and just
27
+ // print the message + stack trace.
28
+ process.on('uncaughtException', (err) => {
29
+ console.error(pc.red(err.message));
30
+ if (err.stack) {
31
+ const lines = err.stack.split('\n');
32
+ const stackOnly = lines.filter((l) => l.trimStart().startsWith('at '));
33
+ if (stackOnly.length > 0) {
34
+ console.error(pc.dim(stackOnly.join('\n')));
35
+ }
36
+ }
37
+ process.exit(1);
38
+ });
39
+ // ─── login command ───────────────────────────────────────────────────────────
40
+ cli
41
+ .command('login', dedent `
42
+ Configure API keys for image generation providers.
43
+ Interactive mode: shows a provider picker and secure key input.
44
+ Non-interactive mode: pass --provider and --key flags, or pipe key via stdin.
45
+ Keys are saved to ~/.config/egaki/credentials.json (mode 0600).
46
+ `)
47
+ .option('-p, --provider [name]', z
48
+ .string()
49
+ .describe(`Provider name for non-interactive login (${Object.keys(PROVIDERS).join(', ')})`))
50
+ .option('-k, --key [key]', z.string().describe('API key value for non-interactive login'))
51
+ .option('--show', 'Show which providers are configured and their status')
52
+ .option('--remove [provider]', z.string().describe('Remove the stored key for a provider'))
53
+ .example('# Interactive login (pick provider, paste key)')
54
+ .example('egaki login')
55
+ .example('# Non-interactive login with flags')
56
+ .example('egaki login --provider google --key AIza...')
57
+ .example('# Pipe key from stdin (useful in CI/scripts)')
58
+ .example('echo "AIza..." | egaki login --provider google')
59
+ .example('# Show configured providers')
60
+ .example('egaki login --show')
61
+ .example('# Remove a stored key')
62
+ .example('egaki login --remove google')
63
+ .action(async (options) => {
64
+ if (options.show) {
65
+ showLoginStatus();
66
+ return;
67
+ }
68
+ if (options.remove) {
69
+ removeLogin(options.remove);
70
+ return;
71
+ }
72
+ // Non-interactive: --provider + --key or stdin
73
+ if (options.provider) {
74
+ const key = options.key || (await readKeyFromStdin());
75
+ loginNonInteractive({ provider: options.provider, key });
76
+ return;
77
+ }
78
+ // Interactive mode
79
+ await loginInteractive();
80
+ });
81
+ // ─── subscribe command ───────────────────────────────────────────────────────
82
+ cli
83
+ .command('subscribe', dedent `
84
+ Subscribe to Egaki for access to all image models with a single API key.
85
+ You can also use your own provider keys (Google/OpenAI/Replicate/Fal)
86
+ via 'egaki login --provider <name> --key <key>' if you prefer BYOK.
87
+ Egaki subscription avoids managing one key per provider.
88
+ Three plans: Starter ($9/mo, 100 credits), Pro ($29/mo, 500 credits),
89
+ Unlimited ($99/mo, 2000 credits). One credit ≈ one standard image.
90
+ Interactive mode: pick a plan, enter email, get checkout URL.
91
+ Non-interactive: pass --email to get the checkout URL directly.
92
+ `)
93
+ .option('-e, --email [email]', z.string().describe('Email for the subscription (skips interactive prompt)'))
94
+ .option('--plan [plan]', z.string().describe('Plan ID: starter, pro, or unlimited (default: pro)'))
95
+ .example('# Interactive subscribe')
96
+ .example('egaki subscribe')
97
+ .example('# Non-interactive (for agents)')
98
+ .example('egaki subscribe --email user@example.com --plan pro')
99
+ .action(async (options) => {
100
+ const isTTY = process.stdout.isTTY && process.stdin.isTTY;
101
+ if (!isTTY || options.email || options.plan) {
102
+ subscribeNonInteractive(options.email, options.plan);
103
+ return;
104
+ }
105
+ await subscribeInteractive();
106
+ });
107
+ // ─── unsubscribe command ─────────────────────────────────────────────────────
108
+ cli
109
+ .command('unsubscribe', dedent `
110
+ Cancel your Egaki subscription. Uses the stored API key to identify
111
+ the subscription. You can resubscribe anytime with 'egaki subscribe'.
112
+ `)
113
+ .example('egaki unsubscribe')
114
+ .action(async () => {
115
+ await unsubscribe();
116
+ });
117
+ // ─── usage command ───────────────────────────────────────────────────────────
118
+ cli
119
+ .command('usage', dedent `
120
+ Show your current Egaki credit usage for this billing period.
121
+ Displays plan, credits used, credits remaining, and period info.
122
+ `)
123
+ .example('egaki usage')
124
+ .action(async () => {
125
+ await showUsage();
126
+ });
127
+ // ─── image command ───────────────────────────────────────────────────────────
128
+ cli
129
+ .command('image <prompt>', dedent `
130
+ Generate images from a text prompt using AI models.
131
+ Supports Imagen models (dedicated image generation) and Gemini
132
+ multimodal models (text+image output). The model type is auto-detected
133
+ from the model ID: imagen-* uses the image API, everything else uses
134
+ the text API with image output enabled.
135
+ `)
136
+ .option('-m, --model [model]', z.enum(IMAGE_MODELS).default(DEFAULT_MODEL).describe('Model ID for generation'))
137
+ .option('-o, --output [path]', z
138
+ .string()
139
+ .default('egaki-output.png')
140
+ .describe('Output file path (index suffix added when generating multiple)'))
141
+ .option('-n, --count [n]', z.number().default(1).describe('Number of images to generate'))
142
+ .option('--aspect-ratio [ratio]', z
143
+ .string()
144
+ .describe('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'))
145
+ .option('--seed [seed]', z.number().describe('Seed for reproducible generation. Same seed + same prompt = same image'))
146
+ .option('--image-size [size]', z
147
+ .enum(['1K', '2K', '4K'])
148
+ .describe('Output resolution for Gemini text-model image generation. Only applies to gemini-*-image* models'))
149
+ .option('-i, --input [file]', z
150
+ .array(z.string())
151
+ .describe('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'))
152
+ .option('--mask [file]', z
153
+ .string()
154
+ .describe('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'))
155
+ .option('--allow-people', 'Allow generating images of people (Imagen blocks people by default)')
156
+ .option('--json', 'Output result metadata as JSON to stdout (model, usage, warnings, file paths)')
157
+ .option('--stdout', 'Write raw image bytes to stdout instead of saving to a file. Useful for piping to other tools')
158
+ .example('# Generate a simple image')
159
+ .example('egaki image "a sunset over mars"')
160
+ .example('# Use a specific model with aspect ratio')
161
+ .example('egaki image "cyberpunk city at night" -m imagen-4.0-ultra-generate-001 --aspect-ratio 16:9')
162
+ .example('# Edit an existing image')
163
+ .example('egaki image "add a wizard hat to the cat" --input cat.jpg -o cat-wizard.png')
164
+ .example('# Edit an image from a URL')
165
+ .example('egaki image "make it pop art" --input https://example.com/photo.jpg')
166
+ .example('# Inpainting with a mask')
167
+ .example('egaki image "fill with flowers" --input photo.jpg --mask mask.png')
168
+ .example('# Generate with Gemini multimodal at 4K')
169
+ .example('egaki image "dreamy landscape" -m gemini-2.5-flash-image --image-size 4K')
170
+ .example('# Generate multiple images')
171
+ .example('egaki image "abstract art" -n 4 -o art.png')
172
+ .example('# Pipe to another tool')
173
+ .example('egaki image "logo design" --stdout | convert - -resize 512x512 logo.png')
174
+ .action(async (prompt, options) => {
175
+ // Inject stored API keys as env vars before calling the AI SDK
176
+ injectCredentialsToEnv();
177
+ const model = options.model;
178
+ const outputPath = options.output;
179
+ const config = getModelConfig(model);
180
+ if (!options.stdout) {
181
+ console.error(pc.dim(`Model: ${model}`));
182
+ console.error(pc.dim(`Prompt: ${prompt}`));
183
+ console.error(pc.dim(config.strategy === 'image'
184
+ ? 'Mode: Image API (generateImage)'
185
+ : 'Mode: Text+Image (generateText)'));
186
+ }
187
+ const inputImages = await readInputImages(options.input);
188
+ const maskImage = options.mask
189
+ ? await readInputSource(options.mask)
190
+ : undefined;
191
+ if (config.strategy === 'image') {
192
+ await generateWithImageModel({
193
+ prompt,
194
+ model,
195
+ outputPath,
196
+ count: options.count,
197
+ aspectRatio: options.aspectRatio,
198
+ seed: options.seed,
199
+ inputImages,
200
+ maskImage,
201
+ allowPeople: options.allowPeople || false,
202
+ json: options.json || false,
203
+ stdout: options.stdout || false,
204
+ });
205
+ }
206
+ else {
207
+ await generateWithTextModel({
208
+ prompt,
209
+ model,
210
+ outputPath,
211
+ inputImages,
212
+ imageSize: options.imageSize,
213
+ aspectRatio: options.aspectRatio,
214
+ json: options.json || false,
215
+ stdout: options.stdout || false,
216
+ });
217
+ }
218
+ });
219
+ // ─── models command ──────────────────────────────────────────────────────────
220
+ cli
221
+ .command('models', dedent `
222
+ List all supported image generation models with pricing, features,
223
+ and provider info. Output is YAML for easy reading and piping.
224
+ `)
225
+ .option('-p, --provider [provider]', z.string().describe('Filter models by provider name (e.g. google, openai, replicate, fal)'))
226
+ .option('--json', 'Output as JSON instead of YAML')
227
+ .action(async (options) => {
228
+ const { CATALOG } = await import('./model-catalog.js');
229
+ const yaml = await import('js-yaml');
230
+ let models = CATALOG;
231
+ if (options.provider) {
232
+ models = models.filter((m) => m.provider === options.provider);
233
+ if (models.length === 0) {
234
+ console.error(pc.red(`No models found for provider: ${options.provider}`));
235
+ process.exit(1);
236
+ }
237
+ }
238
+ const output = models.map((m) => ({
239
+ id: m.id,
240
+ name: m.name,
241
+ ...(m.description ? { description: m.description } : {}),
242
+ provider: m.provider,
243
+ strategy: m.strategy,
244
+ released: m.released,
245
+ cost: m.cost.type === 'per-image'
246
+ ? `$${m.cost.perImage}/image`
247
+ : `$${m.cost.inputPerM}/M input, $${m.cost.outputPerM}/M output`,
248
+ features: {
249
+ editing: m.features.editing,
250
+ inpainting: m.features.inpainting,
251
+ seed: m.features.seed,
252
+ multipleImages: m.features.multipleImages,
253
+ aspectRatios: m.features.aspectRatios.join(', ') || 'none',
254
+ ...(m.features.sizes ? { sizes: m.features.sizes.join(', ') } : {}),
255
+ },
256
+ }));
257
+ if (options.json) {
258
+ console.log(JSON.stringify(output, null, 2));
259
+ }
260
+ else {
261
+ console.log(yaml.dump(output, { lineWidth: 120, noRefs: true }));
262
+ }
263
+ });
264
+ cli.help();
265
+ cli.version(pkg.version);
266
+ cli.parse();
267
+ function isUrl(input) {
268
+ return /^https?:\/\//i.test(input);
269
+ }
270
+ async function readInputSource(input) {
271
+ if (isUrl(input)) {
272
+ console.error(pc.dim(`Fetching ${input}...`));
273
+ const res = await fetch(input);
274
+ if (!res.ok) {
275
+ console.error(pc.red(`Failed to fetch ${input}: ${res.status} ${res.statusText}`));
276
+ process.exit(1);
277
+ }
278
+ return new Uint8Array(await res.arrayBuffer());
279
+ }
280
+ const resolved = path.resolve(input);
281
+ if (!fs.existsSync(resolved)) {
282
+ console.error(pc.red(`File not found: ${resolved}`));
283
+ process.exit(1);
284
+ }
285
+ return new Uint8Array(fs.readFileSync(resolved));
286
+ }
287
+ async function readInputImages(inputs) {
288
+ if (!inputs || inputs.length === 0) {
289
+ return [];
290
+ }
291
+ return Promise.all(inputs.map((f) => readInputSource(f)));
292
+ }
293
+ // Generate using the dedicated generateImage API (Imagen models)
294
+ async function generateWithImageModel({ prompt, model, outputPath, count, aspectRatio, seed, inputImages, maskImage, allowPeople, json, stdout, }) {
295
+ // Build the prompt: plain string or multimodal with reference images
296
+ const imagePrompt = inputImages.length > 0
297
+ ? { text: prompt, images: inputImages, ...(maskImage ? { mask: maskImage } : {}) }
298
+ : prompt;
299
+ const imageModel = await createImageModel(model);
300
+ if (!stdout) {
301
+ console.error(pc.cyan('Generating...'));
302
+ }
303
+ const result = await aiGenerateImage({
304
+ model: imageModel,
305
+ prompt: imagePrompt,
306
+ n: count,
307
+ ...(aspectRatio ? { aspectRatio } : {}),
308
+ ...(seed !== undefined ? { seed } : {}),
309
+ providerOptions: {
310
+ google: {
311
+ ...(allowPeople ? { personGeneration: 'allow_all' } : {}),
312
+ ...(aspectRatio ? { aspectRatio } : {}),
313
+ },
314
+ },
315
+ });
316
+ if (stdout) {
317
+ // Write first image to stdout for piping
318
+ const image = result.images[0];
319
+ if (image) {
320
+ process.stdout.write(Buffer.from(image.uint8Array));
321
+ }
322
+ return;
323
+ }
324
+ const savedFiles = [];
325
+ for (let i = 0; i < result.images.length; i++) {
326
+ const image = result.images[i];
327
+ const ext = extensionFromMediaType(image.mediaType);
328
+ const filePath = result.images.length === 1
329
+ ? ensureExtension(outputPath, ext)
330
+ : insertIndex(outputPath, i, ext);
331
+ fs.writeFileSync(filePath, image.uint8Array);
332
+ console.error(pc.green(`Saved: ${filePath}`));
333
+ savedFiles.push(filePath);
334
+ }
335
+ const config = getModelConfig(model);
336
+ const cost = calculateCost(config.cost, result.usage, result.images.length);
337
+ if (cost != null) {
338
+ console.error(pc.dim(`Cost: ${formatCost(cost)}`));
339
+ }
340
+ if (json) {
341
+ const output = {
342
+ model,
343
+ files: savedFiles,
344
+ count: result.images.length,
345
+ cost,
346
+ usage: result.usage,
347
+ warnings: result.warnings,
348
+ };
349
+ console.log(JSON.stringify(output, null, 2));
350
+ }
351
+ }
352
+ // Generate using generateText with responseModalities (Gemini multimodal models)
353
+ async function generateWithTextModel({ prompt, model, outputPath, inputImages, imageSize, aspectRatio, json, stdout, }) {
354
+ const textModel = await createTextModel(model);
355
+ if (!stdout) {
356
+ console.error(pc.cyan('Generating...'));
357
+ }
358
+ // Build messages: if we have input images, create a multimodal prompt
359
+ const messages = inputImages.length > 0
360
+ ? [
361
+ {
362
+ role: 'user',
363
+ content: [
364
+ { type: 'text', text: prompt },
365
+ ...inputImages.map((img) => ({
366
+ type: 'image',
367
+ image: img,
368
+ })),
369
+ ],
370
+ },
371
+ ]
372
+ : undefined;
373
+ const result = await generateText({
374
+ model: textModel,
375
+ ...(messages ? { messages } : { prompt }),
376
+ providerOptions: {
377
+ google: {
378
+ responseModalities: ['TEXT', 'IMAGE'],
379
+ ...(imageSize || aspectRatio
380
+ ? {
381
+ imageConfig: {
382
+ ...(imageSize ? { imageSize } : {}),
383
+ ...(aspectRatio ? { aspectRatio } : {}),
384
+ },
385
+ }
386
+ : {}),
387
+ },
388
+ },
389
+ });
390
+ const imageFiles = result.files.filter((f) => {
391
+ return f.mediaType.startsWith('image/');
392
+ });
393
+ if (imageFiles.length === 0) {
394
+ console.error(pc.red('No images generated.'));
395
+ process.exit(1);
396
+ }
397
+ if (stdout) {
398
+ const file = imageFiles[0];
399
+ if (file) {
400
+ process.stdout.write(Buffer.from(file.uint8Array));
401
+ }
402
+ return;
403
+ }
404
+ const savedFiles = [];
405
+ for (let i = 0; i < imageFiles.length; i++) {
406
+ const file = imageFiles[i];
407
+ const ext = extensionFromMediaType(file.mediaType);
408
+ const filePath = imageFiles.length === 1
409
+ ? ensureExtension(outputPath, ext)
410
+ : insertIndex(outputPath, i, ext);
411
+ fs.writeFileSync(filePath, file.uint8Array);
412
+ console.error(pc.green(`Saved: ${filePath}`));
413
+ savedFiles.push(filePath);
414
+ }
415
+ const config = getModelConfig(model);
416
+ const cost = calculateCost(config.cost, result.usage, imageFiles.length);
417
+ if (cost != null) {
418
+ console.error(pc.dim(`Cost: ${formatCost(cost)}`));
419
+ }
420
+ if (result.text && !json) {
421
+ console.error(pc.dim(result.text));
422
+ }
423
+ if (json) {
424
+ const output = {
425
+ model,
426
+ files: savedFiles,
427
+ count: imageFiles.length,
428
+ text: result.text || null,
429
+ cost,
430
+ usage: result.usage,
431
+ };
432
+ console.log(JSON.stringify(output, null, 2));
433
+ }
434
+ }
435
+ // ─── cost helpers ────────────────────────────────────────────────────────────
436
+ function calculateCost(cost, usage, imageCount) {
437
+ if (cost.type === 'per-image') {
438
+ return cost.perImage * imageCount;
439
+ }
440
+ if (cost.type === 'per-token' && usage.inputTokens != null && usage.outputTokens != null) {
441
+ return ((usage.inputTokens * cost.inputPerM + usage.outputTokens * cost.outputPerM) / 1_000_000);
442
+ }
443
+ return null;
444
+ }
445
+ function formatCost(dollars) {
446
+ if (dollars < 0.01) {
447
+ return `$${dollars.toFixed(4)}`;
448
+ }
449
+ return `$${dollars.toFixed(2)}`;
450
+ }
451
+ function extensionFromMediaType(mediaType) {
452
+ const map = {
453
+ 'image/png': '.png',
454
+ 'image/jpeg': '.jpg',
455
+ 'image/webp': '.webp',
456
+ 'image/gif': '.gif',
457
+ };
458
+ return map[mediaType] || '.png';
459
+ }
460
+ function ensureExtension(filePath, ext) {
461
+ const parsed = path.parse(filePath);
462
+ if (parsed.ext) {
463
+ return filePath;
464
+ }
465
+ return filePath + ext;
466
+ }
467
+ function insertIndex(filePath, index, ext) {
468
+ const parsed = path.parse(filePath);
469
+ const finalExt = parsed.ext || ext;
470
+ return path.join(parsed.dir, `${parsed.name}-${index}${finalExt}`);
471
+ }
@@ -0,0 +1,18 @@
1
+ export declare const PROVIDERS: Record<string, {
2
+ envVar: string;
3
+ label: string;
4
+ hint: string;
5
+ }>;
6
+ export declare const EGAKI_GATEWAY_URL = "https://egaki.org/v1/ai";
7
+ export type Credentials = Record<string, string>;
8
+ export declare function readCredentials(): Credentials;
9
+ export declare function writeCredentials(creds: Credentials): void;
10
+ export declare function saveProviderKey(provider: string, key: string): void;
11
+ export declare function removeProviderKey(provider: string): void;
12
+ export declare function getProviderKey(provider: string): string | undefined;
13
+ export declare function injectCredentialsToEnv(): void;
14
+ export declare function getKeyStatus(provider: string): {
15
+ available: boolean;
16
+ source: 'env' | 'stored' | 'none';
17
+ };
18
+ //# sourceMappingURL=credentials.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.d.ts","sourceRoot":"","sources":["../src/credentials.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,SAAS,EAAE,MAAM,CAC5B,MAAM,EACN;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CA2BhD,CAAA;AAED,eAAO,MAAM,iBAAiB,4BAA4B,CAAA;AAa1D,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAEhD,wBAAgB,eAAe,IAAI,WAAW,CAO7C;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI,CAOzD;AAED,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAInE;AAED,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAIxD;AAED,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAGnE;AAKD,wBAAgB,sBAAsB,IAAI,IAAI,CAW7C;AAID,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG;IAC9C,SAAS,EAAE,OAAO,CAAA;IAClB,MAAM,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAA;CAClC,CAaA"}
@@ -0,0 +1,107 @@
1
+ // Credential storage for egaki.
2
+ // Reads and writes API keys from ~/.config/egaki/credentials.json.
3
+ // Keys are stored per-provider and injected as env vars at runtime.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import os from 'node:os';
7
+ // Maps provider names to their expected env var names.
8
+ // When a key is stored, we set the corresponding env var before
9
+ // calling the AI SDK so the provider picks it up automatically.
10
+ export const PROVIDERS = {
11
+ egaki: {
12
+ envVar: 'EGAKI_API_KEY',
13
+ label: 'Egaki (all models, one subscription)',
14
+ hint: 'Subscribe at https://egaki.org/buy or run: egaki subscribe',
15
+ },
16
+ google: {
17
+ envVar: 'GOOGLE_GENERATIVE_AI_API_KEY',
18
+ label: 'Google AI (Gemini, Imagen)',
19
+ hint: 'Get your key at https://aistudio.google.com/apikey',
20
+ },
21
+ openai: {
22
+ envVar: 'OPENAI_API_KEY',
23
+ label: 'OpenAI (DALL-E)',
24
+ hint: 'Get your key at https://platform.openai.com/api-keys',
25
+ },
26
+ replicate: {
27
+ envVar: 'REPLICATE_API_TOKEN',
28
+ label: 'Replicate (Flux, SDXL)',
29
+ hint: 'Get your token at https://replicate.com/account/api-tokens',
30
+ },
31
+ fal: {
32
+ envVar: 'FAL_KEY',
33
+ label: 'fal.ai (Flux, SDXL, Recraft)',
34
+ hint: 'Get your key at https://fal.ai/dashboard/keys',
35
+ },
36
+ };
37
+ export const EGAKI_GATEWAY_URL = 'https://egaki.org/v1/ai';
38
+ function getConfigDir() {
39
+ // XDG_CONFIG_HOME or ~/.config/egaki
40
+ const xdg = process.env['XDG_CONFIG_HOME'];
41
+ const base = xdg || path.join(os.homedir(), '.config');
42
+ return path.join(base, 'egaki');
43
+ }
44
+ function getCredentialsPath() {
45
+ return path.join(getConfigDir(), 'credentials.json');
46
+ }
47
+ export function readCredentials() {
48
+ const filePath = getCredentialsPath();
49
+ if (!fs.existsSync(filePath)) {
50
+ return {};
51
+ }
52
+ const raw = fs.readFileSync(filePath, 'utf-8');
53
+ return JSON.parse(raw);
54
+ }
55
+ export function writeCredentials(creds) {
56
+ const dir = getConfigDir();
57
+ fs.mkdirSync(dir, { recursive: true });
58
+ const filePath = getCredentialsPath();
59
+ fs.writeFileSync(filePath, JSON.stringify(creds, null, 2) + '\n', {
60
+ mode: 0o600,
61
+ });
62
+ }
63
+ export function saveProviderKey(provider, key) {
64
+ const creds = readCredentials();
65
+ creds[provider] = key;
66
+ writeCredentials(creds);
67
+ }
68
+ export function removeProviderKey(provider) {
69
+ const creds = readCredentials();
70
+ delete creds[provider];
71
+ writeCredentials(creds);
72
+ }
73
+ export function getProviderKey(provider) {
74
+ const creds = readCredentials();
75
+ return creds[provider];
76
+ }
77
+ // Inject all stored credentials as env vars so the AI SDK
78
+ // providers pick them up automatically. Env vars already set
79
+ // by the user take precedence (we don't overwrite them).
80
+ export function injectCredentialsToEnv() {
81
+ const creds = readCredentials();
82
+ for (const [provider, key] of Object.entries(creds)) {
83
+ const info = PROVIDERS[provider];
84
+ if (!info) {
85
+ continue;
86
+ }
87
+ if (!process.env[info.envVar]) {
88
+ process.env[info.envVar] = key;
89
+ }
90
+ }
91
+ }
92
+ // Check if a provider has a key available (from env or stored credentials).
93
+ // Returns the source of the key for display purposes.
94
+ export function getKeyStatus(provider) {
95
+ const info = PROVIDERS[provider];
96
+ if (!info) {
97
+ return { available: false, source: 'none' };
98
+ }
99
+ if (process.env[info.envVar]) {
100
+ return { available: true, source: 'env' };
101
+ }
102
+ const stored = getProviderKey(provider);
103
+ if (stored) {
104
+ return { available: true, source: 'stored' };
105
+ }
106
+ return { available: false, source: 'none' };
107
+ }
@@ -0,0 +1,9 @@
1
+ export declare function loginInteractive(): Promise<void>;
2
+ export declare function loginNonInteractive({ provider, key, }: {
3
+ provider: string;
4
+ key: string;
5
+ }): void;
6
+ export declare function showLoginStatus(): void;
7
+ export declare function removeLogin(provider: string): void;
8
+ export declare function readKeyFromStdin(): Promise<string>;
9
+ //# sourceMappingURL=login.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"login.d.ts","sourceRoot":"","sources":["../src/login.ts"],"names":[],"mappings":"AAsBA,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC,CAqEtD;AAED,wBAAgB,mBAAmB,CAAC,EAClC,QAAQ,EACR,GAAG,GACJ,EAAE;IACD,QAAQ,EAAE,MAAM,CAAA;IAChB,GAAG,EAAE,MAAM,CAAA;CACZ,GAAG,IAAI,CAiBP;AAED,wBAAgB,eAAe,IAAI,IAAI,CAqBtC;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAYlD;AAGD,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,MAAM,CAAC,CAMxD"}