nansen-cli 2.4.0 → 2.6.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/src/cli.js CHANGED
@@ -19,7 +19,7 @@ import { buildMcpCommands } from './commands/mcp.js';
19
19
  import { buildCompletionCommands } from './commands/completion.js';
20
20
  import { buildResearchCommands, RESEARCH_HISTORICAL_SUBCOMMANDS, RESEARCH_SUBCOMMANDS } from './commands/research.js';
21
21
  import { buildPagination, parseSort, parseCsvOption, rejectBlankOption, parseFiltersOption } from './query-options.js';
22
- import { resolveResearchCommand, validateResearchInput, validateOutputOptions, validateFieldSelection, unknownCommandError, normalizeFilterAddresses } from './input-validation.js';
22
+ import { resolveResearchCommand, validateResearchInput, UNAVAILABLE_COMMANDS, SUBCOMMAND_ALIASES, validateOutputOptions, validateFieldSelection, unknownCommandError, normalizeFilterAddresses } from './input-validation.js';
23
23
  import { enableAutoPagination, DEFAULT_MAX_PAGES, MAX_PAGES_LIMIT, locateRows } from './auto-paginate.js';
24
24
  export { buildPagination, parseSort };
25
25
  import { resolveAddress, isEnsName } from './ens.js';
@@ -32,6 +32,7 @@ import { collectCacheStats, clearCaches, formatCacheStats, formatCacheClear } fr
32
32
  import { creditWarning, noticeWarnings } from './response-meta.js';
33
33
  import { trackCommandSucceeded, trackCommandFailed, trackAuthCommand } from './telemetry.js';
34
34
  import { setDebugEnabled } from './debug.js';
35
+ import { telemetryFlagNames } from './telemetry-flags.js';
35
36
  import { createRequire } from 'module';
36
37
  import * as readline from 'readline';
37
38
 
@@ -224,7 +225,7 @@ export function compactSchema(schema) {
224
225
  // rather than swallowing the token after it.
225
226
  export const VALUELESS_FLAGS = new Set([
226
227
  'pretty', 'help', 'version', 'table', 'no-retry', 'cache', 'no-cache', 'stream',
227
- 'enrich', 'full', 'human', 'no-browser', 'api-key-stdin', 'enabled', 'disabled', 'expert', 'json', 'offline',
228
+ 'enrich', 'full', 'human', 'no-browser', 'api-key-stdin', 'webhook-secret-stdin', 'enabled', 'disabled', 'expert', 'json', 'offline',
228
229
  'no-simulate', 'no-verify-outcome', 'no-revoke-excessive-allowance', 'dry-run',
229
230
  'send-api-key', 'all', 'max', 'gasless', 'auto-slippage', 'unsafe-no-password',
230
231
  'reveal', 'yes', 'paginate', 'debug', 'new',
@@ -1009,8 +1010,9 @@ export async function traceCounterparties(api, params = {}) {
1009
1010
  queue.push({ addr: cpAddr, hop: hop + 1 });
1010
1011
  }
1011
1012
  }
1012
- } catch {
1013
- // Skip addresses that fail (404, etc) but continue the traversal
1013
+ } catch (error) {
1014
+ if (hop === 0) throw error;
1015
+ // Keep later lookups best-effort once the root has been fetched.
1014
1016
  }
1015
1017
 
1016
1018
  if (queue.length > 0) await sleep(delayMs);
@@ -1150,6 +1152,11 @@ export const HELP = `Nansen CLI v${VERSION} - analytics and DEX trading for AI a
1150
1152
 
1151
1153
  USAGE: nansen <command> [subcommand] [options]
1152
1154
 
1155
+ GET STARTED:
1156
+ nansen login Sign in through browser approval
1157
+ nansen research smart-money netflow --chain solana What smart money is buying and selling
1158
+ nansen trade quote --chain solana --from SOL --to USDC --amount 1000000000
1159
+
1153
1160
  COMMANDS:
1154
1161
  trade DEX swaps/bridges: quote, execute, bridge-status, limit-order
1155
1162
  bridge Hyperliquid bridge: quote, execute, status (EVM <-> HL)
@@ -1159,7 +1166,7 @@ COMMANDS:
1159
1166
  agent Ask the Nansen AI research agent (fast/expert modes)
1160
1167
  alerts list, create, update, toggle, delete
1161
1168
  feedback preferences, submit, resume, forget local data, or get a receipt (--json for structured output)
1162
- web search, fetch
1169
+ web search
1163
1170
  mcp install/uninstall/verify the Nansen MCP server
1164
1171
  account Check the effective credential, plan, and remaining credits (free)
1165
1172
  auth status — offline credential source and cached/unverified session metadata
@@ -1170,16 +1177,26 @@ COMMANDS:
1170
1177
  completion Shell completions: bash, zsh, fish
1171
1178
  cache stats, clear
1172
1179
  changelog --since <version> to filter
1180
+ help Topics: auth, options, examples, chains, labels, deprecated, telemetry
1173
1181
 
1174
- OPTIONS: --chain --limit --page N --sort field:dir --fields a,b --days N --filters '{}'
1175
- PAGING: --paginate (alias --all) fetch every page, --max-pages N (default 10), --limit sets page size
1176
- FORMAT: --pretty --table --format csv --stream (NDJSON)
1177
- RETRY: --no-retry --retries N --cache --cache-ttl N
1178
- DEBUG: --debug (or NANSEN_DEBUG=1) traces each request on stderr: method, URL,
1179
- status, time-to-headers (TTFB), retries, request id. Never prints
1180
- credentials or bodies.
1182
+ MORE HELP:
1183
+ nansen <command> --help Subcommands and options for one command
1184
+ nansen help <topic> One topic (see "help" above)
1185
+ nansen schema JSON schema for every command
1186
+ Docs: https://docs.nansen.ai
1187
+ Skills: npx -y skills add nansen-ai/nansen-cli --skill "*" -y (agent docs per command group)
1188
+
1189
+ Telemetry: anonymous usage stats. Details: nansen help telemetry. Disable: DO_NOT_TRACK=1
1190
+ `;
1181
1191
 
1182
- AUTHENTICATION:
1192
+ /**
1193
+ * Detail that used to sit on the top-level page, one topic per
1194
+ * `nansen help <topic>`. The top page stays a short index (every fresh agent
1195
+ * reads it), so longer reference text belongs here. Each topic is also a
1196
+ * `help` subcommand in schema.json, which feeds `nansen schema` and completion.
1197
+ */
1198
+ export const HELP_TOPICS = {
1199
+ auth: `AUTHENTICATION:
1183
1200
  nansen login Fresh browser approval, even with an existing key/session
1184
1201
  nansen login --no-browser Same approval without opening the browser
1185
1202
  nansen auth status Offline, cached/unverified; does not open session storage
@@ -1192,9 +1209,15 @@ AUTHENTICATION:
1192
1209
  Browser sessions renew automatically; uncertain renewal requires fresh login.
1193
1210
  Browser nansen:api sessions have API-key-equivalent account permissions; wallet signing is separate.
1194
1211
  Browser login is enabled in production; saved sessions need native storage (see docs/browser-login.md).
1195
- Public API endpoints keep their usual account, plan and credit checks; MCP key export is separate.
1196
-
1197
- TRADING:
1212
+ Public API endpoints keep their usual account, plan and credit checks; MCP key export is separate.`,
1213
+ options: `OPTIONS: --chain --limit --page N --sort field:dir --fields a,b --days N --filters '{}'
1214
+ PAGING: --paginate (alias --all) fetch every page, --max-pages N (default 10), --limit sets page size
1215
+ FORMAT: --pretty --table --format csv --stream (NDJSON)
1216
+ RETRY: --no-retry --retries N --cache --cache-ttl N
1217
+ DEBUG: --debug (or NANSEN_DEBUG=1) traces each request on stderr: method, URL,
1218
+ status, time-to-headers (TTFB), retries, request id. Never prints
1219
+ credentials or bodies.`,
1220
+ examples: `TRADING:
1198
1221
  nansen trade quote --chain solana --from SOL --to USDC --amount 1000000000
1199
1222
  nansen trade execute --quote <quoteId>
1200
1223
  nansen trade bridge-status --tx-hash <hash> --from-chain base --to-chain solana
@@ -1212,22 +1235,16 @@ EXAMPLES:
1212
1235
  nansen trade quote --chain base --to-chain solana --from USDC --to USDC --amount 1000000
1213
1236
  nansen research smart-money netflow --chain solana
1214
1237
  nansen research token screener --chain solana --timeframe 24h
1215
- nansen research profiler balance --address 0x... --chain ethereum
1216
-
1217
- DEPRECATED ALIASES (still work, will be removed in a future version):
1218
- smart-money, profiler, token, search, portfolio → use "nansen research <command>"
1219
- quote, execute → use "nansen trade <command>"
1220
-
1221
- Research chains: ${SCHEMA.chains.join(', ')}
1238
+ nansen research profiler balance --address 0x... --chain ethereum`,
1239
+ chains: `Research chains: ${SCHEMA.chains.join(', ')}
1222
1240
  Trade chains: solana, base
1223
- Bridge routes: ${formatBridgeRoutes()}
1224
- Labels: Smart Trader, 30D/90D/180D Smart Trader, Smart HL Perps Trader (Smart Trader covers all windows; Fund is no longer a Smart Money label)
1225
-
1226
- Docs: https://docs.nansen.ai
1227
- Skills: npx skills add nansen-ai/nansen-cli (agent-optimised docs per command group)
1228
-
1229
- Telemetry: anonymous usage stats (commands, timing, errors). Perp order/close additionally send each leg's side, outcome, order id, shared submission id, and a SHA-256 wallet identifier. Raw wallet, price, size, and exchange error text are not sent. Disable: DO_NOT_TRACK=1
1230
- `;
1241
+ Bridge routes: ${formatBridgeRoutes()}`,
1242
+ labels: `Labels: Smart Trader, 30D/90D/180D Smart Trader, Smart HL Perps Trader (Smart Trader covers all windows; Fund is no longer a Smart Money label)`,
1243
+ deprecated: `DEPRECATED ALIASES (still work, will be removed in a future version):
1244
+ smart-money, profiler, token, search, portfolio → use "nansen research <command>"
1245
+ quote, execute → use "nansen trade <command>"`,
1246
+ telemetry: `Telemetry: anonymous usage stats (commands, timing, errors). Perp order/close additionally send each leg's side, outcome, order id, shared submission id, and a SHA-256 wallet identifier. Raw wallet, price, size, and exchange error text are not sent. Disable: DO_NOT_TRACK=1`,
1247
+ };
1231
1248
 
1232
1249
  // Usage text for the `cache` command group. Also the answer to "which commands
1233
1250
  // cache?" — caching is decided by the request path, so the rule lives here (and
@@ -1249,7 +1266,7 @@ WHAT CACHES:
1249
1266
  every read the CLI makes through the Nansen API client is served from and
1250
1267
  written to the response cache — that is all of "nansen research ...", plus
1251
1268
  "alerts list" and "alerts get".
1252
- Never cached: account, web search, web fetch, alerts create/update/toggle/delete,
1269
+ Never cached: account, web search, alerts create/update/toggle/delete,
1253
1270
  agent (streamed), feedback, every trade, bridge, wallet and mcp command, and perp trading.
1254
1271
  The analytics commands "perp screener" and "perp leaderboard" are cached.
1255
1272
 
@@ -1283,7 +1300,9 @@ USAGE:
1283
1300
  nansen trade quote --chain <chain> --to-chain <chain> --from <token> --to <token> --amount <units>
1284
1301
  nansen trade execute --quote <quoteId> [--wallet <name>] [--dry-run] [--yes]
1285
1302
  nansen trade bridge-status --tx-hash <hash> --from-chain <chain> --to-chain <chain>
1286
- nansen trade limit-order <create|list|cancel|update> [options]
1303
+ nansen trade limit-order create [options] [--dry-run] [--yes]
1304
+ nansen trade limit-order cancel --order <orderId> [--dry-run] [--yes]
1305
+ nansen trade limit-order <list|update> [options]
1287
1306
 
1288
1307
  EXAMPLES:
1289
1308
  nansen trade quote --chain solana --from SOL --to USDC --amount 1000000000
@@ -1298,9 +1317,10 @@ WALLET:
1298
1317
  --wallet <name> Use a named wallet, or "walletconnect" / "wc" for WalletConnect.
1299
1318
  Defaults to the default local wallet if omitted.
1300
1319
 
1301
- BEFORE BROADCASTING (execute only):
1302
- --dry-run Validate and print what would be sent, then stop. Nothing is
1303
- signed or broadcast and the quote stays usable. Exits 0.
1320
+ BEFORE SIGNING (execute and limit-order create/cancel):
1321
+ --dry-run Print the execution or intent plan, then stop before signing
1322
+ or final submission. Limit-order preview makes no API request;
1323
+ cancel preview never requests its one-time transaction. Exits 0.
1304
1324
  --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt
1305
1325
  only appears when stdin is a terminal — agents, CI and pipes run
1306
1326
  unprompted either way. Declining exits 1 with nothing signed.
@@ -1519,46 +1539,18 @@ export function buildCommands(deps = {}) {
1519
1539
  return apiInstance.webSearch({ queries, numResults });
1520
1540
  },
1521
1541
 
1522
- 'fetch': async () => {
1523
- // Accept URLs as positional args or --url (repeated)
1524
- let urls = subArgs.length > 0 ? subArgs : [];
1525
- if (options.url !== undefined) {
1526
- const fromOption = Array.isArray(options.url) ? options.url : [options.url];
1527
- urls = urls.concat(fromOption);
1528
- }
1529
- if (urls.length === 0) {
1530
- throw new NansenError('At least one URL is required. Usage: nansen web fetch https://example.com --question "What is this about?"', ErrorCode.MISSING_PARAM);
1531
- }
1532
- for (const u of urls) {
1533
- try { new URL(u); } catch {
1534
- throw new NansenError(`Invalid URL: "${u}". URLs must include a scheme, e.g. https://example.com`, ErrorCode.INVALID_PARAMS);
1535
- }
1536
- }
1537
- if (Array.isArray(options.question)) {
1538
- throw new NansenError('--question may only be specified once', ErrorCode.INVALID_PARAMS);
1539
- }
1540
- if (options.question !== undefined && typeof options.question !== 'string') {
1541
- throw new NansenError('--question must be a string', ErrorCode.INVALID_PARAMS);
1542
- }
1543
- if (!options.question || !options.question.trim()) {
1544
- throw new NansenError('--question is required and cannot be blank. Usage: nansen web fetch https://example.com --question "What is this about?"', ErrorCode.MISSING_PARAM);
1545
- }
1546
- return apiInstance.webFetch({ urls, question: options.question });
1547
- },
1548
-
1549
1542
  'help': async () => ({
1550
- subcommands: ['search', 'fetch'],
1551
- description: 'Web search and fetch commands',
1543
+ subcommands: ['search'],
1544
+ description: 'Web search commands',
1552
1545
  examples: [
1553
1546
  'nansen web search "bitcoin price"',
1554
1547
  'nansen web search "solana news" --num-results 5',
1555
- 'nansen web fetch https://nansen.ai --question "What does Nansen do?"',
1556
1548
  ],
1557
1549
  }),
1558
1550
  };
1559
1551
 
1560
1552
  if (!Object.hasOwn(handlers, subcommand)) {
1561
- throw unknownCommandError('web subcommand', subcommand, ['search', 'fetch']);
1553
+ throw unknownCommandError('web subcommand', subcommand, ['search']);
1562
1554
  }
1563
1555
 
1564
1556
  return handlers[subcommand]();
@@ -1972,11 +1964,12 @@ export function buildCommands(deps = {}) {
1972
1964
  rejectBlankOption(options.chain, 'chain', 'solana');
1973
1965
  rejectBlankOption(options.chains, 'chains', 'solana');
1974
1966
  rejectBlankOption(options.timeframe, 'timeframe', '1d');
1967
+ rejectBlankOption(options.interval, 'interval', '1d');
1975
1968
  rejectBlankOption(options['buy-or-sell'], 'buy-or-sell', 'SELL');
1976
1969
  const subcommand = args[0] || 'help';
1977
1970
  const chain = options.chain || 'solana';
1978
- const tokenAddress = normalizeAddress(options.token || options['token-address'], chain);
1979
- const tokenSymbol = options.symbol || options['token-symbol'];
1971
+ const tokenAddress = normalizeAddress(options.token, chain);
1972
+ const tokenSymbol = options.symbol;
1980
1973
  const chains = parseCsvOption(options.chains, 'chains') || [chain];
1981
1974
  const timeframe = options.timeframe || '24h';
1982
1975
  const filters = parseFiltersOption(options.filters);
@@ -2009,7 +2002,7 @@ export function buildCommands(deps = {}) {
2009
2002
 
2010
2003
  const handlers = {
2011
2004
  'indicators': () => apiInstance.tokenIndicators({ tokenAddress, chain }),
2012
- 'ohlcv': () => apiInstance.tokenOhlcv({ tokenAddress, chain, timeframe: options.timeframe || '1d' }),
2005
+ 'ohlcv': () => apiInstance.tokenOhlcv({ tokenAddress, chain, timeframe: options.interval || '1d' }),
2013
2006
  'info': () => apiInstance.tokenInformation({ tokenAddress, chain, timeframe: options.timeframe }),
2014
2007
  'screener': async () => {
2015
2008
  const search = options.search;
@@ -2298,7 +2291,7 @@ export function buildCommands(deps = {}) {
2298
2291
  };
2299
2292
 
2300
2293
  // 'research' delegates to the category handlers defined above
2301
- const RESEARCH_CATEGORIES = new Set(['smart-money', 'profiler', 'token', 'search', 'perp', 'portfolio', 'points', 'prediction-market']);
2294
+ const RESEARCH_CATEGORIES = new Set(['smart-money', 'profiler', 'token', 'search', 'perp', 'portfolio', 'prediction-market']);
2302
2295
 
2303
2296
  // The analytics-only perp handler, captured before the trading wrapper below
2304
2297
  // replaces cmds['perp']. Both the wrapper and the research dispatch route to
@@ -2323,7 +2316,7 @@ export function buildCommands(deps = {}) {
2323
2316
  return researchSub(args, apiInstance, flags, options);
2324
2317
  }
2325
2318
  const category = RESEARCH_CATEGORY_ALIASES[rawCategory] || rawCategory;
2326
- if (!RESEARCH_CATEGORIES.has(category)) {
2319
+ if (!RESEARCH_CATEGORIES.has(category) && !UNAVAILABLE_COMMANDS.has(category)) {
2327
2320
  throw unknownCommandError('research category', rawCategory, [...RESEARCH_CATEGORIES, ...RESEARCH_SUBCOMMANDS]);
2328
2321
  }
2329
2322
  // `research perp` reaches only the analytics half (screener/leaderboard) —
@@ -2339,7 +2332,7 @@ export function buildCommands(deps = {}) {
2339
2332
  // 'trade' delegates to quote/execute from buildTradingCommands and limit-order from buildLimitOrderCommands
2340
2333
  const executionDeps = { ...deps, promptFn: confirmationPromptFn };
2341
2334
  const tradingCmds = buildTradingCommands(executionDeps);
2342
- const limitOrderCmds = buildLimitOrderCommands(deps);
2335
+ const limitOrderCmds = buildLimitOrderCommands(executionDeps);
2343
2336
  cmds['trade'] = async (args, apiInstance, flags, options) => {
2344
2337
  const sub = args[0];
2345
2338
  if (!sub || sub === 'help') {
@@ -2358,9 +2351,9 @@ SUBCOMMANDS:
2358
2351
  update Update trigger price or slippage
2359
2352
 
2360
2353
  USAGE:
2361
- nansen trade limit-order create --from <token> --to <token> --amount <units> --trigger-mint <token> --trigger-condition <above|below> --trigger-price <usd>
2354
+ nansen trade limit-order create --from <token> --to <token> --amount <units> --trigger-mint <token> --trigger-condition <above|below> --trigger-price <usd> [--dry-run] [--yes]
2362
2355
  nansen trade limit-order list [--state <active|past>]
2363
- nansen trade limit-order cancel --order <orderId>
2356
+ nansen trade limit-order cancel --order <orderId> [--dry-run] [--yes]
2364
2357
  nansen trade limit-order update --order <orderId> --trigger-price <usd>`);
2365
2358
  return;
2366
2359
  }
@@ -2411,7 +2404,7 @@ SUPPORTED ROUTES:
2411
2404
  // top of the pre-existing perp analytics command, so capture that handler and
2412
2405
  // keep screener/leaderboard reachable instead of shadowing them — both
2413
2406
  // `nansen perp screener` and `nansen research perp screener` route through here.
2414
- const perpCmds = buildPerpCommands(deps);
2407
+ const perpCmds = buildPerpCommands(executionDeps);
2415
2408
  const PERP_ANALYTICS_SUBCOMMANDS = new Set(['screener', 'leaderboard']);
2416
2409
  cmds['perp'] = async (args, apiInstance, flags, options) => {
2417
2410
  const sub = args[0];
@@ -2433,14 +2426,19 @@ SUBCOMMANDS:
2433
2426
  leaderboard Perp trader leaderboard (analytics)
2434
2427
 
2435
2428
  USAGE:
2436
- nansen perp order --coin BTC --side buy --size 0.001 --price 50000 --type limit
2437
- nansen perp cancel --coin BTC --oid 12345
2438
- nansen perp close --coin BTC --size 0.001 --price 100000 --side sell
2439
- nansen perp leverage --coin BTC --leverage 10 --margin-type cross
2429
+ nansen perp order --symbol BTC --side buy --size 0.001 --price 50000 --type limit
2430
+ nansen perp cancel --symbol BTC --oid 12345
2431
+ nansen perp close --symbol BTC --size 0.001 --price 100000 --side sell
2432
+ nansen perp leverage --symbol BTC --leverage 10 --margin-type cross
2440
2433
  nansen perp transfer --direction spot-to-perp --amount 25
2441
2434
  nansen perp approve-builder-fee
2442
2435
  nansen perp positions
2443
- nansen perp account`);
2436
+ nansen perp account
2437
+
2438
+ BEFORE SUBMITTING (order, cancel, close, leverage):
2439
+ --dry-run Validate and print what would be submitted, then stop. Exits 0.
2440
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt only
2441
+ appears when stdin is a terminal; declining exits 1, signing nothing.`);
2444
2442
  return;
2445
2443
  }
2446
2444
  if (!perpCmds[sub]) {
@@ -2460,6 +2458,31 @@ export const DEPRECATED_TO_RESEARCH = new Set(['smart-money', 'profiler', 'token
2460
2458
  // Subcommands that moved under 'trade'
2461
2459
  export const DEPRECATED_TO_TRADE = new Set(['quote', 'execute']);
2462
2460
 
2461
+ // Subcommands of removed commands (UNAVAILABLE_COMMANDS), which have no schema entry.
2462
+ const REMOVED_SUBCOMMANDS = { points: ['leaderboard'] };
2463
+
2464
+ /**
2465
+ * Command name for telemetry. Positionals are often values (a search query,
2466
+ * an address), so only subcommands listed in the schema are kept.
2467
+ */
2468
+ function telemetryCommandName(commands, command, subcommand) {
2469
+ if (!Object.hasOwn(commands, command)) return 'unknown';
2470
+ if (!subcommand) return command;
2471
+ if (command === 'research') {
2472
+ const category = RESEARCH_CATEGORY_ALIASES[subcommand] || subcommand;
2473
+ const known = Object.hasOwn(SCHEMA.commands.research.subcommands, category) || UNAVAILABLE_COMMANDS.has(category);
2474
+ return known ? `research ${category}` : 'research';
2475
+ }
2476
+ // `perp` is both a top-level command and a research category (screener, leaderboard).
2477
+ const known = [SCHEMA.commands[command]?.subcommands, SCHEMA.commands.research.subcommands[command]?.subcommands];
2478
+ if (known.some(subcommands => subcommands && Object.hasOwn(subcommands, subcommand))
2479
+ || REMOVED_SUBCOMMANDS[command]?.includes(subcommand)
2480
+ || Object.hasOwn(SUBCOMMAND_ALIASES[command] ?? {}, subcommand)) {
2481
+ return `${command} ${subcommand}`;
2482
+ }
2483
+ return command;
2484
+ }
2485
+
2463
2486
  // Command aliases: top-level shortcuts that resolve before routing
2464
2487
  export const COMMAND_ALIASES = {
2465
2488
  'tgm': 'token', // Token God Mode
@@ -2494,6 +2517,28 @@ function costHelpLines(endpoint, options = {}) {
2494
2517
  return lines;
2495
2518
  }
2496
2519
 
2520
+ // One line per positional arg and option, from the schema: name, required
2521
+ // marker, aliases, default, enum, and what it does. Every --help body that
2522
+ // lists options goes through here, so agents never need `nansen schema` just
2523
+ // to learn what a flag means.
2524
+ export function formatOptionHelp(options = {}, args = []) {
2525
+ const line = (label, opt) => {
2526
+ const parts = [`${label}${opt.required ? '*' : ''}`];
2527
+ if (opt.aliases?.length) parts.push(`(alias ${opt.aliases.map(a => `--${a}`).join(', ')})`);
2528
+ if (opt.default !== undefined) parts.push(`(${opt.default})`);
2529
+ if (opt.enum) parts.push(`[${opt.enum.join('|')}]`);
2530
+ if (opt.repeatable) parts.push('(repeatable)');
2531
+ if (opt.requiredUnless?.length) parts.push(`(unless ${opt.requiredUnless.map(o => `--${o}`).join(', ')})`);
2532
+ if (opt.description) parts.push(`— ${opt.description}`);
2533
+ return ` ${parts.join(' ')}`;
2534
+ };
2535
+ const lines = [
2536
+ ...args.map(arg => line(`<${arg.name}>`, arg)),
2537
+ ...Object.entries(options).map(([name, opt]) => line(`--${name}`, opt)),
2538
+ ];
2539
+ return lines.length ? ['Options (* required):', ...lines] : [];
2540
+ }
2541
+
2497
2542
  // Generate help text for a specific subcommand using SCHEMA
2498
2543
  export function generateSubcommandHelp(command, subcommand, prefix = null) {
2499
2544
  // `perp` is both a top-level trading command and a research category, and
@@ -2520,23 +2565,7 @@ export function generateSubcommandHelp(command, subcommand, prefix = null) {
2520
2565
  return lines.join('\n');
2521
2566
  }
2522
2567
 
2523
- const positional = subSchema.args ?? [];
2524
- if (subSchema.options || positional.length) {
2525
- const describe = (label, opt) => {
2526
- const parts = [`${label}${opt.required ? '*' : ''}`];
2527
- if (opt.default !== undefined) parts.push(`(${opt.default})`);
2528
- if (opt.enum) parts.push(`[${opt.enum.join('|')}]`);
2529
- if (command.startsWith('trade') && opt.description) parts.push(`— ${opt.description}`);
2530
- return parts.join(' ');
2531
- };
2532
- const params = [
2533
- ...positional.map(arg => describe(`<${arg.name}>`, arg)),
2534
- ...Object.entries(subSchema.options ?? {}).map(([name, opt]) => describe(`--${name}`, opt)),
2535
- ];
2536
- lines.push(command.startsWith('trade')
2537
- ? `Options (* required):\n ${params.join('\n ')}`
2538
- : `Params (* required): ${params.join(', ')}`);
2539
- }
2568
+ lines.push(...formatOptionHelp(subSchema.options, subSchema.args));
2540
2569
 
2541
2570
  if (subSchema.supportedChains?.length) {
2542
2571
  lines.push(`Chains: ${subSchema.supportedChains.join(', ')}`);
@@ -2581,6 +2610,18 @@ export function generateSubcommandHelp(command, subcommand, prefix = null) {
2581
2610
  return lines.join('\n');
2582
2611
  }
2583
2612
 
2613
+ // A research command run without --chain/--chains uses its schema default
2614
+ // chain. Say so in `_meta.defaults.chain`, so an agent that left the chain out
2615
+ // knows which chain the data is for. The schema default is the chain the
2616
+ // handler sends (a test checks this). Only plain-object results get it, like
2617
+ // `_meta.search`; arrays, --fields, --stream, --table and CSV are unchanged.
2618
+ export function withDefaultChainMeta(result, researchCommand, options) {
2619
+ const chain = researchCommand?.leaf?.options?.chain?.default;
2620
+ if (chain === undefined || options.chain !== undefined || options.chains !== undefined) return result;
2621
+ if (!result || typeof result !== 'object' || Array.isArray(result)) return result;
2622
+ return { ...result, _meta: { ...result._meta, defaults: { ...result._meta?.defaults, chain } } };
2623
+ }
2624
+
2584
2625
  function emitResponseMetadata(api, errorOutput) {
2585
2626
  if (!api) return;
2586
2627
  const responseMeta = api.paginatedResponseMeta || api.lastResponseMeta;
@@ -2591,9 +2632,10 @@ function emitResponseMetadata(api, errorOutput) {
2591
2632
  // An aggregate belongs to the primary paginated endpoint even if a composite
2592
2633
  // handler made auxiliary requests afterward and changed lastEndpoint.
2593
2634
  const endpoint = api.paginatedResponseMeta ? api.paginatedEndpoint : api.lastEndpoint;
2594
- // A cache hit records no response meta; with no live call at all there is
2595
- // nothing to estimate.
2596
- if (!responseMeta && api.servedFromCache === true) {
2635
+ // Cached advisories can supply metadata without any live accounting.
2636
+ // With no live call at all there is nothing to estimate.
2637
+ if (api.servedFromCache === true && !api.paginatedResponseMeta
2638
+ && (!responseMeta || (!responseMeta.credits && !api.lastEndpoint))) {
2597
2639
  errorOutput('Credits: 0 (cached)');
2598
2640
  return;
2599
2641
  }
@@ -2673,7 +2715,23 @@ export async function runCLI(rawArgs, deps = {}) {
2673
2715
  exit(1);
2674
2716
  return { type: 'error', data: errorData };
2675
2717
  }
2676
- const { _: positional, flags, options } = parsed;
2718
+ const { flags, options } = parsed;
2719
+ let positional = parsed._;
2720
+
2721
+ // `nansen help <topic>` prints one topic of HELP_TOPICS. `nansen help
2722
+ // <command> [sub...]` is the same request as `nansen <command> [sub...] --help`,
2723
+ // so rewrite it here and let the usual help paths answer it.
2724
+ let helpTopic = null;
2725
+ let helpRequestedFor = null;
2726
+ if (positional[0] === 'help' && positional.length > 1) {
2727
+ if (positional.length === 2 && Object.hasOwn(HELP_TOPICS, positional[1])) {
2728
+ helpTopic = positional[1];
2729
+ } else {
2730
+ helpRequestedFor = positional[1];
2731
+ positional = positional.slice(1);
2732
+ flags.help = true;
2733
+ }
2734
+ }
2677
2735
 
2678
2736
  // Resolve command aliases
2679
2737
  const rawCommand = positional[0] || 'help';
@@ -2691,18 +2749,36 @@ export async function runCLI(rawArgs, deps = {}) {
2691
2749
  const stream = flags.stream || flags.s;
2692
2750
  const csv = options.format === 'csv';
2693
2751
 
2752
+ // mcp prints its own output via `log`; runCLI callers inject their stdout
2753
+ // sink as `output`, so map it across (an explicit `log` dep still wins).
2754
+ // Only execute/login handlers consume the stdin-interactivity seam. Other
2755
+ // modules retain their existing deps: notably wallet export interprets
2756
+ // `isTTY` as stdout visibility when deciding whether to warn about printing
2757
+ // private keys, so substituting the stdin signal there changes its semantics.
2758
+ const commands = { ...buildCommands(inputInteractiveDeps), ...buildWalletCommands(deps), ...buildTradingCommands(topLevelTradingDeps), ...buildAlertsCommands(deps), ...buildAgentCommands(deps), ...buildFeedbackCommands({ ...deps, log: deps.log ?? output }), ...buildMcpCommands({ ...deps, log: deps.log ?? output }), ...buildCompletionCommands({ ...deps, log: deps.log ?? output }), ...commandOverrides };
2759
+
2694
2760
  // Commands in this set promise zero network activity. That includes update
2695
2761
  // checks, cost-map refreshes and telemetry, not just their primary work.
2696
2762
  // `cache` belongs here specifically so inspecting or clearing caches cannot
2697
- // recreate update/telemetry state during the same invocation.
2763
+ // recreate update/telemetry state during the same invocation. `help` is the
2764
+ // top-level page and its topics only: `help <command>` was rewritten above,
2765
+ // so it behaves like `<command> --help`.
2698
2766
  const isMcpUsage = command === 'mcp' && (subcommand !== 'verify' || flags.help || flags.h);
2699
2767
  const isAuthMutation = command === 'login' || command === 'logout';
2768
+ const isOfflineLimitOrderDryRun = command === 'trade'
2769
+ && subArgs[0] === 'limit-order'
2770
+ && (subArgs[1] === 'create' || subArgs[1] === 'cancel')
2771
+ && flags['dry-run'] === true;
2700
2772
  const isOfflineCommand = command === 'auth'
2773
+ || command === 'help'
2701
2774
  || (command === 'doctor' && flags.offline)
2702
2775
  || isMcpUsage
2703
2776
  || command === 'completion'
2704
2777
  || command === 'cache'
2705
- || (command === 'feedback' && subcommand === 'forget');
2778
+ || (command === 'feedback' && subcommand === 'forget')
2779
+ || isOfflineLimitOrderDryRun
2780
+ // Help for a name that is not a command prints only the top page or an error.
2781
+ || ((flags.help || flags.h) && !commands[command]);
2706
2782
  const trackSucceeded = isOfflineCommand ? async () => {} : isAuthMutation ? metadata => trackAuthCommand({ ...metadata, command }) : trackCommandSucceeded;
2707
2783
  const trackFailed = isOfflineCommand ? async () => {} : isAuthMutation ? metadata => trackAuthCommand({ ...metadata, command, failed: true }) : trackCommandFailed;
2708
2784
 
@@ -2722,23 +2798,27 @@ export async function runCLI(rawArgs, deps = {}) {
2722
2798
  return '';
2723
2799
  };
2724
2800
 
2725
- // mcp prints its own output via `log`; runCLI callers inject their stdout
2726
- // sink as `output`, so map it across (an explicit `log` dep still wins).
2727
- // Only execute/login handlers consume the stdin-interactivity seam. Other
2728
- // modules retain their existing deps: notably wallet export interprets
2729
- // `isTTY` as stdout visibility when deciding whether to warn about printing
2730
- // private keys, so substituting the stdin signal there changes its semantics.
2731
- const commands = { ...buildCommands(inputInteractiveDeps), ...buildWalletCommands(deps), ...buildTradingCommands(topLevelTradingDeps), ...buildAlertsCommands(deps), ...buildAgentCommands(deps), ...buildFeedbackCommands({ ...deps, log: deps.log ?? output }), ...buildMcpCommands({ ...deps, log: deps.log ?? output }), ...buildCompletionCommands({ ...deps, log: deps.log ?? output }), ...commandOverrides };
2732
-
2733
2801
  if (flags.version || flags.v) {
2734
2802
  output(VERSION);
2735
2803
  return { type: 'version', data: VERSION };
2736
2804
  }
2737
2805
 
2738
- if (command === 'help' || flags.help || flags.h) {
2806
+ // A removed command has no help to show: let its handler answer --help with
2807
+ // the same COMMAND_UNAVAILABLE error, rather than printing a generic listing.
2808
+ const unavailableCommand = UNAVAILABLE_COMMANDS.has(command)
2809
+ || (command === 'research' && UNAVAILABLE_COMMANDS.has(RESEARCH_CATEGORY_ALIASES[subcommand] || subcommand));
2810
+ if (command === 'help' || ((flags.help || flags.h) && !unavailableCommand)) {
2739
2811
  // Help for an offline command still owes the zero-network contract: the
2740
2812
  // cost-map refresh fetches the OpenAPI spec and writes ~/.nansen/cost-map.json.
2741
- if (!isOfflineCommand && !isAuthMutation) await refreshCostMapIfStale();
2813
+ // The top-level page and its topics (`help` is offline) show no costs, so
2814
+ // they skip the refresh: on a cold or stale cache it fetches the spec
2815
+ // before printing.
2816
+ if (commands[command] && !isOfflineCommand && !isAuthMutation) await refreshCostMapIfStale();
2817
+ if (helpTopic) {
2818
+ output(HELP_TOPICS[helpTopic]);
2819
+ notify();
2820
+ return { type: 'help-topic', topic: helpTopic };
2821
+ }
2742
2822
  // Check for subcommand-specific help: nansen <command> <subcommand> --help
2743
2823
  if (flags.help || flags.h) {
2744
2824
  // Handle 'research <category> <sub> --help' (3-level)
@@ -2763,13 +2843,7 @@ export async function runCLI(rawArgs, deps = {}) {
2763
2843
  lines.push(`Use: nansen research ${category} <subcommand> --help`);
2764
2844
  } else if (catSchema.options) {
2765
2845
  // Leaf historical subcommand: render options + example
2766
- const params = Object.entries(catSchema.options).map(([name, opt]) => {
2767
- const parts = [`--${name}`];
2768
- if (opt.required) parts[0] += '*';
2769
- if (opt.default !== undefined) parts.push(`(${opt.default})`);
2770
- return parts.join(' ');
2771
- });
2772
- lines.push(`Params (* required): ${params.join(', ')}`);
2846
+ lines.push(...formatOptionHelp(catSchema.options));
2773
2847
  if (catSchema.endpoint) lines.push(...costHelpLines(catSchema.endpoint, catSchema.options));
2774
2848
  }
2775
2849
  output(lines.join('\n'));
@@ -2779,7 +2853,7 @@ export async function runCLI(rawArgs, deps = {}) {
2779
2853
  }
2780
2854
  // First try subcommand help
2781
2855
  // Skip for 'trade'/'alerts' — their handlers show their own rich usage
2782
- if (command && subcommand && command !== 'trade' && command !== 'alerts' && command !== 'agent') {
2856
+ if (command && subcommand && command !== 'help' && command !== 'trade' && command !== 'alerts' && command !== 'agent') {
2783
2857
  const subHelp = generateSubcommandHelp(command, subcommand);
2784
2858
  if (subHelp) {
2785
2859
  output(deprecationNote(command) + subHelp);
@@ -2789,7 +2863,9 @@ export async function runCLI(rawArgs, deps = {}) {
2789
2863
  }
2790
2864
  // Then try command-level help (list subcommands)
2791
2865
  // Skip for 'trade'/'alerts'/'cache' — let the handler show its own usage
2792
- const cmdSchemaLookup = command !== 'trade' && command !== 'alerts' && command !== 'agent' && command !== 'cache' && (SCHEMA.commands[command] || SCHEMA.commands.research.subcommands[command]);
2866
+ // `help` is in schema.json for `nansen schema` and completion, but
2867
+ // `nansen --help` and `nansen help --help` show the top-level page.
2868
+ const cmdSchemaLookup = command !== 'help' && command !== 'trade' && command !== 'alerts' && command !== 'agent' && command !== 'cache' && (SCHEMA.commands[command] || SCHEMA.commands.research.subcommands[command]);
2793
2869
  if (command && cmdSchemaLookup) {
2794
2870
  const cmdSchema = cmdSchemaLookup;
2795
2871
  const lines = [`${command} — ${cmdSchema.description}`];
@@ -2798,16 +2874,8 @@ export async function runCLI(rawArgs, deps = {}) {
2798
2874
  lines.push('Subcommands: ' + Object.keys(cmdSchema.subcommands).join(', '));
2799
2875
  lines.push(`Use: nansen ${command} <subcommand> --help`);
2800
2876
  }
2801
- if (cmdSchema.options) {
2802
- const params = Object.entries(cmdSchema.options).map(([name, opt]) => {
2803
- const parts = [`--${name}`];
2804
- if (opt.required) parts[0] += '*';
2805
- if (opt.default !== undefined) parts.push(`(default: ${opt.default})`);
2806
- if (opt.description) parts.push(`— ${opt.description}`);
2807
- return parts.join(' ');
2808
- });
2809
- lines.push(`\nOptions (* required):\n ${params.join('\n ')}`);
2810
- }
2877
+ const optionLines = formatOptionHelp(cmdSchema.options);
2878
+ if (optionLines.length) lines.push(`\n${optionLines.join('\n')}`);
2811
2879
  if (cmdSchema.examples?.length) {
2812
2880
  lines.push(`\nExamples:\n ${cmdSchema.examples.join('\n ')}`);
2813
2881
  }
@@ -2839,6 +2907,14 @@ export async function runCLI(rawArgs, deps = {}) {
2839
2907
  notify();
2840
2908
  return { type: 'command-help', command };
2841
2909
  }
2910
+ // `nansen help <name>` where <name> is neither a topic nor a command.
2911
+ if (helpRequestedFor && !commands[command]) {
2912
+ const available = [...new Set([...Object.keys(HELP_TOPICS), ...Object.keys(commands).filter(name => name !== 'help' && !UNAVAILABLE_COMMANDS.has(name))])];
2913
+ const errorData = formatError(unknownCommandError('help topic or command', helpRequestedFor, available));
2914
+ output(formatOutput(errorData, { pretty, table, csv }).text);
2915
+ exit(1);
2916
+ return { type: 'error', data: errorData };
2917
+ }
2842
2918
  // 'help' and unknown commands: full banner + command list
2843
2919
  if (command === 'help' || !commands[command]) {
2844
2920
  output(BANNER + HELP);
@@ -2850,9 +2926,13 @@ export async function runCLI(rawArgs, deps = {}) {
2850
2926
  // ── Telemetry setup ──
2851
2927
  const startTime = Date.now();
2852
2928
  const fullCommand = subcommand ? `${command} ${subcommand}` : command;
2929
+ const telemetryCommand = telemetryCommandName(commands, command, subcommand);
2853
2930
  const flagNames = Object.keys(flags).filter(k => flags[k]).map(k => `--${k}`);
2854
2931
  const optionNames = Object.keys(options).map(k => `--${k}`);
2855
- const usedFlags = [...flagNames, ...optionNames];
2932
+ // Only names the CLI defines reach telemetry (login/logout keep their own set).
2933
+ const usedFlags = isAuthMutation
2934
+ ? [...flagNames, ...optionNames]
2935
+ : telemetryFlagNames({ schema: SCHEMA, command, subArgs, switches: VALUELESS_FLAGS }, [...flagNames, ...optionNames]);
2856
2936
  const chain = options.chain || null;
2857
2937
 
2858
2938
  if (!commands[command]) {
@@ -2861,7 +2941,7 @@ export async function runCLI(rawArgs, deps = {}) {
2861
2941
  // or an unquoted shell variable under zsh (which, unlike bash, does not
2862
2942
  // word-split `$var`). Point the user straight at the cause instead of a bare
2863
2943
  // "Unknown command" that reads like a spurious failure.
2864
- const available = Object.keys(commands);
2944
+ const available = Object.keys(commands).filter(name => !UNAVAILABLE_COMMANDS.has(name));
2865
2945
  const error = /\s/.test(command)
2866
2946
  ? new NansenError(
2867
2947
  `Unknown command: "${command}". This looks like multiple words passed as one argument — check your shell quoting (use \`nansen trade --help\`, not \`nansen "trade --help"\`).`,
@@ -2871,7 +2951,7 @@ export async function runCLI(rawArgs, deps = {}) {
2871
2951
  const errorData = formatError(error);
2872
2952
  const formatted = formatOutput(errorData, { pretty, table, csv });
2873
2953
  output(formatted.text);
2874
- await trackFailed({ command: fullCommand, duration_ms: Date.now() - startTime, error_code: ErrorCode.UNKNOWN_COMMAND, flags: usedFlags, chain });
2954
+ await trackFailed({ command: telemetryCommand, duration_ms: Date.now() - startTime, error_code: ErrorCode.UNKNOWN_COMMAND, flags: usedFlags, chain });
2875
2955
  exit(1);
2876
2956
  return { type: 'error', data: errorData };
2877
2957
  }
@@ -2907,11 +2987,16 @@ export async function runCLI(rawArgs, deps = {}) {
2907
2987
  if (options['x402-payment-signature']) {
2908
2988
  defaultHeaders['Payment-Signature'] = options['x402-payment-signature'];
2909
2989
  }
2910
- api = new NansenAPIClass(undefined, undefined, { retry: retryOptions, cache: cacheOptions, defaultHeaders, authState: inputInteractiveDeps.authState });
2990
+ // Limit-order dry runs are intentionally local previews. In addition to
2991
+ // suppressing update checks and telemetry above, avoid constructing the API
2992
+ // client because its constructor resolves saved Nansen credentials.
2993
+ if (!isOfflineLimitOrderDryRun) {
2994
+ api = new NansenAPIClass(undefined, undefined, { retry: retryOptions, cache: cacheOptions, defaultHeaders, authState: inputInteractiveDeps.authState });
2995
+ }
2911
2996
 
2912
2997
  // --all aliases --paginate; wrapping api.request gives every list handler
2913
2998
  // the same max-pages bound while leaving non-list requests untouched.
2914
- if (flags.paginate || flags.all) {
2999
+ if ((flags.paginate || flags.all) && api) {
2915
3000
  const maxPages = parsePositiveSafeIntegerOption(
2916
3001
  'max-pages', options, flags, DEFAULT_MAX_PAGES, { max: MAX_PAGES_LIMIT },
2917
3002
  );
@@ -2939,7 +3024,13 @@ export async function runCLI(rawArgs, deps = {}) {
2939
3024
  // on the instance next to the cache-hit early return in request(), so it
2940
3025
  // survives that reshaping. Compared against `true` so a stubbed API whose
2941
3026
  // every property is a mock function doesn't read as a hit.
2942
- const fromCache = !!result?._meta?.fromCache || api.servedFromCache === true;
3027
+ //
3028
+ // A --paginate result mixes pages, and both of those describe a single
3029
+ // page; it was served from the cache only if no page went to the API.
3030
+ const paginatedPages = api?.paginatedResponseMeta?.pagination;
3031
+ const fromCache = paginatedPages
3032
+ ? paginatedPages.livePages === 0
3033
+ : !!result?._meta?.fromCache || api?.servedFromCache === true;
2943
3034
 
2944
3035
  // Credit balance warning, from the headers on the call just made. Goes to
2945
3036
  // stderr so it never contaminates the JSON on stdout that agents parse.
@@ -2949,14 +3040,14 @@ export async function runCLI(rawArgs, deps = {}) {
2949
3040
 
2950
3041
  // Commands that handle their own output return undefined
2951
3042
  if (result === undefined) {
2952
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, flags: usedFlags, chain });
3043
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, flags: usedFlags, chain });
2953
3044
  return { type: 'no-output', command };
2954
3045
  }
2955
3046
 
2956
3047
  // Feedback JSON is a complete receipt, even alongside list-format flags.
2957
3048
  if (command === 'feedback') {
2958
3049
  output(formatOutput({ success: true, data: result }, { pretty }).text);
2959
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: false, flags: usedFlags, chain });
3050
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, from_cache: false, flags: usedFlags, chain });
2960
3051
  return { type: 'success', data: result };
2961
3052
  }
2962
3053
 
@@ -2964,7 +3055,7 @@ export async function runCLI(rawArgs, deps = {}) {
2964
3055
  if (command === 'schema') {
2965
3056
  const formatted = formatOutput(result, { pretty, table: false });
2966
3057
  output(formatted.text);
2967
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, flags: usedFlags, chain });
3058
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, flags: usedFlags, chain });
2968
3059
  return { type: 'schema', data: result };
2969
3060
  }
2970
3061
 
@@ -2977,12 +3068,14 @@ export async function runCLI(rawArgs, deps = {}) {
2977
3068
  returns: researchCommand?.leaf?.returns,
2978
3069
  });
2979
3070
  result = filterFields(result, fields);
3071
+ } else if (!stream && !table && !csv) {
3072
+ result = withDefaultChainMeta(result, researchCommand, options);
2980
3073
  }
2981
3074
 
2982
3075
  // Alerts list with --table uses custom table format
2983
3076
  if (command === 'alerts' && subcommand === 'list' && table) {
2984
3077
  output(formatAlertsTable(result));
2985
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
3078
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2986
3079
  return { type: 'success', data: result };
2987
3080
  }
2988
3081
 
@@ -2993,14 +3086,14 @@ export async function runCLI(rawArgs, deps = {}) {
2993
3086
  if (streamOutput) {
2994
3087
  output(streamOutput);
2995
3088
  }
2996
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
3089
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2997
3090
  return { type: 'stream', data: result };
2998
3091
  }
2999
3092
 
3000
3093
  const successData = { success: true, data: result };
3001
3094
  const formatted = formatOutput(successData, { pretty, table, csv });
3002
3095
  output(formatted.text);
3003
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
3096
+ await trackSucceeded({ command: telemetryCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
3004
3097
  return { type: csv ? 'csv' : 'success', data: result };
3005
3098
  } catch (error) {
3006
3099
  // A failed later page can still have incurred charges on earlier pages.
@@ -3026,7 +3119,7 @@ export async function runCLI(rawArgs, deps = {}) {
3026
3119
  output(formatted.text);
3027
3120
  }
3028
3121
  await trackFailed({
3029
- command: fullCommand,
3122
+ command: telemetryCommand,
3030
3123
  duration_ms: Date.now() - startTime,
3031
3124
  error_code: error.code || 'UNKNOWN',
3032
3125
  status: error.status || null,