nansen-cli 2.2.0 → 2.3.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
@@ -13,6 +13,7 @@ import { buildPerpCommands } from './perp.js';
13
13
  import { buildTradingCommands } from './trading.js';
14
14
  import { buildLimitOrderCommands } from './limit-order.js';
15
15
  import { formatAlertsTable, buildAlertsCommands } from './commands/alerts.js';
16
+ import { buildFeedbackCommands, feedbackErrorText } from './commands/feedback.js';
16
17
  import { buildAgentCommands } from './commands/agent.js';
17
18
  import { buildMcpCommands } from './commands/mcp.js';
18
19
  import { buildCompletionCommands } from './commands/completion.js';
@@ -197,12 +198,15 @@ export function compactSchema(schema) {
197
198
  // Long options that never consume the next argument. The shell-completion
198
199
  // generator needs the same list to tell an option's value apart from a
199
200
  // subcommand, so it lives here rather than inline in parseArgs.
201
+ // `gasless` is retained after the flag's removal: trade execute rejects it
202
+ // explicitly, and that rejection only fires if it still parses as a boolean
203
+ // rather than swallowing the token after it.
200
204
  export const VALUELESS_FLAGS = new Set([
201
205
  'pretty', 'help', 'version', 'table', 'no-retry', 'cache', 'no-cache', 'stream',
202
206
  'enrich', 'full', 'human', 'no-browser', 'api-key-stdin', 'enabled', 'disabled', 'expert', 'json', 'offline',
203
207
  'no-simulate', 'no-verify-outcome', 'no-revoke-excessive-allowance', 'dry-run',
204
208
  'send-api-key', 'all', 'max', 'gasless', 'auto-slippage', 'unsafe-no-password',
205
- 'reveal', 'yes', 'paginate', 'debug',
209
+ 'reveal', 'yes', 'paginate', 'debug', 'new',
206
210
  ]);
207
211
 
208
212
  export function parseArgs(args) {
@@ -456,15 +460,55 @@ export function formatValue(val) {
456
460
  return String(val);
457
461
  }
458
462
 
463
+ // A row of the perp-positions payload: the wrapper plus its nested `position`.
464
+ // `position` may be absent because --fields runs before formatting and can
465
+ // strip it, so a wrapper-only entry is still a row. Anything else in that key
466
+ // means the payload is not the perp shape and belongs in the JSON fallback.
467
+ function isPositionEntry(entry) {
468
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return false;
469
+ const { position } = entry;
470
+ return position === undefined
471
+ || (position !== null && typeof position === 'object' && !Array.isArray(position));
472
+ }
473
+
474
+ // Perp positions wrap each row in `position`. Flatten only for tabular
475
+ // presentation so JSON output retains the API payload and account summaries.
476
+ function locateTabularRows(data) {
477
+ let sawPositions = false;
478
+ if (data?.success !== false) {
479
+ for (const payload of [data, data?.data, data?.data?.data]) {
480
+ const positions = payload?.asset_positions;
481
+ if (!Array.isArray(positions)) continue;
482
+ sawPositions = true;
483
+ const rows = positions.every(isPositionEntry)
484
+ ? positions.map(({ position, ...fields }) => ({ ...position, ...fields }))
485
+ : null;
486
+ // A row with no fields renders as a blank line, which tells the reader
487
+ // less than the JSON fallback does. Treat it as "not the perp shape".
488
+ if (rows && rows.every(row => Object.keys(row).length > 0)) return { rows };
489
+ }
490
+ }
491
+ // An `asset_positions` array that does not hold perp rows is malformed, not
492
+ // a descriptive row array that happens to share the name. Reading it as one
493
+ // would drop the wrapper and surface the broken rows as columns, so leave it
494
+ // to the payload fallback.
495
+ return sawPositions ? null : locateRows(data, { descriptive: true });
496
+ }
497
+
498
+ // Records for the tabular formatters: the located rows, or the payload itself
499
+ // when nothing matched. Rows that carry no fields at all would render as blank
500
+ // lines, which says less than the payload does, so they take that same
501
+ // fallback. An empty row set is left alone — it means "no results".
502
+ function tabularRecords(data) {
503
+ if (typeof data !== 'object' || data === null) return [];
504
+ const rows = locateTabularRows(data)?.rows;
505
+ if (rows && (rows.length === 0 || rows.some(row => Object.keys(row).length > 0))) return rows;
506
+ return [Array.isArray(data) ? { data } : data];
507
+ }
508
+
459
509
  // Table formatter for human-readable output
460
510
  export function formatTable(data) {
461
- // Extract array of records from various response shapes
462
- const located = locateRows(data, { descriptive: true });
463
- let records = located?.rows || [];
464
- if (!located && typeof data === 'object' && data !== null) {
465
- // Single object - convert to array
466
- records = [Array.isArray(data) ? { data } : data];
467
- }
511
+ const records = tabularRecords(data);
468
512
 
469
513
  if (records.length === 0) {
470
514
  return 'No data';
@@ -523,12 +567,7 @@ export function formatTable(data) {
523
567
  * Format data as CSV with header row
524
568
  */
525
569
  export function formatCsv(data) {
526
- // Extract array of records from various response shapes
527
- const located = locateRows(data, { descriptive: true });
528
- let records = located?.rows || [];
529
- if (!located && typeof data === 'object' && data !== null) {
530
- records = [Array.isArray(data) ? { data } : data];
531
- }
570
+ const records = tabularRecords(data);
532
571
 
533
572
  if (records.length === 0) return '';
534
573
 
@@ -1097,6 +1136,7 @@ COMMANDS:
1097
1136
  wallet ${WALLET_SUBCOMMANDS.join(', ')}
1098
1137
  agent Ask the Nansen AI research agent (fast/expert modes)
1099
1138
  alerts list, create, update, toggle, delete
1139
+ feedback preferences, submit, resume, forget local data, or get a receipt (--json for structured output)
1100
1140
  web search, fetch
1101
1141
  mcp install/uninstall/verify the Nansen MCP server
1102
1142
  account Check the effective credential, plan, and remaining credits (free)
@@ -1188,7 +1228,7 @@ WHAT CACHES:
1188
1228
  written to the response cache — that is all of "nansen research ...", plus
1189
1229
  "alerts list" and "alerts get".
1190
1230
  Never cached: account, web search, web fetch, alerts create/update/toggle/delete,
1191
- agent (streamed), every trade, bridge, wallet and mcp command, and perp trading.
1231
+ agent (streamed), feedback, every trade, bridge, wallet and mcp command, and perp trading.
1192
1232
  The analytics commands "perp screener" and "perp leaderboard" are cached.
1193
1233
 
1194
1234
  CACHE OPTIONS (for any command):
@@ -2578,7 +2618,8 @@ export async function runCLI(rawArgs, deps = {}) {
2578
2618
  || (command === 'doctor' && flags.offline)
2579
2619
  || isMcpUsage
2580
2620
  || command === 'completion'
2581
- || command === 'cache';
2621
+ || command === 'cache'
2622
+ || (command === 'feedback' && subcommand === 'forget');
2582
2623
  const trackSucceeded = isOfflineCommand ? async () => {} : isAuthMutation ? metadata => trackAuthCommand({ ...metadata, command }) : trackCommandSucceeded;
2583
2624
  const trackFailed = isOfflineCommand ? async () => {} : isAuthMutation ? metadata => trackAuthCommand({ ...metadata, command, failed: true }) : trackCommandFailed;
2584
2625
 
@@ -2604,7 +2645,7 @@ export async function runCLI(rawArgs, deps = {}) {
2604
2645
  // modules retain their existing deps: notably wallet export interprets
2605
2646
  // `isTTY` as stdout visibility when deciding whether to warn about printing
2606
2647
  // private keys, so substituting the stdin signal there changes its semantics.
2607
- const commands = { ...buildCommands(inputInteractiveDeps), ...buildWalletCommands(deps), ...buildTradingCommands(topLevelTradingDeps), ...buildAlertsCommands(deps), ...buildAgentCommands(deps), ...buildMcpCommands({ ...deps, log: deps.log ?? output }), ...buildCompletionCommands({ ...deps, log: deps.log ?? output }), ...commandOverrides };
2648
+ 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 };
2608
2649
 
2609
2650
  if (flags.version || flags.v) {
2610
2651
  output(VERSION);
@@ -2818,6 +2859,13 @@ export async function runCLI(rawArgs, deps = {}) {
2818
2859
  return { type: 'no-output', command };
2819
2860
  }
2820
2861
 
2862
+ // Feedback JSON is a complete receipt, even alongside list-format flags.
2863
+ if (command === 'feedback') {
2864
+ output(formatOutput({ success: true, data: result }, { pretty }).text);
2865
+ await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: false, flags: usedFlags, chain });
2866
+ return { type: 'success', data: result };
2867
+ }
2868
+
2821
2869
  // Schema returns data directly (not wrapped in { success, data })
2822
2870
  if (command === 'schema') {
2823
2871
  const formatted = formatOutput(result, { pretty, table: false });
@@ -2865,7 +2913,11 @@ export async function runCLI(rawArgs, deps = {}) {
2865
2913
  // data (e.g. PASSWORD_REQUIRED resolution steps) is preserved under `details`,
2866
2914
  // so agents get one consistent shape to branch on regardless of command.
2867
2915
  const errorData = formatError(error);
2868
- if (error.reported) {
2916
+ if (command === 'feedback' && !flags.json && !pretty) {
2917
+ output(feedbackErrorText(error));
2918
+ } else if (command === 'feedback') {
2919
+ output(formatOutput(errorData, { pretty }).text);
2920
+ } else if (error.reported) {
2869
2921
  // The command already printed its full human-readable failure output;
2870
2922
  // emitting the envelope too would produce two output shapes on stdout.
2871
2923
  } else if (isUsageError(errorData, { pretty, table, csv, stream, isTTY })) {
@@ -56,8 +56,13 @@ export const EXCLUDED_COMMANDS = new Set([
56
56
  * valueless flags: an extra name here is harmless (the following word is
57
57
  * checked against the subcommand table anyway), a missing one makes the walker
58
58
  * swallow a real subcommand.
59
+ *
60
+ * `gasless` is here for the opposite reason to the rest: the flag was removed,
61
+ * so it is gone from schema.json and is never suggested, but parseArgs still
62
+ * treats it as a boolean so that `trade execute` can reject it with
63
+ * GASLESS_REMOVED instead of eating the token after it.
59
64
  */
60
- const EXTRA_VALUELESS = ['help', 'version', 'cache', 'no-cache', 'stream', 'enrich', 'full', 'human'];
65
+ const EXTRA_VALUELESS = ['help', 'version', 'cache', 'no-cache', 'stream', 'enrich', 'full', 'human', 'gasless'];
61
66
 
62
67
  // Command, subcommand, option and enum tokens are interpolated straight into
63
68
  // shell source. Anything that is not a bare word is dropped rather than escaped
@@ -0,0 +1,352 @@
1
+ import fs from 'node:fs';
2
+ import { randomUUID } from 'node:crypto';
3
+ import path from 'node:path';
4
+ import { authDirectory } from '../auth-credentials.js';
5
+ import { feedbackExpiry, withFeedbackJournal } from '../feedback-journal.js';
6
+ import { NansenError, ErrorCode, packageVersion, telemetryHeaders, sleep, statusToErrorCode } from '../api.js';
7
+
8
+ const PATH = '/api/v1/feedback';
9
+ const TEMPORARY = new Set([429, 500, 502, 503, 504]);
10
+ const ERROR_FIELDS = ['error', 'message', 'code', 'status', 'request_id', 'doc_url', 'param', 'reason', 'retry_after', 'quota', 'errors'];
11
+
12
+ function requestId(response) {
13
+ return response?.headers.get('x-request-id') ?? response?.headers.get('x-kong-request-id') ?? null;
14
+ }
15
+
16
+ function preserveUncertainSubmission(error, pending) {
17
+ return new NansenError(`${error.message} ${pending.message}`, pending.code, error.status ?? pending.status,
18
+ { ...error.details, ...pending.details, request_id: error.details?.request_id ?? pending.details.request_id, outcome: 'unknown' });
19
+ }
20
+
21
+ function storageRecoveryError(error, submissionId, unknown = true) {
22
+ return new NansenError(`Private feedback recovery storage is unavailable. ${unknown ? 'The submission may have been saved.' : 'The report was not sent.'} Repair ~/.nansen/feedback, then retry safely with: nansen feedback resume.`,
23
+ error.code, error.status, { ...error.details, submission_id: submissionId, retry_command: 'nansen feedback resume', outcome: unknown ? 'unknown' : 'rejected' });
24
+ }
25
+
26
+ function clearRejectedFeedback(journal, error, submissionId) {
27
+ try { journal.clear(); }
28
+ catch {
29
+ const message = error.code === 'feedback_blocked' ? 'The report was blocked before reaching Nansen. No report was saved.' : error.message;
30
+ throw new NansenError(`${message}${message.endsWith('.') ? '' : '.'} Local retry data could not be erased. Repair ~/.nansen/feedback, then run: nansen feedback forget before using --new with the corrected --file.`,
31
+ error.code, error.status, { ...error.details, submission_id: submissionId, outcome: 'rejected', retry_command: 'nansen feedback forget' });
32
+ }
33
+ }
34
+
35
+ function required(value, name, usage = 'nansen feedback submit --file feedback.json --submission-id <new-id>') {
36
+ if (typeof value !== 'string' || !value.trim()) {
37
+ throw new NansenError(`${name} is required. Use: ${usage}. Reuse the submission ID and unchanged file after an uncertain submission result.`, ErrorCode.MISSING_PARAM);
38
+ }
39
+ return value;
40
+ }
41
+
42
+ function retryDelay(response, data, attempt, retry) {
43
+ const header = response?.headers.get('retry-after');
44
+ const headerDelay = header && /^\d+(\.\d+)?$/.test(header.trim())
45
+ ? Number(header) * 1000 : header ? Date.parse(header) - Date.now() : NaN;
46
+ const advertised = Number.isFinite(headerDelay) ? headerDelay :
47
+ Number.isFinite(data?.retry_after) && data.retry_after >= 0 ? data.retry_after * 1000 : NaN;
48
+ return Math.max(Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** attempt), Number.isFinite(advertised) ? Math.max(0, advertised) : 0);
49
+ }
50
+
51
+ // Feedback keeps the file bytes and uses selected account credentials. It never
52
+ // enters the generic client's body cleaning, cache, pagination or payment paths.
53
+ async function requestFeedback(api, endpoint, body, submissionId, responseType = 'receipt', previouslyUncertain = false) {
54
+ const preference = responseType === 'preferences';
55
+ if (Object.keys(api.defaultHeaders).length) {
56
+ throw new NansenError('Feedback uses account authentication only. Remove --x402-payment-signature.', ErrorCode.INVALID_PARAMS);
57
+ }
58
+ const retry = api.retryOptions;
59
+ const maxRetries = Math.min(retry.maxRetries, 3);
60
+ let lastError;
61
+ let uncertainSubmission = previouslyUncertain ? new NansenError(
62
+ 'An earlier attempt may have been saved. Keep the same --submission-id and unchanged --file for recovery.',
63
+ 'submission_outcome_unknown', null,
64
+ { reason: 'submission_outcome_unknown', submission_id: submissionId, outcome: 'unknown' },
65
+ ) : undefined;
66
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
67
+ let credentials;
68
+ try { credentials = await api.requestCredentials({}); } catch (error) {
69
+ if (!uncertainSubmission) throw error;
70
+ throw preserveUncertainSubmission(error, uncertainSubmission);
71
+ }
72
+ if (!Object.keys(credentials).length) {
73
+ throw new NansenError('Not logged in. Run: nansen login, or set NANSEN_API_KEY.', ErrorCode.UNAUTHORIZED);
74
+ }
75
+ const secrets = Object.values(credentials).flatMap(value => [value, value.replace(/^Bearer /, '')]);
76
+ const redact = value => {
77
+ if (typeof value === 'string') return secrets.reduce((text, secret) => secret ? text.split(secret).join('[redacted]') : text, value);
78
+ if (Array.isArray(value)) return value.map(redact);
79
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redact(item)]));
80
+ return value;
81
+ };
82
+ let response, data;
83
+ api.beforeFeedbackRequest?.();
84
+ try {
85
+ response = await fetch(`${api.baseUrl}${endpoint}`, {
86
+ method: body === undefined ? 'GET' : 'POST', redirect: 'error', cache: 'no-store',
87
+ signal: AbortSignal.timeout(30000),
88
+ headers: {
89
+ 'X-Client-Type': 'nansen-cli', 'X-Client-Version': packageVersion,
90
+ ...telemetryHeaders(), ...credentials,
91
+ ...(body !== undefined && { 'Content-Type': 'application/json', 'Idempotency-Key': submissionId }),
92
+ },
93
+ ...(body !== undefined && { body }),
94
+ });
95
+ data = await response.json();
96
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('Invalid response');
97
+ if (response.ok) {
98
+ if (preference) {
99
+ if (!['enabled', 'disabled'].includes(data.automatic_reporting) || typeof data.configured !== 'boolean' ||
100
+ !Number.isSafeInteger(data.version) || data.version < 0 || typeof data.can_manage !== 'boolean' ||
101
+ !(data.updated_at === null || (typeof data.updated_at === 'string' && Number.isFinite(Date.parse(data.updated_at)))) ||
102
+ (!data.configured && data.automatic_reporting !== 'disabled')) throw new Error('Invalid preference');
103
+ return Object.fromEntries(['automatic_reporting', 'configured', 'version', 'updated_at', 'can_manage'].map(key => [key, data[key]]));
104
+ }
105
+ if (typeof data.feedback_id !== 'string' || typeof data.submission_id !== 'string' ||
106
+ !['received', 'reviewed', 'closed'].includes(data.status) ||
107
+ (submissionId && data.submission_id !== submissionId)) throw new Error('Invalid receipt');
108
+ return redact(data);
109
+ }
110
+ } catch {
111
+ if (body !== undefined && response?.status === 403 && response.headers.get('content-type')?.split(';')[0].trim().toLowerCase() === 'text/html') {
112
+ const blocked = new NansenError(uncertainSubmission
113
+ ? 'This attempt was blocked before reaching Nansen.'
114
+ : 'The report was blocked before reaching Nansen. No report was saved. Change the report and use a new submission ID.',
115
+ 'feedback_blocked', 403,
116
+ { reason: 'feedback_blocked', outcome: 'rejected', submission_id: submissionId, request_id: redact(requestId(response)) });
117
+ if (uncertainSubmission) throw preserveUncertainSubmission(blocked, uncertainSubmission);
118
+ throw blocked;
119
+ }
120
+ if (response && [402, 404, 501].includes(response.status)) {
121
+ const unavailable = new NansenError('Feedback is unavailable on this backend. Retry after feedback support is deployed.', 'feedback_unavailable', response.status,
122
+ { submission_id: submissionId ?? null, request_id: redact(requestId(response)) });
123
+ if (uncertainSubmission) throw preserveUncertainSubmission(unavailable, uncertainSubmission);
124
+ throw unavailable;
125
+ }
126
+ const unknown = body !== undefined;
127
+ lastError = new NansenError(
128
+ unknown ? 'The submission may have been saved. Retry the same --submission-id with the unchanged --file.' : preference ? 'Feedback preference unavailable. Show the report and ask before sending.' : 'Receipt lookup failed. Retry nansen feedback get with the same feedback ID.',
129
+ unknown ? 'submission_outcome_unknown' : ErrorCode.NETWORK_ERROR, response?.status ?? null,
130
+ { reason: unknown ? 'submission_outcome_unknown' : preference ? 'preference_unavailable' : 'receipt_unavailable', submission_id: submissionId ?? null, request_id: redact(requestId(response)), ...(unknown && { outcome: 'unknown' }) },
131
+ );
132
+ if (unknown) uncertainSubmission = lastError;
133
+ if (attempt < maxRetries && (!response || response.ok || TEMPORARY.has(response.status))) {
134
+ const delay = retryDelay(response, null, attempt, retry);
135
+ if (delay <= retry.maxRetryAfterMs) { await sleep(delay); continue; }
136
+ }
137
+ throw lastError;
138
+ }
139
+ const details = redact(Object.fromEntries(ERROR_FIELDS.filter(key => key in data).map(key => [key, data[key]])));
140
+ details.request_id ??= redact(requestId(response));
141
+ if (submissionId) details.submission_id = submissionId;
142
+ if (uncertainSubmission && data.reason !== 'feedback_erased') details.outcome = 'unknown';
143
+ if (response.status === 403 && data.reason === 'feedback_not_enabled') {
144
+ const uncertainty = uncertainSubmission ? ' An earlier attempt may have been saved. Keep the same --submission-id and unchanged --file for recovery.' : '';
145
+ throw new NansenError(`Feedback is not enabled for this account. Stop automatic retries. User approval or an enabled preference does not override rollout.${uncertainty}`,
146
+ uncertainSubmission ? uncertainSubmission.code : details.code || 'forbidden', response.status,
147
+ { ...details, outcome: uncertainSubmission ? 'unknown' : 'rejected' });
148
+ }
149
+ const unavailable = response.status === 402 || data.code === 'insufficient_credits' || response.status === 501 ||
150
+ (response.status === 404 && body !== undefined);
151
+ if (unavailable) {
152
+ const error = new NansenError('Feedback is unavailable on this backend. Retry after feedback support is deployed; no payment or account switch was attempted.', 'feedback_unavailable', response.status, details);
153
+ if (uncertainSubmission) throw preserveUncertainSubmission(error, uncertainSubmission);
154
+ throw error;
155
+ }
156
+ if (response.status === 404) {
157
+ if (preference) throw new NansenError('Feedback preference unavailable on this backend. Show the report and ask before sending.', 'feedback_unavailable', response.status, details);
158
+ throw new NansenError('Receipt not found, or this backend does not support feedback yet. Check the feedback ID, active account and NANSEN_BASE_URL. Do not resubmit as a new report.', details.code || 'not_found', response.status, details);
159
+ }
160
+ lastError = new NansenError(details.message || 'Feedback request failed.', details.code || statusToErrorCode(response.status, data), response.status, details);
161
+ if (body !== undefined && response.status >= 500 && data.reason !== 'feedback_admissions_paused') {
162
+ uncertainSubmission ??= new NansenError('The submission may have been saved. Retry the same --submission-id with the unchanged --file.',
163
+ 'submission_outcome_unknown', response.status,
164
+ { reason: 'submission_outcome_unknown', submission_id: submissionId, request_id: details.request_id });
165
+ }
166
+ if (uncertainSubmission && [401, 403].includes(response.status)) throw preserveUncertainSubmission(lastError, uncertainSubmission);
167
+ const weekly = data.reason === 'feedback_weekly_quota_exhausted';
168
+ const delay = retryDelay(response, data, attempt, retry);
169
+ if (!weekly && TEMPORARY.has(response.status) && attempt < maxRetries && delay <= retry.maxRetryAfterMs) {
170
+ await sleep(delay);
171
+ continue;
172
+ }
173
+ if (uncertainSubmission && response.status >= 500) {
174
+ throw new NansenError(`${lastError.message} ${uncertainSubmission.message}`, uncertainSubmission.code,
175
+ response.status, { ...details, outcome: 'unknown' });
176
+ }
177
+ throw lastError;
178
+ }
179
+ throw lastError;
180
+ }
181
+
182
+ // Resolve the account from the server, then freeze those exact credentials for
183
+ // the entire operation. Re-login in another process cannot redirect a replay.
184
+ async function feedbackIdentity(api) {
185
+ if (Object.keys(api.defaultHeaders).length) throw new NansenError('Feedback uses account authentication only. Remove --x402-payment-signature.', ErrorCode.INVALID_PARAMS);
186
+ const credentials = await api.requestCredentials({});
187
+ if (!Object.keys(credentials).length) throw new NansenError('Not logged in. Run: nansen login, or set NANSEN_API_KEY.', ErrorCode.UNAUTHORIZED);
188
+ try {
189
+ const environment = new URL(api.baseUrl).href.replace(/\/$/, '');
190
+ const response = await fetch(`${environment}/api/v1/account`, { headers: credentials, redirect: 'error', cache: 'no-store', signal: AbortSignal.timeout(15000) });
191
+ const data = await response.json();
192
+ if (!response.ok || typeof data.user_id !== 'string' || !data.user_id || data.user_id.length > 255 || [...data.user_id].some(c => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127)) throw new Error();
193
+ return { account: data.user_id, environment, api: { ...api, baseUrl: environment, requestCredentials: async () => credentials } };
194
+ } catch { throw new NansenError('Could not verify the feedback account. No report was sent. Retry with the original account and NANSEN_BASE_URL.', 'feedback_identity_unverified'); }
195
+ }
196
+
197
+ async function managedFeedback(api, { body, newSubmission = false, forget = false } = {}) {
198
+ return withFeedbackJournal(async journal => {
199
+ let entry = journal.entry;
200
+ if (forget) { journal.clear(); return { forgotten: true }; }
201
+ if (newSubmission && entry?.state === 'pending') throw new NansenError('A submission is still pending. Run: nansen feedback resume. To erase its local retry data, run: nansen feedback forget.', 'feedback_pending');
202
+ if ((!entry && body === undefined) || (entry?.state === 'cleared' && !newSubmission)) throw new NansenError('No replayable feedback remains. Expired or erased submissions are never replayed. Use --new only for a deliberate new report.', 'feedback_recovery_unavailable');
203
+ if (entry?.state === 'confirmed' && body !== undefined && !newSubmission) throw new NansenError('The previous submission has a confirmed receipt. Run: nansen feedback resume. Use --new only for a deliberate new report.', 'feedback_already_confirmed');
204
+ if (entry && !newSubmission && new URL(api.baseUrl).href.replace(/\/$/, '') !== entry.environment) throw new NansenError('The API environment changed. Restore the original NANSEN_BASE_URL, then run: nansen feedback resume.', 'feedback_identity_mismatch');
205
+ if (entry?.state === 'pending' && body !== undefined && body !== entry.body) throw new NansenError('The report changed. Run: nansen feedback resume to retry the saved, unchanged report, or nansen feedback forget to erase its local retry data before a deliberate --new submission.', 'feedback_report_changed');
206
+ const identity = await feedbackIdentity(api);
207
+ if (entry && !newSubmission && identity.account !== entry.account) throw new NansenError('The Nansen account changed. Log in to the original account, then run: nansen feedback resume.', 'feedback_identity_mismatch');
208
+ if (!entry || newSubmission) {
209
+ entry = { version: 1, state: 'pending', submission_id: randomUUID(), account: identity.account, environment: identity.environment, expires_at: feedbackExpiry(Date.now()), body, uncertain: false };
210
+ try { journal.save(entry); }
211
+ catch (error) {
212
+ // The journal may already exist even if its directory sync failed.
213
+ if (error.journalSaved) throw storageRecoveryError(error, entry.submission_id, false);
214
+ throw error;
215
+ }
216
+ }
217
+ // Older journals cannot distinguish a denial from a lost response.
218
+ const previouslyUncertain = entry.state === 'pending' && entry.uncertain !== false;
219
+ let dispatched = false;
220
+ identity.api.beforeFeedbackRequest = () => {
221
+ if (Date.parse(entry.expires_at) <= Date.now()) {
222
+ journal.clear();
223
+ throw new NansenError('Saved feedback expired and was erased. It will not be replayed.', 'feedback_recovery_unavailable');
224
+ }
225
+ if (entry.state === 'pending' && !dispatched) {
226
+ // A crash after dispatch must never turn a possible acceptance into a rejection.
227
+ journal.save({ ...entry, uncertain: true });
228
+ dispatched = true;
229
+ }
230
+ };
231
+ try {
232
+ const receipt = entry.state === 'confirmed'
233
+ ? await requestFeedback(identity.api, `${PATH}/${encodeURIComponent(entry.feedback_id)}`, undefined, entry.submission_id)
234
+ : await requestFeedback(identity.api, PATH, entry.body, entry.submission_id, 'receipt', previouslyUncertain);
235
+ const expiry = Date.parse(receipt.expires_at);
236
+ if (!Number.isFinite(expiry)) throw new NansenError('The receipt expiry could not be confirmed.', 'submission_outcome_unknown');
237
+ // Never retain the body, its digest, or any free-text receipt fields.
238
+ journal.save({ version: 1, state: 'confirmed', submission_id: entry.submission_id, account: entry.account, environment: entry.environment,
239
+ expires_at: new Date(Math.min(expiry, Date.parse(entry.expires_at))).toISOString(), feedback_id: receipt.feedback_id });
240
+ return receipt;
241
+ } catch (error) {
242
+ if (error.details?.reason === 'feedback_erased') { clearRejectedFeedback(journal, error, entry.submission_id); throw error; }
243
+ if (entry.state === 'confirmed' && error.status === 404) {
244
+ try { journal.clear(); } catch (storageError) { throw storageRecoveryError(storageError, entry.submission_id); }
245
+ throw error;
246
+ }
247
+ if (entry.state !== 'pending' || error.code === 'feedback_recovery_unavailable') throw error;
248
+ if (error.code === 'feedback_storage_unavailable') throw storageRecoveryError(error, entry.submission_id, dispatched || previouslyUncertain);
249
+ const unknown = previouslyUncertain || error.code === 'submission_outcome_unknown' || error.details?.outcome === 'unknown';
250
+ if (!unknown && ([400, 413, 422].includes(error.status) || (error.status === 409 && error.details?.reason === 'idempotency_key_reused') ||
251
+ error.code === 'feedback_blocked')) {
252
+ clearRejectedFeedback(journal, error, entry.submission_id);
253
+ throw new NansenError(`${error.message} This attempt was rejected. Local retry data was erased. Correct the report and use --new with the corrected --file.`,
254
+ error.code, error.status, { ...error.details, submission_id: entry.submission_id, outcome: 'rejected' });
255
+ }
256
+ try { journal.save({ ...entry, uncertain: unknown }); }
257
+ catch (error) { throw storageRecoveryError(error, entry.submission_id, dispatched || previouslyUncertain); }
258
+ if (error.status === 403 && error.details?.reason === 'feedback_not_enabled') {
259
+ const outcomeText = unknown ? '' : ' This report was not accepted.';
260
+ throw new NansenError(`${error.message}${outcomeText} The saved ID and report are retained for recovery.`,
261
+ error.code, error.status, { ...error.details, submission_id: entry.submission_id, outcome: unknown ? 'unknown' : 'rejected' });
262
+ }
263
+ if (error.status === 429 && error.details?.reason === 'feedback_weekly_quota_exhausted') {
264
+ throw new NansenError(`${error.message} ${unknown ? 'An earlier attempt may have been accepted.' : 'This submission was not accepted.'} Wait for the weekly reset before running: nansen feedback resume.`,
265
+ error.code, error.status, { ...error.details, submission_id: entry.submission_id, outcome: unknown ? 'unknown' : 'rejected',
266
+ retry_command: 'nansen feedback resume', retry_not_before: error.details.quota?.resets_at ?? null });
267
+ }
268
+ throw new NansenError(`${error.message} ${unknown ? 'The saved submission may have been accepted. Retry safely with: nansen feedback resume' : 'This report was not accepted. Retry the saved report with: nansen feedback resume.'}`,
269
+ error.code, error.status, { ...error.details, submission_id: entry.submission_id, retry_command: 'nansen feedback resume', outcome: unknown ? 'unknown' : 'rejected' });
270
+ }
271
+ }, { erase: forget });
272
+ }
273
+
274
+ function receiptText(receipt) {
275
+ const wording = {
276
+ received: 'Received. Your report is saved; human review may still be pending.',
277
+ reviewed: 'Reviewed. A teammate has triaged your report; no fix or date is promised.',
278
+ closed: `Closed. Review is complete. Disposition: ${receipt.disposition ?? 'unspecified'}.`,
279
+ };
280
+ return [wording[receipt.status], `Feedback ID: ${receipt.feedback_id}`, `Submission ID: ${receipt.submission_id}`,
281
+ ...(receipt.replayed ? ['Replay accepted; no new report slot was consumed.'] : []),
282
+ ...(receipt.quota ? [`Weekly allowance: ${receipt.quota.remaining}/${receipt.quota.limit} remaining. Resets: ${receipt.quota.resets_at}`] : [])].join('\n');
283
+ }
284
+
285
+ export function feedbackErrorText(error) {
286
+ const details = error.details ?? {};
287
+ return [error.message, ...(details.quota?.resets_at ? [`Quota resets: ${details.quota.resets_at}`] : []),
288
+ ...(Array.isArray(details.errors) ? details.errors.filter(item => typeof item?.field === 'string' && typeof item.code === 'string')
289
+ .map(item => `${item.field}: ${item.code}`) : []),
290
+ ...(details.retry_after !== undefined ? [`Retry after: ${details.retry_after} seconds`] : []),
291
+ ...(details.submission_id ? [`Submission ID: ${details.submission_id}`] : []),
292
+ ...(details.request_id ? [`Request ID: ${details.request_id}`] : [])].join('\n');
293
+ }
294
+
295
+ export function buildFeedbackCommands({ log = console.log } = {}) {
296
+ return {
297
+ feedback: async (args, api, flags, options) => {
298
+ let receipt;
299
+ if (flags['submission-id']) throw new NansenError('--submission-id requires a value.', ErrorCode.INVALID_PARAMS);
300
+ if (args[0] === 'preferences') {
301
+ if (args.length !== 1 || options.file || options['submission-id'] || flags.new) throw new NansenError('Use: nansen feedback preferences [--json]', ErrorCode.INVALID_PARAMS);
302
+ try { receipt = await requestFeedback(api, `${PATH}/preferences`, undefined, undefined, 'preferences'); }
303
+ catch (error) {
304
+ const guidance = 'Feedback preference unavailable. Show the report and ask before sending.';
305
+ throw new NansenError(`${guidance}${error.status == null && error.message !== guidance ? ` ${error.message}` : ''}`, error.code, error.status,
306
+ { ...error.details, reason: 'preference_unavailable' });
307
+ }
308
+ if (flags.json || flags.pretty || flags.p) return receipt;
309
+ log(`Automatic feedback: ${receipt.automatic_reporting}${receipt.configured ? '' : ' (not configured)'}.\n${receipt.automatic_reporting === 'enabled' ? 'Agents may send without asking, subject to host controls and account rollout.' : 'Show the report and ask before sending.'}\nChange the lasting choice in Superapp settings. Approval for one report does not change it.`);
310
+ return;
311
+ } else if (args[0] === 'submit') {
312
+ if (args.length !== 1) throw new NansenError('Use: nansen feedback submit --file feedback.json [--submission-id <new-id> | --new] [--json]', ErrorCode.INVALID_PARAMS);
313
+ const id = options['submission-id'];
314
+ if (id !== undefined && flags.new) throw new NansenError('Use either --new or --submission-id.', ErrorCode.INVALID_PARAMS);
315
+ if (id !== undefined && (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id))) throw new NansenError('--submission-id must contain 1 to 128 ASCII letters, digits, underscores or hyphens.', ErrorCode.INVALID_PARAMS);
316
+ const file = required(options.file, '--file');
317
+ let body;
318
+ try { body = fs.readFileSync(file, 'utf8'); } catch { throw new NansenError('Cannot read --file. Supply a readable JSON report file.', ErrorCode.INVALID_PARAMS); }
319
+ let report;
320
+ try { report = JSON.parse(body); } catch { throw new NansenError('--file must contain valid JSON.', ErrorCode.INVALID_PARAMS); }
321
+ if (!report || typeof report !== 'object' || Array.isArray(report)) throw new NansenError('--file must contain a JSON report object.', ErrorCode.INVALID_PARAMS);
322
+ if (Buffer.byteLength(body) > 16384) throw new NansenError('The report exceeds 16 KiB.', ErrorCode.INVALID_PARAMS);
323
+ receipt = id !== undefined ? await requestFeedback(api, PATH, body, id) : await managedFeedback(api, { body, newSubmission: flags.new === true });
324
+ } else if (args[0] === 'resume' || args[0] === 'forget') {
325
+ if (args.length !== 1 || options.file || options['submission-id'] || flags.new) throw new NansenError(`Use: nansen feedback ${args[0]} [--json]`, ErrorCode.INVALID_PARAMS);
326
+ receipt = await managedFeedback(api, { forget: args[0] === 'forget' });
327
+ } else if (args[0] === 'get') {
328
+ const id = required(args[1], 'Feedback ID', 'nansen feedback get <feedback-id> [--json]');
329
+ if (args.length !== 2) throw new NansenError('Use: nansen feedback get <feedback-id> [--json]', ErrorCode.INVALID_PARAMS);
330
+ const local = path.join(authDirectory(), 'feedback', 'recovery.json');
331
+ if (fs.lstatSync(local, { throwIfNoEntry: false })) {
332
+ receipt = await withFeedbackJournal(async journal => {
333
+ if (journal.entry?.state !== 'confirmed' || journal.entry.feedback_id !== id) return requestFeedback(api, `${PATH}/${encodeURIComponent(id)}`);
334
+ const identity = await feedbackIdentity(api);
335
+ if (identity.account !== journal.entry.account || identity.environment !== journal.entry.environment) throw new NansenError('Use the original account and NANSEN_BASE_URL to read the saved receipt.', 'feedback_identity_mismatch');
336
+ try { return await requestFeedback(identity.api, `${PATH}/${encodeURIComponent(id)}`, undefined, journal.entry.submission_id); }
337
+ catch (error) {
338
+ if (error.status === 404 || error.details?.reason === 'feedback_erased') {
339
+ try { journal.clear(); } catch (storageError) { throw storageRecoveryError(storageError, journal.entry.submission_id); }
340
+ }
341
+ throw error;
342
+ }
343
+ });
344
+ } else receipt = await requestFeedback(api, `${PATH}/${encodeURIComponent(id)}`);
345
+ } else {
346
+ throw new NansenError('Use: nansen feedback preferences, nansen feedback submit --file feedback.json, nansen feedback resume, nansen feedback forget, or nansen feedback get <feedback-id>. Add --json for structured output.', ErrorCode.INVALID_PARAMS);
347
+ }
348
+ if (flags.json || flags.pretty || flags.p) return receipt;
349
+ log(receipt.forgotten ? 'Local feedback retry data erased. This does not delete a report already saved by Nansen. Your original input file is unchanged.' : receiptText(receipt));
350
+ },
351
+ };
352
+ }
@@ -0,0 +1,86 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { authDirectory } from './auth-credentials.js';
4
+ import { openLocalFile, readLocalFile } from './local-file.js';
5
+ import { NansenError } from './api.js';
6
+
7
+ const unavailable = () => new NansenError('Private feedback recovery storage is unavailable. Repair ~/.nansen/feedback, or submit with a caller-managed --submission-id and keep the unchanged file.', 'feedback_storage_unavailable');
8
+ const cleared = { version: 1, state: 'cleared' };
9
+ const timestamp = value => typeof value === 'string' && Number.isFinite(Date.parse(value));
10
+
11
+ export function feedbackExpiry(now) {
12
+ const date = new Date(now), month = date.getUTCMonth();
13
+ date.setUTCFullYear(date.getUTCFullYear() + 1);
14
+ if (date.getUTCMonth() !== month) date.setUTCDate(0);
15
+ return date.toISOString();
16
+ }
17
+
18
+ // One active submission. The cleared marker contains no report or identity and
19
+ // prevents expiry/erasure from turning a later retry into a new submission.
20
+ export async function withFeedbackJournal(operation, { erase = false } = {}) {
21
+ let fd, native, locked = false;
22
+ const root = authDirectory(), directory = path.join(root, 'feedback');
23
+ const file = path.join(directory, 'recovery.json'), temp = path.join(directory, 'recovery.tmp');
24
+ const privatePath = (target, isDirectory) => {
25
+ const stat = fs.lstatSync(target);
26
+ if (stat.isSymbolicLink() || (isDirectory ? !stat.isDirectory() : !stat.isFile()) ||
27
+ stat.uid !== process.getuid() || (stat.mode & (isDirectory ? 0o077 : 0o177)) || (!isDirectory && stat.nlink !== 1)) throw unavailable();
28
+ };
29
+ const syncDirectory = () => {
30
+ const descriptor = fs.openSync(directory, 'r');
31
+ try { fs.fsyncSync(descriptor); } finally { fs.closeSync(descriptor); }
32
+ };
33
+ const save = value => {
34
+ let descriptor, journalSaved = false;
35
+ try {
36
+ privatePath(root, true); privatePath(directory, true);
37
+ descriptor = openLocalFile(temp, { root, privateFile: true, flags: fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL });
38
+ fs.writeFileSync(descriptor, JSON.stringify(value)); fs.fsyncSync(descriptor);
39
+ fs.closeSync(descriptor); descriptor = undefined;
40
+ fs.renameSync(temp, file); journalSaved = true; syncDirectory();
41
+ } catch { throw Object.assign(unavailable(), { journalSaved }); }
42
+ finally {
43
+ if (descriptor !== undefined) fs.closeSync(descriptor);
44
+ if (fs.existsSync(temp)) fs.unlinkSync(temp);
45
+ }
46
+ };
47
+ let entry;
48
+ try {
49
+ // POSIX modes cannot establish private Windows ACLs. Fail before sending.
50
+ if (process.platform === 'win32') throw unavailable();
51
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 }); privatePath(root, true);
52
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); privatePath(directory, true);
53
+ native = (await import('fs-native-extensions')).default;
54
+ fd = openLocalFile(path.join(directory, 'recovery.lock'), { root, privateFile: true, flags: fs.constants.O_RDWR | fs.constants.O_CREAT });
55
+ privatePath(path.join(directory, 'recovery.lock'), false);
56
+ locked = native.tryLock(fd);
57
+ if (!locked) throw new NansenError('Another feedback command is running. Retry after it finishes.', 'feedback_busy');
58
+ // A killed writer may leave an uncommitted temp file. It was never sent.
59
+ if (fs.lstatSync(temp, { throwIfNoEntry: false })) {
60
+ if (!erase) privatePath(temp, false);
61
+ fs.unlinkSync(temp); syncDirectory();
62
+ }
63
+ // Erasure atomically replaces even a damaged or insecure journal without
64
+ // reading it. Never unlink it first: a crash in that gap could look new.
65
+ if (!erase && fs.lstatSync(file, { throwIfNoEntry: false })) {
66
+ privatePath(file, false);
67
+ entry = JSON.parse(readLocalFile(file, { root, privateFile: true, maxBytes: 100000 }));
68
+ const keys = entry.state === 'pending' ? ['version', 'state', 'submission_id', 'account', 'environment', 'expires_at', 'body'] :
69
+ entry.state === 'confirmed' ? ['version', 'state', 'submission_id', 'account', 'environment', 'expires_at', 'feedback_id'] : ['version', 'state'];
70
+ const optionalKeys = entry.state === 'pending' ? ['uncertain'] : [];
71
+ if (entry.version !== 1 || !['pending', 'confirmed', 'cleared'].includes(entry.state) ||
72
+ Object.keys(entry).some(key => !keys.includes(key) && !optionalKeys.includes(key)) || keys.some(key => !(key in entry)) ||
73
+ (entry.state !== 'cleared' && (!/^[A-Za-z0-9_-]{1,128}$/.test(entry.submission_id) ||
74
+ typeof entry.account !== 'string' || !entry.account || typeof entry.environment !== 'string' || !timestamp(entry.expires_at))) ||
75
+ (entry.state === 'pending' && (typeof entry.body !== 'string' || ('uncertain' in entry && typeof entry.uncertain !== 'boolean'))) ||
76
+ (entry.state === 'confirmed' && typeof entry.feedback_id !== 'string')) throw unavailable();
77
+ if (entry.state !== 'cleared' && Date.parse(entry.expires_at) <= Date.now()) { save(cleared); entry = cleared; }
78
+ }
79
+ } catch (error) {
80
+ if (fd !== undefined) { if (locked) native.unlock(fd); fs.closeSync(fd); }
81
+ if (error.code === 'feedback_busy') throw error;
82
+ throw unavailable();
83
+ }
84
+ try { return await operation({ entry, save, clear: () => save(cleared) }); }
85
+ finally { try { native.unlock(fd); } finally { fs.closeSync(fd); } }
86
+ }