@aivin-labs/cli 1.0.0 → 1.0.3
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 +76 -6
- package/bin/lib/browserAutomation.mjs +24 -3
- package/bin/lib/connectors.mjs +1 -0
- package/bin/lib/deploy.mjs +66 -8
- package/bin/lib/mcpProxy.mjs +420 -83
- package/bin/lib/missionStream.mjs +1 -1
- package/bin/lib/pluginTrigger.mjs +192 -10
- package/bin/lib/store.mjs +111 -11
- package/docs/CLI.md +220 -25
- package/package.json +1 -1
|
@@ -434,7 +434,7 @@ export function streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClien
|
|
|
434
434
|
}
|
|
435
435
|
});
|
|
436
436
|
|
|
437
|
-
console.log(chalk.gray(`📡 Watching live progress for ${threadId}... (Ctrl+C to stop
|
|
437
|
+
console.log(chalk.gray(`📡 Watching live progress for ${threadId}... (Ctrl+C to stop and request cancellation)\n`));
|
|
438
438
|
bumpIdleTimer();
|
|
439
439
|
});
|
|
440
440
|
}
|
|
@@ -3,10 +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';
|
|
6
7
|
import { flattenManifestFile } from '@aivin-labs/sdk';
|
|
7
8
|
import readline from 'readline';
|
|
8
9
|
import { requireArg } from './util.mjs';
|
|
9
10
|
|
|
11
|
+
const DELETE_TIMEOUT_MS = 30000;
|
|
12
|
+
|
|
10
13
|
/**
|
|
11
14
|
* Resolves which manifest entry `plugin trigger` should invoke: the `--func` match if given, the
|
|
12
15
|
* one-and-only entry for a single-function/single-entry plugin, or a clear error listing the
|
|
@@ -369,8 +372,11 @@ export async function searchPlugins(query, options) {
|
|
|
369
372
|
}
|
|
370
373
|
const authHeaders = { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
|
|
371
374
|
|
|
372
|
-
const params = {
|
|
375
|
+
const params = {};
|
|
376
|
+
if (query) params.query = query;
|
|
373
377
|
if (options.workspace) params.workspace_id = options.workspace;
|
|
378
|
+
if (options.mcp) params.mcp_server_id = options.mcp;
|
|
379
|
+
if (options.store) params.store_id = options.store;
|
|
374
380
|
if (options.limit) params.limit = options.limit;
|
|
375
381
|
|
|
376
382
|
let response;
|
|
@@ -385,20 +391,23 @@ export async function searchPlugins(query, options) {
|
|
|
385
391
|
// relevance-ranked lookup the platform's own agent uses to auto-select a plugin for a mission).
|
|
386
392
|
const data = response.data;
|
|
387
393
|
const results = Array.isArray(data) ? data : data?.items || [];
|
|
394
|
+
// --mcp is an exact-id lookup (no free-text query) - describe results by server id instead.
|
|
395
|
+
const describedAs = (options.mcp ? `MCP server "${options.mcp}"` : `"${query}"`)
|
|
396
|
+
+ (options.store ? ` in store "${options.store}"` : '');
|
|
388
397
|
|
|
389
398
|
if (results.length === 0) {
|
|
390
|
-
console.log(chalk.yellow(`No plugins found matching
|
|
399
|
+
console.log(chalk.yellow(`No plugins found matching ${describedAs}.`));
|
|
391
400
|
return;
|
|
392
401
|
}
|
|
393
402
|
|
|
394
403
|
// Interactive browser needs a real terminal to read raw keypresses - fall back to a flat
|
|
395
404
|
// print for scripts/CI or when the user explicitly asks for it with --plain.
|
|
396
405
|
if (process.stdout.isTTY && process.stdin.isTTY && !options.plain) {
|
|
397
|
-
await browseResults(results, `Found ${results.length} plugin(s) matching
|
|
406
|
+
await browseResults(results, `Found ${results.length} plugin(s) matching ${describedAs}:\n`, formatPluginListLine, formatPluginDetail);
|
|
398
407
|
return;
|
|
399
408
|
}
|
|
400
409
|
|
|
401
|
-
console.log(chalk.blue(`Found ${results.length} plugin(s) matching
|
|
410
|
+
console.log(chalk.blue(`Found ${results.length} plugin(s) matching ${describedAs}:\n`));
|
|
402
411
|
for (const plugin of results) {
|
|
403
412
|
console.log(chalk.bold(plugin.name || plugin.id) + chalk.gray(` (${plugin.id})`));
|
|
404
413
|
if (plugin.description) console.log(` ${plugin.description}`);
|
|
@@ -412,6 +421,109 @@ export async function searchPlugins(query, options) {
|
|
|
412
421
|
);
|
|
413
422
|
}
|
|
414
423
|
|
|
424
|
+
/**
|
|
425
|
+
* `aivin plugin info <id>` - detail view for one already-known plugin id, without going through
|
|
426
|
+
* `plugin search`'s free-text ranking first. Useful when debugging a specific plugin (e.g. one
|
|
427
|
+
* seen in `plugin search --mcp <server>`'s listing, or copied from the platform) and you just want
|
|
428
|
+
* its input/output schema and setup requirements again.
|
|
429
|
+
*
|
|
430
|
+
* There's no dedicated GET /plugins/:id on the backend, so this reuses /plugins/search with the id
|
|
431
|
+
* itself as the query and picks the exact `id` match out of the ranked results - the same lookup
|
|
432
|
+
* `plugin search` already does, just narrowed down for you. Falls back to showing the closest
|
|
433
|
+
* matches (with a clear "no exact match" note) if the id typo'd or the plugin isn't visible to you.
|
|
434
|
+
*/
|
|
435
|
+
export async function showPluginInfo(id, options) {
|
|
436
|
+
const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
|
|
437
|
+
const apiKey = process.env.API_KEY;
|
|
438
|
+
if (!apiKey) {
|
|
439
|
+
console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
|
|
440
|
+
}
|
|
441
|
+
const authHeaders = { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
|
|
442
|
+
|
|
443
|
+
const params = { query: id, limit: options.limit || 10 };
|
|
444
|
+
if (options.workspace) params.workspace_id = options.workspace;
|
|
445
|
+
|
|
446
|
+
let response;
|
|
447
|
+
try {
|
|
448
|
+
response = await axios.get(`${serverUrl}/plugins/search`, { ...authHeaders, params });
|
|
449
|
+
} catch (error) {
|
|
450
|
+
const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
|
|
451
|
+
throw new Error(`Lookup failed: ${message}`, { cause: error });
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const data = response.data;
|
|
455
|
+
const results = Array.isArray(data) ? data : data?.items || [];
|
|
456
|
+
const exact = results.find((p) => p.id === id);
|
|
457
|
+
|
|
458
|
+
if (exact) {
|
|
459
|
+
console.log(formatPluginDetail(exact));
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
if (results.length === 0) {
|
|
464
|
+
console.log(chalk.yellow(`No plugin found for id "${id}".`));
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
console.log(chalk.yellow(`No exact match for "${id}" - closest result(s):\n`));
|
|
469
|
+
if (process.stdout.isTTY && process.stdin.isTTY && !options.plain) {
|
|
470
|
+
await browseResults(results, `Closest to "${id}":\n`, formatPluginListLine, formatPluginDetail);
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
for (const plugin of results) {
|
|
474
|
+
console.log(chalk.bold(plugin.name || plugin.id) + chalk.gray(` (${plugin.id})`));
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* `aivin plugin ask "<mission>"` - the one-shot "just simulate the agent" mode: given a
|
|
480
|
+
* plain-language mission, it searches the plugin ecosystem the same relevance-ranked way the
|
|
481
|
+
* platform's own agent does to auto-select a plugin, picks the top match, and immediately triggers
|
|
482
|
+
* it with that same mission auto-mapped onto the input schema (`plugin trigger -a` under the hood).
|
|
483
|
+
* Where `plugin search` + `plugin trigger --id <id> -a "..."` is the two-step "pick, then run" flow,
|
|
484
|
+
* `ask` collapses both into what an agent actually does at execution time - no manual id copy/paste.
|
|
485
|
+
*
|
|
486
|
+
* `--top <n>` (default 5) controls how many candidates are fetched so the runner-up(s) can be
|
|
487
|
+
* printed for context/debugging when the auto-pick looks wrong; only the #1 match is ever run.
|
|
488
|
+
*/
|
|
489
|
+
export async function askPlugin(mission, options) {
|
|
490
|
+
mission = await requireArg(mission, { prompt: 'What do you want done?', usage: 'Usage: aivin plugin ask "<mission>"' });
|
|
491
|
+
|
|
492
|
+
const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
|
|
493
|
+
const apiKey = process.env.API_KEY;
|
|
494
|
+
if (!apiKey) {
|
|
495
|
+
console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
|
|
496
|
+
}
|
|
497
|
+
const authHeaders = { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
|
|
498
|
+
|
|
499
|
+
const params = { query: mission, limit: options.top || 5 };
|
|
500
|
+
if (options.workspace) params.workspace_id = options.workspace;
|
|
501
|
+
|
|
502
|
+
let response;
|
|
503
|
+
try {
|
|
504
|
+
response = await axios.get(`${serverUrl}/plugins/search`, { ...authHeaders, params });
|
|
505
|
+
} catch (error) {
|
|
506
|
+
const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
|
|
507
|
+
throw new Error(`Search failed: ${message}`, { cause: error });
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const data = response.data;
|
|
511
|
+
const results = Array.isArray(data) ? data : data?.items || [];
|
|
512
|
+
if (results.length === 0) {
|
|
513
|
+
throw new Error(`No plugin matches "${mission}". Try \`aivin plugin search\` with different wording, or \`aivin plugin make\` to write one.`);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const chosen = results[0];
|
|
517
|
+
const matchLabel = typeof chosen._similarity === 'number' ? ` (${(chosen._similarity * 100).toFixed(0)}% match)` : '';
|
|
518
|
+
console.log(chalk.blue(`🤖 Auto-selected: ${chalk.bold(chosen.name || chosen.id)}${matchLabel}`) + chalk.gray(` (${chosen.id})`));
|
|
519
|
+
if (results.length > 1) {
|
|
520
|
+
console.log(chalk.gray(` runner-up(s): ${results.slice(1).map((p) => p.name || p.id).join(', ')}`));
|
|
521
|
+
}
|
|
522
|
+
console.log();
|
|
523
|
+
|
|
524
|
+
await triggerPlugin(mission, options.input, { ...options, auto: mission, id: chosen.id });
|
|
525
|
+
}
|
|
526
|
+
|
|
415
527
|
export function formatPluginListLine(plugin, isSelected) {
|
|
416
528
|
const marker = isSelected ? chalk.cyan('❯ ') : ' ';
|
|
417
529
|
const label = plugin.name || plugin.id;
|
|
@@ -462,8 +574,8 @@ export function formatPluginDetail(plugin) {
|
|
|
462
574
|
return lines.join('\n');
|
|
463
575
|
}
|
|
464
576
|
|
|
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
|
|
577
|
+
// Simple raw-keypress list/detail browser: ↑/↓ to move, space/enter/→ to open an item's detail
|
|
578
|
+
// view, esc/backspace/← to go back to the listing, q/ctrl+c to exit. No extra deps - built on
|
|
467
579
|
// node's own readline keypress events since inquirer's prompts don't support this drill-down.
|
|
468
580
|
// Generic over what's being browsed (plugins, connectors, ...) via the format callbacks.
|
|
469
581
|
export function browseResults(results, headerText, formatLine, formatDetail) {
|
|
@@ -482,10 +594,10 @@ export function browseResults(results, headerText, formatLine, formatDetail) {
|
|
|
482
594
|
for (let i = 0; i < results.length; i++) {
|
|
483
595
|
console.log(formatLine(results[i], i === index));
|
|
484
596
|
}
|
|
485
|
-
console.log(chalk.gray('\n↑/↓ move space/enter view details q quit'));
|
|
597
|
+
console.log(chalk.gray('\n↑/↓ move →/space/enter view details q quit'));
|
|
486
598
|
} else {
|
|
487
599
|
console.log(formatDetail(results[index]));
|
|
488
|
-
console.log(chalk.gray('\
|
|
600
|
+
console.log(chalk.gray('\n←/esc/backspace back q quit'));
|
|
489
601
|
}
|
|
490
602
|
};
|
|
491
603
|
|
|
@@ -502,7 +614,7 @@ export function browseResults(results, headerText, formatLine, formatDetail) {
|
|
|
502
614
|
} else if (key.name === 'down') {
|
|
503
615
|
index = (index + 1) % results.length;
|
|
504
616
|
render();
|
|
505
|
-
} else if (key.name === 'return' || key.name === 'space' || str === ' ') {
|
|
617
|
+
} else if (key.name === 'return' || key.name === 'space' || key.name === 'right' || str === ' ') {
|
|
506
618
|
mode = 'detail';
|
|
507
619
|
render();
|
|
508
620
|
} else if (key.name === 'q' || key.name === 'escape') {
|
|
@@ -510,7 +622,7 @@ export function browseResults(results, headerText, formatLine, formatDetail) {
|
|
|
510
622
|
resolve();
|
|
511
623
|
}
|
|
512
624
|
} else {
|
|
513
|
-
if (key.name === 'escape' || key.name === 'backspace') {
|
|
625
|
+
if (key.name === 'escape' || key.name === 'backspace' || key.name === 'left') {
|
|
514
626
|
mode = 'list';
|
|
515
627
|
render();
|
|
516
628
|
} else if (key.name === 'q') {
|
|
@@ -533,3 +645,73 @@ export function browseResults(results, headerText, formatLine, formatDetail) {
|
|
|
533
645
|
render();
|
|
534
646
|
});
|
|
535
647
|
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* `aivin plugin delete <id>` / `aivin plugin delete --group <groupId>` - the CLI-side counterpart
|
|
651
|
+
* that had been missing: everything else in this file (`create`/`trigger`/`deploy`) had no way to
|
|
652
|
+
* undo itself. Two backend endpoints, both ownership-checked server-side (404, not 403, for a
|
|
653
|
+
* plugin/group that isn't yours - avoids leaking which ids exist in other orgs):
|
|
654
|
+
* - `DELETE /plugins/store/:pluginId` - one plugin.
|
|
655
|
+
* - `DELETE /plugins/group/:groupId` - every plugin sharing one `group_id`, i.e. everything a
|
|
656
|
+
* single batch deploy created in one call - the backend's own controller comment says this
|
|
657
|
+
* exists specifically "để CLI dùng group_id trả về từ batch deploy để rollback cả lô" (so the
|
|
658
|
+
* CLI can use the group_id a batch deploy returns to roll back the whole batch), which is
|
|
659
|
+
* exactly `aivin mcp <url>`'s "N plugin(s) generated from this MCP server" case - it already
|
|
660
|
+
* prints that group_id after deploy, this is what it's for.
|
|
661
|
+
*
|
|
662
|
+
* Both prompt a confirmation (skippable with `-y`/`--yes` for scripts) since neither can be undone
|
|
663
|
+
* from here - `--group` additionally requires typing the id back, same pattern `pluginstore rm`
|
|
664
|
+
* uses, since it can delete many plugins at once from one typo'd id.
|
|
665
|
+
*/
|
|
666
|
+
export async function deletePluginCmd(id, options) {
|
|
667
|
+
const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
|
|
668
|
+
const apiKey = process.env.API_KEY;
|
|
669
|
+
if (!apiKey) {
|
|
670
|
+
console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
|
|
671
|
+
}
|
|
672
|
+
const authHeaders = { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
|
|
673
|
+
|
|
674
|
+
if (options.group) {
|
|
675
|
+
if (!options.yes) {
|
|
676
|
+
const { confirmId } = await inquirer.prompt([
|
|
677
|
+
{
|
|
678
|
+
type: 'input',
|
|
679
|
+
name: 'confirmId',
|
|
680
|
+
message: chalk.red(`This deletes EVERY plugin in group "${options.group}" - can't be undone. Type the group id to confirm:`),
|
|
681
|
+
},
|
|
682
|
+
]);
|
|
683
|
+
if (confirmId !== options.group) {
|
|
684
|
+
console.log(chalk.gray('Cancelled - group id did not match.'));
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
try {
|
|
689
|
+
const res = await axios.delete(`${serverUrl}/plugins/group/${encodeURIComponent(options.group)}`, { ...authHeaders, timeout: DELETE_TIMEOUT_MS });
|
|
690
|
+
console.log(chalk.green(`✅ Deleted ${res.data?.deleted_count ?? '?'} plugin(s) from group "${options.group}".`));
|
|
691
|
+
} catch (error) {
|
|
692
|
+
const message = error.response?.data?.message || error.message;
|
|
693
|
+
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' : '';
|
|
694
|
+
throw new Error(`Group delete failed: ${message}${hint}`, { cause: error });
|
|
695
|
+
}
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
id = await requireArg(id, { prompt: 'Plugin id to delete:', usage: 'Usage: aivin plugin delete <id> (or: aivin plugin delete --group <groupId>)' });
|
|
700
|
+
|
|
701
|
+
if (!options.yes) {
|
|
702
|
+
const { confirmDelete } = await inquirer.prompt([
|
|
703
|
+
{ type: 'confirm', name: 'confirmDelete', message: `Delete plugin "${id}"? This can't be undone.`, default: false },
|
|
704
|
+
]);
|
|
705
|
+
if (!confirmDelete) {
|
|
706
|
+
console.log(chalk.gray('Cancelled.'));
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
try {
|
|
711
|
+
await axios.delete(`${serverUrl}/plugins/store/${encodeURIComponent(id)}`, { ...authHeaders, timeout: DELETE_TIMEOUT_MS });
|
|
712
|
+
console.log(chalk.green(`✅ Deleted "${id}".`));
|
|
713
|
+
} catch (error) {
|
|
714
|
+
const message = error.response?.data?.message || error.message;
|
|
715
|
+
throw new Error(`Delete failed: ${message}`, { cause: error });
|
|
716
|
+
}
|
|
717
|
+
}
|
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) {
|