@genspark/cli 1.13.0 → 1.14.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.
Files changed (39) hide show
  1. package/README.md +10 -7
  2. package/dist/client.d.ts +14 -0
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +62 -2
  5. package/dist/client.js.map +1 -1
  6. package/dist/commands/aidrive-operands.d.ts +29 -0
  7. package/dist/commands/aidrive-operands.d.ts.map +1 -0
  8. package/dist/commands/aidrive-operands.js +178 -0
  9. package/dist/commands/aidrive-operands.js.map +1 -0
  10. package/dist/commands/aidrive-upload.d.ts +149 -0
  11. package/dist/commands/aidrive-upload.d.ts.map +1 -1
  12. package/dist/commands/aidrive-upload.js +344 -0
  13. package/dist/commands/aidrive-upload.js.map +1 -1
  14. package/dist/commands/design.d.ts +9 -0
  15. package/dist/commands/design.d.ts.map +1 -1
  16. package/dist/commands/design.js +12 -2
  17. package/dist/commands/design.js.map +1 -1
  18. package/dist/commands/genteam-download.d.ts +34 -0
  19. package/dist/commands/genteam-download.d.ts.map +1 -0
  20. package/dist/commands/genteam-download.js +95 -0
  21. package/dist/commands/genteam-download.js.map +1 -0
  22. package/dist/config.d.ts +13 -0
  23. package/dist/config.d.ts.map +1 -1
  24. package/dist/config.js +18 -0
  25. package/dist/config.js.map +1 -1
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +477 -63
  28. package/dist/index.js.map +1 -1
  29. package/docs/skills.md +2 -2
  30. package/package.json +1 -1
  31. package/skills/gsk-aidrive/SKILL.md +232 -26
  32. package/skills/gsk-audio-generation/SKILL.md +1 -1
  33. package/skills/gsk-genteam/SKILL.md +3 -3
  34. package/skills/gsk-google-drive/SKILL.md +25 -6
  35. package/skills/gsk-google-sheets/SKILL.md +1 -1
  36. package/skills/gsk-meeting/SKILL.md +1 -0
  37. package/skills/gsk-second-brain/SKILL.md +87 -20
  38. package/skills/gsk-shared/SKILL.md +4 -2
  39. package/skills/gsk-slack/SKILL.md +10 -8
package/dist/index.js CHANGED
@@ -45,8 +45,10 @@ import { addRegisteredCommands, collectToolCommandTokens, staleCacheMissingToken
45
45
  import { shimLegacyTaskInvocation } from './task-shim.js';
46
46
  import { getSandboxRuntime } from './runtime.js';
47
47
  import { registerDesignCommand } from './commands/design.js';
48
- import { collectUploadFiles, pickExistingUploadOperand, buildAidriveUploadQuery, } from './commands/aidrive-upload.js';
48
+ import { collectUploadFiles, aidriveUploadHeaders, buildAidriveUploadQuery, mergeShareIntoUpload, normalizeUploadDestination, resolveAidriveUploadOperands, shareArgsFromUpload, uploadConflictFromCli, uploadConflictProblem, uploadPathForDestination, uploadShareRefusal, } from './commands/aidrive-upload.js';
49
+ import { aidriveOperandArgs } from './commands/aidrive-operands.js';
49
50
  import { resolveAidriveDownloadOperands, normalizeDrivePath, extractReadableUrl, shouldResolveFileWrapperUrl, } from './commands/aidrive-download.js';
51
+ import { fileNameFromContentDisposition, genteamAttachmentEndpoint, resolveGenteamDownloadDestination, saveBodyToFile, } from './commands/genteam-download.js';
50
52
  import { parseLastSeenIndex, eventStdoutLine } from './commands/chat-events.js';
51
53
  import { defaultPiAgentDir, mergePiModelsConfig, mergePiSettingsConfig, readJsonIfExists, resolvePiAgentDir, writeJsonFile, } from './commands/pi-config.js';
52
54
  import { mediaItemsKeyFor, mediaSummaryLines } from './mediaSummary.js';
@@ -57,6 +59,8 @@ const require = createRequire(import.meta.url);
57
59
  const { version: VERSION } = require('../package.json');
58
60
  const DEFAULT_BASE_URL = 'https://www.genspark.ai';
59
61
  const DEFAULT_TIMEOUT = 1800000; // 30 minutes (slides/video generation can be slow)
62
+ const GENTEAM_DOWNLOAD_LOCAL_FILE_HELP = 'download: local destination path (same as a bare operand; a directory ' +
63
+ 'receives the server-reported file name; default ./<file_name>)';
60
64
  /**
61
65
  * Resolve a custom config path from process.env / process.argv before
62
66
  * Commander has had a chance to parse flags. We peek at argv directly
@@ -89,6 +93,14 @@ const fileConfig = loadConfigFile();
89
93
  const program = new Command();
90
94
  program
91
95
  .name('gsk')
96
+ // Root options are parsed only BEFORE the subcommand name; everything
97
+ // after it belongs to the subcommand. Without this, Commander let the
98
+ // root swallow same-named flags from anywhere on the line: `gsk sb-box
99
+ // create --timeout 600` became a 600 ms request timeout and `gsk sb-box
100
+ // resume --version 2` printed the CLI version (2026-09-20). The globals
101
+ // people are used to writing after a tool name keep working through the
102
+ // pass-through copies each tool command registers (addGlobalPassthroughOptions).
103
+ .enablePositionalOptions()
92
104
  .description('Genspark Tool CLI - Search, crawl, analyze, and generate media')
93
105
  // Agents drive this CLI blind (no schema in context): on a bad invocation,
94
106
  // print the full usage + a did-you-mean hint so the caller can self-correct
@@ -116,8 +128,170 @@ program
116
128
  * 2. Environment variables
117
129
  * 3. Config file (~/.genspark-tool-cli/config.json) (lowest)
118
130
  */
131
+ // Global options accepted AFTER a tool subcommand. In positional-options
132
+ // mode the root only sees flags written before the subcommand name, so every
133
+ // dynamic tool command (and each per-action subcommand) re-registers these
134
+ // as hidden pass-through options; runToolInvocation records the values that
135
+ // arrived that way and getGlobalOptions overlays them on the root's. A tool's
136
+ // own parameter with the same flag always wins (sb-box's `--timeout` is
137
+ // seconds of sandbox lifetime, not a request timeout). `--version`,
138
+ // `--refresh` and `--config` stay root-only: version prints and exits, the
139
+ // other two act before the subcommands exist (tools cache, config file).
140
+ const PASSTHROUGH_GLOBALS = [
141
+ { flags: '--api-key <key>', key: 'apiKey' },
142
+ { flags: '--base-url <url>', key: 'baseUrl' },
143
+ { flags: '--project-id <id>', key: 'projectId' },
144
+ { flags: '--debug', key: 'debug', toolParam: 'debug' },
145
+ { flags: '--timeout <ms>', key: 'timeout', toolParam: 'timeout' },
146
+ { flags: '--output <format>', key: 'output', toolParam: 'output' },
147
+ { flags: '--no-input', key: 'input', toolParam: 'input' },
148
+ { flags: '-y, --yes', key: 'yes', toolParam: 'yes' },
149
+ // Accepted after the tool name for compatibility (`gsk list-tools
150
+ // --refresh`, `gsk foo --config p`); they act at startup, where the early
151
+ // scan below already picked them up, so post-parse they are no-ops.
152
+ { flags: '--refresh', key: 'refresh', toolParam: 'refresh' },
153
+ { flags: '--config <path>', key: 'config', toolParam: 'config' },
154
+ ];
155
+ const passthroughKeysByCommand = new WeakMap();
156
+ let activePassthroughOpts = {};
157
+ function addGlobalPassthroughOptions(command, toolProps) {
158
+ const keys = [];
159
+ for (const g of PASSTHROUGH_GLOBALS) {
160
+ if (g.toolParam && toolProps[g.toolParam] !== undefined)
161
+ continue;
162
+ const parts = g.flags.split(',').map(f => f.trim());
163
+ const long = parts[parts.length - 1].split(' ')[0];
164
+ const short = parts.length > 1 ? parts[0].split(' ')[0] : undefined;
165
+ const taken = command.options.some(o => o.long === long || (short !== undefined && o.short === short));
166
+ if (taken)
167
+ continue;
168
+ command.addOption(new Option(g.flags).hideHelp());
169
+ keys.push(g.key);
170
+ }
171
+ passthroughKeysByCommand.set(command, keys);
172
+ }
173
+ // Pass-through values the given commands received on the command line
174
+ // (source 'cli' only — a Commander default is not a user choice).
175
+ function collectPassthrough(...commands) {
176
+ const out = {};
177
+ for (const c of commands) {
178
+ const keys = passthroughKeysByCommand.get(c) ?? [];
179
+ const o = c.opts();
180
+ for (const k of keys) {
181
+ if (o[k] !== undefined && c.getOptionValueSource(k) === 'cli')
182
+ out[k] = o[k];
183
+ }
184
+ }
185
+ return out;
186
+ }
187
+ function passthroughKeysOf(...commands) {
188
+ return commands.flatMap(c => passthroughKeysByCommand.get(c) ?? []);
189
+ }
190
+ // Root options that take a value — the pre-parse must skip their values
191
+ // when looking for the first operand (the subcommand name).
192
+ const ROOT_VALUE_OPTIONS = new Set([
193
+ '--api-key',
194
+ '--base-url',
195
+ '--project-id',
196
+ '--timeout',
197
+ '--output',
198
+ '--config',
199
+ ]);
200
+ // Root flags that are unambiguous ANYWHERE on the line: no tool parameter
201
+ // can produce these kebab-case flags (tool parameters are snake_case), so
202
+ // `gsk search q --api-key K`, `gsk list-tools --refresh` and `gsk crawl u
203
+ // --output json` keep meaning what they always meant, and the startup
204
+ // pre-parse (manifest fetch, output format, debug) sees them wherever they
205
+ // sit. `--timeout` and `--version` are NOT in this set: tools own them after
206
+ // the subcommand name.
207
+ const ROOT_FLAGS_ANYWHERE_VALUE = new Set([
208
+ '--api-key',
209
+ '--base-url',
210
+ '--project-id',
211
+ '--output',
212
+ '--config',
213
+ ]);
214
+ const ROOT_FLAGS_ANYWHERE_BOOL = new Set(['--refresh', '--debug']);
215
+ // The argv slice the ROOT may pre-parse: everything before the first
216
+ // operand, plus the unambiguous root flags from the rest of the line. The
217
+ // startup pre-parse runs before the tool subcommands exist, so Commander
218
+ // cannot stop at the subcommand name by itself — without this cut it read
219
+ // `--version` / `--timeout` from anywhere on the line (2026-09-20).
220
+ function rootArgvPrefix(argv) {
221
+ const picked = [];
222
+ let afterOperand = false;
223
+ for (let i = 0; i < argv.length; i++) {
224
+ const arg = argv[i];
225
+ if (!arg.startsWith('-') || arg === '-') {
226
+ afterOperand = true;
227
+ continue;
228
+ }
229
+ const [flag] = arg.split('=', 1);
230
+ const takesValue = ROOT_VALUE_OPTIONS.has(flag);
231
+ if (!afterOperand) {
232
+ picked.push(arg);
233
+ if (takesValue && !arg.includes('=') && i + 1 < argv.length) {
234
+ picked.push(argv[++i]);
235
+ }
236
+ continue;
237
+ }
238
+ if (ROOT_FLAGS_ANYWHERE_BOOL.has(flag)) {
239
+ picked.push(arg);
240
+ }
241
+ else if (ROOT_FLAGS_ANYWHERE_VALUE.has(flag)) {
242
+ picked.push(arg);
243
+ if (!arg.includes('=') && i + 1 < argv.length)
244
+ picked.push(argv[++i]);
245
+ }
246
+ else if (takesValue && !arg.includes('=')) {
247
+ i++; // a root-looking value option that tools may own (--timeout): skip its value too
248
+ }
249
+ }
250
+ return picked;
251
+ }
252
+ // Option-stripped positional view of argv for the stale-cache check: drop
253
+ // every `-flag`, plus the value of the root options that take one. Only the
254
+ // first two operands are ever consulted (command, subcommand), so a tool
255
+ // flag's value counted as a later operand is harmless.
256
+ function operandsForStaleCheck(argv) {
257
+ const operands = [];
258
+ for (let i = 0; i < argv.length; i++) {
259
+ const arg = argv[i];
260
+ if (arg.startsWith('-') && arg !== '-') {
261
+ if (ROOT_VALUE_OPTIONS.has(arg))
262
+ i++;
263
+ continue;
264
+ }
265
+ operands.push(arg);
266
+ }
267
+ return operands;
268
+ }
269
+ // Give every command that has none yet (the static ones: hosted, login,
270
+ // design, …) the pass-through globals, and record the active command's
271
+ // pass-through values before any action runs. Called once, right before
272
+ // program.parseAsync().
273
+ let passthroughFinalized = false;
274
+ function finalizeGlobalPassthrough() {
275
+ if (passthroughFinalized)
276
+ return;
277
+ passthroughFinalized = true;
278
+ const visit = (c) => {
279
+ if (!passthroughKeysByCommand.has(c))
280
+ addGlobalPassthroughOptions(c, {});
281
+ for (const child of c.commands)
282
+ visit(child);
283
+ };
284
+ for (const child of program.commands)
285
+ visit(child);
286
+ program.hook('preAction', (_thisCommand, actionCommand) => {
287
+ const chain = [];
288
+ for (let c = actionCommand; c; c = c.parent)
289
+ chain.push(c);
290
+ activePassthroughOpts = collectPassthrough(...chain);
291
+ });
292
+ }
119
293
  function getGlobalOptions() {
120
- const opts = program.opts();
294
+ const opts = { ...program.opts(), ...activePassthroughOpts };
121
295
  // API key priority: CLI > env > config file
122
296
  const apiKey = opts.apiKey || process.env.GSK_API_KEY || fileConfig.api_key;
123
297
  // Base URL priority: CLI > env > config file > default
@@ -376,7 +550,7 @@ async function uploadLocalFile(filePath, client) {
376
550
  *
377
551
  * This avoids the roundabout blob-upload + download_file two-step approach.
378
552
  */
379
- async function uploadToAiDrive(filePath, uploadPath, override = false, workspace = 'my_drive', source, onConflict, locator) {
553
+ async function uploadToAiDrive(filePath, uploadPath, workspace = 'my_drive', source, onConflict, locator) {
380
554
  const fileName = pathModule.basename(filePath);
381
555
  const ext = pathModule.extname(filePath).toLowerCase();
382
556
  const contentType = CONTENT_TYPE_MAP[ext] || 'application/octet-stream';
@@ -387,17 +561,16 @@ async function uploadToAiDrive(filePath, uploadPath, override = false, workspace
387
561
  const uploadQuery = buildAidriveUploadQuery({
388
562
  uploadPath,
389
563
  workspace,
390
- override,
391
564
  onConflict,
392
565
  source,
393
566
  locator,
394
567
  });
395
568
  const uploadUrl = `${baseUrl}/api/tool_cli/aidrive/upload?${uploadQuery.toString()}`;
396
- const headers = { 'Content-Type': contentType };
397
- if (globalOpts.apiKey)
398
- headers['X-Api-Key'] = globalOpts.apiKey;
399
- if (globalOpts.projectId)
400
- headers['X-Project-ID'] = globalOpts.projectId;
569
+ const headers = aidriveUploadHeaders({
570
+ apiKey: globalOpts.apiKey,
571
+ projectId: globalOpts.projectId,
572
+ contentType,
573
+ });
401
574
  debug(`AI Drive upload URL: ${uploadUrl}`);
402
575
  const responseBody = await streamFileUpload(filePath, uploadUrl, headers, fileSize, 'POST');
403
576
  try {
@@ -505,9 +678,12 @@ function encodeAttachmentInline(filePath) {
505
678
  * the bytes only exist for the duration of the email-send request. Hosted
506
679
  * URLs in the same array are passed through unchanged.
507
680
  */
508
- async function resolveLocalFiles(args, client) {
681
+ async function resolveLocalFiles(args, client, locatorKeys = new Set()) {
509
682
  const resolved = { ...args };
510
683
  for (const [key, value] of Object.entries(resolved)) {
684
+ // A locator names an entry on the server, never a local file to upload.
685
+ if (locatorKeys.has(key))
686
+ continue;
511
687
  // Email `attachments` — inline base64, no blob round-trip.
512
688
  if (key === 'attachments' && Array.isArray(value)) {
513
689
  const out = [];
@@ -943,14 +1119,23 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
943
1119
  cmd.option('--workspace <value>', 'AI Drive workspace: my_drive, shared_with_me, or shared_drive');
944
1120
  }
945
1121
  cmd.option('--local_file <path>', 'upload: local file path to upload to AI Drive (supports files >5 MB; ' +
946
- 'alternative to --file_content). download: local destination path ' +
1122
+ 'alternative to --file_content; same as the first operand of ' +
1123
+ '`upload <local> <drive folder>/`). download: local destination path ' +
947
1124
  '(same as the second operand; default ./<basename of the drive path>)');
948
- cmd.option('--override', 'Overwrite an existing file at the destination path (used with --local_file)', false);
1125
+ // An optional value, as schema booleans take: presence-only, the
1126
+ // `false` in `--override false` was left over and the upload overwrote.
1127
+ cmd.option('--override [value]', 'Overwrite an existing file at the destination path (used with --local_file)', parseBooleanFlagValue);
949
1128
  cmd.option('--on-conflict <mode>', 'upload: what to do when the destination name is taken — ' +
950
1129
  'error | rename | overwrite (default: rename, which lands ' +
951
1130
  'name(1).ext and reports the path actually written). Use error for ' +
952
1131
  'idempotent scripts that retry on failure.');
953
1132
  }
1133
+ // genteam download saves the attachment to local disk (client-side: only
1134
+ // this process can write the local filesystem). The union view takes the
1135
+ // flag here; the per-action `download` subcommand registers it below.
1136
+ if (tool.name === 'genteam' && !actionViews) {
1137
+ cmd.option('--local_file <path>', GENTEAM_DOWNLOAD_LOCAL_FILE_HELP);
1138
+ }
954
1139
  // For sb-git: `--execute [dest]` turns `clone-url` from a snippet-print
955
1140
  // into an actual `git clone`. Client-side because the backend `clone-url`
956
1141
  // adaptor returns shell placeholders rather than embedding secrets in
@@ -992,6 +1177,11 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
992
1177
  opts = primaryArgValue;
993
1178
  primaryArgValue = undefined;
994
1179
  }
1180
+ // Global flags written after the tool name arrive here as the
1181
+ // subcommand's own options: record them for getGlobalOptions and keep
1182
+ // them out of the tool arguments (they are not server parameters).
1183
+ for (const key of passthroughKeysOf(cmd, invokedCmd))
1184
+ delete opts[key];
995
1185
  // Service tool invoked with no action → list the available actions
996
1186
  // instead of failing on the (intentionally optional) action positional.
997
1187
  const actionEnum = tool.cli.primary_arg
@@ -1268,6 +1458,41 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1268
1458
  process.exit(1);
1269
1459
  }
1270
1460
  }
1461
+ // aidrive: a drive path written as an operand (`gsk drive ls
1462
+ // /Reports`, `gsk drive move /q3.pdf /Archive`) fills the action's
1463
+ // parameters. Commander keeps such operands but maps none of them,
1464
+ // so the server used to answer "Missing required parameter: path".
1465
+ // Upload and download read their operands in their own lanes below.
1466
+ // The operands after the action: a per-action subcommand's are all
1467
+ // bare; the union command's first is the action, unless --args-file
1468
+ // carried it and Commander bound a bare path to the action slot.
1469
+ let aidriveOperands = [];
1470
+ if (tool.name === 'aidrive' && typeof args.action === 'string') {
1471
+ const actionNames = props.action?.enum;
1472
+ if (invokedCmd === cmd &&
1473
+ primaryArgValue !== undefined &&
1474
+ primaryArgValue !== args.action &&
1475
+ Array.isArray(actionNames) &&
1476
+ actionNames.includes(primaryArgValue)) {
1477
+ // Read as an operand, `drive ls --args-file` with a file saying
1478
+ // "rm" would have removed a path named "ls".
1479
+ logError(`The command line names the action ${primaryArgValue} and ` +
1480
+ `--args-file names ${args.action}; pass one. Nothing was sent.`);
1481
+ process.exit(1);
1482
+ }
1483
+ aidriveOperands =
1484
+ invokedCmd !== cmd
1485
+ ? invokedCmd.args
1486
+ : primaryArgValue !== undefined && primaryArgValue === args.action
1487
+ ? invokedCmd.args.slice(1)
1488
+ : invokedCmd.args;
1489
+ const mapped = aidriveOperandArgs(args.action, aidriveOperands, args);
1490
+ if (mapped.error) {
1491
+ logError(mapped.error);
1492
+ process.exit(1);
1493
+ }
1494
+ Object.assign(args, mapped.filled);
1495
+ }
1271
1496
  // Pre-call confirmation (confirm.ts): when the cached /tools
1272
1497
  // payload advertised interactive_confirm AND the schema marks this
1273
1498
  // tool/action confirmation-required, resolve [y/N] / --yes /
@@ -1303,6 +1528,11 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1303
1528
  delete args.override;
1304
1529
  delete args.onConflict;
1305
1530
  }
1531
+ // genteam: --local_file is the download destination, client-side
1532
+ // only; the server's genteam actions know no such parameter.
1533
+ if (tool.name === 'genteam') {
1534
+ delete args.local_file;
1535
+ }
1306
1536
  // sb-git --execute is client-side only; never forward.
1307
1537
  let sbGitExecuteDest;
1308
1538
  let sbGitExecuteRequested = false;
@@ -1371,40 +1601,86 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1371
1601
  // only, not CLI-populated ones).
1372
1602
  args.files = collected.files;
1373
1603
  }
1374
- // aidrive upload ergonomics: `gsk aidrive upload <path>` is the natural
1375
- // invocation and the dominant fumble — the bare path is an excess
1376
- // operand that Commander tolerates but never maps to an option, so the
1377
- // request otherwise reaches the API with no content and fails with a
1378
- // misleading "Missing file_content". When no explicit content source was
1379
- // given, adopt a path-like operand as --local_file (cmd.args[0] is the
1380
- // 'upload' action; later operands are candidate paths, directories
1381
- // skipped) so the streaming upload below handles it; if there is still
1382
- // no usable source, fail with an actionable message that names
1383
- // --local_file rather than the opaque backend error.
1384
- if (tool.name === 'aidrive' &&
1385
- // args.action, not the positional: the action may arrive via
1386
- // --args-file (sb-git's clone-url gate uses the same pattern).
1387
- args.action === 'upload' &&
1388
- !opts.local_file &&
1604
+ // aidrive upload operands: `gsk drive upload <local> [<drive
1605
+ // destination>]`. A bare local path is an operand Commander tolerates
1606
+ // but never maps, so the request used to reach the API with no
1607
+ // content ("Missing file_content"), and a destination operand or
1608
+ // `-p` was dropped, landing the file at the drive root. The local
1609
+ // source is --local_file or the first operand that exists on disk;
1610
+ // the destination is `-p` or the operand left over, read by the
1611
+ // lanes below. With no usable source, fail with an actionable
1612
+ // message that names --local_file rather than the opaque backend
1613
+ // error.
1614
+ let uploadDestination;
1615
+ if (tool.name === 'aidrive' && args.action === 'upload') {
1389
1616
  // args, not opts: file_content is a server param and may have
1390
1617
  // arrived via --args-file (merged into args above).
1391
- !args.file_content) {
1392
- // Skip the first operand only when it really is the action: with
1393
- // the action arriving via --args-file, Commander binds a bare
1394
- // path to the [action] positional slot, so cmd.args[0] is itself
1395
- // a path candidate.
1396
- const operandCandidates = primaryArgValue !== undefined && primaryArgValue === args.action
1397
- ? invokedCmd.args.slice(1)
1398
- : invokedCmd.args;
1399
- const pathOperand = pickExistingUploadOperand(operandCandidates);
1400
- if (pathOperand) {
1401
- opts.local_file = pathOperand;
1618
+ const inline = !!args.file_content && !opts.local_file;
1619
+ const resolved = resolveAidriveUploadOperands({
1620
+ operands: aidriveOperands,
1621
+ localFile: typeof opts.local_file === 'string' ? opts.local_file : undefined,
1622
+ inline,
1623
+ path: typeof args.path === 'string' ? args.path : undefined,
1624
+ uploadPath: typeof args.upload_path === 'string'
1625
+ ? args.upload_path
1626
+ : undefined,
1627
+ });
1628
+ if (resolved.error) {
1629
+ logError(resolved.error);
1630
+ process.exit(1);
1631
+ }
1632
+ // `-p` was the destination; upload has no `path` of its own.
1633
+ delete args.path;
1634
+ for (const key of ['destination', 'upload_path']) {
1635
+ const value = key === 'destination' ? resolved.destination : args.upload_path;
1636
+ if (typeof value !== 'string' || !value)
1637
+ continue;
1638
+ const normalized = normalizeUploadDestination(value);
1639
+ if (normalized.error) {
1640
+ logError(normalized.error);
1641
+ process.exit(1);
1642
+ }
1643
+ if (key === 'destination')
1644
+ uploadDestination = normalized.path;
1645
+ else
1646
+ args.upload_path = normalized.path;
1647
+ }
1648
+ if (inline) {
1649
+ // Inline content has no file name of its own, so its
1650
+ // destination is the file's full path as written.
1651
+ if (uploadDestination !== undefined) {
1652
+ if (uploadDestination.endsWith('/')) {
1653
+ logError(`--file_content needs the file's full path; ${uploadDestination} ` +
1654
+ 'names a folder: add the file name. Nothing was sent.');
1655
+ process.exit(1);
1656
+ }
1657
+ // Relative to a folder --id/--url names; otherwise from the
1658
+ // drive root, which the tool lane requires spelled out.
1659
+ args.upload_path =
1660
+ args.id || args.url || uploadDestination.startsWith('/')
1661
+ ? uploadDestination
1662
+ : `/${uploadDestination}`;
1663
+ }
1664
+ // The tool lane knows `overwrite` only; --on-conflict and
1665
+ // --override are the CLI's spellings, so map them here rather
1666
+ // than let them vanish with the other CLI-only flags.
1667
+ const conflict = uploadConflictFromCli(opts, args);
1668
+ const problem = uploadConflictProblem(conflict, args, true);
1669
+ if (problem) {
1670
+ logError(`${problem}. Nothing was sent.`);
1671
+ process.exit(1);
1672
+ }
1673
+ if (conflict.onConflict === 'overwrite')
1674
+ args.overwrite = true;
1675
+ }
1676
+ else if (resolved.localFile) {
1677
+ opts.local_file = resolved.localFile;
1402
1678
  }
1403
1679
  else {
1404
1680
  logError('upload needs a file source: use `--local_file <path>` for a ' +
1405
1681
  'local file (any size, binaries OK) or `--file_content <text>` ' +
1406
- 'for inline text. Example: gsk aidrive upload --local_file ' +
1407
- './report.pdf --upload_path /report.pdf');
1682
+ 'for inline text. Example: gsk drive upload ./report.pdf ' +
1683
+ '/Reports/');
1408
1684
  process.exit(1);
1409
1685
  }
1410
1686
  }
@@ -1418,7 +1694,7 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1418
1694
  ? invokedCmd.args.slice(1)
1419
1695
  : invokedCmd.args;
1420
1696
  const { drivePath: sourceOperand, localPath: operandDest } = resolveAidriveDownloadOperands(operandCandidates, typeof args.path === 'string' ? args.path : undefined);
1421
- const hasDownloadLocator = !!(args.id || args.url);
1697
+ const hasDownloadLocator = !!(args.id || args.url || args.source || args.share);
1422
1698
  if (!sourceOperand && !hasDownloadLocator) {
1423
1699
  logError('download needs the AI-Drive path: gsk aidrive download ' +
1424
1700
  '<ai-drive-path> [local-path] (or --path/-p). To save an ' +
@@ -1457,9 +1733,10 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1457
1733
  // get_readable_url reports "Readable URL for <path>: <url>".
1458
1734
  const reportedPath = /Readable URL for (.+?): https?:\/\//.exec(String(urlResult.data?.result ?? ''))?.[1];
1459
1735
  const resolvedDrivePath = drivePath ?? reportedPath ?? String(args.id ?? 'download');
1736
+ const fileName = urlResult.session_state?.aidrive_result?.file_name;
1460
1737
  const destPath = (typeof opts.local_file === 'string' ? opts.local_file : '') ||
1461
1738
  operandDest ||
1462
- pathModule.basename(resolvedDrivePath);
1739
+ pathModule.basename(fileName || resolvedDrivePath) || 'download';
1463
1740
  const savedPath = await downloadToFile(readableUrl, destPath, client);
1464
1741
  output({
1465
1742
  status: 'ok',
@@ -1468,6 +1745,59 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1468
1745
  });
1469
1746
  return;
1470
1747
  }
1748
+ // Save a GenTeam attachment to local disk. Client-side because only
1749
+ // this process can write the local filesystem: fetch the gsk-token
1750
+ // stream route — the web and mobile clients' own membership-gated
1751
+ // download lane — straight into the file. No server action call, no
1752
+ // blob copy, no session-gated wrapper URL to 403 on (#61834); the
1753
+ // server's `download` action stays for CLIs that predate this route.
1754
+ if (tool.name === 'genteam' && args.action === 'download') {
1755
+ const channelId = typeof args.channel_id === 'string' ? args.channel_id.trim() : '';
1756
+ const attachmentRef = typeof args.attachment_ref === 'string'
1757
+ ? args.attachment_ref.trim()
1758
+ : '';
1759
+ if (!channelId || !attachmentRef) {
1760
+ logError('download needs --channel_id and --attachment_ref ' +
1761
+ '(attachments[].attachment_ref from `gsk genteam read` output)');
1762
+ process.exit(1);
1763
+ }
1764
+ // A per-action subcommand's operands are all bare; the union view
1765
+ // carries the action as its first operand (the aidrive shape).
1766
+ const operands = invokedCmd !== cmd
1767
+ ? invokedCmd.args
1768
+ : primaryArgValue !== undefined && primaryArgValue === args.action
1769
+ ? invokedCmd.args.slice(1)
1770
+ : invokedCmd.args;
1771
+ let response;
1772
+ try {
1773
+ response = await client.fetchBinary(genteamAttachmentEndpoint(channelId, attachmentRef));
1774
+ }
1775
+ catch (err) {
1776
+ const reason = err instanceof Error ? err.message : String(err);
1777
+ logError(`genteam download failed: ${reason}`);
1778
+ process.exit(1);
1779
+ }
1780
+ if (!response.body) {
1781
+ logError('genteam download failed: empty response body');
1782
+ process.exit(1);
1783
+ }
1784
+ const fileName = fileNameFromContentDisposition(response.headers.get('content-disposition'));
1785
+ const destPath = resolveGenteamDownloadDestination(operands, typeof opts.local_file === 'string' ? opts.local_file : undefined, fileName);
1786
+ const saved = await saveBodyToFile(response.body, destPath);
1787
+ output({
1788
+ status: 'ok',
1789
+ message: 'GenTeam attachment downloaded to local disk',
1790
+ data: {
1791
+ channel_id: channelId,
1792
+ attachment_ref: attachmentRef,
1793
+ file_name: fileName ?? pathModule.basename(destPath),
1794
+ content_type: response.headers.get('content-type') ??
1795
+ 'application/octet-stream',
1796
+ ...saved,
1797
+ },
1798
+ });
1799
+ return;
1800
+ }
1471
1801
  // `download_file` saves an external URL INTO the drive and cannot copy
1472
1802
  // one out, yet it is the obvious spelling for "download a drive file"
1473
1803
  // and both attempts used to fail silently: its handler never consumes
@@ -1502,19 +1832,29 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1502
1832
  args.action === 'upload' &&
1503
1833
  opts.local_file) {
1504
1834
  const localFilePath = opts.local_file;
1505
- const override = !!opts.override;
1506
1835
  // --on-conflict error|rename|overwrite (#54379). Default (unset) is
1507
1836
  // rename server-side: nobody is here to answer a prompt, and
1508
1837
  // dead-ending an agent mid-task is worse than landing a copy.
1509
1838
  // `error` is kept for idempotent scripts that read a failure as
1510
1839
  // "nothing was written" — with rename they would accumulate a copy
1511
- // per retry.
1512
- // Commander camelCases `--on-conflict` to `onConflict`; the other
1513
- // spellings are only for a caller that passed the raw arg through.
1514
- const onConflict = (opts.onConflict ??
1515
- opts['on-conflict'] ??
1516
- opts.on_conflict ??
1517
- args.on_conflict);
1840
+ // per retry. `--overwrite true` (the tool schema's spelling) and
1841
+ // `--override` both mean overwrite here. Commander camelCases
1842
+ // `--on-conflict` to `onConflict`; the other spellings are only
1843
+ // for a caller that passed the raw arg through.
1844
+ const conflict = uploadConflictFromCli(opts, args);
1845
+ const problem = uploadConflictProblem(conflict, args, false);
1846
+ if (problem) {
1847
+ logError(`${problem}. Nothing was sent.`);
1848
+ process.exit(1);
1849
+ }
1850
+ const onConflict = conflict.onConflict;
1851
+ // `upload --to <who>` / `--general_access <audience>`: share the
1852
+ // file the moment it lands, and answer with the link that opens
1853
+ // for them — the share verb the caller would run next, addressed
1854
+ // by the uploaded entry's id. My Drive only, as on the server:
1855
+ // a shared source's sharing has its own verb and admin gate.
1856
+ const shareAfterUpload = shareArgsFromUpload(args);
1857
+ const sharesAfterUpload = Object.keys(shareAfterUpload).length > 0;
1518
1858
  const workspace = args.workspace || 'my_drive';
1519
1859
  const source = args.source ||
1520
1860
  args.share;
@@ -1523,7 +1863,8 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1523
1863
  process.exit(1);
1524
1864
  }
1525
1865
  // args.upload_path is safe here: args = { ...opts } at line above, and
1526
- // only local_file/override were deleted from args — upload_path is intact.
1866
+ // only the CLI-only flags (local_file, override, onConflict) were
1867
+ // deleted from args — upload_path is intact.
1527
1868
  // --id / --owner / --url: the server resolves the folder and treats
1528
1869
  // upload_path as RELATIVE to it, so keep the caller's spelling and
1529
1870
  // default to the file name instead of forcing a leading slash.
@@ -1533,15 +1874,42 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1533
1874
  url: args.url,
1534
1875
  };
1535
1876
  const addressedById = !!(locator.id || locator.url);
1877
+ const localStat = fs.statSync(localFilePath);
1878
+ // --upload_path is the exact path; an operand or `-p` destination
1879
+ // is a folder unless it names the upload itself.
1880
+ let destinationPath;
1881
+ if (!args.upload_path && uploadDestination !== undefined) {
1882
+ const placed = uploadPathForDestination(uploadDestination, localFilePath, localStat.isDirectory());
1883
+ if (placed.error) {
1884
+ logError(placed.error);
1885
+ process.exit(1);
1886
+ }
1887
+ destinationPath = placed.uploadPath;
1888
+ }
1536
1889
  const rawUploadPath = args.upload_path ||
1890
+ destinationPath ||
1891
+ // Named after the resolved path, as with a destination: `.`
1892
+ // spread its files over the drive root.
1537
1893
  (addressedById
1538
- ? pathModule.basename(localFilePath)
1539
- : `/${pathModule.basename(localFilePath)}`);
1894
+ ? pathModule.basename(pathModule.resolve(localFilePath))
1895
+ : `/${pathModule.basename(pathModule.resolve(localFilePath))}`);
1540
1896
  const uploadPath = addressedById || rawUploadPath.startsWith('/')
1541
1897
  ? rawUploadPath
1542
1898
  : `/${rawUploadPath}`;
1543
- const localStat = fs.statSync(localFilePath);
1544
1899
  const files = collectUploadFiles(localFilePath);
1900
+ if (sharesAfterUpload) {
1901
+ const refusal = uploadShareRefusal({
1902
+ workspace,
1903
+ source,
1904
+ addressedById: Boolean(args.id || args.url),
1905
+ isDirectory: localStat.isDirectory(),
1906
+ uploadPath,
1907
+ });
1908
+ if (refusal) {
1909
+ logError(refusal);
1910
+ process.exit(1);
1911
+ }
1912
+ }
1545
1913
  if (localStat.isDirectory()) {
1546
1914
  if (files.length === 0) {
1547
1915
  logError(`Folder has no files to upload: ${localFilePath}`);
@@ -1551,7 +1919,7 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1551
1919
  const uploaded = [];
1552
1920
  for (const file of files) {
1553
1921
  const destination = pathModule.posix.join(uploadPath, file.relativePath);
1554
- const result = await uploadToAiDrive(file.absolutePath, destination, override, workspace, source, onConflict, locator);
1922
+ const result = await uploadToAiDrive(file.absolutePath, destination, workspace, source, onConflict, locator);
1555
1923
  if (result.status !== 'ok') {
1556
1924
  output(result);
1557
1925
  process.exit(1);
@@ -1572,8 +1940,37 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1572
1940
  }
1573
1941
  else {
1574
1942
  // Stream directly to AI Drive — single request, no blob middleman
1575
- const result = await uploadToAiDrive(localFilePath, uploadPath, override, workspace, source, onConflict, locator);
1576
- output(result);
1943
+ const result = await uploadToAiDrive(localFilePath, uploadPath, workspace, source, onConflict, locator);
1944
+ const uploadedData = result.data;
1945
+ const uploadedId = uploadedData?.entry_id || uploadedData?.id;
1946
+ if (result.status !== 'ok' || !sharesAfterUpload || !uploadedId) {
1947
+ if (result.status === 'ok' && sharesAfterUpload && !uploadedId) {
1948
+ result.message +=
1949
+ ' (the server did not return the file id, so it was not shared; run `gsk drive share` on it)';
1950
+ }
1951
+ output(result);
1952
+ return;
1953
+ }
1954
+ // A share that throws (network, parse) must not read as a
1955
+ // failed upload: the file is written, and a retry would land a
1956
+ // second copy.
1957
+ let shared;
1958
+ try {
1959
+ shared = await client.executeTool('aidrive', {
1960
+ action: 'share',
1961
+ workspace,
1962
+ id: uploadedId,
1963
+ ...shareAfterUpload,
1964
+ });
1965
+ }
1966
+ catch (error) {
1967
+ shared = {
1968
+ status: 'error',
1969
+ message: error instanceof Error ? error.message : String(error),
1970
+ data: null,
1971
+ };
1972
+ }
1973
+ output(mergeShareIntoUpload(result, shared));
1577
1974
  }
1578
1975
  return;
1579
1976
  }
@@ -1625,7 +2022,8 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1625
2022
  delete args.file; // CLI-only option, not a server parameter
1626
2023
  }
1627
2024
  // Resolve local file paths to uploaded URLs
1628
- const resolvedArgs = await resolveLocalFiles(args, client);
2025
+ // The drive's --url is the Drive link an entry is addressed by.
2026
+ const resolvedArgs = await resolveLocalFiles(args, client, tool.name === 'aidrive' ? new Set(['url']) : undefined);
1629
2027
  // The server owns the async-first default: create_task /
1630
2028
  // task_continue return a submit stub ({status: "submitted",
1631
2029
  // run_id, stream_url}) unless `--wait true` was passed. --attach
@@ -1874,6 +2272,7 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1874
2272
  }
1875
2273
  }
1876
2274
  };
2275
+ addGlobalPassthroughOptions(cmd, props);
1877
2276
  cmd.action((primaryArgValue, opts) => runToolInvocation(primaryArgValue, opts));
1878
2277
  // Per-action subcommands (issue #51377) — see the actionViews comment at
1879
2278
  // the top of this function: a wrong-action flag now fails at parse time
@@ -1916,6 +2315,10 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1916
2315
  if (outputFileKeys.length > 0) {
1917
2316
  sub.option('-o, --output-file <path>', 'Download the generated file to a local path');
1918
2317
  }
2318
+ if (tool.name === 'genteam' && view.name === 'download') {
2319
+ sub.option('--local_file <path>', GENTEAM_DOWNLOAD_LOCAL_FILE_HELP);
2320
+ }
2321
+ addGlobalPassthroughOptions(sub, props);
1919
2322
  sub.action((opts) => runToolInvocation(view.name, opts, sub));
1920
2323
  }
1921
2324
  }
@@ -2886,13 +3289,17 @@ async function main() {
2886
3289
  .allowExcessArguments(false)
2887
3290
  .requiredOption('--port <port>', 'Local loopback port', parseLocalPort)
2888
3291
  .action(async (flags) => {
2889
- setOutputFormat(program.opts().output);
3292
+ // Offline probe: must not touch getGlobalOptions (project binding /
3293
+ // login resolution can fail here by design). Overlay-aware read only.
3294
+ setOutputFormat(activePassthroughOpts.output ??
3295
+ program.opts().output);
2890
3296
  const result = await localServiceUrl(flags.port);
2891
3297
  output(result);
2892
3298
  if (result.status === 'error')
2893
3299
  process.exitCode = 1;
2894
3300
  });
2895
3301
  try {
3302
+ finalizeGlobalPassthrough();
2896
3303
  await program.parseAsync();
2897
3304
  }
2898
3305
  catch (error) {
@@ -2909,6 +3316,7 @@ async function main() {
2909
3316
  }
2910
3317
  if (['project', 'preflight'].includes(localRoute.command || '') ||
2911
3318
  (localRoute.command === 'hosted' && localRoute.subcommand === 'deploy-local')) {
3319
+ finalizeGlobalPassthrough();
2912
3320
  await program.parseAsync();
2913
3321
  return;
2914
3322
  }
@@ -2923,7 +3331,7 @@ async function main() {
2923
3331
  // commands/mesh.ts for why).
2924
3332
  const meshArgs = getMeshInvocation(process.argv.slice(2));
2925
3333
  if (meshArgs !== null) {
2926
- program.parseOptions(process.argv);
3334
+ program.parseOptions(rootArgvPrefix(process.argv.slice(2)));
2927
3335
  setDebugEnabled(getGlobalOptions().debug);
2928
3336
  // Forward an explicit `--base-url` flag only; env/config/default resolution
2929
3337
  // happens inside the mesh layer.
@@ -2941,8 +3349,9 @@ async function main() {
2941
3349
  catch {
2942
3350
  // Never block CLI execution due to update check failures
2943
3351
  }
2944
- // Pre-parse global options before program.parse() so --refresh, --debug etc. work
2945
- program.parseOptions(process.argv);
3352
+ // Pre-parse global options before program.parse() so --refresh, --debug etc.
3353
+ // work — root flags only, i.e. the slice before the subcommand name.
3354
+ program.parseOptions(rootArgvPrefix(process.argv.slice(2)));
2946
3355
  const globalOpts = getGlobalOptions();
2947
3356
  setDebugEnabled(globalOpts.debug);
2948
3357
  setOutputFormat(globalOpts.output);
@@ -2964,7 +3373,11 @@ async function main() {
2964
3373
  if (tools && globalOpts.apiKey) {
2965
3374
  let missing = null;
2966
3375
  try {
2967
- const { operands } = program.parseOptions(process.argv.slice(2));
3376
+ // Positional tokens only — never let the ROOT parse the whole line
3377
+ // here: before the subcommands exist it would swallow a tool's
3378
+ // `--timeout` / `--version` as its own (2026-09-20, cached-manifest
3379
+ // path only, which is why a `--refresh` run looked fine).
3380
+ const operands = operandsForStaleCheck(process.argv.slice(2));
2968
3381
  const index = collectToolCommandTokens(tools, Boolean(vdProjectId));
2969
3382
  // phone-call / call-for-me dial by DEFAULT subcommand, so their second
2970
3383
  // token may be a recipient — never provably a miss. (`telephony call
@@ -3076,6 +3489,7 @@ async function main() {
3076
3489
  }
3077
3490
  }
3078
3491
  // Parse and run
3492
+ finalizeGlobalPassthrough();
3079
3493
  await program.parseAsync();
3080
3494
  }
3081
3495
  main().catch(err => {