@velaro/cli 1.4.120 → 1.4.121

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +0 -19
  2. package/bin/velaro.js +21 -92
  3. package/lib/avatar-motion.test.js +1 -1
  4. package/lib/avatar-switch.test.js +1 -1
  5. package/lib/commands/agent.js +7 -58
  6. package/lib/commands/ai-config.js +8 -34
  7. package/lib/commands/index.js +18 -14
  8. package/lib/commands/kb.js +4 -94
  9. package/lib/commands/knowledge.js +2 -2
  10. package/lib/commands/ops-groups.js +0 -13
  11. package/lib/commands/safety.js +1 -1
  12. package/lib/commands/salesforce.js +1 -1
  13. package/lib/commands/sap.js +1 -1
  14. package/lib/commands/schedule-adherence.js +1 -1
  15. package/lib/commands/teams.js +1 -1
  16. package/lib/commands/woocommerce.js +1 -1
  17. package/lib/commands/workflow.js +4 -31
  18. package/lib/staff-optional.js +10 -0
  19. package/package.json +2 -2
  20. package/lib/cobrowse-settings.js +0 -90
  21. package/lib/cobrowse-settings.test.js +0 -45
  22. package/lib/commands/activity.js +0 -147
  23. package/lib/commands/acuity.js +0 -66
  24. package/lib/commands/ai-federation.js +0 -55
  25. package/lib/commands/ai-models.js +0 -203
  26. package/lib/commands/ai-spend.js +0 -71
  27. package/lib/commands/avatar.js +0 -253
  28. package/lib/commands/bigcommerce.js +0 -50
  29. package/lib/commands/calendly.js +0 -62
  30. package/lib/commands/cobrowse.js +0 -99
  31. package/lib/commands/coupon-grant.js +0 -192
  32. package/lib/commands/diag-groups.js +0 -108
  33. package/lib/commands/diagnostics.js +0 -298
  34. package/lib/commands/email-inbox.js +0 -110
  35. package/lib/commands/entitlement.js +0 -375
  36. package/lib/commands/image-analysis.js +0 -27
  37. package/lib/commands/logs-insights.js +0 -342
  38. package/lib/commands/logs.js +0 -1248
  39. package/lib/commands/migrate.js +0 -379
  40. package/lib/commands/migration-status.js +0 -66
  41. package/lib/commands/ops.js +0 -266
  42. package/lib/commands/parity-staff-tools.js +0 -205
  43. package/lib/commands/pricing.js +0 -132
  44. package/lib/commands/report-speed.js +0 -112
  45. package/lib/commands/scraper.js +0 -38
  46. package/lib/commands/site-provision.js +0 -68
  47. package/lib/commands/sitesync.js +0 -158
  48. package/lib/commands/skill-usage.js +0 -39
  49. package/lib/commands/staff.js +0 -31
  50. package/lib/commands/status-page.js +0 -95
  51. package/lib/commands/status-sla.js +0 -47
  52. package/lib/commands/subscription.js +0 -102
  53. package/lib/commands/support.js +0 -309
  54. package/lib/commands/tour-policy.js +0 -61
  55. package/lib/commands/triage.js +0 -66
  56. package/lib/entitlement-report-packages.test.js +0 -47
  57. package/lib/log-search.js +0 -252
  58. package/lib/log-search.test.js +0 -374
  59. package/lib/logs-insights.test.js +0 -146
  60. package/lib/messaging-routes.test.js +0 -37
  61. package/lib/report-speed.test.js +0 -26
  62. package/lib/siteUser.js +0 -35
  63. package/lib/siteUser.test.js +0 -45
  64. package/lib/skill-usage.test.js +0 -36
  65. package/lib/status-sla.test.js +0 -23
@@ -1,1248 +0,0 @@
1
- import { getCredentials } from '../api.js';
2
- import { readConfig, ENVS } from '../config.js';
3
- import { logsInsightsCommand } from './logs-insights.js';
4
- import { completeLogSearch, describeCompleteness, describeRawMeta, fetchJsonRetry } from '../log-search.js';
5
-
6
- // ── helpers ──────────────────────────────────────────────────────────────────
7
-
8
- const RESET = '\x1b[0m';
9
- const DIM = '\x1b[2m';
10
- const RED = '\x1b[31m';
11
- const YEL = '\x1b[33m';
12
- const CYN = '\x1b[36m';
13
-
14
- function parseDuration(s) {
15
- const m = /^(\d+)(m|h|d)$/i.exec(String(s).trim());
16
- if (!m) return 2 * 3600 * 1000;
17
- const n = parseInt(m[1], 10);
18
- if (m[2] === 'm') return n * 60 * 1000;
19
- if (m[2] === 'h') return n * 3600 * 1000;
20
- return n * 24 * 3600 * 1000;
21
- }
22
-
23
- // FIXED 2026-09-24: velaro-messaging's /superadmin/logs/search used to return a bare JSON array
24
- // for some queries and {entries, nextCursor} for others, depending on which internal code path
25
- // served the request. It now always returns {entries, nextCursor} -- this helper also accepts a
26
- // bare array so the CLI degrades gracefully rather than crashing if pointed at an older deploy.
27
- function extractLogEntries(response) {
28
- if (Array.isArray(response)) return response;
29
- if (response && Array.isArray(response.entries)) return response.entries;
30
- return [];
31
- }
32
-
33
- function printEntry(e) {
34
- const ts = new Date(e.timestamp ?? e.LogTimestamp).toISOString().replace('T', ' ').slice(0, 19);
35
- const lvl = (e.Level ?? e.level ?? '?').padEnd(5);
36
- const color = (e.Level ?? e.level) === 'ERROR' ? RED : (e.Level ?? e.level) === 'WARN' ? YEL : RESET;
37
- const tag = (e.IntegrationTag ?? e.integrationTag) ? ` ${CYN}[${e.IntegrationTag ?? e.integrationTag}]${RESET}` : '';
38
- const site = (e.siteId ?? e.SiteId) ? ` ${DIM}(site ${e.siteId ?? e.SiteId})${RESET}` : '';
39
- const logger = (e.Logger ?? e.logger ?? '').split('.').pop() ?? '';
40
- const msg = e.Message ?? e.message ?? '';
41
- console.log(`${DIM}${ts}${RESET} ${color}${lvl}${RESET} ${DIM}${logger}${RESET}${tag}${site} ${msg}`);
42
- }
43
-
44
- async function getMsgBase(argv) {
45
- const cfg = readConfig();
46
- const env = argv.env || cfg.env || 'staging';
47
- return cfg.envs?.[env]?.messagingApiBase ?? ENVS[env]?.messagingApiBase
48
- ?? 'https://velaro-messaging-api-staging.azurewebsites.net';
49
- }
50
-
51
- async function requireAdmin(creds) {
52
- if (creds.siteId !== 1032) {
53
- console.error('velaro logs is only available to Velaro staff (site 1032).');
54
- process.exit(1);
55
- }
56
- }
57
-
58
- // ── search handler ────────────────────────────────────────────────────────────
59
-
60
- async function searchLogs(argv) {
61
- try { await searchLogsInner(argv); } catch (err) { console.error(err?.message ?? String(err)); process.exit(1); }
62
- }
63
-
64
- async function searchLogsInner(argv) {
65
- const creds = await getCredentials();
66
- await requireAdmin(creds);
67
- const msgBase = await getMsgBase(argv);
68
- // Always say WHICH environment is searched. The CLI defaults to prod, and a staging problem searched
69
- // there looks identical to "nothing was logged" (cost days on 2026-10-21).
70
- const searchedEnv = /staging|stg/i.test(msgBase) ? 'staging' : 'prod';
71
- console.log(`${DIM}environment: ${searchedEnv} (${msgBase})${searchedEnv === 'prod' ? ' - add --env staging for staging logs' : ''}${RESET}`);
72
-
73
- const to = argv.to ? new Date(argv.to) : new Date();
74
- const from = argv.from ? new Date(argv.from) : new Date(to.getTime() - parseDuration(argv.last ?? '2h'));
75
- if (Number.isNaN(from.getTime()) || Number.isNaN(to.getTime()) || to <= from) {
76
- console.error('Invalid time window: --from/--to must be ISO timestamps with --to after --from.');
77
- process.exit(1);
78
- }
79
- const headers = { Authorization: `Bearer ${creds.velaroToken}`, 'X-Internal-SiteId': String(creds.siteId) };
80
- // 40 s: the server's own scan budget is 12 s (+6 s AI search) per request, and a 429 (scan gate full) is retried with Retry-After.
81
- const getJson = (query) => fetchJsonRetry(`${msgBase}/superadmin/logs/search?${query}`, () => ({ headers, signal: AbortSignal.timeout(40000) }));
82
-
83
- // --raw: the server's own q= search (kept for parity). Proven 2026-10-14 to under-report (q=[HttpFallback]
84
- // returned 0-2 rows while 136 existed), so it now always prints the server's searchPath/scannedRows/truncated.
85
- if (argv.raw) {
86
- const params = new URLSearchParams({ from: from.toISOString(), to: to.toISOString(), take: String(argv.take ?? 50) });
87
- if (argv.query) params.set('q', argv.query);
88
- if (argv.level) params.set('level', argv.level.toUpperCase());
89
- if (argv.integration) params.set('integration', argv.integration);
90
- if (argv.site) params.set('siteId', String(argv.site));
91
- if (argv.source) params.set('source', argv.source);
92
- if (argv.platform) params.set('platform', argv.platform);
93
- if (argv.environment) params.set('environment', argv.environment);
94
- if (argv.correlationId) params.set('correlationId', argv.correlationId);
95
- if (argv.regex) params.set('regex', 'true');
96
- const resp = await getJson(params.toString());
97
- const entries = extractLogEntries(resp);
98
- console.log(`${DIM}${describeRawMeta(resp)}${RESET}`);
99
- if (!entries.length) { console.log('No results (raw server search; see the line above before trusting that).'); return; }
100
- console.log(`\n${DIM}${entries.length} result(s) from ${from.toISOString().slice(0, 16)} UTC${RESET}\n`);
101
- for (const e of entries) printEntry(e);
102
- console.log('');
103
- return;
104
- }
105
-
106
- // Default: COMPLETE read. Never sends q=: filters level/site/source/... server side, bisects any slice the
107
- // server reports as capped (includeTotal), filters text client side, and says COMPLETE or INCOMPLETE.
108
- const result = await completeLogSearch({
109
- fetchJson: getJson,
110
- from, to,
111
- params: { level: argv.level, siteId: argv.site, source: argv.source, integration: argv.integration, platform: argv.platform, environment: argv.environment, correlationId: argv.correlationId },
112
- contains: argv.regex ? undefined : argv.query,
113
- regex: argv.regex ? argv.query : undefined,
114
- logger: argv.logger,
115
- maxRequests: argv.maxRequests ?? 200,
116
- maxSeconds: argv.maxSeconds ?? 120,
117
- wanted: argv.take ?? 50,
118
- });
119
- console.log(`${result.complete ? DIM : YEL}${describeCompleteness(result)}${RESET}`);
120
- if (!result.entries.length) {
121
- console.log(searchedEnv === 'prod' ? 'No results in PROD. If you meant staging, re-run with --env staging.' : 'No results.');
122
- return;
123
- }
124
- const shown = result.entries.slice(0, argv.take ?? 50);
125
- console.log(`\n${DIM}showing ${shown.length} of ${result.entries.length} (newest first) from ${from.toISOString().slice(0, 16)} UTC${RESET}\n`);
126
- for (const e of shown) printEntry(e);
127
- console.log('');
128
- }
129
-
130
- // ── tail handler (SSE stream) ─────────────────────────────────────────────────
131
-
132
- async function tailLogs(argv) {
133
- const creds = await getCredentials();
134
- await requireAdmin(creds);
135
- const msgBase = await getMsgBase(argv);
136
-
137
- const url = new URL(`${msgBase}/superadmin/logs/stream`);
138
- if (argv.level) url.searchParams.set('level', argv.level.toUpperCase());
139
- if (argv.integration) url.searchParams.set('integration', argv.integration);
140
- if (argv.site) url.searchParams.set('siteId', String(argv.site));
141
- if (argv.source) url.searchParams.set('source', argv.source);
142
-
143
- const envLabel = argv.env || readConfig().env || 'staging';
144
- console.log(`\n${DIM}Streaming from ${envLabel} — Ctrl+C to stop${RESET}\n`);
145
-
146
- const res = await fetch(url.toString(), {
147
- headers: {
148
- Authorization: `Bearer ${creds.velaroToken}`,
149
- 'X-Internal-SiteId': String(creds.siteId),
150
- },
151
- signal: AbortSignal.timeout(660_000),
152
- });
153
-
154
- if (!res.ok) {
155
- console.error(`HTTP ${res.status}: could not connect to log stream`);
156
- process.exit(1);
157
- }
158
-
159
- const decoder = new TextDecoder();
160
- for await (const chunk of res.body) {
161
- const text = decoder.decode(chunk, { stream: true });
162
- for (const line of text.split('\n')) {
163
- if (!line.startsWith('data: ')) continue;
164
- const json = line.slice(6).trim();
165
- if (!json || json.startsWith('{"status"')) continue;
166
- try { printEntry(JSON.parse(json)); } catch { /* malformed line */ }
167
- }
168
- }
169
- }
170
-
171
- // ── digest-recipients handlers ────────────────────────────────────────────────
172
-
173
- async function getAdminBase(argv) {
174
- const cfg = readConfig();
175
- const env = argv.env || cfg.env || 'staging';
176
- return cfg.envs?.[env]?.adminApiBase ?? ENVS[env]?.adminApiBase
177
- ?? 'https://velaro-admin-staging.azurewebsites.net';
178
- }
179
-
180
- async function getDigestRecipients(argv) {
181
- const creds = await getCredentials();
182
- await requireAdmin(creds);
183
- const adminBase = await getAdminBase(argv);
184
-
185
- const res = await fetch(`${adminBase}/superadmin/logs/digest-recipients`, {
186
- headers: {
187
- Authorization: `Bearer ${creds.velaroToken}`,
188
- 'X-Internal-SiteId': String(creds.siteId),
189
- },
190
- signal: AbortSignal.timeout(15000),
191
- });
192
-
193
- if (!res.ok) {
194
- console.error(`HTTP ${res.status}: ${await res.text().catch(() => '')}`);
195
- process.exit(1);
196
- }
197
-
198
- const data = await res.json();
199
- console.log(`\nLog digest recipients: ${data.recipients}`);
200
- console.log(`\nTo persist changes: set LOG_DIGEST_RECIPIENTS in Azure App Settings.`);
201
- console.log(`Digest job runs every 4h (Hangfire job: log-digest-4h, queue: low).\n`);
202
- }
203
-
204
- async function setDigestRecipients(argv) {
205
- const creds = await getCredentials();
206
- await requireAdmin(creds);
207
- const adminBase = await getAdminBase(argv);
208
-
209
- if (!argv.emails) {
210
- console.error('--emails is required. Example: velaro logs set-digest-recipients --emails "noc@velaro.com;alex@velaro.com"');
211
- process.exit(1);
212
- }
213
-
214
- const res = await fetch(`${adminBase}/superadmin/logs/digest-recipients`, {
215
- method: 'POST',
216
- headers: {
217
- Authorization: `Bearer ${creds.velaroToken}`,
218
- 'X-Internal-SiteId': String(creds.siteId),
219
- 'Content-Type': 'application/json',
220
- },
221
- body: JSON.stringify({ recipients: argv.emails }),
222
- signal: AbortSignal.timeout(15000),
223
- });
224
-
225
- if (!res.ok) {
226
- const body = await res.text().catch(() => '');
227
- console.error(`HTTP ${res.status}: ${body}`);
228
- process.exit(1);
229
- }
230
-
231
- const data = await res.json();
232
- console.log(`\n✓ Recipients validated: ${data.recipients}`);
233
- console.log(`Note: ${data.note}\n`);
234
- }
235
-
236
- // ── diagnose handler ──────────────────────────────────────────────────────────
237
-
238
- async function diagnoseLogs(argv) {
239
- const creds = await getCredentials();
240
- await requireAdmin(creds);
241
- const msgBase = await getMsgBase(argv);
242
- const window = argv.last ?? '1h';
243
- const from = new Date(Date.now() - parseDuration(window));
244
-
245
- const BOLD = '\x1b[1m'; const RESET2 = '\x1b[0m'; const GREEN = '\x1b[32m';
246
-
247
- console.log(`\n${BOLD}── Bot Diagnostic — last ${window} ──────────────────────────────${RESET2}`);
248
-
249
- // Run error search and perf/routing search in parallel. FIXED 2026-10-14: the old calls searched the TEXT "level:ERROR" and the
250
- // TEXT "WF-AI-ROUTE OR PERF-SLOW", which no log line contains, so this printed "No errors" no matter what. Errors are now the
251
- // server-side level filter and the perf/routing pair is a regex; the server's scan metadata is surfaced so an unverified
252
- // empty answer is never shown as a clean bill of health.
253
- const notes = [];
254
- async function search(label, p0) {
255
- const p = new URLSearchParams({ from: from.toISOString(), take: '50', ...p0 });
256
- const resp = await fetchJsonRetry(`${msgBase}/superadmin/logs/search?${p}`, () => ({
257
- headers: { Authorization: `Bearer ${creds.velaroToken}`, 'X-Internal-SiteId': String(creds.siteId) },
258
- signal: AbortSignal.timeout(40000),
259
- })).catch((err) => { notes.push(`${label}: search failed (${err.message})`); return null; });
260
- if (resp && !Array.isArray(resp) && resp.truncated !== false) notes.push(`${label}: ${describeRawMeta(resp)}`);
261
- else if (Array.isArray(resp)) notes.push(`${label}: ${describeRawMeta(resp)}`);
262
- return resp ? extractLogEntries(resp) : [];
263
- }
264
-
265
- // One at a time: the server runs at most 2 exact scans per instance.
266
- const errors = await search('errors', { level: 'ERROR' });
267
- const perfAndRouting = await search('perf/routing', { q: 'WF-AI-ROUTE|PERF-SLOW', regex: 'true' });
268
- for (const n of notes) console.log(` \x1b[33m!\x1b[0m ${n}`);
269
-
270
- // ── Errors ──
271
- console.log(`\n${BOLD}Errors${RESET2}`);
272
- if (!errors.length) {
273
- console.log(` ${GREEN}✓${RESET2} No errors`);
274
- } else {
275
- for (const e of errors) printEntry(e);
276
- }
277
-
278
- // ── Perf ──
279
- const perfEntries = perfAndRouting.filter(e => (e.Message ?? e.message ?? '').includes('PERF-SLOW'));
280
- const routeEntries = perfAndRouting.filter(e => (e.Message ?? e.message ?? '').includes('WF-AI-ROUTE'));
281
-
282
- console.log(`\n${BOLD}Perf [WF-PERF-SLOW] [AI-PERF-SLOW]${RESET2}`);
283
- if (!perfEntries.length) {
284
- console.log(` ${GREEN}✓${RESET2} No slow responses`);
285
- } else {
286
- for (const e of perfEntries) printEntry(e);
287
- }
288
-
289
- // ── AI Routing ──
290
- console.log(`\n${BOLD}AI Intent Routing [WF-AI-ROUTE]${RESET2}`);
291
- if (!routeEntries.length) {
292
- console.log(` ${GREEN}✓${RESET2} No AI routing events`);
293
- } else {
294
- const matched = routeEntries.filter(e => (e.Message ?? e.message ?? '').includes('AI matched'));
295
- const timeouts = routeEntries.filter(e => (e.Message ?? e.message ?? '').includes('timed out'));
296
- const failed = routeEntries.filter(e => (e.Message ?? e.message ?? '').includes('failed'));
297
- console.log(` Matched: ${matched.length} Timeouts: ${timeouts.length} Errors: ${failed.length}`);
298
- for (const e of routeEntries.slice(0, 10)) printEntry(e);
299
- if (routeEntries.length > 10) console.log(` ... and ${routeEntries.length - 10} more`);
300
- }
301
-
302
- // ── Summary ──
303
- const status = errors.length ? '\x1b[31m⚠ ERRORS FOUND\x1b[0m'
304
- : perfEntries.length ? '\x1b[33m⚠ SLOW RESPONSES\x1b[0m'
305
- : routeEntries.length ? '\x1b[36m🤖 AI ROUTING ACTIVE\x1b[0m'
306
- : `${GREEN}✅ ALL CLEAR\x1b[0m`;
307
- console.log(`\n${BOLD}Summary:${RESET2} ${status} (${errors.length} errors, ${perfEntries.length} slow, ${routeEntries.length} ai-routes)\n`);
308
- console.log(`Velaro Logger presaved filter: "AI Intent Routing + Perf"\n`);
309
- }
310
-
311
- // ── alert rule helpers ───────────────────────────────────────────────────────
312
-
313
- const ALERT_RULE_DEFAULTS = {
314
- windowMinutes: 5,
315
- thresholdCount: 1,
316
- minRefireMinutes: 60,
317
- };
318
-
319
- // Strips ANSI/control characters from AI-generated text before it ever reaches
320
- // the terminal (not just the copy-pasteable command line below) — an AI
321
- // suggestion is untrusted text and should never be able to inject escape
322
- // sequences into the user's terminal.
323
- function sanitizeForTerminal(s) {
324
- if (typeof s !== 'string') return s;
325
- // eslint-disable-next-line no-control-regex
326
- return s.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
327
- }
328
-
329
- // POSIX-safe single-quote wrapping for interpolating untrusted values into a
330
- // printed shell command line (standard 'wrap, escape embedded quotes' trick).
331
- function shellQuote(value) {
332
- const s = String(value ?? '');
333
- return `'${s.replace(/'/g, `'\\''`)}'`;
334
- }
335
-
336
- // Validates a value is meant to be a positive (>=1) finite integer for a
337
- // numeric alert-rule flag. Returns the parsed integer, or null if invalid.
338
- // `argv[flag]` from yargs with `type: 'number'` is already a number (or NaN
339
- // if the user passed something non-numeric like `--threshold abc`), but we
340
- // re-parse defensively since a flag can also arrive as a string in some
341
- // invocation paths.
342
- function parsePositiveIntFlag(flagName, rawValue, { max } = {}) {
343
- if (rawValue === undefined || rawValue === null) return { ok: true, value: undefined };
344
- const n = typeof rawValue === 'number' ? rawValue : Number(rawValue);
345
- if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1) {
346
- return { ok: false, error: `--${flagName} must be a whole number >= 1 (got ${JSON.stringify(rawValue)}).` };
347
- }
348
- if (max !== undefined && n > max) {
349
- return { ok: false, error: `--${flagName} must be <= ${max} (got ${n}).` };
350
- }
351
- return { ok: true, value: n };
352
- }
353
-
354
- // A rule with none of the five notification channels fires into the void —
355
- // it's pure log noise that pages no one. Mirrors the same guard in
356
- // client/src/pages/Messaging/Integrations/AlertRules.tsx (extended here to
357
- // also cover webhook/teams, which that component's check omits).
358
- // NOTE: a blank emails/sms does NOT necessarily mean "no one" any more --
359
- // LogAlertEvaluationService.ResolveRecipients falls back to global-default
360
- // AlertContacts when a rule leaves those blank. Callers should pass
361
- // hasGlobalDefaultContacts (from fetchHasGlobalDefaultContacts) so a blank
362
- // emails/sms isn't wrongly flagged as "fires into the void" when defaults
363
- // actually cover it.
364
- function hasAnyRecipient({ emails, sms, webhook, teams, mobileUserIds, hasGlobalDefaultContacts }) {
365
- return Boolean(
366
- (emails && String(emails).trim()) ||
367
- (sms && String(sms).trim()) ||
368
- (webhook && String(webhook).trim()) ||
369
- teams ||
370
- (mobileUserIds && String(mobileUserIds).trim()) ||
371
- // Blank emails AND blank sms both fall back to global defaults together (see
372
- // ResolveRecipients) -- if there's at least one global-default contact with a phone or
373
- // email, a rule with both blank is NOT actually silent, even though neither field is set.
374
- ((!emails || !String(emails).trim()) && (!sms || !String(sms).trim()) && hasGlobalDefaultContacts)
375
- );
376
- }
377
-
378
- // Fetches whether at least one global-default AlertContact exists with a phone or email --
379
- // used only to soften the "fires into the void" guard above, never cached across CLI
380
- // invocations, so a stale answer can't cause a false pass. Returns false (fail toward the
381
- // stricter behavior) on any fetch error rather than silently skipping the guard.
382
- async function fetchHasGlobalDefaultContacts(creds, msgBase) {
383
- try {
384
- const res = await fetch(`${msgBase}/superadmin/log-alerts/contacts`, {
385
- headers: { Authorization: `Bearer ${creds.velaroToken}`, 'X-Internal-SiteId': String(creds.siteId) },
386
- signal: AbortSignal.timeout(15000),
387
- });
388
- if (!res.ok) return false;
389
- const contacts = await res.json();
390
- return Array.isArray(contacts) && contacts.some(c =>
391
- c.isGlobalDefault && ((c.phoneNumber && c.phoneNumber.trim()) || (c.email && c.email.trim())));
392
- } catch {
393
- return false;
394
- }
395
- }
396
-
397
- function printAlertRule(r) {
398
- const state = r.enabled === false ? `${DIM}paused${RESET}` : `${CYN}active${RESET}`;
399
- const bits = [`>=${r.thresholdCount} in ${r.windowMinutes}m`];
400
- if (r.level) bits.push(`level=${r.level}`);
401
- if (r.queryText) bits.push(`q="${r.queryText}"`);
402
- if (r.integration) bits.push(`tag=${r.integration}`);
403
- if (r.siteId) bits.push(`site=${r.siteId}`);
404
- if (r.notifyPhoneNumbers) bits.push('SMS');
405
- else if (!r.notifyEmails) bits.push('SMS+email (global defaults)');
406
- if (r.notifyEmails) bits.push('email');
407
- if (r.notifyWebhookUrl) bits.push('webhook');
408
- if (r.notifyTeams) bits.push('Teams');
409
- if (r.notifyMobileUserIds) bits.push('mobile push');
410
- if (r.excludeContactNames) bits.push(`excl:${r.excludeContactNames}`);
411
- if (r.notifyTeams) bits.push('Teams');
412
- bits.push(`cooldown ${r.minRefireMinutes}m`);
413
- console.log(`${DIM}[${r.id}]${RESET} ${r.name} ${state}`);
414
- console.log(` ${bits.join(' ')}`);
415
- }
416
-
417
- async function listAlertRules(argv) {
418
- const creds = await getCredentials();
419
- await requireAdmin(creds);
420
- const msgBase = await getMsgBase(argv);
421
-
422
- const res = await fetch(`${msgBase}/superadmin/log-alerts/rules`, {
423
- headers: { Authorization: `Bearer ${creds.velaroToken}`, 'X-Internal-SiteId': String(creds.siteId) },
424
- signal: AbortSignal.timeout(15000),
425
- });
426
- if (!res.ok) {
427
- console.error(`HTTP ${res.status}: ${await res.text().catch(() => '')}`);
428
- process.exit(1);
429
- }
430
- const rules = await res.json();
431
- if (!Array.isArray(rules) || !rules.length) {
432
- console.log('No alert rules yet. Create one with: velaro logs alerts create --name "..." --query "..."');
433
- return;
434
- }
435
- console.log(`\n${DIM}${rules.length} alert rule(s)${RESET}\n`);
436
- for (const r of rules) printAlertRule(r);
437
- console.log('');
438
- }
439
-
440
- async function suggestAlertRule(argv) {
441
- const creds = await getCredentials();
442
- await requireAdmin(creds);
443
- const msgBase = await getMsgBase(argv);
444
-
445
- if (!argv.description) {
446
- console.error('--description is required. Example: velaro logs alerts suggest --description "text me if NetSuite errors 3+ times in 10 min"');
447
- process.exit(1);
448
- }
449
-
450
- const res = await fetch(`${msgBase}/superadmin/log-alerts/suggest`, {
451
- method: 'POST',
452
- headers: {
453
- Authorization: `Bearer ${creds.velaroToken}`,
454
- 'X-Internal-SiteId': String(creds.siteId),
455
- 'Content-Type': 'application/json',
456
- },
457
- body: JSON.stringify({ description: argv.description }),
458
- signal: AbortSignal.timeout(30000),
459
- });
460
-
461
- if (!res.ok) {
462
- console.error(`HTTP ${res.status}: ${await res.text().catch(() => '')}`);
463
- process.exit(1);
464
- }
465
-
466
- const data = await res.json();
467
- if (data.error) {
468
- console.error(`Could not generate a suggestion: ${sanitizeForTerminal(String(data.error))}`);
469
- console.log('You can still create a rule manually with: velaro logs alerts create --name "..." --query "..."');
470
- process.exit(1);
471
- }
472
-
473
- // Every AI-generated field is untrusted text — strip control/ANSI escapes
474
- // before it ever reaches the terminal, not just in the copy-paste line below.
475
- const name = sanitizeForTerminal(data.name ?? '');
476
- const queryText = sanitizeForTerminal(data.queryText ?? '');
477
- const level = sanitizeForTerminal(data.level ?? '');
478
- const integration = sanitizeForTerminal(data.integration ?? '');
479
- const reasoning = data.reasoning ? sanitizeForTerminal(String(data.reasoning)) : null;
480
- const windowMinutes = data.windowMinutes ?? ALERT_RULE_DEFAULTS.windowMinutes;
481
- const thresholdCount = data.thresholdCount ?? ALERT_RULE_DEFAULTS.thresholdCount;
482
- const minRefireMinutes = data.minRefireMinutes ?? ALERT_RULE_DEFAULTS.minRefireMinutes;
483
-
484
- console.log(`\n${DIM}Suggested rule (preview only — not created; pass to 'create' to save):${RESET}\n`);
485
- console.log(` name: ${name}`);
486
- console.log(` queryText: ${queryText}`);
487
- console.log(` level: ${level || '(any)'}`);
488
- console.log(` integration: ${integration || '(any)'}`);
489
- console.log(` windowMinutes: ${windowMinutes}`);
490
- console.log(` thresholdCount: ${thresholdCount}`);
491
- console.log(` minRefireMinutes: ${minRefireMinutes}`);
492
- if (reasoning) console.log(`\n${DIM}Why:${RESET} ${reasoning}`);
493
- console.log(`\nNote: this suggestion has no notification channels — add --emails/--sms/--webhook when you create it, or the rule will fire into the void.`);
494
- console.log(`\nTo create it:\n velaro logs alerts create --name ${shellQuote(name)} --query ${shellQuote(queryText)}${level ? ` --level ${shellQuote(level)}` : ''} --window-minutes ${windowMinutes} --threshold ${thresholdCount} --cooldown-minutes ${minRefireMinutes} --emails "..." --yes\n`);
495
- }
496
-
497
- async function createAlertRule(argv) {
498
- const creds = await getCredentials();
499
- await requireAdmin(creds);
500
- const msgBase = await getMsgBase(argv);
501
-
502
- if (!argv.name || !argv.query) {
503
- console.error('--name and --query are required. Example: velaro logs alerts create --name "NetSuite errors" --query "exception"');
504
- process.exit(1);
505
- }
506
-
507
- // HIGH: LogAlertDecisionEngine evaluates `count >= effectiveThreshold`, so a
508
- // threshold of 0 (or negative, or NaN from a bad --threshold value) fires on
509
- // every single evaluation tick — a permanently-firing, unresolvable alert.
510
- // The backend's CreateRule endpoint (unlike UpdateRule/PatchRuleByName) does
511
- // not clamp this, so the CLI must validate before sending the request.
512
- const checks = [
513
- parsePositiveIntFlag('threshold', argv.threshold),
514
- parsePositiveIntFlag('window-minutes', argv.windowMinutes, { max: 1440 }),
515
- parsePositiveIntFlag('cooldown-minutes', argv.cooldownMinutes),
516
- ];
517
- const failed = checks.find(c => !c.ok);
518
- if (failed) {
519
- console.error(failed.error);
520
- process.exit(1);
521
- }
522
- const [thresholdCheck, windowCheck, cooldownCheck] = checks;
523
-
524
- // HIGH: a rule with zero notification channels fires into the void. A blank --emails/--sms
525
- // may still be covered by global-default AlertContacts (see hasAnyRecipient docs), so check
526
- // those before failing.
527
- const hasDefaults = await fetchHasGlobalDefaultContacts(creds, msgBase);
528
- if (!hasAnyRecipient({ emails: argv.emails, sms: argv.sms, webhook: argv.webhook, teams: argv.teams, mobileUserIds: argv.mobileUserIds, hasGlobalDefaultContacts: hasDefaults })
529
- && !argv.noRecipientsOk) {
530
- console.error('No notification channel given (--emails, --sms, --webhook, --teams, or --mobile-user-ids), and no global-default contact exists to fall back to — this rule would fire but notify no one.');
531
- console.error('If that\'s intentional (e.g. you only want it visible in Alert History), pass --no-recipients-ok to proceed anyway.');
532
- console.error('To set up global defaults so a blank --emails/--sms is covered automatically: velaro logs contacts add --name alex --phone +1... --email alex@velaro.com --global');
533
- process.exit(1);
534
- }
535
-
536
- const body = {
537
- name: argv.name,
538
- queryText: argv.query,
539
- level: argv.level ? argv.level.toUpperCase() : undefined,
540
- integration: argv.integration,
541
- windowMinutes: windowCheck.value ?? ALERT_RULE_DEFAULTS.windowMinutes,
542
- thresholdCount: thresholdCheck.value ?? ALERT_RULE_DEFAULTS.thresholdCount,
543
- minRefireMinutes: cooldownCheck.value ?? ALERT_RULE_DEFAULTS.minRefireMinutes,
544
- notifyEmails: argv.emails,
545
- notifyPhoneNumbers: argv.sms,
546
- notifyWebhookUrl: argv.webhook,
547
- notifyTeams: Boolean(argv.teams),
548
- notifyMobileUserIds: argv.mobileUserIds,
549
- excludeContactNames: argv.excludeContacts,
550
- notifyTeams: Boolean(argv.teams),
551
- enabled: true,
552
- };
553
-
554
- // HIGH: create is a real, live write with no undo from the CLI — preview
555
- // before sending, require --yes to actually proceed. Mirrors the
556
- // `kb swap-connection` confirmation pattern in cli/lib/commands/kb.js.
557
- if (!argv.yes) {
558
- console.log(`\n${DIM}About to create this alert rule (dry run — nothing sent yet):${RESET}\n`);
559
- printAlertRule({ ...body, id: '(new)' });
560
- console.log(`\nRe-run with --yes to actually create it.\n`);
561
- return;
562
- }
563
-
564
- const res = await fetch(`${msgBase}/superadmin/log-alerts/rules`, {
565
- method: 'POST',
566
- headers: {
567
- Authorization: `Bearer ${creds.velaroToken}`,
568
- 'X-Internal-SiteId': String(creds.siteId),
569
- 'Content-Type': 'application/json',
570
- },
571
- body: JSON.stringify(body),
572
- signal: AbortSignal.timeout(15000),
573
- });
574
-
575
- if (!res.ok) {
576
- console.error(`HTTP ${res.status}: ${await res.text().catch(() => '')}`);
577
- process.exit(1);
578
- }
579
-
580
- const data = await res.json();
581
- console.log(`\n${CYN}✓${RESET} Created rule [${data.id}] "${data.name}"\n`);
582
- printAlertRule(data);
583
- console.log('');
584
- }
585
-
586
- async function updateAlertRule(argv) {
587
- const creds = await getCredentials();
588
- await requireAdmin(creds);
589
- const msgBase = await getMsgBase(argv);
590
-
591
- if (!argv.id) {
592
- console.error('Rule id is required. Example: velaro logs alerts update 42 --threshold 60');
593
- process.exit(1);
594
- }
595
-
596
- // No single-rule GET endpoint (same limitation deleteAlertRule already works
597
- // around) -- UpdateRule is a whole-object PUT, not a partial patch, so every
598
- // field has to be re-sent or it gets wiped. Fetch the current rule from the
599
- // list first and merge only the flags actually passed on top of it.
600
- const listRes = await fetch(`${msgBase}/superadmin/log-alerts/rules`, {
601
- headers: { Authorization: `Bearer ${creds.velaroToken}`, 'X-Internal-SiteId': String(creds.siteId) },
602
- signal: AbortSignal.timeout(15000),
603
- });
604
- if (!listRes.ok) {
605
- console.error(`HTTP ${listRes.status}: ${await listRes.text().catch(() => '')}`);
606
- process.exit(1);
607
- }
608
- const rules = await listRes.json().catch(() => []);
609
- const target = Array.isArray(rules) ? rules.find(r => String(r.id) === String(argv.id)) : null;
610
- if (!target) {
611
- console.error(`No rule with id ${argv.id} found. Run 'velaro logs alerts list' to see current ids.`);
612
- process.exit(1);
613
- }
614
-
615
- const checks = [
616
- parsePositiveIntFlag('threshold', argv.threshold),
617
- parsePositiveIntFlag('window-minutes', argv.windowMinutes, { max: 1440 }),
618
- parsePositiveIntFlag('cooldown-minutes', argv.cooldownMinutes),
619
- ];
620
- const failed = checks.find(c => !c.ok);
621
- if (failed) {
622
- console.error(failed.error);
623
- process.exit(1);
624
- }
625
- const [thresholdCheck, windowCheck, cooldownCheck] = checks;
626
-
627
- const body = {
628
- ...target,
629
- name: argv.name ?? target.name,
630
- queryText: argv.query ?? target.queryText,
631
- level: argv.level ? argv.level.toUpperCase() : target.level,
632
- integration: argv.integration ?? target.integration,
633
- windowMinutes: windowCheck.value ?? target.windowMinutes,
634
- thresholdCount: thresholdCheck.value ?? target.thresholdCount,
635
- minRefireMinutes: cooldownCheck.value ?? target.minRefireMinutes,
636
- notifyEmails: argv.emails ?? target.notifyEmails,
637
- notifyPhoneNumbers: argv.sms ?? target.notifyPhoneNumbers,
638
- notifyWebhookUrl: argv.webhook ?? target.notifyWebhookUrl,
639
- notifyTeams: argv.teams !== undefined ? Boolean(argv.teams) : target.notifyTeams,
640
- notifyMobileUserIds: argv.mobileUserIds ?? target.notifyMobileUserIds,
641
- excludeContactNames: argv.excludeContacts ?? target.excludeContactNames,
642
- notifyTeams: argv.teams !== undefined ? Boolean(argv.teams) : Boolean(target.notifyTeams),
643
- enabled: argv.enabled !== undefined ? argv.enabled : target.enabled,
644
- };
645
-
646
- // HIGH: same "fires into the void" guard as create -- an update that strips
647
- // every notification channel (or a rule that already had none, being
648
- // re-enabled without adding one) silently produces an alert nobody sees.
649
- const hasDefaults = await fetchHasGlobalDefaultContacts(creds, msgBase);
650
- if (!hasAnyRecipient({ emails: body.notifyEmails, sms: body.notifyPhoneNumbers, webhook: body.notifyWebhookUrl, teams: body.notifyTeams, mobileUserIds: body.notifyMobileUserIds, hasGlobalDefaultContacts: hasDefaults })
651
- && !argv.noRecipientsOk) {
652
- console.error('This update would leave the rule with no notification channel (--emails, --sms, --webhook, --teams, or --mobile-user-ids), and no global-default contact exists to fall back to — it would fire but notify no one.');
653
- console.error('If that\'s intentional, pass --no-recipients-ok to proceed anyway.');
654
- process.exit(1);
655
- }
656
-
657
- if (!argv.yes) {
658
- console.log(`\n${DIM}Current rule:${RESET}\n`);
659
- printAlertRule(target);
660
- console.log(`\n${DIM}About to update to (dry run — nothing sent yet):${RESET}\n`);
661
- printAlertRule(body);
662
- console.log(`\nRe-run with --yes to actually apply this update.\n`);
663
- return;
664
- }
665
-
666
- const res = await fetch(`${msgBase}/superadmin/log-alerts/rules/${argv.id}`, {
667
- method: 'PUT',
668
- headers: {
669
- Authorization: `Bearer ${creds.velaroToken}`,
670
- 'X-Internal-SiteId': String(creds.siteId),
671
- 'Content-Type': 'application/json',
672
- },
673
- body: JSON.stringify(body),
674
- signal: AbortSignal.timeout(15000),
675
- });
676
- if (!res.ok) {
677
- console.error(`HTTP ${res.status}: ${await res.text().catch(() => '')}`);
678
- process.exit(1);
679
- }
680
- const data = await res.json();
681
- console.log(`\n${CYN}✓${RESET} Updated rule [${data.id}] "${data.name}"\n`);
682
- printAlertRule(data);
683
- console.log('');
684
- }
685
-
686
- async function toggleAlertRule(argv) {
687
- const creds = await getCredentials();
688
- await requireAdmin(creds);
689
- const msgBase = await getMsgBase(argv);
690
-
691
- if (!argv.id) {
692
- console.error('Rule id is required. Example: velaro logs alerts toggle 42');
693
- process.exit(1);
694
- }
695
-
696
- const res = await fetch(`${msgBase}/superadmin/log-alerts/rules/${argv.id}/toggle`, {
697
- method: 'POST',
698
- headers: { Authorization: `Bearer ${creds.velaroToken}`, 'X-Internal-SiteId': String(creds.siteId) },
699
- signal: AbortSignal.timeout(15000),
700
- });
701
- if (!res.ok) {
702
- console.error(`HTTP ${res.status}: ${await res.text().catch(() => '')}`);
703
- process.exit(1);
704
- }
705
- const data = await res.json();
706
- console.log(`Rule ${argv.id} is now ${data.enabled ? 'active' : 'paused'}.`);
707
- }
708
-
709
- async function deleteAlertRule(argv) {
710
- const creds = await getCredentials();
711
- await requireAdmin(creds);
712
- const msgBase = await getMsgBase(argv);
713
-
714
- if (!argv.id) {
715
- console.error('Rule id is required. Example: velaro logs alerts delete 42');
716
- process.exit(1);
717
- }
718
-
719
- // HIGH: delete is a real, live, irreversible write — fetch and print the
720
- // rule being deleted (name, query, recipients) before doing anything.
721
- // There's no single-rule GET endpoint, so pull the list and find it there.
722
- const listRes = await fetch(`${msgBase}/superadmin/log-alerts/rules`, {
723
- headers: { Authorization: `Bearer ${creds.velaroToken}`, 'X-Internal-SiteId': String(creds.siteId) },
724
- signal: AbortSignal.timeout(15000),
725
- });
726
- let target = null;
727
- if (listRes.ok) {
728
- const rules = await listRes.json().catch(() => []);
729
- target = Array.isArray(rules) ? rules.find(r => String(r.id) === String(argv.id)) : null;
730
- }
731
-
732
- if (target) {
733
- console.log(`\n${DIM}About to delete this alert rule:${RESET}\n`);
734
- printAlertRule(target);
735
- } else {
736
- console.log(`\n${YEL}Could not fetch rule ${argv.id} to preview it (it may already be gone) — proceeding on id alone.${RESET}`);
737
- }
738
-
739
- if (!argv.yes) {
740
- console.log(`\nRe-run with --yes to actually delete it.\n`);
741
- return;
742
- }
743
-
744
- const res = await fetch(`${msgBase}/superadmin/log-alerts/rules/${argv.id}`, {
745
- method: 'DELETE',
746
- headers: { Authorization: `Bearer ${creds.velaroToken}`, 'X-Internal-SiteId': String(creds.siteId) },
747
- signal: AbortSignal.timeout(15000),
748
- });
749
- if (!res.ok) {
750
- console.error(`HTTP ${res.status}: ${await res.text().catch(() => '')}`);
751
- process.exit(1);
752
- }
753
- console.log(`\nDeleted rule ${argv.id}.\n`);
754
- }
755
-
756
- // ── Product family rules ─────────────────────────────────────────────────────
757
- // Logger-prefix -> product-family rules (REST: /superadmin/logs/product-families).
758
-
759
- async function productFamilyRequest(argv, method, path, body) {
760
- const creds = await getCredentials();
761
- await requireAdmin(creds);
762
- const msgBase = await getMsgBase(argv);
763
- const res = await fetch(`${msgBase}/superadmin/logs/product-families${path}`, {
764
- method,
765
- headers: {
766
- Authorization: `Bearer ${creds.velaroToken}`,
767
- 'X-Internal-SiteId': String(creds.siteId),
768
- ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
769
- },
770
- body: body !== undefined ? JSON.stringify(body) : undefined,
771
- signal: AbortSignal.timeout(15000),
772
- });
773
- if (!res.ok) {
774
- console.error(`HTTP ${res.status}: ${await res.text().catch(() => '')}`);
775
- process.exit(1);
776
- }
777
- const text = await res.text().catch(() => '');
778
- return text ? JSON.parse(text) : null;
779
- }
780
-
781
- async function listProductFamilies(argv) {
782
- const qs = argv.site !== undefined ? `?siteId=${encodeURIComponent(argv.site)}` : '';
783
- const rules = await productFamilyRequest(argv, 'GET', qs);
784
- if (!Array.isArray(rules)) {
785
- console.error('Unexpected response from product-families list (expected an array).');
786
- process.exit(1);
787
- }
788
- if (!rules.length) {
789
- console.log('No product family rules. Add one with: velaro logs product-family set <loggerPrefix> <productFamily>');
790
- return;
791
- }
792
- console.log(`\n${DIM}${rules.length} product family rule(s)${RESET}\n`);
793
- for (const r of rules) {
794
- const scope = r.siteId == null ? 'platform' : `site ${r.siteId}`;
795
- console.log(` ${String(r.id).padEnd(5)} ${String(r.loggerPrefix).padEnd(40)} ${CYN}${r.productFamily}${RESET} ${DIM}(${scope})${RESET}`);
796
- }
797
- console.log('');
798
- }
799
-
800
- async function setProductFamily(argv) {
801
- if (!argv.loggerPrefix || !argv.productFamily) {
802
- console.error('Usage: velaro logs product-family set <loggerPrefix> <productFamily> [--site <id>]');
803
- process.exit(1);
804
- }
805
- const body = { loggerPrefix: String(argv.loggerPrefix), productFamily: String(argv.productFamily) };
806
- if (argv.site !== undefined) body.siteId = Number(argv.site);
807
- const saved = await productFamilyRequest(argv, 'PUT', '', body);
808
- console.log(`Saved rule ${saved?.id ?? ''}: ${body.loggerPrefix} -> ${body.productFamily} (${body.siteId == null ? 'platform' : `site ${body.siteId}`})`);
809
- }
810
-
811
- async function deleteProductFamily(argv) {
812
- if (argv.id === undefined || Number.isNaN(Number(argv.id))) {
813
- console.error('Usage: velaro logs product-family delete <id>');
814
- process.exit(1);
815
- }
816
- await productFamilyRequest(argv, 'DELETE', `/${encodeURIComponent(argv.id)}`);
817
- console.log(`Deleted product family rule ${argv.id}.`);
818
- }
819
-
820
- // ── Alert contacts ───────────────────────────────────────────────────────────
821
-
822
- function printAlertContact(c) {
823
- const scope = c.isGlobalDefault ? `${CYN}global default${RESET}` : `${DIM}not global${RESET}`;
824
- const bits = [];
825
- if (c.phoneNumber) bits.push(`SMS ${c.phoneNumber}`);
826
- if (c.email) bits.push(`email ${c.email}`);
827
- console.log(`${DIM}[${c.id}]${RESET} ${c.name}${c.displayName ? ` (${c.displayName})` : ''} ${scope}`);
828
- console.log(` ${bits.join(' ') || '(no phone/email set)'}`);
829
- }
830
-
831
- async function listAlertContacts(argv) {
832
- const creds = await getCredentials();
833
- await requireAdmin(creds);
834
- const msgBase = await getMsgBase(argv);
835
-
836
- const res = await fetch(`${msgBase}/superadmin/log-alerts/contacts`, {
837
- headers: { Authorization: `Bearer ${creds.velaroToken}`, 'X-Internal-SiteId': String(creds.siteId) },
838
- signal: AbortSignal.timeout(15000),
839
- });
840
- if (!res.ok) {
841
- console.error(`HTTP ${res.status}: ${await res.text().catch(() => '')}`);
842
- process.exit(1);
843
- }
844
- const contacts = await res.json();
845
- if (!Array.isArray(contacts) || !contacts.length) {
846
- console.log('No alert contacts yet. Add one with: velaro logs contacts add --name alex --phone +1... --email alex@velaro.com');
847
- return;
848
- }
849
- console.log(`\n${DIM}${contacts.length} alert contact(s)${RESET}\n`);
850
- for (const c of contacts) printAlertContact(c);
851
- console.log('');
852
- }
853
-
854
- async function addAlertContact(argv) {
855
- const creds = await getCredentials();
856
- await requireAdmin(creds);
857
- const msgBase = await getMsgBase(argv);
858
-
859
- if (!argv.name) {
860
- console.error('--name is required. Example: velaro logs contacts add --name alex --phone +14436295872 --email alex@velaro.com');
861
- process.exit(1);
862
- }
863
- if (!argv.phone && !argv.email) {
864
- console.error('At least one of --phone or --email is required.');
865
- process.exit(1);
866
- }
867
-
868
- const body = {
869
- name: argv.name,
870
- displayName: argv.displayName,
871
- phoneNumber: argv.phone,
872
- email: argv.email,
873
- isGlobalDefault: argv.global,
874
- };
875
-
876
- if (!argv.yes) {
877
- console.log(`\n${DIM}About to create this contact (dry run — nothing sent yet):${RESET}\n`);
878
- printAlertContact({ ...body, id: '(new)' });
879
- console.log(`\nRe-run with --yes to actually create it.\n`);
880
- return;
881
- }
882
-
883
- const res = await fetch(`${msgBase}/superadmin/log-alerts/contacts`, {
884
- method: 'POST',
885
- headers: {
886
- Authorization: `Bearer ${creds.velaroToken}`,
887
- 'X-Internal-SiteId': String(creds.siteId),
888
- 'Content-Type': 'application/json',
889
- },
890
- body: JSON.stringify(body),
891
- signal: AbortSignal.timeout(15000),
892
- });
893
- if (!res.ok) {
894
- console.error(`HTTP ${res.status}: ${await res.text().catch(() => '')}`);
895
- process.exit(1);
896
- }
897
- const data = await res.json();
898
- console.log(`\n${CYN}✓${RESET} Created contact [${data.id}] "${data.name}"\n`);
899
- printAlertContact(data);
900
- console.log('');
901
- }
902
-
903
- async function updateAlertContact(argv) {
904
- const creds = await getCredentials();
905
- await requireAdmin(creds);
906
- const msgBase = await getMsgBase(argv);
907
-
908
- if (!argv.id) {
909
- console.error('Contact id is required. Example: velaro logs contacts update 1 --phone +1...');
910
- process.exit(1);
911
- }
912
-
913
- const listRes = await fetch(`${msgBase}/superadmin/log-alerts/contacts`, {
914
- headers: { Authorization: `Bearer ${creds.velaroToken}`, 'X-Internal-SiteId': String(creds.siteId) },
915
- signal: AbortSignal.timeout(15000),
916
- });
917
- if (!listRes.ok) {
918
- console.error(`HTTP ${listRes.status}: ${await listRes.text().catch(() => '')}`);
919
- process.exit(1);
920
- }
921
- const contacts = await listRes.json().catch(() => []);
922
- const target = Array.isArray(contacts) ? contacts.find(c => String(c.id) === String(argv.id)) : null;
923
- if (!target) {
924
- console.error(`No contact with id ${argv.id} found. Run 'velaro logs contacts list' to see current ids.`);
925
- process.exit(1);
926
- }
927
-
928
- const body = {
929
- ...target,
930
- displayName: argv.displayName ?? target.displayName,
931
- phoneNumber: argv.phone ?? target.phoneNumber,
932
- email: argv.email ?? target.email,
933
- isGlobalDefault: argv.global !== undefined ? argv.global : target.isGlobalDefault,
934
- };
935
-
936
- if (!argv.yes) {
937
- console.log(`\n${DIM}Current contact:${RESET}\n`);
938
- printAlertContact(target);
939
- console.log(`\n${DIM}About to update to (dry run — nothing sent yet):${RESET}\n`);
940
- printAlertContact(body);
941
- console.log(`\nRe-run with --yes to actually apply this update.\n`);
942
- return;
943
- }
944
-
945
- const res = await fetch(`${msgBase}/superadmin/log-alerts/contacts/${argv.id}`, {
946
- method: 'PUT',
947
- headers: {
948
- Authorization: `Bearer ${creds.velaroToken}`,
949
- 'X-Internal-SiteId': String(creds.siteId),
950
- 'Content-Type': 'application/json',
951
- },
952
- body: JSON.stringify(body),
953
- signal: AbortSignal.timeout(15000),
954
- });
955
- if (!res.ok) {
956
- console.error(`HTTP ${res.status}: ${await res.text().catch(() => '')}`);
957
- process.exit(1);
958
- }
959
- const data = await res.json();
960
- console.log(`\n${CYN}✓${RESET} Updated contact [${data.id}] "${data.name}"\n`);
961
- printAlertContact(data);
962
- console.log('');
963
- }
964
-
965
- async function removeAlertContact(argv) {
966
- const creds = await getCredentials();
967
- await requireAdmin(creds);
968
- const msgBase = await getMsgBase(argv);
969
-
970
- if (!argv.id) {
971
- console.error('Contact id is required. Example: velaro logs contacts remove 1');
972
- process.exit(1);
973
- }
974
-
975
- const listRes = await fetch(`${msgBase}/superadmin/log-alerts/contacts`, {
976
- headers: { Authorization: `Bearer ${creds.velaroToken}`, 'X-Internal-SiteId': String(creds.siteId) },
977
- signal: AbortSignal.timeout(15000),
978
- });
979
- let target = null;
980
- if (listRes.ok) {
981
- const contacts = await listRes.json().catch(() => []);
982
- target = Array.isArray(contacts) ? contacts.find(c => String(c.id) === String(argv.id)) : null;
983
- }
984
-
985
- if (target) {
986
- console.log(`\n${DIM}About to delete this contact:${RESET}\n`);
987
- printAlertContact(target);
988
- if (target.isGlobalDefault) {
989
- console.log(`${YEL}This is a global-default contact -- removing it stops it from covering any rule that leaves --emails/--sms blank.${RESET}`);
990
- }
991
- } else {
992
- console.log(`\n${YEL}Could not fetch contact ${argv.id} to preview it (it may already be gone) — proceeding on id alone.${RESET}`);
993
- }
994
-
995
- if (!argv.yes) {
996
- console.log(`\nRe-run with --yes to actually delete it.\n`);
997
- return;
998
- }
999
-
1000
- const res = await fetch(`${msgBase}/superadmin/log-alerts/contacts/${argv.id}`, {
1001
- method: 'DELETE',
1002
- headers: { Authorization: `Bearer ${creds.velaroToken}`, 'X-Internal-SiteId': String(creds.siteId) },
1003
- signal: AbortSignal.timeout(15000),
1004
- });
1005
- if (!res.ok) {
1006
- console.error(`HTTP ${res.status}: ${await res.text().catch(() => '')}`);
1007
- process.exit(1);
1008
- }
1009
- console.log(`\nDeleted contact ${argv.id}.\n`);
1010
- }
1011
-
1012
- // ── command export ────────────────────────────────────────────────────────────
1013
-
1014
- export const logsCommand = {
1015
- command: 'logs <subcommand>',
1016
- describe: 'Search and stream Velaro Logger (Velaro staff only)',
1017
- builder: yargs => yargs
1018
- .command({
1019
- command: 'search [query]',
1020
- describe: 'Search application logs',
1021
- builder: y => y
1022
- .positional('query', { describe: 'Text to search for (or regex with --regex)', type: 'string' })
1023
- .option('level', { describe: 'Filter by level: ERROR, WARN, INFO, DEBUG', type: 'string' })
1024
- .option('integration', { describe: 'Integration tag (HubSpot, NetSuite, [Skill], etc.)', type: 'string' })
1025
- .option('site', { describe: 'Filter by site ID', type: 'number' })
1026
- .option('source', { describe: 'App source (velaro-messaging-Staging, etc.)', type: 'string' })
1027
- .option('platform', { describe: 'Filter by platform: v10, v20, admin', type: 'string' })
1028
- .option('environment', { describe: 'Filter by environment: Production, Staging, Development', type: 'string' })
1029
- .option('correlationId', { describe: 'Exact correlation/trace ID filter', type: 'string' })
1030
- .option('last', { describe: 'Time window: 30m, 2h, 1d', default: '2h', type: 'string' })
1031
- .option('regex', { describe: 'Treat query as regex', boolean: true, default: false })
1032
- .option('logger', { describe: 'Logger-name substring (client side)', type: 'string' })
1033
- .option('from', { describe: 'ISO start time (overrides --last)', type: 'string' })
1034
- .option('to', { describe: 'ISO end time (default now)', type: 'string' })
1035
- .option('raw', { describe: 'Use the server q= search (can under-report; prints searchPath/scannedRows/truncated)', boolean: true, default: false })
1036
- .option('max-requests', { describe: 'Request budget for the complete read', default: 200, type: 'number' })
1037
- .option('max-seconds', { describe: 'Wall-clock budget for the complete read', default: 120, type: 'number' })
1038
- .option('take', { describe: 'Max lines to print (complete read) / server page size (--raw, max 500)', default: 50, type: 'number' })
1039
- .option('env', { describe: 'staging or prod', type: 'string' }),
1040
- handler: searchLogs,
1041
- })
1042
- .command({
1043
- command: 'tail',
1044
- describe: 'Stream new log entries in real-time via SSE',
1045
- builder: y => y
1046
- .option('level', { describe: 'Filter by level: ERROR, WARN, INFO, DEBUG', type: 'string' })
1047
- .option('integration', { describe: 'Integration tag', type: 'string' })
1048
- .option('site', { describe: 'Filter by site ID', type: 'number' })
1049
- .option('source', { describe: 'App source', type: 'string' })
1050
- .option('env', { describe: 'staging or prod', type: 'string' }),
1051
- handler: tailLogs,
1052
- })
1053
- .command({
1054
- command: 'digest-recipients',
1055
- describe: 'Show current log digest email recipients (Velaro staff only)',
1056
- builder: y => y
1057
- .option('env', { describe: 'staging or prod', type: 'string' }),
1058
- handler: getDigestRecipients,
1059
- })
1060
- .command({
1061
- command: 'set-digest-recipients',
1062
- describe: 'Update log digest email recipients (Velaro staff only)',
1063
- builder: y => y
1064
- .option('emails', { describe: 'Semicolon-separated email list, e.g. "noc@velaro.com;alex@velaro.com"', type: 'string', demandOption: true })
1065
- .option('env', { describe: 'staging or prod', type: 'string' }),
1066
- handler: setDigestRecipients,
1067
- })
1068
- .command({
1069
- command: 'diagnose',
1070
- describe: 'Run combined bot diagnostic: errors + [WF-PERF-SLOW] + [AI-PERF-SLOW] + [WF-AI-ROUTE]',
1071
- builder: y => y
1072
- .option('last', { describe: 'Time window: 30m, 1h, 2h, 1d', default: '1h', type: 'string' })
1073
- .option('env', { describe: 'staging or prod', type: 'string' }),
1074
- handler: diagnoseLogs,
1075
- })
1076
- .command({
1077
- command: 'alerts <subcommand>',
1078
- describe: 'Manage Velaro Logger alert rules (Velaro staff only)',
1079
- builder: y => y
1080
- .command({
1081
- command: 'list',
1082
- describe: 'List current alert rules',
1083
- builder: yy => yy.option('env', { describe: 'staging or prod', type: 'string' }),
1084
- handler: listAlertRules,
1085
- })
1086
- .command({
1087
- command: 'suggest',
1088
- describe: 'Preview an AI-suggested rule config from a plain-English description (does not create it)',
1089
- builder: yy => yy
1090
- .option('description', { describe: 'Plain-English description of what to alert on', type: 'string', demandOption: true })
1091
- .option('env', { describe: 'staging or prod', type: 'string' }),
1092
- handler: suggestAlertRule,
1093
- })
1094
- .command({
1095
- command: 'create',
1096
- describe: 'Create a new alert rule',
1097
- builder: yy => yy
1098
- .option('name', { describe: 'Rule name', type: 'string', demandOption: true })
1099
- .option('query', { describe: 'Message-contains text to match', type: 'string', demandOption: true })
1100
- .option('level', { describe: 'ERROR, WARN, INFO, or DEBUG', type: 'string' })
1101
- .option('integration', { describe: 'Integration tag to match', type: 'string' })
1102
- .option('window-minutes', { describe: 'Rolling window in minutes', type: 'number' })
1103
- .option('threshold', { describe: 'Fire when count >= this within the window', type: 'number' })
1104
- .option('cooldown-minutes', { describe: 'Minimum minutes between re-fires', type: 'number' })
1105
- .option('emails', { describe: 'Comma-separated notification email addresses. Leave blank to fall back to global-default contacts (see: velaro logs contacts list)', type: 'string' })
1106
- .option('sms', { describe: 'Comma-separated E.164 phone numbers for SMS. Leave blank to fall back to global-default contacts', type: 'string' })
1107
- .option('webhook', { describe: 'Custom webhook URL for a generic JSON POST on fire (Slack, PagerDuty, etc). NOT for Teams -- use --teams instead, which posts a properly formatted Adaptive Card through Velaro\'s existing Teams pipeline', type: 'string' })
1108
- .option('teams', { describe: 'Post fired/resolved notifications to the velaro-alerts-to-teams Teams channel', type: 'boolean' })
1109
- .option('exclude-contacts', { describe: 'Comma-separated global-default contact names to exclude from this rule (e.g. "andrea") -- only relevant when --emails/--sms are left blank', type: 'string' })
1110
- .option('emails', { describe: 'Comma-separated notification email addresses', type: 'string' })
1111
- .option('sms', { describe: 'Comma-separated E.164 phone numbers for SMS', type: 'string' })
1112
- .option('webhook', { describe: 'Webhook URL (Slack/Teams) to POST on fire', type: 'string' })
1113
- .option('teams', { describe: 'Also post to the Production/Staging Alerts Teams channel via the velaro-alerts-to-teams Logic App', type: 'boolean' })
1114
- .option('mobile-user-ids', { describe: 'Comma-separated Velaro workspace user IDs for mobile push', type: 'string' })
1115
- .option('no-recipients-ok', { describe: 'Allow creating a rule with zero notification channels (visible in Alert History only)', type: 'boolean', default: false })
1116
- .option('yes', { describe: 'Skip the dry-run preview and actually create the rule', type: 'boolean', default: false })
1117
- .option('env', { describe: 'staging or prod', type: 'string' }),
1118
- handler: createAlertRule,
1119
- })
1120
- .command({
1121
- command: 'update <id>',
1122
- describe: 'Change an existing alert rule (threshold, window, query, recipients, etc.) without touching code',
1123
- builder: yy => yy
1124
- .positional('id', { describe: 'Rule id (from: velaro logs alerts list)', type: 'number' })
1125
- .option('name', { describe: 'Rule name', type: 'string' })
1126
- .option('query', { describe: 'Message-contains text to match', type: 'string' })
1127
- .option('level', { describe: 'ERROR, WARN, INFO, or DEBUG', type: 'string' })
1128
- .option('integration', { describe: 'Integration tag to match', type: 'string' })
1129
- .option('window-minutes', { describe: 'Rolling window in minutes', type: 'number' })
1130
- .option('threshold', { describe: 'Fire when count >= this within the window', type: 'number' })
1131
- .option('cooldown-minutes', { describe: 'Minimum minutes between re-fires', type: 'number' })
1132
- .option('emails', { describe: 'Comma-separated notification email addresses. Leave blank to fall back to global-default contacts (see: velaro logs contacts list)', type: 'string' })
1133
- .option('sms', { describe: 'Comma-separated E.164 phone numbers for SMS. Leave blank to fall back to global-default contacts', type: 'string' })
1134
- .option('webhook', { describe: 'Custom webhook URL for a generic JSON POST on fire (Slack, PagerDuty, etc). NOT for Teams -- use --teams instead, which posts a properly formatted Adaptive Card through Velaro\'s existing Teams pipeline', type: 'string' })
1135
- .option('teams', { describe: 'Post fired/resolved notifications to the velaro-alerts-to-teams Teams channel', type: 'boolean' })
1136
- .option('exclude-contacts', { describe: 'Comma-separated global-default contact names to exclude from this rule (e.g. "andrea") -- only relevant when --emails/--sms are left blank', type: 'string' })
1137
- .option('emails', { describe: 'Comma-separated notification email addresses', type: 'string' })
1138
- .option('sms', { describe: 'Comma-separated E.164 phone numbers for SMS', type: 'string' })
1139
- .option('webhook', { describe: 'Webhook URL (Slack/Teams) to POST on fire', type: 'string' })
1140
- .option('teams', { describe: 'Also post to the Production/Staging Alerts Teams channel via the velaro-alerts-to-teams Logic App', type: 'boolean' })
1141
- .option('mobile-user-ids', { describe: 'Comma-separated Velaro workspace user IDs for mobile push', type: 'string' })
1142
- .option('enabled', { describe: 'Enable (true) or pause (false) the rule', type: 'boolean' })
1143
- .option('no-recipients-ok', { describe: 'Allow leaving the rule with zero notification channels', type: 'boolean', default: false })
1144
- .option('yes', { describe: 'Skip the dry-run preview and actually apply the update', type: 'boolean', default: false })
1145
- .option('env', { describe: 'staging or prod', type: 'string' }),
1146
- handler: updateAlertRule,
1147
- })
1148
- .command({
1149
- command: 'toggle <id>',
1150
- describe: 'Enable/pause an alert rule',
1151
- builder: yy => yy
1152
- .positional('id', { describe: 'Rule id', type: 'number' })
1153
- .option('env', { describe: 'staging or prod', type: 'string' }),
1154
- handler: toggleAlertRule,
1155
- })
1156
- .command({
1157
- command: 'delete <id>',
1158
- describe: 'Delete an alert rule',
1159
- builder: yy => yy
1160
- .positional('id', { describe: 'Rule id', type: 'number' })
1161
- .option('yes', { describe: 'Skip the confirmation preview and actually delete', type: 'boolean', default: false })
1162
- .option('env', { describe: 'staging or prod', type: 'string' }),
1163
- handler: deleteAlertRule,
1164
- })
1165
- .demandCommand(1, 'Specify a subcommand: list, suggest, create, update, toggle, or delete'),
1166
- })
1167
- .command({
1168
- command: 'contacts <subcommand>',
1169
- describe: 'Manage global-default notification contacts for alert rules (Velaro staff only)',
1170
- builder: y => y
1171
- .command({
1172
- command: 'list',
1173
- describe: 'List all alert contacts',
1174
- builder: yy => yy.option('env', { describe: 'staging or prod', type: 'string' }),
1175
- handler: listAlertContacts,
1176
- })
1177
- .command({
1178
- command: 'add',
1179
- describe: 'Add a new alert contact',
1180
- builder: yy => yy
1181
- .option('name', { describe: 'Short unique handle, e.g. "alex" -- used in --exclude-contacts', type: 'string', demandOption: true })
1182
- .option('display-name', { describe: 'Human-readable label, e.g. "Alex Bloom"', type: 'string' })
1183
- .option('phone', { describe: 'E.164 phone number for SMS, e.g. +14436295872', type: 'string' })
1184
- .option('email', { describe: 'Email address', type: 'string' })
1185
- .option('global', { describe: 'Include this contact in every rule that leaves --emails/--sms blank (the normal case)', type: 'boolean', default: true })
1186
- .option('yes', { describe: 'Skip the dry-run preview and actually create the contact', type: 'boolean', default: false })
1187
- .option('env', { describe: 'staging or prod', type: 'string' }),
1188
- handler: addAlertContact,
1189
- })
1190
- .command({
1191
- command: 'update <id>',
1192
- describe: 'Change an existing contact\'s phone/email/global-default flag',
1193
- builder: yy => yy
1194
- .positional('id', { describe: 'Contact id (from: velaro logs contacts list)', type: 'number' })
1195
- .option('display-name', { describe: 'Human-readable label', type: 'string' })
1196
- .option('phone', { describe: 'E.164 phone number for SMS', type: 'string' })
1197
- .option('email', { describe: 'Email address', type: 'string' })
1198
- .option('global', { describe: 'Include/exclude this contact from global defaults', type: 'boolean' })
1199
- .option('yes', { describe: 'Skip the dry-run preview and actually apply the update', type: 'boolean', default: false })
1200
- .option('env', { describe: 'staging or prod', type: 'string' }),
1201
- handler: updateAlertContact,
1202
- })
1203
- .command({
1204
- command: 'remove <id>',
1205
- describe: 'Delete an alert contact',
1206
- builder: yy => yy
1207
- .positional('id', { describe: 'Contact id', type: 'number' })
1208
- .option('yes', { describe: 'Skip the confirmation preview and actually delete', type: 'boolean', default: false })
1209
- .option('env', { describe: 'staging or prod', type: 'string' }),
1210
- handler: removeAlertContact,
1211
- })
1212
- .demandCommand(1, 'Specify a subcommand: list, add, update, or remove'),
1213
- })
1214
- .command({
1215
- command: 'product-family <subcommand>',
1216
- describe: 'Manage logger-prefix to product-family rules shown in the Product column (Velaro staff only)',
1217
- builder: y => y
1218
- .command({
1219
- command: 'list',
1220
- describe: 'List product family rules (platform rules, plus a site\'s rules with --site)',
1221
- builder: yy => yy
1222
- .option('site', { describe: 'Site id to include site-scoped rules for', type: 'number' })
1223
- .option('env', { describe: 'staging or prod', type: 'string' }),
1224
- handler: listProductFamilies,
1225
- })
1226
- .command({
1227
- command: 'set <loggerPrefix> <productFamily>',
1228
- describe: 'Create or update a rule: loggers starting with <loggerPrefix> belong to <productFamily>',
1229
- builder: yy => yy
1230
- .positional('loggerPrefix', { describe: 'Logger name prefix, e.g. Velaro.Messaging.Ivr', type: 'string' })
1231
- .positional('productFamily', { describe: 'Product family label, e.g. IVR', type: 'string' })
1232
- .option('site', { describe: 'Scope the rule to one site (default: all sites)', type: 'number' })
1233
- .option('env', { describe: 'staging or prod', type: 'string' }),
1234
- handler: setProductFamily,
1235
- })
1236
- .command({
1237
- command: 'delete <id>',
1238
- describe: 'Delete a rule by id (from: velaro logs product-family list)',
1239
- builder: yy => yy
1240
- .positional('id', { describe: 'Rule id', type: 'number' })
1241
- .option('env', { describe: 'staging or prod', type: 'string' }),
1242
- handler: deleteProductFamily,
1243
- })
1244
- .demandCommand(1, 'Specify a subcommand: list, set, or delete'),
1245
- })
1246
- .command(logsInsightsCommand)
1247
- .demandCommand(1, 'Specify a subcommand: search, tail, diagnose, digest-recipients, set-digest-recipients, alerts, contacts, product-family, or insights'),
1248
- };