@genspark/cli 1.15.2 → 1.15.4-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -35,8 +35,7 @@ import * as os from 'os';
35
35
  import * as pathModule from 'path';
36
36
  import { createRequire } from 'module';
37
37
  import { spawn } from 'child_process';
38
- import { Readable } from 'stream';
39
- import { pipeline } from 'stream/promises';
38
+ import { LOCAL_SAVE_FAILED_EXIT_CODE, describeDownloadFailure, downloadFailureMessage, preflightOutputFile, writeBodyToFile, } from './download-file.js';
40
39
  import { ApiClient, isAuthError, unauthenticatedRequest, } from './client.js';
41
40
  import { tokenPassHeaders } from './native-waf.js';
42
41
  import { classifyFileArg, awaitLocalFileReady, decideAfterWait, localFileNotReadyError, passthroughWarning, urlsParamItems, } from './localFiles.js';
@@ -430,46 +429,6 @@ const CONTENT_TYPE_MAP = {
430
429
  '.wav': 'audio/wav',
431
430
  '.webm': 'video/webm',
432
431
  };
433
- /** Preserve interleaved --image/--file order; Commander groups options by key. */
434
- export function collectDesignAttachmentArgs(argv) {
435
- const result = [];
436
- for (let index = 0; index < argv.length; index += 1) {
437
- const token = argv[index];
438
- const equalsMatch = token.match(/^--(image|file)=(.+)$/);
439
- if (equalsMatch) {
440
- result.push({
441
- path: equalsMatch[2],
442
- role: equalsMatch[1] === 'image' ? 'visual_reference' : 'context',
443
- });
444
- continue;
445
- }
446
- if (token !== '--image' && token !== '--file')
447
- continue;
448
- const role = token === '--image' ? 'visual_reference' : 'context';
449
- while (index + 1 < argv.length && !argv[index + 1].startsWith('-')) {
450
- result.push({ path: argv[index + 1], role });
451
- index += 1;
452
- }
453
- }
454
- return result;
455
- }
456
- async function uploadDesignAttachments(values, client) {
457
- const attachments = [];
458
- // Upload the complete batch before executeTool: any failure aborts project
459
- // creation/continuation rather than leaving a half-bound Design project.
460
- for (const value of values) {
461
- const localPath = expandHome(value.path);
462
- if (!isLocalFilePath(localPath)) {
463
- throw new Error(`File not found: ${value.path}`);
464
- }
465
- const name = pathModule.basename(localPath);
466
- const ext = pathModule.extname(localPath).toLowerCase();
467
- const mimeType = CONTENT_TYPE_MAP[ext] || 'application/octet-stream';
468
- const url = await uploadLocalFile(localPath, client);
469
- attachments.push({ url, name, mime_type: mimeType, role: value.role });
470
- }
471
- return attachments;
472
- }
473
432
  /**
474
433
  * Stream a local file to a URL using Node.js http/https.request +
475
434
  * fs.createReadStream so the file is never fully buffered in memory.
@@ -648,11 +607,30 @@ async function downloadToFile(url, savePath, client) {
648
607
  throw new Error('Download failed: empty response body');
649
608
  // Stream to disk: AI-Drive reads reach GB scale, past what the sandbox's
650
609
  // swap-less RAM tolerates as a single buffer.
651
- await pipeline(Readable.fromWeb(resp.body), fs.createWriteStream(savePath));
610
+ await writeBodyToFile(resp.body, savePath);
652
611
  const sizeBytes = fs.statSync(savePath).size;
653
612
  progress(`Downloaded ${formatFileSize(sizeBytes)} → ${savePath}`);
654
613
  return pathModule.resolve(savePath);
655
614
  }
615
+ /**
616
+ * Save the file behind an already-successful (and possibly billed) result.
617
+ * A failed save must not discard the result: it is recorded as
618
+ * `data.download_error` (URL + download-only retry) and `result` is still
619
+ * printed, so the caller re-fetches the bytes instead of regenerating them.
620
+ */
621
+ async function saveResultFile(url, savePath, client, result) {
622
+ const data = result.data;
623
+ try {
624
+ data.local_path = await downloadToFile(url, savePath, client);
625
+ return undefined;
626
+ }
627
+ catch (err) {
628
+ const failure = describeDownloadFailure(url, savePath, err);
629
+ data.download_error = failure;
630
+ result.message = downloadFailureMessage(failure);
631
+ return failure;
632
+ }
633
+ }
656
634
  function isLocalFilePath(value) {
657
635
  return (!value.startsWith('http://') &&
658
636
  !value.startsWith('https://') &&
@@ -1181,8 +1159,7 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1181
1159
  cmd.option('--follow', 'After the async submit, follow the durable run live (SSE) and exit with the terminal result', false);
1182
1160
  cmd.option('-o, --output-file <path>', 'Export the artifact (pptx/docx/xlsx) to a local file after task completes');
1183
1161
  cmd.option('--session-id <id>', 'ACP session ID (used with get-project)');
1184
- cmd.option('--file <values...>', 'Attach local files or URLs to the task (media_agent: reference images / video / audio / documents; Design: structured context; sheets: CSV/Excel import)');
1185
- cmd.option('--image <values...>', 'Design only: upload ordered local visual references');
1162
+ cmd.option('--file <values...>', 'Attach local files or URLs to the task (media_agent: reference images / video / audio / documents; design: reference images / documents; sheets: CSV/Excel import)');
1186
1163
  cmd.addHelpText('after', '\nVirtual subcommands:\n' +
1187
1164
  ' get-project Get Genspark project info for an ACP session (local file lookup, no API call)\n' +
1188
1165
  ' --session-id <id> ACP session ID (required)\n' +
@@ -1191,8 +1168,7 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1191
1168
  ' gsk task get-project --session-id <acp_session_id>\n');
1192
1169
  }
1193
1170
  if (tool.name === 'task_continue') {
1194
- cmd.option('--image <values...>', 'Design only: append ordered local visual references');
1195
- cmd.option('--file <values...>', 'Design only: append ordered local context files');
1171
+ cmd.option('--file <values...>', 'Attach local files or URLs to the follow-up (uploaded into file_urls, same as task create --file)');
1196
1172
  }
1197
1173
  // For the aidrive tool, add client-side options used by the --local_file
1198
1174
  // upload and by `download`'s local destination.
@@ -1355,6 +1331,8 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1355
1331
  }
1356
1332
  // Extract and remove client-side-only options before sending to API
1357
1333
  const outputFilePath = opts.outputFile;
1334
+ if (outputFilePath !== undefined)
1335
+ preflightOutputFile(outputFilePath);
1358
1336
  delete opts.outputFile;
1359
1337
  delete opts.acp; // ACP flag is client-side only
1360
1338
  // -o exports an artifact of the FINISHED project — an async submit
@@ -2166,24 +2144,11 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
2166
2144
  }
2167
2145
  return;
2168
2146
  }
2169
- const designAttachmentArgs = collectDesignAttachmentArgs(process.argv);
2170
- const isDesignAttachmentCommand = designAttachmentArgs.length > 0 &&
2171
- ((tool.name === 'create_task' && args.task_type === 'design') ||
2172
- tool.name === 'task_continue');
2173
- if (isDesignAttachmentCommand) {
2174
- const uploaded = await uploadDesignAttachments(designAttachmentArgs, client);
2175
- const existing = Array.isArray(args.attachments)
2176
- ? args.attachments
2177
- : [];
2178
- args.attachments = [...existing, ...uploaded];
2179
- delete args.image;
2180
- delete args.file;
2181
- }
2182
- // Non-Design create_task --file: local files are uploaded and every
2183
- // value lands in file_urls — media_agent reference material (images /
2184
- // video / audio / documents), sheets CSV/Excel import.
2185
- if (tool.name === 'create_task' &&
2186
- args.task_type !== 'design' &&
2147
+ // task create / task continue --file: local files are uploaded and
2148
+ // every value lands in file_urls — media_agent reference material
2149
+ // (images / video / audio / documents), design references, sheets
2150
+ // CSV/Excel import, a new reference for a follow-up turn.
2151
+ if ((tool.name === 'create_task' || tool.name === 'task_continue') &&
2187
2152
  opts.file) {
2188
2153
  const fileValues = Array.isArray(opts.file)
2189
2154
  ? opts.file
@@ -2497,6 +2462,7 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
2497
2462
  }
2498
2463
  // If -o was specified and tool succeeded, download the output file.
2499
2464
  // Skip for create_task — it has its own export logic below.
2465
+ let downloadFailure;
2500
2466
  if (tool.name !== 'create_task' &&
2501
2467
  outputFilePath &&
2502
2468
  outputFileKeys.length > 0 &&
@@ -2505,8 +2471,7 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
2505
2471
  typeof result.data === 'object') {
2506
2472
  const fileUrl = extractFileUrl(result.data, outputFileKeys);
2507
2473
  if (fileUrl) {
2508
- const localPath = await downloadToFile(fileUrl, outputFilePath, client);
2509
- result.data.local_path = localPath;
2474
+ downloadFailure = await saveResultFile(fileUrl, outputFilePath, client, result);
2510
2475
  }
2511
2476
  else {
2512
2477
  info('Warning: Could not find a file URL in the result to download');
@@ -2526,23 +2491,24 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
2526
2491
  const taskType = args.type;
2527
2492
  if (projectId && taskType) {
2528
2493
  info(`Exporting ${taskType} artifact...`);
2494
+ let exportResult;
2529
2495
  try {
2530
- const exportResult = await client.exportArtifact(projectId, taskType);
2531
- if (exportResult.status === 'ok' && exportResult.data) {
2532
- const expData = exportResult.data;
2533
- const downloadUrl = expData.download_url;
2534
- if (downloadUrl) {
2535
- const localPath = await downloadToFile(downloadUrl, outputFilePath, client);
2536
- data.local_path = localPath;
2537
- data.export_format = expData.format;
2538
- }
2539
- }
2540
- else {
2541
- info(`Warning: Export not available — ${exportResult.message || 'unknown error'}`);
2542
- }
2496
+ exportResult = await client.exportArtifact(projectId, taskType);
2543
2497
  }
2544
2498
  catch (exportErr) {
2545
- info(`Warning: Export failed — ${exportErr.message}`);
2499
+ const reason = exportErr instanceof Error ? exportErr.message : String(exportErr);
2500
+ info(`Warning: Export failed — ${reason}`);
2501
+ }
2502
+ if (exportResult?.status === 'ok' && exportResult.data) {
2503
+ const expData = exportResult.data;
2504
+ const downloadUrl = expData.download_url;
2505
+ if (downloadUrl) {
2506
+ data.export_format = expData.format;
2507
+ downloadFailure = await saveResultFile(downloadUrl, outputFilePath, client, result);
2508
+ }
2509
+ }
2510
+ else if (exportResult) {
2511
+ info(`Warning: Export not available — ${exportResult.message || 'unknown error'}`);
2546
2512
  }
2547
2513
  }
2548
2514
  }
@@ -2571,6 +2537,10 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
2571
2537
  // payloads stay one line even on a terminal so a `grep | head` can
2572
2538
  // never split the URL list (PR #41690).
2573
2539
  output(result, { compact: Boolean(mediaItemsKeyFor(tool.name)) });
2540
+ if (downloadFailure) {
2541
+ logError(downloadFailureMessage(downloadFailure));
2542
+ process.exitCode = LOCAL_SAVE_FAILED_EXIT_CODE;
2543
+ }
2574
2544
  }
2575
2545
  catch (err) {
2576
2546
  logError(err.message);
@@ -2739,11 +2709,31 @@ program
2739
2709
  if (opts.save) {
2740
2710
  const { developerInputDownload } = await import('./commands/developer-input.js');
2741
2711
  const download = developerInputDownload(result.data.download_url, getGlobalOptions().baseUrl, getGlobalOptions().apiKey || '');
2742
- const resp = await fetch(download.url, download.init);
2743
- if (!resp.ok)
2744
- throw new Error(`Download failed: HTTP ${resp.status}`);
2745
- const buffer = Buffer.from(await resp.arrayBuffer());
2746
- fs.writeFileSync(opts.save, buffer);
2712
+ let sizeBytes;
2713
+ try {
2714
+ const resp = await fetch(download.url, download.init);
2715
+ if (!resp.ok)
2716
+ throw new Error(`Download failed: HTTP ${resp.status}`);
2717
+ if (!resp.body)
2718
+ throw new Error('Download failed: empty response body');
2719
+ await writeBodyToFile(resp.body, opts.save);
2720
+ sizeBytes = fs.statSync(opts.save).size;
2721
+ }
2722
+ catch (err) {
2723
+ // Keep the resolved URL: it is what a retry (or curl) needs.
2724
+ const reason = err instanceof Error ? err.message : String(err);
2725
+ output({
2726
+ status: 'error',
2727
+ message: `Saving to ${pathModule.resolve(opts.save)} failed: ${reason}`,
2728
+ data: {
2729
+ file_name: result.data.file_name,
2730
+ content_type: result.data.content_type,
2731
+ download_url: result.data.download_url,
2732
+ output_file: pathModule.resolve(opts.save),
2733
+ },
2734
+ });
2735
+ process.exit(1);
2736
+ }
2747
2737
  // Report only what the save produced: `download_url` is the CLI's
2748
2738
  // own fetch handle (a ~400-char signed URL) and `original_url` is
2749
2739
  // the argument the caller just passed. Agents re-read every echoed
@@ -2755,7 +2745,7 @@ program
2755
2745
  file_name: result.data.file_name,
2756
2746
  content_type: result.data.content_type,
2757
2747
  local_path: pathModule.resolve(opts.save),
2758
- size_bytes: buffer.length,
2748
+ size_bytes: sizeBytes,
2759
2749
  },
2760
2750
  });
2761
2751
  }
@@ -3567,6 +3557,8 @@ taskCmd
3567
3557
  .option('-o, --output-file <path>', 'save the exported file to this path')
3568
3558
  .action(async (projectId, opts) => {
3569
3559
  try {
3560
+ if (opts.outputFile !== undefined)
3561
+ preflightOutputFile(opts.outputFile);
3570
3562
  const client = createClient();
3571
3563
  const statusResult = await client.executeTool('task_status', {
3572
3564
  id: projectId,
@@ -3590,7 +3582,12 @@ taskCmd
3590
3582
  if (exportResult.status === 'ok' && expData && opts.outputFile) {
3591
3583
  const downloadUrl = expData.download_url;
3592
3584
  if (downloadUrl) {
3593
- expData.local_path = await downloadToFile(downloadUrl, opts.outputFile, client);
3585
+ const failure = await saveResultFile(downloadUrl, opts.outputFile, client, exportResult);
3586
+ if (failure) {
3587
+ output(exportResult);
3588
+ logError(downloadFailureMessage(failure));
3589
+ process.exit(LOCAL_SAVE_FAILED_EXIT_CODE);
3590
+ }
3594
3591
  }
3595
3592
  else {
3596
3593
  // The converter can report ok with an empty URL (e.g. the