gipity 1.1.11 → 1.1.13

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.
@@ -1,5 +1,5 @@
1
1
  import { Command, Option } from 'commander';
2
- import { post } from '../api.js';
2
+ import { post, LONG_REQUEST_TIMEOUT_MS } from '../api.js';
3
3
  import { resolveProjectContext, getConfigPath } from '../config.js';
4
4
  import { pushFile } from '../sync.js';
5
5
  import { mkdirSync, writeFileSync, readFileSync } from 'fs';
@@ -254,7 +254,7 @@ Examples:
254
254
  image_size: opts.imageSize,
255
255
  seed: Number.isFinite(opts.seed) ? opts.seed : undefined,
256
256
  input_images: inputImages,
257
- });
257
+ }, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
258
258
  const verb = inputImages ? 'Editing image...' : 'Generating image...';
259
259
  const started = Date.now();
260
260
  const result = opts.json
@@ -323,7 +323,7 @@ Examples:
323
323
  aspect_ratio: opts.aspect,
324
324
  resolution: opts.resolution,
325
325
  duration_seconds: opts.duration ? Number(opts.duration) : undefined,
326
- });
326
+ }, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
327
327
  // Veo runs 30-120s; the bouncing bar + timer keeps the wait honest.
328
328
  const started = Date.now();
329
329
  const result = opts.json
@@ -396,7 +396,7 @@ Examples:
396
396
  voice: opts.voice,
397
397
  language: opts.language,
398
398
  speakers,
399
- });
399
+ }, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
400
400
  const started = Date.now();
401
401
  const result = opts.json
402
402
  ? await doGenerate()
@@ -428,18 +428,24 @@ default; pass --model <id> only if you want a specific one (see the catalog with
428
428
 
429
429
  Tips:
430
430
  - Describe genre, mood, instruments, and tempo (e.g. "upbeat lo-fi hip hop with mellow piano")
431
- - Music is instrumental by default; pass --vocals to allow singing
431
+ - Music is instrumental by default; pass --vocals to allow singing, or --lyrics /
432
+ --lyrics-file to have the vocalist sing YOUR exact words (section tags like
433
+ [Verse] / [Chorus] are understood; keep the prompt to style only)
434
+ - With lyrics, size --duration to the words (roughly 10s per short section)
432
435
  - Longer clips cost more; the max length depends on the model
433
436
 
434
437
  Examples:
435
438
  gipity generate music "chill lo-fi beat for studying"
436
439
  gipity generate music "epic orchestral battle theme" --duration 60 -o src/assets/audio/theme.mp3
437
440
  gipity generate music "indie pop chorus" --vocals --duration 20
441
+ gipity generate music "80s synth-pop, female vocals" --lyrics-file lyrics.txt --duration 120 -o song.mp3
438
442
  `)
439
443
  .argument('<prompt>', 'Text description of the music to generate')
440
444
  .option('--duration <seconds>', 'Clip length in seconds (default 30; max depends on the model)', (v) => parseInt(v, 10))
441
445
  .option('--model <model>', 'Music model id (default: platform default; list ids: gipity service call music/models --get)')
442
446
  .option('--vocals', 'Allow vocals (default: instrumental only)')
447
+ .option('--lyrics <text>', 'Exact lyrics to sing (implies vocals; only lyrics-capable models)')
448
+ .option('--lyrics-file <file>', 'Read the exact lyrics to sing from a file (implies vocals)')
443
449
  .option('-o, --output <file>', 'Output path (default ./music.mp3). For audio your app ships, write it into the source tree so it deploys, e.g. -o src/assets/audio/theme.mp3; the cwd default is fine for one-off generation.')
444
450
  .option('--json', 'Output as JSON')
445
451
  .action(async (prompt, opts) => {
@@ -447,12 +453,21 @@ Examples:
447
453
  const { config } = await resolveProjectContext();
448
454
  if (opts.output)
449
455
  ensureOutputDir(opts.output);
456
+ if (opts.lyrics && opts.lyricsFile) {
457
+ console.error(clrError('Pass --lyrics or --lyrics-file, not both.'));
458
+ process.exit(1);
459
+ }
460
+ const lyrics = opts.lyricsFile
461
+ ? readFileSync(opts.lyricsFile, 'utf8').trim()
462
+ : opts.lyrics;
450
463
  const doGenerate = () => post(`/projects/${config.projectGuid}/generate/music`, {
451
464
  prompt,
452
465
  duration_seconds: opts.duration,
453
466
  model: opts.model,
454
- instrumental: !opts.vocals,
455
- });
467
+ // Lyrics imply vocals; otherwise instrumental unless --vocals.
468
+ instrumental: lyrics ? false : !opts.vocals,
469
+ lyrics: lyrics || undefined,
470
+ }, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
456
471
  const started = Date.now();
457
472
  const result = opts.json
458
473
  ? await doGenerate()
@@ -506,7 +521,7 @@ Examples:
506
521
  text,
507
522
  duration_seconds: opts.duration,
508
523
  prompt_influence: opts.influence,
509
- });
524
+ }, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
510
525
  const started = Date.now();
511
526
  const result = opts.json
512
527
  ? await doGenerate()
@@ -1,5 +1,5 @@
1
1
  import { Command } from 'commander';
2
- import { get, post, publicRequest, mintAppToken, ApiError } from '../api.js';
2
+ import { get, post, publicRequest, mintAppToken, ApiError, LONG_REQUEST_TIMEOUT_MS } from '../api.js';
3
3
  import { getAuth } from '../auth.js';
4
4
  import { requireConfig } from '../config.js';
5
5
  import { bold, muted } from '../colors.js';
@@ -110,7 +110,12 @@ serviceCommand
110
110
  res = await publicRequest(opts.get ? 'GET' : 'POST', url, opts.get ? undefined : body, headers);
111
111
  }
112
112
  else {
113
- res = opts.get ? await get(url) : await post(url, body);
113
+ // Generation services (music, video, image, ...) can hold the request
114
+ // open for minutes - e.g. a GPU music model cold-starting from
115
+ // scale-to-zero renders nothing for 1-3 min first. The server bounds
116
+ // the work at 300s, so give POSTs that full budget instead of the 60s
117
+ // default (which killed every cold-start render at exactly 60s).
118
+ res = opts.get ? await get(url) : await post(url, body, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
114
119
  }
115
120
  }
116
121
  catch (err) {
@@ -79,10 +79,14 @@ function readState(convGuid) {
79
79
  try {
80
80
  const raw = readFileSync(p, 'utf-8');
81
81
  const parsed = JSON.parse(raw);
82
+ const posNum = (v) => (typeof v === 'number' && v >= 0 ? v : undefined);
82
83
  return {
83
84
  last_uuid: typeof parsed.last_uuid === 'string' ? parsed.last_uuid : null,
84
85
  last_flush_ms: typeof parsed.last_flush_ms === 'number' ? parsed.last_flush_ms : undefined,
85
86
  attached: typeof parsed.attached === 'boolean' ? parsed.attached : undefined,
87
+ pending_tokens_in: posNum(parsed.pending_tokens_in),
88
+ pending_tokens_out: posNum(parsed.pending_tokens_out),
89
+ pending_active_ms: posNum(parsed.pending_active_ms),
86
90
  };
87
91
  }
88
92
  catch {
@@ -365,7 +369,51 @@ async function ensureAttached(convGuid, hook) {
365
369
  if (ok)
366
370
  writeState(convGuid, { ...(state ?? { last_uuid: null }), attached: true });
367
371
  }
368
- async function handleStopFamily(convGuid, src, hook, isSubagent, minIntervalMs = 0) {
372
+ // A gap between consecutive transcript timestamps longer than this is idle
373
+ // time (e.g. a replayed range spanning the user's think-time between
374
+ // prompts), not agent work - skip it when estimating active time.
375
+ export const ACTIVE_GAP_MAX_MS = 5 * 60_000;
376
+ /** Estimate the agent's working time over a batch of entries: the sum of
377
+ * gaps between consecutive entry timestamps, skipping idle stretches.
378
+ * Within one prompt run the transcript grows continuously (tool calls,
379
+ * assistant chunks), so this tracks real work closely; the hook path has no
380
+ * agent-reported duration the way the relay's stream `result` footer does. */
381
+ export function activeMsFromEntries(entries) {
382
+ let total = 0;
383
+ let prev = null;
384
+ for (const e of entries) {
385
+ if (!e.ts)
386
+ continue;
387
+ const t = Date.parse(e.ts);
388
+ if (isNaN(t))
389
+ continue;
390
+ if (prev !== null) {
391
+ const gap = t - prev;
392
+ if (gap > 0 && gap <= ACTIVE_GAP_MAX_MS)
393
+ total += gap;
394
+ }
395
+ prev = t;
396
+ }
397
+ return total;
398
+ }
399
+ /** Fallback token totals for parsers that don't report `usage` (Codex, Grok):
400
+ * sum the assistant entries' token fields. Claude/opencode override this via
401
+ * ParseResult.usage - their per-entry fields undercount (no cache tokens)
402
+ * or repeat across lines, which a plain entry sum can't correct. */
403
+ export function entryTokenTotals(entries) {
404
+ let tokensIn = 0;
405
+ let tokensOut = 0;
406
+ for (const e of entries) {
407
+ if (e.kind !== 'assistant')
408
+ continue;
409
+ if (typeof e.input_tokens === 'number' && e.input_tokens > 0)
410
+ tokensIn += e.input_tokens;
411
+ if (typeof e.output_tokens === 'number' && e.output_tokens > 0)
412
+ tokensOut += e.output_tokens;
413
+ }
414
+ return { tokensIn, tokensOut };
415
+ }
416
+ async function handleStopFamily(convGuid, src, hook, isSubagent, minIntervalMs = 0, emitResult = false) {
369
417
  void isSubagent;
370
418
  if (!hook.transcript_path || !existsSync(hook.transcript_path))
371
419
  return;
@@ -382,11 +430,13 @@ async function handleStopFamily(convGuid, src, hook, isSubagent, minIntervalMs =
382
430
  try {
383
431
  const state = readState(convGuid) ?? { last_uuid: null };
384
432
  const content = await readWholeFile(hook.transcript_path);
433
+ let replayed = false;
385
434
  let result = src.capture.parse(content, state.last_uuid, hook);
386
435
  if (!result.foundWatermark && state.last_uuid !== null) {
387
436
  // Transcript rotated (/clear or compact) - watermark isn't present.
388
437
  // Replay from top; server dedupes via the source_uuid unique index.
389
438
  result = src.capture.parse(content, null, hook);
439
+ replayed = true;
390
440
  }
391
441
  // Base64 image blocks (Read-of-image tool results) upload to VFS and
392
442
  // become image_ref blocks — same no-inline-base64 chokepoint as the
@@ -395,11 +445,49 @@ async function handleStopFamily(convGuid, src, hook, isSubagent, minIntervalMs =
395
445
  if (hook.cwd)
396
446
  rewriter.setCwd(hook.cwd);
397
447
  const entries = await rewriter.rewrite(result.entries);
448
+ // Roll this flush's token usage + working time into the pending
449
+ // counters. A replayed-from-top range re-parses lines whose rows the
450
+ // server already has (and whose tokens an earlier result already
451
+ // counted), so its usage is unknowable without server state - skip it
452
+ // rather than double-count; only the rotation boundary is undercounted.
453
+ const flushUsage = replayed
454
+ ? { tokensIn: 0, tokensOut: 0 }
455
+ : result.usage ?? entryTokenTotals(result.entries);
456
+ const flushActive = replayed ? 0 : activeMsFromEntries(result.entries);
457
+ const pendIn = (state.pending_tokens_in ?? 0) + flushUsage.tokensIn;
458
+ const pendOut = (state.pending_tokens_out ?? 0) + flushUsage.tokensOut;
459
+ const pendActive = (state.pending_active_ms ?? 0) + flushActive;
460
+ // On a clean end-of-run event, emit the accumulated metrics as a
461
+ // `result` entry - the same footer the relay's stream path posts, which
462
+ // the server rolls into the conversation counters the projects list
463
+ // reads (tokens_in/tokens_out/active_ms). The source_uuid is
464
+ // deterministic in the watermark so a retried POST dedupes instead of
465
+ // double-counting. No cost here: only the stream footer reports cost.
466
+ let resultEmitted = false;
467
+ if (emitResult && result.lastUuid && (pendIn > 0 || pendOut > 0 || pendActive > 0)) {
468
+ const lastTs = [...entries].reverse().find((e) => e.ts)?.ts;
469
+ entries.push({
470
+ kind: 'result',
471
+ tokens_in: pendIn,
472
+ tokens_out: pendOut,
473
+ duration_ms: pendActive,
474
+ source_uuid: `${hook.session_id ?? convGuid}-result-${result.lastUuid}`,
475
+ ...(lastTs ? { ts: lastTs } : {}),
476
+ });
477
+ resultEmitted = true;
478
+ }
398
479
  const ok = await postEntries(convGuid, entries);
399
480
  if (ok) {
400
481
  // Stamp the flush time even when no new lines landed, so the throttle
401
482
  // above measures from the last attempt. Keep the watermark if unchanged.
402
- writeState(convGuid, { last_uuid: result.lastUuid ?? state.last_uuid, last_flush_ms: Date.now() });
483
+ writeState(convGuid, {
484
+ ...state,
485
+ last_uuid: result.lastUuid ?? state.last_uuid,
486
+ last_flush_ms: Date.now(),
487
+ pending_tokens_in: resultEmitted ? 0 : pendIn,
488
+ pending_tokens_out: resultEmitted ? 0 : pendOut,
489
+ pending_active_ms: resultEmitted ? 0 : pendActive,
490
+ });
403
491
  }
404
492
  }
405
493
  finally {
@@ -411,7 +499,7 @@ async function handleSessionEnd(convGuid, src, hook) {
411
499
  // Stop, so there's usually nothing new, but a race between Stop and
412
500
  // SessionEnd could leave lines behind.
413
501
  if (hook.transcript_path && existsSync(hook.transcript_path)) {
414
- await handleStopFamily(convGuid, src, hook, false);
502
+ await handleStopFamily(convGuid, src, hook, false, 0, true);
415
503
  }
416
504
  const sessionId = hook.session_id ?? 'unknown';
417
505
  const entries = [{
@@ -518,7 +606,9 @@ async function main() {
518
606
  case 'session-start':
519
607
  break; // ensureAttached above already covers what this event used to do
520
608
  case 'stop':
521
- await handleStopFamily(convGuid, src, hook, false);
609
+ // End of a prompt run - flush AND roll the run's accumulated
610
+ // tokens/working time into the conversation via a result entry.
611
+ await handleStopFamily(convGuid, src, hook, false, 0, true);
522
612
  break;
523
613
  case 'subagent-stop':
524
614
  await handleStopFamily(convGuid, src, hook, true);