@genspark/cli 1.13.0 → 1.13.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/dist/index.js CHANGED
@@ -47,6 +47,7 @@ import { getSandboxRuntime } from './runtime.js';
47
47
  import { registerDesignCommand } from './commands/design.js';
48
48
  import { collectUploadFiles, pickExistingUploadOperand, buildAidriveUploadQuery, } from './commands/aidrive-upload.js';
49
49
  import { resolveAidriveDownloadOperands, normalizeDrivePath, extractReadableUrl, shouldResolveFileWrapperUrl, } from './commands/aidrive-download.js';
50
+ import { fileNameFromContentDisposition, genteamAttachmentEndpoint, resolveGenteamDownloadDestination, saveBodyToFile, } from './commands/genteam-download.js';
50
51
  import { parseLastSeenIndex, eventStdoutLine } from './commands/chat-events.js';
51
52
  import { defaultPiAgentDir, mergePiModelsConfig, mergePiSettingsConfig, readJsonIfExists, resolvePiAgentDir, writeJsonFile, } from './commands/pi-config.js';
52
53
  import { mediaItemsKeyFor, mediaSummaryLines } from './mediaSummary.js';
@@ -57,6 +58,8 @@ const require = createRequire(import.meta.url);
57
58
  const { version: VERSION } = require('../package.json');
58
59
  const DEFAULT_BASE_URL = 'https://www.genspark.ai';
59
60
  const DEFAULT_TIMEOUT = 1800000; // 30 minutes (slides/video generation can be slow)
61
+ const GENTEAM_DOWNLOAD_LOCAL_FILE_HELP = 'download: local destination path (same as a bare operand; a directory ' +
62
+ 'receives the server-reported file name; default ./<file_name>)';
60
63
  /**
61
64
  * Resolve a custom config path from process.env / process.argv before
62
65
  * Commander has had a chance to parse flags. We peek at argv directly
@@ -89,6 +92,14 @@ const fileConfig = loadConfigFile();
89
92
  const program = new Command();
90
93
  program
91
94
  .name('gsk')
95
+ // Root options are parsed only BEFORE the subcommand name; everything
96
+ // after it belongs to the subcommand. Without this, Commander let the
97
+ // root swallow same-named flags from anywhere on the line: `gsk sb-box
98
+ // create --timeout 600` became a 600 ms request timeout and `gsk sb-box
99
+ // resume --version 2` printed the CLI version (2026-09-20). The globals
100
+ // people are used to writing after a tool name keep working through the
101
+ // pass-through copies each tool command registers (addGlobalPassthroughOptions).
102
+ .enablePositionalOptions()
92
103
  .description('Genspark Tool CLI - Search, crawl, analyze, and generate media')
93
104
  // Agents drive this CLI blind (no schema in context): on a bad invocation,
94
105
  // print the full usage + a did-you-mean hint so the caller can self-correct
@@ -116,8 +127,170 @@ program
116
127
  * 2. Environment variables
117
128
  * 3. Config file (~/.genspark-tool-cli/config.json) (lowest)
118
129
  */
130
+ // Global options accepted AFTER a tool subcommand. In positional-options
131
+ // mode the root only sees flags written before the subcommand name, so every
132
+ // dynamic tool command (and each per-action subcommand) re-registers these
133
+ // as hidden pass-through options; runToolInvocation records the values that
134
+ // arrived that way and getGlobalOptions overlays them on the root's. A tool's
135
+ // own parameter with the same flag always wins (sb-box's `--timeout` is
136
+ // seconds of sandbox lifetime, not a request timeout). `--version`,
137
+ // `--refresh` and `--config` stay root-only: version prints and exits, the
138
+ // other two act before the subcommands exist (tools cache, config file).
139
+ const PASSTHROUGH_GLOBALS = [
140
+ { flags: '--api-key <key>', key: 'apiKey' },
141
+ { flags: '--base-url <url>', key: 'baseUrl' },
142
+ { flags: '--project-id <id>', key: 'projectId' },
143
+ { flags: '--debug', key: 'debug', toolParam: 'debug' },
144
+ { flags: '--timeout <ms>', key: 'timeout', toolParam: 'timeout' },
145
+ { flags: '--output <format>', key: 'output', toolParam: 'output' },
146
+ { flags: '--no-input', key: 'input', toolParam: 'input' },
147
+ { flags: '-y, --yes', key: 'yes', toolParam: 'yes' },
148
+ // Accepted after the tool name for compatibility (`gsk list-tools
149
+ // --refresh`, `gsk foo --config p`); they act at startup, where the early
150
+ // scan below already picked them up, so post-parse they are no-ops.
151
+ { flags: '--refresh', key: 'refresh', toolParam: 'refresh' },
152
+ { flags: '--config <path>', key: 'config', toolParam: 'config' },
153
+ ];
154
+ const passthroughKeysByCommand = new WeakMap();
155
+ let activePassthroughOpts = {};
156
+ function addGlobalPassthroughOptions(command, toolProps) {
157
+ const keys = [];
158
+ for (const g of PASSTHROUGH_GLOBALS) {
159
+ if (g.toolParam && toolProps[g.toolParam] !== undefined)
160
+ continue;
161
+ const parts = g.flags.split(',').map(f => f.trim());
162
+ const long = parts[parts.length - 1].split(' ')[0];
163
+ const short = parts.length > 1 ? parts[0].split(' ')[0] : undefined;
164
+ const taken = command.options.some(o => o.long === long || (short !== undefined && o.short === short));
165
+ if (taken)
166
+ continue;
167
+ command.addOption(new Option(g.flags).hideHelp());
168
+ keys.push(g.key);
169
+ }
170
+ passthroughKeysByCommand.set(command, keys);
171
+ }
172
+ // Pass-through values the given commands received on the command line
173
+ // (source 'cli' only — a Commander default is not a user choice).
174
+ function collectPassthrough(...commands) {
175
+ const out = {};
176
+ for (const c of commands) {
177
+ const keys = passthroughKeysByCommand.get(c) ?? [];
178
+ const o = c.opts();
179
+ for (const k of keys) {
180
+ if (o[k] !== undefined && c.getOptionValueSource(k) === 'cli')
181
+ out[k] = o[k];
182
+ }
183
+ }
184
+ return out;
185
+ }
186
+ function passthroughKeysOf(...commands) {
187
+ return commands.flatMap(c => passthroughKeysByCommand.get(c) ?? []);
188
+ }
189
+ // Root options that take a value — the pre-parse must skip their values
190
+ // when looking for the first operand (the subcommand name).
191
+ const ROOT_VALUE_OPTIONS = new Set([
192
+ '--api-key',
193
+ '--base-url',
194
+ '--project-id',
195
+ '--timeout',
196
+ '--output',
197
+ '--config',
198
+ ]);
199
+ // Root flags that are unambiguous ANYWHERE on the line: no tool parameter
200
+ // can produce these kebab-case flags (tool parameters are snake_case), so
201
+ // `gsk search q --api-key K`, `gsk list-tools --refresh` and `gsk crawl u
202
+ // --output json` keep meaning what they always meant, and the startup
203
+ // pre-parse (manifest fetch, output format, debug) sees them wherever they
204
+ // sit. `--timeout` and `--version` are NOT in this set: tools own them after
205
+ // the subcommand name.
206
+ const ROOT_FLAGS_ANYWHERE_VALUE = new Set([
207
+ '--api-key',
208
+ '--base-url',
209
+ '--project-id',
210
+ '--output',
211
+ '--config',
212
+ ]);
213
+ const ROOT_FLAGS_ANYWHERE_BOOL = new Set(['--refresh', '--debug']);
214
+ // The argv slice the ROOT may pre-parse: everything before the first
215
+ // operand, plus the unambiguous root flags from the rest of the line. The
216
+ // startup pre-parse runs before the tool subcommands exist, so Commander
217
+ // cannot stop at the subcommand name by itself — without this cut it read
218
+ // `--version` / `--timeout` from anywhere on the line (2026-09-20).
219
+ function rootArgvPrefix(argv) {
220
+ const picked = [];
221
+ let afterOperand = false;
222
+ for (let i = 0; i < argv.length; i++) {
223
+ const arg = argv[i];
224
+ if (!arg.startsWith('-') || arg === '-') {
225
+ afterOperand = true;
226
+ continue;
227
+ }
228
+ const [flag] = arg.split('=', 1);
229
+ const takesValue = ROOT_VALUE_OPTIONS.has(flag);
230
+ if (!afterOperand) {
231
+ picked.push(arg);
232
+ if (takesValue && !arg.includes('=') && i + 1 < argv.length) {
233
+ picked.push(argv[++i]);
234
+ }
235
+ continue;
236
+ }
237
+ if (ROOT_FLAGS_ANYWHERE_BOOL.has(flag)) {
238
+ picked.push(arg);
239
+ }
240
+ else if (ROOT_FLAGS_ANYWHERE_VALUE.has(flag)) {
241
+ picked.push(arg);
242
+ if (!arg.includes('=') && i + 1 < argv.length)
243
+ picked.push(argv[++i]);
244
+ }
245
+ else if (takesValue && !arg.includes('=')) {
246
+ i++; // a root-looking value option that tools may own (--timeout): skip its value too
247
+ }
248
+ }
249
+ return picked;
250
+ }
251
+ // Option-stripped positional view of argv for the stale-cache check: drop
252
+ // every `-flag`, plus the value of the root options that take one. Only the
253
+ // first two operands are ever consulted (command, subcommand), so a tool
254
+ // flag's value counted as a later operand is harmless.
255
+ function operandsForStaleCheck(argv) {
256
+ const operands = [];
257
+ for (let i = 0; i < argv.length; i++) {
258
+ const arg = argv[i];
259
+ if (arg.startsWith('-') && arg !== '-') {
260
+ if (ROOT_VALUE_OPTIONS.has(arg))
261
+ i++;
262
+ continue;
263
+ }
264
+ operands.push(arg);
265
+ }
266
+ return operands;
267
+ }
268
+ // Give every command that has none yet (the static ones: hosted, login,
269
+ // design, …) the pass-through globals, and record the active command's
270
+ // pass-through values before any action runs. Called once, right before
271
+ // program.parseAsync().
272
+ let passthroughFinalized = false;
273
+ function finalizeGlobalPassthrough() {
274
+ if (passthroughFinalized)
275
+ return;
276
+ passthroughFinalized = true;
277
+ const visit = (c) => {
278
+ if (!passthroughKeysByCommand.has(c))
279
+ addGlobalPassthroughOptions(c, {});
280
+ for (const child of c.commands)
281
+ visit(child);
282
+ };
283
+ for (const child of program.commands)
284
+ visit(child);
285
+ program.hook('preAction', (_thisCommand, actionCommand) => {
286
+ const chain = [];
287
+ for (let c = actionCommand; c; c = c.parent)
288
+ chain.push(c);
289
+ activePassthroughOpts = collectPassthrough(...chain);
290
+ });
291
+ }
119
292
  function getGlobalOptions() {
120
- const opts = program.opts();
293
+ const opts = { ...program.opts(), ...activePassthroughOpts };
121
294
  // API key priority: CLI > env > config file
122
295
  const apiKey = opts.apiKey || process.env.GSK_API_KEY || fileConfig.api_key;
123
296
  // Base URL priority: CLI > env > config file > default
@@ -951,6 +1124,12 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
951
1124
  'name(1).ext and reports the path actually written). Use error for ' +
952
1125
  'idempotent scripts that retry on failure.');
953
1126
  }
1127
+ // genteam download saves the attachment to local disk (client-side: only
1128
+ // this process can write the local filesystem). The union view takes the
1129
+ // flag here; the per-action `download` subcommand registers it below.
1130
+ if (tool.name === 'genteam' && !actionViews) {
1131
+ cmd.option('--local_file <path>', GENTEAM_DOWNLOAD_LOCAL_FILE_HELP);
1132
+ }
954
1133
  // For sb-git: `--execute [dest]` turns `clone-url` from a snippet-print
955
1134
  // into an actual `git clone`. Client-side because the backend `clone-url`
956
1135
  // adaptor returns shell placeholders rather than embedding secrets in
@@ -992,6 +1171,11 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
992
1171
  opts = primaryArgValue;
993
1172
  primaryArgValue = undefined;
994
1173
  }
1174
+ // Global flags written after the tool name arrive here as the
1175
+ // subcommand's own options: record them for getGlobalOptions and keep
1176
+ // them out of the tool arguments (they are not server parameters).
1177
+ for (const key of passthroughKeysOf(cmd, invokedCmd))
1178
+ delete opts[key];
995
1179
  // Service tool invoked with no action → list the available actions
996
1180
  // instead of failing on the (intentionally optional) action positional.
997
1181
  const actionEnum = tool.cli.primary_arg
@@ -1303,6 +1487,11 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1303
1487
  delete args.override;
1304
1488
  delete args.onConflict;
1305
1489
  }
1490
+ // genteam: --local_file is the download destination, client-side
1491
+ // only; the server's genteam actions know no such parameter.
1492
+ if (tool.name === 'genteam') {
1493
+ delete args.local_file;
1494
+ }
1306
1495
  // sb-git --execute is client-side only; never forward.
1307
1496
  let sbGitExecuteDest;
1308
1497
  let sbGitExecuteRequested = false;
@@ -1418,7 +1607,7 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1418
1607
  ? invokedCmd.args.slice(1)
1419
1608
  : invokedCmd.args;
1420
1609
  const { drivePath: sourceOperand, localPath: operandDest } = resolveAidriveDownloadOperands(operandCandidates, typeof args.path === 'string' ? args.path : undefined);
1421
- const hasDownloadLocator = !!(args.id || args.url);
1610
+ const hasDownloadLocator = !!(args.id || args.url || args.source || args.share);
1422
1611
  if (!sourceOperand && !hasDownloadLocator) {
1423
1612
  logError('download needs the AI-Drive path: gsk aidrive download ' +
1424
1613
  '<ai-drive-path> [local-path] (or --path/-p). To save an ' +
@@ -1457,9 +1646,10 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1457
1646
  // get_readable_url reports "Readable URL for <path>: <url>".
1458
1647
  const reportedPath = /Readable URL for (.+?): https?:\/\//.exec(String(urlResult.data?.result ?? ''))?.[1];
1459
1648
  const resolvedDrivePath = drivePath ?? reportedPath ?? String(args.id ?? 'download');
1649
+ const fileName = urlResult.session_state?.aidrive_result?.file_name;
1460
1650
  const destPath = (typeof opts.local_file === 'string' ? opts.local_file : '') ||
1461
1651
  operandDest ||
1462
- pathModule.basename(resolvedDrivePath);
1652
+ pathModule.basename(fileName || resolvedDrivePath) || 'download';
1463
1653
  const savedPath = await downloadToFile(readableUrl, destPath, client);
1464
1654
  output({
1465
1655
  status: 'ok',
@@ -1468,6 +1658,59 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1468
1658
  });
1469
1659
  return;
1470
1660
  }
1661
+ // Save a GenTeam attachment to local disk. Client-side because only
1662
+ // this process can write the local filesystem: fetch the gsk-token
1663
+ // stream route — the web and mobile clients' own membership-gated
1664
+ // download lane — straight into the file. No server action call, no
1665
+ // blob copy, no session-gated wrapper URL to 403 on (#61834); the
1666
+ // server's `download` action stays for CLIs that predate this route.
1667
+ if (tool.name === 'genteam' && args.action === 'download') {
1668
+ const channelId = typeof args.channel_id === 'string' ? args.channel_id.trim() : '';
1669
+ const attachmentRef = typeof args.attachment_ref === 'string'
1670
+ ? args.attachment_ref.trim()
1671
+ : '';
1672
+ if (!channelId || !attachmentRef) {
1673
+ logError('download needs --channel_id and --attachment_ref ' +
1674
+ '(attachments[].attachment_ref from `gsk genteam read` output)');
1675
+ process.exit(1);
1676
+ }
1677
+ // A per-action subcommand's operands are all bare; the union view
1678
+ // carries the action as its first operand (the aidrive shape).
1679
+ const operands = invokedCmd !== cmd
1680
+ ? invokedCmd.args
1681
+ : primaryArgValue !== undefined && primaryArgValue === args.action
1682
+ ? invokedCmd.args.slice(1)
1683
+ : invokedCmd.args;
1684
+ let response;
1685
+ try {
1686
+ response = await client.fetchBinary(genteamAttachmentEndpoint(channelId, attachmentRef));
1687
+ }
1688
+ catch (err) {
1689
+ const reason = err instanceof Error ? err.message : String(err);
1690
+ logError(`genteam download failed: ${reason}`);
1691
+ process.exit(1);
1692
+ }
1693
+ if (!response.body) {
1694
+ logError('genteam download failed: empty response body');
1695
+ process.exit(1);
1696
+ }
1697
+ const fileName = fileNameFromContentDisposition(response.headers.get('content-disposition'));
1698
+ const destPath = resolveGenteamDownloadDestination(operands, typeof opts.local_file === 'string' ? opts.local_file : undefined, fileName);
1699
+ const saved = await saveBodyToFile(response.body, destPath);
1700
+ output({
1701
+ status: 'ok',
1702
+ message: 'GenTeam attachment downloaded to local disk',
1703
+ data: {
1704
+ channel_id: channelId,
1705
+ attachment_ref: attachmentRef,
1706
+ file_name: fileName ?? pathModule.basename(destPath),
1707
+ content_type: response.headers.get('content-type') ??
1708
+ 'application/octet-stream',
1709
+ ...saved,
1710
+ },
1711
+ });
1712
+ return;
1713
+ }
1471
1714
  // `download_file` saves an external URL INTO the drive and cannot copy
1472
1715
  // one out, yet it is the obvious spelling for "download a drive file"
1473
1716
  // and both attempts used to fail silently: its handler never consumes
@@ -1874,6 +2117,7 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1874
2117
  }
1875
2118
  }
1876
2119
  };
2120
+ addGlobalPassthroughOptions(cmd, props);
1877
2121
  cmd.action((primaryArgValue, opts) => runToolInvocation(primaryArgValue, opts));
1878
2122
  // Per-action subcommands (issue #51377) — see the actionViews comment at
1879
2123
  // the top of this function: a wrong-action flag now fails at parse time
@@ -1916,6 +2160,10 @@ function registerToolCommand(parentProgram, tool, clientFactory, vdProjectIdDefa
1916
2160
  if (outputFileKeys.length > 0) {
1917
2161
  sub.option('-o, --output-file <path>', 'Download the generated file to a local path');
1918
2162
  }
2163
+ if (tool.name === 'genteam' && view.name === 'download') {
2164
+ sub.option('--local_file <path>', GENTEAM_DOWNLOAD_LOCAL_FILE_HELP);
2165
+ }
2166
+ addGlobalPassthroughOptions(sub, props);
1919
2167
  sub.action((opts) => runToolInvocation(view.name, opts, sub));
1920
2168
  }
1921
2169
  }
@@ -2886,13 +3134,17 @@ async function main() {
2886
3134
  .allowExcessArguments(false)
2887
3135
  .requiredOption('--port <port>', 'Local loopback port', parseLocalPort)
2888
3136
  .action(async (flags) => {
2889
- setOutputFormat(program.opts().output);
3137
+ // Offline probe: must not touch getGlobalOptions (project binding /
3138
+ // login resolution can fail here by design). Overlay-aware read only.
3139
+ setOutputFormat(activePassthroughOpts.output ??
3140
+ program.opts().output);
2890
3141
  const result = await localServiceUrl(flags.port);
2891
3142
  output(result);
2892
3143
  if (result.status === 'error')
2893
3144
  process.exitCode = 1;
2894
3145
  });
2895
3146
  try {
3147
+ finalizeGlobalPassthrough();
2896
3148
  await program.parseAsync();
2897
3149
  }
2898
3150
  catch (error) {
@@ -2909,6 +3161,7 @@ async function main() {
2909
3161
  }
2910
3162
  if (['project', 'preflight'].includes(localRoute.command || '') ||
2911
3163
  (localRoute.command === 'hosted' && localRoute.subcommand === 'deploy-local')) {
3164
+ finalizeGlobalPassthrough();
2912
3165
  await program.parseAsync();
2913
3166
  return;
2914
3167
  }
@@ -2923,7 +3176,7 @@ async function main() {
2923
3176
  // commands/mesh.ts for why).
2924
3177
  const meshArgs = getMeshInvocation(process.argv.slice(2));
2925
3178
  if (meshArgs !== null) {
2926
- program.parseOptions(process.argv);
3179
+ program.parseOptions(rootArgvPrefix(process.argv.slice(2)));
2927
3180
  setDebugEnabled(getGlobalOptions().debug);
2928
3181
  // Forward an explicit `--base-url` flag only; env/config/default resolution
2929
3182
  // happens inside the mesh layer.
@@ -2941,8 +3194,9 @@ async function main() {
2941
3194
  catch {
2942
3195
  // Never block CLI execution due to update check failures
2943
3196
  }
2944
- // Pre-parse global options before program.parse() so --refresh, --debug etc. work
2945
- program.parseOptions(process.argv);
3197
+ // Pre-parse global options before program.parse() so --refresh, --debug etc.
3198
+ // work — root flags only, i.e. the slice before the subcommand name.
3199
+ program.parseOptions(rootArgvPrefix(process.argv.slice(2)));
2946
3200
  const globalOpts = getGlobalOptions();
2947
3201
  setDebugEnabled(globalOpts.debug);
2948
3202
  setOutputFormat(globalOpts.output);
@@ -2964,7 +3218,11 @@ async function main() {
2964
3218
  if (tools && globalOpts.apiKey) {
2965
3219
  let missing = null;
2966
3220
  try {
2967
- const { operands } = program.parseOptions(process.argv.slice(2));
3221
+ // Positional tokens only — never let the ROOT parse the whole line
3222
+ // here: before the subcommands exist it would swallow a tool's
3223
+ // `--timeout` / `--version` as its own (2026-09-20, cached-manifest
3224
+ // path only, which is why a `--refresh` run looked fine).
3225
+ const operands = operandsForStaleCheck(process.argv.slice(2));
2968
3226
  const index = collectToolCommandTokens(tools, Boolean(vdProjectId));
2969
3227
  // phone-call / call-for-me dial by DEFAULT subcommand, so their second
2970
3228
  // token may be a recipient — never provably a miss. (`telephony call
@@ -3076,6 +3334,7 @@ async function main() {
3076
3334
  }
3077
3335
  }
3078
3336
  // Parse and run
3337
+ finalizeGlobalPassthrough();
3079
3338
  await program.parseAsync();
3080
3339
  }
3081
3340
  main().catch(err => {