@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
@@ -4,20 +4,21 @@ import { get, post, del, messagingGet, messagingPost, messagingDel } from '../a
4
4
  import { requireFeature } from '../subscription.js';
5
5
  import { runCommand } from '../run.js';
6
6
  import { articleCommand } from './article.js';
7
+ import { loadStaff } from '../staff-optional.js';
8
+
9
+ const staffKb = await loadStaff('commands/kb-staff.js');
7
10
 
8
11
  export const kbCommand = {
9
12
  command: 'kb <subcommand>',
10
13
  describe: 'Manage knowledge base — articles, Q&A pairs, bot overrides, and custom content',
11
14
  builder: (yargs) =>
12
- yargs
15
+ (staffKb ? staffKb.addKbStaffCommands(yargs) : yargs)
13
16
  .command(articleCommand)
14
17
  .command(qnaCommand)
15
18
  .command(overrideCommand)
16
19
  .command(contentCommand)
17
- .command(reindexCommand)
18
20
  .command(settingsCommand)
19
21
  .command(statusCommand)
20
- .command(swapConnectionCommand)
21
22
  .command(tenantCommand)
22
23
  .demandCommand(1, 'Specify a subcommand: article, qna, override, content, reindex, settings, status, swap-connection, tenant'),
23
24
  handler: () => {},
@@ -65,77 +66,6 @@ const tenantCommand = {
65
66
  handler: () => {},
66
67
  };
67
68
 
68
- // ────────────────────────────────────────────────────────────────────────────
69
- // Reindex — re-embed all KB articles with the current embedding model
70
- // ────────────────────────────────────────────────────────────────────────────
71
-
72
- const reindexCommand = {
73
- command: 'reindex',
74
- describe: 'Re-embed KB articles or scraper/ingestion content (use after embedding model upgrade)',
75
- builder: (y) =>
76
- y
77
- .option('all', {
78
- type: 'boolean',
79
- describe: 'Reindex ALL sites (Velaro staff only)',
80
- default: false,
81
- })
82
- .option('site', {
83
- type: 'number',
84
- describe: 'Reindex a specific site by ID (Velaro staff only)',
85
- })
86
- .option('ingestion', {
87
- type: 'boolean',
88
- describe: 'Reindex scraper/ingestion Azure Search indexers instead of KB articles',
89
- default: false,
90
- }),
91
- handler: runCommand(async (argv) => {
92
- if (argv.ingestion) {
93
- if (argv.all) {
94
- console.log('Starting bulk ingestion reindex for all sites — runs in background.');
95
- console.log('Watch server logs ([ReindexAllIngestion]) for progress.\n');
96
- const result = await post('/DatabaseTool/ReindexAllIngestionIndexes', {});
97
- console.log(result.message ?? 'Queued.');
98
- } else if (argv.site) {
99
- console.log(`Reindexing scraper/ingestion index for site ${argv.site}…`);
100
- const result = await post(`/DatabaseTool/ReindexIngestionIndex/${argv.site}`, {});
101
- if (result.success) {
102
- console.log(`✅ Triggered ${result.indexersRun} indexer(s) — re-processing in background.`);
103
- } else {
104
- console.error(`❌ Failed: ${result.message}`);
105
- }
106
- } else {
107
- console.error('--ingestion requires --site <id> or --all (Velaro staff only)');
108
- process.exit(1);
109
- }
110
- } else if (argv.all) {
111
- console.log('Starting bulk KB reindex for all sites — this runs in the background.');
112
- console.log('Watch server logs ([ReindexAllKb]) for progress.\n');
113
- const result = await post('/DatabaseTool/ReindexAllKb', {});
114
- console.log(result.message ?? 'Queued.');
115
- } else if (argv.site) {
116
- console.log(`Reindexing KB articles for site ${argv.site}…`);
117
- const result = await messagingPost(`/Scraper/superadmin/kb/reindex/${argv.site}`, {});
118
- if (result?.queued) {
119
- console.log(`✅ Queued — full re-ingest running in background for site ${argv.site}.`);
120
- } else {
121
- console.error(`❌ Failed: ${result?.error ?? 'unknown error'}`);
122
- }
123
- } else {
124
- console.log("Reindexing your site's KB articles\u2026");
125
- // KBSearchIndexController is routed api/kb/search (the old /KBSearchIndex/reindex 404'd).
126
- const result = await post('/api/kb/search/reindex', {});
127
- if (result.success === false) {
128
- console.error(`❌ Failed: ${result.message}`);
129
- } else {
130
- console.log(`✅ Done — ${result.articles ?? result.count ?? 'all'} articles reindexed.`);
131
- }
132
- }
133
- }),
134
- };
135
-
136
- // ────────────────────────────────────────────────────────────────────────────
137
- // Status — which physical DB this environment's KB is actually connected to
138
- // ────────────────────────────────────────────────────────────────────────────
139
69
 
140
70
  const statusCommand = {
141
71
  command: 'status',
@@ -146,26 +76,6 @@ const statusCommand = {
146
76
  }),
147
77
  };
148
78
 
149
- const swapConnectionCommand = {
150
- command: 'swap-connection',
151
- describe: 'Toggle which physical database this environment\'s KB is connected to (primary vs. alternate, per KBConnectionHolder). Built 2026-08-18 after staging was found silently connected to PRODUCTION\'s KB database (KnowledgeBaseConnectionString, not _Staging) with no CLI/API way to check or fix it except a raw REST call.',
152
- builder: (y) =>
153
- y
154
- .option('use-alternate', { type: 'boolean', demandOption: true, describe: 'true = use the alternate (KnowledgeBaseConnectionString_Staging) DB; false = use primary' })
155
- .option('yes', { type: 'boolean', default: false, describe: 'Skip the confirmation prompt (for scripting)' }),
156
- handler: runCommand(async (argv) => {
157
- const before = await get('/api/kb/status');
158
- console.log(`Currently connected to: ${before.server} / ${before.database} (alternate: ${before.isAlternate})`);
159
-
160
- if (!argv.yes) {
161
- console.log(`\nAbout to switch to ${argv['use-alternate'] ? 'ALTERNATE' : 'PRIMARY'}. Re-run with --yes to confirm.`);
162
- return;
163
- }
164
-
165
- const result = await post('/DatabaseTool/KBSwapConnection', { useAlternate: argv['use-alternate'] });
166
- console.log(`✅ Switched. Now connected to: ${result.current.server} / ${result.current.database} (alternate: ${result.current.isAlternate})`);
167
- }),
168
- };
169
79
 
170
80
  // ────────────────────────────────────────────────────────────────────────────
171
81
  // Settings — branding, domain, layout, SEO/analytics
@@ -64,7 +64,7 @@ const clinicalGet = {
64
64
  command: 'get',
65
65
  describe: 'Show emergency/safety wording, supported languages and emergency-service mode',
66
66
  builder: (y) => y
67
- .option('site', { type: 'number', describe: 'Target site ID (Velaro staff only; omit for your own site)' })
67
+ .option('site', { type: 'number', describe: 'Target site ID (restricted, enforced server-side; omit for your own site)' })
68
68
  .option('json', { type: 'boolean', default: false }),
69
69
  handler: runCommand(async (argv) => {
70
70
  const state = await messagingGet(`${basePath(argv.site)}/state`);
@@ -79,7 +79,7 @@ const clinicalSet = {
79
79
  command: 'set',
80
80
  describe: 'Set emergency/safety wording. Entries replace the stored set: pass every override you want to keep (use get --json).',
81
81
  builder: (y) => y
82
- .option('site', { type: 'number', describe: 'Target site ID (Velaro staff only)' })
82
+ .option('site', { type: 'number', describe: 'Target site ID (restricted, enforced server-side)' })
83
83
  .option('emergency', { type: 'array', string: true, describe: 'key=text, key is default|chat|voice|sms|whatsapp|email|<lang>|<lang>.<channel>; must contain {emergencyNumber}' })
84
84
  .option('referral', { type: 'array', string: true, describe: 'key=text, same keys as --emergency' })
85
85
  .option('emergency-number', { type: 'string', describe: 'Replaces {emergencyNumber}' })
@@ -104,19 +104,6 @@ export const conversionCommand = { command: 'conversion', ...group('Conversion g
104
104
  async (a) => show(await get(`/Conversions/report?days=${a.days ?? 30}`))],
105
105
  ]) };
106
106
 
107
- export const emailCommand = { command: 'email', ...group('Velaro staff: email delivery queue and stats', [
108
- ['queue-status', 'Email delivery queue status', (y) => y.option('site-id', { type: 'number' }),
109
- async (a) => show(await messagingGet(`/SuperAdmin/email-delivery/status${qs({ siteId: a['site-id'] })}`))],
110
- ['delivery-stats', 'Email delivery stats', (y) => y.option('site-id', { type: 'number' }).option('days', { type: 'number' }).option('hours', { type: 'number' }),
111
- async (a) => show(await messagingGet(`/SuperAdmin/email-delivery/stats${qs({ siteId: a['site-id'], days: a.days, hours: a.hours })}`))],
112
- ['queue-replay', 'Replay stuck emails (dry run unless --apply --yes)',
113
- (y) => y.option('apply', { type: 'boolean', describe: 'Actually replay (default is a dry run)' }).option('yes', { type: 'boolean' }),
114
- async (a) => {
115
- if (a.apply) needYes(a, 'replay the email queue');
116
- show(await messagingPost(`/SuperAdmin/email-delivery/replay?dryRun=${a.apply ? 'false' : 'true'}`));
117
- }],
118
- ]) };
119
-
120
107
  export const ivrCommand = { command: 'ivr', ...group('IVR voice configurations, phone lines and business hours', [
121
108
  ['list-voice-configs', 'List IVR voice configurations', null, async () => show(await get('/IVRVoiceConfigurations'))],
122
109
  ['get-voice-config <id>', 'Show one voice configuration', (y) => y.positional('id', { type: 'number' }),
@@ -82,7 +82,7 @@ async function applyChange(a, enabled) {
82
82
  return last;
83
83
  }
84
84
 
85
- const siteOpt = { type: 'number', describe: 'Velaro staff only: target site ID (uses the staff route)' };
85
+ const siteOpt = { type: 'number', describe: 'restricted, enforced server-side: target site ID (uses the staff route)' };
86
86
  const controlOpt = { type: 'string', demandOption: true, describe: 'emergency_self_harm | abuse_ladder | threat_detection | input_jailbreak | output_filter' };
87
87
  const audienceOpt = { type: 'string', choices: [...AUDIENCES, 'both'], default: 'both' };
88
88
  const featureOpt = { type: 'string', describe: 'Per-feature/channel scope (chat, voice, sms, whatsapp, email). Omit for the whole account.' };
@@ -4,7 +4,7 @@
4
4
  * velaro salesforce diagnose --site-id <id> [--quick] Live read-only diagnostic: config, auth, per-capability probes
5
5
  * velaro salesforce matrix --site-id <id> Capability matrix vs live probes (same data as diagnose)
6
6
  *
7
- * Calls messaging DiagController GET /diagnostics/test-salesforce?siteId=<id>&deep=<bool> (Velaro staff only). Read-only:
7
+ * Calls messaging DiagController GET /diagnostics/test-salesforce?siteId=<id>&deep=<bool> (restricted, enforced server-side). Read-only:
8
8
  * nothing is created or changed in Salesforce, and a write capability is never reported as verified.
9
9
  */
10
10
 
@@ -4,7 +4,7 @@
4
4
  * velaro sap diagnose --site-id <id> [--quick] Live read-only diagnostic: config, auth, per-capability probes
5
5
  * velaro sap matrix --site-id <id> Capability matrix vs live probes (same data as diagnose)
6
6
  *
7
- * Calls messaging DiagController GET /diagnostics/test-sap?siteId=<id>&deep=<bool> (Velaro staff only). Read-only:
7
+ * Calls messaging DiagController GET /diagnostics/test-sap?siteId=<id>&deep=<bool> (restricted, enforced server-side). Read-only:
8
8
  * nothing is created or changed in SAP, and a write capability is never reported as verified.
9
9
  */
10
10
 
@@ -4,7 +4,7 @@ import { runCommand } from '../run.js';
4
4
  // -- velaro schedule-adherence --------------------------------------------------
5
5
  // Staff-only. siteId is an EXPLICIT argument (SupportTools-style), never derived from the caller.
6
6
  // Backend: velaro-messaging GET /Reports/sites/{siteId}/schedule-adherence-diagnostics
7
- // (IsSuperAdminAsync allowSupport gate; role=agent requires agentId, fails closed).
7
+ // (server-side staff gate; role=agent requires agentId, fails closed).
8
8
 
9
9
  export const scheduleAdherenceCommand = {
10
10
  command: 'schedule-adherence <siteId>',
@@ -103,7 +103,7 @@ export const teamsCommand = {
103
103
  )
104
104
  .command(
105
105
  'send-direct <user> <title>',
106
- 'Send a 1:1 Teams message to any user in the tenant (UPN or Entra id). Velaro staff only.',
106
+ 'Send a 1:1 Teams message to any user in the tenant (UPN or Entra id). restricted, enforced server-side.',
107
107
  (y) =>
108
108
  y
109
109
  .positional('user', { type: 'string', describe: 'alex@velaro.com or Entra object id' })
@@ -87,7 +87,7 @@ async function skillsHandler(argv) {
87
87
  const wooSkills = skills.filter(s => s.category === 'WooCommerce');
88
88
  if (wooSkills.length === 0) {
89
89
  console.log(`\n${YLW}No WooCommerce skills available for this site.${RST}`);
90
- console.log(`${DIM}Enable in SuperAdmin → Subscription: EnableWooCommerce (core/read), EnableWooCommerceWrite (write tier), EnableDestructiveAiSkills (cancel/refund/coupon).${RST}\n`);
90
+ console.log(`${DIM}Enable in the site Subscription settings (staff) → Subscription: EnableWooCommerce (core/read), EnableWooCommerceWrite (write tier), EnableDestructiveAiSkills (cancel/refund/coupon).${RST}\n`);
91
91
  return;
92
92
  }
93
93
  console.log(`\n${BOLD}${wooSkills.length} WooCommerce AI skill(s)${RST}\n`);
@@ -3,12 +3,15 @@ import { getCredentials, messagingGet, messagingPost, messagingPut, messagingDel
3
3
  import { requireFeature } from '../subscription.js';
4
4
  import { runCommand } from '../run.js';
5
5
  import { applyFollowUpOptions } from '../ai-followups.js';
6
+ import { loadStaff } from '../staff-optional.js';
7
+
8
+ const staffWorkflow = await loadStaff('commands/workflow-staff.js');
6
9
 
7
10
  export const workflowCommand = {
8
11
  command: 'workflow <subcommand>',
9
12
  describe: 'Manage automation workflows',
10
13
  builder: (yargs) =>
11
- yargs
14
+ (staffWorkflow ? staffWorkflow.addWorkflowStaffCommands(yargs) : yargs)
12
15
  .command(workflowListCommand)
13
16
  .command(workflowGetCommand)
14
17
  .command(workflowCreateCommand)
@@ -16,7 +19,6 @@ export const workflowCommand = {
16
19
  .command(workflowDisableCommand)
17
20
  .command(workflowRunCommand)
18
21
  .command(workflowNodeOptionsCommand)
19
- .command(workflowIntegrityScanCommand)
20
22
  .command(workflowAiFollowupsCommand)
21
23
  .command(workflowScheduleCommand)
22
24
  .command(siteAiFollowupsCommand)
@@ -331,35 +333,6 @@ const siteAiFollowupsCommand = {
331
333
  }),
332
334
  };
333
335
 
334
- // ── integrity-scan (Velaro staff only) ──────────────────────────────────────────
335
-
336
- const workflowIntegrityScanCommand = {
337
- command: 'integrity-scan <siteId>',
338
- describe: 'Scan every workflow on a site for NodesBlob that fails to parse (Velaro staff only)',
339
- builder: (y) => y.positional('siteId', { type: 'number', describe: 'Site ID to scan' }),
340
- handler: runCommand(async (argv) => {
341
- const creds = await getCredentials();
342
- if (creds.siteId !== 1032) {
343
- console.error('velaro workflow integrity-scan is only available to Velaro staff.');
344
- process.exit(1);
345
- }
346
-
347
- const results = await messagingGet(`/SuperAdmin/workflows/integrity-scan?siteId=${argv.siteId}`);
348
-
349
- if (!results?.length) {
350
- console.log(`\nSite ${argv.siteId}: no corrupted workflows found.\n`);
351
- return;
352
- }
353
-
354
- console.log(`\nSite ${argv.siteId}: ${results.length} corrupted workflow(s):\n`);
355
- for (const r of results) {
356
- console.log(` [${r.id}] ${r.name}`);
357
- console.log(` Last modified: ${r.lastModified}`);
358
- console.log(` Error: ${r.error}\n`);
359
- }
360
- }),
361
- };
362
-
363
336
  // ── schedule (workflow schedule priority; messaging owns /Workflows/schedule/*) ──────────────
364
337
  // Mirrors the velaro MCP tools workflow_schedule_resolve / _timeline / _validate / _banner / _override_save / _override_list / _override_delete.
365
338
  // An older messaging answers 404/501: print "not available" instead of failing.
@@ -0,0 +1,10 @@
1
+ // Staff-only subcommands live in cli/staff (NOT published in the public npm package). A customer command that has a
2
+ // staff-only subcommand loads it through this helper and gets null when the staff folder is absent.
3
+ export async function loadStaff(rel) {
4
+ try {
5
+ return await import(new URL(`../staff/${rel}`, import.meta.url).href);
6
+ } catch (e) {
7
+ if (e?.code === 'ERR_MODULE_NOT_FOUND' && /[\\/]staff[\\/]/.test(String(e.message))) return null;
8
+ throw e;
9
+ }
10
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@velaro/cli",
3
- "version": "1.4.120",
3
+ "version": "1.4.121",
4
4
  "description": "Velaro Workspace v20 — command-line interface for managing bots, knowledge base ingestion, MCP API keys, search indexes, and ops health.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -8,7 +8,7 @@
8
8
  },
9
9
  "scripts": {
10
10
  "postinstall": "node scripts/postinstall.js",
11
- "test": "node --test lib/*.test.js"
11
+ "test": "node --test lib/*.test.js staff/tests/*.test.js"
12
12
  },
13
13
  "engines": {
14
14
  "node": ">=18.0.0"
@@ -1,90 +0,0 @@
1
- // Pure helpers for `velaro cobrowse ...` (kept free of I/O so they are unit-testable).
2
- //
3
- // The platform API (messaging: GET/PUT superadmin/sites/{siteId}/cobrowse...) has REPLACE semantics: every setting
4
- // that is not sent goes back to the platform default. For a CLI that is a footgun, so `set` first reads the current
5
- // raw settings and only overwrites what the operator named on the command line.
6
-
7
- export const TRI_FIELDS = [
8
- ['cues', 'cuesEnabled'],
9
- ['formFill', 'formFillEnabled'],
10
- ['strictMask', 'strictMaskMode'],
11
- ['disableMobile', 'disableOnMobile'],
12
- ];
13
-
14
- /** "on" / "off" / "default" (also true/false) -> true / false / null. Throws on anything else. */
15
- export function parseTri(value, flag) {
16
- if (value === undefined) return undefined;
17
- const v = String(value).trim().toLowerCase();
18
- if (['on', 'true', 'yes', '1'].includes(v)) return true;
19
- if (['off', 'false', 'no', '0'].includes(v)) return false;
20
- if (['default', 'inherit', 'null', ''].includes(v)) return null;
21
- throw new Error(`--${flag} must be on, off or default (got "${value}")`);
22
- }
23
-
24
- function parseIntOrDefault(value, flag) {
25
- if (value === undefined) return undefined;
26
- const v = String(value).trim().toLowerCase();
27
- if (v === 'default' || v === '') return null;
28
- const n = Number(v);
29
- if (!Number.isInteger(n)) throw new Error(`--${flag} must be a whole number of minutes or "default" (got "${value}")`);
30
- return n;
31
- }
32
-
33
- function parseTextOrDefault(value) {
34
- if (value === undefined) return undefined;
35
- return String(value).trim().toLowerCase() === 'default' ? null : String(value);
36
- }
37
-
38
- /**
39
- * Merge operator flags over the site's current raw settings. Returns the full request body to PUT.
40
- * Protected pages: "default" -> platform list, "none" -> no protected pages, otherwise a newline/comma list.
41
- */
42
- export function buildCobrowseUpdate(current, args) {
43
- const body = { ...(current ?? {}) };
44
- delete body.updatedAt;
45
-
46
- for (const [flag, field] of TRI_FIELDS) {
47
- const v = parseTri(args[flag], flag);
48
- if (v !== undefined) body[field] = v;
49
- }
50
-
51
- if (args.protectedPages !== undefined) {
52
- const raw = String(args.protectedPages).trim();
53
- const lower = raw.toLowerCase();
54
- body.blockedUrlPatterns = lower === 'default' ? null : lower === 'none' ? '' : raw.split(/[\n,]/).map(s => s.trim()).filter(Boolean).join('\n');
55
- }
56
-
57
- const max = parseIntOrDefault(args.maxMinutes, 'max-minutes');
58
- if (max !== undefined) body.maxSessionMinutes = max;
59
- const idle = parseIntOrDefault(args.idleMinutes, 'idle-minutes');
60
- if (idle !== undefined) body.idleStopMinutes = idle;
61
-
62
- const title = parseTextOrDefault(args.consentTitle);
63
- if (title !== undefined) body.consentTitle = title;
64
- const message = parseTextOrDefault(args.consentMessage);
65
- if (message !== undefined) body.consentMessage = message;
66
- const allow = parseTextOrDefault(args.consentAllow);
67
- if (allow !== undefined) body.consentAllowLabel = allow;
68
-
69
- const teams = parseTextOrDefault(args.teams);
70
- if (teams !== undefined) body.allowedTeamIds = teams === 'none' ? null : teams;
71
- const roles = parseTextOrDefault(args.roles);
72
- if (roles !== undefined) body.allowedRoles = roles === 'none' ? null : roles;
73
-
74
- return body;
75
- }
76
-
77
- export function describeEffective(e) {
78
- if (!e) return [];
79
- return [
80
- ['Agent cues', e.cuesEnabled ? 'on' : 'off'],
81
- ['Guided form fill', e.formFillEnabled ? 'on' : 'off'],
82
- ['Strict mask mode', e.strictMask ? 'on' : 'off'],
83
- ['Off on mobile', e.disableOnMobile ? 'yes' : 'no'],
84
- ['Protected pages', (e.blockedUrlPatterns ?? []).length ? e.blockedUrlPatterns.join(' ') : 'none'],
85
- ['Max session / idle stop', `${e.maxSessionMinutes} min / ${e.idleStopMinutes} min`],
86
- ['Who can start', (e.allowedTeamIds ?? []).length || (e.allowedRoles ?? []).length
87
- ? `teams [${(e.allowedTeamIds ?? []).join(', ')}] roles [${(e.allowedRoles ?? []).join(', ')}]`
88
- : 'everyone with a seat'],
89
- ];
90
- }
@@ -1,45 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { buildCobrowseUpdate, parseTri, describeEffective } from './cobrowse-settings.js';
4
-
5
- test('parseTri maps on/off/default and rejects anything else', () => {
6
- assert.equal(parseTri('on', 'cues'), true);
7
- assert.equal(parseTri('OFF', 'cues'), false);
8
- assert.equal(parseTri('default', 'cues'), null);
9
- assert.equal(parseTri(undefined, 'cues'), undefined);
10
- assert.throws(() => parseTri('maybe', 'cues'), /--cues must be on, off or default/);
11
- });
12
-
13
- test('set only changes the flags named; everything else is preserved (the API itself replaces)', () => {
14
- const current = { cuesEnabled: true, strictMaskMode: true, maxSessionMinutes: 30, blockedUrlPatterns: '/a\n/b', updatedAt: '2026-10-15T00:00:00Z' };
15
- const body = buildCobrowseUpdate(current, { formFill: 'on', maxMinutes: '60' });
16
- assert.deepEqual(body, { cuesEnabled: true, strictMaskMode: true, maxSessionMinutes: 60, blockedUrlPatterns: '/a\n/b', formFillEnabled: true });
17
- });
18
-
19
- test('default clears a setting back to the platform default', () => {
20
- const body = buildCobrowseUpdate({ cuesEnabled: false, maxSessionMinutes: 30 }, { cues: 'default', maxMinutes: 'default' });
21
- assert.equal(body.cuesEnabled, null);
22
- assert.equal(body.maxSessionMinutes, null);
23
- });
24
-
25
- test('protected pages: default / none / explicit list', () => {
26
- assert.equal(buildCobrowseUpdate({}, { protectedPages: 'default' }).blockedUrlPatterns, null);
27
- assert.equal(buildCobrowseUpdate({}, { protectedPages: 'none' }).blockedUrlPatterns, '');
28
- assert.equal(buildCobrowseUpdate({}, { protectedPages: '/checkout, /portal/pay ' }).blockedUrlPatterns, '/checkout\n/portal/pay');
29
- });
30
-
31
- test('teams and roles accept "none"', () => {
32
- const body = buildCobrowseUpdate({ allowedTeamIds: '1,2', allowedRoles: 'Manager' }, { teams: 'none', roles: 'Agent' });
33
- assert.equal(body.allowedTeamIds, null);
34
- assert.equal(body.allowedRoles, 'Agent');
35
- });
36
-
37
- test('non-integer minutes are rejected before anything is sent', () => {
38
- assert.throws(() => buildCobrowseUpdate({}, { maxMinutes: 'soon' }), /whole number/);
39
- });
40
-
41
- test('describeEffective renders a readable summary', () => {
42
- const rows = describeEffective({ cuesEnabled: true, formFillEnabled: false, strictMask: false, disableOnMobile: false, blockedUrlPatterns: ['/checkout'], maxSessionMinutes: 120, idleStopMinutes: 15, allowedTeamIds: [], allowedRoles: [] });
43
- assert.ok(rows.some(([k, v]) => k === 'Protected pages' && v === '/checkout'));
44
- assert.ok(rows.some(([k, v]) => k === 'Who can start' && v === 'everyone with a seat'));
45
- });
@@ -1,147 +0,0 @@
1
- import { get, getCredentials, messagingGet } from '../api.js';
2
-
3
- // ── helpers ──────────────────────────────────────────────────────────────────
4
-
5
- const RESET = '\x1b[0m';
6
- const DIM = '\x1b[2m';
7
- const RED = '\x1b[31m';
8
- const YEL = '\x1b[33m';
9
- const CYN = '\x1b[36m';
10
-
11
- function formatEntry(item) {
12
- const ts = new Date(item.createdAt).toISOString().replace('T', ' ').slice(0, 19);
13
- const sev = (item.severity ?? 'Info').padEnd(8);
14
- const color = item.severity === 'Error' ? RED : item.severity === 'Warning' ? YEL : RESET;
15
- const cat = `${DIM}[${item.category ?? '?'}]${RESET}`;
16
- const int = item.integration ? `${CYN}${item.integration}${RESET} ` : '';
17
- const lines = [`${DIM}${ts}${RESET} ${color}${sev}${RESET} ${int}${cat} ${item.message ?? ''}`];
18
- if (item.additionalInfo) lines.push(` ${DIM}${item.additionalInfo}${RESET}`);
19
- if (item.suppressedCount > 0) lines.push(` ${DIM}(+${item.suppressedCount} suppressed)${RESET}`);
20
- return lines.join('\n');
21
- }
22
-
23
- function formatAuditEntry(e) {
24
- const ts = new Date(e.createdAt).toISOString().replace('T', ' ').slice(0, 19);
25
- const actor = e.actorType === 'AI_Moshky'
26
- ? `${CYN}Moshky${RESET} (on behalf of ${e.initiatedByEmail ?? 'unknown'})`
27
- : `${e.actorType === 'HumanStaff' ? YEL : RESET}${e.actorType}${RESET} ${e.actorEmail ?? ''}`.trim();
28
- const lines = [`${DIM}${ts}${RESET} [${e.entityType}#${e.entityId}] ${e.action} ${DIM}by${RESET} ${actor}`];
29
- if (e.oldValueJson) lines.push(` ${DIM}before:${RESET} ${e.oldValueJson}`);
30
- if (e.newValueJson) lines.push(` ${DIM}after: ${RESET} ${e.newValueJson}`);
31
- return lines.join('\n');
32
- }
33
-
34
- // ── audit-trail handler (distinct shape/endpoint from integration activity logs) ───
35
-
36
- async function auditTrailHandler(argv) {
37
- await getCredentials();
38
-
39
- const params = new URLSearchParams();
40
- if (argv.entityType) params.set('entityType', argv.entityType);
41
- if (argv.entityId) params.set('entityId', argv.entityId);
42
- params.set('take', String(Math.min(500, argv.take ?? 200)));
43
-
44
- const qs = params.toString();
45
- const data = await get(`/AuditTrail${qs ? '?' + qs : ''}`);
46
-
47
- if (!data?.entries?.length) {
48
- console.log('\nNo audit trail entries.');
49
- return;
50
- }
51
-
52
- console.log(`\n${data.entries.length} audit trail entries`);
53
- if (!data.fullDetailAvailable) {
54
- console.log(`${DIM}${data.complianceUpsellMessage ?? 'Upgrade to a Compliance package for full before/after detail.'}${RESET}`);
55
- }
56
- console.log('');
57
-
58
- for (const e of data.entries) console.log(formatAuditEntry(e));
59
- console.log('');
60
- }
61
-
62
- // ── integration activity handler ────────────────────────────────────────────────
63
-
64
- async function activityHandler(argv) {
65
- await getCredentials(); // ensure logged in
66
-
67
- if (argv.slug === 'audit-trail') return auditTrailHandler(argv);
68
-
69
- // 'skills' is a convenience alias for AI tool logs
70
- const isSkills = argv.slug === 'skills';
71
- let path;
72
- if (isSkills) {
73
- path = '/Integration/Logs';
74
- argv.category = 'AiTool';
75
- } else if (argv.slug) {
76
- path = `/Integration/Logs/${encodeURIComponent(argv.slug)}`;
77
- } else {
78
- path = '/Integration/Logs';
79
- }
80
-
81
- const params = new URLSearchParams();
82
- if (argv.severity && argv.severity !== 'All') params.set('severity', argv.severity);
83
- if (argv.category && argv.category !== 'All') params.set('category', argv.category);
84
- if (argv.search) params.set('search', argv.search);
85
- params.set('page', String(Math.max(1, argv.page ?? 1)));
86
- params.set('pageSize', String(Math.min(100, argv.pageSize ?? 25)));
87
-
88
- const qs = params.toString();
89
- let data;
90
- if (argv.site) {
91
- // Staff: read ANOTHER site's Activity Log (customer/test site) without logging in as it.
92
- const sp = new URLSearchParams();
93
- if (isSkills) sp.set('slug', 'AiTool');
94
- else if (argv.slug) sp.set('slug', argv.slug);
95
- if (argv.severity && argv.severity !== 'All') sp.set('severity', argv.severity);
96
- if (argv.search) sp.set('search', argv.search);
97
- sp.set('take', String(Math.min(200, argv.pageSize ?? 25)));
98
- const r = await messagingGet(`/SupportTools/sites/${argv.site}/integration-logs?${sp.toString()}`);
99
- data = { items: r?.items ?? [], total: r?.count ?? 0 };
100
- } else {
101
- data = await get(`${path}${qs ? '?' + qs : ''}`);
102
- }
103
-
104
- if (!data?.items?.length) {
105
- console.log('\nNo activity log entries.');
106
- return;
107
- }
108
-
109
- const label = isSkills ? 'AI skill calls' : argv.slug ? `${argv.slug} activity` : 'integration activity';
110
- console.log(`\n${data.items.length} of ${data.total} ${label} entries\n`);
111
-
112
- for (const item of data.items) console.log(formatEntry(item));
113
-
114
- if (data.total > data.page * data.pageSize) {
115
- console.log(`\n${DIM}More results — use --page ${data.page + 1}${RESET}`);
116
- }
117
-
118
- console.log('');
119
- }
120
-
121
- // ── command export ────────────────────────────────────────────────────────────
122
-
123
- export const activityCommand = {
124
- command: 'activity [slug]',
125
- describe: 'View integration activity logs, or "audit-trail" for who-changed-what settings history',
126
- builder: y => y
127
- .positional('slug', {
128
- describe: 'Integration name (HubSpot, Square…), "skills" for AI tool logs, or "audit-trail" for settings change history',
129
- type: 'string',
130
- })
131
- .option('severity', {
132
- describe: 'Info, Warning, Error',
133
- type: 'string',
134
- })
135
- .option('category', {
136
- describe: 'Auth, Config, Request, Response, AiTool, Setup, Error',
137
- type: 'string',
138
- })
139
- .option('search', { describe: 'Message search', type: 'string' })
140
- .option('site', { describe: "Staff only: read this site's Activity Log instead of your own", type: 'number' })
141
- .option('page', { describe: 'Page number', default: 1, type: 'number' })
142
- .option('pageSize', { describe: 'Results per page', default: 25, type: 'number' })
143
- .option('entityType', { describe: '[audit-trail] Filter to one entity type, e.g. Workflow', type: 'string' })
144
- .option('entityId', { describe: '[audit-trail] Filter to one specific entity', type: 'string' })
145
- .option('take', { describe: '[audit-trail] Max results (default 200, max 500)', type: 'number' }),
146
- handler: activityHandler,
147
- };