@aivin-labs/cli 1.0.0 → 1.0.4
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/LICENSE +21 -0
- package/README.md +2 -0
- package/bin/cli.mjs +111 -6
- package/bin/lib/browserAutomation.mjs +138 -65
- package/bin/lib/browserTui.mjs +245 -0
- package/bin/lib/connectors.mjs +1 -0
- package/bin/lib/deploy.mjs +66 -8
- package/bin/lib/mcpProxy.mjs +476 -83
- package/bin/lib/missionStream.mjs +13 -9
- package/bin/lib/pluginTrigger.mjs +226 -13
- package/bin/lib/store.mjs +111 -11
- package/bin/lib/util.mjs +26 -0
- package/docs/CLI.md +220 -25
- package/package.json +5 -2
|
@@ -328,31 +328,35 @@ export function streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClien
|
|
|
328
328
|
const statusIcon = (status) =>
|
|
329
329
|
status === 'error' ? chalk.red('✗') : status === 'success' ? chalk.green('✓') : status === 'warning' ? chalk.yellow('!') : chalk.gray('·');
|
|
330
330
|
|
|
331
|
-
|
|
331
|
+
// `reason` lets the caller (browserAutomation.mjs's tunnel-retry loop) tell a genuine mission
|
|
332
|
+
// outcome ('success'/'failed'/'cancelled') apart from "we just gave up watching"
|
|
333
|
+
// ('idle'/'sigint'/'connect_error') - only the latter group is worth retrying on tunnel drop.
|
|
334
|
+
const stop = (reason) => {
|
|
332
335
|
if (settled) return;
|
|
333
336
|
settled = true;
|
|
334
337
|
clearTimeout(idleTimer);
|
|
335
338
|
socket.disconnect();
|
|
336
|
-
process.off('SIGINT',
|
|
339
|
+
process.off('SIGINT', onSigint);
|
|
337
340
|
// The auto-opened HIL viewer keeps a listening HTTP server alive (and with it the whole
|
|
338
341
|
// process) past the point the mission actually finished - close it along with everything else.
|
|
339
342
|
viewerServer?.close();
|
|
340
|
-
resolve();
|
|
343
|
+
resolve(reason);
|
|
341
344
|
};
|
|
342
345
|
|
|
343
346
|
const bumpIdleTimer = () => {
|
|
344
347
|
clearTimeout(idleTimer);
|
|
345
348
|
idleTimer = setTimeout(() => {
|
|
346
349
|
console.log(chalk.gray(`\n(no activity for ${Math.round(idleTimeoutMs / 1000)}s - stopped watching; the run may still be going in the background)`));
|
|
347
|
-
stop();
|
|
350
|
+
stop('idle');
|
|
348
351
|
}, idleTimeoutMs);
|
|
349
352
|
};
|
|
350
353
|
|
|
351
|
-
|
|
354
|
+
const onSigint = () => stop('sigint');
|
|
355
|
+
process.on('SIGINT', onSigint);
|
|
352
356
|
|
|
353
357
|
socket.on('connect_error', (error) => {
|
|
354
358
|
console.log(chalk.yellow(`⚠️ Couldn't watch live progress (${error.message}) - the run continues regardless.`));
|
|
355
|
-
stop();
|
|
359
|
+
stop('connect_error');
|
|
356
360
|
});
|
|
357
361
|
|
|
358
362
|
for (const eventName of MISSION_LOG_EVENTS) {
|
|
@@ -397,7 +401,7 @@ export function streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClien
|
|
|
397
401
|
if (payload.event_key === 'ai_browser.success' || payload.event_key === 'ai_browser.failed' || MISSION_DONE_EVENT_KEYS.has(payload.event_key)) {
|
|
398
402
|
const ok = payload.event_key !== 'ai_browser.failed' && payload.status !== 'error';
|
|
399
403
|
sendOSNotification(ok ? '✅ AI Browser hoàn tất' : '❌ AI Browser thất bại', payload.message || '');
|
|
400
|
-
stop();
|
|
404
|
+
stop(ok ? 'success' : 'failed');
|
|
401
405
|
}
|
|
402
406
|
});
|
|
403
407
|
}
|
|
@@ -409,7 +413,7 @@ export function streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClien
|
|
|
409
413
|
// even though the backend was emitting a full trace the whole time. `detail` (when present)
|
|
410
414
|
// carries the LLM's actual per-action reasoning (AIBrowserActionItem.reason), not just the
|
|
411
415
|
// truncated one-line summary meant for a chat bubble.
|
|
412
|
-
const STEP_ICON = { perceiving: '👁', executing: '▶', blocked: '🛡', recovering: '↺', auditing: '🔎', done: '✅', failed: '❌' };
|
|
416
|
+
const STEP_ICON = { planning: '📋', perceiving: '👁', executing: '▶', blocked: '🛡', recovering: '↺', auditing: '🔎', done: '✅', failed: '❌' };
|
|
413
417
|
socket.on('browser:agent-step', (payload) => {
|
|
414
418
|
if (!payload) return;
|
|
415
419
|
bumpIdleTimer();
|
|
@@ -434,7 +438,7 @@ export function streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClien
|
|
|
434
438
|
}
|
|
435
439
|
});
|
|
436
440
|
|
|
437
|
-
console.log(chalk.gray(`📡 Watching live progress for ${threadId}... (Ctrl+C to stop
|
|
441
|
+
console.log(chalk.gray(`📡 Watching live progress for ${threadId}... (Ctrl+C to stop and request cancellation)\n`));
|
|
438
442
|
bumpIdleTimer();
|
|
439
443
|
});
|
|
440
444
|
}
|
|
@@ -3,9 +3,13 @@ import chalk from 'chalk';
|
|
|
3
3
|
import fs from 'fs';
|
|
4
4
|
import path from 'path';
|
|
5
5
|
import axios from 'axios';
|
|
6
|
+
import inquirer from 'inquirer';
|
|
7
|
+
import { randomUUID } from 'crypto';
|
|
6
8
|
import { flattenManifestFile } from '@aivin-labs/sdk';
|
|
7
9
|
import readline from 'readline';
|
|
8
|
-
import { requireArg } from './util.mjs';
|
|
10
|
+
import { requireArg, withProgressSpinner } from './util.mjs';
|
|
11
|
+
|
|
12
|
+
const DELETE_TIMEOUT_MS = 30000;
|
|
9
13
|
|
|
10
14
|
/**
|
|
11
15
|
* Resolves which manifest entry `plugin trigger` should invoke: the `--func` match if given, the
|
|
@@ -70,6 +74,30 @@ export async function watchPluginLogLines(pluginId, { serverUrl, apiKey, onLine
|
|
|
70
74
|
return { subscribed, denyReason, stop: () => socket.disconnect() };
|
|
71
75
|
}
|
|
72
76
|
|
|
77
|
+
/**
|
|
78
|
+
* Realtime stage/percent progress for a single `trigger` call — mirrors `withScanLog`/
|
|
79
|
+
* `scanAndPublishMcp` (`mcpProxy.mjs`, used for `aivin mcp <url>`'s scan step): join the Socket.IO
|
|
80
|
+
* room BEFORE the caller sends its POST (so no early progress events are missed), then track the
|
|
81
|
+
* latest `plugin-execute-progress` payload for a spinner to poll. Useful for the same reason as
|
|
82
|
+
* `--watch-logs` — a cold-start Docker install can take 60-150s+ with zero feedback otherwise —
|
|
83
|
+
* but this is on by default (no flag needed) since it's cheap and doesn't require log-view
|
|
84
|
+
* permission the way `--watch-logs` does.
|
|
85
|
+
*/
|
|
86
|
+
async function withExecuteProgress(executeSessionId, { serverUrl, apiKey }) {
|
|
87
|
+
const socket = io(serverUrl, { auth: { token: apiKey || 'dev-token' }, transports: ['websocket'], reconnection: true, timeout: 8000 });
|
|
88
|
+
const room = `plugin-execute:${executeSessionId}`;
|
|
89
|
+
let current = { stage: 'starting', percent: 0, message: 'Đang gửi yêu cầu...' };
|
|
90
|
+
await new Promise((resolve) => {
|
|
91
|
+
const giveUp = setTimeout(resolve, 8000);
|
|
92
|
+
socket.on('connect_error', () => { clearTimeout(giveUp); resolve(); });
|
|
93
|
+
socket.on('connect', () => {
|
|
94
|
+
socket.emit('join-room', { name: 'plugin-execute', rooms: [room] }, () => { clearTimeout(giveUp); resolve(); });
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
socket.on('plugin-execute-progress', (payload) => { current = payload; });
|
|
98
|
+
return { getCurrent: () => current, stop: () => socket.disconnect() };
|
|
99
|
+
}
|
|
100
|
+
|
|
73
101
|
/**
|
|
74
102
|
* `aivin plugin trigger` - invokes an already-deployed plugin for real via the same
|
|
75
103
|
* `POST /plugins/execute` the platform's own Playground uses (PluginExecutionService.executePlugin
|
|
@@ -204,17 +232,22 @@ export async function triggerPlugin(mission, inputJson, options) {
|
|
|
204
232
|
}
|
|
205
233
|
}
|
|
206
234
|
|
|
207
|
-
|
|
235
|
+
const executeSessionId = randomUUID();
|
|
236
|
+
body.execute_session_id = executeSessionId;
|
|
237
|
+
const progress = await withExecuteProgress(executeSessionId, { serverUrl, apiKey });
|
|
208
238
|
|
|
209
239
|
let response;
|
|
210
240
|
try {
|
|
211
|
-
response = await
|
|
241
|
+
response = await withProgressSpinner(`🚀 Triggering ${entryLabel || entryId}`, progress.getCurrent, () =>
|
|
242
|
+
axios.post(`${serverUrl}/plugins/execute`, body, { ...authHeaders, timeout: EXECUTE_TIMEOUT_MS }),
|
|
243
|
+
);
|
|
212
244
|
} catch (error) {
|
|
213
245
|
if (logWatcher?.subscribed) {
|
|
214
246
|
// Give trailing log lines from this failed call a moment to arrive before disconnecting.
|
|
215
247
|
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
216
248
|
}
|
|
217
249
|
logWatcher?.stop();
|
|
250
|
+
progress.stop();
|
|
218
251
|
const message = error.response?.data?.message || error.message;
|
|
219
252
|
throw new Error(`Trigger failed: ${message}`, { cause: error });
|
|
220
253
|
}
|
|
@@ -223,6 +256,7 @@ export async function triggerPlugin(mission, inputJson, options) {
|
|
|
223
256
|
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
224
257
|
}
|
|
225
258
|
logWatcher?.stop();
|
|
259
|
+
progress.stop();
|
|
226
260
|
|
|
227
261
|
const result = response.data ?? {};
|
|
228
262
|
|
|
@@ -369,8 +403,11 @@ export async function searchPlugins(query, options) {
|
|
|
369
403
|
}
|
|
370
404
|
const authHeaders = { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
|
|
371
405
|
|
|
372
|
-
const params = {
|
|
406
|
+
const params = {};
|
|
407
|
+
if (query) params.query = query;
|
|
373
408
|
if (options.workspace) params.workspace_id = options.workspace;
|
|
409
|
+
if (options.mcp) params.mcp_server_id = options.mcp;
|
|
410
|
+
if (options.store) params.store_id = options.store;
|
|
374
411
|
if (options.limit) params.limit = options.limit;
|
|
375
412
|
|
|
376
413
|
let response;
|
|
@@ -385,20 +422,23 @@ export async function searchPlugins(query, options) {
|
|
|
385
422
|
// relevance-ranked lookup the platform's own agent uses to auto-select a plugin for a mission).
|
|
386
423
|
const data = response.data;
|
|
387
424
|
const results = Array.isArray(data) ? data : data?.items || [];
|
|
425
|
+
// --mcp is an exact-id lookup (no free-text query) - describe results by server id instead.
|
|
426
|
+
const describedAs = (options.mcp ? `MCP server "${options.mcp}"` : `"${query}"`)
|
|
427
|
+
+ (options.store ? ` in store "${options.store}"` : '');
|
|
388
428
|
|
|
389
429
|
if (results.length === 0) {
|
|
390
|
-
console.log(chalk.yellow(`No plugins found matching
|
|
430
|
+
console.log(chalk.yellow(`No plugins found matching ${describedAs}.`));
|
|
391
431
|
return;
|
|
392
432
|
}
|
|
393
433
|
|
|
394
434
|
// Interactive browser needs a real terminal to read raw keypresses - fall back to a flat
|
|
395
435
|
// print for scripts/CI or when the user explicitly asks for it with --plain.
|
|
396
436
|
if (process.stdout.isTTY && process.stdin.isTTY && !options.plain) {
|
|
397
|
-
await browseResults(results, `Found ${results.length} plugin(s) matching
|
|
437
|
+
await browseResults(results, `Found ${results.length} plugin(s) matching ${describedAs}:\n`, formatPluginListLine, formatPluginDetail);
|
|
398
438
|
return;
|
|
399
439
|
}
|
|
400
440
|
|
|
401
|
-
console.log(chalk.blue(`Found ${results.length} plugin(s) matching
|
|
441
|
+
console.log(chalk.blue(`Found ${results.length} plugin(s) matching ${describedAs}:\n`));
|
|
402
442
|
for (const plugin of results) {
|
|
403
443
|
console.log(chalk.bold(plugin.name || plugin.id) + chalk.gray(` (${plugin.id})`));
|
|
404
444
|
if (plugin.description) console.log(` ${plugin.description}`);
|
|
@@ -412,6 +452,109 @@ export async function searchPlugins(query, options) {
|
|
|
412
452
|
);
|
|
413
453
|
}
|
|
414
454
|
|
|
455
|
+
/**
|
|
456
|
+
* `aivin plugin info <id>` - detail view for one already-known plugin id, without going through
|
|
457
|
+
* `plugin search`'s free-text ranking first. Useful when debugging a specific plugin (e.g. one
|
|
458
|
+
* seen in `plugin search --mcp <server>`'s listing, or copied from the platform) and you just want
|
|
459
|
+
* its input/output schema and setup requirements again.
|
|
460
|
+
*
|
|
461
|
+
* There's no dedicated GET /plugins/:id on the backend, so this reuses /plugins/search with the id
|
|
462
|
+
* itself as the query and picks the exact `id` match out of the ranked results - the same lookup
|
|
463
|
+
* `plugin search` already does, just narrowed down for you. Falls back to showing the closest
|
|
464
|
+
* matches (with a clear "no exact match" note) if the id typo'd or the plugin isn't visible to you.
|
|
465
|
+
*/
|
|
466
|
+
export async function showPluginInfo(id, options) {
|
|
467
|
+
const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
|
|
468
|
+
const apiKey = process.env.API_KEY;
|
|
469
|
+
if (!apiKey) {
|
|
470
|
+
console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
|
|
471
|
+
}
|
|
472
|
+
const authHeaders = { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
|
|
473
|
+
|
|
474
|
+
const params = { query: id, limit: options.limit || 10 };
|
|
475
|
+
if (options.workspace) params.workspace_id = options.workspace;
|
|
476
|
+
|
|
477
|
+
let response;
|
|
478
|
+
try {
|
|
479
|
+
response = await axios.get(`${serverUrl}/plugins/search`, { ...authHeaders, params });
|
|
480
|
+
} catch (error) {
|
|
481
|
+
const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
|
|
482
|
+
throw new Error(`Lookup failed: ${message}`, { cause: error });
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
const data = response.data;
|
|
486
|
+
const results = Array.isArray(data) ? data : data?.items || [];
|
|
487
|
+
const exact = results.find((p) => p.id === id);
|
|
488
|
+
|
|
489
|
+
if (exact) {
|
|
490
|
+
console.log(formatPluginDetail(exact));
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
if (results.length === 0) {
|
|
495
|
+
console.log(chalk.yellow(`No plugin found for id "${id}".`));
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
console.log(chalk.yellow(`No exact match for "${id}" - closest result(s):\n`));
|
|
500
|
+
if (process.stdout.isTTY && process.stdin.isTTY && !options.plain) {
|
|
501
|
+
await browseResults(results, `Closest to "${id}":\n`, formatPluginListLine, formatPluginDetail);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
for (const plugin of results) {
|
|
505
|
+
console.log(chalk.bold(plugin.name || plugin.id) + chalk.gray(` (${plugin.id})`));
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* `aivin plugin ask "<mission>"` - the one-shot "just simulate the agent" mode: given a
|
|
511
|
+
* plain-language mission, it searches the plugin ecosystem the same relevance-ranked way the
|
|
512
|
+
* platform's own agent does to auto-select a plugin, picks the top match, and immediately triggers
|
|
513
|
+
* it with that same mission auto-mapped onto the input schema (`plugin trigger -a` under the hood).
|
|
514
|
+
* Where `plugin search` + `plugin trigger --id <id> -a "..."` is the two-step "pick, then run" flow,
|
|
515
|
+
* `ask` collapses both into what an agent actually does at execution time - no manual id copy/paste.
|
|
516
|
+
*
|
|
517
|
+
* `--top <n>` (default 5) controls how many candidates are fetched so the runner-up(s) can be
|
|
518
|
+
* printed for context/debugging when the auto-pick looks wrong; only the #1 match is ever run.
|
|
519
|
+
*/
|
|
520
|
+
export async function askPlugin(mission, options) {
|
|
521
|
+
mission = await requireArg(mission, { prompt: 'What do you want done?', usage: 'Usage: aivin plugin ask "<mission>"' });
|
|
522
|
+
|
|
523
|
+
const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
|
|
524
|
+
const apiKey = process.env.API_KEY;
|
|
525
|
+
if (!apiKey) {
|
|
526
|
+
console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
|
|
527
|
+
}
|
|
528
|
+
const authHeaders = { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
|
|
529
|
+
|
|
530
|
+
const params = { query: mission, limit: options.top || 5 };
|
|
531
|
+
if (options.workspace) params.workspace_id = options.workspace;
|
|
532
|
+
|
|
533
|
+
let response;
|
|
534
|
+
try {
|
|
535
|
+
response = await axios.get(`${serverUrl}/plugins/search`, { ...authHeaders, params });
|
|
536
|
+
} catch (error) {
|
|
537
|
+
const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
|
|
538
|
+
throw new Error(`Search failed: ${message}`, { cause: error });
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
const data = response.data;
|
|
542
|
+
const results = Array.isArray(data) ? data : data?.items || [];
|
|
543
|
+
if (results.length === 0) {
|
|
544
|
+
throw new Error(`No plugin matches "${mission}". Try \`aivin plugin search\` with different wording, or \`aivin plugin make\` to write one.`);
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
const chosen = results[0];
|
|
548
|
+
const matchLabel = typeof chosen._similarity === 'number' ? ` (${(chosen._similarity * 100).toFixed(0)}% match)` : '';
|
|
549
|
+
console.log(chalk.blue(`🤖 Auto-selected: ${chalk.bold(chosen.name || chosen.id)}${matchLabel}`) + chalk.gray(` (${chosen.id})`));
|
|
550
|
+
if (results.length > 1) {
|
|
551
|
+
console.log(chalk.gray(` runner-up(s): ${results.slice(1).map((p) => p.name || p.id).join(', ')}`));
|
|
552
|
+
}
|
|
553
|
+
console.log();
|
|
554
|
+
|
|
555
|
+
await triggerPlugin(mission, options.input, { ...options, auto: mission, id: chosen.id });
|
|
556
|
+
}
|
|
557
|
+
|
|
415
558
|
export function formatPluginListLine(plugin, isSelected) {
|
|
416
559
|
const marker = isSelected ? chalk.cyan('❯ ') : ' ';
|
|
417
560
|
const label = plugin.name || plugin.id;
|
|
@@ -462,8 +605,8 @@ export function formatPluginDetail(plugin) {
|
|
|
462
605
|
return lines.join('\n');
|
|
463
606
|
}
|
|
464
607
|
|
|
465
|
-
// Simple raw-keypress list/detail browser: ↑/↓ to move, space/enter to open an item's detail
|
|
466
|
-
// view, esc/backspace to go back to the listing, q/ctrl+c to exit. No extra deps - built on
|
|
608
|
+
// Simple raw-keypress list/detail browser: ↑/↓ to move, space/enter/→ to open an item's detail
|
|
609
|
+
// view, esc/backspace/← to go back to the listing, q/ctrl+c to exit. No extra deps - built on
|
|
467
610
|
// node's own readline keypress events since inquirer's prompts don't support this drill-down.
|
|
468
611
|
// Generic over what's being browsed (plugins, connectors, ...) via the format callbacks.
|
|
469
612
|
export function browseResults(results, headerText, formatLine, formatDetail) {
|
|
@@ -482,10 +625,10 @@ export function browseResults(results, headerText, formatLine, formatDetail) {
|
|
|
482
625
|
for (let i = 0; i < results.length; i++) {
|
|
483
626
|
console.log(formatLine(results[i], i === index));
|
|
484
627
|
}
|
|
485
|
-
console.log(chalk.gray('\n↑/↓ move space/enter view details q quit'));
|
|
628
|
+
console.log(chalk.gray('\n↑/↓ move →/space/enter view details q quit'));
|
|
486
629
|
} else {
|
|
487
630
|
console.log(formatDetail(results[index]));
|
|
488
|
-
console.log(chalk.gray('\
|
|
631
|
+
console.log(chalk.gray('\n←/esc/backspace back q quit'));
|
|
489
632
|
}
|
|
490
633
|
};
|
|
491
634
|
|
|
@@ -502,7 +645,7 @@ export function browseResults(results, headerText, formatLine, formatDetail) {
|
|
|
502
645
|
} else if (key.name === 'down') {
|
|
503
646
|
index = (index + 1) % results.length;
|
|
504
647
|
render();
|
|
505
|
-
} else if (key.name === 'return' || key.name === 'space' || str === ' ') {
|
|
648
|
+
} else if (key.name === 'return' || key.name === 'space' || key.name === 'right' || str === ' ') {
|
|
506
649
|
mode = 'detail';
|
|
507
650
|
render();
|
|
508
651
|
} else if (key.name === 'q' || key.name === 'escape') {
|
|
@@ -510,7 +653,7 @@ export function browseResults(results, headerText, formatLine, formatDetail) {
|
|
|
510
653
|
resolve();
|
|
511
654
|
}
|
|
512
655
|
} else {
|
|
513
|
-
if (key.name === 'escape' || key.name === 'backspace') {
|
|
656
|
+
if (key.name === 'escape' || key.name === 'backspace' || key.name === 'left') {
|
|
514
657
|
mode = 'list';
|
|
515
658
|
render();
|
|
516
659
|
} else if (key.name === 'q') {
|
|
@@ -533,3 +676,73 @@ export function browseResults(results, headerText, formatLine, formatDetail) {
|
|
|
533
676
|
render();
|
|
534
677
|
});
|
|
535
678
|
}
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* `aivin plugin delete <id>` / `aivin plugin delete --group <groupId>` - the CLI-side counterpart
|
|
682
|
+
* that had been missing: everything else in this file (`create`/`trigger`/`deploy`) had no way to
|
|
683
|
+
* undo itself. Two backend endpoints, both ownership-checked server-side (404, not 403, for a
|
|
684
|
+
* plugin/group that isn't yours - avoids leaking which ids exist in other orgs):
|
|
685
|
+
* - `DELETE /plugins/store/:pluginId` - one plugin.
|
|
686
|
+
* - `DELETE /plugins/group/:groupId` - every plugin sharing one `group_id`, i.e. everything a
|
|
687
|
+
* single batch deploy created in one call - the backend's own controller comment says this
|
|
688
|
+
* exists specifically "để CLI dùng group_id trả về từ batch deploy để rollback cả lô" (so the
|
|
689
|
+
* CLI can use the group_id a batch deploy returns to roll back the whole batch), which is
|
|
690
|
+
* exactly `aivin mcp <url>`'s "N plugin(s) generated from this MCP server" case - it already
|
|
691
|
+
* prints that group_id after deploy, this is what it's for.
|
|
692
|
+
*
|
|
693
|
+
* Both prompt a confirmation (skippable with `-y`/`--yes` for scripts) since neither can be undone
|
|
694
|
+
* from here - `--group` additionally requires typing the id back, same pattern `pluginstore rm`
|
|
695
|
+
* uses, since it can delete many plugins at once from one typo'd id.
|
|
696
|
+
*/
|
|
697
|
+
export async function deletePluginCmd(id, options) {
|
|
698
|
+
const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
|
|
699
|
+
const apiKey = process.env.API_KEY;
|
|
700
|
+
if (!apiKey) {
|
|
701
|
+
console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
|
|
702
|
+
}
|
|
703
|
+
const authHeaders = { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
|
|
704
|
+
|
|
705
|
+
if (options.group) {
|
|
706
|
+
if (!options.yes) {
|
|
707
|
+
const { confirmId } = await inquirer.prompt([
|
|
708
|
+
{
|
|
709
|
+
type: 'input',
|
|
710
|
+
name: 'confirmId',
|
|
711
|
+
message: chalk.red(`This deletes EVERY plugin in group "${options.group}" - can't be undone. Type the group id to confirm:`),
|
|
712
|
+
},
|
|
713
|
+
]);
|
|
714
|
+
if (confirmId !== options.group) {
|
|
715
|
+
console.log(chalk.gray('Cancelled - group id did not match.'));
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
try {
|
|
720
|
+
const res = await axios.delete(`${serverUrl}/plugins/group/${encodeURIComponent(options.group)}`, { ...authHeaders, timeout: DELETE_TIMEOUT_MS });
|
|
721
|
+
console.log(chalk.green(`✅ Deleted ${res.data?.deleted_count ?? '?'} plugin(s) from group "${options.group}".`));
|
|
722
|
+
} catch (error) {
|
|
723
|
+
const message = error.response?.data?.message || error.message;
|
|
724
|
+
const hint = [401, 403].includes(error.response?.status) ? ' - this may need a `full_access`-scoped API key (see `aivin key gen`), not just a logged-in session' : '';
|
|
725
|
+
throw new Error(`Group delete failed: ${message}${hint}`, { cause: error });
|
|
726
|
+
}
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
id = await requireArg(id, { prompt: 'Plugin id to delete:', usage: 'Usage: aivin plugin delete <id> (or: aivin plugin delete --group <groupId>)' });
|
|
731
|
+
|
|
732
|
+
if (!options.yes) {
|
|
733
|
+
const { confirmDelete } = await inquirer.prompt([
|
|
734
|
+
{ type: 'confirm', name: 'confirmDelete', message: `Delete plugin "${id}"? This can't be undone.`, default: false },
|
|
735
|
+
]);
|
|
736
|
+
if (!confirmDelete) {
|
|
737
|
+
console.log(chalk.gray('Cancelled.'));
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
try {
|
|
742
|
+
await axios.delete(`${serverUrl}/plugins/store/${encodeURIComponent(id)}`, { ...authHeaders, timeout: DELETE_TIMEOUT_MS });
|
|
743
|
+
console.log(chalk.green(`✅ Deleted "${id}".`));
|
|
744
|
+
} catch (error) {
|
|
745
|
+
const message = error.response?.data?.message || error.message;
|
|
746
|
+
throw new Error(`Delete failed: ${message}`, { cause: error });
|
|
747
|
+
}
|
|
748
|
+
}
|
package/bin/lib/store.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import path from 'path';
|
|
|
4
4
|
import chalk from 'chalk';
|
|
5
5
|
import axios from 'axios';
|
|
6
6
|
import inquirer from 'inquirer';
|
|
7
|
-
import { withSpinner } from './util.mjs';
|
|
7
|
+
import { withSpinner, requireArg } from './util.mjs';
|
|
8
8
|
|
|
9
9
|
// ── Plugin store (self-host aivin-service worker) — attach/create/ls/enable/disable/detach ──────
|
|
10
10
|
//
|
|
@@ -32,7 +32,7 @@ function defaultDataDir() {
|
|
|
32
32
|
|
|
33
33
|
/** Ghi `worker-identity.json` — schema PHẢI khớp CHÍNH XÁC với `WorkerIdentity.ts` (repo
|
|
34
34
|
* `aivin-service`) đọc, không thêm/bớt field tuỳ tiện ở 1 phía mà không sửa phía kia. */
|
|
35
|
-
function writeWorkerIdentity(dataDir, { beEndpoint, orgId, storeId, nodeId, nodeLabel, workerToken }) {
|
|
35
|
+
function writeWorkerIdentity(dataDir, { beEndpoint, orgId, storeId, storeName, nodeId, nodeLabel, workerToken, sdkGrpcEndpoint }) {
|
|
36
36
|
fs.mkdirSync(dataDir, { recursive: true });
|
|
37
37
|
const filePath = path.join(dataDir, 'worker-identity.json');
|
|
38
38
|
const payload = {
|
|
@@ -40,24 +40,58 @@ function writeWorkerIdentity(dataDir, { beEndpoint, orgId, storeId, nodeId, node
|
|
|
40
40
|
be_endpoint: beEndpoint,
|
|
41
41
|
org_id: orgId,
|
|
42
42
|
store_id: storeId,
|
|
43
|
+
store_name: storeName || '',
|
|
43
44
|
node_id: nodeId,
|
|
44
45
|
node_label: nodeLabel || '',
|
|
45
46
|
worker_token: workerToken,
|
|
47
|
+
// Tuỳ chọn — chỉ có nếu BE cấu hình SDK_GRPC_EXTERNAL_PUBLIC_ENDPOINT (xem
|
|
48
|
+
// PluginStoreRegistryService.ts's resolveSdkGrpcPublicEndpoint). Cho phép node self-host gọi
|
|
49
|
+
// AI-call RPC (ScanAwesomeMcpList/ScanSingleMcpRepo) qua worker_token thay vì cần
|
|
50
|
+
// SDK_ENDPOINT/SDK_SECRET riêng — xem WorkerConnectClient.configureSdkTransport() phía service.
|
|
51
|
+
...(sdkGrpcEndpoint ? { sdk_grpc_endpoint: sdkGrpcEndpoint } : {}),
|
|
46
52
|
paired_at: new Date().toISOString(),
|
|
47
53
|
};
|
|
48
54
|
fs.writeFileSync(filePath, JSON.stringify(payload, null, 2) + '\n', { mode: 0o600 });
|
|
49
55
|
return filePath;
|
|
50
56
|
}
|
|
51
57
|
|
|
52
|
-
|
|
53
|
-
|
|
58
|
+
// How long `attach`/`create` wait for the just-written node to actually show up `online` before
|
|
59
|
+
// giving up and printing troubleshooting hints - long enough to cover a running aivin-service
|
|
60
|
+
// noticing the file (~200ms) + dialing WorkerHub.Connect + TLS handshake, short enough that a
|
|
61
|
+
// first-time setup (container not started yet) doesn't feel like the command hung.
|
|
62
|
+
const NODE_ONLINE_POLL_TOTAL_MS = 12000;
|
|
63
|
+
const NODE_ONLINE_POLL_INTERVAL_MS = 1500;
|
|
64
|
+
|
|
65
|
+
/** Polls `GET /stores` until `nodeId` shows `status: 'online'` or the budget runs out. Best-effort -
|
|
66
|
+
* a transient network/auth error while polling is swallowed (not fatal to `attach`/`create`
|
|
67
|
+
* itself, which already succeeded server-side); the caller just sees "not online yet". */
|
|
68
|
+
async function waitForNodeOnline(storeId, nodeId) {
|
|
69
|
+
const deadline = Date.now() + NODE_ONLINE_POLL_TOTAL_MS;
|
|
70
|
+
while (Date.now() < deadline) {
|
|
71
|
+
await new Promise((resolve) => setTimeout(resolve, NODE_ONLINE_POLL_INTERVAL_MS));
|
|
72
|
+
try {
|
|
73
|
+
const res = await axios.get(`${storeBaseUrl()}/stores`, storeAuthHeaders());
|
|
74
|
+
const store = (res.data || []).find((s) => s.store_id === storeId);
|
|
75
|
+
const node = store?.nodes?.find((n) => n.node_id === nodeId);
|
|
76
|
+
if (node?.status === 'online') return true;
|
|
77
|
+
} catch {
|
|
78
|
+
// transient - keep polling until the deadline
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function printAttachResult(res, dataDir) {
|
|
85
|
+
const { store, node, worker_token, worker_hub_endpoint, sdk_grpc_endpoint } = res.data;
|
|
54
86
|
const filePath = writeWorkerIdentity(dataDir, {
|
|
55
87
|
beEndpoint: worker_hub_endpoint,
|
|
56
88
|
orgId: store.owner_org_id,
|
|
57
89
|
storeId: store.store_id,
|
|
90
|
+
storeName: store.label,
|
|
58
91
|
nodeId: node.node_id,
|
|
59
92
|
nodeLabel: node.label,
|
|
60
93
|
workerToken: worker_token,
|
|
94
|
+
sdkGrpcEndpoint: sdk_grpc_endpoint,
|
|
61
95
|
});
|
|
62
96
|
console.log(chalk.green(`\n✅ Node "${node.node_id}" attached to store "${store.store_id}"`));
|
|
63
97
|
console.log(chalk.gray(` Credential written to ${filePath}`));
|
|
@@ -66,25 +100,51 @@ function printAttachResult(res, dataDir) {
|
|
|
66
100
|
` If aivin-service isn't running yet: docker run -v ${dataDir}:/app/data ... (mount this exact directory as WORKER_DATA_DIR)`,
|
|
67
101
|
),
|
|
68
102
|
);
|
|
69
|
-
|
|
103
|
+
|
|
104
|
+
// Best-effort confirmation, not a hard requirement - a fresh setup with aivin-service not
|
|
105
|
+
// started yet is expected to still be "offline" here, that's normal, not a failure. This only
|
|
106
|
+
// upgrades a previously-silent "trust me, it worked" into an actual observed state, so a broken
|
|
107
|
+
// connect (bad token/TLS/tunnel/firewall) is caught right here instead of surfacing later as a
|
|
108
|
+
// confusing "no nodes attached"/trigger-hangs-then-524 the next time this store is used.
|
|
109
|
+
const online = await withSpinner(` Waiting for "${node.node_id}" to come online`, () => waitForNodeOnline(store.store_id, node.node_id));
|
|
110
|
+
if (online) {
|
|
111
|
+
console.log(chalk.green(` ✅ Connected - node is online.`));
|
|
112
|
+
} else {
|
|
113
|
+
console.log(chalk.yellow(` ⏳ Not online yet.`));
|
|
114
|
+
console.log(chalk.gray(' Normal if aivin-service isn\'t running yet on this credential\'s data dir - nothing else to do,'));
|
|
115
|
+
console.log(chalk.gray(' it picks up the file within ~200ms once started, no restart needed.'));
|
|
116
|
+
console.log(chalk.gray(` Already running and still offline after a bit? Check: it can reach ${worker_hub_endpoint} over TLS`));
|
|
117
|
+
console.log(chalk.gray(' (firewall/tunnel in the way?), and its own logs for a connect error. Re-check with `aivin pluginstore ls`.'));
|
|
118
|
+
console.log(
|
|
119
|
+
chalk.gray(
|
|
120
|
+
` If this node never comes online, remove it with \`aivin pluginstore rm-node ${store.store_id} ${node.node_id}\` and re-attach once fixed.`,
|
|
121
|
+
),
|
|
122
|
+
);
|
|
123
|
+
}
|
|
70
124
|
}
|
|
71
125
|
|
|
72
126
|
export async function createStore(storeId, options) {
|
|
127
|
+
const interactive = process.stdout.isTTY && process.stdin.isTTY;
|
|
128
|
+
|
|
73
129
|
if (!storeId) {
|
|
130
|
+
if (!interactive) throw new Error('Store id is required - pass it as an argument (non-interactive session).');
|
|
74
131
|
const { answer } = await inquirer.prompt([{ type: 'input', name: 'answer', message: 'Store id (slug, e.g. phong-ban-a):' }]);
|
|
75
132
|
storeId = answer;
|
|
76
133
|
}
|
|
134
|
+
|
|
77
135
|
let label = options.label;
|
|
78
|
-
if (!label &&
|
|
79
|
-
const { answer } = await inquirer.prompt([{ type: 'input', name: 'answer', message: '
|
|
136
|
+
if (!label && interactive) {
|
|
137
|
+
const { answer } = await inquirer.prompt([{ type: 'input', name: 'answer', message: 'Store name:', default: storeId }]);
|
|
80
138
|
label = answer;
|
|
81
139
|
}
|
|
82
140
|
|
|
141
|
+
const nodeLabel = options.nodeLabel || os.hostname();
|
|
142
|
+
|
|
83
143
|
try {
|
|
84
144
|
const res = await withSpinner(`📦 Creating store "${storeId}"`, () =>
|
|
85
|
-
axios.post(`${storeBaseUrl()}/stores`, { store_id: storeId, label, node_label:
|
|
145
|
+
axios.post(`${storeBaseUrl()}/stores`, { store_id: storeId, label, node_label: nodeLabel }, storeAuthHeaders()),
|
|
86
146
|
);
|
|
87
|
-
printAttachResult(res, options.dataDir || defaultDataDir());
|
|
147
|
+
await printAttachResult(res, options.dataDir || defaultDataDir());
|
|
88
148
|
} catch (error) {
|
|
89
149
|
const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
|
|
90
150
|
throw new Error(`Create store failed: ${message}`, { cause: error });
|
|
@@ -103,7 +163,7 @@ export async function attachStore(storeId, options) {
|
|
|
103
163
|
const res = await withSpinner(`🔗 Attaching to store "${storeId}"`, () =>
|
|
104
164
|
axios.post(`${storeBaseUrl()}/stores/${encodeURIComponent(storeId)}/attach`, { node_label: options.nodeLabel }, storeAuthHeaders()),
|
|
105
165
|
);
|
|
106
|
-
printAttachResult(res, options.dataDir || defaultDataDir());
|
|
166
|
+
await printAttachResult(res, options.dataDir || defaultDataDir());
|
|
107
167
|
} catch (error) {
|
|
108
168
|
if (error.response?.status === 404) {
|
|
109
169
|
console.log(chalk.yellow(`Store "${storeId}" doesn't exist yet.`));
|
|
@@ -145,7 +205,13 @@ export async function listStores(options) {
|
|
|
145
205
|
const nodeStatus = n.status === 'online' ? chalk.green('online') : chalk.gray('offline');
|
|
146
206
|
console.log(chalk.gray(` - ${n.label || n.node_id} (${n.node_id}) ${nodeStatus}`));
|
|
147
207
|
}
|
|
148
|
-
if (options.plain !== true && (s.nodes || []).length === 0)
|
|
208
|
+
if (options.plain !== true && (s.nodes || []).length === 0) {
|
|
209
|
+
// `kind=system` (the "aivin default" store) is served by Aivin's own managed fleet, not by
|
|
210
|
+
// self-host nodes attached via this CLI - it ALWAYS has 0 nodes here, by design, not because
|
|
211
|
+
// anything is wrong. Printing the same "(no nodes attached)" line self-host stores use made
|
|
212
|
+
// this look like a standing error on every single `ls` for every account.
|
|
213
|
+
console.log(chalk.gray(s.kind === 'system' ? ' (served by Aivin\'s managed fleet - self-host nodes not applicable)' : ' (no nodes attached)'));
|
|
214
|
+
}
|
|
149
215
|
console.log();
|
|
150
216
|
}
|
|
151
217
|
}
|
|
@@ -189,6 +255,40 @@ export async function deleteStore(storeId, options) {
|
|
|
189
255
|
}
|
|
190
256
|
}
|
|
191
257
|
|
|
258
|
+
/** `rm-node` - removes ONE node from a store without touching any other node attached to it
|
|
259
|
+
* (unlike `rm`, which revokes every node's credential at once). Meant for cleaning up a node that
|
|
260
|
+
* never came online (bad token/TLS/network at `attach` time - see `waitForNodeOnline` above) and
|
|
261
|
+
* is just sitting there `offline` forever, without having to nuke and re-pair every other machine
|
|
262
|
+
* attached to the same store. BE refuses this for a node that's currently `online` (409) - detach
|
|
263
|
+
* it there first (stop aivin-service, or `aivin pluginstore detach` on that machine). */
|
|
264
|
+
export async function removeNode(storeId, nodeId, options) {
|
|
265
|
+
storeId = await requireArg(storeId, { prompt: 'Store id:', usage: 'Usage: aivin pluginstore rm-node <store_id> <node_id>' });
|
|
266
|
+
nodeId = await requireArg(nodeId, { prompt: 'Node id to remove:', usage: 'Usage: aivin pluginstore rm-node <store_id> <node_id>' });
|
|
267
|
+
|
|
268
|
+
if (!options.yes) {
|
|
269
|
+
const { confirm } = await inquirer.prompt([
|
|
270
|
+
{ type: 'confirm', name: 'confirm', message: `Remove node "${nodeId}" from store "${storeId}"? This can't be undone.`, default: false },
|
|
271
|
+
]);
|
|
272
|
+
if (!confirm) {
|
|
273
|
+
console.log(chalk.gray('Cancelled.'));
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
try {
|
|
279
|
+
await withSpinner(`🗑 Removing node "${nodeId}"`, () =>
|
|
280
|
+
axios.delete(`${storeBaseUrl()}/stores/${encodeURIComponent(storeId)}/nodes/${encodeURIComponent(nodeId)}`, storeAuthHeaders()),
|
|
281
|
+
);
|
|
282
|
+
console.log(chalk.green(`✅ Node "${nodeId}" removed from store "${storeId}".`));
|
|
283
|
+
} catch (error) {
|
|
284
|
+
const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
|
|
285
|
+
if (error.response?.status === 409) {
|
|
286
|
+
throw new Error(`${message} - this node is still online. Stop aivin-service (or run \`aivin pluginstore detach\` on that machine) first.`, { cause: error });
|
|
287
|
+
}
|
|
288
|
+
throw new Error(`Remove node failed: ${message}`, { cause: error });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
192
292
|
/** `detach` — THUẦN CỤC BỘ, không gọi BE (xem doc thiết kế mục 7): chỉ xoá file credential của
|
|
193
293
|
* ĐÚNG máy này. `aivin-service`'s `WorkerIdentity.ts` tự bắt được qua `fs.watch` và disconnect. */
|
|
194
294
|
export function detachStore(options) {
|
package/bin/lib/util.mjs
CHANGED
|
@@ -25,6 +25,32 @@ export async function withSpinner(label, fn) {
|
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
// Same as withSpinner but also renders a stage/percent readout that changes over time — for calls
|
|
29
|
+
// where the backend publishes realtime progress (e.g. `plugin trigger`'s cold-start Docker install,
|
|
30
|
+
// which can take 60-150s+ with zero feedback otherwise). `getCurrent()` is polled every tick and
|
|
31
|
+
// should return the latest `{ stage, percent, message }` received (or null before anything arrives).
|
|
32
|
+
export async function withProgressSpinner(label, getCurrent, fn) {
|
|
33
|
+
if (!process.stdout.isTTY) {
|
|
34
|
+
console.log(chalk.blue(`${label}...`));
|
|
35
|
+
return fn();
|
|
36
|
+
}
|
|
37
|
+
const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
|
38
|
+
let i = 0;
|
|
39
|
+
const timer = setInterval(() => {
|
|
40
|
+
const current = getCurrent?.();
|
|
41
|
+
const suffix = current?.percent != null ? ` ${current.message || current.stage} ${current.percent}%` : '...';
|
|
42
|
+
process.stdout.write(`\r${chalk.cyan(frames[i])} ${label}${suffix}`);
|
|
43
|
+
i = (i + 1) % frames.length;
|
|
44
|
+
}, 100);
|
|
45
|
+
try {
|
|
46
|
+
return await fn();
|
|
47
|
+
} finally {
|
|
48
|
+
clearInterval(timer);
|
|
49
|
+
readline.cursorTo(process.stdout, 0);
|
|
50
|
+
readline.clearLine(process.stdout, 0);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
28
54
|
// Positional CLI args are declared optional ([arg]) everywhere, not required (<arg>), so Commander
|
|
29
55
|
// never hard-fails before the action() runs - every command instead calls this to fill a missing
|
|
30
56
|
// value interactively. Falls back to throwing `usage` when there's no TTY to prompt on (scripts/
|