@genspark/cli 1.6.2 → 1.7.1

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
@@ -394,12 +394,19 @@ gsk transcribe -i ./meeting.wav -m "whisper-large-v3"
394
394
 
395
395
  ### aidrive (alias: `drive`)
396
396
 
397
- AI-Drive file storage and management. List, create, delete, move files and directories. Download videos, audio, and files from URLs directly to AI-Drive.
397
+ AI-Drive file storage and management. Canonical workspaces are `my_drive`,
398
+ `shared_with_me`, and `shared_drive`. Run `ls` on a shared workspace first, then pass
399
+ the returned stable `source_id` to work inside one source. `shared_with_me` is
400
+ an ACL-filtered view and does not own bytes or quota.
398
401
 
399
402
  ```bash
400
403
  # List files in root directory
401
- gsk drive ls
402
- gsk drive ls -p "/documents" -f file
404
+ gsk drive ls --workspace my_drive
405
+ gsk drive ls --workspace my_drive -p "/documents" -f file
406
+
407
+ # Discover and read a source shared with you
408
+ gsk drive ls --workspace shared_with_me
409
+ gsk drive ls --workspace shared_with_me --source "<source_id>"
403
410
 
404
411
  # Create directory
405
412
  gsk drive mkdir -p "/my-folder"
@@ -407,10 +414,13 @@ gsk drive mkdir -p "/my-folder"
407
414
  # Move file
408
415
  gsk drive move -p "/old-path/file.txt" --target_path "/new-path/file.txt"
409
416
 
410
- # Download video/audio/file to AI-Drive
417
+ # Download an external video/audio/file into AI-Drive (the "download for me" actions)
411
418
  gsk drive download_video --video_url "https://example.com/video.mp4" --target_folder "/videos"
412
419
  gsk drive download_file --file_url "https://example.com/doc.pdf" --target_folder "/docs"
413
420
 
421
+ # Download an AI-Drive file to the local machine
422
+ gsk drive download "/docs/report.pdf" ./report.pdf
423
+
414
424
  # Upload inline text content to AI-Drive
415
425
  gsk drive upload --file_content "Hello World" --upload_path "/notes/hello.txt"
416
426
 
@@ -427,15 +437,17 @@ gsk drive get_readable_url -p "/documents/report.pdf"
427
437
 
428
438
  | Option | Default | Description |
429
439
  |--------|---------|-------------|
440
+ | `--workspace <name>` | `my_drive` | `my_drive`, `shared_with_me`, or `shared_drive` |
441
+ | `--source <id>` | — | Stable source ID returned by listing a shared workspace |
430
442
  | `-p, --path <path>` | — | File or directory path in AI-Drive |
431
443
  | `-f, --filter_type <type>` | `all` | Filter: `all`, `file`, `directory` |
432
444
  | `--file_type <type>` | `all` | File type filter: `all`, `audio`, `video`, `image` |
433
445
  | `--target_path <path>` | — | Target path for move operations |
434
- | `--target_folder <path>` | — | Target folder for downloads |
435
- | `--video_url <url>` | — | Video URL for download_video action |
436
- | `--audio_url <url>` | — | Audio URL for download_audio action |
437
- | `--file_url <url>` | — | File URL for download_file action |
438
- | `--file_name <name>` | — | Custom file name for downloads |
446
+ | `--target_folder <path>` | — | Target folder for `download_video`, `download_audio`, or `download_file` |
447
+ | `--video_url <url>` | — | External video URL for `download_video` |
448
+ | `--audio_url <url>` | — | External audio/video URL for `download_audio` |
449
+ | `--file_url <url>` | — | External file URL for `download_file` |
450
+ | `--file_name <name>` | — | Custom filename for `download_file` |
439
451
  | `--file_content <text>` | — | Inline text content to upload |
440
452
  | `--local_file <path>` | — | Local file path to upload directly to AI-Drive (streaming, no size limit) |
441
453
  | `--upload_path <path>` | — | Destination path for upload (defaults to `/<filename>` for `--local_file`) |
@@ -0,0 +1,30 @@
1
+ import type { ApiResponse } from '../types.js';
2
+ /**
3
+ * Name the operands of `gsk aidrive download <ai-drive-path> [local-path]`:
4
+ * first is the source, second the destination. With `explicitDrivePath` from
5
+ * `--path`/`-p`, the first operand is the destination instead.
6
+ */
7
+ export declare function resolveAidriveDownloadOperands(operands: readonly string[], explicitDrivePath?: string): {
8
+ drivePath?: string;
9
+ localPath?: string;
10
+ };
11
+ /**
12
+ * Accept either spelling of an AI-Drive location — `aidrive:///a/b.pdf` (how
13
+ * attachments arrive) or the plain `/a/b.pdf` — and return the plain path the
14
+ * API takes. A path without the scheme passes through untouched.
15
+ */
16
+ export declare function normalizeDrivePath(pathOrUrl: string): string;
17
+ /**
18
+ * Pull the signed download URL out of a `get_readable_url` response.
19
+ * `data.result` is prose ("Readable URL for <path>: <url>") and not meant to
20
+ * be parsed; the structured value lives in `session_state.aidrive_result`.
21
+ */
22
+ export declare function extractReadableUrl(response: Pick<ApiResponse, 'status' | 'session_state'>): string | undefined;
23
+ /**
24
+ * A file-wrapper URL carrying its own access token is already the final,
25
+ * fetchable URL. Sending it through `/file/download` re-checks ownership and
26
+ * incorrectly rejects files the caller may read through a Drive share.
27
+ * Token-less wrapper URLs still need the resolver used by other CLI exports.
28
+ */
29
+ export declare function shouldResolveFileWrapperUrl(url: string): boolean;
30
+ //# sourceMappingURL=aidrive-download.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aidrive-download.d.ts","sourceRoot":"","sources":["../../src/commands/aidrive-download.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAE9C;;;;GAIG;AACH,wBAAgB,8BAA8B,CAC5C,QAAQ,EAAE,SAAS,MAAM,EAAE,EAC3B,iBAAiB,CAAC,EAAE,MAAM,GACzB;IAAE,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,CAQ5C;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAG5D;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,IAAI,CAAC,WAAW,EAAE,QAAQ,GAAG,eAAe,CAAC,GACtD,MAAM,GAAG,SAAS,CAMpB;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAOhE"}
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Name the operands of `gsk aidrive download <ai-drive-path> [local-path]`:
3
+ * first is the source, second the destination. With `explicitDrivePath` from
4
+ * `--path`/`-p`, the first operand is the destination instead.
5
+ */
6
+ export function resolveAidriveDownloadOperands(operands, explicitDrivePath) {
7
+ const bareOperands = operands.filter(operand => operand.length > 0 && !operand.startsWith('-'));
8
+ if (explicitDrivePath) {
9
+ return { drivePath: explicitDrivePath, localPath: bareOperands[0] };
10
+ }
11
+ return { drivePath: bareOperands[0], localPath: bareOperands[1] };
12
+ }
13
+ /**
14
+ * Accept either spelling of an AI-Drive location — `aidrive:///a/b.pdf` (how
15
+ * attachments arrive) or the plain `/a/b.pdf` — and return the plain path the
16
+ * API takes. A path without the scheme passes through untouched.
17
+ */
18
+ export function normalizeDrivePath(pathOrUrl) {
19
+ // The scheme normally carries an empty host, hence the slash run.
20
+ return pathOrUrl.replace(/^aidrive:\/+/, '/');
21
+ }
22
+ /**
23
+ * Pull the signed download URL out of a `get_readable_url` response.
24
+ * `data.result` is prose ("Readable URL for <path>: <url>") and not meant to
25
+ * be parsed; the structured value lives in `session_state.aidrive_result`.
26
+ */
27
+ export function extractReadableUrl(response) {
28
+ if (response.status !== 'ok')
29
+ return undefined;
30
+ const aidriveResult = response.session_state?.aidrive_result;
31
+ if (!aidriveResult || typeof aidriveResult !== 'object')
32
+ return undefined;
33
+ const url = aidriveResult.readable_url;
34
+ return typeof url === 'string' && url ? url : undefined;
35
+ }
36
+ /**
37
+ * A file-wrapper URL carrying its own access token is already the final,
38
+ * fetchable URL. Sending it through `/file/download` re-checks ownership and
39
+ * incorrectly rejects files the caller may read through a Drive share.
40
+ * Token-less wrapper URLs still need the resolver used by other CLI exports.
41
+ */
42
+ export function shouldResolveFileWrapperUrl(url) {
43
+ if (!url.includes('/api/files/'))
44
+ return false;
45
+ try {
46
+ return !new URL(url, 'https://local.invalid').searchParams.has('token');
47
+ }
48
+ catch {
49
+ return true;
50
+ }
51
+ }
52
+ //# sourceMappingURL=aidrive-download.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aidrive-download.js","sourceRoot":"","sources":["../../src/commands/aidrive-download.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,MAAM,UAAU,8BAA8B,CAC5C,QAA2B,EAC3B,iBAA0B;IAE1B,MAAM,YAAY,GAAG,QAAQ,CAAC,MAAM,CAClC,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAC1D,CAAA;IACD,IAAI,iBAAiB,EAAE,CAAC;QACtB,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,SAAS,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,CAAA;IACrE,CAAC;IACD,OAAO,EAAE,SAAS,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,CAAA;AACnE,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,SAAiB;IAClD,kEAAkE;IAClE,OAAO,SAAS,CAAC,OAAO,CAAC,cAAc,EAAE,GAAG,CAAC,CAAA;AAC/C,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAChC,QAAuD;IAEvD,IAAI,QAAQ,CAAC,MAAM,KAAK,IAAI;QAAE,OAAO,SAAS,CAAA;IAC9C,MAAM,aAAa,GAAG,QAAQ,CAAC,aAAa,EAAE,cAAc,CAAA;IAC5D,IAAI,CAAC,aAAa,IAAI,OAAO,aAAa,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAA;IACzE,MAAM,GAAG,GAAI,aAAyC,CAAC,YAAY,CAAA;IACnE,OAAO,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAA;AACzD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,2BAA2B,CAAC,GAAW;IACrD,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,aAAa,CAAC;QAAE,OAAO,KAAK,CAAA;IAC9C,IAAI,CAAC;QACH,OAAO,CAAC,IAAI,GAAG,CAAC,GAAG,EAAE,uBAAuB,CAAC,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;IACzE,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAA;IACb,CAAC;AACH,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;GAkBG;AA0QH,KAAK,oBAAoB,GAAG,kBAAkB,GAAG,SAAS,GAAG,SAAS,CAAA;AAEtE,UAAU,mBAAmB;IAC3B,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,oBAAoB,CAAA;CAC3B;AAED,kFAAkF;AAClF,wBAAgB,2BAA2B,CACzC,IAAI,EAAE,MAAM,EAAE,GACb,mBAAmB,EAAE,CAqBvB"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;GAkBG;AAkRH,KAAK,oBAAoB,GAAG,kBAAkB,GAAG,SAAS,GAAG,SAAS,CAAA;AAEtE,UAAU,mBAAmB;IAC3B,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,oBAAoB,CAAA;CAC3B;AAED,kFAAkF;AAClF,wBAAgB,2BAA2B,CACzC,IAAI,EAAE,MAAM,EAAE,GACb,mBAAmB,EAAE,CAqBvB"}
package/dist/index.js CHANGED
@@ -26,6 +26,8 @@ import * as os from 'os';
26
26
  import * as pathModule from 'path';
27
27
  import { createRequire } from 'module';
28
28
  import { spawn } from 'child_process';
29
+ import { Readable } from 'stream';
30
+ import { pipeline } from 'stream/promises';
29
31
  import { ApiClient, isAuthError, unauthenticatedRequest, } from './client.js';
30
32
  import { classifyFileArg, awaitLocalFileReady, decideAfterWait, localFileNotReadyError, passthroughWarning, urlsParamItems, } from './localFiles.js';
31
33
  import { setDebugEnabled, setOutputFormat, debug, info, warn, error as logError, output, } from './logger.js';
@@ -36,6 +38,7 @@ import { shimLegacyTaskInvocation } from './task-shim.js';
36
38
  import { getSandboxRuntime } from './runtime.js';
37
39
  import { registerDesignCommand } from './commands/design.js';
38
40
  import { collectUploadFiles, pickExistingUploadOperand, } from './commands/aidrive-upload.js';
41
+ import { resolveAidriveDownloadOperands, normalizeDrivePath, extractReadableUrl, shouldResolveFileWrapperUrl, } from './commands/aidrive-download.js';
39
42
  import { parseLastSeenIndex, eventStdoutLine } from './commands/chat-events.js';
40
43
  import { mediaItemsKeyFor, mediaSummaryLines } from './mediaSummary.js';
41
44
  import { registerMeshCommand, getMeshInvocation, runMesh, } from './commands/mesh.js';
@@ -321,6 +324,8 @@ async function streamFileUpload(filePath, uploadUrl, headers, fileSize, method =
321
324
  });
322
325
  }
323
326
  function formatFileSize(bytes) {
327
+ if (bytes >= 1024 ** 3)
328
+ return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
324
329
  if (bytes >= 1024 * 1024)
325
330
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
326
331
  return `${(bytes / 1024).toFixed(1)} KB`;
@@ -354,7 +359,7 @@ async function uploadLocalFile(filePath, client) {
354
359
  *
355
360
  * This avoids the roundabout blob-upload + download_file two-step approach.
356
361
  */
357
- async function uploadToAiDrive(filePath, uploadPath, override = false, workspace = 'personal') {
362
+ async function uploadToAiDrive(filePath, uploadPath, override = false, workspace = 'my_drive', source) {
358
363
  const fileName = pathModule.basename(filePath);
359
364
  const ext = pathModule.extname(filePath).toLowerCase();
360
365
  const contentType = CONTENT_TYPE_MAP[ext] || 'application/octet-stream';
@@ -362,7 +367,15 @@ async function uploadToAiDrive(filePath, uploadPath, override = false, workspace
362
367
  info(`Uploading ${fileName} (${formatFileSize(fileSize)}, ${contentType}) directly to AI Drive...`);
363
368
  const globalOpts = getGlobalOptions();
364
369
  const baseUrl = globalOpts.baseUrl.replace(/\/$/, '');
365
- const uploadUrl = `${baseUrl}/api/tool_cli/aidrive/upload?upload_path=${encodeURIComponent(uploadPath)}&workspace=${encodeURIComponent(workspace)}${override ? '&override=true' : ''}`;
370
+ const uploadQuery = new URLSearchParams({
371
+ upload_path: uploadPath,
372
+ workspace,
373
+ });
374
+ if (override)
375
+ uploadQuery.set('override', 'true');
376
+ if (source)
377
+ uploadQuery.set('source', source);
378
+ const uploadUrl = `${baseUrl}/api/tool_cli/aidrive/upload?${uploadQuery.toString()}`;
366
379
  const headers = { 'Content-Type': contentType };
367
380
  if (globalOpts.apiKey)
368
381
  headers['X-Api-Key'] = globalOpts.apiKey;
@@ -380,8 +393,10 @@ async function uploadToAiDrive(filePath, uploadPath, override = false, workspace
380
393
  async function downloadToFile(url, savePath, client) {
381
394
  info(`Downloading to ${savePath}...`);
382
395
  let downloadUrl = url;
383
- // File wrapper URLs need to be resolved via /file/download first
384
- if (url.includes('/api/files/')) {
396
+ // Token-less file wrappers need `/file/download`; a signed wrapper is
397
+ // already fetchable and must keep its share token (important for Drive
398
+ // files whose storage owner is not the caller).
399
+ if (shouldResolveFileWrapperUrl(url)) {
385
400
  const result = await client.getDownloadUrl({ file_wrapper_url: url });
386
401
  if (result.status !== 'ok' || !result.data)
387
402
  throw new Error(`Failed to get download URL: ${result.message}`);
@@ -390,9 +405,13 @@ async function downloadToFile(url, savePath, client) {
390
405
  const resp = await fetch(downloadUrl);
391
406
  if (!resp.ok)
392
407
  throw new Error(`Download failed: HTTP ${resp.status}`);
393
- const buffer = Buffer.from(await resp.arrayBuffer());
394
- fs.writeFileSync(savePath, buffer);
395
- info(`Downloaded ${(buffer.length / 1024).toFixed(1)} KB → ${savePath}`);
408
+ if (!resp.body)
409
+ throw new Error('Download failed: empty response body');
410
+ // Stream to disk: AI-Drive reads reach GB scale, past what the sandbox's
411
+ // swap-less RAM tolerates as a single buffer.
412
+ await pipeline(Readable.fromWeb(resp.body), fs.createWriteStream(savePath));
413
+ const sizeBytes = fs.statSync(savePath).size;
414
+ info(`Downloaded ${formatFileSize(sizeBytes)} → ${savePath}`);
396
415
  return pathModule.resolve(savePath);
397
416
  }
398
417
  function isLocalFilePath(value) {
@@ -818,12 +837,15 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
818
837
  cmd.option('--image <values...>', 'Design only: append ordered local visual references');
819
838
  cmd.option('--file <values...>', 'Design only: append ordered local context files');
820
839
  }
821
- // For the aidrive tool, add client-side options used with --local_file upload
840
+ // For the aidrive tool, add client-side options used by the --local_file
841
+ // upload and by `download`'s local destination.
822
842
  if (tool.name === 'aidrive') {
823
843
  if (!Object.hasOwn(props, 'workspace')) {
824
- cmd.option('--workspace <value>', 'AI Drive workspace: personal or public_brain');
844
+ cmd.option('--workspace <value>', 'AI Drive workspace: my_drive, shared_with_me, or shared_drive');
825
845
  }
826
- cmd.option('--local_file <path>', 'Local file path to upload to AI Drive (supports files >5 MB; alternative to --file_content)');
846
+ cmd.option('--local_file <path>', 'upload: local file path to upload to AI Drive (supports files >5 MB; ' +
847
+ 'alternative to --file_content). download: local destination path ' +
848
+ '(same as the second operand; default ./<basename of the drive path>)');
827
849
  cmd.option('--override', 'Overwrite an existing file at the destination path (used with --local_file)', false);
828
850
  }
829
851
  // For sb-git: `--execute [dest]` turns `clone-url` from a snippet-print
@@ -1191,6 +1213,78 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1191
1213
  process.exit(1);
1192
1214
  }
1193
1215
  }
1216
+ // Copy an AI-Drive file OUT to local disk. Client-side because only
1217
+ // this process can write the local filesystem: resolve the path to a
1218
+ // signed URL, then save it with the same streaming helper `-o` uses.
1219
+ // Never forwarded to the server, which answers a CLI too old to
1220
+ // intercept it with the two-call equivalent.
1221
+ if (tool.name === 'aidrive' && args.action === 'download') {
1222
+ const operandCandidates = primaryArgValue !== undefined && primaryArgValue === args.action
1223
+ ? invokedCmd.args.slice(1)
1224
+ : invokedCmd.args;
1225
+ const { drivePath: sourceOperand, localPath: operandDest } = resolveAidriveDownloadOperands(operandCandidates, typeof args.path === 'string' ? args.path : undefined);
1226
+ if (!sourceOperand) {
1227
+ logError('download needs the AI-Drive path: gsk aidrive download ' +
1228
+ '<ai-drive-path> [local-path] (or --path/-p). To save an ' +
1229
+ 'external url INTO AI Drive instead, use ' +
1230
+ '`download_file --file_url <url>`.');
1231
+ process.exit(1);
1232
+ }
1233
+ // Attachments arrive spelled `aidrive:///a/b.pdf`; take that as-is
1234
+ // rather than making the caller strip the scheme.
1235
+ const drivePath = normalizeDrivePath(sourceOperand);
1236
+ const urlResult = await client.executeTool('aidrive', {
1237
+ // Use the established wire spelling; both older backends and the
1238
+ // current canonical contract recognize it.
1239
+ action: 'get_readable_url',
1240
+ path: drivePath,
1241
+ workspace: args.workspace,
1242
+ source: args.source,
1243
+ share: args.share,
1244
+ });
1245
+ const readableUrl = extractReadableUrl(urlResult);
1246
+ if (!readableUrl) {
1247
+ logError(`Failed to resolve AI-Drive path ${drivePath}: ${urlResult.message}`);
1248
+ process.exit(1);
1249
+ }
1250
+ const destPath = (typeof opts.local_file === 'string' ? opts.local_file : '') ||
1251
+ operandDest ||
1252
+ pathModule.basename(drivePath);
1253
+ const savedPath = await downloadToFile(readableUrl, destPath, client);
1254
+ output({
1255
+ status: 'ok',
1256
+ message: 'AI-Drive file downloaded to local disk',
1257
+ data: { ai_drive_path: drivePath, local_path: savedPath },
1258
+ });
1259
+ return;
1260
+ }
1261
+ // `download_file` saves an external URL INTO the drive and cannot copy
1262
+ // one out, yet it is the obvious spelling for "download a drive file"
1263
+ // and both attempts used to fail silently: its handler never consumes
1264
+ // `path`, and an `aidrive://` --file_url fails the server's URL
1265
+ // validation (16 consecutive no-op calls observed in #52631). Name
1266
+ // `download` instead of letting either shape exit 0 having done
1267
+ // nothing.
1268
+ if (tool.name === 'aidrive' && args.action === 'download_file') {
1269
+ const fileUrl = typeof args.file_url === 'string' ? args.file_url : '';
1270
+ if (fileUrl.startsWith('aidrive://')) {
1271
+ logError('download_file saves an external URL INTO AI Drive; it cannot ' +
1272
+ 'copy one out. Use: gsk aidrive download ' +
1273
+ `${fileUrl} <local-path>`);
1274
+ process.exit(1);
1275
+ }
1276
+ if (!fileUrl) {
1277
+ const operandCandidates = primaryArgValue !== undefined && primaryArgValue === args.action
1278
+ ? invokedCmd.args.slice(1)
1279
+ : invokedCmd.args;
1280
+ const { drivePath } = resolveAidriveDownloadOperands(operandCandidates, typeof args.path === 'string' ? args.path : undefined);
1281
+ logError('download_file needs `--file_url <external-url>` — it saves an ' +
1282
+ 'external URL INTO AI Drive. To copy a drive file OUT to ' +
1283
+ 'local disk: gsk aidrive download ' +
1284
+ `${drivePath || '<ai-drive-path>'} <local-path>`);
1285
+ process.exit(1);
1286
+ }
1287
+ }
1194
1288
  // aidrive: handle --local_file for the upload action.
1195
1289
  // Stream the file directly to AI Drive via the dedicated tool_cli
1196
1290
  // endpoint (POST /api/tool_cli/aidrive/upload) — no blob middleman.
@@ -1199,7 +1293,9 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1199
1293
  opts.local_file) {
1200
1294
  const localFilePath = opts.local_file;
1201
1295
  const override = !!opts.override;
1202
- const workspace = args.workspace || 'personal';
1296
+ const workspace = args.workspace || 'my_drive';
1297
+ const source = args.source ||
1298
+ args.share;
1203
1299
  if (!fs.existsSync(localFilePath)) {
1204
1300
  logError(`File not found: ${localFilePath}`);
1205
1301
  process.exit(1);
@@ -1222,7 +1318,7 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1222
1318
  const uploaded = [];
1223
1319
  for (const file of files) {
1224
1320
  const destination = pathModule.posix.join(uploadPath, file.relativePath);
1225
- const result = await uploadToAiDrive(file.absolutePath, destination, override, workspace);
1321
+ const result = await uploadToAiDrive(file.absolutePath, destination, override, workspace, source);
1226
1322
  if (result.status !== 'ok') {
1227
1323
  output(result);
1228
1324
  process.exit(1);
@@ -1237,7 +1333,7 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1237
1333
  }
1238
1334
  else {
1239
1335
  // Stream directly to AI Drive — single request, no blob middleman
1240
- const result = await uploadToAiDrive(localFilePath, uploadPath, override, workspace);
1336
+ const result = await uploadToAiDrive(localFilePath, uploadPath, override, workspace, source);
1241
1337
  output(result);
1242
1338
  }
1243
1339
  return;
@@ -1667,7 +1763,8 @@ program
1667
1763
  program
1668
1764
  .command('login')
1669
1765
  .description('Log in to Genspark via browser to obtain an API key')
1670
- .action(async () => {
1766
+ .option('--no-open', 'Print the login URL without opening a browser')
1767
+ .action(async (loginOpts) => {
1671
1768
  const globalOpts = getGlobalOptions();
1672
1769
  setDebugEnabled(globalOpts.debug);
1673
1770
  setOutputFormat(globalOpts.output);
@@ -1677,44 +1774,52 @@ program
1677
1774
  info('Requesting device code...');
1678
1775
  const deviceResp = await unauthenticatedRequest(baseUrl, '/api/cli_auth/device_code', 'POST');
1679
1776
  const { device_code, auth_url, poll_interval, expires_in } = deviceResp;
1680
- // Step 2: Open browser (use spawn to avoid shell command injection)
1681
- info('Opening browser for login...');
1777
+ // Step 2: Open browser unless the caller explicitly opted out. Tests
1778
+ // and headless automation use --no-open so a mock URL never escapes
1779
+ // into the user's desktop session.
1780
+ if (loginOpts.open !== false)
1781
+ info('Opening browser for login...');
1682
1782
  info(`Login URL: ${auth_url}`);
1683
- // Validate auth_url is a same-origin HTTP(S) URL before passing to spawn
1684
- try {
1685
- const parsed = new URL(auth_url);
1686
- const base = new URL(baseUrl);
1687
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
1688
- throw new Error('auth_url is not http(s)');
1689
- }
1690
- if (parsed.host !== base.host) {
1691
- throw new Error('auth_url host does not match baseUrl host');
1692
- }
1693
- let cmd;
1694
- let args;
1695
- if (process.platform === 'win32') {
1696
- // Avoid cmd.exe which interprets & in URLs as command separators
1697
- cmd = 'rundll32';
1698
- args = ['url.dll,FileProtocolHandler', auth_url];
1699
- }
1700
- else if (process.platform === 'darwin') {
1701
- cmd = 'open';
1702
- args = [auth_url];
1703
- }
1704
- else {
1705
- cmd = 'xdg-open';
1706
- args = [auth_url];
1783
+ if (loginOpts.open === false) {
1784
+ info('Browser opening disabled; open the URL above manually.');
1785
+ }
1786
+ else {
1787
+ // Validate auth_url is a same-origin HTTP(S) URL before passing to spawn
1788
+ try {
1789
+ const parsed = new URL(auth_url);
1790
+ const base = new URL(baseUrl);
1791
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
1792
+ throw new Error('auth_url is not http(s)');
1793
+ }
1794
+ if (parsed.host !== base.host) {
1795
+ throw new Error('auth_url host does not match baseUrl host');
1796
+ }
1797
+ let cmd;
1798
+ let args;
1799
+ if (process.platform === 'win32') {
1800
+ // Avoid cmd.exe which interprets & in URLs as command separators
1801
+ cmd = 'rundll32';
1802
+ args = ['url.dll,FileProtocolHandler', auth_url];
1803
+ }
1804
+ else if (process.platform === 'darwin') {
1805
+ cmd = 'open';
1806
+ args = [auth_url];
1807
+ }
1808
+ else {
1809
+ cmd = 'xdg-open';
1810
+ args = [auth_url];
1811
+ }
1812
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
1813
+ child.on('error', () => {
1814
+ info('Could not open browser automatically.');
1815
+ info('Please open the URL above manually.');
1816
+ });
1817
+ child.unref();
1707
1818
  }
1708
- const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
1709
- child.on('error', () => {
1819
+ catch {
1710
1820
  info('Could not open browser automatically.');
1711
1821
  info('Please open the URL above manually.');
1712
- });
1713
- child.unref();
1714
- }
1715
- catch {
1716
- info('Could not open browser automatically.');
1717
- info('Please open the URL above manually.');
1822
+ }
1718
1823
  }
1719
1824
  info(`Waiting for authorization (expires in ${expires_in}s, press Ctrl+C to cancel)...`);
1720
1825
  // Step 3: Poll for token