@aivin-labs/cli 1.0.47 → 1.0.51

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 (34) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.mjs +1 -1
  3. package/bin/lib/auth.mjs +1 -1
  4. package/bin/lib/context.mjs +3 -3
  5. package/bin/lib/openFile.mjs +3 -2
  6. package/bin/lib/remote/client.mjs +1418 -1221
  7. package/bin/lib/remote/confirmBarrier.mjs +45 -0
  8. package/bin/lib/remote/constants.mjs +3 -1
  9. package/bin/lib/remote/desktop/aivinIco.mjs +696 -0
  10. package/bin/lib/remote/desktop/castAuth.mjs +23 -9
  11. package/bin/lib/remote/desktop/castConsent.mjs +37 -6
  12. package/bin/lib/remote/desktop/castFileDrop.mjs +24 -0
  13. package/bin/lib/remote/desktop/castInput.mjs +63 -19
  14. package/bin/lib/remote/desktop/castTouchViewers.mjs +26 -0
  15. package/bin/lib/remote/desktop/desktopCast.mjs +25 -2
  16. package/bin/lib/remote/desktop/desktopCastSource.mjs +298 -101
  17. package/bin/lib/remote/desktop/index.mjs +5 -3
  18. package/bin/lib/remote/desktop/traySource.mjs +1385 -1343
  19. package/bin/lib/remote/desktop/webrtcWorker.mjs +3 -0
  20. package/bin/lib/remote/deviceProfile.mjs +2 -0
  21. package/bin/lib/remote/gui/index.mjs +485 -480
  22. package/bin/lib/remote/humanInput.mjs +117 -0
  23. package/bin/lib/remote/idempotency.mjs +19 -2
  24. package/bin/lib/remote/keepAwake.mjs +15 -9
  25. package/bin/lib/remote/localConfirm.mjs +26 -7
  26. package/bin/lib/remote/mascot/ask.mjs +23 -4
  27. package/bin/lib/remote/mascot/askHostSource.mjs +10 -4
  28. package/bin/lib/remote/processes.mjs +231 -230
  29. package/bin/lib/remote/scheduler.mjs +164 -124
  30. package/bin/lib/remote/toolHandlers.mjs +3 -2
  31. package/bin/lib/remote/winTree.mjs +29 -0
  32. package/bin/lib/servers.mjs +31 -1
  33. package/docs/CLI.md +2 -2
  34. package/package.json +1 -1
@@ -1,124 +1,164 @@
1
- import { DEFAULT_GROUP_LIMITS, DeviceErrorCode } from './constants.mjs';
2
- import { DeviceToolError } from './sandbox.mjs';
3
-
4
- function createSemaphore(limit) {
5
- let active = 0;
6
- const queue = [];
7
- const release = () => {
8
- active--;
9
- const next = queue.shift();
10
- if (next) { active++; next(); }
11
- };
12
- return {
13
- async acquire() {
14
- if (active < limit) { active++; return release; }
15
- await new Promise((resolve) => queue.push(resolve));
16
- return release;
17
- },
18
- stats: () => ({ active, queued: queue.length, limit }),
19
- };
20
- }
21
-
22
- function groupLimit(group) {
23
- const fromEnv = Number(process.env[`AIVIN_REMOTE_LIMIT_${String(group).toUpperCase()}`]);
24
- return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : (DEFAULT_GROUP_LIMITS[group] ?? 4);
25
- }
26
-
27
- /**
28
- * Bộ điều phối lời gọi trên máy: mỗi nhóm công cụ một semaphore (đọc tệp 16, chạy lệnh 3…), thao tác ghi khoá theo từng đường dẫn
29
- * (hai lệnh ghi cùng tệp chạy lần lượt, khác tệp chạy song song), mỗi lời gọi một AbortController (huỷ / hết giờ → dừng cả cây tiến
30
- * trình con).
31
- *
32
- * `scopeLimits` (máy tính tổ chức): thêm trần theo từng thành viên (`call.user_scope`) trong mỗi nhóm. Lấy chỗ của vùng TRƯỚC rồi mới
33
- * tới chỗ chung — lời gọi đang chờ trần của riêng mình không giữ chỗ chung của người khác. Không truyền → như máy một người.
34
- */
35
- export function createScheduler({ scopeLimits = null } = {}) {
36
- const semaphores = new Map();
37
- const scopeSemaphores = new Map();
38
- const pathLocks = new Map();
39
- const inflight = new Map();
40
-
41
- const semaphoreOf = (group) => {
42
- if (!semaphores.has(group)) semaphores.set(group, createSemaphore(groupLimit(group)));
43
- return semaphores.get(group);
44
- };
45
-
46
- const scopeSemaphoreOf = (scope, group) => {
47
- const fromEnv = Number(process.env[`AIVIN_REMOTE_SCOPE_LIMIT_${String(group).toUpperCase()}`]);
48
- const limit = Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : scopeLimits?.[group];
49
- if (!limit || typeof scope !== 'string' || !scope) return null;
50
- const key = `${scope}\u0000${group}`;
51
- if (!scopeSemaphores.has(key)) scopeSemaphores.set(key, createSemaphore(limit));
52
- return scopeSemaphores.get(key);
53
- };
54
-
55
- async function withPathLocks(keys, fn) {
56
- const sorted = [...new Set(keys)].sort();
57
- const previous = sorted.map((k) => pathLocks.get(k) || Promise.resolve());
58
- let done;
59
- const mine = new Promise((resolve) => { done = resolve; });
60
- sorted.forEach((k) => pathLocks.set(k, mine));
61
- try {
62
- await Promise.all(previous);
63
- return await fn();
64
- } finally {
65
- done();
66
- sorted.forEach((k) => { if (pathLocks.get(k) === mine) pathLocks.delete(k); });
67
- }
68
- }
69
-
70
- /**
71
- * Chạy một lời gọi. `spec`: { group, lockKeys?(args) }, `handler(args, ctx)`; ctx = { signal, onOutput }.
72
- * Không ném lỗi: trả { ok, result } hoặc { ok:false, error, error_code }.
73
- */
74
- async function run(call, spec, handler, { onOutput } = {}) {
75
- const controller = new AbortController();
76
- inflight.set(call.call_id, controller);
77
- const startedAt = Date.now();
78
- const timeoutMs = Math.max(1000, Number(call.timeout_ms) || 60_000);
79
- const timer = setTimeout(() => controller.abort(new DeviceToolError(DeviceErrorCode.CALL_TIMEOUT, `Timed out after ${timeoutMs} ms`)), timeoutMs);
80
- const releaseScope = scopeLimits ? await scopeSemaphoreOf(call.user_scope, spec.group)?.acquire() : null;
81
- const release = await semaphoreOf(spec.group).acquire();
82
- try {
83
- if (controller.signal.aborted) throw controller.signal.reason;
84
- const exec = () => handler(call.args || {}, { signal: controller.signal, onOutput, timeoutMs });
85
- const keys = spec.lockKeys ? spec.lockKeys(call.args || {}) : [];
86
- const result = keys.length ? await withPathLocks(keys, exec) : await exec();
87
- return { ok: true, result, duration_ms: Date.now() - startedAt };
88
- } catch (error) {
89
- const reason = controller.signal.aborted ? controller.signal.reason : error;
90
- return {
91
- ok: false,
92
- error: reason?.message || String(reason),
93
- error_code: reason?.code || DeviceErrorCode.EXECUTION_FAILED,
94
- duration_ms: Date.now() - startedAt,
95
- };
96
- } finally {
97
- clearTimeout(timer);
98
- release();
99
- releaseScope?.();
100
- inflight.delete(call.call_id);
101
- }
102
- }
103
-
104
- function cancel(callIds) {
105
- for (const id of callIds || []) {
106
- inflight.get(id)?.abort(new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled by server'));
107
- }
108
- }
109
-
110
- /** Huỷ mọi lời gọi đang chạy; chờ tối đa `waitMs` cho chúng dọn xong (giết cây tiến trình con) — dùng khi tạm dừng / dừng / bị thu hồi. */
111
- async function cancelAll(message = 'Cancelled on this device', { waitMs = 5000 } = {}) {
112
- for (const controller of inflight.values()) controller.abort(new DeviceToolError(DeviceErrorCode.CANCELLED, message));
113
- const deadline = Date.now() + waitMs;
114
- while (inflight.size && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50));
115
- }
116
-
117
- return {
118
- run,
119
- cancel,
120
- cancelAll,
121
- stats: () => Object.fromEntries([...semaphores.entries()].map(([g, s]) => [g, s.stats()])),
122
- inflightCount: () => inflight.size,
123
- };
124
- }
1
+ import path from 'path';
2
+ import { DEFAULT_GROUP_LIMITS, DeviceErrorCode } from './constants.mjs';
3
+ import { DeviceToolError } from './sandbox.mjs';
4
+
5
+ function createSemaphore(limit) {
6
+ let active = 0;
7
+ const queue = [];
8
+ const release = () => {
9
+ active--;
10
+ const next = queue.shift();
11
+ if (next) { active++; next(); }
12
+ };
13
+ return {
14
+ async acquire() {
15
+ if (active < limit) { active++; return release; }
16
+ await new Promise((resolve) => queue.push(resolve));
17
+ return release;
18
+ },
19
+ stats: () => ({ active, queued: queue.length, limit }),
20
+ };
21
+ }
22
+
23
+ function groupLimit(group) {
24
+ const fromEnv = Number(process.env[`AIVIN_REMOTE_LIMIT_${String(group).toUpperCase()}`]);
25
+ return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : (DEFAULT_GROUP_LIMITS[group] ?? 4);
26
+ }
27
+
28
+ /**
29
+ * Khoá đường dẫn so theo dạng chuẩn hoá: Windows / macOS không phân biệt hoa thường (`A.txt` và `a.txt` là một tệp), và có dấu phân cách cuối
30
+ * để so cha – con (`C:\a` chứa `C:\a\b`, không chứa `C:\ab`).
31
+ */
32
+ export function lockKeyOf(key, platform = process.platform) {
33
+ const p = path.resolve(String(key));
34
+ const folded = platform === 'win32' || platform === 'darwin' ? p.toLowerCase() : p;
35
+ return folded.endsWith(path.sep) ? folded : folded + path.sep;
36
+ }
37
+
38
+ /** Hai khoá đụng nhau khi là cùng đường hoặc một bên nằm trong bên kia (xoá thư mục `a` và ghi `a/b.txt` phải chạy lần lượt). */
39
+ const overlaps = (a, b) => a.startsWith(b) || b.startsWith(a);
40
+
41
+ /** Lỗi trả về khi lời gọi bị huỷ / hết giờ TRƯỚC khi công cụ chạy: chưa có gì xảy ra, Planner làm lại được. */
42
+ function notStarted(reason) {
43
+ const why = reason?.code === DeviceErrorCode.CALL_TIMEOUT ? 'timed out' : 'was cancelled';
44
+ return new DeviceToolError(DeviceErrorCode.NOT_STARTED, `The step ${why} while waiting for its turn on this device — it did not run, nothing changed`);
45
+ }
46
+
47
+ /**
48
+ * Bộ điều phối lời gọi trên máy: mỗi nhóm công cụ một semaphore (đọc tệp 16, chạy lệnh 3…), thao tác ghi khoá theo đường dẫn (hai lệnh ghi
49
+ * cùng tệp — hoặc tệp nằm trong thư mục đang bị xoá / chuyển — chạy lần lượt, không liên quan thì song song), mỗi lời gọi một AbortController
50
+ * (huỷ / hết giờ → dừng cả cây tiến trình con).
51
+ *
52
+ * Kết quả lỗi mang `ran`: công cụ đã bắt đầu chạy chưa. Huỷ / hết giờ lúc còn xếp hàng (semaphore, khoá đường dẫn) → `NOT_STARTED`, công cụ
53
+ * không bao giờ chạy sau đó; huỷ / hết giờ giữa chừng → mã gốc (`CALL_TIMEOUT` / `CANCELLED`) với `ran: true` — có thể đã làm một phần
54
+ * (idempotency.mjs không cho chạy lại mù quáng).
55
+ *
56
+ * `scopeLimits` (máy tính tổ chức): thêm trần theo từng thành viên (`call.user_scope`) trong mỗi nhóm. Lấy chỗ của vùng TRƯỚC rồi mới
57
+ * tới chỗ chung — lời gọi đang chờ trần của riêng mình không giữ chỗ chung của người khác. Không truyền → như máy một người.
58
+ */
59
+ export function createScheduler({ scopeLimits = null } = {}) {
60
+ const semaphores = new Map();
61
+ const scopeSemaphores = new Map();
62
+ const lockEntries = new Set();
63
+ const inflight = new Map();
64
+
65
+ const semaphoreOf = (group) => {
66
+ if (!semaphores.has(group)) semaphores.set(group, createSemaphore(groupLimit(group)));
67
+ return semaphores.get(group);
68
+ };
69
+
70
+ const scopeSemaphoreOf = (scope, group) => {
71
+ const fromEnv = Number(process.env[`AIVIN_REMOTE_SCOPE_LIMIT_${String(group).toUpperCase()}`]);
72
+ const limit = Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : scopeLimits?.[group];
73
+ if (!limit || typeof scope !== 'string' || !scope) return null;
74
+ const key = `${scope}\u0000${group}`;
75
+ if (!scopeSemaphores.has(key)) scopeSemaphores.set(key, createSemaphore(limit));
76
+ return scopeSemaphores.get(key);
77
+ };
78
+
79
+ /** Chờ mọi khoá vào TRƯỚC mà đụng nhau (thứ tự vào hàng — không có vòng chờ), rồi mới chạy. Bị huỷ trong lúc chờ → không chạy. */
80
+ async function withPathLocks(keys, fn, signal) {
81
+ const mine = [...new Set(keys.map((k) => lockKeyOf(k)))];
82
+ const blockers = [...lockEntries].filter((e) => e.keys.some((k) => mine.some((m) => overlaps(k, m)))).map((e) => e.promise);
83
+ let done;
84
+ const entry = { keys: mine, promise: new Promise((resolve) => { done = resolve; }) };
85
+ lockEntries.add(entry);
86
+ try {
87
+ if (blockers.length) await Promise.race([Promise.all(blockers), abortPromise(signal)]);
88
+ if (signal.aborted) throw notStarted(signal.reason);
89
+ return await fn();
90
+ } finally {
91
+ done();
92
+ lockEntries.delete(entry);
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Chạy một lời gọi. `spec`: { group, lockKeys?(args) }, `handler(args, ctx)`; ctx = { signal, onOutput }.
98
+ * Không ném lỗi: trả { ok, result } hoặc { ok:false, error, error_code, ran }.
99
+ */
100
+ async function run(call, spec, handler, { onOutput } = {}) {
101
+ const controller = new AbortController();
102
+ inflight.set(call.call_id, controller);
103
+ const startedAt = Date.now();
104
+ const timeoutMs = Math.max(1000, Number(call.timeout_ms) || 60_000);
105
+ const timer = setTimeout(() => controller.abort(new DeviceToolError(DeviceErrorCode.CALL_TIMEOUT, `Timed out after ${timeoutMs} ms`)), timeoutMs);
106
+ let ran = false;
107
+ let releaseScope = null;
108
+ let release = null;
109
+ try {
110
+ releaseScope = scopeLimits ? await scopeSemaphoreOf(call.user_scope, spec.group)?.acquire() : null;
111
+ release = await semaphoreOf(spec.group).acquire();
112
+ if (controller.signal.aborted) throw notStarted(controller.signal.reason);
113
+ const exec = () => {
114
+ ran = true;
115
+ return handler(call.args || {}, { signal: controller.signal, onOutput, timeoutMs });
116
+ };
117
+ const keys = spec.lockKeys ? spec.lockKeys(call.args || {}) : [];
118
+ const result = keys.length ? await withPathLocks(keys, exec, controller.signal) : await exec();
119
+ return { ok: true, result, duration_ms: Date.now() - startedAt };
120
+ } catch (error) {
121
+ const reason = !ran && error?.code === DeviceErrorCode.NOT_STARTED ? error : controller.signal.aborted ? controller.signal.reason : error;
122
+ return {
123
+ ok: false,
124
+ error: reason?.message || String(reason),
125
+ error_code: reason?.code || DeviceErrorCode.EXECUTION_FAILED,
126
+ duration_ms: Date.now() - startedAt,
127
+ ran,
128
+ };
129
+ } finally {
130
+ clearTimeout(timer);
131
+ release?.();
132
+ releaseScope?.();
133
+ inflight.delete(call.call_id);
134
+ }
135
+ }
136
+
137
+ function cancel(callIds) {
138
+ for (const id of callIds || []) {
139
+ inflight.get(id)?.abort(new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled by server'));
140
+ }
141
+ }
142
+
143
+ /** Huỷ mọi lời gọi đang chạy; chờ tối đa `waitMs` cho chúng dọn xong (giết cây tiến trình con) — dùng khi tạm dừng / dừng / bị thu hồi. */
144
+ async function cancelAll(message = 'Cancelled on this device', { waitMs = 5000 } = {}) {
145
+ for (const controller of inflight.values()) controller.abort(new DeviceToolError(DeviceErrorCode.CANCELLED, message));
146
+ const deadline = Date.now() + waitMs;
147
+ while (inflight.size && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50));
148
+ }
149
+
150
+ return {
151
+ run,
152
+ cancel,
153
+ cancelAll,
154
+ stats: () => Object.fromEntries([...semaphores.entries()].map(([g, s]) => [g, s.stats()])),
155
+ inflightCount: () => inflight.size,
156
+ };
157
+ }
158
+
159
+ function abortPromise(signal) {
160
+ return new Promise((resolve) => {
161
+ if (signal.aborted) return resolve();
162
+ signal.addEventListener('abort', () => resolve(), { once: true });
163
+ });
164
+ }
@@ -29,6 +29,7 @@ import { buildTransferTools } from './httpTransfer.mjs';
29
29
  import { safeGitArgv, safeGitEnv } from './gitSafe.mjs';
30
30
  import { buildMeetingTools } from './meeting/index.mjs';
31
31
  import { buildClipboardTools } from './clipboard.mjs';
32
+ import { killWindowsTree } from './winTree.mjs';
32
33
 
33
34
  /**
34
35
  * Công cụ trên máy, chia gói theo năng lực phát hiện được (git chỉ có khi máy cài git, tìm nội dung dùng ripgrep nếu có…). Mỗi công cụ
@@ -356,8 +357,8 @@ function runProcess(cmd, argv, { cwd, signal, onOutput, env, maxOutput = MAX_EXE
356
357
  const killTree = () => {
357
358
  if (killed) return;
358
359
  killed = true;
359
- // Shell đã thoát mà cháu còn chạy: trên Linux / macOS vẫn giết được cả nhóm tiến trình; Windows mất dấu cây, taskkill báo lỗi vô hại.
360
- if (process.platform === 'win32') { if (child.exitCode === null) spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true }).on('error', () => undefined); }
360
+ // Shell đã thoát mà cháu còn chạy: Linux / macOS giết cả nhóm tiến trình; Windows lần theo PID cha (cả phần mồ côi — winTree.mjs).
361
+ if (process.platform === 'win32') killWindowsTree(child, startedAt);
361
362
  else { try { process.kill(-child.pid, 'SIGKILL'); } catch { try { child.kill('SIGKILL'); } catch { /* đã thoát */ } } }
362
363
  };
363
364
  const onAbort = () => {
@@ -0,0 +1,29 @@
1
+ import { spawn } from 'child_process';
2
+
3
+ /**
4
+ * Giết cả cây tiến trình trên Windows, kể cả phần đã "mồ côi" (09/11/2026). `taskkill /T` chỉ đi theo cây còn sống: shell đã thoát (lệnh dùng
5
+ * `start`, `Start-Process`, script tự tách nền) thì các tiến trình cháu không còn nối với cây — huỷ / hết giờ là chúng chạy tiếp mãi. Windows không
6
+ * đổi `ParentProcessId` của tiến trình mồ côi, nên vẫn lần ra được từ PID gốc; lọc theo giờ tạo (≥ lúc chạy lệnh) để không giết nhầm tiến trình
7
+ * lạ dùng lại PID cũ.
8
+ */
9
+ export function orphanSweepScript(rootPid, sinceMs) {
10
+ const pid = Math.trunc(Number(rootPid));
11
+ const since = Math.trunc(Number(sinceMs)) - 1000;
12
+ if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isSafeInteger(since)) return null;
13
+ return [
14
+ '$all = Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId, CreationDate',
15
+ `$since = [DateTimeOffset]::FromUnixTimeMilliseconds(${since}).LocalDateTime`,
16
+ `$q = New-Object System.Collections.Queue; $q.Enqueue([uint32]${pid}); $kill = New-Object System.Collections.Generic.List[uint32]`,
17
+ 'while ($q.Count) { $p = $q.Dequeue(); foreach ($c in $all) { if ($c.ParentProcessId -eq $p -and $c.CreationDate -ge $since -and -not $kill.Contains($c.ProcessId)) { $kill.Add($c.ProcessId); $q.Enqueue($c.ProcessId) } } }',
18
+ 'foreach ($k in $kill) { Stop-Process -Id $k -Force -ErrorAction SilentlyContinue }',
19
+ ].join('; ');
20
+ }
21
+
22
+ /** `child`: tiến trình Node đã spawn; `startedAt`: ms lúc chạy. Cây còn sống → taskkill /T; luôn quét thêm phần mồ côi. */
23
+ export function killWindowsTree(child, startedAt, { spawnImpl = spawn } = {}) {
24
+ const run = (cmd, args) => { try { spawnImpl(cmd, args, { windowsHide: true, stdio: 'ignore' }).on('error', () => undefined); } catch { /* bỏ qua */ } };
25
+ if (!child?.pid) return;
26
+ if (child.exitCode === null && child.signalCode === null) run('taskkill', ['/pid', String(child.pid), '/T', '/F']);
27
+ const script = orphanSweepScript(child.pid, startedAt);
28
+ if (script) run('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script]);
29
+ }
@@ -45,6 +45,36 @@ export function resolveServerUrl(input, { fallback = DEFAULT_SERVER_URL } = {})
45
45
  return url.toString().replace(/\/+$/, '');
46
46
  }
47
47
 
48
+ const AIVIN_WEB_BY_ZONE = Object.freeze({
49
+ 'aivin.vn': 'https://app.aivin.vn',
50
+ 'aivin.cloud': 'https://app.aivin.cloud',
51
+ });
52
+
53
+ function aivinZone(hostname) {
54
+ const host = hostname.toLowerCase();
55
+ return Object.keys(AIVIN_WEB_BY_ZONE).find((zone) => host === zone || host.endsWith(`.${zone}`)) || null;
56
+ }
57
+
58
+ /** Web mặc định theo gốc tên miền của máy chủ Aivin; null với máy chủ tự dựng / localhost. */
59
+ export function defaultWebUrl(serverUrl) {
60
+ try {
61
+ return AIVIN_WEB_BY_ZONE[aivinZone(new URL(resolveServerUrl(serverUrl)).hostname)] || null;
62
+ } catch { return null; }
63
+ }
64
+
65
+ /**
66
+ * Chọn địa chỉ web từ `app_url` máy chủ khai. Máy chủ Aivin chính thức chỉ được dùng web cùng gốc tên miền:
67
+ * các máy chủ có thể dùng chung cấu hình nên `app_url` của api.aivin.vn có thể là brain.aivin.cloud.
68
+ */
69
+ export function webUrlForServer(serverUrl, appUrl) {
70
+ const fallback = defaultWebUrl(serverUrl);
71
+ if (!fallback) return appUrl || null;
72
+ try {
73
+ if (aivinZone(new URL(appUrl).hostname) === aivinZone(new URL(fallback).hostname)) return appUrl;
74
+ } catch { /* app_url hỏng thì dùng web mặc định */ }
75
+ return fallback;
76
+ }
77
+
48
78
  export function serverKey(serverUrl) {
49
79
  return createHash('sha256').update(resolveServerUrl(serverUrl)).digest('hex').slice(0, 24);
50
80
  }
@@ -75,4 +105,4 @@ export function serverLabel(serverUrl) {
75
105
  if (url === 'https://api.aivin.vn') return 'VN';
76
106
  if (url.startsWith('http://localhost:') || url.startsWith('http://127.0.0.1:')) return 'Local';
77
107
  return new URL(url).host;
78
- }
108
+ }
package/docs/CLI.md CHANGED
@@ -965,7 +965,7 @@ Options:
965
965
  aivin login
966
966
  ```
967
967
 
968
- Opens your default browser to the platform's actual login page (`https://brain.aivin.cloud`) with
968
+ Opens your default browser to the platform's actual login page (`https://app.aivin.cloud`) with
969
969
  a one-time state token and a `localhost` callback URL. Log in exactly the way you normally would in the
970
970
  browser - custom-domain org, password, Google, OTP, whatever applies to your account. Once you
971
971
  confirm on the "Aivin CLI wants to create an API Key" prompt that appears after login, a fresh key
@@ -1585,7 +1585,7 @@ machine picks it up automatically - there's no per-project credential to manage.
1585
1585
  | -------------------- | -------------------------------------------------- | ----------------------------- | ---------------------------------------------------------------- |
1586
1586
  | `SDK_ENDPOINT` | SDK calls, `aivin start` | `sdk.aivin.cloud:443` | Point `main()`'s SDK calls at a local/dev/staging backend instead of production. Staging: `sdk.aivin.vn:50052` (dedicated Cloudflare Tunnel TLS port - production goes through a load balancer on the standard 443 port instead, a different setup). |
1587
1587
  | `AIVIN_BASE_URL` | `deploy`, `test`, `plugin make/convert/trigger`, `login --basic` | `https://api.aivin.cloud` | Only for a self-hosted or staging instance. Staging: `https://api.aivin.vn`. |
1588
- | `AIVIN_WEB_URL` | `login` (browser flow) | `https://brain.aivin.cloud` | Only for a self-hosted or staging instance. |
1588
+ | `AIVIN_WEB_URL` | `login` (browser flow) | `https://app.aivin.cloud` | Only for a self-hosted or staging instance. |
1589
1589
  | `LOCAL_TEST_PORT` | `aivin start` | `4001` | Only if `4001` is already taken on your machine. |
1590
1590
  | `LOCAL_TEST_HOST` | `aivin start` | `127.0.0.1` | Loopback-only by default (`/invoke` has no auth) - only widen this if you deliberately want another device on your network to reach it. See [sdk repo's SECURITY.md](https://github.com/aivin-labs/AIVIN-SDK/blob/main/docs/SECURITY.md). |
1591
1591
  | `AIVIN_SANDBOX_WORKER` | `aivin start`, deployed containers | `false` | Set `true` to run `src/main.ts` inside an isolated `worker_threads.Worker` (no direct access to the container's secret, restricted fs/child_process) instead of loading it in-process. Off by default - see [sdk repo's worker-sandbox.md](https://github.com/aivin-labs/AIVIN-SDK/blob/main/docs/draft/plugins/worker-sandbox.md). |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aivin-labs/cli",
3
- "version": "1.0.47",
3
+ "version": "1.0.51",
4
4
  "description": "aivin CLI - scaffold, run, and deploy Aivin plugins built on @aivin-labs/sdk",
5
5
  "type": "module",
6
6
  "bin": {