@velaro/cli 1.4.131 → 1.4.133

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/velaro.js CHANGED
@@ -13,6 +13,7 @@ import { indexMoveCommand } from '../lib/commands/index-move.js';
13
13
  import { safetyCommand } from '../lib/commands/safety.js';
14
14
  import { knowledgeAdvisorCommand } from '../lib/commands/knowledge-advisor.js';
15
15
  import { productMatchCommand } from '../lib/commands/product-match.js';
16
+ import { partFinderCommand } from '../lib/commands/part-finder.js';
16
17
  import { knowledgeCommand } from '../lib/commands/knowledge.js';
17
18
  import { productCommand } from '../lib/commands/product.js';
18
19
  import { mcpKeyCommand } from '../lib/commands/mcp-key.js';
@@ -160,6 +161,7 @@ await (registerStaffCommands ? registerStaffCommands(baseYargs) : baseYargs)
160
161
  .command(safetyCommand)
161
162
  .command(knowledgeAdvisorCommand)
162
163
  .command(productMatchCommand)
164
+ .command(partFinderCommand)
163
165
  .command(knowledgeCommand)
164
166
  .command(productCommand)
165
167
  .command(mcpKeyCommand)
@@ -73,6 +73,16 @@ ${RED}✗ Connection failed: ${e.message}${RST}
73
73
  }
74
74
  }
75
75
 
76
+ // The search endpoints need the Magento config id (configId) and the search text (query).
77
+ // Resolve the active store from /Magento/Configs; --config-id overrides it.
78
+ async function resolveConfigId(argv) {
79
+ if (argv.configId) return argv.configId;
80
+ const stores = await request('GET', '/Magento/Configs');
81
+ const active = (Array.isArray(stores) ? stores : []).find((s) => s.isActive);
82
+ if (!active) throw new Error('No active Magento store connected for this site.');
83
+ return active.id;
84
+ }
85
+
76
86
  // ── customers ─────────────────────────────────────────────────────────────────
77
87
 
78
88
  async function customersHandler(argv) {
@@ -81,7 +91,8 @@ async function customersHandler(argv) {
81
91
  process.exitCode = 1;
82
92
  return;
83
93
  }
84
- const r = await request('GET', `/Magento/Customers/Search?q=${encodeURIComponent(argv.email)}`);
94
+ const configId = await resolveConfigId(argv);
95
+ const r = await request('GET', `/Magento/Customers/Search?configId=${configId}&query=${encodeURIComponent(argv.email)}`);
85
96
  if (!r || !r.id) {
86
97
  console.log(`\nNo customer found for ${argv.email}.\n`);
87
98
  return;
@@ -104,7 +115,8 @@ async function ordersHandler(argv) {
104
115
  }
105
116
  const q = argv.id ?? argv.email;
106
117
  const limit = Math.min(50, argv.limit ?? 10);
107
- const orders = await request('GET', `/Magento/Orders/Search?q=${encodeURIComponent(q)}&limit=${limit}`);
118
+ const configId = await resolveConfigId(argv);
119
+ const orders = await request('GET', `/Magento/Orders/Search?configId=${configId}&query=${encodeURIComponent(q)}&limit=${limit}`);
108
120
  if (!Array.isArray(orders) || orders.length === 0) {
109
121
  console.log(`\nNo orders found for "${q}".\n`);
110
122
  return;
@@ -129,7 +141,8 @@ async function productsHandler(argv) {
129
141
  return;
130
142
  }
131
143
  const limit = Math.min(50, argv.limit ?? 10);
132
- const products = await request('GET', `/Magento/Products/Search?q=${encodeURIComponent(argv.query)}&limit=${limit}`);
144
+ const configId = await resolveConfigId(argv);
145
+ const products = await request('GET', `/Magento/Products/Search?configId=${configId}&query=${encodeURIComponent(argv.query)}&limit=${limit}`);
133
146
  if (!Array.isArray(products) || products.length === 0) {
134
147
  console.log(`\nNo products found for "${argv.query}".\n`);
135
148
  return;
@@ -0,0 +1,151 @@
1
+ // velaro part-finder - the per-site Part Finder: one ordered lookup (cross-reference matrix, business system, own catalog, spec search, hand-off).
2
+ //
3
+ // velaro part-finder find "<part, model or description>" Run the same lookup the bot uses (shows the trace)
4
+ // velaro part-finder config get Show the order, time limits, confidence and no-result action
5
+ // velaro part-finder config set [--enabled true|false] [--order matrix,erp,catalog_exact,spec_search] [--disable erp,...]
6
+ // [--min-confidence 0.8] [--no-result handoff|categories|handoff_and_categories|capture_lead]
7
+ // velaro part-finder sources list|add|sync|preview|remove Matrix sources (SharePoint, OneDrive); preview shows the diff, nothing applied
8
+ // velaro part-finder misses [--dismiss <id>] What customers asked that found nothing
9
+ // velaro part-finder suggestions list|generate|approve <id>|reject <id>
10
+ //
11
+ // Calls messaging /PartFinder endpoints. Site scope comes from the signed-in identity. Needs the Part Finder package (EnablePartFinder);
12
+ // without it the server answers 403 / not enabled.
13
+ import { messagingGet, messagingPost, messagingPut, messagingDel } from '../api.js';
14
+ import { runCommand } from '../run.js';
15
+
16
+ export const STEP_IDS = ['matrix', 'erp', 'catalog_exact', 'spec_search'];
17
+ export const NO_RESULT_ACTIONS = ['handoff', 'categories', 'handoff_and_categories', 'capture_lead'];
18
+
19
+ export function parseList(text) {
20
+ return String(text ?? '').split(/[,\s;]+/).map((t) => t.trim()).filter(Boolean);
21
+ }
22
+
23
+ /** Build the PUT /PartFinder/Config body from the current config and the flags. Pure, so it is unit tested. */
24
+ export function buildConfigPatch(current, flags) {
25
+ const patch = {};
26
+ let steps = (current?.steps ?? []).map((s) => ({ ...s }));
27
+ if (flags.order !== undefined) {
28
+ const order = parseList(flags.order);
29
+ for (const id of order) if (!STEP_IDS.includes(id)) throw new Error(`Unknown step "${id}". Steps: ${STEP_IDS.join(', ')}`);
30
+ if (new Set(order).size !== order.length) throw new Error('A step can only appear once in --order.');
31
+ const byId = new Map(steps.map((s) => [s.id, s]));
32
+ const named = order.map((id) => byId.get(id) ?? { id, enabled: true, timeoutMs: 1000 });
33
+ const rest = steps.filter((s) => !order.includes(s.id));
34
+ steps = [...named, ...rest];
35
+ }
36
+ if (flags.disable !== undefined || flags.enable !== undefined) {
37
+ const off = parseList(flags.disable);
38
+ const on = parseList(flags.enable);
39
+ for (const id of [...off, ...on]) if (!STEP_IDS.includes(id)) throw new Error(`Unknown step "${id}". Steps: ${STEP_IDS.join(', ')}`);
40
+ steps = steps.map((s) => (off.includes(s.id) ? { ...s, enabled: false } : on.includes(s.id) ? { ...s, enabled: true } : s));
41
+ }
42
+ if (flags.order !== undefined || flags.disable !== undefined || flags.enable !== undefined) {
43
+ const isOn = (id) => steps.some((s) => s.id === id && s.enabled);
44
+ if (!isOn('matrix') && !isOn('catalog_exact')) throw new Error('Keep at least one of matrix or catalog_exact switched on.');
45
+ patch.steps = steps;
46
+ }
47
+ if (flags['min-confidence'] !== undefined) {
48
+ const v = Number(flags['min-confidence']);
49
+ if (!Number.isFinite(v) || v < 0 || v > 1) throw new Error('--min-confidence must be between 0 and 1.');
50
+ patch.minConfidence = v;
51
+ }
52
+ if (flags['no-result'] !== undefined) {
53
+ if (!NO_RESULT_ACTIONS.includes(flags['no-result'])) throw new Error(`--no-result must be one of ${NO_RESULT_ACTIONS.join(', ')}.`);
54
+ patch.noResultAction = flags['no-result'];
55
+ }
56
+ if (flags.enabled !== undefined) patch.enabled = String(flags.enabled) === 'true';
57
+ if (Object.keys(patch).length === 0) throw new Error('Nothing to change. Pass at least one flag.');
58
+ return patch;
59
+ }
60
+
61
+ export function listOf(r, ...keys) {
62
+ if (Array.isArray(r)) return r;
63
+ for (const k of keys) if (Array.isArray(r?.[k])) return r[k];
64
+ return [];
65
+ }
66
+
67
+ export function describeFind(d) {
68
+ const lines = [`Status: ${d.status} source: ${d.source}${d.handoff ? ' (hand off to a person)' : ''}`];
69
+ for (const m of d.recommendations ?? []) lines.push(` ${m.sku} ${m.name ?? ''} [${m.matchType ?? ''}]`);
70
+ for (const m of d.candidates ?? []) lines.push(` possible: ${m.sku} ${m.name ?? ''}`);
71
+ for (const t of d.trace ?? []) lines.push(` trace: ${t.step} -> ${t.outcome} (${t.ms} ms)`);
72
+ return lines.join('\n');
73
+ }
74
+
75
+ const J = { type: 'boolean', describe: 'print raw JSON' };
76
+
77
+ export const partFinderCommand = {
78
+ command: 'part-finder',
79
+ describe: 'Part Finder: find the right part from a photo, a part number or a competitor model, in the order you choose',
80
+ builder: (yargs) => yargs
81
+ .command('find <query>', 'Run the lookup the bot uses', (y) => y.positional('query', { type: 'string' }).option('json', J),
82
+ runCommand(async (a) => {
83
+ const r = await messagingPost('/PartFinder/Find', { query: a.query });
84
+ if (a.json) { console.log(JSON.stringify(r, null, 2)); return; }
85
+ console.log(describeFind(r));
86
+ }))
87
+ .command('config <action>', 'get or set the order, confidence and no-result action', (y) => y
88
+ .positional('action', { choices: ['get', 'set'] })
89
+ .option('enabled', { type: 'string' })
90
+ .option('order', { type: 'string', describe: 'comma separated step ids, first to last' })
91
+ .option('disable', { type: 'string' })
92
+ .option('enable', { type: 'string' })
93
+ .option('min-confidence', { type: 'string' })
94
+ .option('no-result', { type: 'string' })
95
+ .option('json', J),
96
+ runCommand(async (a) => {
97
+ let r = await messagingGet('/PartFinder/Config');
98
+ if (a.action === 'set') r = await messagingPut('/PartFinder/Config', buildConfigPatch(r, a));
99
+ if (a.json) { console.log(JSON.stringify(r, null, 2)); return; }
100
+ console.log(`Part Finder: ${r.enabled ? 'on' : 'off'} min confidence ${r.minConfidence} no result: ${r.noResultAction}`);
101
+ (r.steps ?? []).forEach((s, i) => console.log(` ${i + 1}. ${s.id} ${s.enabled ? 'on' : 'off'} ${s.timeoutMs} ms`));
102
+ }))
103
+ .command('sources <action> [id]', 'list, add, sync, preview or remove matrix sources', (y) => y
104
+ .positional('action', { choices: ['list', 'add', 'sync', 'preview', 'remove'] })
105
+ .positional('id', { type: 'number' })
106
+ .option('type', { type: 'string', default: 'sharepoint', describe: 'sharepoint or onedrive (add)' })
107
+ .option('file', { type: 'string', describe: 'file name or link (add)' })
108
+ .option('load-mode', { type: 'string', default: 'preload', describe: 'preload or live (add)' })
109
+ .option('json', J),
110
+ runCommand(async (a) => {
111
+ let r;
112
+ if (a.action === 'list') r = await messagingGet('/PartFinder/Sources');
113
+ else if (a.action === 'add') {
114
+ if (!a.file) throw new Error('--file is required for add.');
115
+ r = await messagingPost('/PartFinder/Sources', { type: a.type, fileName: a.file, loadMode: a['load-mode'], enabled: true });
116
+ } else {
117
+ if (!a.id) throw new Error(`An id is required for ${a.action}.`);
118
+ if (a.action === 'remove') { await messagingDel(`/PartFinder/Sources/${a.id}`); console.log(`Removed source ${a.id}`); return; }
119
+ r = a.action === 'sync'
120
+ ? await messagingPost(`/PartFinder/Sources/${a.id}/SyncNow`, {})
121
+ : await messagingGet(`/PartFinder/Sources/${a.id}/Preview`);
122
+ }
123
+ if (a.json || a.action !== 'list') { console.log(JSON.stringify(r, null, 2)); return; }
124
+ for (const s of listOf(r, 'sources', 'items')) console.log(` #${s.id} ${s.type} ${s.fileName ?? ''} ${s.loadMode ?? ''} last sync ${s.lastSyncAt ?? 'never'} ${s.lastSyncStatus ?? ''}`);
125
+ }))
126
+ .command('misses', 'List what customers asked that found nothing', (y) => y
127
+ .option('dismiss', { type: 'number', describe: 'dismiss one miss by id' }).option('json', J),
128
+ runCommand(async (a) => {
129
+ if (a.dismiss) { await messagingPost(`/PartFinder/Misses/${a.dismiss}/Dismiss`, {}); console.log(`Dismissed miss ${a.dismiss}`); return; }
130
+ const r = await messagingGet('/PartFinder/Misses');
131
+ if (a.json) { console.log(JSON.stringify(r, null, 2)); return; }
132
+ for (const m of listOf(r, 'misses', 'items')) console.log(` #${m.id} x${m.count ?? 1} ${m.sampleText ?? ''}`);
133
+ }))
134
+ .command('suggestions <action> [id]', 'list, generate, approve or reject AI-suggested matches (people approve, nothing is recommended before)', (y) => y
135
+ .positional('action', { choices: ['list', 'generate', 'approve', 'reject'] })
136
+ .positional('id', { type: 'number' })
137
+ .option('json', J),
138
+ runCommand(async (a) => {
139
+ let r;
140
+ if (a.action === 'list') r = await messagingGet('/PartFinder/Suggestions');
141
+ else if (a.action === 'generate') r = await messagingPost('/PartFinder/Suggestions/Generate', {});
142
+ else {
143
+ if (!a.id) throw new Error(`An id is required for ${a.action}.`);
144
+ r = await messagingPost(`/PartFinder/Suggestions/${a.id}/${a.action === 'approve' ? 'Approve' : 'Reject'}`, {});
145
+ }
146
+ if (a.json || a.action !== 'list') { console.log(JSON.stringify(r, null, 2)); return; }
147
+ for (const s of listOf(r, 'suggestions', 'items', 'entries')) console.log(` #${s.id} ${s.source} -> ${s.target} [${s.matchType ?? ''}]`);
148
+ }))
149
+ .demandCommand(1),
150
+ handler: () => {},
151
+ };
@@ -0,0 +1,95 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { buildConfigPatch, describeFind, listOf, parseList } from './commands/part-finder.js';
4
+ import { tools, handlers } from '../../mcp/parity/part-finder.customer.js';
5
+
6
+ const current = () => ({
7
+ enabled: true,
8
+ steps: [
9
+ { id: 'matrix', enabled: true, timeoutMs: 500 },
10
+ { id: 'erp', enabled: true, timeoutMs: 3000 },
11
+ { id: 'catalog_exact', enabled: true, timeoutMs: 500 },
12
+ { id: 'spec_search', enabled: true, timeoutMs: 4000 },
13
+ ],
14
+ minConfidence: 0.8,
15
+ noResultAction: 'handoff_and_categories',
16
+ });
17
+
18
+ test('parses step lists from commas, spaces and semicolons', () => {
19
+ assert.deepEqual(parseList('matrix, erp;catalog_exact spec_search'), ['matrix', 'erp', 'catalog_exact', 'spec_search']);
20
+ assert.deepEqual(parseList(undefined), []);
21
+ });
22
+
23
+ test('reorders steps and keeps the time limits of each', () => {
24
+ const p = buildConfigPatch(current(), { order: 'catalog_exact,matrix' });
25
+ assert.deepEqual(p.steps.map((s) => s.id), ['catalog_exact', 'matrix', 'erp', 'spec_search']);
26
+ assert.equal(p.steps[1].timeoutMs, 500);
27
+ assert.equal(p.steps[2].timeoutMs, 3000);
28
+ });
29
+
30
+ test('rejects unknown steps, duplicates, and switching off both matrix and catalog_exact', () => {
31
+ assert.throws(() => buildConfigPatch(current(), { order: 'matrix,bogus' }), /Unknown step/);
32
+ assert.throws(() => buildConfigPatch(current(), { order: 'matrix,matrix' }), /only appear once/);
33
+ assert.throws(() => buildConfigPatch(current(), { disable: 'matrix,catalog_exact' }), /at least one/);
34
+ assert.doesNotThrow(() => buildConfigPatch(current(), { disable: 'matrix' }));
35
+ });
36
+
37
+ test('validates confidence and the no-result action, and refuses an empty change', () => {
38
+ assert.equal(buildConfigPatch(current(), { 'min-confidence': '0.9' }).minConfidence, 0.9);
39
+ assert.throws(() => buildConfigPatch(current(), { 'min-confidence': '2' }), /between 0 and 1/);
40
+ assert.equal(buildConfigPatch(current(), { 'no-result': 'capture_lead' }).noResultAction, 'capture_lead');
41
+ assert.throws(() => buildConfigPatch(current(), { 'no-result': 'shrug' }), /must be one of/);
42
+ assert.equal(buildConfigPatch(current(), { enabled: 'false' }).enabled, false);
43
+ assert.throws(() => buildConfigPatch(current(), {}), /Nothing to change/);
44
+ });
45
+
46
+ test('reads bare or wrapped lists and describes a find result with its trace', () => {
47
+ assert.deepEqual(listOf([1]), [1]);
48
+ assert.deepEqual(listOf({ items: [2] }, 'sources', 'items'), [2]);
49
+ assert.deepEqual(listOf(null, 'items'), []);
50
+ const text = describeFind({ status: 'no_result', source: 'none', handoff: true, trace: [{ step: 'matrix', outcome: 'miss', ms: 3 }] });
51
+ assert.match(text, /hand off to a person/);
52
+ assert.match(text, /trace: matrix -> miss \(3 ms\)/);
53
+ });
54
+
55
+ test('MCP parity: every tool has a handler, none takes a siteId, endpoints match the CLI', async () => {
56
+ for (const t of tools) {
57
+ assert.equal(typeof handlers[t.name], 'function');
58
+ assert.ok(t.name.startsWith('part_finder_'));
59
+ assert.ok(!Object.keys(t.inputSchema.properties ?? {}).includes('siteId'));
60
+ }
61
+ const calls = [];
62
+ const ctx = {
63
+ messagingGet: async (p) => { calls.push(['GET', p]); return {}; },
64
+ messagingPost: async (p, b) => { calls.push(['POST', p, b]); return {}; },
65
+ messagingPut: async (p, b) => { calls.push(['PUT', p, b]); return {}; },
66
+ messagingDel: async (p) => { calls.push(['DEL', p]); return {}; },
67
+ };
68
+ await handlers.part_finder_find({ query: 'AB-1' }, ctx);
69
+ await handlers.part_finder_config({}, ctx);
70
+ await handlers.part_finder_config({ minConfidence: 0.9 }, ctx);
71
+ await handlers.part_finder_sources({}, ctx);
72
+ await handlers.part_finder_source_preview({ id: 4 }, ctx);
73
+ await handlers.part_finder_source_sync({ id: 4 }, ctx);
74
+ await handlers.part_finder_source_remove({ id: 4 }, ctx);
75
+ await handlers.part_finder_misses({}, ctx);
76
+ await handlers.part_finder_suggestions_generate({}, ctx);
77
+ await handlers.part_finder_suggestion_decide({ id: 7 }, ctx);
78
+ await handlers.part_finder_suggestion_decide({ id: 7, approved: false }, ctx);
79
+ assert.deepEqual(calls.map((c) => c.slice(0, 2)), [
80
+ ['POST', '/PartFinder/Find'],
81
+ ['GET', '/PartFinder/Config'],
82
+ ['PUT', '/PartFinder/Config'],
83
+ ['GET', '/PartFinder/Sources'],
84
+ ['GET', '/PartFinder/Sources/4/Preview'],
85
+ ['POST', '/PartFinder/Sources/4/SyncNow'],
86
+ ['DEL', '/PartFinder/Sources/4'],
87
+ ['GET', '/PartFinder/Misses'],
88
+ ['POST', '/PartFinder/Suggestions/Generate'],
89
+ ['POST', '/PartFinder/Suggestions/7/Approve'],
90
+ ['POST', '/PartFinder/Suggestions/7/Reject'],
91
+ ]);
92
+ await assert.rejects(() => handlers.part_finder_find({}, ctx), /query is required/);
93
+ await assert.rejects(() => handlers.part_finder_source_sync({ id: 0 }, ctx), /positive integer/);
94
+ await assert.rejects(() => handlers.part_finder_config({ minConfidence: 3 }, ctx), /between 0 and 1/);
95
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@velaro/cli",
3
- "version": "1.4.131",
3
+ "version": "1.4.133",
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": {