gipity 1.1.26 → 1.1.28

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/README.md CHANGED
@@ -158,7 +158,7 @@ gipity push <file> # Push one or more files
158
158
  | `gipity login` / `gipity logout` | Authenticate with email + verification code / sign out |
159
159
  | `gipity status` | Show project and login status |
160
160
  | `gipity skill list` / `skill read <name>` | Task docs: read the matching skill before building |
161
- | `gipity project` | List, create, switch, rename, or delete projects |
161
+ | `gipity project` | List, create, switch, rename, or delete projects; set app sign-in (`project auth`) and manage the app's users (`project users`) |
162
162
  | `gipity add <template\|kit>` | Add a template (web-simple, web-fullstack, api, 2d-game, 3d-world, ...) or a kit (realtime, stripe, i18n, ...) |
163
163
  | `gipity remove <kit>` | Remove a kit |
164
164
  | `gipity brand` | Show or set the app's icon, accent color, and share card |
@@ -179,7 +179,7 @@ gipity push <file> # Push one or more files
179
179
  | `gipity approval` | List, create, answer, or cancel pending approvals |
180
180
  | `gipity memory` | Read/write project memory used by workflow llm steps |
181
181
  | `gipity ask "<question>"` | Ask a model one question and print the answer |
182
- | `gipity generate` | Generate images, video, speech, sound effects, or music |
182
+ | `gipity generate` | Generate images, video, speech, sound effects, or music; `generate models`, `status`, `cancel` and `list` for queued Gipity GPU images |
183
183
  | `gipity service` | Call an app service (llm, tts, image, transcribe, ...) |
184
184
  | `gipity notify` | Send a test web push notification, count or remove subscriptions |
185
185
  | `gipity payments` | Connect Stripe to charge your users |
@@ -277,6 +277,10 @@ gipity project # List projects
277
277
  gipity project create "My App" # Create new project
278
278
  gipity project my-app # Switch active project
279
279
  gipity project rename "My Great App" # Rename (display name only)
280
+ gipity project auth app # Users sign in to this app alone (Google, Apple, Discord, email codes, Steam, guest)
281
+ gipity project auth provider google # Setup steps + redirect URI; --client-id/--client-secret to use your own
282
+ gipity project users --search ann # List the app's own users
283
+ gipity project users export -o users.csv
280
284
  ```
281
285
 
282
286
  ## Project Config
package/dist/api.js CHANGED
@@ -161,7 +161,9 @@ function with401Hint(status, message) {
161
161
  function apiErrorFrom(res, json, label, hint = true) {
162
162
  const err = json?.error ?? {};
163
163
  const message = err.message || `HTTP ${res.status}${res.statusText ? ` ${res.statusText}` : ''} from ${label}`;
164
- return new ApiError(res.status, err.code || 'UNKNOWN', hint ? with401Hint(res.status, message) : message, json?.data);
164
+ // A retryable refusal (e.g. Gipity GPU MODEL_WARMING) says how long to wait.
165
+ const data = json?.data ?? (typeof err.retry_after_s === 'number' ? { retry_after_s: err.retry_after_s } : undefined);
166
+ return new ApiError(res.status, err.code || 'UNKNOWN', hint ? with401Hint(res.status, message) : message, data);
165
167
  }
166
168
  async function getHeaders() {
167
169
  return {
@@ -0,0 +1,80 @@
1
+ import { Command } from 'commander';
2
+ import { get, patch } from '../api.js';
3
+ import { bold, brand, dim, muted } from '../colors.js';
4
+ import { run } from '../helpers/index.js';
5
+ import { confirm } from '../utils.js';
6
+ /** The terms a person accepts when turning NSFW services on. Plain language. */
7
+ export const NSFW_TERMS = [
8
+ 'Turning on NSFW services lets this account use adult (NSFW) image models.',
9
+ '',
10
+ 'By turning it on you confirm that:',
11
+ ' - you are 18 or older;',
12
+ ' - nothing you make involves minors, ever;',
13
+ ' - you will not make sexual images of real people;',
14
+ ' - you will not make content showing sexual violence or non-consent;',
15
+ ' - you are responsible for what your apps show and to whom.',
16
+ '',
17
+ 'Prompts are checked for safety and kept for abuse review. Gipity may turn this off.',
18
+ 'While it is on, app payments (Stripe Connect) stop working for your apps.',
19
+ 'Buying credits and your plan are not affected.',
20
+ ].join('\n');
21
+ function renderState(s) {
22
+ console.log(`NSFW services: ${s.allow_nsfw_services ? bold('on') : dim('off')}`);
23
+ if (s.nsfw_attested_at)
24
+ console.log(muted(` Terms accepted: ${s.nsfw_attested_at.slice(0, 10)}`));
25
+ if (s.allow_nsfw_services)
26
+ console.log(muted(' App payments (Stripe Connect) are off while this is on.'));
27
+ else if (!s.self_serve_open)
28
+ console.log(muted(' Not open for self-serve yet.'));
29
+ }
30
+ export const accountCommand = new Command('account')
31
+ .description('Account settings')
32
+ .addHelpText('after', '\nAccount-level settings for your Gipity account, e.g. `gipity account nsfw status`.');
33
+ const nsfwCommand = accountCommand
34
+ .command('nsfw')
35
+ .description('Allow NSFW services (adult image models) for this account');
36
+ nsfwCommand
37
+ .command('status', { isDefault: true })
38
+ .description('Show whether NSFW services are on')
39
+ .option('--json', 'Output as JSON')
40
+ .action((opts) => run('Account', async () => {
41
+ const res = await get('/users/me/nsfw');
42
+ if (opts.json) {
43
+ console.log(JSON.stringify(res.data));
44
+ return;
45
+ }
46
+ renderState(res.data);
47
+ }));
48
+ nsfwCommand
49
+ .command('on')
50
+ .description('Turn NSFW services on (confirms you are 18+ and accept the adult-content terms)')
51
+ .option('-y, --yes', 'Accept the terms without asking')
52
+ .option('--json', 'Output as JSON')
53
+ .action((opts) => run('Account', async () => {
54
+ if (!opts.json)
55
+ console.log(`${NSFW_TERMS}\n`);
56
+ const ok = await confirm(`Turn on ${brand('NSFW services')} and accept these terms?`, { default: 'no', skip: opts.yes === true });
57
+ if (!ok) {
58
+ console.log(muted('Left off.'));
59
+ process.exit(1);
60
+ }
61
+ const res = await patch('/users/me/nsfw', { allow: true, attest: true });
62
+ if (opts.json) {
63
+ console.log(JSON.stringify(res.data));
64
+ return;
65
+ }
66
+ renderState(res.data);
67
+ }));
68
+ nsfwCommand
69
+ .command('off')
70
+ .description('Turn NSFW services off (app payments work again)')
71
+ .option('--json', 'Output as JSON')
72
+ .action((opts) => run('Account', async () => {
73
+ const res = await patch('/users/me/nsfw', { allow: false });
74
+ if (opts.json) {
75
+ console.log(JSON.stringify(res.data));
76
+ return;
77
+ }
78
+ renderState(res.data);
79
+ }));
80
+ //# sourceMappingURL=account.js.map
@@ -1,12 +1,28 @@
1
1
  import { Command } from 'commander';
2
2
  import { readFileSync, fstatSync } from 'fs';
3
- import { post } from '../api.js';
3
+ import { post, ApiError } from '../api.js';
4
4
  import { resolveProjectContext } from '../config.js';
5
5
  import { guessMime } from '../upload.js';
6
6
  import { warning } from '../colors.js';
7
7
  import { run } from '../helpers/index.js';
8
8
  import { withSpinner } from '../progress.js';
9
9
  const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
10
+ /** Longest we'll wait for a model that is loading (MODEL_WARMING) before one retry. */
11
+ const MAX_WARM_WAIT_S = 90;
12
+ /** Call once; if the model is loading (Gipity GPU after idle), wait as told and retry once. */
13
+ async function askWithWarmRetry(call, onWarming) {
14
+ try {
15
+ return await call();
16
+ }
17
+ catch (e) {
18
+ if (!(e instanceof ApiError) || e.code !== 'MODEL_WARMING')
19
+ throw e;
20
+ const waitS = Math.min(Number(e.data?.retry_after_s ?? 45), MAX_WARM_WAIT_S);
21
+ onWarming(waitS);
22
+ await new Promise((r) => setTimeout(r, waitS * 1000));
23
+ return call();
24
+ }
25
+ }
10
26
  /** True when stdin is piped or redirected (not a terminal, not /dev/null). */
11
27
  function stdinIsPiped() {
12
28
  try {
@@ -55,7 +71,7 @@ export const askCommand = new Command('ask')
55
71
  .argument('[prompt...]', 'The question or instruction')
56
72
  .option('--file <path...>', 'Add a text file to the prompt (repeatable); - reads stdin')
57
73
  .option('--image <path...>', 'Attach an image: png, jpg, gif or webp (repeatable)')
58
- .option('--model <model>', 'Model id, alias (small, fast, medium, large, haiku, sonnet, opus, ...) or provider (openai, anthropic, gemini). Default: small')
74
+ .option('--model <model>', 'Model id, alias (small, fast, medium, large, haiku, sonnet, opus, ...) or provider (openai, anthropic, gemini). gipity-qwen3.6-35b runs on Gipity GPU at half price (text only). Default: small')
59
75
  .option('--system <text>', 'Replace the default system prompt')
60
76
  .option('--schema <json>', 'Answer with a JSON value matching this JSON schema; prints the JSON')
61
77
  .option('--max-tokens <n>', 'Cap the answer length', (v) => parseInt(v, 10))
@@ -99,7 +115,8 @@ Examples:
99
115
  body.schema = schema;
100
116
  if (opts.maxTokens)
101
117
  body.max_tokens = opts.maxTokens;
102
- const call = () => post(`/projects/${config.projectGuid}/generate/text`, body);
118
+ const once = () => post(`/projects/${config.projectGuid}/generate/text`, body);
119
+ const call = () => askWithWarmRetry(once, (s) => console.error(`The model is loading; retrying in ${s}s...`));
103
120
  const result = opts.json || !process.stderr.isTTY ? await call() : await withSpinner('Thinking...', call, { done: null });
104
121
  if (opts.json) {
105
122
  console.log(JSON.stringify(result));
@@ -5,6 +5,17 @@ import { error as clrError, success } from '../colors.js';
5
5
  import { run, printList, emitField } from '../helpers/index.js';
6
6
  import { confirm } from '../utils.js';
7
7
  import { createCheckpoint, restoreCheckpoint, dropCheckpoint, resolveDatabase } from '../db-checkpoint.js';
8
+ /** Longest cell the table view prints in full. Longer values (a vector(1536)
9
+ * column is ~20 KB of digits) are cut with their length named; --json and
10
+ * --field still return the whole value. */
11
+ export const TABLE_CELL_MAX = 200;
12
+ export function tableCell(value) {
13
+ const text = value === null || value === undefined ? 'NULL'
14
+ : typeof value === 'object' ? JSON.stringify(value) : String(value);
15
+ if (text.length <= TABLE_CELL_MAX)
16
+ return text;
17
+ return `${text.slice(0, 60)}… (${text.length} chars; --json for all)`;
18
+ }
8
19
  export const dbCommand = new Command('db')
9
20
  .description('Manage databases');
10
21
  dbCommand
@@ -42,7 +53,7 @@ dbCommand
42
53
  const columns = Object.keys(res.data.rows[0]);
43
54
  console.log(columns.join('\t'));
44
55
  for (const row of res.data.rows) {
45
- console.log(columns.map(c => String(row[c] ?? 'NULL')).join('\t'));
56
+ console.log(columns.map(c => tableCell(row[c])).join('\t'));
46
57
  }
47
58
  }
48
59
  // DML with RETURNING carries both rows and a count - the rows are the
@@ -0,0 +1,262 @@
1
+ // Async image generations: submit, wait (live status), download, and the
2
+ // status / cancel / list / models subcommands of `gipity generate`.
3
+ //
4
+ // Gipity GPU models (`gipity-*`) are queued: a job can wait a while behind
5
+ // others, so they always go through the generations API rather than one long
6
+ // request. Any model can use it with `--no-wait`.
7
+ import { Command } from 'commander';
8
+ import { get, post } from '../api.js';
9
+ import { resolveProjectContext } from '../config.js';
10
+ import { error as clrError, success, muted, warning } from '../colors.js';
11
+ import { printCommandError, run } from '../helpers/command.js';
12
+ import { confirm } from '../utils.js';
13
+ /** Gipity GPU models are queued and always generate asynchronously. */
14
+ export const isQueuedModel = (model) => !!model && model.startsWith('gipity-');
15
+ export const TERMINAL = new Set(['succeeded', 'failed', 'cancelled', 'expired']);
16
+ const gensPath = (guid) => `/projects/${guid}/generate/image/generations`;
17
+ /** How often to re-read status while waiting. Overridable for tests. */
18
+ function pollMs() {
19
+ const v = Number(process.env.GIPITY_GENERATE_POLL_MS);
20
+ return Number.isFinite(v) && v > 0 ? v : 2000;
21
+ }
22
+ /** "about 2 min", "about 40s", "under 10s". */
23
+ export function fmtEta(ms) {
24
+ if (ms == null || !Number.isFinite(ms))
25
+ return null;
26
+ const s = Math.round(ms / 1000);
27
+ if (s < 10)
28
+ return 'under 10s';
29
+ if (s < 90)
30
+ return `about ${s}s`;
31
+ const m = Math.round(s / 60);
32
+ if (m < 90)
33
+ return `about ${m} min`;
34
+ return `about ${Math.round(m / 60)} h`;
35
+ }
36
+ /** One short line describing where a generation is. */
37
+ export function statusText(g) {
38
+ switch (g.status) {
39
+ case 'queued': {
40
+ const ahead = g.queue_position != null ? Math.max(0, g.queue_position - 1) : null;
41
+ const eta = fmtEta(g.eta_ms);
42
+ const where = ahead === null ? 'queued' : ahead === 0 ? 'queued: next up' : `queued: ${ahead} ahead`;
43
+ return eta ? `${where}, ${eta}` : where;
44
+ }
45
+ case 'dispatched':
46
+ return 'starting';
47
+ case 'running': {
48
+ if (g.phase === 'loading')
49
+ return 'loading the model';
50
+ if (g.step != null && g.total)
51
+ return `rendering ${g.step}/${g.total}`;
52
+ if (g.progress != null)
53
+ return `rendering ${Math.round(g.progress * 100)}%`;
54
+ return 'rendering';
55
+ }
56
+ case 'succeeded':
57
+ return 'done';
58
+ case 'failed':
59
+ return `failed: ${g.error?.message ?? 'unknown error'}`;
60
+ case 'cancelled':
61
+ return 'cancelled';
62
+ case 'expired':
63
+ return 'expired: it waited too long in the queue (not charged)';
64
+ }
65
+ }
66
+ export async function submitGenerations(projectGuid, body) {
67
+ const res = await post(gensPath(projectGuid), body);
68
+ return res.data;
69
+ }
70
+ export async function fetchGenerations(projectGuid, ids) {
71
+ const res = await get(`${gensPath(projectGuid)}?ids=${ids.map(encodeURIComponent).join(',')}`);
72
+ return res.data;
73
+ }
74
+ /** Combined status line for one or several generations. */
75
+ function combinedText(gens) {
76
+ if (gens.length === 1)
77
+ return statusText(gens[0]);
78
+ const done = gens.filter((g) => TERMINAL.has(g.status)).length;
79
+ const live = gens.find((g) => !TERMINAL.has(g.status));
80
+ return `${done}/${gens.length} finished${live ? `; ${statusText(live)}` : ''}`;
81
+ }
82
+ /**
83
+ * Poll until every generation is finished. Draws one live line on a TTY;
84
+ * otherwise prints a line each time the status changes (to stderr under --json,
85
+ * so stdout stays pure JSON). Ctrl-C asks whether to cancel or leave them queued.
86
+ */
87
+ export async function waitForGenerations(projectGuid, initial, opts = {}) {
88
+ const ids = initial.map((g) => g.id);
89
+ const tty = !!process.stdout.isTTY && !opts.json;
90
+ const say = (line) => (opts.json ? console.error(line) : console.log(line));
91
+ let gens = initial;
92
+ let last = '';
93
+ let lineOpen = false;
94
+ const draw = (text) => {
95
+ if (tty) {
96
+ process.stdout.write(`\r ${muted(text)}\x1b[K`);
97
+ lineOpen = true;
98
+ }
99
+ else if (text !== last) {
100
+ say(` ${text}`);
101
+ }
102
+ last = text;
103
+ };
104
+ const closeLine = () => {
105
+ if (lineOpen) {
106
+ process.stdout.write('\r\x1b[K');
107
+ lineOpen = false;
108
+ }
109
+ };
110
+ let interrupted = false;
111
+ const onSigint = () => { interrupted = true; };
112
+ process.on('SIGINT', onSigint);
113
+ try {
114
+ draw(combinedText(gens));
115
+ while (!gens.every((g) => TERMINAL.has(g.status))) {
116
+ await sleepUnlessInterrupted(pollMs(), () => interrupted);
117
+ if (interrupted)
118
+ break;
119
+ gens = await fetchGenerations(projectGuid, ids);
120
+ draw(combinedText(gens));
121
+ }
122
+ }
123
+ finally {
124
+ process.off('SIGINT', onSigint);
125
+ closeLine();
126
+ }
127
+ if (interrupted) {
128
+ const open = gens.filter((g) => !TERMINAL.has(g.status)).map((g) => g.id);
129
+ if (process.stdin.isTTY && await confirm(`Cancel ${open.length === 1 ? 'the generation' : `${open.length} generations`}? No leaves ${open.length === 1 ? 'it' : 'them'} queued`, { default: 'no', headless: 'no' })) {
130
+ for (const id of open)
131
+ await post(`${gensPath(projectGuid)}/${encodeURIComponent(id)}/cancel`);
132
+ console.log(muted(`Cancelled ${open.join(' ')} (not charged).`));
133
+ }
134
+ else {
135
+ console.error(muted(`Left queued. Check later with: gipity generate status ${open.join(' ')}`));
136
+ }
137
+ process.exit(130);
138
+ }
139
+ return gens;
140
+ }
141
+ function sleepUnlessInterrupted(ms, stop) {
142
+ return new Promise((resolve) => {
143
+ const started = Date.now();
144
+ const tick = () => {
145
+ if (stop() || Date.now() - started >= ms)
146
+ return resolve();
147
+ setTimeout(tick, Math.min(100, ms));
148
+ };
149
+ tick();
150
+ });
151
+ }
152
+ // ── Subcommands ────────────────────────────────────────────────────────
153
+ function printGeneration(g) {
154
+ const head = g.status === 'succeeded' ? success(g.id) : g.status === 'failed' || g.status === 'expired' ? clrError(g.id) : g.id;
155
+ console.log(`${head} ${muted(g.model)} ${statusText(g)}`);
156
+ if (g.status === 'succeeded' && g.outputs?.full?.url)
157
+ console.log(` ${muted('url:')} ${g.outputs.full.url}`);
158
+ if (g.credits_charged != null && g.credits_charged > 0)
159
+ console.log(` ${muted('credits:')} ${g.credits_charged}`);
160
+ }
161
+ const statusCommand = new Command('status')
162
+ .description('Show where queued or finished image generations are')
163
+ .argument('<ids...>', 'Generation ids (gen_...)')
164
+ .option('--json', 'Output as JSON')
165
+ .action((ids, opts) => run('Generation status', async () => {
166
+ const { config } = await resolveProjectContext();
167
+ const gens = await fetchGenerations(config.projectGuid, ids);
168
+ if (opts.json) {
169
+ console.log(JSON.stringify(gens));
170
+ return;
171
+ }
172
+ const found = new Set(gens.map((g) => g.id));
173
+ for (const g of gens)
174
+ printGeneration(g);
175
+ for (const id of ids.filter((i) => !found.has(i)))
176
+ console.log(`${clrError(id)} not found`);
177
+ }));
178
+ const cancelCommand = new Command('cancel')
179
+ .description('Cancel queued or running image generations (a cancelled one is not charged)')
180
+ .argument('<ids...>', 'Generation ids (gen_...)')
181
+ .option('--json', 'Output as JSON')
182
+ .action((ids, opts) => run('Cancel', async () => {
183
+ const { config } = await resolveProjectContext();
184
+ const out = [];
185
+ for (const id of ids) {
186
+ const res = await post(`${gensPath(config.projectGuid)}/${encodeURIComponent(id)}/cancel`);
187
+ out.push(res.data);
188
+ }
189
+ if (opts.json) {
190
+ console.log(JSON.stringify(out));
191
+ return;
192
+ }
193
+ for (const g of out)
194
+ printGeneration(g);
195
+ }));
196
+ const listCommand = new Command('list')
197
+ .description('List your recent image generations in this project')
198
+ .option('--open', 'Only queued or running ones')
199
+ .option('--limit <n>', 'How many (default 20)', (v) => parseInt(v, 10))
200
+ .option('--json', 'Output as JSON')
201
+ .action((opts) => run('List generations', async () => {
202
+ const { config } = await resolveProjectContext();
203
+ const qs = opts.open ? 'status=open' : `limit=${Number.isFinite(opts.limit) ? opts.limit : 20}`;
204
+ const res = await get(`${gensPath(config.projectGuid)}?${qs}`);
205
+ if (opts.json) {
206
+ console.log(JSON.stringify(res.data));
207
+ return;
208
+ }
209
+ if (!res.data.length) {
210
+ console.log(muted(opts.open ? 'Nothing queued or running.' : 'No generations yet.'));
211
+ return;
212
+ }
213
+ for (const g of res.data)
214
+ printGeneration(g);
215
+ }));
216
+ function fmtWait(s) {
217
+ return s === undefined ? '?' : (fmtEta(s * 1000) ?? '?');
218
+ }
219
+ const modelsCommand = new Command('models')
220
+ .description('List image models, with prices and queue estimates for Gipity GPU models')
221
+ .option('--json', 'Output as JSON')
222
+ .action((opts) => run('Image models', async () => {
223
+ const { config } = await resolveProjectContext();
224
+ const res = await get(`/projects/${config.projectGuid}/generate/image/models`);
225
+ if (opts.json) {
226
+ console.log(JSON.stringify(res.data));
227
+ return;
228
+ }
229
+ const { models, gipity_gpu: gpu } = res.data;
230
+ const cloud = models.filter((m) => !isQueuedModel(m.id));
231
+ const queued = models.filter((m) => isQueuedModel(m.id));
232
+ if (cloud.length) {
233
+ console.log('Cloud models (one request, immediate):');
234
+ for (const m of cloud)
235
+ console.log(` ${m.id.padEnd(30)} ${muted(m.provider)}`);
236
+ }
237
+ if (queued.length) {
238
+ if (cloud.length)
239
+ console.log('');
240
+ console.log('Gipity GPU models (queued, half the usual price):');
241
+ if (gpu) {
242
+ console.log(muted(gpu.online
243
+ ? ` queue: ${gpu.queue?.paid_ahead ?? 0} paid + ${gpu.queue?.free_ahead ?? 0} free ahead; wait ${fmtWait(gpu.est_wait_s?.paid)} on a paid plan, ${fmtWait(gpu.est_wait_s?.free)} on Free`
244
+ : ' offline right now: new jobs wait in the queue until it is back'));
245
+ }
246
+ const width = Math.max(...queued.map((m) => m.id.length));
247
+ for (const m of queued) {
248
+ const price = m.price_credits != null ? `${m.price_credits} credits` : 'not priced yet';
249
+ const tags = [m.nsfw ? warning('NSFW') : '', m.max_references ? muted(`refs:${m.max_references}`) : ''].filter(Boolean).join(' ');
250
+ const state = m.available === false ? clrError(`unavailable${m.unavailable_reason ? `: ${m.unavailable_reason}` : ''}`) : '';
251
+ console.log(` ${m.id.padEnd(width)} ${price.padEnd(16)} ${[tags, state].filter(Boolean).join(' ')}`.trimEnd());
252
+ if (m.label || m.description)
253
+ console.log(muted(` ${''.padEnd(width)} ${[m.label, m.description].filter(Boolean).join(': ')}`));
254
+ }
255
+ }
256
+ }));
257
+ /** Attach the async subcommands to the `generate` parent. */
258
+ export function addGenerationSubcommands(parent) {
259
+ return parent.addCommand(statusCommand).addCommand(cancelCommand).addCommand(listCommand).addCommand(modelsCommand);
260
+ }
261
+ export { printCommandError };
262
+ //# sourceMappingURL=generate-async.js.map
@@ -8,6 +8,7 @@ import { error as clrError, success, muted } from '../colors.js';
8
8
  import { printCommandError } from '../helpers/command.js';
9
9
  import { withSpinner } from '../progress.js';
10
10
  import { guessMime } from '../upload.js';
11
+ import { addGenerationSubcommands, isQueuedModel, submitGenerations, waitForGenerations, statusText, } from './generate-async.js';
11
12
  import { IMAGE_MODELS_TABLE, IMAGE_PROVIDER_IDS, IMAGE_QUALITY_IDS, IMAGE_TIER_ALIASES_DOC, IMAGE_TIER_ALIAS_IDS, IMAGE_GEMINI_ASPECT_RATIO_IDS, IMAGE_GEMINI_SIZE_IDS, VIDEO_MODEL_IDS, VIDEO_MODELS_TABLE, VIDEO_ASPECT_RATIOS, VIDEO_ASPECT_RATIO_IDS, VIDEO_RESOLUTION_IDS, TTS_PROVIDER_IDS, TTS_PROVIDER_DESCRIPTIONS, GEMINI_TTS_VOICES_DOC, } from '../provider-docs.js';
12
13
  function printMetrics(metrics) {
13
14
  const rows = metrics.filter((m) => m !== null);
@@ -214,6 +215,13 @@ ${IMAGE_MODELS_TABLE}
214
215
  Tier aliases (pass to --model instead of an id; each names a provider+model):
215
216
  ${IMAGE_TIER_ALIASES_DOC}
216
217
 
218
+ Gipity GPU models (--model gipity-...; list them with \`gipity generate models\`):
219
+ half the usual price for the same model, but queued: paid plans go first, and a
220
+ job may wait a while. The CLI waits and shows the queue position, then saves the
221
+ image. --no-wait queues it and prints the id instead (check it with
222
+ \`gipity generate status <id>\`). GPU-only options: --aspect, --n, --ref, --avoid,
223
+ --nsfw, --format. NSFW models need "Allow NSFW services" on your account.
224
+
217
225
  Editing (--input): pass one or more source images and the prompt becomes an edit
218
226
  instruction applied to them - "make it night time", "add a hat", "remove the car
219
227
  in the background", or compose several inputs together. Editing routes to Gemini
@@ -226,23 +234,37 @@ Examples:
226
234
  gipity generate image "landscape sunset" --provider gemini --aspect-ratio 16:9 --image-size 2K
227
235
  gipity generate image "product photo" --provider openai --model gpt-image-2 --size 1536x1024 --quality high
228
236
  gipity generate image "abstract art" --provider bfl --model flux-2-pro -o art.png
237
+ gipity generate image "a red canoe at sunrise" --model gipity-krea2-realistic --aspect landscape
238
+ gipity generate image "same canoe, now at night" --model gipity-qwen21-consistent --ref gen_abc12345
239
+ gipity generate image "a lighthouse" --model gipity-krea2-realistic --n 4 --no-wait
229
240
  `)
230
241
  .argument('<prompt>', 'Text description of the image, or (with --input) the edit instruction to apply')
231
242
  .option('--input <file>', 'Source image to edit/compose (repeatable). With --input the prompt is an edit instruction; routes to Gemini.', (v, acc) => (acc || []).concat(v))
232
243
  .addOption(new Option('--provider <provider>', 'Image provider (default: bfl)').choices(IMAGE_PROVIDER_IDS))
233
244
  .option('--model <model>', `Model id for the chosen provider, or a tier alias (${IMAGE_TIER_ALIAS_IDS.join(', ')}); see Models below`)
234
- .option('--size <size>', 'Dimensions as WxH, e.g. "1024x1024" (OpenAI/BFL)')
245
+ .option('--size <size>', 'Dimensions as WxH, e.g. "1024x1024" (Gemini snaps to its nearest tier and aspect ratio)')
235
246
  .addOption(new Option('--quality <quality>', 'Quality (OpenAI gpt-image models only)').choices(IMAGE_QUALITY_IDS))
236
247
  .addOption(new Option('--aspect-ratio <ratio>', 'Aspect ratio (Gemini only)').choices(IMAGE_GEMINI_ASPECT_RATIO_IDS))
237
- .addOption(new Option('--image-size <size>', 'Output resolution (Gemini only)').choices(IMAGE_GEMINI_SIZE_IDS))
238
- .option('--seed <n>', 'Deterministic seed (BFL only): reuse one seed to keep a set of images visually coherent', (v) => parseInt(v, 10))
239
- .option('-o, --output <file>', 'Output path (default ./generated.png). For an image your app ships, write it into the source tree so it deploys, e.g. -o src/assets/images/hero.png; the cwd default is fine for one-off generation.')
248
+ .addOption(new Option('--image-size <size>', 'Output resolution tier (Gemini only; each model supports only some, see the app-image skill)').choices(IMAGE_GEMINI_SIZE_IDS))
249
+ .option('--seed <n>', 'Deterministic seed (BFL and Gipity GPU models): reuse one seed to keep a set of images visually coherent', (v) => parseInt(v, 10))
250
+ .option('-o, --output <file>', 'Output path (default ./generated.png). For an image your app ships, write it into the source tree so it deploys, e.g. -o src/assets/images/hero.png; the cwd default is fine for one-off generation. With --n > 1 the files are numbered (hero-1.png, hero-2.png).')
251
+ .addOption(new Option('--aspect <aspect>', 'Shape (Gipity GPU models)').choices(['portrait', 'square', 'landscape']))
252
+ .option('--n <count>', 'Number of images, 1-4, with consecutive seeds (Gipity GPU models)', (v) => parseInt(v, 10))
253
+ .option('--ref <gen_id>', 'An earlier generation to keep consistent with (repeatable; models that take references)', (v, acc) => (acc || []).concat(v))
254
+ .option('--avoid <text>', 'What to keep out of the image (Gipity GPU models that support it)')
255
+ .option('--nsfw', 'Allow adult content (NSFW models; needs "Allow NSFW services" on your account)')
256
+ .addOption(new Option('--format <format>', 'Full-size file format (Gipity GPU models; default jpeg)').choices(['jpeg', 'png']))
257
+ .option('--no-wait', 'Queue it and print the generation id(s) instead of waiting')
240
258
  .option('--json', 'Output as JSON')
241
259
  .action(async (prompt, opts) => {
242
260
  try {
243
261
  const { config } = await resolveProjectContext();
244
262
  if (opts.output)
245
263
  ensureOutputDir(opts.output);
264
+ if (isQueuedModel(opts.model) || opts.wait === false) {
265
+ await generateQueued(config.projectGuid, prompt, opts);
266
+ return;
267
+ }
246
268
  const inputImages = opts.input ? readInputImages(opts.input) : undefined;
247
269
  const doGenerate = () => post(`/projects/${config.projectGuid}/generate/image`, {
248
270
  prompt,
@@ -271,9 +293,12 @@ Examples:
271
293
  console.log(muted(`Generated with ${result.provider}/${result.model}`));
272
294
  printMetrics([
273
295
  ...generationMetrics(result, elapsed),
296
+ result.width && result.height ? { label: 'pixels', value: `${result.width}x${result.height}` } : null,
274
297
  result.seed !== undefined
275
298
  ? { label: 'seed', value: `${result.seed} ${muted(`(pass --seed ${result.seed} to keep the next image coherent)`)}` } : null,
276
299
  ]);
300
+ if (result.note)
301
+ console.log(muted(result.note));
277
302
  // Saved-path last: a caller reading a truncated tail of this output (an
278
303
  // agent batching several generates in one shell call) must still see
279
304
  // WHERE the bytes landed - that is the one line the next command needs.
@@ -285,6 +310,83 @@ Examples:
285
310
  process.exit(1);
286
311
  }
287
312
  });
313
+ /** File name for image i of n: the -o path (or ./generated.<ext>), numbered when n > 1. */
314
+ function numberedPath(base, i, n) {
315
+ if (n <= 1)
316
+ return base;
317
+ const dot = base.lastIndexOf('.');
318
+ const slash = Math.max(base.lastIndexOf('/'), base.lastIndexOf('\\'));
319
+ return dot > slash ? `${base.slice(0, dot)}-${i + 1}${base.slice(dot)}` : `${base}-${i + 1}`;
320
+ }
321
+ /** Queued (async) path: submit, wait with live status, download each image. */
322
+ async function generateQueued(projectGuid, prompt, opts) {
323
+ if (opts.input)
324
+ throw new Error('--input editing is not available on queued generations; drop --input or pick a cloud model.');
325
+ if (!opts.model || !String(opts.model).startsWith('gipity-')) {
326
+ throw new Error('--no-wait is for Gipity GPU models (--model gipity-...; see `gipity generate models`). Cloud models render right away: drop --no-wait.');
327
+ }
328
+ const started = Date.now();
329
+ const submitted = await submitGenerations(projectGuid, {
330
+ model: opts.model,
331
+ prompt,
332
+ avoid: opts.avoid,
333
+ aspect: opts.aspect,
334
+ size: opts.size,
335
+ seed: Number.isFinite(opts.seed) ? opts.seed : undefined,
336
+ n: Number.isFinite(opts.n) ? opts.n : undefined,
337
+ nsfw: opts.nsfw ? true : undefined,
338
+ format: opts.format,
339
+ references: opts.ref,
340
+ });
341
+ if (opts.wait === false) {
342
+ if (opts.json) {
343
+ console.log(JSON.stringify(submitted));
344
+ return;
345
+ }
346
+ for (const g of submitted)
347
+ console.log(`${g.id} ${muted(statusText(g))}`);
348
+ console.log(muted(`Check with: gipity generate status ${submitted.map((g) => g.id).join(' ')}`));
349
+ return;
350
+ }
351
+ if (!opts.json)
352
+ console.log(muted(`Queued ${submitted.length === 1 ? submitted[0].id : submitted.map((g) => g.id).join(', ')} on ${opts.model}`));
353
+ const done = await waitForGenerations(projectGuid, submitted, { json: !!opts.json });
354
+ const elapsed = (Date.now() - started) / 1000;
355
+ const saved = [];
356
+ for (let i = 0; i < done.length; i++) {
357
+ const g = done[i];
358
+ const url = g.status === 'succeeded' ? g.outputs?.full?.url : undefined;
359
+ if (!url) {
360
+ saved.push({ gen: g, path: null });
361
+ continue;
362
+ }
363
+ const ext = (g.outputs?.full?.mime ?? '').includes('png') ? 'png' : 'jpg';
364
+ const target = numberedPath(opts.output || `generated.${ext}`, i, done.length);
365
+ saved.push({ gen: g, path: await downloadFile(url, target, !!opts.output) });
366
+ }
367
+ const failed = saved.filter((s) => !s.path);
368
+ if (opts.json) {
369
+ console.log(JSON.stringify(saved.map((s) => ({ ...s.gen, saved: s.path })).map((r) => ({ ...r, generation_seconds: Math.round(elapsed * 10) / 10 }))));
370
+ }
371
+ else {
372
+ const credits = done.reduce((sum, g) => sum + (g.credits_charged ?? 0), 0);
373
+ console.log(muted(`Generated with gipity/${opts.model}`));
374
+ const first = saved.find((s) => s.path)?.gen;
375
+ printMetrics([
376
+ { label: 'time', value: fmtSeconds(elapsed) },
377
+ first?.width && first?.height ? { label: 'pixels', value: `${first.width}x${first.height}` } : null,
378
+ first?.seed != null ? { label: 'seed', value: `${first.seed} ${muted(`(pass --seed ${first.seed} to keep the next image coherent)`)}` } : null,
379
+ credits > 0 ? { label: 'credits', value: credits.toLocaleString('en-US') } : null,
380
+ ]);
381
+ for (const s of failed)
382
+ console.error(clrError(`${s.gen.id} ${statusText(s.gen)}`));
383
+ for (const s of saved)
384
+ if (s.path)
385
+ console.log(success(`Saved ${s.gen.id} to ${s.path}`));
386
+ }
387
+ if (failed.length === done.length)
388
+ process.exit(1);
389
+ }
288
390
  // ── VIDEO ──────────────────────────────────────────────────────────────
289
391
  const videoCommand = new Command('video')
290
392
  .description('Generate a short video (3-10 seconds) from a text prompt')
@@ -358,7 +460,7 @@ voice ids: gipity service call "tts/voices?provider=elevenlabs" --get
358
460
 
359
461
  Gemini voices: ${GEMINI_TTS_VOICES_DOC}
360
462
 
361
- Multi-speaker (--speakers, Gemini only): JSON array like
463
+ Multi-speaker (--speakers, Gemini only): JSON array of exactly 2 speakers like
362
464
  [{"name":"Joe","voice":"Kore"},{"name":"Jane","voice":"Puck"}]; format the
363
465
  text as "Name: dialogue" on each line.
364
466
 
@@ -372,7 +474,7 @@ Examples:
372
474
  .addOption(new Option('--provider <provider>', 'TTS provider (default: elevenlabs)').choices(TTS_PROVIDER_IDS))
373
475
  .option('--voice <voice>', 'Voice ID or name (provider-specific; see Voices below)')
374
476
  .option('--language <code>', 'BCP-47 language code, e.g. ja-JP, es-ES (Gemini only, 60+ languages)')
375
- .option('--speakers <json>', 'Multi-speaker config as JSON array (Gemini only, up to 2 speakers)')
477
+ .option('--speakers <json>', 'Multi-speaker config as JSON array (Gemini only, exactly 2 speakers)')
376
478
  .option('-o, --output <file>', 'Output path (default ./speech.mp3; --provider gemini returns WAV, so name it .wav). For audio your app ships, write it into the source tree so it deploys, e.g. -o src/assets/sounds/intro.mp3; the cwd default is fine for one-off generation.')
377
479
  .option('--json', 'Output as JSON')
378
480
  .action(async (text, opts) => {
@@ -544,11 +646,11 @@ Examples:
544
646
  }
545
647
  });
546
648
  // ── PARENT COMMAND ─────────────────────────────────────────────────────
547
- export const generateCommand = new Command('generate')
649
+ export const generateCommand = addGenerationSubcommands(new Command('generate')
548
650
  .description('Generate images, video, speech, sound effects, or music')
549
651
  .addCommand(imageCommand)
550
652
  .addCommand(videoCommand)
551
653
  .addCommand(speechCommand)
552
654
  .addCommand(soundCommand)
553
- .addCommand(musicCommand);
655
+ .addCommand(musicCommand));
554
656
  //# sourceMappingURL=generate.js.map