@aivin-labs/cli 1.0.28 → 1.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -51,30 +51,9 @@ Aivin is a modular, composable ecosystem for agentic software:
51
51
 
52
52
  The CLI brings the full power of **AIVIN Bot** directly into your terminal workflows:
53
53
 
54
- ```mermaid
55
- flowchart TD
56
- CLIUser(["Terminal / Developer"]) --> Command["aivin CLI Commands"]
57
-
58
- subgraph BotActions["AIVIN Bot Actions"]
59
- Command -->|"aivin do [agent] [mission]"| AgentTask["AI Staff Goal Execution"]
60
- Command -->|"aivin plugin ask [mission]"| AutoMatch["Auto-Pick & Execute Best Plugin"]
61
- Command -->|"aivin browser [mission]"| WebTask["Autonomous Web Navigation"]
62
- Command -->|"aivin do job [description]"| AutoJob["Natural Language Scheduled Cron"]
63
- end
64
-
65
- subgraph RemoteSupervision["Supervised Local Execution"]
66
- Command -->|"aivin remote start"| RemoteTunnel["Secure Outbound Tunnel"]
67
- RemoteTunnel --> LocalBrowser["Isolated Browser Profile (~/.aivin)"]
68
- RemoteTunnel --> DesktopMascot["Windows Interactive Floating Mascot"]
69
- RemoteTunnel --> CDPFilter["CDP Safety Filter: Block Local Files & Executables"]
70
- end
71
-
72
- subgraph Extensibility["Zero-Code Tooling"]
73
- Command -->|"aivin mcp <url>"| MCPProxy["Auto-Convert MCP Server to Plugin"]
74
- Command -->|"aivin init <name>"| AIScaffold["AI-Generated Typed Plugin Project"]
75
- Command -->|"aivin deploy"| Marketplace["Deploy to Organization / Marketplace"]
76
- end
77
- ```
54
+ <p align="center">
55
+ <img src="docs/media/cli-capabilities.png" alt="Diagram of AIVIN CLI capabilities across AI agents and automation, supervised local execution, and the plugin ecosystem" width="1000" />
56
+ </p>
78
57
 
79
58
  ### 1. Goal-Driven Staff Agents (`aivin do`)
80
59
  Dispatch an objective directly to an AI Staff agent. The agent breaks down the mission, queries relevant documents, invokes available plugins, and reports back:
@@ -104,31 +83,9 @@ aivin plugin ask "Convert the quarterly sales data in data.csv into an executive
104
83
 
105
84
  ## How the CLI Powers AIVIN Bot
106
85
 
107
- ```mermaid
108
- sequenceDiagram
109
- autonumber
110
- actor Dev as Developer
111
- participant CLI as aivin CLI
112
- participant Cloud as AIVIN Platform / Bot
113
- participant Browser as Local Browser Window
114
- participant Target as Target Web / SaaS
115
-
116
- Dev->>CLI: aivin remote start --code <code>
117
- CLI->>Cloud: Authenticate and establish outbound tunnel
118
- Cloud-->>CLI: Machine connected to AIVIN Bot
119
-
120
- Dev->>Cloud: Assign web mission via Chat or CLI
121
- Cloud->>CLI: Route browser action to paired computer
122
- CLI->>Browser: Launch isolated profile with existing user cookies
123
- Browser->>Target: Navigate and execute steps
124
- opt Requires 2FA or Human Checkpoint
125
- CLI->>Dev: Native desktop notification / Mascot alert
126
- Dev->>Browser: Complete 2FA prompt
127
- end
128
- Browser->>Target: Finalize download or update
129
- CLI-->>Cloud: Mission complete & report progress
130
- Cloud-->>Dev: Return finalized result
131
- ```
86
+ <p align="center">
87
+ <img src="docs/media/aivin-mission-flow.png" alt="Five-step AIVIN web mission flow, including optional human approval and result reporting" width="1000" />
88
+ </p>
132
89
 
133
90
  ---
134
91
 
@@ -198,7 +155,7 @@ Have an existing project you want to wrap? `aivin plugin convert` converts it in
198
155
  ## Aivin Mascot on Windows
199
156
 
200
157
  <p align="center">
201
- <img src="docs/media/aivin-mascot-live.gif" alt="The live Aivin mascot showing chat, file drag, and attached-file states" width="480" />
158
+ <img src="docs/media/aivin-mascot-live.gif" alt="The live Aivin mascot ask box showing a conversation and the mascot" width="704" />
202
159
  </p>
203
160
 
204
161
  When Aivin Remote is running on Windows, an interactive animated **Aivin Mascot** floats smoothly above your desktop windows:
package/bin/cli.mjs CHANGED
@@ -23,6 +23,7 @@ import { flattenManifestFile } from '@aivin-labs/sdk';
23
23
  import './lib/cancellation.mjs';
24
24
 
25
25
  import { DEFAULT_AIVIN_BASE_URL, GLOBAL_CREDENTIALS_PATH, fetchWebUrl, loadActiveContext, clearActiveContext } from './lib/context.mjs';
26
+ import { resolveServerUrl as normalizeServerUrl, readActiveServer, setActiveServer, serverLabel } from './lib/servers.mjs';
26
27
  import { requireArg } from './lib/util.mjs';
27
28
  import { readStdin, createFromJSON, createInteractive, validatePluginConfig, validateMcpProxyConfig } from './lib/scaffold.mjs';
28
29
  import { buildDeploymentPayload, deployPlugin, incrementVersion } from './lib/deploy.mjs';
@@ -57,7 +58,7 @@ import {
57
58
  import { runMission, runBrowserMission } from './lib/mission.mjs';
58
59
  import { DeviceAccess } from './lib/remote/constants.mjs';
59
60
  import { configureProxy } from './lib/remote/netProxy.mjs';
60
- import { DAEMON_RUNNING } from './lib/remote/daemonLock.mjs';
61
+ import { DAEMON_RUNNING, lockHolder } from './lib/remote/daemonLock.mjs';
61
62
  import { runPolicyCommand } from './lib/remote/policyCommand.mjs';
62
63
  import { loadMascotSettings, requestMascotAttach, saveMascotSettings } from './lib/remote/mascot/index.mjs';
63
64
  import { forgetWorkFolder } from './lib/remote/workFolder.mjs';
@@ -135,9 +136,12 @@ import {
135
136
  dotenv.config({ quiet: true });
136
137
 
137
138
  {
138
- const activeContext = loadActiveContext();
139
+ const selectedServer = process.env.AIVIN_BASE_URL
140
+ ? normalizeServerUrl(process.env.AIVIN_BASE_URL)
141
+ : (readActiveServer() || loadDeviceCredentials()?.server_url || DEFAULT_AIVIN_BASE_URL);
142
+ process.env.AIVIN_BASE_URL = selectedServer;
143
+ const activeContext = loadActiveContext(selectedServer);
139
144
  if (activeContext) {
140
- if (!process.env.AIVIN_BASE_URL) process.env.AIVIN_BASE_URL = activeContext.base_url;
141
145
  if (!process.env.API_KEY) process.env.API_KEY = activeContext.api_key;
142
146
  if (!process.env.SDK_ENDPOINT && activeContext.sdk_endpoint) process.env.SDK_ENDPOINT = activeContext.sdk_endpoint;
143
147
  }
@@ -826,9 +830,44 @@ mcpCommand
826
830
  }
827
831
  });
828
832
 
833
+ program
834
+ .command('server [target]')
835
+ .description('Show or switch the active Aivin server (cloud, vn, local, or a URL)')
836
+ .action(async (target) => {
837
+ try {
838
+ const current = normalizeServerUrl(process.env.AIVIN_BASE_URL || readActiveServer() || DEFAULT_AIVIN_BASE_URL);
839
+ if (!target) {
840
+ console.log(`Máy chủ đang chọn: ${serverLabel(current)} (${current})`);
841
+ if (!loadActiveContext(current)) console.log(chalk.yellow(' Chưa đăng nhập CLI ở máy chủ này — chạy `aivin login` hoặc ghép máy bằng mã.'));
842
+ return;
843
+ }
844
+ const next = normalizeServerUrl(target);
845
+ if (next === current) return console.log(`Đang dùng ${serverLabel(next)} (${next}).`);
846
+ const holder = lockHolder();
847
+ if (holder) {
848
+ const { proceed } = await inquirer.prompt([{
849
+ type: 'confirm', name: 'proceed', default: false,
850
+ message: `Đổi sang ${serverLabel(next)} sẽ dừng daemon PID ${holder} và huỷ việc đang chạy. Tiếp tục?`,
851
+ }]);
852
+ if (!proceed) return console.log(chalk.gray('Đã huỷ; máy chủ hiện tại không đổi.'));
853
+ }
854
+ setActiveServer(next);
855
+ if (holder) {
856
+ try { process.kill(holder, 'SIGTERM'); } catch (error) { if (error?.code !== 'ESRCH') throw error; }
857
+ }
858
+ console.log(chalk.green(`✅ Đã chọn ${serverLabel(next)} (${next}).`));
859
+ if (loadActiveContext(next)) console.log(chalk.gray(' CLI sẽ dùng thông tin đăng nhập đã lưu riêng cho máy chủ này.'));
860
+ else console.log(chalk.yellow(' Chưa có đăng nhập cho máy chủ này; chạy `aivin login` nếu cần dùng API.'));
861
+ if (holder) console.log(chalk.gray(' Phiên nhận việc đã được dừng; khay sẽ mở lại bằng token ghép riêng của server mới. Nếu đang chạy trong terminal, hãy chạy lại `aivin remote start`.'));
862
+ } catch (error) {
863
+ console.error(chalk.red('❌'), error.message);
864
+ process.exitCode = 1;
865
+ }
866
+ });
867
+
829
868
  program
830
869
  .command('login')
831
- .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`.')
870
+ .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 api.aivin.vn`.')
832
871
  .description('Log in and save an API key for plugin deployment (opens your browser by default)')
833
872
  .option('-k, --api-key <key>', 'Set API key directly (skip login entirely)')
834
873
  .option('--basic', 'Log in with email/password directly in the terminal instead of a browser')
@@ -836,9 +875,9 @@ program
836
875
  .option('--client <client>', 'Client/org id to use with --basic (default: "aivin.cloud")')
837
876
  .action(async (baseUrl, options) => {
838
877
  try {
839
- // Bare hostname (no scheme) is the common case for a quick `aivin login beta-api.aivin.vn` -
878
+ // Bare hostname (no scheme) is the common case for a quick `aivin login api.aivin.vn` -
840
879
  // assume https, same as every other *.aivin.* endpoint in this file.
841
- const resolvedBaseUrl = baseUrl ? (/^https?:\/\//.test(baseUrl) ? baseUrl : `https://${baseUrl}`) : DEFAULT_AIVIN_BASE_URL;
880
+ const resolvedBaseUrl = normalizeServerUrl(baseUrl || process.env.AIVIN_BASE_URL || readActiveServer() || DEFAULT_AIVIN_BASE_URL);
842
881
  process.env.AIVIN_BASE_URL = resolvedBaseUrl;
843
882
 
844
883
  if (options.apiKey) {
@@ -913,7 +952,7 @@ program
913
952
  .action(() => {
914
953
  try {
915
954
  const apiKey = requireSavedApiKey();
916
- const serverUrl = process.env.AIVIN_BASE_URL || DEFAULT_AIVIN_BASE_URL;
955
+ const serverUrl = normalizeServerUrl(process.env.AIVIN_BASE_URL || readActiveServer() || DEFAULT_AIVIN_BASE_URL);
917
956
  const localClient = parseApiKeyClient(apiKey);
918
957
 
919
958
  // The effective API_KEY may come from a project's own .env instead of `~/.aivin/credentials`
@@ -957,7 +996,7 @@ keyCommand
957
996
  console.log(chalk.yellow('🔑 Key:'), chalk.cyan(plainKey));
958
997
  console.log(chalk.gray(' This is shown only once - store it somewhere safe.'));
959
998
  if (options.save) {
960
- const serverUrl = process.env.AIVIN_BASE_URL || DEFAULT_AIVIN_BASE_URL;
999
+ const serverUrl = normalizeServerUrl(process.env.AIVIN_BASE_URL || readActiveServer() || DEFAULT_AIVIN_BASE_URL);
961
1000
  const identity = await tryFetchWhoami(serverUrl, plainKey);
962
1001
  saveGlobalApiKey(plainKey, serverUrl, identity);
963
1002
  console.log(chalk.green(`💾 Saved to ${GLOBAL_CREDENTIALS_PATH} - every project on this machine can use it now.`));
@@ -988,7 +1027,7 @@ keyCommand
988
1027
  .description('List API keys on your account')
989
1028
  .action(async () => {
990
1029
  try {
991
- const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
1030
+ const serverUrl = normalizeServerUrl(process.env.AIVIN_BASE_URL || readActiveServer() || DEFAULT_AIVIN_BASE_URL);
992
1031
  const apiKey = requireSavedApiKey();
993
1032
  await logAccountIdentity(serverUrl, apiKey);
994
1033
  const items = await listRemoteApiKeys(serverUrl, apiKey);
@@ -1071,6 +1110,7 @@ program
1071
1110
  .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 | defaults (Windows: pick AIVIN Bot as default for file types) | status (default)')
1072
1111
  .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)")
1073
1112
  .option('--no-launch', "install: don't open Aivin now")
1113
+ .option('--open-platform', 'Windows install: also open the Aivin platform in an app window after installation')
1074
1114
  .option('--export-xml <file>', 'defaults (Windows): write a default-associations file for IT (Group Policy / Intune) instead of opening Settings')
1075
1115
  .option('--all', 'defaults --export-xml: include Office formats, not only md/txt/csv')
1076
1116
  .action((action = 'status', options) => {
@@ -1079,7 +1119,7 @@ program
1079
1119
  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] || '';
1080
1120
  try {
1081
1121
  if (action === 'install') {
1082
- const res = installDesktopApp({ autostart: options.autostart !== false, launch: options.launch !== false });
1122
+ const res = installDesktopApp({ autostart: options.autostart !== false, launch: options.launch !== false, openPlatform: options.openPlatform });
1083
1123
  console.log(chalk.green(`✅ Đã cài Aivin vào máy: ${where}.`));
1084
1124
  console.log(chalk.gray(` Ứng dụng: ${res.exe}`));
1085
1125
  console.log(chalk.gray(` Khởi động cùng máy: ${res.autostart ? 'bật' : 'tắt'} (đổi ở menu Aivin hoặc ${startupWhere})`));
@@ -1301,14 +1341,28 @@ remoteCommand
1301
1341
  .action(async (options) => {
1302
1342
  try {
1303
1343
  if (options.code) {
1304
- // Bộ cài (đã có khay): chỉ ghép — khay mở listener ngay khi thấy máy đã ghép.
1344
+ // Bộ cài (đã có khay): chỉ ghép — khay thấy máy đã ghép là mở listener.
1305
1345
  const { creds, stopped } = await pairWithCodeOnly(options);
1306
1346
  console.log(chalk.green(`✅ Đã kết nối máy "${creds.name}" với tài khoản ${creds.account || 'Aivin của bạn'} — quay lại Aivin để chọn máy này.`));
1307
1347
  if (stopped) console.log(chalk.gray(' Đã dừng phiên nhận việc cũ — Aivin mở lại bằng kết nối mới.'));
1308
1348
  return;
1309
1349
  }
1310
1350
  const roots = [path.resolve(options.dir || process.cwd())];
1311
- const creds = await pairDevice({ serverUrl: missionServerUrl(), apiKey: process.env.API_KEY, roots, name: options.name, profile: buildDeviceProfile(roots) });
1351
+ const serverUrl = normalizeServerUrl(options.server || missionServerUrl());
1352
+ const currentCreds = loadDeviceCredentials();
1353
+ if (options.server && currentCreds?.server_url && currentCreds.server_url !== serverUrl) {
1354
+ const { proceed } = await inquirer.prompt([{
1355
+ type: 'confirm', name: 'proceed', default: false,
1356
+ message: `Chuyển ghép máy từ ${currentCreds.server_url} sang ${serverUrl}? Máy chủ mới sẽ có quyền điều khiển máy này.`,
1357
+ }]);
1358
+ if (!proceed) return console.log(chalk.gray('Đã huỷ.'));
1359
+ }
1360
+ const apiKey = options.server
1361
+ ? (loadActiveContext(serverUrl)?.api_key || (process.env.AIVIN_BASE_URL === serverUrl ? process.env.API_KEY : undefined))
1362
+ : process.env.API_KEY;
1363
+ if (!apiKey) throw new Error(`Chưa đăng nhập tại ${serverUrl}; chạy ` + '`aivin login ${serverUrl}`' + ` trước, hoặc ghép bằng --code.`);
1364
+ setActiveServer(serverUrl);
1365
+ const creds = await pairDevice({ serverUrl, apiKey, roots, name: options.name, profile: buildDeviceProfile(roots) });
1312
1366
  console.log(chalk.green(`✅ Đã ghép máy "${creds.name}" (${creds.device_id})`));
1313
1367
  console.log(chalk.gray(` Thư mục được phép: ${creds.roots.join(' | ')}`));
1314
1368
  console.log(chalk.gray(' Chạy `aivin remote start` để bắt đầu nhận việc.'));
@@ -3,147 +3,95 @@ import path from 'path';
3
3
  import os from 'os';
4
4
  import axios from 'axios';
5
5
  import { execFileSync } from 'child_process';
6
+ import { readActiveServer, resolveServerUrl, serverKey, setActiveServer } from './servers.mjs';
6
7
 
7
- // `~/.aivin/credentials` - written once by `aivin login [baseUrl]`, read by every plugin project
8
- // on this machine. One ACTIVE context at a time (base_url + api_key together, like `kubectl config
9
- // use-context`) - not a per-project setting, and not a multi-server map either. Logging into a
10
- // different server (`aivin login beta-api.aivin.vn`) simply replaces the active context outright;
11
- // every project on the machine picks up wherever you last logged in, with zero `.env` needed for
12
- // the common case. A project's own `.env` can still set AIVIN_BASE_URL/API_KEY directly to pin
13
- // itself to something other than the machine's current context (e.g. CI using a fixed scoped key)
14
- // - dotenv.config() never overrides a variable that's already set, so that always wins.
15
- //
16
- // Old files from before this existed were flat `API_KEY=...` (implicitly production) - still loads
17
- // fine, just with no recorded base_url (falls back to the production default below).
18
8
  export const GLOBAL_CREDENTIALS_PATH = path.join(os.homedir(), '.aivin', 'credentials');
19
-
20
9
  export const DEFAULT_AIVIN_BASE_URL = 'https://api.aivin.cloud';
21
10
 
22
- /**
23
- * The REST API and the gRPC SDK channel are two different hostnames behind the same login (e.g.
24
- * `api.aivin.cloud` / `sdk.aivin.cloud` in production, `beta-api.aivin.vn` / `beta-sdk.aivin.vn` in
25
- * staging - proven consistent across both real environments this SDK talks to). Derived once at
26
- * login time by swapping the leading `api.` label for `sdk.`, so `SDK_ENDPOINT` never needs its own
27
- * separate manual config for the common case - same context, same command.
28
- */
29
11
  export function deriveSdkEndpoint(baseUrl) {
30
12
  try {
31
- const host = new URL(baseUrl).hostname;
32
- // Match "api." as its own label, whether at the very start ("api.aivin.cloud") or after a
33
- // prefix like "beta-" ("beta-api.aivin.vn" -> "beta-sdk.aivin.vn") - a plain `^api\.` anchor
34
- // only caught the production case and silently produced no SDK_ENDPOINT for staging.
13
+ const host = new URL(resolveServerUrl(baseUrl)).hostname;
35
14
  if (!/(^|-)api\./.test(host)) return null;
36
15
  return host.replace(/(^|-)api\./, '$1sdk.');
37
- } catch {
38
- return null;
39
- }
16
+ } catch { return null; }
40
17
  }
41
18
 
42
- /**
43
- * No guessing/hardcoded map - the backend already knows its own web app URL (`config/app.json`'s
44
- * `app_url`, admin-tunable via ConfigIO, same value every branded page/asset link on that instance
45
- * already uses) and serves it through `GET /setting/lang/default`, a public route (no auth) meant
46
- * for exactly this: reading branding/config before a session exists. Each real backend (production,
47
- * staging, self-hosted) already has this correct for itself - a hardcoded CLI-side map would just
48
- * be a second, driftable copy of the same fact.
49
- */
50
19
  export async function fetchWebUrl(baseUrl) {
51
20
  try {
52
- const res = await axios.get(`${baseUrl}/setting/lang/default`, { timeout: 5000 });
53
- const appUrl = res.data?.app_url;
54
- return typeof appUrl === 'string' && appUrl ? appUrl : null;
55
- } catch {
56
- return null;
57
- }
21
+ const res = await axios.get(`${resolveServerUrl(baseUrl)}/setting/lang/default`, { timeout: 5000 });
22
+ return typeof res.data?.app_url === 'string' && res.data.app_url ? res.data.app_url : null;
23
+ } catch { return null; }
58
24
  }
59
25
 
60
- /**
61
- * JSON-only, no legacy flat `API_KEY=...` dotenv-format fallback - a hard cutover, by request.
62
- * Anyone with an old-format credentials file just needs to `aivin login` again; this stays simple
63
- * instead of carrying a permanent "read either shape" branch for a one-time migration.
64
- */
65
- export function loadActiveContext() {
66
- if (!fs.existsSync(GLOBAL_CREDENTIALS_PATH)) return null;
26
+ function readCredentialStore() {
67
27
  try {
68
28
  const parsed = JSON.parse(fs.readFileSync(GLOBAL_CREDENTIALS_PATH, 'utf8'));
29
+ if (parsed?.contexts && typeof parsed.contexts === 'object') return parsed;
69
30
  if (!parsed?.api_key) return null;
70
- const base_url = parsed.base_url || DEFAULT_AIVIN_BASE_URL;
71
- return {
72
- base_url,
73
- api_key: parsed.api_key,
74
- sdk_endpoint: parsed.sdk_endpoint || deriveSdkEndpoint(base_url),
75
- // Absent on credentials files written before these fields existed - `aivin whoami` just
76
- // falls back to a live `/apikey/whoami` lookup in that case rather than showing stale/blank
77
- // identity.
78
- logged_in_at: parsed.logged_in_at || null,
79
- email: parsed.email || null,
80
- name: parsed.name || null,
81
- client: parsed.client || null,
82
- org_name: parsed.org_name || null,
83
- org_domain: parsed.org_domain || null,
84
- };
85
- } catch {
86
- return null;
87
- }
31
+ const base_url = resolveServerUrl(parsed.base_url || DEFAULT_AIVIN_BASE_URL);
32
+ return { version: 2, contexts: { [serverKey(base_url)]: { ...parsed, base_url } } };
33
+ } catch { return null; }
34
+ }
35
+
36
+ function writeCredentialStore(store) {
37
+ fs.mkdirSync(path.dirname(GLOBAL_CREDENTIALS_PATH), { recursive: true });
38
+ fs.writeFileSync(GLOBAL_CREDENTIALS_PATH, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 });
39
+ restrictToOwner(GLOBAL_CREDENTIALS_PATH);
40
+ }
41
+
42
+ export function loadActiveContext(baseUrl) {
43
+ const target = resolveServerUrl(baseUrl || process.env.AIVIN_BASE_URL || readActiveServer() || DEFAULT_AIVIN_BASE_URL);
44
+ const ctx = readCredentialStore()?.contexts?.[serverKey(target)];
45
+ if (!ctx?.api_key) return null;
46
+ return {
47
+ base_url: target,
48
+ api_key: ctx.api_key,
49
+ sdk_endpoint: ctx.sdk_endpoint || deriveSdkEndpoint(target),
50
+ logged_in_at: ctx.logged_in_at || null,
51
+ email: ctx.email || null,
52
+ name: ctx.name || null,
53
+ client: ctx.client || null,
54
+ org_name: ctx.org_name || null,
55
+ org_domain: ctx.org_domain || null,
56
+ };
88
57
  }
89
58
 
90
- /**
91
- * `{ mode: 0o600 }` on writeFileSync is a POSIX permission bit - Node has no Windows-ACL
92
- * equivalent for it, so on Windows the file otherwise just inherits whatever access the parent
93
- * directory/profile already grants (every other local account with access to that tree, not just
94
- * the owner). Best-effort hardening: explicitly strip inherited permissions and grant only the
95
- * current user. Never blocks login over this failing (e.g. no `icacls` on a stripped-down PATH).
96
- */
97
59
  function restrictToOwner(filePath) {
98
60
  if (process.platform !== 'win32') return;
99
61
  try {
100
62
  execFileSync('icacls', [filePath, '/inheritance:r', '/grant:r', `${os.userInfo().username}:F`], {
101
63
  stdio: 'ignore',
102
64
  });
103
- } catch {
104
- // best-effort only
105
- }
65
+ } catch { /* best-effort only */ }
106
66
  }
107
67
 
108
- /**
109
- * `aivin logout` - removes `~/.aivin/credentials` entirely. A project's own `.env` (AIVIN_BASE_URL/
110
- * API_KEY, see the dotenv precedence note at the top of cli.mjs) is untouched, so a directory that
111
- * pins its own key stays "logged in" for itself even after this.
112
- */
113
- export function clearActiveContext() {
114
- if (!fs.existsSync(GLOBAL_CREDENTIALS_PATH)) return false;
115
- fs.unlinkSync(GLOBAL_CREDENTIALS_PATH);
68
+ export function clearActiveContext(baseUrl) {
69
+ const target = resolveServerUrl(baseUrl || process.env.AIVIN_BASE_URL || readActiveServer() || DEFAULT_AIVIN_BASE_URL);
70
+ const store = readCredentialStore();
71
+ if (!store?.contexts?.[serverKey(target)]) return false;
72
+ delete store.contexts[serverKey(target)];
73
+ if (!Object.keys(store.contexts).length) fs.rmSync(GLOBAL_CREDENTIALS_PATH, { force: true });
74
+ else writeCredentialStore(store);
116
75
  return true;
117
76
  }
118
77
 
119
- /**
120
- * `identity` ({ email, name, client, org: { name, domain } }) is best-effort and optional -
121
- * callers that can't reach `/apikey/whoami` at login time (e.g. `-k` direct key set, offline)
122
- * still get a working login, just with `aivin whoami` showing less than the full picture since
123
- * nothing here is ever fetched again after login - see GLOBAL_CREDENTIALS_PATH's comment above.
124
- */
125
78
  export function saveActiveContext(baseUrl, apiKey, identity = {}) {
126
- fs.mkdirSync(path.dirname(GLOBAL_CREDENTIALS_PATH), { recursive: true });
127
- const sdkEndpoint = deriveSdkEndpoint(baseUrl);
128
- fs.writeFileSync(
129
- GLOBAL_CREDENTIALS_PATH,
130
- JSON.stringify(
131
- {
132
- base_url: baseUrl,
133
- api_key: apiKey,
134
- sdk_endpoint: sdkEndpoint,
135
- logged_in_at: new Date().toISOString(),
136
- email: identity.email || null,
137
- name: identity.name || null,
138
- client: identity.client || null,
139
- org_name: identity.org?.name || null,
140
- org_domain: identity.org?.domain || null,
141
- },
142
- null,
143
- 2,
144
- ) + '\n',
145
- { mode: 0o600 },
146
- );
147
- restrictToOwner(GLOBAL_CREDENTIALS_PATH);
148
- return sdkEndpoint;
149
- }
79
+ const normalized = resolveServerUrl(baseUrl || readActiveServer() || DEFAULT_AIVIN_BASE_URL);
80
+ const store = readCredentialStore() || { version: 2, contexts: {} };
81
+ store.version = 2;
82
+ store.contexts ||= {};
83
+ store.contexts[serverKey(normalized)] = {
84
+ base_url: normalized,
85
+ api_key: apiKey,
86
+ sdk_endpoint: deriveSdkEndpoint(normalized),
87
+ logged_in_at: new Date().toISOString(),
88
+ email: identity.email || null,
89
+ name: identity.name || null,
90
+ client: identity.client || null,
91
+ org_name: identity.org?.name || null,
92
+ org_domain: identity.org?.domain || null,
93
+ };
94
+ writeCredentialStore(store);
95
+ setActiveServer(normalized);
96
+ return store.contexts[serverKey(normalized)].sdk_endpoint;
97
+ }
@@ -408,11 +408,11 @@ function tryPosixDesktop(argv, launch) {
408
408
  * dụng + khay; (mặc định) khởi động cùng máy. Giữ đối số daemon của lần `aivin remote enable` trước; chưa có thì `remote start --quiet`
409
409
  * trần — daemon dùng thư mục / chế độ đã lưu lúc ghép máy.
410
410
  */
411
- export function installDesktopApp({ autostart = true, launch = true } = {}) {
411
+ export function installDesktopApp({ autostart = true, launch = true, openPlatform = false } = {}) {
412
412
  const cli = cliLaunchCommand();
413
413
  if (process.platform === 'win32') {
414
414
  const argv = [...cli, 'remote', 'start', ...(readSavedDaemonArgs() || ['--quiet'])];
415
- const res = installDesktop({ argv, rollback: supervisorRollbackPaths(cli), lang: mascotLang(), autostart, launch });
415
+ const res = installDesktop({ argv, rollback: supervisorRollbackPaths(cli), lang: mascotLang(), autostart, launch, launchMode: openPlatform ? TrayLaunch.OPEN : TrayLaunch.INSTALLED });
416
416
  if (autostart) {
417
417
  removeLegacyWindowsAutoStart();
418
418
  writeDaemonConfig({ rootDir: os.homedir(), filePath: RUN_ENTRY, method: 'run', nodeExec: cli[0] });
@@ -4,7 +4,8 @@ import axios from 'axios';
4
4
  import chalk from 'chalk';
5
5
  import readline from 'readline/promises';
6
6
  import { io } from 'socket.io-client';
7
- import { DEFAULT_AIVIN_BASE_URL } from '../context.mjs';
7
+ import { DEFAULT_AIVIN_BASE_URL } from '../context.mjs';
8
+ import { readActiveServer, resolveServerUrl as normalizeServerUrl, setActiveServer } from '../servers.mjs';
8
9
  import { logActivity } from './activityLog.mjs';
9
10
  import { DEFAULT_SCOPE_LIMITS, DEVICE_NAMESPACE, CastState, DeviceAccess, DeviceErrorCode, DeviceEvent, HoldPhase, MAX_RESULT_BYTES, PROTOCOL_VERSION, REMOTE_IDEM_FILE, REMOTE_OUTBOX_FILE, ServerFeature, ToolGroup } from './constants.mjs';
10
11
  import { CallState, createCallLedger } from './callLedger.mjs';
@@ -125,11 +126,14 @@ function boundedResult(outcome) {
125
126
  * khởi động lại trên máy đang đăng nhập CLI với máy chủ B sẽ lặng lẽ ghép lại sang B bằng API key (chạy thật 26/10/2026). Đổi máy chủ
126
127
  * thì dùng `--server` (hoặc `--repair`).
127
128
  */
128
- export function resolveServerUrl(options, saved, env = process.env) {
129
- const url = options.server || options.serverUrl
130
- || (options.code ? undefined : (options.repair ? undefined : saved?.server_url) || env.AIVIN_BASE_URL)
131
- || DEFAULT_AIVIN_BASE_URL;
132
- return String(url).replace(/\/+$/, '');
129
+ export function resolveServerUrl(options, saved, env = process.env) {
130
+ const explicit = options.server || options.serverUrl;
131
+ const url = explicit || (options.code ? DEFAULT_AIVIN_BASE_URL : null)
132
+ || readActiveServer()
133
+ || (options.repair ? undefined : saved?.server_url)
134
+ || env.AIVIN_BASE_URL || env.AIVIN_SERVER
135
+ || DEFAULT_AIVIN_BASE_URL;
136
+ return normalizeServerUrl(url);
133
137
  }
134
138
 
135
139
  /**
@@ -154,18 +158,20 @@ async function confirmServerChange(saved, serverUrl) {
154
158
  * Thông tin ghép máy: có mã kết nối thì luôn ghép bằng mã (người dùng vừa bấm "Thêm máy tính này"); có sẵn và đúng máy chủ thì dùng;
155
159
  * không thì ghép mới bằng API key đang đăng nhập.
156
160
  */
157
- async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name, repair, profile }) {
158
- let creds = loadDeviceCredentials();
159
- await confirmServerChange(creds, serverUrl);
160
- if (code) {
161
- creds = await pairDeviceWithCode({ serverUrl, code, roots, name, profile });
162
- } else if (!creds || creds.server_url !== serverUrl || repair) {
163
- creds = await pairDevice({ serverUrl, apiKey, roots, name, profile });
164
- } else if (rootsGiven && JSON.stringify(roots) !== JSON.stringify(creds.roots)) {
165
- creds.roots = roots;
166
- saveDeviceCredentials(creds);
167
- }
168
- return creds;
161
+ async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name, repair, profile }) {
162
+ const current = loadDeviceCredentials();
163
+ await confirmServerChange(current, serverUrl);
164
+ setActiveServer(serverUrl);
165
+ let creds = loadDeviceCredentials(serverUrl);
166
+ if (code) {
167
+ creds = await pairDeviceWithCode({ serverUrl, code, roots, name, profile });
168
+ } else if (!creds || repair) {
169
+ creds = await pairDevice({ serverUrl, apiKey, roots, name, profile });
170
+ } else if (rootsGiven && JSON.stringify(roots) !== JSON.stringify(creds.roots)) {
171
+ creds.roots = roots;
172
+ saveDeviceCredentials(creds);
173
+ }
174
+ return creds;
169
175
  }
170
176
 
171
177
  /**
@@ -173,7 +179,7 @@ async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name,
173
179
  * người dùng đóng được cửa sổ cài). Listener đang chạy bằng token cũ thì dừng nó để khay mở lại bằng token mới. Trả pid đã dừng (hoặc null).
174
180
  */
175
181
  export async function pairWithCodeOnly(options) {
176
- const saved = loadDeviceCredentials();
182
+ const saved = loadDeviceCredentials();
177
183
  const serverUrl = resolveServerUrl(options, saved);
178
184
  await confirmServerChange(saved, serverUrl);
179
185
  configureProxy({ explicit: options.proxy });
@@ -181,7 +187,8 @@ export async function pairWithCodeOnly(options) {
181
187
  const roots = (fullAccess ? fullAccessRoots() : [options.dir || process.cwd()]).map((r) => path.resolve(r));
182
188
  const access = fullAccess ? DeviceAccess.FULL : DeviceAccess.FOLDERS;
183
189
  const profile = { ...buildDeviceProfile(fullAccess ? [os.homedir()] : roots), roots, access };
184
- const creds = await pairDeviceWithCode({ serverUrl, code: options.code, roots, name: options.name, profile });
190
+ const creds = await pairDeviceWithCode({ serverUrl, code: options.code, roots, name: options.name, profile });
191
+ setActiveServer(serverUrl);
185
192
  saveDeviceCredentials({ ...creds, access });
186
193
  const stale = lockHolder();
187
194
  if (stale) try { process.kill(stale); } catch { /* vừa tự thoát */ }
@@ -199,8 +206,9 @@ export async function startRemoteClient(options = {}) {
199
206
  const envCreds = multiUser ? credentialsFromEnv() : null;
200
207
  if (multiUser && !envCreds) throw new Error('--multi-user cần AIVIN_DEVICE_TOKEN, AIVIN_DEVICE_ID và AIVIN_SERVER (máy tính tổ chức do Aivin cấp).');
201
208
  if (multiUser && process.platform === 'win32') throw new Error('--multi-user chỉ chạy trên Linux (container máy tính tổ chức).');
202
- const saved = envCreds || loadDeviceCredentials();
203
- const serverUrl = resolveServerUrl(options, saved);
209
+ const savedHint = envCreds || loadDeviceCredentials();
210
+ const serverUrl = resolveServerUrl(options, savedHint);
211
+ const saved = envCreds || loadDeviceCredentials(serverUrl);
204
212
  // Trước mọi lời gọi mạng (ghép máy cũng đi qua proxy).
205
213
  const proxy = configureProxy({ explicit: options.proxy });
206
214
  const apiKey = options.apiKey ?? process.env.API_KEY;
@@ -666,7 +674,7 @@ export async function startRemoteClient(options = {}) {
666
674
  const fallback = saveDeviceCredentials({ ...creds, device_token: token }, { previousToken: previous });
667
675
  if (fallback) say(chalk.yellow(` ⚠️ Kho bí mật của máy lỗi (${fallback}) — token mới nằm trong tệp thường`));
668
676
  // Đọc lại thật từ tệp + kho bí mật (không qua bộ nhớ đệm): ghi hỏng mà vẫn báo BE là lần khởi động sau máy bị khoá ngoài.
669
- if (readStoredTokenFresh() !== token) throw new Error('saved token does not read back');
677
+ if (readStoredTokenFresh(serverUrl) !== token) throw new Error('saved token does not read back');
670
678
  } catch (e) {
671
679
  try { saveDeviceCredentials({ ...creds, device_token: previous }, { previousToken: null }); } catch { /* giữ nguyên tệp */ }
672
680
  say(chalk.yellow(` ⚠️ Không lưu được token mới (${e.message}) — tiếp tục dùng token cũ`));
@@ -676,7 +684,7 @@ export async function startRemoteClient(options = {}) {
676
684
  socket.auth = { ...socket.auth, device_token: token };
677
685
  // Gửi kèm chính token mới: BE chỉ chốt khi băm của nó đúng token đang chờ (chứng minh máy này nhận được token đó).
678
686
  const ack = await socket.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.ROTATED, { token }).catch(() => null);
679
- if (ack?.ok === true) settleRotation(token);
687
+ if (ack?.ok === true) settleRotation(token, serverUrl);
680
688
  logActivity({ type: 'token_rotated', deviceId: creds.device_id, confirmed: ack?.ok === true });
681
689
  say(chalk.gray(ack?.ok
682
690
  ? ' 🔑 Đã đổi token máy định kỳ (token cũ hết hiệu lực)'
@@ -711,7 +719,7 @@ export async function startRemoteClient(options = {}) {
711
719
  cancelGating(orphaned);
712
720
  ledger.drop(orphaned);
713
721
  }
714
- if (!envCreds) settleRotation(creds.device_token); // chào được bằng token đang dùng → bỏ token cũ còn giữ (nếu có)
722
+ if (!envCreds) settleRotation(creds.device_token, serverUrl); // chào được bằng token đang dùng → bỏ token cũ còn giữ (nếu có)
715
723
  if (typeof hello?.rotate_token === 'string' && !envCreds) await rotateToken(hello.rotate_token);
716
724
  // BE cần bản CLI tối thiểu (tính năng mới phía máy) → kiểm cập nhật ngay thay vì chờ tới lượt.
717
725
  if (hello?.cli) updater?.setServerHints(hello.cli);
@@ -903,7 +911,7 @@ export async function startRemoteClient(options = {}) {
903
911
  if (err?.message === 'DEVICE_UNAUTHORIZED') {
904
912
  // Token xoay vòng chưa được chốt → thử lại bằng token cũ trước khi xoá ghép máy (02/11/2026).
905
913
  if (!envCreds && fallBackToPreviousToken({ creds, socket, isStopped: () => stopped })) return void say(chalk.yellow(' ⚠️ Máy chủ chưa nhận token mới — nối lại bằng token cũ'));
906
- const replaced = !clearDeviceCredentials(creds.device_token);
914
+ const replaced = !clearDeviceCredentials(creds.device_token, serverUrl);
907
915
  console.log(chalk.red(replaced
908
916
  ? '❌ Máy này vừa được ghép lại bởi một cửa sổ khác — cửa sổ này dừng, cửa sổ mới tiếp tục nhận việc.'
909
917
  : '❌ Token của máy không còn hiệu lực (đã thu hồi hoặc ghép lại ở nơi khác). Chạy `aivin remote start` để ghép lại.'));
@@ -918,7 +926,7 @@ export async function startRemoteClient(options = {}) {
918
926
  stopForGood();
919
927
  }));
920
928
  socket.on(DeviceEvent.REVOKED, guarded(DeviceEvent.REVOKED, () => {
921
- clearDeviceCredentials(creds.device_token);
929
+ clearDeviceCredentials(creds.device_token, serverUrl);
922
930
  console.log(chalk.red('❌ Máy này đã bị thu hồi quyền điều khiển từ xa.'));
923
931
  stopForGood();
924
932
  }));
@@ -1076,8 +1084,9 @@ export async function startRemoteClient(options = {}) {
1076
1084
  * socket, bắt tay thử sẽ đá daemon đang chạy ra.
1077
1085
  */
1078
1086
  export async function testRemoteConnection(options = {}) {
1079
- const creds = loadDeviceCredentials();
1080
- const serverUrl = resolveServerUrl(options, creds);
1087
+ const savedHint = loadDeviceCredentials();
1088
+ const serverUrl = resolveServerUrl(options, savedHint);
1089
+ const creds = loadDeviceCredentials(serverUrl);
1081
1090
  const apiKey = options.apiKey ?? process.env.API_KEY;
1082
1091
  const report = { serverUrl, paired: !!creds, deviceId: creds?.device_id, httpOk: false, latencyMs: null, online: null, error: null };
1083
1092
  const startedAt = Date.now();