@aivin-labs/cli 1.0.8 → 1.0.11

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 (51) hide show
  1. package/README.md +25 -0
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +1912 -1780
  4. package/bin/lib/browserAutomation.mjs +232 -469
  5. package/bin/lib/localBrowser.mjs +345 -0
  6. package/bin/lib/remote/activityLog.mjs +1 -1
  7. package/bin/lib/remote/autoStart.mjs +174 -14
  8. package/bin/lib/remote/browserTunnel.mjs +142 -31
  9. package/bin/lib/remote/callLedger.mjs +1 -1
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -1
  11. package/bin/lib/remote/client.mjs +87 -5
  12. package/bin/lib/remote/clipboard.mjs +138 -0
  13. package/bin/lib/remote/codingAgents.mjs +293 -0
  14. package/bin/lib/remote/constants.mjs +61 -0
  15. package/bin/lib/remote/dailyBrowser.mjs +1 -1
  16. package/bin/lib/remote/desktop/index.mjs +272 -0
  17. package/bin/lib/remote/desktop/linux.mjs +144 -0
  18. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
  19. package/bin/lib/remote/desktop/mac.mjs +187 -0
  20. package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
  21. package/bin/lib/remote/desktop/strings.mjs +74 -0
  22. package/bin/lib/remote/desktop/traySource.mjs +527 -0
  23. package/bin/lib/remote/docText.mjs +1 -1
  24. package/bin/lib/remote/fileIndexer.mjs +1 -1
  25. package/bin/lib/remote/gui/index.mjs +93 -12
  26. package/bin/lib/remote/gui/windowsHostSource.mjs +280 -28
  27. package/bin/lib/remote/idempotency.mjs +1 -1
  28. package/bin/lib/remote/localPolicy.mjs +9 -2
  29. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  30. package/bin/lib/remote/mascot/ask.mjs +768 -0
  31. package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
  32. package/bin/lib/remote/mascot/assets.mjs +825 -216
  33. package/bin/lib/remote/mascot/bot.mjs +372 -0
  34. package/bin/lib/remote/mascot/hostSource.mjs +498 -101
  35. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  36. package/bin/lib/remote/mascot/index.mjs +199 -28
  37. package/bin/lib/remote/mascot/labels.mjs +2 -3
  38. package/bin/lib/remote/mascot/rigSource.mjs +609 -0
  39. package/bin/lib/remote/mascot/strings.mjs +204 -18
  40. package/bin/lib/remote/mascot/ui.mjs +104 -0
  41. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  42. package/bin/lib/remote/meeting/index.mjs +415 -0
  43. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  44. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  45. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  46. package/bin/lib/remote/tabGroups.mjs +209 -0
  47. package/bin/lib/remote/toolHandlers.mjs +15 -0
  48. package/docs/AIVIN_MASCOT.md +116 -0
  49. package/docs/CLI.md +142 -11
  50. package/docs/media/aivin-mascot-states.mp4 +0 -0
  51. package/package.json +1 -1
package/bin/cli.mjs CHANGED
@@ -1,1780 +1,1912 @@
1
- #!/usr/bin/env node
2
-
3
- import { Command } from 'commander';
4
- import chalk from 'chalk';
5
- import fs from 'fs';
6
- import path from 'path';
7
- import inquirer from 'inquirer';
8
- import { spawn } from 'child_process';
9
- import axios from 'axios';
10
- import dotenv from 'dotenv';
11
- import { fileURLToPath, pathToFileURL } from 'url';
12
- import { dirname } from 'path';
13
- import { createRequire } from 'module';
14
- // Same flatten logic PluginServer.ts uses for local/production runtime resolution - re-exported
15
- // from the installed @aivin-labs/sdk (not vendored here) so deploy and runtime agree on exactly
16
- // the same rules for what manifest.json's { ...commonFields, plugins: [...] } authoring shape
17
- // expands into.
18
- import { flattenManifestFile } from '@aivin-labs/sdk';
19
-
20
- // Side-effect only import - installs the global Ctrl+C → abort-in-flight-requests wiring
21
- // (`bin/lib/cancellation.mjs`) once, before any command runs. Must load before any lib file below
22
- // makes its first axios call so the interceptor is already in place.
23
- import './lib/cancellation.mjs';
24
-
25
- import { DEFAULT_AIVIN_BASE_URL, GLOBAL_CREDENTIALS_PATH, fetchWebUrl, loadActiveContext, clearActiveContext } from './lib/context.mjs';
26
- import { requireArg } from './lib/util.mjs';
27
- import { readStdin, createFromJSON, createInteractive, validatePluginConfig, validateMcpProxyConfig } from './lib/scaffold.mjs';
28
- import { buildDeploymentPayload, deployPlugin, incrementVersion } from './lib/deploy.mjs';
29
- import { initInteractive, makePluginFromDescription, convertExistingProject } from './lib/codegen.mjs';
30
- import { searchPlugins, showPluginInfo, askPlugin, streamPluginLogs, triggerPlugin, deletePluginCmd } from './lib/pluginTrigger.mjs';
31
- import { connectorAuthHeaders, connectorBaseUrl, listConnectors, registerConnector, searchConnectors, buildRegisterConnectorDto } from './lib/connectors.mjs';
32
- import { attachStore, createStore, deleteStore, detachStore, listStores, removeNode, setStoreEnabled } from './lib/store.mjs';
33
- import { buildMcpManifest, parseMcpArgs, guessConnectorQueryFromEnvVarName, createMcpProxyPlugin, scanAndPublishMcp, registerMcpWatch, unwatchMcp, listMcpWatches, setFieldConnector } from './lib/mcpProxy.mjs';
34
- import {
35
- saveGlobalApiKey,
36
- browserLogin,
37
- basicLogin,
38
- requireSavedApiKey,
39
- logAccountIdentity,
40
- listRemoteApiKeys,
41
- generateApiKey,
42
- revokeApiKeyByName,
43
- tryFetchWhoami,
44
- parseApiKeyClient,
45
- } from './lib/auth.mjs';
46
- import {
47
- missionAuthHeaders,
48
- missionServerUrl,
49
- resolveWorkspace,
50
- searchAgents,
51
- pullAgentIntoWorkspace,
52
- createAgent,
53
- publishAgent,
54
- installAgentInteractive,
55
- listAgentsCmd,
56
- } from './lib/workspace.mjs';
57
- import { runMission, runBrowserMission } from './lib/mission.mjs';
58
- import { DeviceAccess } from './lib/remote/constants.mjs';
59
- import { configureProxy } from './lib/remote/netProxy.mjs';
60
- import { DAEMON_RUNNING } from './lib/remote/daemonLock.mjs';
61
- import { runPolicyCommand } from './lib/remote/policyCommand.mjs';
62
- import { loadMascotSettings, saveMascotSettings } from './lib/remote/mascot/index.mjs';
63
- import { MascotText, mascotLang, mascotText } from './lib/remote/mascot/strings.mjs';
64
- import { RESTART_EXIT_CODE, UPDATE_ROLLED_BACK, UpdateStatus, cleanupRetired, downloadRoot, installUpdate, isStandaloneBinary, saveUpdateSettings } from './lib/selfUpdate.mjs';
65
- import {
66
- createAutomationJob,
67
- listTasks,
68
- listMyTasks,
69
- getTaskById,
70
- updateTaskById,
71
- deleteTaskById,
72
- createTask,
73
- buildCreateTaskPayload,
74
- pickWorkspaceAndProject,
75
- createProjectCmd,
76
- updateProjectCmd,
77
- deleteProjectCmd,
78
- listProjectsCmd,
79
- } from './lib/tasks.mjs';
80
- import {
81
- startRemoteClient,
82
- testRemoteConnection,
83
- enableAutoStart,
84
- disableAutoStart,
85
- getAutoStartStatus,
86
- buildDeviceProfile,
87
- buildTools,
88
- buildCatalog,
89
- getOrCreateDeviceId,
90
- resetDeviceId,
91
- loadDeviceCredentials,
92
- pairDevice,
93
- listDevices,
94
- unpairDevice,
95
- isRemotePaused,
96
- setRemotePaused,
97
- getRecentLogs,
98
- clearLogs,
99
- memoryStats,
100
- listMemoryItems,
101
- searchMemory,
102
- putMemoryItems,
103
- deleteMemoryItems,
104
- clearDeviceMemory,
105
- createFileIndex,
106
- indexRootsFor,
107
- runRemoteMission,
108
- MemoryKind,
109
- } from './lib/remoteControl.mjs';
110
-
111
- // Load env vars: the current project's `.env` first (any deliberate per-project override), THEN
112
- // fill in AIVIN_BASE_URL/API_KEY/SDK_ENDPOINT from the machine's active context if the project
113
- // didn't set them. `dotenv.config()` never overrides a variable that's already set, so a project's
114
- // own `.env` (or a real shell env var) always wins over the global context, exactly like before -
115
- // but nothing requires a project to have a `.env` at all anymore for the common single-context case.
116
- // `quiet: true` - otherwise dotenv prints an "injected env" tip line to stdout on every run, which
117
- // would corrupt `--json-output` mode (meant for clean, parseable JSON on stdout).
118
- dotenv.config({ quiet: true });
119
-
120
- {
121
- const activeContext = loadActiveContext();
122
- if (activeContext) {
123
- if (!process.env.AIVIN_BASE_URL) process.env.AIVIN_BASE_URL = activeContext.base_url;
124
- if (!process.env.API_KEY) process.env.API_KEY = activeContext.api_key;
125
- if (!process.env.SDK_ENDPOINT && activeContext.sdk_endpoint) process.env.SDK_ENDPOINT = activeContext.sdk_endpoint;
126
- }
127
- }
128
-
129
- const __filename = fileURLToPath(import.meta.url);
130
-
131
- const __dirname = dirname(__filename);
132
-
133
- // This CLI's own version (`aivin --version`) - distinct from whatever @aivin-labs/sdk version a
134
- // given plugin project has installed. See lib/scaffold.mjs for how a fresh scaffold's `@aivin-labs/
135
- // sdk` dependency pin is resolved (from the actually-installed sdk, not from here).
136
- // Bản tệp chạy đóng gói (scripts/build-binary.mjs) không có package.json trên đĩa — phiên bản được ghi sẵn lúc build.
137
- const CLI_PACKAGE_JSON = process.env.AIVIN_CLI_BINARY
138
- ? { version: process.env.AIVIN_CLI_BINARY, engines: {} }
139
- : JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'));
140
-
141
- const CLI_VERSION = CLI_PACKAGE_JSON.version;
142
-
143
- /**
144
- * `aivin start` spawns the plugin project's own installed `@aivin-labs/sdk`'s `bin/server.mjs`,
145
- * which loads `src/main.ts` directly via Node's native TS execution (no separate compile step) -
146
- * the same mechanism this CLI's own `engines.node` field (">=22.0.0") documents as required for
147
- * itself. Node <22 doesn't strip TS types at all, so that failure doesn't surface as anything about
148
- * Node versions - it's a raw loader error ("Unknown file extension \".ts\"") thrown from deep inside
149
- * `server.mjs`, giving no hint that the fix is just "use a newer Node". Check the constraint up
150
- * front instead, once, with a message that says exactly what's wrong and how to fix it.
151
- */
152
- function checkNodeVersion() {
153
- const required = CLI_PACKAGE_JSON.engines?.node;
154
- const requiredMajor = required && parseInt(required.match(/(\d+)/)?.[1], 10);
155
- const currentMajor = parseInt(process.versions.node.split('.')[0], 10);
156
- if (requiredMajor && currentMajor < requiredMajor) {
157
- console.error(
158
- chalk.red(`❌ Node ${process.version} detected - aivin requires Node ${required} (native TypeScript execution).`),
159
- );
160
- console.error(chalk.gray(` Switch versions (e.g. \`nvm use ${requiredMajor}\`) and try again.`));
161
- process.exit(1);
162
- }
163
- }
164
-
165
- /**
166
- * Resolves `bin/server.mjs` from the CURRENT PROJECT's own installed `@aivin-labs/sdk` (not this
167
- * CLI's install location - after the cli/sdk package split those are two different places, and
168
- * `aivin start`/`aivin test` must run whatever sdk version the plugin project actually depends on,
169
- * the same one its own `npm install` resolved). Resolves `@aivin-labs/sdk/package.json` (an
170
- * explicit "./package.json" export, see the sdk's package.json) via Node's normal module resolution
171
- * rooted at the current directory, then derives `bin/server.mjs` from its location by plain path
172
- * math - deliberately not a second module-specifier resolution, since `bin/server.mjs` itself isn't
173
- * (and doesn't need to be) part of the sdk's public `exports` map.
174
- */
175
- function resolveLocalSdkServerPath(currentDir = process.cwd()) {
176
- const localRequire = createRequire(pathToFileURL(path.join(currentDir, 'noop.cjs')).href);
177
- let sdkPackageJsonPath;
178
- try {
179
- sdkPackageJsonPath = localRequire.resolve('@aivin-labs/sdk/package.json');
180
- } catch (error) {
181
- throw new Error(
182
- `Could not find @aivin-labs/sdk installed in ${currentDir} - run \`npm install\` first.`,
183
- { cause: error },
184
- );
185
- }
186
- return path.join(path.dirname(sdkPackageJsonPath), 'bin', 'server.mjs');
187
- }
188
-
189
- const program = new Command();
190
-
191
- program.name('aivin').description('aivin CLI - scaffold, run, and deploy Aivin plugins').version(CLI_VERSION);
192
-
193
- // Command: create plugin
194
- program
195
- .command('create [name]')
196
- .description('Create new plugin')
197
- .option('--json <config>', 'JSON config (AI mode)')
198
- .option('--stdin', 'Read from stdin')
199
- .option('--name <name>', 'Plugin name (if not specified, will prompt)')
200
- .option('--silent', 'Silent mode')
201
- .option('--json-output', 'JSON output')
202
- .action(async (name, options) => {
203
- if (name) options.name = name;
204
- try {
205
- let result;
206
-
207
- if (options.stdin) {
208
- const stdinData = await readStdin();
209
- result = await createFromJSON(stdinData, options);
210
- } else if (options.json) {
211
- result = await createFromJSON(options.json, options);
212
- } else {
213
- result = await createInteractive(options);
214
- }
215
-
216
- if (options.jsonOutput && result) {
217
- console.log(JSON.stringify(result, null, 2));
218
- }
219
- } catch (error) {
220
- if (options.jsonOutput) {
221
- console.log(
222
- JSON.stringify(
223
- {
224
- success: false,
225
- error: error.message,
226
- code: error.code || 'ERROR',
227
- },
228
- null,
229
- 2,
230
- ),
231
- );
232
- } else if (!options.silent) {
233
- console.error(chalk.red('❌'), error.message);
234
- }
235
- process.exit(1);
236
- }
237
- });
238
-
239
- // Command: init plugin - guided one-step replacement for `create` + `plugin make`
240
- program
241
- .command('init [name]')
242
- .description('Set up a new plugin step by step: asks what it should do, then generates real working code from that description')
243
- .option('--name <name>', 'Plugin name (if not specified, will prompt)')
244
- .option('--model <model>', 'LLM model to use for generation')
245
- .option('--provider <provider>', 'LLM provider to use for generation')
246
- .action(async (name, options) => {
247
- if (name) options.name = name;
248
- try {
249
- await initInteractive(options);
250
- } catch (error) {
251
- console.error(chalk.red('❌'), error.message);
252
- process.exit(1);
253
- }
254
- });
255
-
256
- // Command: Validate plugin config
257
- program
258
- .command('validate')
259
- .description('Validate manifest.json in the current directory (or --json/--stdin for scripted use)')
260
- .option('--json <config>', 'JSON config, instead of reading manifest.json from the current directory')
261
- .option('--stdin', 'Read JSON config from stdin, instead of reading manifest.json')
262
- .option('--json-output', 'JSON output')
263
- .action(async (options) => {
264
- try {
265
- let configData;
266
-
267
- if (options.stdin) {
268
- configData = await readStdin();
269
- } else if (options.json) {
270
- configData = options.json;
271
- } else {
272
- // Simple, no-flags default: validate manifest.json in the current directory - the case
273
- // you actually want most of the time (`aivin validate` from inside your plugin project).
274
- // --json/--stdin remain for scripted/CI use where the config isn't a file on disk yet.
275
- const manifestPath = path.join(process.cwd(), 'manifest.json');
276
- if (!fs.existsSync(manifestPath)) {
277
- throw new Error('No manifest.json found in the current directory. Pass --json <config> or --stdin instead.');
278
- }
279
- configData = fs.readFileSync(manifestPath, 'utf8');
280
- }
281
-
282
- // Expand the default { ...commonFields, plugins: [...] } shape and validate every entry -
283
- // flattenManifestFile itself throws on structural problems (empty plugins[], missing
284
- // id/name/func, bare top-level array).
285
- const config = flattenManifestFile(JSON.parse(configData));
286
- const entries = Array.isArray(config) ? config : [config];
287
- const errors = entries.flatMap((entry, i) =>
288
- validatePluginConfig(entry).errors.map((e) =>
289
- entries.length > 1 ? `plugins[${i}] (${entry.name || 'unnamed'}): ${e}` : e,
290
- ),
291
- );
292
- const result = { valid: errors.length === 0, errors };
293
-
294
- if (options.jsonOutput) {
295
- console.log(
296
- JSON.stringify(
297
- {
298
- valid: result.valid,
299
- errors: result.errors,
300
- },
301
- null,
302
- 2,
303
- ),
304
- );
305
- } else {
306
- if (result.valid) {
307
- console.log(chalk.green('✅ Valid'));
308
- } else {
309
- console.log(chalk.red('❌ Invalid:'));
310
- result.errors.forEach((error) => console.log(` • ${error}`));
311
- }
312
- }
313
-
314
- if (!result.valid) process.exit(1);
315
- } catch (error) {
316
- if (options.jsonOutput) {
317
- console.log(JSON.stringify({ valid: false, error: error.message }, null, 2));
318
- } else {
319
- console.error(chalk.red('❌'), error.message);
320
- }
321
- process.exit(1);
322
- }
323
- });
324
-
325
- // Command: start plugin server
326
- program
327
- .command('start')
328
- .description('Start plugin server')
329
- .option('--debug', 'Log every sdk.* call live as it happens (human-readable), not just the final trace summary')
330
- .option('--debug-json', 'Same live per-call logging as --debug, but one JSON object per line on stdout - for a script/coding agent to parse instead of a human')
331
- .option('--no-watch', 'Disable hot-reload - restart manually (Ctrl+C + `aivin start` again) after editing src/ instead')
332
- .action((options) => {
333
- checkNodeVersion();
334
- let serverPath;
335
- try {
336
- serverPath = resolveLocalSdkServerPath();
337
- } catch (error) {
338
- console.error(chalk.red('❌'), error.message);
339
- process.exit(1);
340
- }
341
- const debugEnv = options.debugJson ? { SDK_DEBUG: 'json' } : options.debug ? { SDK_DEBUG: 'true' } : {};
342
- const watchEnv = options.watch === false ? { AIVIN_START_WATCH: 'false' } : {};
343
- const child = spawn('node', [serverPath], {
344
- stdio: 'inherit',
345
- env: { ...process.env, ...debugEnv, ...watchEnv },
346
- });
347
-
348
- child.on('error', (error) => {
349
- console.error(chalk.red('❌'), error.message);
350
- process.exit(1);
351
- });
352
-
353
- child.on('exit', (code) => {
354
- if (code !== 0) {
355
- process.exit(code);
356
- }
357
- });
358
- });
359
-
360
- // Command: deploy plugin to server (always private to your org - see buildDeploymentPayload's
361
- // doc comment above for why there's no public/store-submission scope here)
362
- program
363
- .command('deploy')
364
- .description('Deploy plugin to your org on the Aivin server')
365
- .action(async () => {
366
- try {
367
- await deployPlugin({
368
- endpointPath: '/plugins/deploy',
369
- label: 'Deploying plugin',
370
- });
371
- } catch (error) {
372
- console.error(chalk.red('❌'), error.message);
373
- process.exit(1);
374
- }
375
- });
376
-
377
- // Command: deploy to a throwaway test instance (backend rejects this in production)
378
- program
379
- .command('test')
380
- .description(
381
- 'Deploy to a non-production test instance, then smoke-test it with generated input and save a report to .test/',
382
- )
383
- .option('--workspace <id>', 'Workspace id to run the smoke test against (default: auto-picks your first one)')
384
- .option('--no-smoke-test', 'Only deploy - skip the generated-input invoke test and report')
385
- .option('--verify-proxy', 'Also invoke MCP proxy entries for real (empty input) instead of skipping them - only use if you know the underlying tool(s) have no meaningful side effects')
386
- .action(async (options) => {
387
- try {
388
- await deployPlugin({
389
- endpointPath: '/plugins/test/deploy',
390
- label: 'Deploying to test instance',
391
- smokeTest: options.smokeTest !== false,
392
- workspaceOverride: options.workspace,
393
- verifyProxy: options.verifyProxy,
394
- });
395
- } catch (error) {
396
- console.error(chalk.red('❌'), error.message);
397
- process.exit(1);
398
- }
399
- });
400
-
401
- const pluginCommand = program.command('plugin').description('AI-assisted plugin authoring');
402
-
403
- pluginCommand
404
- .command('search [query]')
405
- .description("Search the platform's plugin ecosystem for something to reuse instead of writing it yourself")
406
- .option('--workspace <id>', 'Restrict to plugins visible in this workspace (default: your whole org)')
407
- .option('--mcp <server_id>', 'List every tool/resource/prompt plugin generated from one MCP server (the id printed by `aivin mcp`/`aivin plugin search`, e.g. "modelcontextprotocol-servers-src-everything") instead of doing a text search')
408
- .option('--store <store_id>', 'Restrict to plugins hosted on one self-hosted plugin store (the id printed by `aivin pluginstore ls`) - combines with the text query/--mcp, not a replacement for them')
409
- .option('--limit <n>', 'Max results to show')
410
- .option('--plain', 'Print a flat list instead of the interactive browser (for scripts/CI)')
411
- .action(async (query, options) => {
412
- try {
413
- // --mcp is an exact-id lookup, not a text search - the query string is optional in that mode.
414
- if (!options.mcp) {
415
- query = await requireArg(query, { prompt: 'What are you looking for?', usage: 'Usage: aivin plugin search "<query>"' });
416
- }
417
- await searchPlugins(query, options);
418
- } catch (error) {
419
- console.error(chalk.red('❌'), error.message);
420
- process.exit(1);
421
- }
422
- });
423
-
424
- pluginCommand
425
- .command('info <id>')
426
- .description("Show one plugin's detail (input/output schema, setup needs) directly by id, no search query needed")
427
- .option('--workspace <id>', 'Restrict to plugins visible in this workspace (default: your whole org)')
428
- .option('--plain', 'Print flat instead of the interactive browser, if falling back to closest-match results')
429
- .action(async (id, options) => {
430
- try {
431
- await showPluginInfo(id, options);
432
- } catch (error) {
433
- console.error(chalk.red('❌'), error.message);
434
- process.exit(1);
435
- }
436
- });
437
-
438
- pluginCommand
439
- .command('ask [mission]')
440
- .description('One-shot: search for the best-matching plugin for a plain-language mission and trigger it right away, like an agent would')
441
- .option('--top <n>', 'How many candidates to consider/print as runner-up context (default 5) - only the top match is ever run')
442
- .option('-i, --input <json>', 'Input fields as a JSON string - skips the interactive field-by-field prompt')
443
- .option('--workspace <id>', 'Workspace id to search/run against (default: auto-picks your first one)')
444
- .option('--agent <id>', 'Agent id to run as, if the plugin needs one for HIL/confirm behavior to be accurate')
445
- .option('--watch-logs', "Also stream the chosen plugin's own live console output inline")
446
- .option('--no-auth-prompt', "Don't offer to connect/configure a missing connector interactively when the run comes back needing one - just print the result and exit")
447
- .option('--save', 'Write this run\'s result to .test/trigger/<timestamp>.json for later --compare')
448
- .option('--compare <file>', 'Diff this run\'s result against a previously --save\'d .test/trigger/*.json file')
449
- .action(async (mission, options) => {
450
- try {
451
- await askPlugin(mission, options);
452
- } catch (error) {
453
- console.error(chalk.red('❌'), error.message);
454
- process.exit(1);
455
- }
456
- });
457
-
458
- pluginCommand
459
- .command('make [description]')
460
- .description('Generate src/main.ts from a natural-language business description')
461
- .option('--model <model>', 'LLM model to use for generation')
462
- .option('--provider <provider>', 'LLM provider to use for generation')
463
- .action(async (description, options) => {
464
- try {
465
- description = await requireArg(description, { prompt: 'What should this plugin do?', usage: 'Usage: aivin plugin make "<description>"' });
466
- await makePluginFromDescription(description, options);
467
- } catch (error) {
468
- console.error(chalk.red('❌'), error.message);
469
- process.exit(1);
470
- }
471
- });
472
-
473
- pluginCommand
474
- .command('convert [hint]')
475
- .description('Turn an existing project in the current directory into an Aivin plugin')
476
- .option('--model <model>', 'LLM model to use for generation')
477
- .option('--provider <provider>', 'LLM provider to use for generation')
478
- .option('--force', 'Re-run conversion even if src/main.ts already exists (e.g. redo a previous bad/stale result)')
479
- .action(async (hint, options) => {
480
- try {
481
- await convertExistingProject(hint, options);
482
- } catch (error) {
483
- console.error(chalk.red('❌'), error.message);
484
- process.exit(1);
485
- }
486
- });
487
-
488
- pluginCommand
489
- .command('trigger [mission] [input]')
490
- .description('Invoke this deployed plugin for real and print the result - like the platform\'s Playground')
491
- .option('--id <pluginId>', 'Plugin id to trigger directly - skips the local manifest.json lookup (e.g. for `aivin mcp` plugins, which have no local project directory)')
492
- .option('--func <name>', 'Which function to trigger, for a multi-function plugin (matches name/func/id) - ignored when --id is given')
493
- .option('--workspace <id>', 'Workspace id to run against (default: auto-picks your first one)')
494
- .option('--agent <id>', 'Agent id to run as, if the plugin needs one for HIL/confirm behavior to be accurate')
495
- .option('--watch-logs', 'Also stream the plugin\'s own live console output inline (same feed as `aivin plugin logs`) instead of needing a second terminal - requires permission to view that plugin\'s logs (your own/org\'s deployments; most store plugins from other orgs will just skip this and fall back to the REST result only)')
496
- .option('--no-auth-prompt', "Don't offer to connect/configure a missing connector interactively when the run comes back needing one - just print the result and exit")
497
- .option('--save', 'Write this run\'s result to .test/trigger/<timestamp>.json for later --compare')
498
- .option('--compare <file>', 'Diff this run\'s result against a previously --save\'d .test/trigger/*.json file')
499
- .action(async (mission, input, options) => {
500
- try {
501
- await triggerPlugin(mission, input, options);
502
- } catch (error) {
503
- console.error(chalk.red('❌'), error.message);
504
- process.exit(1);
505
- }
506
- });
507
-
508
- pluginCommand
509
- .command('logs [pluginId]')
510
- .description('Tail a deployed plugin\'s own console output live (defaults to the current directory\'s manifest.json id)')
511
- .option('--func <name>', 'Which function\'s id to resolve, for a multi-function plugin (only used when pluginId is omitted)')
512
- .action(async (pluginId, options) => {
513
- try {
514
- await streamPluginLogs(pluginId, options);
515
- } catch (error) {
516
- console.error(chalk.red('❌'), error.message);
517
- process.exit(1);
518
- }
519
- });
520
-
521
- pluginCommand
522
- .command('delete [id]')
523
- .description("Delete a plugin you own, or every plugin from one batch deploy at once with --group <groupId> (e.g. everything `aivin mcp <url>` generated in one run - see the group_id it prints after deploying)")
524
- .option('--group <groupId>', 'Delete every plugin sharing this group_id instead of a single plugin by id')
525
- .option('-y, --yes', 'Skip the confirmation prompt (for scripts/CI)')
526
- .action(async (id, options) => {
527
- try {
528
- await deletePluginCmd(id, options);
529
- } catch (error) {
530
- console.error(chalk.red('❌'), error.message);
531
- process.exit(1);
532
- }
533
- });
534
-
535
- const connectorCommand = program.command('connector').description('Register and discover reusable connectors (OAuth apps / credential-form namespaces)');
536
-
537
- connectorCommand
538
- .command('register')
539
- .description('Register a new connector namespace, interactively')
540
- .action(async () => {
541
- try {
542
- await registerConnector();
543
- } catch (error) {
544
- console.error(chalk.red('❌'), error.message);
545
- process.exit(1);
546
- }
547
- });
548
-
549
- connectorCommand
550
- .command('search [query]')
551
- .description("Search connectors for something to reuse instead of registering a new one")
552
- .option('--limit <n>', 'Max results to show')
553
- .option('--plain', 'Print a flat list instead of the interactive browser (for scripts/CI)')
554
- .action(async (query, options) => {
555
- try {
556
- query = await requireArg(query, { prompt: 'What are you looking for?', usage: 'Usage: aivin connector search "<query>"' });
557
- await searchConnectors(query, options);
558
- } catch (error) {
559
- console.error(chalk.red('❌'), error.message);
560
- process.exit(1);
561
- }
562
- });
563
-
564
- connectorCommand
565
- .command('list')
566
- .description('List connectors visible to your org')
567
- .option('--page <n>', 'Page number')
568
- .option('--limit <n>', 'Items per page')
569
- .option('--include-deprecated', "Also show your org's deprecated connectors (hidden by default)")
570
- .option('--plain', 'Print a flat list instead of the interactive browser (for scripts/CI)')
571
- .action(async (options) => {
572
- try {
573
- await listConnectors(options);
574
- } catch (error) {
575
- console.error(chalk.red('❌'), error.message);
576
- process.exit(1);
577
- }
578
- });
579
-
580
- connectorCommand
581
- .command('deprecate [id]')
582
- .description("Hide a connector you own from search/list without breaking plugins already using it")
583
- .action(async (id) => {
584
- try {
585
- id = await requireArg(id, { prompt: 'Connector id to deprecate:', usage: 'Usage: aivin connector deprecate <id>' });
586
- await axios.post(`${connectorBaseUrl()}/connectors/${encodeURIComponent(id)}/deprecate`, {}, connectorAuthHeaders());
587
- console.log(chalk.green(`✅ "${id}" is now deprecated - still usable, hidden from new search/list.`));
588
- } catch (error) {
589
- const message = error.response?.data?.message || error.message;
590
- console.error(chalk.red('❌'), message);
591
- process.exit(1);
592
- }
593
- });
594
-
595
- connectorCommand
596
- .command('undeprecate [id]')
597
- .description('Make a previously-deprecated connector you own discoverable again')
598
- .action(async (id) => {
599
- try {
600
- id = await requireArg(id, { prompt: 'Connector id to un-deprecate:', usage: 'Usage: aivin connector undeprecate <id>' });
601
- await axios.post(`${connectorBaseUrl()}/connectors/${encodeURIComponent(id)}/undeprecate`, {}, connectorAuthHeaders());
602
- console.log(chalk.green(`✅ "${id}" is discoverable again.`));
603
- } catch (error) {
604
- const message = error.response?.data?.message || error.message;
605
- console.error(chalk.red('❌'), message);
606
- process.exit(1);
607
- }
608
- });
609
-
610
- const pluginStoreCommand = program
611
- .command('pluginstore')
612
- .description('Self-hosted aivin-service worker (Docker) - attach it to your org as a plugin store. See docs/GETTING_STARTED.md.');
613
-
614
- pluginStoreCommand
615
- .command('create [store_id]')
616
- .description('Create a new plugin store + attach this machine as its first node')
617
- .option('--label <label>', 'Display label for the store (defaults to store_id)')
618
- .option('--node-label <label>', 'Display label for this node/instance')
619
- .option('--data-dir <path>', 'Where to write worker-identity.json (default: ~/.aivin/service-data)')
620
- .action(async (storeId, options) => {
621
- try {
622
- await createStore(storeId, options);
623
- } catch (error) {
624
- console.error(chalk.red('❌'), error.message);
625
- process.exit(1);
626
- }
627
- });
628
-
629
- pluginStoreCommand
630
- .command('attach [store_id]')
631
- .description('Attach this machine as another node of an existing plugin store')
632
- .option('--node-label <label>', 'Display label for this node/instance')
633
- .option('--data-dir <path>', 'Where to write worker-identity.json (default: ~/.aivin/service-data)')
634
- .action(async (storeId, options) => {
635
- try {
636
- await attachStore(storeId, options);
637
- } catch (error) {
638
- console.error(chalk.red('❌'), error.message);
639
- process.exit(1);
640
- }
641
- });
642
-
643
- pluginStoreCommand
644
- .command('ls')
645
- .description('List plugin stores visible to your org, with online/offline status per node')
646
- .action(async (options) => {
647
- try {
648
- await listStores(options);
649
- } catch (error) {
650
- console.error(chalk.red('❌'), error.message);
651
- process.exit(1);
652
- }
653
- });
654
-
655
- pluginStoreCommand
656
- .command('enable [store_id]')
657
- .description('Enable a store for your org (org admin only)')
658
- .action(async (storeId) => {
659
- try {
660
- storeId = await requireArg(storeId, { prompt: 'Store id to enable:', usage: 'Usage: aivin pluginstore enable <store_id>' });
661
- await setStoreEnabled(storeId, true);
662
- } catch (error) {
663
- console.error(chalk.red('❌'), error.message);
664
- process.exit(1);
665
- }
666
- });
667
-
668
- pluginStoreCommand
669
- .command('disable [store_id]')
670
- .description('Disable a store for your org without deleting it (org admin only)')
671
- .action(async (storeId) => {
672
- try {
673
- storeId = await requireArg(storeId, { prompt: 'Store id to disable:', usage: 'Usage: aivin pluginstore disable <store_id>' });
674
- await setStoreEnabled(storeId, false);
675
- } catch (error) {
676
- console.error(chalk.red('❌'), error.message);
677
- process.exit(1);
678
- }
679
- });
680
-
681
- pluginStoreCommand
682
- .command('rm [store_id]')
683
- .description('Delete a store - revokes EVERY node attached to it, not just this machine (org admin only)')
684
- .option('-y, --yes', 'Skip the confirmation prompt')
685
- .action(async (storeId, options) => {
686
- try {
687
- storeId = await requireArg(storeId, { prompt: 'Store id to delete:', usage: 'Usage: aivin pluginstore rm <store_id>' });
688
- await deleteStore(storeId, options);
689
- } catch (error) {
690
- console.error(chalk.red('❌'), error.message);
691
- process.exit(1);
692
- }
693
- });
694
-
695
- pluginStoreCommand
696
- .command('rm-node [store_id] [node_id]')
697
- .description('Remove one node from a store (e.g. one that never came online) without touching its other nodes - org admin not required')
698
- .option('-y, --yes', 'Skip the confirmation prompt')
699
- .action(async (storeId, nodeId, options) => {
700
- try {
701
- await removeNode(storeId, nodeId, options);
702
- } catch (error) {
703
- console.error(chalk.red('❌'), error.message);
704
- process.exit(1);
705
- }
706
- });
707
-
708
- pluginStoreCommand
709
- .command('detach')
710
- .description("Remove THIS machine's pairing only (local file only, no BE call) - the running aivin-service picks it up automatically")
711
- .option('--data-dir <path>', 'Where worker-identity.json lives (default: ~/.aivin/service-data)')
712
- .action((options) => {
713
- try {
714
- detachStore(options);
715
- } catch (error) {
716
- console.error(chalk.red('❌'), error.message);
717
- process.exit(1);
718
- }
719
- });
720
-
721
- const mcpCommand = program
722
- .command('mcp')
723
- .description('MCP proxy plugins - wrap an external MCP server tool/resource/prompt, no code required');
724
-
725
- mcpCommand
726
- .argument('[url]', 'GitHub/GitLab/npm/Smithery URL, or a live MCP server URL, to scan and convert')
727
- .option('--publish', 'Deploy to your org, then submit for community store review (needs admin approval)')
728
- .option('--private', 'Deploy to your org only - default')
729
- .option('--org', 'Alias of --private - there is no narrower per-workspace scope today')
730
- .option('--quiet', 'Skip live progress output while scanning (on by default otherwise)')
731
- .option('--auth', 'Đánh dấu MCP này cần credential -> BE sinh connection_id, CLI hỏi gắn connector (OAuth HOẶC credential_form tuỳ chọn lúc đó). Dùng cho MCP cần API key/token mà scan không tự nhận ra')
732
- .option('--oauth', 'Bí danh cũ của --auth (giữ để không phá lệnh đã dùng)')
733
- .option('--test-token <token>', 'Access token dùng THỬ để đọc tool của remote MCP cần OAuth (Notion/Slack/Linear/Figma...). Chỉ dùng lúc quét, KHÔNG lưu lại - xem test_token trong plugin-store.proto')
734
- .option('-y, --yes', 'Skip the deploy confirmation prompt (required in non-TTY/CI contexts, which otherwise now refuse to deploy at all - see scanAndPublishMcp)')
735
- .action(async (url, options) => {
736
- try {
737
- url = await requireArg(url, {
738
- prompt: 'GitHub/GitLab/npm/Smithery URL, or a live MCP server URL:',
739
- usage: 'Usage: aivin mcp <url> [--publish|--private|--org]',
740
- });
741
- await scanAndPublishMcp(url, options);
742
- } catch (error) {
743
- console.error(chalk.red('❌'), error.message);
744
- process.exit(1);
745
- }
746
- });
747
-
748
- mcpCommand
749
- .command('create [name]')
750
- .description('Scaffold a manifest-only plugin that proxies to an external MCP server')
751
- .option('--transport <transport>', 'stdio | sse')
752
- .option('--command <command>', 'Command to launch the MCP server (stdio transport)')
753
- .option('--args <args>', 'Space-separated args for --command (stdio transport)')
754
- .option('--url <url>', 'Remote MCP server URL (sse transport)')
755
- .option('--kind <kind>', 'tool | resource | prompt (default: tool)')
756
- .option('--tool-name <name>', 'MCP tool name (kind=tool)')
757
- .option('--resource-uri <uri>', 'MCP resource URI (kind=resource)')
758
- .option('--resource-mime-type <mime>', 'MIME type of the resource (kind=resource)')
759
- .option('--prompt-name <name>', 'MCP prompt name (kind=prompt)')
760
- .option('--description <description>', 'Plugin description')
761
- .option(
762
- '--auth-secret-key <key>',
763
- 'Name of the workspace secret to use as the token/credential, if the MCP server needs auth',
764
- )
765
- .option('--auth-type <type>', 'auth_type value to send (default: "bearer" when --auth-secret-key is set) - check your backend for which values it supports')
766
- .option('--connector <id>', "Existing connector id for this plugin's connection_id (readiness/\"needs login\" display only - does NOT inject anything into the running MCP server; run with no flags for the interactive per-variable auth setup that actually does)")
767
- .action(async (name, options) => {
768
- try {
769
- name = await requireArg(name, { prompt: 'Plugin name (lowercase letters, numbers, hyphens):', usage: 'Usage: aivin mcp create <name>' });
770
- await createMcpProxyPlugin(name, options);
771
- } catch (error) {
772
- console.error(chalk.red('❌'), error.message);
773
- process.exit(1);
774
- }
775
- });
776
-
777
- mcpCommand
778
- .command('watch [url]')
779
- .description('Watch a GitHub repo/branch and auto-rescan+resync its plugins when the branch updates (checked server-side every ~5 min, no CLI process needs to stay running)')
780
- .option('--branch <name>', "Branch to watch (default: the repo's default branch)")
781
- .option('--list', 'List your watched repos instead of registering a new one')
782
- .action(async (url, options) => {
783
- try {
784
- if (options.list) {
785
- await listMcpWatches();
786
- return;
787
- }
788
- url = await requireArg(url, {
789
- prompt: 'GitHub repo URL to watch:',
790
- usage: 'Usage: aivin mcp watch <url> [--branch <name>] | aivin mcp watch --list',
791
- });
792
- await registerMcpWatch(url, options);
793
- } catch (error) {
794
- console.error(chalk.red('❌'), error.message);
795
- process.exit(1);
796
- }
797
- });
798
-
799
- mcpCommand
800
- .command('unwatch <url>')
801
- .description('Stop auto-resyncing a previously watched repo')
802
- .option('--branch <name>', 'Branch to unwatch (default: all watched branches for this repo)')
803
- .action(async (url, options) => {
804
- try {
805
- await unwatchMcp(url, options);
806
- } catch (error) {
807
- console.error(chalk.red('❌'), error.message);
808
- process.exit(1);
809
- }
810
- });
811
-
812
- program
813
- .command('login')
814
- .argument('[baseUrl]', 'Server to log into (REST API base) - defaults to production (api.aivin.cloud). Pass a staging/self-hosted host to switch the machine\'s active context to it, e.g. `aivin login beta-api.aivin.vn`.')
815
- .description('Log in and save an API key for plugin deployment (opens your browser by default)')
816
- .option('-k, --api-key <key>', 'Set API key directly (skip login entirely)')
817
- .option('--basic', 'Log in with email/password directly in the terminal instead of a browser')
818
- .option('--google', 'Alias of the default browser flow - pick Google once the page opens')
819
- .option('--client <client>', 'Client/org id to use with --basic (default: "aivin.cloud")')
820
- .action(async (baseUrl, options) => {
821
- try {
822
- // Bare hostname (no scheme) is the common case for a quick `aivin login beta-api.aivin.vn` -
823
- // assume https, same as every other *.aivin.* endpoint in this file.
824
- const resolvedBaseUrl = baseUrl ? (/^https?:\/\//.test(baseUrl) ? baseUrl : `https://${baseUrl}`) : DEFAULT_AIVIN_BASE_URL;
825
- process.env.AIVIN_BASE_URL = resolvedBaseUrl;
826
-
827
- if (options.apiKey) {
828
- console.log(chalk.blue('🔑 Setting API key...'));
829
- // Best-effort - `aivin whoami` reads straight from the saved file with no server calls of
830
- // its own, so whatever identity is resolvable here is all it will ever have to show.
831
- const identity = await tryFetchWhoami(resolvedBaseUrl, options.apiKey);
832
- const sdkEndpoint = saveGlobalApiKey(options.apiKey, resolvedBaseUrl, identity);
833
- console.log(chalk.green('✅ API key set successfully!'));
834
- console.log(chalk.gray(` Active context: ${resolvedBaseUrl}${sdkEndpoint ? ` (SDK_ENDPOINT: ${sdkEndpoint})` : ''}`));
835
- console.log(chalk.green(`💾 Saved to ${GLOBAL_CREDENTIALS_PATH} - every project on this machine now targets this server.`));
836
- return;
837
- }
838
-
839
- // Only the browser flow needs a web app URL - fetch it from the backend itself (not needed/
840
- // fetched for --basic, which never touches AIVIN_WEB_URL at all). Same override precedence
841
- // as everywhere else: a caller-set AIVIN_WEB_URL (project .env/shell) always wins.
842
- if (!options.basic && !process.env.AIVIN_WEB_URL) {
843
- const webUrl = await fetchWebUrl(resolvedBaseUrl);
844
- if (webUrl) {
845
- process.env.AIVIN_WEB_URL = webUrl;
846
- } else {
847
- // fetchWebUrl swallows its own errors (bad host, typo'd domain, TLS/DNS failure) and
848
- // returns null - warn instead of silently opening the PRODUCTION web app's login page,
849
- // which would mint a key for the wrong server without any indication why.
850
- console.log(chalk.yellow(`⚠️ Couldn't reach ${resolvedBaseUrl} to resolve its web app URL - check the host is correct.`));
851
- console.log(chalk.yellow(` Falling back to the production web app (https://brain.aivin.cloud) - the key it mints will still be saved against ${resolvedBaseUrl}, likely NOT what you want.`));
852
- }
853
- }
854
-
855
- const apiKey = options.basic ? await basicLogin(options) : await browserLogin();
856
-
857
- console.log(chalk.green('✅ Login successful!'));
858
- const identity = await tryFetchWhoami(resolvedBaseUrl, apiKey);
859
- const sdkEndpoint = saveGlobalApiKey(apiKey, resolvedBaseUrl, identity);
860
- console.log(chalk.gray(` Active context: ${resolvedBaseUrl}${sdkEndpoint ? ` (SDK_ENDPOINT: ${sdkEndpoint})` : ''}`));
861
- console.log(chalk.green(`💾 Saved to ${GLOBAL_CREDENTIALS_PATH} - every project on this machine now targets this server.`));
862
- } catch (error) {
863
- console.log(chalk.red('❌ Login failed:'), error.message);
864
- process.exit(1);
865
- }
866
- });
867
-
868
- program
869
- .command('logout')
870
- .description('Clear the saved API key on this machine (~/.aivin/credentials) - run `aivin login` again to log back in')
871
- .action(() => {
872
- try {
873
- // Captured BEFORE clearing so we can tell whether the currently-effective API_KEY (already
874
- // loaded into process.env at startup - see the dotenv/loadActiveContext precedence block at
875
- // the top of this file) came from this file or from a project's own .env, which logout never
876
- // touches.
877
- const savedContext = loadActiveContext();
878
- const cleared = clearActiveContext();
879
- if (cleared) {
880
- console.log(chalk.green(`✅ Logged out - removed ${GLOBAL_CREDENTIALS_PATH}`));
881
- } else {
882
- console.log(chalk.gray('Already logged out - no saved credentials found.'));
883
- }
884
- if (process.env.API_KEY && process.env.API_KEY !== savedContext?.api_key) {
885
- console.log(chalk.gray(" Note: this directory still has its own API_KEY set (from a project .env or shell env) - unset that too if you want it fully logged out here."));
886
- }
887
- } catch (error) {
888
- console.error(chalk.red('❌'), error.message);
889
- process.exit(1);
890
- }
891
- });
892
-
893
- program
894
- .command('whoami')
895
- .description('Show which account is currently logged in on this machine (reads ~/.aivin/credentials - no server call)')
896
- .action(() => {
897
- try {
898
- const apiKey = requireSavedApiKey();
899
- const serverUrl = process.env.AIVIN_BASE_URL || DEFAULT_AIVIN_BASE_URL;
900
- const localClient = parseApiKeyClient(apiKey);
901
-
902
- // The effective API_KEY may come from a project's own .env instead of `~/.aivin/credentials`
903
- // (see the dotenv precedence near the top of this file) - identity/login time only exist in
904
- // the latter, so a project .env override has nothing to show beyond the key's own client id.
905
- const savedContext = loadActiveContext();
906
- const fromSavedContext = savedContext?.api_key === apiKey;
907
- const identity = fromSavedContext ? savedContext : {};
908
-
909
- console.log(chalk.green('✅ Logged in'));
910
- console.log(chalk.gray(' Email: ') + (identity.email || chalk.gray('unknown')));
911
- console.log(chalk.gray(' Name: ') + (identity.name || chalk.gray('unknown')));
912
- console.log(chalk.gray(' Org: ') + (identity.org_name || identity.client || localClient || chalk.gray('unknown')));
913
- if (identity.org_domain) console.log(chalk.gray(' Domain: ') + identity.org_domain);
914
- console.log(chalk.gray(' Server: ') + serverUrl);
915
- if (fromSavedContext && savedContext.logged_in_at) {
916
- console.log(chalk.gray(' Logged in at: ') + new Date(savedContext.logged_in_at).toLocaleString());
917
- } else if (!fromSavedContext) {
918
- console.log(chalk.gray(" (API_KEY is from this project's .env, not `aivin login` - no recorded identity/login time)"));
919
- } else if (!identity.email) {
920
- console.log(chalk.gray(' (Account info wasn\'t resolvable at login time - run `aivin login` again to refresh it)'));
921
- }
922
- } catch (error) {
923
- console.error(chalk.red('❌'), error.message);
924
- process.exit(1);
925
- }
926
- });
927
-
928
- const keyCommand = program.command('key').description('Manage named API keys for your account');
929
-
930
- keyCommand
931
- .command('gen [name]')
932
- .description('Create (or replace) a named API key for your account - shown only once')
933
- .option('--save', 'Also save this key as this machine\'s default (~/.aivin/credentials), like `aivin login -k`')
934
- .action(async (name, options) => {
935
- try {
936
- name = await requireArg(name, { prompt: 'Name for this API key:', usage: 'Usage: aivin key gen <name>' });
937
- console.log(chalk.blue(`🔑 Creating API key "${name}"...`));
938
- const plainKey = await generateApiKey(name);
939
- console.log(chalk.green('✅ API key created!'));
940
- console.log(chalk.yellow('🔑 Key:'), chalk.cyan(plainKey));
941
- console.log(chalk.gray(' This is shown only once - store it somewhere safe.'));
942
- if (options.save) {
943
- const serverUrl = process.env.AIVIN_BASE_URL || DEFAULT_AIVIN_BASE_URL;
944
- const identity = await tryFetchWhoami(serverUrl, plainKey);
945
- saveGlobalApiKey(plainKey, serverUrl, identity);
946
- console.log(chalk.green(`💾 Saved to ${GLOBAL_CREDENTIALS_PATH} - every project on this machine can use it now.`));
947
- }
948
- } catch (error) {
949
- console.error(chalk.red('❌'), error.message);
950
- process.exit(1);
951
- }
952
- });
953
-
954
- keyCommand
955
- .command('revoke [name]')
956
- .description('Revoke a named API key for your account')
957
- .action(async (name) => {
958
- try {
959
- name = await requireArg(name, { prompt: 'Name of the API key to revoke:', usage: 'Usage: aivin key revoke <name>' });
960
- console.log(chalk.blue(`🔑 Revoking API key "${name}"...`));
961
- await revokeApiKeyByName(name);
962
- console.log(chalk.green(`✅ API key "${name}" revoked.`));
963
- } catch (error) {
964
- console.error(chalk.red('❌'), error.message);
965
- process.exit(1);
966
- }
967
- });
968
-
969
- keyCommand
970
- .command('list')
971
- .description('List API keys on your account')
972
- .action(async () => {
973
- try {
974
- const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
975
- const apiKey = requireSavedApiKey();
976
- await logAccountIdentity(serverUrl, apiKey);
977
- const items = await listRemoteApiKeys(serverUrl, apiKey);
978
- if (items.length === 0) {
979
- console.log(chalk.gray('No API keys found.'));
980
- return;
981
- }
982
- items.forEach((k) => {
983
- const created = k.created_at ? new Date(k.created_at).toISOString() : 'unknown';
984
- console.log(` ${chalk.cyan(k.name)} ${chalk.gray(`(created ${created})`)}`);
985
- });
986
- } catch (error) {
987
- console.error(chalk.red('❌'), error.message);
988
- process.exit(1);
989
- }
990
- });
991
-
992
- program
993
- .command('browser [mission]')
994
- .description("Run an AI Browser mission - by default opens/reuses a local browser window dedicated to AI Browser (own profile, own cookies - log in once, watch missions run live from then on); --remote uses a server-side browser instead")
995
- .option('--remote', 'Use a server-side pooled browser instead of your own local one (no local browser needed, no cookies/logins carried over)')
996
- .option('--debug-port <port>', 'Local mode only: port to look for/launch your browser\'s remote debugging on (default: 9222, auto-tries a few nearby ports if that one is taken by something else) - pass this to pin an exact port instead')
997
- .option('--browser <edge|chrome>', "Local mode only: which browser to drive - default: auto-detects your OS's actual default browser, falling back to whichever of Edge/Chrome is installed if that can't be determined")
998
- .option('--url <url>', "Local mode only: open this URL before the mission starts, instead of a blank page - skips a wasted first analysis step and avoids the AI having to search the web to find the target site itself (auto-guessed for a few well-known sites mentioned by name in the mission if omitted)")
999
- .option('--workspace <id>', 'Workspace id to run in (default: your personal workspace)')
1000
- .option('--project <id>', 'Project id within the workspace (--remote only)')
1001
- .option('--agent <id>', "Agent id to run as (default: an auto-created/cached agent for local mode, or the workspace's default agent for --remote) - AI Browser is triggered as a tool this agent uses, real HIL suspend/resume requires an agent context")
1002
- .option('--no-watch', 'Fire the mission and return immediately - skip streaming live progress and auto-opening the viewer')
1003
- .option('--view', 'Just (re)open the fullscreen interactive viewer for whatever HIL session is already active - no mission is started')
1004
- .action(async (mission, options) => {
1005
- try {
1006
- if (!options.view) {
1007
- mission = await requireArg(mission, {
1008
- prompt: 'What should the AI Browser do?',
1009
- usage: 'Usage: aivin browser "<mission detail>" (or: aivin browser --view to just reopen the interactive viewer)',
1010
- });
1011
- }
1012
- await runBrowserMission(mission, options);
1013
- } catch (error) {
1014
- console.error(chalk.red('❌'), error.message);
1015
- process.exit(1);
1016
- }
1017
- });
1018
-
1019
- program
1020
- .command('update')
1021
- .description('Update aivin to the latest release (installs from get.aivin.vn; checks the release signature, the SHA256 and that the new build starts)')
1022
- .option('--check', 'Only check whether a newer release exists')
1023
- .option('--to <version>', 'Install this release instead of the latest, e.g. v1.0.9 (also allows going back)')
1024
- .option('--auto <on|off>', 'Turn background updates of `aivin remote start` on or off for this computer')
1025
- .option('--proxy <url>', 'HTTP proxy to download through (default: HTTPS_PROXY, else the system proxy setting; "none" = connect directly)')
1026
- .action(async (options) => {
1027
- try {
1028
- if (options.auto !== undefined) {
1029
- const value = String(options.auto).toLowerCase();
1030
- if (!['on', 'off'].includes(value)) throw new Error('Dùng: aivin update --auto on|off');
1031
- saveUpdateSettings({ auto: value === 'on' });
1032
- console.log(chalk.green(value === 'on' ? '✅ Đã bật tự cập nhật nền.' : '✅ Đã tắt tự cập nhật nền — cập nhật bằng `aivin update` khi cần.'));
1033
- return;
1034
- }
1035
- configureProxy({ explicit: options.proxy });
1036
- if (isStandaloneBinary()) cleanupRetired();
1037
- const root = downloadRoot();
1038
- const res = await installUpdate({ version: options.to, root, check: !!options.check, force: !!options.to });
1039
- if (res.status === UpdateStatus.UP_TO_DATE) return console.log(chalk.green(`✅ aivin ${res.current} là bản mới nhất.`));
1040
- if (res.status === UpdateStatus.NOT_BINARY) {
1041
- return console.log(chalk.yellow(`⬆ Có aivin ${res.latest} (máy này ${res.current}). Bản cài qua npm: npm i -g @aivin-labs/cli@latest`));
1042
- }
1043
- if (res.status === UpdateStatus.AVAILABLE) return console.log(chalk.yellow(`⬆ Có aivin ${res.latest} (máy này ${res.current}) — chạy \`aivin update\` để cài.`));
1044
- if (res.status === UpdateStatus.SKIPPED) {
1045
- return console.log(chalk.yellow(`⚠️ Máy này đã tự lùi khỏi aivin ${res.latest} (khởi động hỏng). Vẫn muốn cài: aivin update --to ${res.latest}`));
1046
- }
1047
- if (res.status === UpdateStatus.BUSY) return console.log(chalk.yellow('⏳ Đang có một lần cập nhật khác chạy trên máy này — thử lại sau ít phút.'));
1048
- console.log(chalk.green(`✅ Đã cài aivin ${res.latest} (trước đó ${res.current}).`));
1049
- console.log(chalk.gray(' `aivin remote start` chạy nền (tự khởi động cùng máy) tự chuyển sang bản mới khi máy rảnh; cửa sổ đang mở thì đóng và chạy lại.'));
1050
- } catch (error) {
1051
- console.error(chalk.red('❌'), error.message);
1052
- process.exit(1);
1053
- }
1054
- });
1055
-
1056
- const remoteCommand = program
1057
- .command('remote')
1058
- .description('Let your Aivin agents work on this computer (Device Agent) - pair, run the listener, manage memory and safety')
1059
- // Proxy công ty cho mọi lệnh remote gọi máy chủ (ghép máy, remote do, test…) — `start` tự cấu hình kèm --proxy của nó.
1060
- .hook('preAction', (_cmd, action) => { if (action.name() !== 'start') configureProxy({ explicit: action.opts().proxy }); });
1061
-
1062
- const remoteFail = (error) => {
1063
- console.error(chalk.red('❌'), error.message);
1064
- process.exit(1);
1065
- };
1066
-
1067
- remoteCommand
1068
- .command('start')
1069
- .description('Pair this computer (first time) and listen for work from your agents in the foreground')
1070
- .option('--dir <path>', 'Folder the agent may work in (default: the folder saved at pairing, else the current folder)')
1071
- .option('--name <name>', 'Name shown for this computer (default: hostname)')
1072
- .option('--repair', 'Pair again (new device token; the old one stops working)')
1073
- .option('--full-access', 'Let the agent work anywhere on this computer (all drives; relative paths start at your home folder). Kept across restarts; --dir switches back to one folder')
1074
- .option('--code <code>', 'Pair with a one-time code from Aivin (chat box → Browser ▾ → Add this computer) - no `aivin login` needed')
1075
- .option('--server <url>', 'Aivin server the code belongs to (Aivin prints it in the command when needed)')
1076
- .option('--no-browser', "Don't let AI Browser use a browser window on this computer (web tasks then run in Aivin's server-side browser)")
1077
- .option('--no-gui', "Don't let the agent control app windows on this computer with the mouse/keyboard (Windows)")
1078
- .option('--separate-browser', "Always use Aivin's own browser window, never your everyday Chrome/Edge (even if remote debugging is enabled at chrome://inspect/#remote-debugging)")
1079
- .option('--quiet', 'No interactive logs')
1080
- .option('--proxy <url>', 'HTTP proxy to reach Aivin through (default: HTTPS_PROXY, else the system proxy setting; "none" = connect directly)')
1081
- .option('--no-keep-awake', "Don't keep this computer from sleeping while the agent is working on it")
1082
- .option('--no-auto-update', "Don't download new aivin releases in the background this run (to turn it off for good: aivin update --auto off)")
1083
- .option('--no-mascot', "Don't show the Aivin mascot on screen this run (to turn it off for good: aivin remote mascot off)")
1084
- .option('--multi-user', "Organization cloud computer (Linux container provisioned by Aivin): token from AIVIN_DEVICE_TOKEN/AIVIN_DEVICE_ID/AIVIN_SERVER, every org member works in their own Linux account + home folder")
1085
- .action(async (options) => {
1086
- try {
1087
- await startRemoteClient(options);
1088
- } catch (error) {
1089
- // Tự khởi động (--quiet) mà đã có cửa sổ khác nhận việc: không phải lỗi — thoát 0 để trình giữ chạy không chạy lại mãi.
1090
- if (error?.code === DAEMON_RUNNING && options.quiet) {
1091
- console.error(chalk.gray(error.message));
1092
- process.exit(0);
1093
- }
1094
- // Vừa tự lùi bản: có trình giữ chạy → mã 75, được mở lại ngay bằng bản cũ.
1095
- if (error?.code === UPDATE_ROLLED_BACK) {
1096
- console.error(chalk.yellow(`↩ ${error.message}`));
1097
- process.exit(error.restart ? RESTART_EXIT_CODE : 1);
1098
- }
1099
- remoteFail(error);
1100
- }
1101
- });
1102
-
1103
- remoteCommand
1104
- .command('pair')
1105
- .description('Pair (or re-pair) this computer with your account without starting the listener')
1106
- .option('--dir <path>', 'Folder the agent may work in (default: current folder)')
1107
- .option('--name <name>', 'Name shown for this computer (default: hostname)')
1108
- .action(async (options) => {
1109
- try {
1110
- const roots = [path.resolve(options.dir || process.cwd())];
1111
- const creds = await pairDevice({ serverUrl: missionServerUrl(), apiKey: process.env.API_KEY, roots, name: options.name, profile: buildDeviceProfile(roots) });
1112
- console.log(chalk.green(`✅ Đã ghép máy "${creds.name}" (${creds.device_id})`));
1113
- console.log(chalk.gray(` Thư mục được phép: ${creds.roots.join(' | ')}`));
1114
- console.log(chalk.gray(' Chạy `aivin remote start` để bắt đầu nhận việc.'));
1115
- } catch (error) {
1116
- remoteFail(error);
1117
- }
1118
- });
1119
-
1120
- remoteCommand
1121
- .command('devices')
1122
- .description('List computers paired with your account and whether they are online')
1123
- .action(async () => {
1124
- try {
1125
- const devices = await listDevices({ serverUrl: missionServerUrl(), apiKey: process.env.API_KEY });
1126
- const mine = loadDeviceCredentials()?.device_id;
1127
- if (!devices.length) return console.log(chalk.gray('Chưa có máy nào được ghép. Chạy `aivin remote start` trên máy cần dùng.'));
1128
- for (const d of devices) {
1129
- const state = d.online ? chalk.green('● online') : chalk.gray('○ offline');
1130
- console.log(`${state} ${chalk.bold(d.name)}${d.device_id === mine ? chalk.cyan(' (máy này)') : ''} ${chalk.gray(`${d.platform || ''} · ${d.tools_count} công cụ · ${d.device_id}`)}`);
1131
- }
1132
- } catch (error) {
1133
- remoteFail(error);
1134
- }
1135
- });
1136
-
1137
- remoteCommand
1138
- .command('unpair [deviceId]')
1139
- .description('Revoke a paired computer (default: this one) - its token stops working immediately')
1140
- .action(async (deviceId) => {
1141
- try {
1142
- const target = deviceId || loadDeviceCredentials()?.device_id;
1143
- if (!target) throw new Error('Máy này chưa được ghép.');
1144
- await unpairDevice({ serverUrl: missionServerUrl(), apiKey: process.env.API_KEY, deviceId: target });
1145
- console.log(chalk.green(`✅ Đã thu hồi máy ${target}.`));
1146
- } catch (error) {
1147
- remoteFail(error);
1148
- }
1149
- });
1150
-
1151
- remoteCommand
1152
- .command('pause')
1153
- .description('Kill switch: refuse every remote call on this computer until `aivin remote resume`')
1154
- .action(() => {
1155
- setRemotePaused(true);
1156
- console.log(chalk.yellow('⏸ Đã tạm dừng — máy này từ chối mọi việc từ xa.'));
1157
- });
1158
-
1159
- remoteCommand
1160
- .command('mascot [action]')
1161
- .description('The Aivin mascot floating on screen while the listener runs (Windows): on | off — no argument shows the current setting')
1162
- .action((action) => {
1163
- const lang = mascotLang();
1164
- if (action && !['on', 'off'].includes(action)) remoteFail(new Error(mascotText(lang, MascotText.CMD_USAGE)));
1165
- if (process.platform !== 'win32') console.log(chalk.gray(mascotText(lang, MascotText.CMD_UNSUPPORTED)));
1166
- if (!action) return console.log(mascotText(lang, loadMascotSettings().enabled ? MascotText.CMD_STATUS_ON : MascotText.CMD_STATUS_OFF));
1167
- saveMascotSettings({ enabled: action === 'on' });
1168
- console.log(chalk.green(`✅ ${mascotText(lang, action === 'on' ? MascotText.CMD_ON : MascotText.CMD_OFF)}`));
1169
- });
1170
-
1171
- remoteCommand
1172
- .command('policy [action] [value]')
1173
- .description('Rules enforced on this computer itself (Aivin cannot change them): which steps need a click on this computer, tools turned off, extra blocked commands')
1174
- .action(async (action, value) => {
1175
- try {
1176
- await runPolicyCommand(action, value);
1177
- } catch (error) {
1178
- remoteFail(error);
1179
- }
1180
- });
1181
-
1182
- remoteCommand
1183
- .command('resume')
1184
- .description('Turn the kill switch off')
1185
- .action(() => {
1186
- setRemotePaused(false);
1187
- console.log(chalk.green('▶ Máy này nhận việc từ xa trở lại.'));
1188
- });
1189
-
1190
- remoteCommand
1191
- .command('enable')
1192
- .description('Start the listener automatically when this computer starts')
1193
- .option('--dir <path>', 'Folder the agent may work in (default: current folder)')
1194
- .option('--proxy <url>', 'HTTP proxy the auto-started listener should use (default: detect at every start)')
1195
- .action((options) => {
1196
- try {
1197
- const res = enableAutoStart(options);
1198
- console.log(chalk.green('✅ Đã bật tự khởi động cùng máy.'));
1199
- console.log(chalk.gray(` Thư mục: ${res.rootDir}`));
1200
- console.log(chalk.gray(` Tệp khởi động: ${res.filePath}`));
1201
- if (res.warning) console.log(chalk.yellow(` ⚠️ ${res.warning}`));
1202
- } catch (error) {
1203
- remoteFail(error);
1204
- }
1205
- });
1206
-
1207
- remoteCommand
1208
- .command('disable')
1209
- .description('Stop starting the listener with this computer')
1210
- .action(() => {
1211
- try {
1212
- disableAutoStart();
1213
- console.log(chalk.green('✅ Đã tắt tự khởi động cùng máy.'));
1214
- } catch (error) {
1215
- remoteFail(error);
1216
- }
1217
- });
1218
-
1219
- remoteCommand
1220
- .command('status')
1221
- .description('Show pairing, allowed folders, kill switch, auto-start, tools and memory of this computer')
1222
- .action(() => {
1223
- try {
1224
- const creds = loadDeviceCredentials();
1225
- const roots = creds?.roots?.length ? creds.roots : [process.cwd()];
1226
- const profile = buildDeviceProfile(roots);
1227
- const { catalog, hash } = buildCatalog(buildTools({ roots, binaries: profile.binaries, projects: profile.projects }));
1228
- const stats = memoryStats();
1229
- console.log(chalk.blue('💻 Máy này:'));
1230
- console.log(chalk.gray(` Mã máy: ${getOrCreateDeviceId()}`));
1231
- console.log(chalk.gray(` Đã ghép: ${creds ? chalk.green(`có — ${creds.name} @ ${creds.server_url}`) : chalk.yellow('chưa')}`));
1232
- console.log(chalk.gray(` Thư mục: ${roots.join(' | ')}`));
1233
- console.log(chalk.gray(` Công tắc ngắt: ${isRemotePaused() ? chalk.yellow('ĐANG TẠM DỪNG') : 'tắt'}`));
1234
- console.log(chalk.gray(` Tự khởi động: ${getAutoStartStatus().enabled ? 'bật' : 'tắt'}`));
1235
- console.log(chalk.gray(` Chương trình: ${profile.binaries.join(', ') || '-'}`));
1236
- console.log(chalk.gray(` Dự án: ${profile.projects.map((p) => `${p.name} (${p.kind})`).join(', ') || '-'}`));
1237
- console.log(chalk.gray(` Ghi nhớ: ${stats.total} mục (${stats.with_vector} có vector) — ${stats.dir}`));
1238
- console.log(chalk.blue(`\n🛠️ ${catalog.length} công cụ (dấu vân tay ${hash.slice(0, 12)}):`));
1239
- for (const t of catalog) console.log(` - ${chalk.cyan(t.name)}${t.read_only ? chalk.gray(' [chỉ đọc]') : t.destructive ? chalk.red(' [không hoàn tác]') : chalk.yellow(' [ghi]')}`);
1240
- } catch (error) {
1241
- remoteFail(error);
1242
- }
1243
- });
1244
-
1245
- remoteCommand
1246
- .command('test')
1247
- .description('Check the server connection and whether the server sees this computer online')
1248
- .action(async () => {
1249
- try {
1250
- const r = await testRemoteConnection();
1251
- console.log(chalk.gray(` Máy chủ: ${r.serverUrl} — ${r.httpOk ? chalk.green(`thông (${r.latencyMs} ms)`) : chalk.red('không kết nối được')}`));
1252
- console.log(chalk.gray(` Đã ghép: ${r.paired ? `có (${r.deviceId})` : chalk.yellow('chưa — chạy aivin remote start')}`));
1253
- if (r.online !== null) console.log(chalk.gray(` Online: ${r.online ? chalk.green('có') : chalk.yellow(r.registered === false ? 'máy chủ không có máy này (đã thu hồi?)' : 'không — chạy aivin remote start')}`));
1254
- if (r.error) console.log(chalk.yellow(` ⚠️ ${r.error}`));
1255
- } catch (error) {
1256
- remoteFail(error);
1257
- }
1258
- });
1259
-
1260
- remoteCommand
1261
- .command('logs')
1262
- .description('Recent remote activity on this computer')
1263
- .option('--limit <n>', 'Entries to show (default 30)', '30')
1264
- .option('--clear', 'Clear the activity log')
1265
- .action((options) => {
1266
- if (options.clear) {
1267
- clearLogs();
1268
- return console.log(chalk.green('✅ Đã xoá nhật ký.'));
1269
- }
1270
- const logs = getRecentLogs(options.limit);
1271
- if (!logs.length) return console.log(chalk.gray('Chưa có hoạt động nào.'));
1272
- for (const log of logs) {
1273
- const time = log.timestamp ? new Date(log.timestamp).toLocaleTimeString() : '';
1274
- if (log.type === 'tool_call') console.log(` [${time}] ${log.success ? chalk.green('✓') : chalk.red('✗')} ${chalk.cyan(log.tool)}${log.ms !== undefined ? chalk.gray(` ${log.ms} ms`) : ''} ${log.error ? chalk.red(log.error) : ''}`);
1275
- else console.log(` [${time}] ${chalk.gray(log.type)} ${chalk.gray(log.reason || log.serverUrl || '')}`);
1276
- }
1277
- });
1278
-
1279
- remoteCommand
1280
- .command('memory [action] [value...]')
1281
- .description('On-device memory (~/.aivin/memory/*.yaml): list [kind] | search <words> | add <text> | forget <id> | clear [kind]')
1282
- .option('--kind <kind>', `Kind: ${Object.values(MemoryKind).join(', ')}`)
1283
- .option('--key <key>', 'Stable key for add (default: derived from the text)')
1284
- .action((action = 'list', valueParts = [], options) => {
1285
- try {
1286
- const value = valueParts.join(' ').trim();
1287
- if (action === 'search') {
1288
- if (!value) throw new Error('Dùng: aivin remote memory search <từ khoá>');
1289
- const hits = searchMemory({ query: value, kinds: options.kind ? [options.kind] : undefined, limit: 20 });
1290
- if (!hits.length) return console.log(chalk.gray('Không có mục nào khớp.'));
1291
- hits.forEach((h) => console.log(` ${chalk.gray(h.id)} [${h.kind}] ${chalk.bold(h.key)}: ${h.text}`));
1292
- return;
1293
- }
1294
- if (action === 'add') {
1295
- if (!value) throw new Error('Dùng: aivin remote memory add "<nội dung>" --kind fact --key <khoá>');
1296
- const kind = options.kind || MemoryKind.FACT;
1297
- const key = options.key || value.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').slice(0, 60);
1298
- putMemoryItems([{ kind, key, text: value }]);
1299
- return console.log(chalk.green(`✅ Đã nhớ [${kind}] ${key}`));
1300
- }
1301
- if (action === 'forget') {
1302
- if (!value) throw new Error('Dùng: aivin remote memory forget <id> (xem id bằng memory list / search)');
1303
- const res = deleteMemoryItems({ ids: value.split(/[\s,]+/) });
1304
- return console.log(chalk.green(`✅ Đã quên ${res.deleted} mục.`));
1305
- }
1306
- if (action === 'clear') {
1307
- clearDeviceMemory(value || options.kind || undefined);
1308
- return console.log(chalk.green('✅ Đã xoá bộ nhớ.'));
1309
- }
1310
- const page = listMemoryItems({ kind: value || options.kind, limit: 100 });
1311
- const stats = memoryStats();
1312
- console.log(chalk.blue(`🧠 Bộ nhớ trên máy: ${stats.total} mục — ${stats.dir} (sửa tay các tệp .yaml được)`));
1313
- page.items.forEach((i) => console.log(` ${chalk.gray(i.id)} [${i.kind}] ${chalk.bold(i.key)}: ${String(i.text).slice(0, 160)}`));
1314
- if (page.next_cursor !== null) console.log(chalk.gray(` … còn ${page.total - page.items.length} mục`));
1315
- } catch (error) {
1316
- remoteFail(error);
1317
- }
1318
- });
1319
-
1320
- remoteCommand
1321
- .command('reindex')
1322
- .description('Rebuild the file index of the allowed folders now')
1323
- .action(async () => {
1324
- try {
1325
- const creds = loadDeviceCredentials();
1326
- const index = createFileIndex(indexRootsFor(creds?.roots || [process.cwd()], creds?.access === DeviceAccess.FULL));
1327
- const stats = await index.build();
1328
- index.close();
1329
- console.log(chalk.green(`✅ Chỉ mục: ${stats.files} tệp (${stats.updated} cập nhật, ${stats.removed} bỏ) trong ${stats.ms} ms`));
1330
- } catch (error) {
1331
- remoteFail(error);
1332
- }
1333
- });
1334
-
1335
- remoteCommand
1336
- .command('reset-id')
1337
- .description('Give this computer a new device id (cloned machines) - you must pair again')
1338
- .action(() => {
1339
- const id = resetDeviceId();
1340
- console.log(chalk.green(`✅ Mã máy mới: ${id} — chạy \`aivin remote start\` để ghép lại.`));
1341
- });
1342
-
1343
- remoteCommand
1344
- .command('do [objective]')
1345
- .description('Give a job to the Device Agent on your computer (the listener must be running there)')
1346
- .option('--device <name>', 'Which paired computer (default: your online one)')
1347
- .option('--cwd <path>', 'Folder the job is about')
1348
- .option('--file <id...>', 'Aivin workspace file id(s) the job may save onto the computer')
1349
- .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1350
- .option('--agent <id>', 'Agent to act as (default: the workspace default agent)')
1351
- .option('--no-watch', 'Do not stream progress')
1352
- .action(async (objective, options) => {
1353
- try {
1354
- objective = await requireArg(objective, { prompt: 'What should the agent do on your computer?', usage: 'Usage: aivin remote do "<job>"' });
1355
- await runRemoteMission(objective, options);
1356
- } catch (error) {
1357
- remoteFail(error);
1358
- }
1359
- });
1360
-
1361
- const doCommand = program
1362
- .command('do [agentNickname] [mission]')
1363
- .description("Have <agentNickname> work toward a goal in the background - not a specific deployed plugin")
1364
- .option('--workspace <id>', 'Workspace id to run in (default: your personal workspace)')
1365
- .option('--project <id>', 'Project id within the workspace')
1366
- .option('--no-watch', 'Fire the mission and return immediately - skip streaming live progress')
1367
- .action(async (agentNickname, mission, options) => {
1368
- try {
1369
- mission = await requireArg(mission, {
1370
- prompt: 'What should the agent do?',
1371
- usage: 'Usage: aivin do <agent_nickname> "<mission detail>" (or: aivin do job "<automation job description>")',
1372
- });
1373
- await runMission(agentNickname, mission, options);
1374
- } catch (error) {
1375
- console.error(chalk.red('❌'), error.message);
1376
- process.exit(1);
1377
- }
1378
- });
1379
-
1380
- doCommand
1381
- .command('job [description]')
1382
- .description('Create a new automation job from a plain-language description')
1383
- .option('--workspace <id>', 'Workspace id to create the job in (default: your personal workspace)')
1384
- .option('--project <id>', 'Project id within the workspace')
1385
- .option('--agent <id>', "Agent id the job runs as (default: the workspace's default agent)")
1386
- .option('--schedule <condition>', 'Natural-language schedule, e.g. "every Monday at 9am" (default: let the platform infer one)')
1387
- .action(async (description, options) => {
1388
- try {
1389
- description = await requireArg(description, { prompt: 'What should this automation job do?', usage: 'Usage: aivin do job "<automation job description>"' });
1390
- await createAutomationJob(description, options);
1391
- } catch (error) {
1392
- console.error(chalk.red('❌'), error.message);
1393
- process.exit(1);
1394
- }
1395
- });
1396
-
1397
- const taskCommand = program
1398
- .command('task [description]')
1399
- .description('Create a new task from a plain-language description')
1400
- .option('--workspace <id>', 'Workspace id to create the task in (default: your personal workspace)')
1401
- .option('--project <id>', 'Project id within the workspace')
1402
- .option('--assignee <userId>', 'User id to assign the task to (default: unassigned)')
1403
- .action(async (description, options) => {
1404
- try {
1405
- description = await requireArg(description, {
1406
- prompt: 'What is this task?',
1407
- usage: 'Usage: aivin task "<description>" (or: aivin task list/mine/get/update/delete)',
1408
- });
1409
- await createTask(description, options);
1410
- } catch (error) {
1411
- console.error(chalk.red('❌'), error.message);
1412
- process.exit(1);
1413
- }
1414
- });
1415
-
1416
- taskCommand
1417
- .command('list')
1418
- .description('List tasks in a project')
1419
- .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1420
- .option('--project <id>', "Project id (default: the workspace's first project)")
1421
- .option('--status <status>', 'Filter by status (todo/doing/done/backlog/cancel)')
1422
- .option('--assignee <userId>', 'Filter by assignee user id')
1423
- .option('--search <text>', 'Filter by search text')
1424
- .action(async (options) => {
1425
- try {
1426
- await listTasks(options);
1427
- } catch (error) {
1428
- console.error(chalk.red('❌'), error.message);
1429
- process.exit(1);
1430
- }
1431
- });
1432
-
1433
- taskCommand
1434
- .command('mine')
1435
- .description('List tasks assigned to you in a project')
1436
- .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1437
- .option('--project <id>', "Project id (default: the workspace's first project)")
1438
- .action(async (options) => {
1439
- try {
1440
- await listMyTasks(options);
1441
- } catch (error) {
1442
- console.error(chalk.red('❌'), error.message);
1443
- process.exit(1);
1444
- }
1445
- });
1446
-
1447
- taskCommand
1448
- .command('get [id]')
1449
- .description('Get a task by id')
1450
- .action(async (id) => {
1451
- try {
1452
- id = await requireArg(id, { prompt: 'Task id:', usage: 'Usage: aivin task get <id>' });
1453
- await getTaskById(id);
1454
- } catch (error) {
1455
- console.error(chalk.red('❌'), error.message);
1456
- process.exit(1);
1457
- }
1458
- });
1459
-
1460
- taskCommand
1461
- .command('update [id]')
1462
- .description('Update a task')
1463
- .option('--status <status>', 'todo|doing|done|backlog|cancel')
1464
- .option('--title <title>', 'New title')
1465
- .option('--description <text>', 'New content/description')
1466
- .option('--assignee <userId>', 'Reassign to this user id')
1467
- .option('--priority <priority>', 'low|medium|high|urgent')
1468
- .action(async (id, options) => {
1469
- try {
1470
- id = await requireArg(id, { prompt: 'Task id:', usage: 'Usage: aivin task update <id>' });
1471
- await updateTaskById(id, options);
1472
- } catch (error) {
1473
- console.error(chalk.red('❌'), error.message);
1474
- process.exit(1);
1475
- }
1476
- });
1477
-
1478
- taskCommand
1479
- .command('delete [id]')
1480
- .description('Delete a task')
1481
- .option('-y, --yes', 'Skip the confirmation prompt (for scripts/CI)')
1482
- .action(async (id, options) => {
1483
- try {
1484
- id = await requireArg(id, { prompt: 'Task id to delete:', usage: 'Usage: aivin task delete <id>' });
1485
- await deleteTaskById(id, options);
1486
- } catch (error) {
1487
- console.error(chalk.red('❌'), error.message);
1488
- process.exit(1);
1489
- }
1490
- });
1491
-
1492
- program
1493
- .command('workspace')
1494
- .description('Browse your workspaces and projects, and pick one to use with --workspace/--project')
1495
- .option('--plain', 'Print a flat list instead of the interactive picker (for scripts/CI)')
1496
- .action(async (options) => {
1497
- try {
1498
- await pickWorkspaceAndProject(options);
1499
- } catch (error) {
1500
- console.error(chalk.red('❌'), error.message);
1501
- process.exit(1);
1502
- }
1503
- });
1504
-
1505
- const agentCommand = program.command('agent').description('List, search, install, create, and publish AI Staff agents');
1506
-
1507
- agentCommand
1508
- .command('list')
1509
- .description('Browse agents already installed in a workspace (↑/↓ to move, space/enter for details, q to quit)')
1510
- .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1511
- .option('--plain', 'Print a flat list instead of the interactive browser (for scripts/CI)')
1512
- .action(async (options) => {
1513
- try {
1514
- await listAgentsCmd(options);
1515
- } catch (error) {
1516
- console.error(chalk.red('❌'), error.message);
1517
- process.exit(1);
1518
- }
1519
- });
1520
-
1521
- agentCommand
1522
- .command('search [query]')
1523
- .description('Search the AI Staff marketplace for an agent')
1524
- .option('--workspace <id>', 'Workspace id for context (default: your personal workspace)')
1525
- .option('--limit <n>', 'Max results to show')
1526
- .action(async (query, options) => {
1527
- try {
1528
- query = await requireArg(query, { prompt: 'What are you looking for?', usage: 'Usage: aivin agent search "<query>"' });
1529
- const serverUrl = missionServerUrl();
1530
- const authHeaders = missionAuthHeaders();
1531
- const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
1532
- const results = await searchAgents(serverUrl, authHeaders, {
1533
- query,
1534
- workspaceId: workspace.id || workspace._id,
1535
- limit: options.limit,
1536
- });
1537
- if (results.length === 0) {
1538
- console.log(chalk.yellow(`No agents found matching "${query}".`));
1539
- return;
1540
- }
1541
- console.log(chalk.blue(`Found ${results.length} agent(s) matching "${query}":\n`));
1542
- results.forEach((a) => {
1543
- console.log(chalk.bold(a.nickname || a.name) + chalk.gray(` (${a.id})`));
1544
- if (a.bio) console.log(` ${a.bio}`);
1545
- console.log();
1546
- });
1547
- } catch (error) {
1548
- console.error(chalk.red('❌'), error.message);
1549
- process.exit(1);
1550
- }
1551
- });
1552
-
1553
- agentCommand
1554
- .command('install [query]')
1555
- .description('Search the marketplace and install an agent into a workspace')
1556
- .option('--workspace <id>', 'Workspace id to install into (default: your personal workspace)')
1557
- .action(async (query, options) => {
1558
- try {
1559
- const serverUrl = missionServerUrl();
1560
- const authHeaders = missionAuthHeaders();
1561
- const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
1562
- const workspaceId = workspace.id || workspace._id;
1563
-
1564
- let picked;
1565
- if (query) {
1566
- const results = await searchAgents(serverUrl, authHeaders, { query, workspaceId, limit: 10 });
1567
- if (results.length === 0) throw new Error(`No marketplace agents found matching "${query}".`);
1568
- if (!process.stdout.isTTY || !process.stdin.isTTY) {
1569
- picked = results[0];
1570
- } else {
1571
- const { pickedAgent } = await inquirer.prompt([
1572
- {
1573
- type: 'select',
1574
- name: 'pickedAgent',
1575
- message: 'Install which agent?',
1576
- choices: results.map((a) => ({ name: `${a.nickname || a.name}${a.bio ? chalk.gray(` - ${a.bio}`) : ''}`, value: a })),
1577
- },
1578
- ]);
1579
- picked = pickedAgent;
1580
- }
1581
- } else {
1582
- picked = await installAgentInteractive(serverUrl, authHeaders, workspaceId);
1583
- console.log(chalk.gray(`Installed into ${workspace.name || workspaceId}.`));
1584
- return;
1585
- }
1586
-
1587
- await pullAgentIntoWorkspace(serverUrl, authHeaders, { agentId: picked.id, workspaceId });
1588
- console.log(chalk.green(`✅ Installed "${picked.nickname || picked.name}" into ${workspace.name || workspaceId}.`));
1589
- } catch (error) {
1590
- console.error(chalk.red('❌'), error.message);
1591
- process.exit(1);
1592
- }
1593
- });
1594
-
1595
- agentCommand
1596
- .command('make')
1597
- .description('Create a brand new AI Staff agent')
1598
- .option('--name <name>', 'Agent name')
1599
- .option('--nickname <nickname>', 'Agent nickname (used to @-mention/target it)')
1600
- .option('--email <email>', 'Agent email')
1601
- .option('--bio <bio>', 'Short bio')
1602
- .option('--workspace <id>', 'Workspace to install the new agent into (default: your personal workspace)')
1603
- .action(async (options) => {
1604
- try {
1605
- const serverUrl = missionServerUrl();
1606
- const authHeaders = missionAuthHeaders();
1607
- const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
1608
-
1609
- const canPrompt = process.stdout.isTTY && process.stdin.isTTY;
1610
- const answers = { name: options.name, nickname: options.nickname, email: options.email, bio: options.bio };
1611
- if ((!answers.name || !answers.nickname || !answers.email) && canPrompt) {
1612
- const prompted = await inquirer.prompt(
1613
- [
1614
- !answers.name && { type: 'input', name: 'name', message: 'Agent name:', validate: (v) => v.trim().length > 0 || 'Required' },
1615
- !answers.nickname && {
1616
- type: 'input',
1617
- name: 'nickname',
1618
- message: 'Agent nickname (used to @-mention/target it):',
1619
- validate: (v) => v.trim().length > 0 || 'Required',
1620
- },
1621
- !answers.email && { type: 'input', name: 'email', message: 'Agent email:', validate: (v) => v.trim().length > 0 || 'Required' },
1622
- !answers.bio && { type: 'input', name: 'bio', message: 'Short bio (optional):' },
1623
- ].filter(Boolean),
1624
- );
1625
- Object.assign(answers, prompted);
1626
- }
1627
- if (!answers.name || !answers.nickname || !answers.email) {
1628
- throw new Error('Usage: aivin agent make --name <name> --nickname <nickname> --email <email> [--bio <bio>]');
1629
- }
1630
-
1631
- const agent = await createAgent(serverUrl, authHeaders, { ...answers, workspaceId: workspace.id || workspace._id });
1632
- console.log(chalk.green(`✅ Created agent "${agent.nickname || agent.name}"!`));
1633
- if (agent.id) console.log(chalk.gray(` ID: ${agent.id}`));
1634
- } catch (error) {
1635
- console.error(chalk.red('❌'), error.message);
1636
- process.exit(1);
1637
- }
1638
- });
1639
-
1640
- agentCommand
1641
- .command('publish [agentId]')
1642
- .description('Publish an agent you own to the marketplace')
1643
- .option('--workspace <id>', 'Workspace the agent lives in (default: your personal workspace)')
1644
- .action(async (agentId, options) => {
1645
- try {
1646
- const serverUrl = missionServerUrl();
1647
- const authHeaders = missionAuthHeaders();
1648
- const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
1649
-
1650
- if (!agentId) {
1651
- const agents = workspace.agents || [];
1652
- if (agents.length === 0) throw new Error(`Workspace "${workspace.name}" has no agents to publish.`);
1653
- if (!process.stdout.isTTY || !process.stdin.isTTY) {
1654
- throw new Error('Usage: aivin agent publish <agentId>');
1655
- }
1656
- const { pickedAgentId } = await inquirer.prompt([
1657
- {
1658
- type: 'select',
1659
- name: 'pickedAgentId',
1660
- message: 'Publish which agent?',
1661
- choices: agents.map((a) => ({ name: a.nickname || a.name || a.id, value: a.id || a.agent_id })),
1662
- },
1663
- ]);
1664
- agentId = pickedAgentId;
1665
- }
1666
-
1667
- await publishAgent(serverUrl, authHeaders, { agentId, workspaceId: workspace.id || workspace._id });
1668
- console.log(chalk.green(`✅ Published agent ${agentId} to the marketplace.`));
1669
- } catch (error) {
1670
- console.error(chalk.red('❌'), error.message);
1671
- process.exit(1);
1672
- }
1673
- });
1674
-
1675
- const projectCommand = program.command('project').description('List, create, update, and delete projects within a workspace');
1676
-
1677
- projectCommand
1678
- .command('list')
1679
- .description('List projects in a workspace')
1680
- .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1681
- .action(async (options) => {
1682
- try {
1683
- await listProjectsCmd(options);
1684
- } catch (error) {
1685
- console.error(chalk.red('❌'), error.message);
1686
- process.exit(1);
1687
- }
1688
- });
1689
-
1690
- projectCommand
1691
- .command('create [name]')
1692
- .description('Create a new project in a workspace')
1693
- .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1694
- .action(async (name, options) => {
1695
- try {
1696
- name = await requireArg(name, { prompt: 'Project name:', usage: 'Usage: aivin project create <name>' });
1697
- await createProjectCmd(name, options);
1698
- } catch (error) {
1699
- console.error(chalk.red('❌'), error.message);
1700
- process.exit(1);
1701
- }
1702
- });
1703
-
1704
- projectCommand
1705
- .command('update [id]')
1706
- .description('Update a project (currently: rename)')
1707
- .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1708
- .option('--name <name>', 'New name')
1709
- .action(async (id, options) => {
1710
- try {
1711
- id = await requireArg(id, { prompt: 'Project id:', usage: 'Usage: aivin project update <id> --name <new name>' });
1712
- await updateProjectCmd(id, options);
1713
- } catch (error) {
1714
- console.error(chalk.red('❌'), error.message);
1715
- process.exit(1);
1716
- }
1717
- });
1718
-
1719
- projectCommand
1720
- .command('delete [id]')
1721
- .description('Delete a project')
1722
- .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1723
- .option('-y, --yes', 'Skip the confirmation prompt (for scripts/CI)')
1724
- .action(async (id, options) => {
1725
- try {
1726
- id = await requireArg(id, { prompt: 'Project id to delete:', usage: 'Usage: aivin project delete <id>' });
1727
- await deleteProjectCmd(id, options);
1728
- } catch (error) {
1729
- console.error(chalk.red('❌'), error.message);
1730
- process.exit(1);
1731
- }
1732
- });
1733
-
1734
- export {
1735
- validatePluginConfig,
1736
- incrementVersion,
1737
- validateMcpProxyConfig,
1738
- buildDeploymentPayload,
1739
- buildMcpManifest,
1740
- parseMcpArgs,
1741
- guessConnectorQueryFromEnvVarName,
1742
- setFieldConnector,
1743
- buildRegisterConnectorDto,
1744
- buildCreateTaskPayload,
1745
- buildDeviceProfile,
1746
- buildTools,
1747
- buildCatalog,
1748
- enableAutoStart,
1749
- disableAutoStart,
1750
- getAutoStartStatus,
1751
- resetDeviceId,
1752
- getRecentLogs,
1753
- clearLogs,
1754
- testRemoteConnection,
1755
- runRemoteMission,
1756
- };
1757
-
1758
- // Only parse argv when run directly (`aivin ...` / `node bin/cli.mjs ...`),
1759
- // not when this module is imported (e.g. by tests) - otherwise Commander
1760
- // would parse the importing process's argv and could call process.exit().
1761
- //
1762
- // `import.meta.url` is always the module's real (symlink-resolved) path, but `process.argv[1]` is
1763
- // whatever literal path launched it - through `npm link`'s global shim that's a symlink
1764
- // (~/AppData/Roaming/npm/node_modules/@aivin-labs/sdk/bin/cli.mjs -> this repo), which would never
1765
- // string-equal the resolved URL and silently skip program.parse() entirely (global `aivin` would
1766
- // do nothing at all). Resolve argv[1] through the same symlink before comparing.
1767
- function resolveIsMain() {
1768
- // Tệp chạy đóng gói: chính nó là chương trình, không có chuyện bị import.
1769
- if (process.env.AIVIN_CLI_BINARY) return true;
1770
- if (!process.argv[1]) return false;
1771
- try {
1772
- return import.meta.url === pathToFileURL(fs.realpathSync(process.argv[1])).href;
1773
- } catch {
1774
- return import.meta.url === pathToFileURL(process.argv[1]).href;
1775
- }
1776
- }
1777
-
1778
- if (resolveIsMain()) {
1779
- program.parse(process.argv);
1780
- }
1
+ #!/usr/bin/env node
2
+
3
+ import { Command } from 'commander';
4
+ import chalk from 'chalk';
5
+ import fs from 'fs';
6
+ import path from 'path';
7
+ import inquirer from 'inquirer';
8
+ import { spawn } from 'child_process';
9
+ import axios from 'axios';
10
+ import dotenv from 'dotenv';
11
+ import { fileURLToPath, pathToFileURL } from 'url';
12
+ import { dirname } from 'path';
13
+ import { createRequire } from 'module';
14
+ // Same flatten logic PluginServer.ts uses for local/production runtime resolution - re-exported
15
+ // from the installed @aivin-labs/sdk (not vendored here) so deploy and runtime agree on exactly
16
+ // the same rules for what manifest.json's { ...commonFields, plugins: [...] } authoring shape
17
+ // expands into.
18
+ import { flattenManifestFile } from '@aivin-labs/sdk';
19
+
20
+ // Side-effect only import - installs the global Ctrl+C → abort-in-flight-requests wiring
21
+ // (`bin/lib/cancellation.mjs`) once, before any command runs. Must load before any lib file below
22
+ // makes its first axios call so the interceptor is already in place.
23
+ import './lib/cancellation.mjs';
24
+
25
+ import { DEFAULT_AIVIN_BASE_URL, GLOBAL_CREDENTIALS_PATH, fetchWebUrl, loadActiveContext, clearActiveContext } from './lib/context.mjs';
26
+ import { requireArg } from './lib/util.mjs';
27
+ import { readStdin, createFromJSON, createInteractive, validatePluginConfig, validateMcpProxyConfig } from './lib/scaffold.mjs';
28
+ import { buildDeploymentPayload, deployPlugin, incrementVersion } from './lib/deploy.mjs';
29
+ import { initInteractive, makePluginFromDescription, convertExistingProject } from './lib/codegen.mjs';
30
+ import { searchPlugins, showPluginInfo, askPlugin, streamPluginLogs, triggerPlugin, deletePluginCmd } from './lib/pluginTrigger.mjs';
31
+ import { connectorAuthHeaders, connectorBaseUrl, listConnectors, registerConnector, searchConnectors, buildRegisterConnectorDto } from './lib/connectors.mjs';
32
+ import { attachStore, createStore, deleteStore, detachStore, listStores, removeNode, setStoreEnabled } from './lib/store.mjs';
33
+ import { buildMcpManifest, parseMcpArgs, guessConnectorQueryFromEnvVarName, createMcpProxyPlugin, scanAndPublishMcp, registerMcpWatch, unwatchMcp, listMcpWatches, setFieldConnector } from './lib/mcpProxy.mjs';
34
+ import {
35
+ saveGlobalApiKey,
36
+ browserLogin,
37
+ basicLogin,
38
+ requireSavedApiKey,
39
+ logAccountIdentity,
40
+ listRemoteApiKeys,
41
+ generateApiKey,
42
+ revokeApiKeyByName,
43
+ tryFetchWhoami,
44
+ parseApiKeyClient,
45
+ } from './lib/auth.mjs';
46
+ import {
47
+ missionAuthHeaders,
48
+ missionServerUrl,
49
+ resolveWorkspace,
50
+ searchAgents,
51
+ pullAgentIntoWorkspace,
52
+ createAgent,
53
+ publishAgent,
54
+ installAgentInteractive,
55
+ listAgentsCmd,
56
+ } from './lib/workspace.mjs';
57
+ import { runMission, runBrowserMission } from './lib/mission.mjs';
58
+ import { DeviceAccess } from './lib/remote/constants.mjs';
59
+ import { configureProxy } from './lib/remote/netProxy.mjs';
60
+ import { DAEMON_RUNNING } from './lib/remote/daemonLock.mjs';
61
+ import { runPolicyCommand } from './lib/remote/policyCommand.mjs';
62
+ import { loadMascotSettings, saveMascotSettings } from './lib/remote/mascot/index.mjs';
63
+ import { MascotText, mascotLang, mascotText } from './lib/remote/mascot/strings.mjs';
64
+ import { UiResult, showMascotDemo, showMascotUi } from './lib/remote/mascot/ui.mjs';
65
+ import { desktopAppStatus, installDesktopApp, uninstallDesktopApp } from './lib/remote/autoStart.mjs';
66
+ import { createMeetingManager, requestMeeting } from './lib/remote/meeting/index.mjs';
67
+ import { DEFAULT_HOTKEYS, hotkeyCandidates, parseHotkey, probeHotkey } from './lib/remote/mascot/hotkey.mjs';
68
+ import { RESTART_EXIT_CODE, UPDATE_ROLLED_BACK, UpdateStatus, cleanupRetired, downloadRoot, installUpdate, isStandaloneBinary, saveUpdateSettings } from './lib/selfUpdate.mjs';
69
+ import {
70
+ createAutomationJob,
71
+ listTasks,
72
+ listMyTasks,
73
+ getTaskById,
74
+ updateTaskById,
75
+ deleteTaskById,
76
+ createTask,
77
+ buildCreateTaskPayload,
78
+ pickWorkspaceAndProject,
79
+ createProjectCmd,
80
+ updateProjectCmd,
81
+ deleteProjectCmd,
82
+ listProjectsCmd,
83
+ } from './lib/tasks.mjs';
84
+ import {
85
+ startRemoteClient,
86
+ testRemoteConnection,
87
+ enableAutoStart,
88
+ disableAutoStart,
89
+ getAutoStartStatus,
90
+ buildDeviceProfile,
91
+ buildTools,
92
+ buildCatalog,
93
+ getOrCreateDeviceId,
94
+ resetDeviceId,
95
+ loadDeviceCredentials,
96
+ pairDevice,
97
+ listDevices,
98
+ unpairDevice,
99
+ isRemotePaused,
100
+ setRemotePaused,
101
+ getRecentLogs,
102
+ clearLogs,
103
+ memoryStats,
104
+ listMemoryItems,
105
+ searchMemory,
106
+ putMemoryItems,
107
+ deleteMemoryItems,
108
+ clearDeviceMemory,
109
+ createFileIndex,
110
+ indexRootsFor,
111
+ runRemoteMission,
112
+ MemoryKind,
113
+ } from './lib/remoteControl.mjs';
114
+
115
+ // Load env vars: the current project's `.env` first (any deliberate per-project override), THEN
116
+ // fill in AIVIN_BASE_URL/API_KEY/SDK_ENDPOINT from the machine's active context if the project
117
+ // didn't set them. `dotenv.config()` never overrides a variable that's already set, so a project's
118
+ // own `.env` (or a real shell env var) always wins over the global context, exactly like before -
119
+ // but nothing requires a project to have a `.env` at all anymore for the common single-context case.
120
+ // `quiet: true` - otherwise dotenv prints an "injected env" tip line to stdout on every run, which
121
+ // would corrupt `--json-output` mode (meant for clean, parseable JSON on stdout).
122
+ dotenv.config({ quiet: true });
123
+
124
+ {
125
+ const activeContext = loadActiveContext();
126
+ if (activeContext) {
127
+ if (!process.env.AIVIN_BASE_URL) process.env.AIVIN_BASE_URL = activeContext.base_url;
128
+ if (!process.env.API_KEY) process.env.API_KEY = activeContext.api_key;
129
+ if (!process.env.SDK_ENDPOINT && activeContext.sdk_endpoint) process.env.SDK_ENDPOINT = activeContext.sdk_endpoint;
130
+ }
131
+ }
132
+
133
+ const __filename = fileURLToPath(import.meta.url);
134
+
135
+ const __dirname = dirname(__filename);
136
+
137
+ // This CLI's own version (`aivin --version`) - distinct from whatever @aivin-labs/sdk version a
138
+ // given plugin project has installed. See lib/scaffold.mjs for how a fresh scaffold's `@aivin-labs/
139
+ // sdk` dependency pin is resolved (from the actually-installed sdk, not from here).
140
+ // Bản tệp chạy đóng gói (scripts/build-binary.mjs) không có package.json trên đĩa — phiên bản được ghi sẵn lúc build.
141
+ const CLI_PACKAGE_JSON = process.env.AIVIN_CLI_BINARY
142
+ ? { version: process.env.AIVIN_CLI_BINARY, engines: {} }
143
+ : JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'));
144
+
145
+ const CLI_VERSION = CLI_PACKAGE_JSON.version;
146
+
147
+ /**
148
+ * `aivin start` spawns the plugin project's own installed `@aivin-labs/sdk`'s `bin/server.mjs`,
149
+ * which loads `src/main.ts` directly via Node's native TS execution (no separate compile step) -
150
+ * the same mechanism this CLI's own `engines.node` field (">=22.0.0") documents as required for
151
+ * itself. Node <22 doesn't strip TS types at all, so that failure doesn't surface as anything about
152
+ * Node versions - it's a raw loader error ("Unknown file extension \".ts\"") thrown from deep inside
153
+ * `server.mjs`, giving no hint that the fix is just "use a newer Node". Check the constraint up
154
+ * front instead, once, with a message that says exactly what's wrong and how to fix it.
155
+ */
156
+ function checkNodeVersion() {
157
+ const required = CLI_PACKAGE_JSON.engines?.node;
158
+ const requiredMajor = required && parseInt(required.match(/(\d+)/)?.[1], 10);
159
+ const currentMajor = parseInt(process.versions.node.split('.')[0], 10);
160
+ if (requiredMajor && currentMajor < requiredMajor) {
161
+ console.error(
162
+ chalk.red(`❌ Node ${process.version} detected - aivin requires Node ${required} (native TypeScript execution).`),
163
+ );
164
+ console.error(chalk.gray(` Switch versions (e.g. \`nvm use ${requiredMajor}\`) and try again.`));
165
+ process.exit(1);
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Resolves `bin/server.mjs` from the CURRENT PROJECT's own installed `@aivin-labs/sdk` (not this
171
+ * CLI's install location - after the cli/sdk package split those are two different places, and
172
+ * `aivin start`/`aivin test` must run whatever sdk version the plugin project actually depends on,
173
+ * the same one its own `npm install` resolved). Resolves `@aivin-labs/sdk/package.json` (an
174
+ * explicit "./package.json" export, see the sdk's package.json) via Node's normal module resolution
175
+ * rooted at the current directory, then derives `bin/server.mjs` from its location by plain path
176
+ * math - deliberately not a second module-specifier resolution, since `bin/server.mjs` itself isn't
177
+ * (and doesn't need to be) part of the sdk's public `exports` map.
178
+ */
179
+ function resolveLocalSdkServerPath(currentDir = process.cwd()) {
180
+ const localRequire = createRequire(pathToFileURL(path.join(currentDir, 'noop.cjs')).href);
181
+ let sdkPackageJsonPath;
182
+ try {
183
+ sdkPackageJsonPath = localRequire.resolve('@aivin-labs/sdk/package.json');
184
+ } catch (error) {
185
+ throw new Error(
186
+ `Could not find @aivin-labs/sdk installed in ${currentDir} - run \`npm install\` first.`,
187
+ { cause: error },
188
+ );
189
+ }
190
+ return path.join(path.dirname(sdkPackageJsonPath), 'bin', 'server.mjs');
191
+ }
192
+
193
+ const program = new Command();
194
+
195
+ program.name('aivin').description('aivin CLI - scaffold, run, and deploy Aivin plugins').version(CLI_VERSION);
196
+
197
+ // Command: create plugin
198
+ program
199
+ .command('create [name]')
200
+ .description('Create new plugin')
201
+ .option('--json <config>', 'JSON config (AI mode)')
202
+ .option('--stdin', 'Read from stdin')
203
+ .option('--name <name>', 'Plugin name (if not specified, will prompt)')
204
+ .option('--silent', 'Silent mode')
205
+ .option('--json-output', 'JSON output')
206
+ .action(async (name, options) => {
207
+ if (name) options.name = name;
208
+ try {
209
+ let result;
210
+
211
+ if (options.stdin) {
212
+ const stdinData = await readStdin();
213
+ result = await createFromJSON(stdinData, options);
214
+ } else if (options.json) {
215
+ result = await createFromJSON(options.json, options);
216
+ } else {
217
+ result = await createInteractive(options);
218
+ }
219
+
220
+ if (options.jsonOutput && result) {
221
+ console.log(JSON.stringify(result, null, 2));
222
+ }
223
+ } catch (error) {
224
+ if (options.jsonOutput) {
225
+ console.log(
226
+ JSON.stringify(
227
+ {
228
+ success: false,
229
+ error: error.message,
230
+ code: error.code || 'ERROR',
231
+ },
232
+ null,
233
+ 2,
234
+ ),
235
+ );
236
+ } else if (!options.silent) {
237
+ console.error(chalk.red('❌'), error.message);
238
+ }
239
+ process.exit(1);
240
+ }
241
+ });
242
+
243
+ // Command: init plugin - guided one-step replacement for `create` + `plugin make`
244
+ program
245
+ .command('init [name]')
246
+ .description('Set up a new plugin step by step: asks what it should do, then generates real working code from that description')
247
+ .option('--name <name>', 'Plugin name (if not specified, will prompt)')
248
+ .option('--model <model>', 'LLM model to use for generation')
249
+ .option('--provider <provider>', 'LLM provider to use for generation')
250
+ .action(async (name, options) => {
251
+ if (name) options.name = name;
252
+ try {
253
+ await initInteractive(options);
254
+ } catch (error) {
255
+ console.error(chalk.red('❌'), error.message);
256
+ process.exit(1);
257
+ }
258
+ });
259
+
260
+ // Command: Validate plugin config
261
+ program
262
+ .command('validate')
263
+ .description('Validate manifest.json in the current directory (or --json/--stdin for scripted use)')
264
+ .option('--json <config>', 'JSON config, instead of reading manifest.json from the current directory')
265
+ .option('--stdin', 'Read JSON config from stdin, instead of reading manifest.json')
266
+ .option('--json-output', 'JSON output')
267
+ .action(async (options) => {
268
+ try {
269
+ let configData;
270
+
271
+ if (options.stdin) {
272
+ configData = await readStdin();
273
+ } else if (options.json) {
274
+ configData = options.json;
275
+ } else {
276
+ // Simple, no-flags default: validate manifest.json in the current directory - the case
277
+ // you actually want most of the time (`aivin validate` from inside your plugin project).
278
+ // --json/--stdin remain for scripted/CI use where the config isn't a file on disk yet.
279
+ const manifestPath = path.join(process.cwd(), 'manifest.json');
280
+ if (!fs.existsSync(manifestPath)) {
281
+ throw new Error('No manifest.json found in the current directory. Pass --json <config> or --stdin instead.');
282
+ }
283
+ configData = fs.readFileSync(manifestPath, 'utf8');
284
+ }
285
+
286
+ // Expand the default { ...commonFields, plugins: [...] } shape and validate every entry -
287
+ // flattenManifestFile itself throws on structural problems (empty plugins[], missing
288
+ // id/name/func, bare top-level array).
289
+ const config = flattenManifestFile(JSON.parse(configData));
290
+ const entries = Array.isArray(config) ? config : [config];
291
+ const errors = entries.flatMap((entry, i) =>
292
+ validatePluginConfig(entry).errors.map((e) =>
293
+ entries.length > 1 ? `plugins[${i}] (${entry.name || 'unnamed'}): ${e}` : e,
294
+ ),
295
+ );
296
+ const result = { valid: errors.length === 0, errors };
297
+
298
+ if (options.jsonOutput) {
299
+ console.log(
300
+ JSON.stringify(
301
+ {
302
+ valid: result.valid,
303
+ errors: result.errors,
304
+ },
305
+ null,
306
+ 2,
307
+ ),
308
+ );
309
+ } else {
310
+ if (result.valid) {
311
+ console.log(chalk.green('✅ Valid'));
312
+ } else {
313
+ console.log(chalk.red('❌ Invalid:'));
314
+ result.errors.forEach((error) => console.log(` • ${error}`));
315
+ }
316
+ }
317
+
318
+ if (!result.valid) process.exit(1);
319
+ } catch (error) {
320
+ if (options.jsonOutput) {
321
+ console.log(JSON.stringify({ valid: false, error: error.message }, null, 2));
322
+ } else {
323
+ console.error(chalk.red('❌'), error.message);
324
+ }
325
+ process.exit(1);
326
+ }
327
+ });
328
+
329
+ // Command: start plugin server
330
+ program
331
+ .command('start')
332
+ .description('Start plugin server')
333
+ .option('--debug', 'Log every sdk.* call live as it happens (human-readable), not just the final trace summary')
334
+ .option('--debug-json', 'Same live per-call logging as --debug, but one JSON object per line on stdout - for a script/coding agent to parse instead of a human')
335
+ .option('--no-watch', 'Disable hot-reload - restart manually (Ctrl+C + `aivin start` again) after editing src/ instead')
336
+ .action((options) => {
337
+ checkNodeVersion();
338
+ let serverPath;
339
+ try {
340
+ serverPath = resolveLocalSdkServerPath();
341
+ } catch (error) {
342
+ console.error(chalk.red('❌'), error.message);
343
+ process.exit(1);
344
+ }
345
+ const debugEnv = options.debugJson ? { SDK_DEBUG: 'json' } : options.debug ? { SDK_DEBUG: 'true' } : {};
346
+ const watchEnv = options.watch === false ? { AIVIN_START_WATCH: 'false' } : {};
347
+ const child = spawn('node', [serverPath], {
348
+ stdio: 'inherit',
349
+ env: { ...process.env, ...debugEnv, ...watchEnv },
350
+ });
351
+
352
+ child.on('error', (error) => {
353
+ console.error(chalk.red('❌'), error.message);
354
+ process.exit(1);
355
+ });
356
+
357
+ child.on('exit', (code) => {
358
+ if (code !== 0) {
359
+ process.exit(code);
360
+ }
361
+ });
362
+ });
363
+
364
+ // Command: deploy plugin to server (always private to your org - see buildDeploymentPayload's
365
+ // doc comment above for why there's no public/store-submission scope here)
366
+ program
367
+ .command('deploy')
368
+ .description('Deploy plugin to your org on the Aivin server')
369
+ .action(async () => {
370
+ try {
371
+ await deployPlugin({
372
+ endpointPath: '/plugins/deploy',
373
+ label: 'Deploying plugin',
374
+ });
375
+ } catch (error) {
376
+ console.error(chalk.red('❌'), error.message);
377
+ process.exit(1);
378
+ }
379
+ });
380
+
381
+ // Command: deploy to a throwaway test instance (backend rejects this in production)
382
+ program
383
+ .command('test')
384
+ .description(
385
+ 'Deploy to a non-production test instance, then smoke-test it with generated input and save a report to .test/',
386
+ )
387
+ .option('--workspace <id>', 'Workspace id to run the smoke test against (default: auto-picks your first one)')
388
+ .option('--no-smoke-test', 'Only deploy - skip the generated-input invoke test and report')
389
+ .option('--verify-proxy', 'Also invoke MCP proxy entries for real (empty input) instead of skipping them - only use if you know the underlying tool(s) have no meaningful side effects')
390
+ .action(async (options) => {
391
+ try {
392
+ await deployPlugin({
393
+ endpointPath: '/plugins/test/deploy',
394
+ label: 'Deploying to test instance',
395
+ smokeTest: options.smokeTest !== false,
396
+ workspaceOverride: options.workspace,
397
+ verifyProxy: options.verifyProxy,
398
+ });
399
+ } catch (error) {
400
+ console.error(chalk.red('❌'), error.message);
401
+ process.exit(1);
402
+ }
403
+ });
404
+
405
+ const pluginCommand = program.command('plugin').description('AI-assisted plugin authoring');
406
+
407
+ pluginCommand
408
+ .command('search [query]')
409
+ .description("Search the platform's plugin ecosystem for something to reuse instead of writing it yourself")
410
+ .option('--workspace <id>', 'Restrict to plugins visible in this workspace (default: your whole org)')
411
+ .option('--mcp <server_id>', 'List every tool/resource/prompt plugin generated from one MCP server (the id printed by `aivin mcp`/`aivin plugin search`, e.g. "modelcontextprotocol-servers-src-everything") instead of doing a text search')
412
+ .option('--store <store_id>', 'Restrict to plugins hosted on one self-hosted plugin store (the id printed by `aivin pluginstore ls`) - combines with the text query/--mcp, not a replacement for them')
413
+ .option('--limit <n>', 'Max results to show')
414
+ .option('--plain', 'Print a flat list instead of the interactive browser (for scripts/CI)')
415
+ .action(async (query, options) => {
416
+ try {
417
+ // --mcp is an exact-id lookup, not a text search - the query string is optional in that mode.
418
+ if (!options.mcp) {
419
+ query = await requireArg(query, { prompt: 'What are you looking for?', usage: 'Usage: aivin plugin search "<query>"' });
420
+ }
421
+ await searchPlugins(query, options);
422
+ } catch (error) {
423
+ console.error(chalk.red('❌'), error.message);
424
+ process.exit(1);
425
+ }
426
+ });
427
+
428
+ pluginCommand
429
+ .command('info <id>')
430
+ .description("Show one plugin's detail (input/output schema, setup needs) directly by id, no search query needed")
431
+ .option('--workspace <id>', 'Restrict to plugins visible in this workspace (default: your whole org)')
432
+ .option('--plain', 'Print flat instead of the interactive browser, if falling back to closest-match results')
433
+ .action(async (id, options) => {
434
+ try {
435
+ await showPluginInfo(id, options);
436
+ } catch (error) {
437
+ console.error(chalk.red('❌'), error.message);
438
+ process.exit(1);
439
+ }
440
+ });
441
+
442
+ pluginCommand
443
+ .command('ask [mission]')
444
+ .description('One-shot: search for the best-matching plugin for a plain-language mission and trigger it right away, like an agent would')
445
+ .option('--top <n>', 'How many candidates to consider/print as runner-up context (default 5) - only the top match is ever run')
446
+ .option('-i, --input <json>', 'Input fields as a JSON string - skips the interactive field-by-field prompt')
447
+ .option('--workspace <id>', 'Workspace id to search/run against (default: auto-picks your first one)')
448
+ .option('--agent <id>', 'Agent id to run as, if the plugin needs one for HIL/confirm behavior to be accurate')
449
+ .option('--watch-logs', "Also stream the chosen plugin's own live console output inline")
450
+ .option('--no-auth-prompt', "Don't offer to connect/configure a missing connector interactively when the run comes back needing one - just print the result and exit")
451
+ .option('--save', 'Write this run\'s result to .test/trigger/<timestamp>.json for later --compare')
452
+ .option('--compare <file>', 'Diff this run\'s result against a previously --save\'d .test/trigger/*.json file')
453
+ .action(async (mission, options) => {
454
+ try {
455
+ await askPlugin(mission, options);
456
+ } catch (error) {
457
+ console.error(chalk.red('❌'), error.message);
458
+ process.exit(1);
459
+ }
460
+ });
461
+
462
+ pluginCommand
463
+ .command('make [description]')
464
+ .description('Generate src/main.ts from a natural-language business description')
465
+ .option('--model <model>', 'LLM model to use for generation')
466
+ .option('--provider <provider>', 'LLM provider to use for generation')
467
+ .action(async (description, options) => {
468
+ try {
469
+ description = await requireArg(description, { prompt: 'What should this plugin do?', usage: 'Usage: aivin plugin make "<description>"' });
470
+ await makePluginFromDescription(description, options);
471
+ } catch (error) {
472
+ console.error(chalk.red('❌'), error.message);
473
+ process.exit(1);
474
+ }
475
+ });
476
+
477
+ pluginCommand
478
+ .command('convert [hint]')
479
+ .description('Turn an existing project in the current directory into an Aivin plugin')
480
+ .option('--model <model>', 'LLM model to use for generation')
481
+ .option('--provider <provider>', 'LLM provider to use for generation')
482
+ .option('--force', 'Re-run conversion even if src/main.ts already exists (e.g. redo a previous bad/stale result)')
483
+ .action(async (hint, options) => {
484
+ try {
485
+ await convertExistingProject(hint, options);
486
+ } catch (error) {
487
+ console.error(chalk.red('❌'), error.message);
488
+ process.exit(1);
489
+ }
490
+ });
491
+
492
+ pluginCommand
493
+ .command('trigger [mission] [input]')
494
+ .description('Invoke this deployed plugin for real and print the result - like the platform\'s Playground')
495
+ .option('--id <pluginId>', 'Plugin id to trigger directly - skips the local manifest.json lookup (e.g. for `aivin mcp` plugins, which have no local project directory)')
496
+ .option('--func <name>', 'Which function to trigger, for a multi-function plugin (matches name/func/id) - ignored when --id is given')
497
+ .option('--workspace <id>', 'Workspace id to run against (default: auto-picks your first one)')
498
+ .option('--agent <id>', 'Agent id to run as, if the plugin needs one for HIL/confirm behavior to be accurate')
499
+ .option('--watch-logs', 'Also stream the plugin\'s own live console output inline (same feed as `aivin plugin logs`) instead of needing a second terminal - requires permission to view that plugin\'s logs (your own/org\'s deployments; most store plugins from other orgs will just skip this and fall back to the REST result only)')
500
+ .option('--no-auth-prompt', "Don't offer to connect/configure a missing connector interactively when the run comes back needing one - just print the result and exit")
501
+ .option('--save', 'Write this run\'s result to .test/trigger/<timestamp>.json for later --compare')
502
+ .option('--compare <file>', 'Diff this run\'s result against a previously --save\'d .test/trigger/*.json file')
503
+ .action(async (mission, input, options) => {
504
+ try {
505
+ await triggerPlugin(mission, input, options);
506
+ } catch (error) {
507
+ console.error(chalk.red('❌'), error.message);
508
+ process.exit(1);
509
+ }
510
+ });
511
+
512
+ pluginCommand
513
+ .command('logs [pluginId]')
514
+ .description('Tail a deployed plugin\'s own console output live (defaults to the current directory\'s manifest.json id)')
515
+ .option('--func <name>', 'Which function\'s id to resolve, for a multi-function plugin (only used when pluginId is omitted)')
516
+ .action(async (pluginId, options) => {
517
+ try {
518
+ await streamPluginLogs(pluginId, options);
519
+ } catch (error) {
520
+ console.error(chalk.red('❌'), error.message);
521
+ process.exit(1);
522
+ }
523
+ });
524
+
525
+ pluginCommand
526
+ .command('delete [id]')
527
+ .description("Delete a plugin you own, or every plugin from one batch deploy at once with --group <groupId> (e.g. everything `aivin mcp <url>` generated in one run - see the group_id it prints after deploying)")
528
+ .option('--group <groupId>', 'Delete every plugin sharing this group_id instead of a single plugin by id')
529
+ .option('-y, --yes', 'Skip the confirmation prompt (for scripts/CI)')
530
+ .action(async (id, options) => {
531
+ try {
532
+ await deletePluginCmd(id, options);
533
+ } catch (error) {
534
+ console.error(chalk.red('❌'), error.message);
535
+ process.exit(1);
536
+ }
537
+ });
538
+
539
+ const connectorCommand = program.command('connector').description('Register and discover reusable connectors (OAuth apps / credential-form namespaces)');
540
+
541
+ connectorCommand
542
+ .command('register')
543
+ .description('Register a new connector namespace, interactively')
544
+ .action(async () => {
545
+ try {
546
+ await registerConnector();
547
+ } catch (error) {
548
+ console.error(chalk.red('❌'), error.message);
549
+ process.exit(1);
550
+ }
551
+ });
552
+
553
+ connectorCommand
554
+ .command('search [query]')
555
+ .description("Search connectors for something to reuse instead of registering a new one")
556
+ .option('--limit <n>', 'Max results to show')
557
+ .option('--plain', 'Print a flat list instead of the interactive browser (for scripts/CI)')
558
+ .action(async (query, options) => {
559
+ try {
560
+ query = await requireArg(query, { prompt: 'What are you looking for?', usage: 'Usage: aivin connector search "<query>"' });
561
+ await searchConnectors(query, options);
562
+ } catch (error) {
563
+ console.error(chalk.red('❌'), error.message);
564
+ process.exit(1);
565
+ }
566
+ });
567
+
568
+ connectorCommand
569
+ .command('list')
570
+ .description('List connectors visible to your org')
571
+ .option('--page <n>', 'Page number')
572
+ .option('--limit <n>', 'Items per page')
573
+ .option('--include-deprecated', "Also show your org's deprecated connectors (hidden by default)")
574
+ .option('--plain', 'Print a flat list instead of the interactive browser (for scripts/CI)')
575
+ .action(async (options) => {
576
+ try {
577
+ await listConnectors(options);
578
+ } catch (error) {
579
+ console.error(chalk.red('❌'), error.message);
580
+ process.exit(1);
581
+ }
582
+ });
583
+
584
+ connectorCommand
585
+ .command('deprecate [id]')
586
+ .description("Hide a connector you own from search/list without breaking plugins already using it")
587
+ .action(async (id) => {
588
+ try {
589
+ id = await requireArg(id, { prompt: 'Connector id to deprecate:', usage: 'Usage: aivin connector deprecate <id>' });
590
+ await axios.post(`${connectorBaseUrl()}/connectors/${encodeURIComponent(id)}/deprecate`, {}, connectorAuthHeaders());
591
+ console.log(chalk.green(`✅ "${id}" is now deprecated - still usable, hidden from new search/list.`));
592
+ } catch (error) {
593
+ const message = error.response?.data?.message || error.message;
594
+ console.error(chalk.red('❌'), message);
595
+ process.exit(1);
596
+ }
597
+ });
598
+
599
+ connectorCommand
600
+ .command('undeprecate [id]')
601
+ .description('Make a previously-deprecated connector you own discoverable again')
602
+ .action(async (id) => {
603
+ try {
604
+ id = await requireArg(id, { prompt: 'Connector id to un-deprecate:', usage: 'Usage: aivin connector undeprecate <id>' });
605
+ await axios.post(`${connectorBaseUrl()}/connectors/${encodeURIComponent(id)}/undeprecate`, {}, connectorAuthHeaders());
606
+ console.log(chalk.green(`✅ "${id}" is discoverable again.`));
607
+ } catch (error) {
608
+ const message = error.response?.data?.message || error.message;
609
+ console.error(chalk.red('❌'), message);
610
+ process.exit(1);
611
+ }
612
+ });
613
+
614
+ const pluginStoreCommand = program
615
+ .command('pluginstore')
616
+ .description('Self-hosted aivin-service worker (Docker) - attach it to your org as a plugin store. See docs/GETTING_STARTED.md.');
617
+
618
+ pluginStoreCommand
619
+ .command('create [store_id]')
620
+ .description('Create a new plugin store + attach this machine as its first node')
621
+ .option('--label <label>', 'Display label for the store (defaults to store_id)')
622
+ .option('--node-label <label>', 'Display label for this node/instance')
623
+ .option('--data-dir <path>', 'Where to write worker-identity.json (default: ~/.aivin/service-data)')
624
+ .action(async (storeId, options) => {
625
+ try {
626
+ await createStore(storeId, options);
627
+ } catch (error) {
628
+ console.error(chalk.red('❌'), error.message);
629
+ process.exit(1);
630
+ }
631
+ });
632
+
633
+ pluginStoreCommand
634
+ .command('attach [store_id]')
635
+ .description('Attach this machine as another node of an existing plugin store')
636
+ .option('--node-label <label>', 'Display label for this node/instance')
637
+ .option('--data-dir <path>', 'Where to write worker-identity.json (default: ~/.aivin/service-data)')
638
+ .action(async (storeId, options) => {
639
+ try {
640
+ await attachStore(storeId, options);
641
+ } catch (error) {
642
+ console.error(chalk.red('❌'), error.message);
643
+ process.exit(1);
644
+ }
645
+ });
646
+
647
+ pluginStoreCommand
648
+ .command('ls')
649
+ .description('List plugin stores visible to your org, with online/offline status per node')
650
+ .action(async (options) => {
651
+ try {
652
+ await listStores(options);
653
+ } catch (error) {
654
+ console.error(chalk.red('❌'), error.message);
655
+ process.exit(1);
656
+ }
657
+ });
658
+
659
+ pluginStoreCommand
660
+ .command('enable [store_id]')
661
+ .description('Enable a store for your org (org admin only)')
662
+ .action(async (storeId) => {
663
+ try {
664
+ storeId = await requireArg(storeId, { prompt: 'Store id to enable:', usage: 'Usage: aivin pluginstore enable <store_id>' });
665
+ await setStoreEnabled(storeId, true);
666
+ } catch (error) {
667
+ console.error(chalk.red('❌'), error.message);
668
+ process.exit(1);
669
+ }
670
+ });
671
+
672
+ pluginStoreCommand
673
+ .command('disable [store_id]')
674
+ .description('Disable a store for your org without deleting it (org admin only)')
675
+ .action(async (storeId) => {
676
+ try {
677
+ storeId = await requireArg(storeId, { prompt: 'Store id to disable:', usage: 'Usage: aivin pluginstore disable <store_id>' });
678
+ await setStoreEnabled(storeId, false);
679
+ } catch (error) {
680
+ console.error(chalk.red('❌'), error.message);
681
+ process.exit(1);
682
+ }
683
+ });
684
+
685
+ pluginStoreCommand
686
+ .command('rm [store_id]')
687
+ .description('Delete a store - revokes EVERY node attached to it, not just this machine (org admin only)')
688
+ .option('-y, --yes', 'Skip the confirmation prompt')
689
+ .action(async (storeId, options) => {
690
+ try {
691
+ storeId = await requireArg(storeId, { prompt: 'Store id to delete:', usage: 'Usage: aivin pluginstore rm <store_id>' });
692
+ await deleteStore(storeId, options);
693
+ } catch (error) {
694
+ console.error(chalk.red('❌'), error.message);
695
+ process.exit(1);
696
+ }
697
+ });
698
+
699
+ pluginStoreCommand
700
+ .command('rm-node [store_id] [node_id]')
701
+ .description('Remove one node from a store (e.g. one that never came online) without touching its other nodes - org admin not required')
702
+ .option('-y, --yes', 'Skip the confirmation prompt')
703
+ .action(async (storeId, nodeId, options) => {
704
+ try {
705
+ await removeNode(storeId, nodeId, options);
706
+ } catch (error) {
707
+ console.error(chalk.red('❌'), error.message);
708
+ process.exit(1);
709
+ }
710
+ });
711
+
712
+ pluginStoreCommand
713
+ .command('detach')
714
+ .description("Remove THIS machine's pairing only (local file only, no BE call) - the running aivin-service picks it up automatically")
715
+ .option('--data-dir <path>', 'Where worker-identity.json lives (default: ~/.aivin/service-data)')
716
+ .action((options) => {
717
+ try {
718
+ detachStore(options);
719
+ } catch (error) {
720
+ console.error(chalk.red('❌'), error.message);
721
+ process.exit(1);
722
+ }
723
+ });
724
+
725
+ const mcpCommand = program
726
+ .command('mcp')
727
+ .description('MCP proxy plugins - wrap an external MCP server tool/resource/prompt, no code required');
728
+
729
+ mcpCommand
730
+ .argument('[url]', 'GitHub/GitLab/npm/Smithery URL, or a live MCP server URL, to scan and convert')
731
+ .option('--publish', 'Deploy to your org, then submit for community store review (needs admin approval)')
732
+ .option('--private', 'Deploy to your org only - default')
733
+ .option('--org', 'Alias of --private - there is no narrower per-workspace scope today')
734
+ .option('--quiet', 'Skip live progress output while scanning (on by default otherwise)')
735
+ .option('--auth', 'Đánh dấu MCP này cần credential -> BE sinh connection_id, CLI hỏi gắn connector (OAuth HOẶC credential_form tuỳ chọn lúc đó). Dùng cho MCP cần API key/token mà scan không tự nhận ra')
736
+ .option('--oauth', 'Bí danh cũ của --auth (giữ để không phá lệnh đã dùng)')
737
+ .option('--test-token <token>', 'Access token dùng THỬ để đọc tool của remote MCP cần OAuth (Notion/Slack/Linear/Figma...). Chỉ dùng lúc quét, KHÔNG lưu lại - xem test_token trong plugin-store.proto')
738
+ .option('-y, --yes', 'Skip the deploy confirmation prompt (required in non-TTY/CI contexts, which otherwise now refuse to deploy at all - see scanAndPublishMcp)')
739
+ .action(async (url, options) => {
740
+ try {
741
+ url = await requireArg(url, {
742
+ prompt: 'GitHub/GitLab/npm/Smithery URL, or a live MCP server URL:',
743
+ usage: 'Usage: aivin mcp <url> [--publish|--private|--org]',
744
+ });
745
+ await scanAndPublishMcp(url, options);
746
+ } catch (error) {
747
+ console.error(chalk.red('❌'), error.message);
748
+ process.exit(1);
749
+ }
750
+ });
751
+
752
+ mcpCommand
753
+ .command('create [name]')
754
+ .description('Scaffold a manifest-only plugin that proxies to an external MCP server')
755
+ .option('--transport <transport>', 'stdio | sse')
756
+ .option('--command <command>', 'Command to launch the MCP server (stdio transport)')
757
+ .option('--args <args>', 'Space-separated args for --command (stdio transport)')
758
+ .option('--url <url>', 'Remote MCP server URL (sse transport)')
759
+ .option('--kind <kind>', 'tool | resource | prompt (default: tool)')
760
+ .option('--tool-name <name>', 'MCP tool name (kind=tool)')
761
+ .option('--resource-uri <uri>', 'MCP resource URI (kind=resource)')
762
+ .option('--resource-mime-type <mime>', 'MIME type of the resource (kind=resource)')
763
+ .option('--prompt-name <name>', 'MCP prompt name (kind=prompt)')
764
+ .option('--description <description>', 'Plugin description')
765
+ .option(
766
+ '--auth-secret-key <key>',
767
+ 'Name of the workspace secret to use as the token/credential, if the MCP server needs auth',
768
+ )
769
+ .option('--auth-type <type>', 'auth_type value to send (default: "bearer" when --auth-secret-key is set) - check your backend for which values it supports')
770
+ .option('--connector <id>', "Existing connector id for this plugin's connection_id (readiness/\"needs login\" display only - does NOT inject anything into the running MCP server; run with no flags for the interactive per-variable auth setup that actually does)")
771
+ .action(async (name, options) => {
772
+ try {
773
+ name = await requireArg(name, { prompt: 'Plugin name (lowercase letters, numbers, hyphens):', usage: 'Usage: aivin mcp create <name>' });
774
+ await createMcpProxyPlugin(name, options);
775
+ } catch (error) {
776
+ console.error(chalk.red('❌'), error.message);
777
+ process.exit(1);
778
+ }
779
+ });
780
+
781
+ mcpCommand
782
+ .command('watch [url]')
783
+ .description('Watch a GitHub repo/branch and auto-rescan+resync its plugins when the branch updates (checked server-side every ~5 min, no CLI process needs to stay running)')
784
+ .option('--branch <name>', "Branch to watch (default: the repo's default branch)")
785
+ .option('--list', 'List your watched repos instead of registering a new one')
786
+ .action(async (url, options) => {
787
+ try {
788
+ if (options.list) {
789
+ await listMcpWatches();
790
+ return;
791
+ }
792
+ url = await requireArg(url, {
793
+ prompt: 'GitHub repo URL to watch:',
794
+ usage: 'Usage: aivin mcp watch <url> [--branch <name>] | aivin mcp watch --list',
795
+ });
796
+ await registerMcpWatch(url, options);
797
+ } catch (error) {
798
+ console.error(chalk.red('❌'), error.message);
799
+ process.exit(1);
800
+ }
801
+ });
802
+
803
+ mcpCommand
804
+ .command('unwatch <url>')
805
+ .description('Stop auto-resyncing a previously watched repo')
806
+ .option('--branch <name>', 'Branch to unwatch (default: all watched branches for this repo)')
807
+ .action(async (url, options) => {
808
+ try {
809
+ await unwatchMcp(url, options);
810
+ } catch (error) {
811
+ console.error(chalk.red('❌'), error.message);
812
+ process.exit(1);
813
+ }
814
+ });
815
+
816
+ program
817
+ .command('login')
818
+ .argument('[baseUrl]', 'Server to log into (REST API base) - defaults to production (api.aivin.cloud). Pass a staging/self-hosted host to switch the machine\'s active context to it, e.g. `aivin login beta-api.aivin.vn`.')
819
+ .description('Log in and save an API key for plugin deployment (opens your browser by default)')
820
+ .option('-k, --api-key <key>', 'Set API key directly (skip login entirely)')
821
+ .option('--basic', 'Log in with email/password directly in the terminal instead of a browser')
822
+ .option('--google', 'Alias of the default browser flow - pick Google once the page opens')
823
+ .option('--client <client>', 'Client/org id to use with --basic (default: "aivin.cloud")')
824
+ .action(async (baseUrl, options) => {
825
+ try {
826
+ // Bare hostname (no scheme) is the common case for a quick `aivin login beta-api.aivin.vn` -
827
+ // assume https, same as every other *.aivin.* endpoint in this file.
828
+ const resolvedBaseUrl = baseUrl ? (/^https?:\/\//.test(baseUrl) ? baseUrl : `https://${baseUrl}`) : DEFAULT_AIVIN_BASE_URL;
829
+ process.env.AIVIN_BASE_URL = resolvedBaseUrl;
830
+
831
+ if (options.apiKey) {
832
+ console.log(chalk.blue('🔑 Setting API key...'));
833
+ // Best-effort - `aivin whoami` reads straight from the saved file with no server calls of
834
+ // its own, so whatever identity is resolvable here is all it will ever have to show.
835
+ const identity = await tryFetchWhoami(resolvedBaseUrl, options.apiKey);
836
+ const sdkEndpoint = saveGlobalApiKey(options.apiKey, resolvedBaseUrl, identity);
837
+ console.log(chalk.green('✅ API key set successfully!'));
838
+ console.log(chalk.gray(` Active context: ${resolvedBaseUrl}${sdkEndpoint ? ` (SDK_ENDPOINT: ${sdkEndpoint})` : ''}`));
839
+ console.log(chalk.green(`💾 Saved to ${GLOBAL_CREDENTIALS_PATH} - every project on this machine now targets this server.`));
840
+ return;
841
+ }
842
+
843
+ // Only the browser flow needs a web app URL - fetch it from the backend itself (not needed/
844
+ // fetched for --basic, which never touches AIVIN_WEB_URL at all). Same override precedence
845
+ // as everywhere else: a caller-set AIVIN_WEB_URL (project .env/shell) always wins.
846
+ if (!options.basic && !process.env.AIVIN_WEB_URL) {
847
+ const webUrl = await fetchWebUrl(resolvedBaseUrl);
848
+ if (webUrl) {
849
+ process.env.AIVIN_WEB_URL = webUrl;
850
+ } else {
851
+ // fetchWebUrl swallows its own errors (bad host, typo'd domain, TLS/DNS failure) and
852
+ // returns null - warn instead of silently opening the PRODUCTION web app's login page,
853
+ // which would mint a key for the wrong server without any indication why.
854
+ console.log(chalk.yellow(`⚠️ Couldn't reach ${resolvedBaseUrl} to resolve its web app URL - check the host is correct.`));
855
+ console.log(chalk.yellow(` Falling back to the production web app (https://brain.aivin.cloud) - the key it mints will still be saved against ${resolvedBaseUrl}, likely NOT what you want.`));
856
+ }
857
+ }
858
+
859
+ const apiKey = options.basic ? await basicLogin(options) : await browserLogin();
860
+
861
+ console.log(chalk.green('✅ Login successful!'));
862
+ const identity = await tryFetchWhoami(resolvedBaseUrl, apiKey);
863
+ const sdkEndpoint = saveGlobalApiKey(apiKey, resolvedBaseUrl, identity);
864
+ console.log(chalk.gray(` Active context: ${resolvedBaseUrl}${sdkEndpoint ? ` (SDK_ENDPOINT: ${sdkEndpoint})` : ''}`));
865
+ console.log(chalk.green(`💾 Saved to ${GLOBAL_CREDENTIALS_PATH} - every project on this machine now targets this server.`));
866
+ } catch (error) {
867
+ console.log(chalk.red('❌ Login failed:'), error.message);
868
+ process.exit(1);
869
+ }
870
+ });
871
+
872
+ program
873
+ .command('logout')
874
+ .description('Clear the saved API key on this machine (~/.aivin/credentials) - run `aivin login` again to log back in')
875
+ .action(() => {
876
+ try {
877
+ // Captured BEFORE clearing so we can tell whether the currently-effective API_KEY (already
878
+ // loaded into process.env at startup - see the dotenv/loadActiveContext precedence block at
879
+ // the top of this file) came from this file or from a project's own .env, which logout never
880
+ // touches.
881
+ const savedContext = loadActiveContext();
882
+ const cleared = clearActiveContext();
883
+ if (cleared) {
884
+ console.log(chalk.green(`✅ Logged out - removed ${GLOBAL_CREDENTIALS_PATH}`));
885
+ } else {
886
+ console.log(chalk.gray('Already logged out - no saved credentials found.'));
887
+ }
888
+ if (process.env.API_KEY && process.env.API_KEY !== savedContext?.api_key) {
889
+ console.log(chalk.gray(" Note: this directory still has its own API_KEY set (from a project .env or shell env) - unset that too if you want it fully logged out here."));
890
+ }
891
+ } catch (error) {
892
+ console.error(chalk.red('❌'), error.message);
893
+ process.exit(1);
894
+ }
895
+ });
896
+
897
+ program
898
+ .command('whoami')
899
+ .description('Show which account is currently logged in on this machine (reads ~/.aivin/credentials - no server call)')
900
+ .action(() => {
901
+ try {
902
+ const apiKey = requireSavedApiKey();
903
+ const serverUrl = process.env.AIVIN_BASE_URL || DEFAULT_AIVIN_BASE_URL;
904
+ const localClient = parseApiKeyClient(apiKey);
905
+
906
+ // The effective API_KEY may come from a project's own .env instead of `~/.aivin/credentials`
907
+ // (see the dotenv precedence near the top of this file) - identity/login time only exist in
908
+ // the latter, so a project .env override has nothing to show beyond the key's own client id.
909
+ const savedContext = loadActiveContext();
910
+ const fromSavedContext = savedContext?.api_key === apiKey;
911
+ const identity = fromSavedContext ? savedContext : {};
912
+
913
+ console.log(chalk.green('✅ Logged in'));
914
+ console.log(chalk.gray(' Email: ') + (identity.email || chalk.gray('unknown')));
915
+ console.log(chalk.gray(' Name: ') + (identity.name || chalk.gray('unknown')));
916
+ console.log(chalk.gray(' Org: ') + (identity.org_name || identity.client || localClient || chalk.gray('unknown')));
917
+ if (identity.org_domain) console.log(chalk.gray(' Domain: ') + identity.org_domain);
918
+ console.log(chalk.gray(' Server: ') + serverUrl);
919
+ if (fromSavedContext && savedContext.logged_in_at) {
920
+ console.log(chalk.gray(' Logged in at: ') + new Date(savedContext.logged_in_at).toLocaleString());
921
+ } else if (!fromSavedContext) {
922
+ console.log(chalk.gray(" (API_KEY is from this project's .env, not `aivin login` - no recorded identity/login time)"));
923
+ } else if (!identity.email) {
924
+ console.log(chalk.gray(' (Account info wasn\'t resolvable at login time - run `aivin login` again to refresh it)'));
925
+ }
926
+ } catch (error) {
927
+ console.error(chalk.red('❌'), error.message);
928
+ process.exit(1);
929
+ }
930
+ });
931
+
932
+ const keyCommand = program.command('key').description('Manage named API keys for your account');
933
+
934
+ keyCommand
935
+ .command('gen [name]')
936
+ .description('Create (or replace) a named API key for your account - shown only once')
937
+ .option('--save', 'Also save this key as this machine\'s default (~/.aivin/credentials), like `aivin login -k`')
938
+ .action(async (name, options) => {
939
+ try {
940
+ name = await requireArg(name, { prompt: 'Name for this API key:', usage: 'Usage: aivin key gen <name>' });
941
+ console.log(chalk.blue(`🔑 Creating API key "${name}"...`));
942
+ const plainKey = await generateApiKey(name);
943
+ console.log(chalk.green('✅ API key created!'));
944
+ console.log(chalk.yellow('🔑 Key:'), chalk.cyan(plainKey));
945
+ console.log(chalk.gray(' This is shown only once - store it somewhere safe.'));
946
+ if (options.save) {
947
+ const serverUrl = process.env.AIVIN_BASE_URL || DEFAULT_AIVIN_BASE_URL;
948
+ const identity = await tryFetchWhoami(serverUrl, plainKey);
949
+ saveGlobalApiKey(plainKey, serverUrl, identity);
950
+ console.log(chalk.green(`💾 Saved to ${GLOBAL_CREDENTIALS_PATH} - every project on this machine can use it now.`));
951
+ }
952
+ } catch (error) {
953
+ console.error(chalk.red('❌'), error.message);
954
+ process.exit(1);
955
+ }
956
+ });
957
+
958
+ keyCommand
959
+ .command('revoke [name]')
960
+ .description('Revoke a named API key for your account')
961
+ .action(async (name) => {
962
+ try {
963
+ name = await requireArg(name, { prompt: 'Name of the API key to revoke:', usage: 'Usage: aivin key revoke <name>' });
964
+ console.log(chalk.blue(`🔑 Revoking API key "${name}"...`));
965
+ await revokeApiKeyByName(name);
966
+ console.log(chalk.green(`✅ API key "${name}" revoked.`));
967
+ } catch (error) {
968
+ console.error(chalk.red('❌'), error.message);
969
+ process.exit(1);
970
+ }
971
+ });
972
+
973
+ keyCommand
974
+ .command('list')
975
+ .description('List API keys on your account')
976
+ .action(async () => {
977
+ try {
978
+ const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
979
+ const apiKey = requireSavedApiKey();
980
+ await logAccountIdentity(serverUrl, apiKey);
981
+ const items = await listRemoteApiKeys(serverUrl, apiKey);
982
+ if (items.length === 0) {
983
+ console.log(chalk.gray('No API keys found.'));
984
+ return;
985
+ }
986
+ items.forEach((k) => {
987
+ const created = k.created_at ? new Date(k.created_at).toISOString() : 'unknown';
988
+ console.log(` ${chalk.cyan(k.name)} ${chalk.gray(`(created ${created})`)}`);
989
+ });
990
+ } catch (error) {
991
+ console.error(chalk.red('❌'), error.message);
992
+ process.exit(1);
993
+ }
994
+ });
995
+
996
+ program
997
+ .command('browser [mission]')
998
+ .description("Run an AI Browser mission - by default in your everyday Chrome/Edge if you've switched on remote debugging in it (chrome://inspect/#remote-debugging), otherwise in a local browser window dedicated to AI Browser (own profile - log in once, the AI's tabs grouped together); --remote uses a server-side browser instead")
999
+ .option('--remote', 'Use a server-side pooled browser instead of your own local one (no local browser needed, no cookies/logins carried over)')
1000
+ .option('--debug-port <port>', 'Local mode only: port to launch the AI Browser window\'s remote debugging on (default: 9222, auto-tries a few nearby ports if that one is taken by something else) - pass this to pin an exact port instead')
1001
+ .option('--browser <edge|chrome|brave|chromium>', "Local mode only: which browser to drive - default: auto-detects your OS's actual default browser, falling back to whichever of Edge/Chrome/Brave/Chromium is installed if that can't be determined")
1002
+ .option('--separate-browser', 'Local mode only: always use the dedicated AI Browser window, never your everyday browser (even if remote debugging is switched on in it)')
1003
+ .option('--url <url>', "Local mode only: open this URL before the mission starts, instead of a blank page - skips a wasted first analysis step and avoids the AI having to search the web to find the target site itself (auto-guessed for a few well-known sites mentioned by name in the mission if omitted)")
1004
+ .option('--workspace <id>', 'Workspace id to run in (default: your personal workspace)')
1005
+ .option('--project <id>', 'Project id within the workspace (--remote only)')
1006
+ .option('--agent <id>', "Agent id to run as (default: an auto-created/cached agent for local mode, or the workspace's default agent for --remote) - AI Browser is triggered as a tool this agent uses, real HIL suspend/resume requires an agent context")
1007
+ .option('--no-watch', 'Fire the mission and return immediately - skip streaming live progress and auto-opening the viewer')
1008
+ .option('--view', 'Just (re)open the fullscreen interactive viewer for whatever HIL session is already active - no mission is started')
1009
+ .action(async (mission, options) => {
1010
+ try {
1011
+ if (!options.view) {
1012
+ mission = await requireArg(mission, {
1013
+ prompt: 'What should the AI Browser do?',
1014
+ usage: 'Usage: aivin browser "<mission detail>" (or: aivin browser --view to just reopen the interactive viewer)',
1015
+ });
1016
+ }
1017
+ await runBrowserMission(mission, options);
1018
+ } catch (error) {
1019
+ console.error(chalk.red('❌'), error.message);
1020
+ process.exit(1);
1021
+ }
1022
+ });
1023
+
1024
+ program
1025
+ .command('ui')
1026
+ .description('Show the Aivin mascot on this computer with its ask box (Windows) - starts the background listener if it is not running')
1027
+ .option('--demo', 'Preview every mascot animation state without pairing or starting the listener')
1028
+ .action(async (options) => {
1029
+ const lang = mascotLang();
1030
+ const say = (key, color = chalk.green) => console.log(color(mascotText(lang, key)));
1031
+ if (options.demo) {
1032
+ const result = showMascotDemo();
1033
+ if (result === UiResult.UNSUPPORTED) return say(MascotText.CMD_UNSUPPORTED, chalk.yellow);
1034
+ if (result === UiResult.START_FAILED) { console.error(chalk.red('Không thể mở bản demo linh vật.')); process.exitCode = 1; return; }
1035
+ console.log(chalk.green('✓ Demo linh vật đang chạy qua 8 trạng thái — đóng cửa sổ hoặc nhấn Ctrl+C để dừng.'));
1036
+ return;
1037
+ }
1038
+ const result = await showMascotUi({ onStarting: () => say(MascotText.UI_STARTING, chalk.gray) });
1039
+ if (result === UiResult.UNSUPPORTED) return say(MascotText.CMD_UNSUPPORTED, chalk.yellow);
1040
+ if (result === UiResult.SHOWN) return say(MascotText.UI_SHOWN);
1041
+ if (result === UiResult.STARTED) return say(MascotText.UI_STARTED);
1042
+ if (result === UiResult.NOT_PAIRED) return say(MascotText.UI_NOT_PAIRED, chalk.yellow);
1043
+ say(MascotText.UI_START_FAILED, chalk.red);
1044
+ process.exitCode = 1;
1045
+ });
1046
+
1047
+ program
1048
+ .command('desktop [action]')
1049
+ .description('Aivin as a desktop app: install (Windows: system tray + Start menu; macOS: menu bar + Aivin.app; Linux: app menu + tray) and start it with the computer | uninstall | status (default)')
1050
+ .option('--no-autostart', "install: don't start Aivin with the computer (turn it on later from Aivin's menu or the system's startup settings)")
1051
+ .option('--no-launch', "install: don't open Aivin now")
1052
+ .action((action = 'status', options) => {
1053
+ // Chỗ bật / tắt khởi động cùng máy của từng hệ điều hành — cùng chỗ menu Aivin và `aivin remote enable|disable` đổi.
1054
+ const startupWhere = { win32: 'Task Manager → Startup apps', darwin: 'System Settings → General → Login Items', linux: 'Startup Applications / Autostart' }[process.platform] || '';
1055
+ const where = { win32: 'khay hệ thống, tìm "Aivin" trong Start', darwin: 'thanh menu, tìm "Aivin" bằng Spotlight', linux: 'khay hệ thống, tìm "Aivin" trong menu ứng dụng' }[process.platform] || '';
1056
+ try {
1057
+ if (action === 'install') {
1058
+ const res = installDesktopApp({ autostart: options.autostart !== false, launch: options.launch !== false });
1059
+ console.log(chalk.green(`✅ Đã cài Aivin vào máy: ${where}.`));
1060
+ console.log(chalk.gray(` Ứng dụng: ${res.exe}`));
1061
+ console.log(chalk.gray(` Khởi động cùng máy: ${res.autostart ? 'bật' : 'tắt'} (đổi ở menu Aivin hoặc ${startupWhere})`));
1062
+ if (process.platform === 'linux' && !desktopAppStatus().tray) {
1063
+ console.log(chalk.yellow(' ⚠️ Máy chưa có AppIndicator cho python3 nên không có biểu tượng khay — Aivin vẫn chạy nền. Cài: sudo apt install gir1.2-ayatanaappindicator3-0.1 (Ubuntu / Debian)'));
1064
+ }
1065
+ return;
1066
+ }
1067
+ if (action === 'uninstall') {
1068
+ const res = uninstallDesktopApp();
1069
+ console.log(chalk.green('✅ Đã gỡ ứng dụng Aivin trên màn hình và mục khởi động cùng máy (lệnh `aivin` vẫn còn).'));
1070
+ if (!res.removed) console.log(chalk.yellow(' ⚠️ Ứng dụng còn đang chạy nên chưa xoá hết được tệp — chạy lại lệnh này sau ít giây.'));
1071
+ return;
1072
+ }
1073
+ if (action !== 'status') throw new Error('Dùng: aivin desktop install [--no-autostart] [--no-launch] | uninstall | status');
1074
+ const st = desktopAppStatus();
1075
+ if (st.supported === false) return console.log(chalk.gray(`Chưa có ứng dụng Aivin trên màn hình cho ${process.platform} — dùng \`aivin remote enable\`.`));
1076
+ console.log(chalk.blue('🖥️ Aivin trên máy này:'));
1077
+ console.log(chalk.gray(` Ứng dụng: ${st.installed ? st.app : 'chưa cài — aivin desktop install'}`));
1078
+ if (st.installed) console.log(chalk.gray(` Tìm bằng: ${st.search || 'không'}`));
1079
+ console.log(chalk.gray(` Khởi động cùng máy: ${st.startup.registered ? (st.startup.enabled ? 'bật' : `tắt (${startupWhere})`) : 'không'}`));
1080
+ if (process.platform === 'linux') console.log(chalk.gray(` Biểu tượng khay: ${st.tray ? 'có' : 'không (thiếu python3 + AppIndicator) — vẫn chạy nền'}`));
1081
+ } catch (error) {
1082
+ console.error(chalk.red('❌'), error.message);
1083
+ process.exit(1);
1084
+ }
1085
+ });
1086
+
1087
+ program
1088
+ .command('update')
1089
+ .description('Update aivin to the latest release (installs from get.aivin.vn; checks the release signature, the SHA256 and that the new build starts)')
1090
+ .option('--check', 'Only check whether a newer release exists')
1091
+ .option('--to <version>', 'Install this release instead of the latest, e.g. v1.0.9 (also allows going back)')
1092
+ .option('--auto <on|off>', 'Turn background updates of `aivin remote start` on or off for this computer')
1093
+ .option('--proxy <url>', 'HTTP proxy to download through (default: HTTPS_PROXY, else the system proxy setting; "none" = connect directly)')
1094
+ .action(async (options) => {
1095
+ try {
1096
+ if (options.auto !== undefined) {
1097
+ const value = String(options.auto).toLowerCase();
1098
+ if (!['on', 'off'].includes(value)) throw new Error('Dùng: aivin update --auto on|off');
1099
+ saveUpdateSettings({ auto: value === 'on' });
1100
+ console.log(chalk.green(value === 'on' ? '✅ Đã bật tự cập nhật nền.' : '✅ Đã tắt tự cập nhật nền — cập nhật bằng `aivin update` khi cần.'));
1101
+ return;
1102
+ }
1103
+ configureProxy({ explicit: options.proxy });
1104
+ if (isStandaloneBinary()) cleanupRetired();
1105
+ const root = downloadRoot();
1106
+ const res = await installUpdate({ version: options.to, root, check: !!options.check, force: !!options.to });
1107
+ if (res.status === UpdateStatus.UP_TO_DATE) return console.log(chalk.green(`✅ aivin ${res.current} là bản mới nhất.`));
1108
+ if (res.status === UpdateStatus.NOT_BINARY) {
1109
+ return console.log(chalk.yellow(`⬆ Có aivin ${res.latest} (máy này ${res.current}). Bản cài qua npm: npm i -g @aivin-labs/cli@latest`));
1110
+ }
1111
+ if (res.status === UpdateStatus.AVAILABLE) return console.log(chalk.yellow(`⬆ Có aivin ${res.latest} (máy này ${res.current}) — chạy \`aivin update\` để cài.`));
1112
+ if (res.status === UpdateStatus.SKIPPED) {
1113
+ return console.log(chalk.yellow(`⚠️ Máy này đã tự lùi khỏi aivin ${res.latest} (khởi động hỏng). Vẫn muốn cài: aivin update --to ${res.latest}`));
1114
+ }
1115
+ if (res.status === UpdateStatus.BUSY) return console.log(chalk.yellow('⏳ Đang có một lần cập nhật khác chạy trên máy này — thử lại sau ít phút.'));
1116
+ console.log(chalk.green(`✅ Đã cài aivin ${res.latest} (trước đó ${res.current}).`));
1117
+ console.log(chalk.gray(' `aivin remote start` chạy nền (tự khởi động cùng máy) tự chuyển sang bản mới khi máy rảnh; cửa sổ đang mở thì đóng và chạy lại.'));
1118
+ } catch (error) {
1119
+ console.error(chalk.red('❌'), error.message);
1120
+ process.exit(1);
1121
+ }
1122
+ });
1123
+
1124
+ const remoteCommand = program
1125
+ .command('remote')
1126
+ .description('Let your Aivin agents work on this computer (Device Agent) - pair, run the listener, manage memory and safety')
1127
+ // Proxy công ty cho mọi lệnh remote gọi máy chủ (ghép máy, remote do, test…) — `start` tự cấu hình kèm --proxy của nó.
1128
+ .hook('preAction', (_cmd, action) => { if (action.name() !== 'start') configureProxy({ explicit: action.opts().proxy }); });
1129
+
1130
+ const remoteFail = (error) => {
1131
+ console.error(chalk.red('❌'), error.message);
1132
+ process.exit(1);
1133
+ };
1134
+
1135
+ remoteCommand
1136
+ .command('start')
1137
+ .description('Pair this computer (first time) and listen for work from your agents in the foreground')
1138
+ .option('--dir <path>', 'Folder the agent may work in (default: the folder saved at pairing, else the current folder)')
1139
+ .option('--name <name>', 'Name shown for this computer (default: hostname)')
1140
+ .option('--repair', 'Pair again (new device token; the old one stops working)')
1141
+ .option('--full-access', 'Let the agent work anywhere on this computer (all drives; relative paths start at your home folder). Kept across restarts; --dir switches back to one folder')
1142
+ .option('--code <code>', 'Pair with a one-time code from Aivin (chat box → Browser ▾ → Add this computer) - no `aivin login` needed')
1143
+ .option('--server <url>', 'Aivin server the code belongs to (Aivin prints it in the command when needed)')
1144
+ .option('--no-browser', "Don't let AI Browser use a browser window on this computer (web tasks then run in Aivin's server-side browser)")
1145
+ .option('--no-gui', "Don't let the agent control app windows on this computer with the mouse/keyboard (Windows)")
1146
+ .option('--no-meetings', "Don't let the agent take notes of meetings (record the computer's sound + microphone) or take screenshots on this computer (Windows)")
1147
+ .option('--separate-browser', "Always use Aivin's own browser window, never your everyday Chrome/Edge (even if remote debugging is enabled at chrome://inspect/#remote-debugging)")
1148
+ .option('--quiet', 'No interactive logs')
1149
+ .option('--proxy <url>', 'HTTP proxy to reach Aivin through (default: HTTPS_PROXY, else the system proxy setting; "none" = connect directly)')
1150
+ .option('--no-keep-awake', "Don't keep this computer from sleeping while the agent is working on it")
1151
+ .option('--no-auto-update', "Don't download new aivin releases in the background this run (to turn it off for good: aivin update --auto off)")
1152
+ .option('--no-mascot', "Don't show the Aivin mascot on screen this run (to turn it off for good: aivin remote mascot off)")
1153
+ .option('--multi-user', "Organization cloud computer (Linux container provisioned by Aivin): token from AIVIN_DEVICE_TOKEN/AIVIN_DEVICE_ID/AIVIN_SERVER, every org member works in their own Linux account + home folder")
1154
+ .action(async (options) => {
1155
+ try {
1156
+ await startRemoteClient(options);
1157
+ } catch (error) {
1158
+ // Tự khởi động (--quiet) mà đã có cửa sổ khác nhận việc: không phải lỗi — thoát 0 để trình giữ chạy không chạy lại mãi.
1159
+ if (error?.code === DAEMON_RUNNING && options.quiet) {
1160
+ console.error(chalk.gray(error.message));
1161
+ process.exit(0);
1162
+ }
1163
+ // Vừa tự lùi bản: có trình giữ chạy → mã 75, được mở lại ngay bằng bản cũ.
1164
+ if (error?.code === UPDATE_ROLLED_BACK) {
1165
+ console.error(chalk.yellow(`↩ ${error.message}`));
1166
+ process.exit(error.restart ? RESTART_EXIT_CODE : 1);
1167
+ }
1168
+ remoteFail(error);
1169
+ }
1170
+ });
1171
+
1172
+ remoteCommand
1173
+ .command('pair')
1174
+ .description('Pair (or re-pair) this computer with your account without starting the listener')
1175
+ .option('--dir <path>', 'Folder the agent may work in (default: current folder)')
1176
+ .option('--name <name>', 'Name shown for this computer (default: hostname)')
1177
+ .action(async (options) => {
1178
+ try {
1179
+ const roots = [path.resolve(options.dir || process.cwd())];
1180
+ const creds = await pairDevice({ serverUrl: missionServerUrl(), apiKey: process.env.API_KEY, roots, name: options.name, profile: buildDeviceProfile(roots) });
1181
+ console.log(chalk.green(`✅ Đã ghép máy "${creds.name}" (${creds.device_id})`));
1182
+ console.log(chalk.gray(` Thư mục được phép: ${creds.roots.join(' | ')}`));
1183
+ console.log(chalk.gray(' Chạy `aivin remote start` để bắt đầu nhận việc.'));
1184
+ } catch (error) {
1185
+ remoteFail(error);
1186
+ }
1187
+ });
1188
+
1189
+ remoteCommand
1190
+ .command('devices')
1191
+ .description('List computers paired with your account and whether they are online')
1192
+ .action(async () => {
1193
+ try {
1194
+ const devices = await listDevices({ serverUrl: missionServerUrl(), apiKey: process.env.API_KEY });
1195
+ const mine = loadDeviceCredentials()?.device_id;
1196
+ if (!devices.length) return console.log(chalk.gray('Chưa có máy nào được ghép. Chạy `aivin remote start` trên máy cần dùng.'));
1197
+ for (const d of devices) {
1198
+ const state = d.online ? chalk.green('● online') : chalk.gray('○ offline');
1199
+ console.log(`${state} ${chalk.bold(d.name)}${d.device_id === mine ? chalk.cyan(' (máy này)') : ''} ${chalk.gray(`${d.platform || ''} · ${d.tools_count} công cụ · ${d.device_id}`)}`);
1200
+ }
1201
+ } catch (error) {
1202
+ remoteFail(error);
1203
+ }
1204
+ });
1205
+
1206
+ remoteCommand
1207
+ .command('unpair [deviceId]')
1208
+ .description('Revoke a paired computer (default: this one) - its token stops working immediately')
1209
+ .action(async (deviceId) => {
1210
+ try {
1211
+ const target = deviceId || loadDeviceCredentials()?.device_id;
1212
+ if (!target) throw new Error('Máy này chưa được ghép.');
1213
+ await unpairDevice({ serverUrl: missionServerUrl(), apiKey: process.env.API_KEY, deviceId: target });
1214
+ console.log(chalk.green(`✅ Đã thu hồi máy ${target}.`));
1215
+ } catch (error) {
1216
+ remoteFail(error);
1217
+ }
1218
+ });
1219
+
1220
+ remoteCommand
1221
+ .command('pause')
1222
+ .description('Kill switch: refuse every remote call on this computer until `aivin remote resume`')
1223
+ .action(() => {
1224
+ setRemotePaused(true);
1225
+ console.log(chalk.yellow('⏸ Đã tạm dừng — máy này từ chối mọi việc từ xa.'));
1226
+ });
1227
+
1228
+ remoteCommand
1229
+ .command('mascot [action] [combo]')
1230
+ .description('The Aivin mascot floating on screen while the listener runs (Windows): on | off — no argument shows the current setting; hotkey [combo|off|default] — the key combination that calls the mascot (default Win+Alt+Space)')
1231
+ .action((action, combo) => {
1232
+ const lang = mascotLang();
1233
+ if (action === 'hotkey') {
1234
+ try {
1235
+ const setting = loadMascotSettings().hotkey;
1236
+ if (!combo) {
1237
+ const active = hotkeyCandidates(setting);
1238
+ if (!active.length) return console.log('Phím tắt gọi linh vật: tắt (bật lại: aivin remote mascot hotkey default)');
1239
+ return console.log(`Phím tắt gọi linh vật: ${active[0].label}${setting ? '' : ' (mặc định)'} — không đăng ký được thì thử lần lượt: ${active.slice(1).map((h) => h.label).join(', ')}`);
1240
+ }
1241
+ if (combo === 'off') { saveMascotSettings({ hotkey: 'off' }); return console.log(chalk.green('✅ Đã tắt phím tắt gọi linh vật.')); }
1242
+ if (combo === 'default') { saveMascotSettings({ hotkey: null }); return console.log(chalk.green(`✅ Dùng phím tắt mặc định ${DEFAULT_HOTKEYS[0]}.`)); }
1243
+ const hotkey = parseHotkey(combo);
1244
+ const free = probeHotkey(hotkey);
1245
+ if (free === false) {
1246
+ console.log(chalk.yellow(`⚠️ ${hotkey.label} đang bị một ứng dụng khác (hoặc chính linh vật đang chạy) giữ — nếu không phải linh vật thì chọn tổ hợp khác.`));
1247
+ }
1248
+ saveMascotSettings({ hotkey: hotkey.label });
1249
+ return console.log(chalk.green(`✅ Phím tắt gọi linh vật: ${hotkey.label} — có hiệu lực khi linh vật khởi động lại (aivin remote start).`));
1250
+ } catch (error) {
1251
+ return remoteFail(error);
1252
+ }
1253
+ }
1254
+ if (action && !['on', 'off'].includes(action)) remoteFail(new Error(mascotText(lang, MascotText.CMD_USAGE)));
1255
+ if (process.platform !== 'win32') console.log(chalk.gray(mascotText(lang, MascotText.CMD_UNSUPPORTED)));
1256
+ if (!action) return console.log(mascotText(lang, loadMascotSettings().enabled ? MascotText.CMD_STATUS_ON : MascotText.CMD_STATUS_OFF));
1257
+ saveMascotSettings({ enabled: action === 'on' });
1258
+ console.log(chalk.green(`✅ ${mascotText(lang, action === 'on' ? MascotText.CMD_ON : MascotText.CMD_OFF)}`));
1259
+ });
1260
+
1261
+ remoteCommand
1262
+ .command('meeting [action] [title...]')
1263
+ .description('Meeting notes on this computer (Windows, needs `aivin remote start` running): start [title] | stop | status | list | show [id] — records the computer\'s sound (the others) + your microphone, transcribes it when the meeting ends')
1264
+ .option('--then <instruction>', 'start: what Aivin should do with the transcript afterwards, e.g. "summarize and draft an email to my manager"')
1265
+ .option('--lang <vi|en>', 'start: language spoken in the meeting')
1266
+ .option('--no-screens', "start: don't save screenshots when the screen changes")
1267
+ .action(async (action = 'status', titleWords = [], options) => {
1268
+ try {
1269
+ const fmt = (s) => { const m = Math.floor((s || 0) / 60); return `${m} phút ${String((s || 0) % 60).padStart(2, '0')} giây`; };
1270
+ if (action === 'start') {
1271
+ const res = await requestMeeting('start', { title: titleWords.join(' '), then: options.then, lang: options.lang, screens: options.screens });
1272
+ console.log(chalk.green(`🎙️ Đang ghi "${res.title}" (id ${res.id})${res.sources && !res.sources.mic ? ' — không mở được micro' : ''}${res.sources && !res.sources.system ? ' — không mở được âm thanh máy' : ''}.`));
1273
+ console.log(chalk.yellow(' Hãy báo cho mọi người trong cuộc họp biết họ đang được ghi âm.'));
1274
+ console.log(chalk.gray(' Tự dừng khi cửa sổ họp đóng / im lặng lâu; dừng tay: aivin remote meeting stop'));
1275
+ return;
1276
+ }
1277
+ if (action === 'stop') {
1278
+ const res = await requestMeeting('stop', { id: titleWords[0] });
1279
+ console.log(chalk.green(`⏹ Đã dừng ghi "${res.title}" (${fmt(res.duration_s)}) — đang làm biên bản, xem: aivin remote meeting status`));
1280
+ return;
1281
+ }
1282
+ const meetings = createMeetingManager({ media: null });
1283
+ if (action === 'list' || action === 'status') {
1284
+ const list = meetings.list({ limit: action === 'list' ? 20 : 5 });
1285
+ if (!list.length) return console.log(chalk.gray('Chưa ghi cuộc họp nào trên máy này. Bắt đầu: aivin remote meeting start "Tên cuộc họp"'));
1286
+ for (const m of list) {
1287
+ const when = new Date(m.started_at).toLocaleString('vi-VN');
1288
+ console.log(`${m.status === 'recording' ? '🔴' : m.status === 'done' ? '✅' : m.status === 'failed' ? '❌' : '⏳'} ${m.title} ${chalk.gray(`${when} · ${fmt(m.duration_s)} · ${m.status}${m.follow_up ? ` · việc sau họp: ${m.follow_up}` : ''} · ${m.id}`)}`);
1289
+ }
1290
+ return;
1291
+ }
1292
+ if (action === 'show') {
1293
+ const t = meetings.transcript({ id: titleWords[0], max_chars: 100_000 });
1294
+ console.log(t.text || chalk.gray(t.note));
1295
+ return;
1296
+ }
1297
+ remoteFail(new Error('Usage: aivin remote meeting start [title] [--then "..."] | stop | status | list | show [id]'));
1298
+ } catch (error) {
1299
+ remoteFail(error);
1300
+ }
1301
+ });
1302
+
1303
+ remoteCommand
1304
+ .command('policy [action] [value]')
1305
+ .description('Rules enforced on this computer itself (Aivin cannot change them): which steps need a click on this computer, tools turned off, extra blocked commands')
1306
+ .action(async (action, value) => {
1307
+ try {
1308
+ await runPolicyCommand(action, value);
1309
+ } catch (error) {
1310
+ remoteFail(error);
1311
+ }
1312
+ });
1313
+
1314
+ remoteCommand
1315
+ .command('resume')
1316
+ .description('Turn the kill switch off')
1317
+ .action(() => {
1318
+ setRemotePaused(false);
1319
+ console.log(chalk.green('▶ Máy này nhận việc từ xa trở lại.'));
1320
+ });
1321
+
1322
+ remoteCommand
1323
+ .command('enable')
1324
+ .description('Start the listener automatically when this computer starts (Windows: the Aivin tray app, listed in Task Manager → Startup apps)')
1325
+ .option('--dir <path>', 'Folder the agent may work in (default: current folder)')
1326
+ .option('--proxy <url>', 'HTTP proxy the auto-started listener should use (default: detect at every start)')
1327
+ .action((options) => {
1328
+ try {
1329
+ const res = enableAutoStart(options);
1330
+ console.log(chalk.green('✅ Đã bật tự khởi động cùng máy.'));
1331
+ console.log(chalk.gray(` Thư mục: ${res.rootDir}`));
1332
+ console.log(chalk.gray(` Tệp khởi động: ${res.filePath}`));
1333
+ if (res.warning) console.log(chalk.yellow(` ⚠️ ${res.warning}`));
1334
+ } catch (error) {
1335
+ remoteFail(error);
1336
+ }
1337
+ });
1338
+
1339
+ remoteCommand
1340
+ .command('disable')
1341
+ .description('Stop starting the listener with this computer')
1342
+ .action(() => {
1343
+ try {
1344
+ disableAutoStart();
1345
+ console.log(chalk.green('✅ Đã tắt tự khởi động cùng máy.'));
1346
+ } catch (error) {
1347
+ remoteFail(error);
1348
+ }
1349
+ });
1350
+
1351
+ remoteCommand
1352
+ .command('status')
1353
+ .description('Show pairing, allowed folders, kill switch, auto-start, tools and memory of this computer')
1354
+ .action(() => {
1355
+ try {
1356
+ const creds = loadDeviceCredentials();
1357
+ const roots = creds?.roots?.length ? creds.roots : [process.cwd()];
1358
+ const profile = buildDeviceProfile(roots);
1359
+ const { catalog, hash } = buildCatalog(buildTools({ roots, binaries: profile.binaries, projects: profile.projects }));
1360
+ const stats = memoryStats();
1361
+ console.log(chalk.blue('💻 Máy này:'));
1362
+ console.log(chalk.gray(` Mã máy: ${getOrCreateDeviceId()}`));
1363
+ console.log(chalk.gray(` Đã ghép: ${creds ? chalk.green(`có — ${creds.name} @ ${creds.server_url}`) : chalk.yellow('chưa')}`));
1364
+ console.log(chalk.gray(` Thư mục: ${roots.join(' | ')}`));
1365
+ console.log(chalk.gray(` Công tắc ngắt: ${isRemotePaused() ? chalk.yellow('ĐANG TẠM DỪNG') : 'tắt'}`));
1366
+ console.log(chalk.gray(` Tự khởi động: ${getAutoStartStatus().enabled ? 'bật' : 'tắt'}`));
1367
+ console.log(chalk.gray(` Chương trình: ${profile.binaries.join(', ') || '-'}`));
1368
+ console.log(chalk.gray(` Dự án: ${profile.projects.map((p) => `${p.name} (${p.kind})`).join(', ') || '-'}`));
1369
+ console.log(chalk.gray(` Ghi nhớ: ${stats.total} mục (${stats.with_vector} có vector) — ${stats.dir}`));
1370
+ console.log(chalk.blue(`\n🛠️ ${catalog.length} công cụ (dấu vân tay ${hash.slice(0, 12)}):`));
1371
+ for (const t of catalog) console.log(` - ${chalk.cyan(t.name)}${t.read_only ? chalk.gray(' [chỉ đọc]') : t.destructive ? chalk.red(' [không hoàn tác]') : chalk.yellow(' [ghi]')}`);
1372
+ } catch (error) {
1373
+ remoteFail(error);
1374
+ }
1375
+ });
1376
+
1377
+ remoteCommand
1378
+ .command('test')
1379
+ .description('Check the server connection and whether the server sees this computer online')
1380
+ .action(async () => {
1381
+ try {
1382
+ const r = await testRemoteConnection();
1383
+ console.log(chalk.gray(` Máy chủ: ${r.serverUrl} — ${r.httpOk ? chalk.green(`thông (${r.latencyMs} ms)`) : chalk.red('không kết nối được')}`));
1384
+ console.log(chalk.gray(` Đã ghép: ${r.paired ? `có (${r.deviceId})` : chalk.yellow('chưa — chạy aivin remote start')}`));
1385
+ if (r.online !== null) console.log(chalk.gray(` Online: ${r.online ? chalk.green('có') : chalk.yellow(r.registered === false ? 'máy chủ không có máy này (đã thu hồi?)' : 'không — chạy aivin remote start')}`));
1386
+ if (r.error) console.log(chalk.yellow(` ⚠️ ${r.error}`));
1387
+ } catch (error) {
1388
+ remoteFail(error);
1389
+ }
1390
+ });
1391
+
1392
+ remoteCommand
1393
+ .command('logs')
1394
+ .description('Recent remote activity on this computer')
1395
+ .option('--limit <n>', 'Entries to show (default 30)', '30')
1396
+ .option('--clear', 'Clear the activity log')
1397
+ .action((options) => {
1398
+ if (options.clear) {
1399
+ clearLogs();
1400
+ return console.log(chalk.green('✅ Đã xoá nhật ký.'));
1401
+ }
1402
+ const logs = getRecentLogs(options.limit);
1403
+ if (!logs.length) return console.log(chalk.gray('Chưa có hoạt động nào.'));
1404
+ for (const log of logs) {
1405
+ const time = log.timestamp ? new Date(log.timestamp).toLocaleTimeString() : '';
1406
+ if (log.type === 'tool_call') console.log(` [${time}] ${log.success ? chalk.green('✓') : chalk.red('✗')} ${chalk.cyan(log.tool)}${log.ms !== undefined ? chalk.gray(` ${log.ms} ms`) : ''} ${log.error ? chalk.red(log.error) : ''}`);
1407
+ else console.log(` [${time}] ${chalk.gray(log.type)} ${chalk.gray(log.reason || log.serverUrl || '')}`);
1408
+ }
1409
+ });
1410
+
1411
+ remoteCommand
1412
+ .command('memory [action] [value...]')
1413
+ .description('On-device memory (~/.aivin/memory/*.yaml): list [kind] | search <words> | add <text> | forget <id> | clear [kind]')
1414
+ .option('--kind <kind>', `Kind: ${Object.values(MemoryKind).join(', ')}`)
1415
+ .option('--key <key>', 'Stable key for add (default: derived from the text)')
1416
+ .action((action = 'list', valueParts = [], options) => {
1417
+ try {
1418
+ const value = valueParts.join(' ').trim();
1419
+ if (action === 'search') {
1420
+ if (!value) throw new Error('Dùng: aivin remote memory search <từ khoá>');
1421
+ const hits = searchMemory({ query: value, kinds: options.kind ? [options.kind] : undefined, limit: 20 });
1422
+ if (!hits.length) return console.log(chalk.gray('Không có mục nào khớp.'));
1423
+ hits.forEach((h) => console.log(` ${chalk.gray(h.id)} [${h.kind}] ${chalk.bold(h.key)}: ${h.text}`));
1424
+ return;
1425
+ }
1426
+ if (action === 'add') {
1427
+ if (!value) throw new Error('Dùng: aivin remote memory add "<nội dung>" --kind fact --key <khoá>');
1428
+ const kind = options.kind || MemoryKind.FACT;
1429
+ const key = options.key || value.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').slice(0, 60);
1430
+ putMemoryItems([{ kind, key, text: value }]);
1431
+ return console.log(chalk.green(`✅ Đã nhớ [${kind}] ${key}`));
1432
+ }
1433
+ if (action === 'forget') {
1434
+ if (!value) throw new Error('Dùng: aivin remote memory forget <id> (xem id bằng memory list / search)');
1435
+ const res = deleteMemoryItems({ ids: value.split(/[\s,]+/) });
1436
+ return console.log(chalk.green(`✅ Đã quên ${res.deleted} mục.`));
1437
+ }
1438
+ if (action === 'clear') {
1439
+ clearDeviceMemory(value || options.kind || undefined);
1440
+ return console.log(chalk.green('✅ Đã xoá bộ nhớ.'));
1441
+ }
1442
+ const page = listMemoryItems({ kind: value || options.kind, limit: 100 });
1443
+ const stats = memoryStats();
1444
+ console.log(chalk.blue(`🧠 Bộ nhớ trên máy: ${stats.total} mục — ${stats.dir} (sửa tay các tệp .yaml được)`));
1445
+ page.items.forEach((i) => console.log(` ${chalk.gray(i.id)} [${i.kind}] ${chalk.bold(i.key)}: ${String(i.text).slice(0, 160)}`));
1446
+ if (page.next_cursor !== null) console.log(chalk.gray(` … còn ${page.total - page.items.length} mục`));
1447
+ } catch (error) {
1448
+ remoteFail(error);
1449
+ }
1450
+ });
1451
+
1452
+ remoteCommand
1453
+ .command('reindex')
1454
+ .description('Rebuild the file index of the allowed folders now')
1455
+ .action(async () => {
1456
+ try {
1457
+ const creds = loadDeviceCredentials();
1458
+ const index = createFileIndex(indexRootsFor(creds?.roots || [process.cwd()], creds?.access === DeviceAccess.FULL));
1459
+ const stats = await index.build();
1460
+ index.close();
1461
+ console.log(chalk.green(`✅ Chỉ mục: ${stats.files} tệp (${stats.updated} cập nhật, ${stats.removed} bỏ) trong ${stats.ms} ms`));
1462
+ } catch (error) {
1463
+ remoteFail(error);
1464
+ }
1465
+ });
1466
+
1467
+ remoteCommand
1468
+ .command('reset-id')
1469
+ .description('Give this computer a new device id (cloned machines) - you must pair again')
1470
+ .action(() => {
1471
+ const id = resetDeviceId();
1472
+ console.log(chalk.green(`✅ Mã máy mới: ${id} — chạy \`aivin remote start\` để ghép lại.`));
1473
+ });
1474
+
1475
+ remoteCommand
1476
+ .command('do [objective]')
1477
+ .description('Give a job to the Device Agent on your computer (the listener must be running there)')
1478
+ .option('--device <name>', 'Which paired computer (default: your online one)')
1479
+ .option('--cwd <path>', 'Folder the job is about')
1480
+ .option('--file <id...>', 'Aivin workspace file id(s) the job may save onto the computer')
1481
+ .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1482
+ .option('--agent <id>', 'Agent to act as (default: the workspace default agent)')
1483
+ .option('--no-watch', 'Do not stream progress')
1484
+ .action(async (objective, options) => {
1485
+ try {
1486
+ objective = await requireArg(objective, { prompt: 'What should the agent do on your computer?', usage: 'Usage: aivin remote do "<job>"' });
1487
+ await runRemoteMission(objective, options);
1488
+ } catch (error) {
1489
+ remoteFail(error);
1490
+ }
1491
+ });
1492
+
1493
+ const doCommand = program
1494
+ .command('do [agentNickname] [mission]')
1495
+ .description("Have <agentNickname> work toward a goal in the background - not a specific deployed plugin")
1496
+ .option('--workspace <id>', 'Workspace id to run in (default: your personal workspace)')
1497
+ .option('--project <id>', 'Project id within the workspace')
1498
+ .option('--no-watch', 'Fire the mission and return immediately - skip streaming live progress')
1499
+ .action(async (agentNickname, mission, options) => {
1500
+ try {
1501
+ mission = await requireArg(mission, {
1502
+ prompt: 'What should the agent do?',
1503
+ usage: 'Usage: aivin do <agent_nickname> "<mission detail>" (or: aivin do job "<automation job description>")',
1504
+ });
1505
+ await runMission(agentNickname, mission, options);
1506
+ } catch (error) {
1507
+ console.error(chalk.red('❌'), error.message);
1508
+ process.exit(1);
1509
+ }
1510
+ });
1511
+
1512
+ doCommand
1513
+ .command('job [description]')
1514
+ .description('Create a new automation job from a plain-language description')
1515
+ .option('--workspace <id>', 'Workspace id to create the job in (default: your personal workspace)')
1516
+ .option('--project <id>', 'Project id within the workspace')
1517
+ .option('--agent <id>', "Agent id the job runs as (default: the workspace's default agent)")
1518
+ .option('--schedule <condition>', 'Natural-language schedule, e.g. "every Monday at 9am" (default: let the platform infer one)')
1519
+ .action(async (description, options) => {
1520
+ try {
1521
+ description = await requireArg(description, { prompt: 'What should this automation job do?', usage: 'Usage: aivin do job "<automation job description>"' });
1522
+ await createAutomationJob(description, options);
1523
+ } catch (error) {
1524
+ console.error(chalk.red('❌'), error.message);
1525
+ process.exit(1);
1526
+ }
1527
+ });
1528
+
1529
+ const taskCommand = program
1530
+ .command('task [description]')
1531
+ .description('Create a new task from a plain-language description')
1532
+ .option('--workspace <id>', 'Workspace id to create the task in (default: your personal workspace)')
1533
+ .option('--project <id>', 'Project id within the workspace')
1534
+ .option('--assignee <userId>', 'User id to assign the task to (default: unassigned)')
1535
+ .action(async (description, options) => {
1536
+ try {
1537
+ description = await requireArg(description, {
1538
+ prompt: 'What is this task?',
1539
+ usage: 'Usage: aivin task "<description>" (or: aivin task list/mine/get/update/delete)',
1540
+ });
1541
+ await createTask(description, options);
1542
+ } catch (error) {
1543
+ console.error(chalk.red('❌'), error.message);
1544
+ process.exit(1);
1545
+ }
1546
+ });
1547
+
1548
+ taskCommand
1549
+ .command('list')
1550
+ .description('List tasks in a project')
1551
+ .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1552
+ .option('--project <id>', "Project id (default: the workspace's first project)")
1553
+ .option('--status <status>', 'Filter by status (todo/doing/done/backlog/cancel)')
1554
+ .option('--assignee <userId>', 'Filter by assignee user id')
1555
+ .option('--search <text>', 'Filter by search text')
1556
+ .action(async (options) => {
1557
+ try {
1558
+ await listTasks(options);
1559
+ } catch (error) {
1560
+ console.error(chalk.red('❌'), error.message);
1561
+ process.exit(1);
1562
+ }
1563
+ });
1564
+
1565
+ taskCommand
1566
+ .command('mine')
1567
+ .description('List tasks assigned to you in a project')
1568
+ .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1569
+ .option('--project <id>', "Project id (default: the workspace's first project)")
1570
+ .action(async (options) => {
1571
+ try {
1572
+ await listMyTasks(options);
1573
+ } catch (error) {
1574
+ console.error(chalk.red('❌'), error.message);
1575
+ process.exit(1);
1576
+ }
1577
+ });
1578
+
1579
+ taskCommand
1580
+ .command('get [id]')
1581
+ .description('Get a task by id')
1582
+ .action(async (id) => {
1583
+ try {
1584
+ id = await requireArg(id, { prompt: 'Task id:', usage: 'Usage: aivin task get <id>' });
1585
+ await getTaskById(id);
1586
+ } catch (error) {
1587
+ console.error(chalk.red('❌'), error.message);
1588
+ process.exit(1);
1589
+ }
1590
+ });
1591
+
1592
+ taskCommand
1593
+ .command('update [id]')
1594
+ .description('Update a task')
1595
+ .option('--status <status>', 'todo|doing|done|backlog|cancel')
1596
+ .option('--title <title>', 'New title')
1597
+ .option('--description <text>', 'New content/description')
1598
+ .option('--assignee <userId>', 'Reassign to this user id')
1599
+ .option('--priority <priority>', 'low|medium|high|urgent')
1600
+ .action(async (id, options) => {
1601
+ try {
1602
+ id = await requireArg(id, { prompt: 'Task id:', usage: 'Usage: aivin task update <id>' });
1603
+ await updateTaskById(id, options);
1604
+ } catch (error) {
1605
+ console.error(chalk.red('❌'), error.message);
1606
+ process.exit(1);
1607
+ }
1608
+ });
1609
+
1610
+ taskCommand
1611
+ .command('delete [id]')
1612
+ .description('Delete a task')
1613
+ .option('-y, --yes', 'Skip the confirmation prompt (for scripts/CI)')
1614
+ .action(async (id, options) => {
1615
+ try {
1616
+ id = await requireArg(id, { prompt: 'Task id to delete:', usage: 'Usage: aivin task delete <id>' });
1617
+ await deleteTaskById(id, options);
1618
+ } catch (error) {
1619
+ console.error(chalk.red('❌'), error.message);
1620
+ process.exit(1);
1621
+ }
1622
+ });
1623
+
1624
+ program
1625
+ .command('workspace')
1626
+ .description('Browse your workspaces and projects, and pick one to use with --workspace/--project')
1627
+ .option('--plain', 'Print a flat list instead of the interactive picker (for scripts/CI)')
1628
+ .action(async (options) => {
1629
+ try {
1630
+ await pickWorkspaceAndProject(options);
1631
+ } catch (error) {
1632
+ console.error(chalk.red('❌'), error.message);
1633
+ process.exit(1);
1634
+ }
1635
+ });
1636
+
1637
+ const agentCommand = program.command('agent').description('List, search, install, create, and publish AI Staff agents');
1638
+
1639
+ agentCommand
1640
+ .command('list')
1641
+ .description('Browse agents already installed in a workspace (↑/↓ to move, space/enter for details, q to quit)')
1642
+ .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1643
+ .option('--plain', 'Print a flat list instead of the interactive browser (for scripts/CI)')
1644
+ .action(async (options) => {
1645
+ try {
1646
+ await listAgentsCmd(options);
1647
+ } catch (error) {
1648
+ console.error(chalk.red('❌'), error.message);
1649
+ process.exit(1);
1650
+ }
1651
+ });
1652
+
1653
+ agentCommand
1654
+ .command('search [query]')
1655
+ .description('Search the AI Staff marketplace for an agent')
1656
+ .option('--workspace <id>', 'Workspace id for context (default: your personal workspace)')
1657
+ .option('--limit <n>', 'Max results to show')
1658
+ .action(async (query, options) => {
1659
+ try {
1660
+ query = await requireArg(query, { prompt: 'What are you looking for?', usage: 'Usage: aivin agent search "<query>"' });
1661
+ const serverUrl = missionServerUrl();
1662
+ const authHeaders = missionAuthHeaders();
1663
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
1664
+ const results = await searchAgents(serverUrl, authHeaders, {
1665
+ query,
1666
+ workspaceId: workspace.id || workspace._id,
1667
+ limit: options.limit,
1668
+ });
1669
+ if (results.length === 0) {
1670
+ console.log(chalk.yellow(`No agents found matching "${query}".`));
1671
+ return;
1672
+ }
1673
+ console.log(chalk.blue(`Found ${results.length} agent(s) matching "${query}":\n`));
1674
+ results.forEach((a) => {
1675
+ console.log(chalk.bold(a.nickname || a.name) + chalk.gray(` (${a.id})`));
1676
+ if (a.bio) console.log(` ${a.bio}`);
1677
+ console.log();
1678
+ });
1679
+ } catch (error) {
1680
+ console.error(chalk.red('❌'), error.message);
1681
+ process.exit(1);
1682
+ }
1683
+ });
1684
+
1685
+ agentCommand
1686
+ .command('install [query]')
1687
+ .description('Search the marketplace and install an agent into a workspace')
1688
+ .option('--workspace <id>', 'Workspace id to install into (default: your personal workspace)')
1689
+ .action(async (query, options) => {
1690
+ try {
1691
+ const serverUrl = missionServerUrl();
1692
+ const authHeaders = missionAuthHeaders();
1693
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
1694
+ const workspaceId = workspace.id || workspace._id;
1695
+
1696
+ let picked;
1697
+ if (query) {
1698
+ const results = await searchAgents(serverUrl, authHeaders, { query, workspaceId, limit: 10 });
1699
+ if (results.length === 0) throw new Error(`No marketplace agents found matching "${query}".`);
1700
+ if (!process.stdout.isTTY || !process.stdin.isTTY) {
1701
+ picked = results[0];
1702
+ } else {
1703
+ const { pickedAgent } = await inquirer.prompt([
1704
+ {
1705
+ type: 'select',
1706
+ name: 'pickedAgent',
1707
+ message: 'Install which agent?',
1708
+ choices: results.map((a) => ({ name: `${a.nickname || a.name}${a.bio ? chalk.gray(` - ${a.bio}`) : ''}`, value: a })),
1709
+ },
1710
+ ]);
1711
+ picked = pickedAgent;
1712
+ }
1713
+ } else {
1714
+ picked = await installAgentInteractive(serverUrl, authHeaders, workspaceId);
1715
+ console.log(chalk.gray(`Installed into ${workspace.name || workspaceId}.`));
1716
+ return;
1717
+ }
1718
+
1719
+ await pullAgentIntoWorkspace(serverUrl, authHeaders, { agentId: picked.id, workspaceId });
1720
+ console.log(chalk.green(`✅ Installed "${picked.nickname || picked.name}" into ${workspace.name || workspaceId}.`));
1721
+ } catch (error) {
1722
+ console.error(chalk.red('❌'), error.message);
1723
+ process.exit(1);
1724
+ }
1725
+ });
1726
+
1727
+ agentCommand
1728
+ .command('make')
1729
+ .description('Create a brand new AI Staff agent')
1730
+ .option('--name <name>', 'Agent name')
1731
+ .option('--nickname <nickname>', 'Agent nickname (used to @-mention/target it)')
1732
+ .option('--email <email>', 'Agent email')
1733
+ .option('--bio <bio>', 'Short bio')
1734
+ .option('--workspace <id>', 'Workspace to install the new agent into (default: your personal workspace)')
1735
+ .action(async (options) => {
1736
+ try {
1737
+ const serverUrl = missionServerUrl();
1738
+ const authHeaders = missionAuthHeaders();
1739
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
1740
+
1741
+ const canPrompt = process.stdout.isTTY && process.stdin.isTTY;
1742
+ const answers = { name: options.name, nickname: options.nickname, email: options.email, bio: options.bio };
1743
+ if ((!answers.name || !answers.nickname || !answers.email) && canPrompt) {
1744
+ const prompted = await inquirer.prompt(
1745
+ [
1746
+ !answers.name && { type: 'input', name: 'name', message: 'Agent name:', validate: (v) => v.trim().length > 0 || 'Required' },
1747
+ !answers.nickname && {
1748
+ type: 'input',
1749
+ name: 'nickname',
1750
+ message: 'Agent nickname (used to @-mention/target it):',
1751
+ validate: (v) => v.trim().length > 0 || 'Required',
1752
+ },
1753
+ !answers.email && { type: 'input', name: 'email', message: 'Agent email:', validate: (v) => v.trim().length > 0 || 'Required' },
1754
+ !answers.bio && { type: 'input', name: 'bio', message: 'Short bio (optional):' },
1755
+ ].filter(Boolean),
1756
+ );
1757
+ Object.assign(answers, prompted);
1758
+ }
1759
+ if (!answers.name || !answers.nickname || !answers.email) {
1760
+ throw new Error('Usage: aivin agent make --name <name> --nickname <nickname> --email <email> [--bio <bio>]');
1761
+ }
1762
+
1763
+ const agent = await createAgent(serverUrl, authHeaders, { ...answers, workspaceId: workspace.id || workspace._id });
1764
+ console.log(chalk.green(`✅ Created agent "${agent.nickname || agent.name}"!`));
1765
+ if (agent.id) console.log(chalk.gray(` ID: ${agent.id}`));
1766
+ } catch (error) {
1767
+ console.error(chalk.red('❌'), error.message);
1768
+ process.exit(1);
1769
+ }
1770
+ });
1771
+
1772
+ agentCommand
1773
+ .command('publish [agentId]')
1774
+ .description('Publish an agent you own to the marketplace')
1775
+ .option('--workspace <id>', 'Workspace the agent lives in (default: your personal workspace)')
1776
+ .action(async (agentId, options) => {
1777
+ try {
1778
+ const serverUrl = missionServerUrl();
1779
+ const authHeaders = missionAuthHeaders();
1780
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
1781
+
1782
+ if (!agentId) {
1783
+ const agents = workspace.agents || [];
1784
+ if (agents.length === 0) throw new Error(`Workspace "${workspace.name}" has no agents to publish.`);
1785
+ if (!process.stdout.isTTY || !process.stdin.isTTY) {
1786
+ throw new Error('Usage: aivin agent publish <agentId>');
1787
+ }
1788
+ const { pickedAgentId } = await inquirer.prompt([
1789
+ {
1790
+ type: 'select',
1791
+ name: 'pickedAgentId',
1792
+ message: 'Publish which agent?',
1793
+ choices: agents.map((a) => ({ name: a.nickname || a.name || a.id, value: a.id || a.agent_id })),
1794
+ },
1795
+ ]);
1796
+ agentId = pickedAgentId;
1797
+ }
1798
+
1799
+ await publishAgent(serverUrl, authHeaders, { agentId, workspaceId: workspace.id || workspace._id });
1800
+ console.log(chalk.green(`✅ Published agent ${agentId} to the marketplace.`));
1801
+ } catch (error) {
1802
+ console.error(chalk.red('❌'), error.message);
1803
+ process.exit(1);
1804
+ }
1805
+ });
1806
+
1807
+ const projectCommand = program.command('project').description('List, create, update, and delete projects within a workspace');
1808
+
1809
+ projectCommand
1810
+ .command('list')
1811
+ .description('List projects in a workspace')
1812
+ .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1813
+ .action(async (options) => {
1814
+ try {
1815
+ await listProjectsCmd(options);
1816
+ } catch (error) {
1817
+ console.error(chalk.red('❌'), error.message);
1818
+ process.exit(1);
1819
+ }
1820
+ });
1821
+
1822
+ projectCommand
1823
+ .command('create [name]')
1824
+ .description('Create a new project in a workspace')
1825
+ .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1826
+ .action(async (name, options) => {
1827
+ try {
1828
+ name = await requireArg(name, { prompt: 'Project name:', usage: 'Usage: aivin project create <name>' });
1829
+ await createProjectCmd(name, options);
1830
+ } catch (error) {
1831
+ console.error(chalk.red('❌'), error.message);
1832
+ process.exit(1);
1833
+ }
1834
+ });
1835
+
1836
+ projectCommand
1837
+ .command('update [id]')
1838
+ .description('Update a project (currently: rename)')
1839
+ .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1840
+ .option('--name <name>', 'New name')
1841
+ .action(async (id, options) => {
1842
+ try {
1843
+ id = await requireArg(id, { prompt: 'Project id:', usage: 'Usage: aivin project update <id> --name <new name>' });
1844
+ await updateProjectCmd(id, options);
1845
+ } catch (error) {
1846
+ console.error(chalk.red('❌'), error.message);
1847
+ process.exit(1);
1848
+ }
1849
+ });
1850
+
1851
+ projectCommand
1852
+ .command('delete [id]')
1853
+ .description('Delete a project')
1854
+ .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1855
+ .option('-y, --yes', 'Skip the confirmation prompt (for scripts/CI)')
1856
+ .action(async (id, options) => {
1857
+ try {
1858
+ id = await requireArg(id, { prompt: 'Project id to delete:', usage: 'Usage: aivin project delete <id>' });
1859
+ await deleteProjectCmd(id, options);
1860
+ } catch (error) {
1861
+ console.error(chalk.red('❌'), error.message);
1862
+ process.exit(1);
1863
+ }
1864
+ });
1865
+
1866
+ export {
1867
+ validatePluginConfig,
1868
+ incrementVersion,
1869
+ validateMcpProxyConfig,
1870
+ buildDeploymentPayload,
1871
+ buildMcpManifest,
1872
+ parseMcpArgs,
1873
+ guessConnectorQueryFromEnvVarName,
1874
+ setFieldConnector,
1875
+ buildRegisterConnectorDto,
1876
+ buildCreateTaskPayload,
1877
+ buildDeviceProfile,
1878
+ buildTools,
1879
+ buildCatalog,
1880
+ enableAutoStart,
1881
+ disableAutoStart,
1882
+ getAutoStartStatus,
1883
+ resetDeviceId,
1884
+ getRecentLogs,
1885
+ clearLogs,
1886
+ testRemoteConnection,
1887
+ runRemoteMission,
1888
+ };
1889
+
1890
+ // Only parse argv when run directly (`aivin ...` / `node bin/cli.mjs ...`),
1891
+ // not when this module is imported (e.g. by tests) - otherwise Commander
1892
+ // would parse the importing process's argv and could call process.exit().
1893
+ //
1894
+ // `import.meta.url` is always the module's real (symlink-resolved) path, but `process.argv[1]` is
1895
+ // whatever literal path launched it - through `npm link`'s global shim that's a symlink
1896
+ // (~/AppData/Roaming/npm/node_modules/@aivin-labs/sdk/bin/cli.mjs -> this repo), which would never
1897
+ // string-equal the resolved URL and silently skip program.parse() entirely (global `aivin` would
1898
+ // do nothing at all). Resolve argv[1] through the same symlink before comparing.
1899
+ function resolveIsMain() {
1900
+ // Tệp chạy đóng gói: chính nó là chương trình, không có chuyện bị import.
1901
+ if (process.env.AIVIN_CLI_BINARY) return true;
1902
+ if (!process.argv[1]) return false;
1903
+ try {
1904
+ return import.meta.url === pathToFileURL(fs.realpathSync(process.argv[1])).href;
1905
+ } catch {
1906
+ return import.meta.url === pathToFileURL(process.argv[1]).href;
1907
+ }
1908
+ }
1909
+
1910
+ if (resolveIsMain()) {
1911
+ program.parse(process.argv);
1912
+ }