@aivin-labs/cli 1.0.68 → 1.0.78

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.
@@ -32,7 +32,10 @@ import { showOSNotification } from './notify.mjs';
32
32
  import { createMeetingManager, watchMeetingRequests } from './meeting/index.mjs';
33
33
  import { createMediaHost, mediaSupported } from './meeting/recorder.mjs';
34
34
  import { createClipboard } from './clipboard.mjs';
35
- import { activeAgentRunner, activeLocalLlm, buildTools, toolMap } from './toolHandlers.mjs';
35
+ import { lightcodeOrgJobsEnabled, lightcodeReadiness, readHeadlessConnector, startLightcodeEventBridge } from './lightcodeAgent.mjs';
36
+ import { sanitizeAuthEnv } from './ephemeralAuth.mjs';
37
+ import { activeAgentRunner, activeLlmLogin, activeLocalLlm, buildTools, toolMap } from './toolHandlers.mjs';
38
+ import { createLocalLlm } from './localLlm.mjs';
36
39
  import { localLlmAccounts } from './localLlmAccounts.mjs';
37
40
  import { createBrowserTunnels, detectLocalBrowser } from './browserTunnel.mjs';
38
41
  import { createGuiController, detectGui } from './gui/index.mjs';
@@ -45,6 +48,7 @@ import { createWatchManager } from './deviceWatches.mjs';
45
48
  import { createScheduleManager } from './schedule.mjs';
46
49
  import { remoteDebuggingPage } from './dailyBrowser.mjs';
47
50
  import { HOME_BASE, SHARED_DIR, createMultiUserHost, isMultiUserMode } from './multiUser.mjs';
51
+ import { LICENSE_RENEW_EVENT, createLicenseRenewHandler } from './orgComputerLicense.mjs';
48
52
  import { createAutoUpdater } from './autoUpdate.mjs';
49
53
  import { castLeadInConfig, createDesktopCastManager } from './desktop/desktopCast.mjs';
50
54
  import { createDesktopWebRtcWorker } from './desktop/webrtcWorker.mjs';
@@ -69,6 +73,8 @@ import {
69
73
  } from '../selfUpdate.mjs';
70
74
  import { cliLaunchCommand, detectSupervisor } from './autoStart.mjs';
71
75
 
76
+ /** Cách nhau bao lâu thì xem lại LightCode đã dùng được chưa (người dùng đăng nhập tài khoản sau khi máy kết nối). */
77
+ const LIGHTCODE_WATCH_MS = 60_000;
72
78
  const HEARTBEAT_MS = 20_000;
73
79
  // Nhịp nối lại tối đa. Máy cá nhân giãn tới 30 s (nhiều máy cùng dội BE lúc deploy). Cloud Computer (`--multi-user`): một socket / org qua
74
80
  // mạng nội bộ, BE có thể đang chờ máy nối về để giao việc — giãn 30 s (+50 % ngẫu nhiên) nghĩa là BE lên lại rồi vẫn chờ tới ~45 s (28/10/2026).
@@ -135,6 +141,7 @@ export function isValidDeviceCall(call) {
135
141
  if (call.args !== undefined && call.args !== null && !isPlainObject(call.args)) return false;
136
142
  if (call.timeout_ms !== undefined && call.timeout_ms !== null && !Number.isFinite(call.timeout_ms)) return false;
137
143
  if (call.user_scope !== undefined && call.user_scope !== null && typeof call.user_scope !== 'string') return false;
144
+ if (call.auth_env !== undefined && call.auth_env !== null && !isPlainObject(call.auth_env)) return false;
138
145
  if (call.idem_key !== undefined && call.idem_key !== null && (typeof call.idem_key !== 'string' || call.idem_key.length > 80)) return false;
139
146
  if (call.purpose !== undefined && call.purpose !== null && typeof call.purpose !== 'string') return false;
140
147
  return true;
@@ -401,21 +408,31 @@ export async function startRemoteClient(options = {}) {
401
408
  return ack?.ok ? { ok: true } : { ok: false, error: ack?.error || 'failed' };
402
409
  },
403
410
  }) : null;
404
- const env = { roots, binaries: profile.binaries, projects: profile.projects, fileIndex, browserTunnels, gui, office: officeApps.length ? { host: officeHost, apps: officeApps } : null, undo, processes, schedules, watches, transfer, meetings, media, clipboard: multiUser ? null : createClipboard() };
411
+ // Cài xong LightCode (lightcode.install) → chào lại để BE thấy agent mới ngay, không chờ nối lại.
412
+ const env = { announceProfile: () => announceProfile?.(), roots, binaries: profile.binaries, projects: profile.projects, fileIndex, browserTunnels, gui, office: officeApps.length ? { host: officeHost, apps: officeApps } : null, undo, processes, schedules, watches, transfer, meetings, media, clipboard: multiUser ? null : createClipboard(),
413
+ // Máy tính tổ chức: agent làm mô hình chạy dưới tài khoản từng thành viên, bằng đăng nhập của chính họ (localLlmMembers.mjs).
414
+ ...(multiUser ? { localLlm: createLocalLlm({ memberMode: true }) } : {}) };
405
415
  const host = multiUser ? createMultiUserHost({ baseEnv: env, say: (m) => say(chalk.gray(m)) }) : null;
406
416
  host?.start();
407
417
  const tools = buildTools(env);
408
418
  const byName = toolMap(tools);
409
419
  // Mô hình trên máy (`llm.complete`, công cụ BE-only nên BE biết qua cờ này) — BE dùng cho tier nặng khi phiên chat gắn với máy này.
410
- if (byName.has('llm.complete')) {
420
+ // Tách thành hàm để gọi lại trong `announce()` mỗi khi LightCode được bật / tắt sau lúc daemon khởi động.
421
+ let lightcodeLlmSent = false;
422
+ const refreshLocalLlmProfile = () => {
423
+ if (!byName.has('llm.complete')) return;
411
424
  const agents = activeLocalLlm()?.info().agents || [];
412
- // `accounts`: băm tài khoản từng agent — BE tính hạn mức theo tài khoản + nhóm model (localLlmAccounts.mjs).
413
425
  if (agents.length) {
414
426
  const ids = agents.map((a) => a.id);
415
- const accounts = localLlmAccounts(ids);
416
- profile.local_llm = { provider: ids[0], agents: ids, ...(accounts ? { accounts } : {}) };
427
+ const accounts = multiUser ? undefined : localLlmAccounts(ids);
428
+ profile.local_llm = { provider: ids[0], agents: ids, ...(accounts ? { accounts } : {}), ...(multiUser ? { per_member: true } : {}) };
429
+ lightcodeLlmSent = ids.includes('lightcode');
430
+ } else {
431
+ delete profile.local_llm;
432
+ lightcodeLlmSent = false;
417
433
  }
418
- }
434
+ };
435
+ refreshLocalLlmProfile();
419
436
  // Công cụ chủ máy tắt (`aivin remote policy deny`) không vào danh mục — Planner không lập kế hoạch với nó (gọi tới vẫn bị chặn ở sàn luật).
420
437
  const deniedTools = new Set(policyGuard.read().deny_tools);
421
438
  if (deniedTools.has('gui.act')) deniedTools.add('gui.do');
@@ -426,6 +443,8 @@ export async function startRemoteClient(options = {}) {
426
443
  const earlyDrops = [];
427
444
  let earlyWorkDir = null;
428
445
  let announceProfile = null;
446
+ /** Sự cố LightCode đã báo cho BE ở lần chào gần nhất (null = dùng được / chưa biết) — để chào lại đúng lúc nó đổi. */
447
+ let lightcodeIssueSent = null;
429
448
  const applyWorkDir = (dir) => { if (mascotChat) mascotChat.setWorkDir(dir); else earlyWorkDir = dir; };
430
449
  /** Chủ máy đồng ý mở thêm thư mục: có hiệu lực ngay (công cụ đọc env.roots lúc gọi), báo BE hồ sơ mới, lưu cho các lần chạy sau. */
431
450
  const grantRoot = (dir) => {
@@ -461,6 +480,7 @@ export async function startRemoteClient(options = {}) {
461
480
  onCancel: () => { void mascotChat?.cancel(); },
462
481
  onNewChat: () => { void mascotChat?.newChat(); },
463
482
  onOpenTool: (msg) => { void mascotChat?.openTool(msg); },
483
+ onOpenLocal: (id) => mascotChat?.openLocal(id),
464
484
  onNotifyFreq: (val) => { mascotChat?.setNotifyFreq(val); },
465
485
  // Thả tệp vào bot → đi kèm câu gõ kế tiếp.
466
486
  // "Gửi cho AIVIN Bot" từ Explorer có thể tới trước khi ô hỏi dựng xong (daemon vừa được khay mở) → giữ lại, dựng xong thì đính.
@@ -811,6 +831,31 @@ export async function startRemoteClient(options = {}) {
811
831
  }
812
832
  const pauseWatch = setInterval(checkPauseNow, PAUSE_POLL_MS);
813
833
  pauseWatch.unref?.();
834
+ // Người dùng đăng nhập tài khoản AI (hoặc bật/tắt LightCode) sau khi máy đã kết nối → chào lại ngay để BE cập nhật agent và bộ chọn model, không đợi lần nối lại.
835
+ const lightcodeWatch = setInterval(async () => {
836
+ if (stopped || multiUser || !socket.connected) return;
837
+ const hasLightcodeLlmNow = !!(byName.has('llm.complete') && activeLocalLlm()?.info().agents?.some((a) => a.id === 'lightcode'));
838
+ if (hasLightcodeLlmNow !== lightcodeLlmSent) {
839
+ void announceProfile?.();
840
+ return;
841
+ }
842
+ if (!activeAgentRunner()?.installed().some((a) => a.id === 'lightcode')) return;
843
+ const why = await lightcodeReadiness().catch(() => undefined);
844
+ if (why === undefined || (why || null) === lightcodeIssueSent) return;
845
+ void announceProfile?.();
846
+ }, LIGHTCODE_WATCH_MS);
847
+ lightcodeWatch.unref?.();
848
+ // Cầu đẩy sự kiện từ LightCode (`job.finished`, `job.attention` — gồm cả deploy): báo ngay lên BE và hiện thông báo hệ thống khi cần chú ý.
849
+ const lightcodeEventBridge = (!multiUser && process.platform === 'win32') ? startLightcodeEventBridge({
850
+ onEvent: (ev) => {
851
+ if (socket.connected) socket.emit(DeviceEvent.LIGHTCODE_EVENT, ev);
852
+ if (ev?.type === 'job.attention' && !isPaused()) {
853
+ const title = `LightCode · ${String(ev.title || 'Needs attention').slice(0, 80)}`;
854
+ const body = String(ev.data?.summary || ev.data?.kind || 'A LightCode job needs your input').slice(0, 200);
855
+ showOSNotification(title, body);
856
+ }
857
+ },
858
+ }) : null;
814
859
  // `aivin remote pause` / nút ở khay / lệnh ngắt cast ở cửa sổ khác: phản ứng ngay khi tệp đổi (fs.watch), không đợi tới 1–2 s của lượt kiểm
815
860
  // định kỳ — trong lúc đó màn hình vẫn đang phát cho người xem. Tên tệp có thể vắng (Windows) → kiểm cả hai.
816
861
  let configWatcher = null;
@@ -852,6 +897,8 @@ export async function startRemoteClient(options = {}) {
852
897
  stopped = true;
853
898
  clearInterval(heartbeat);
854
899
  clearInterval(pauseWatch);
900
+ clearInterval(lightcodeWatch);
901
+ lightcodeEventBridge?.stop();
855
902
  clearInterval(castActionTimer);
856
903
  try { configWatcher?.close(); } catch { /* đã đóng */ }
857
904
  clearTimeout(confirmTimer);
@@ -879,6 +926,7 @@ export async function startRemoteClient(options = {}) {
879
926
  // Job của agent lập trình: dừng + ghi hồ sơ (`stopped`) — lần chạy sau `agent.status` vẫn đọc được, nói tiếp bằng session_id.
880
927
  activeAgentRunner()?.stopAll();
881
928
  activeLocalLlm()?.stopAll();
929
+ activeLlmLogin()?.closeAll();
882
930
  keepAwake.close();
883
931
  castAwake.close();
884
932
  watches?.closeAll();
@@ -956,6 +1004,22 @@ export async function startRemoteClient(options = {}) {
956
1004
  const announce = async () => {
957
1005
  try {
958
1006
  if (!multiUser) profile.update = updateProfile({ enabled: autoUpdateEnabled });
1007
+ refreshLocalLlmProfile();
1008
+ // Agent lập trình chạy được HỢP ĐỒNG trên máy (20/11/2026: gồm LightCode — cài / bật sau khi daemon chạy nên đọc lại mỗi lần chào).
1009
+ // Luôn gửi (kể cả rỗng): BE coi đây là danh sách đầy đủ, không còn đoán "có agent.run là có Claude".
1010
+ // Container: LightCode headless chỉ được quảng bá khi bật cờ AIVIN_LIGHTCODE_ORG_JOBS=1 (mặc định tắt → org dùng Claude Code / Codex).
1011
+ const runner = multiUser ? null : activeAgentRunner();
1012
+ const headlessLc = multiUser && lightcodeOrgJobsEnabled() ? readHeadlessConnector() : null;
1013
+ if (runner || headlessLc) {
1014
+ profile.coding_agents = runner ? runner.installed().map((a) => a.id) : (headlessLc ? ['lightcode'] : []);
1015
+ // LightCode cài rồi mà chưa dùng được (chưa đăng nhập tài khoản AI nào / hết bản quyền) → BE không giao việc cho nó, thay vì thất bại ngay lượt đầu.
1016
+ delete profile.coding_agent_issues;
1017
+ lightcodeIssueSent = null;
1018
+ if (profile.coding_agents.includes('lightcode')) {
1019
+ const why = await lightcodeReadiness().catch(() => null);
1020
+ if (why) { profile.coding_agent_issues = { lightcode: why }; lightcodeIssueSent = why; }
1021
+ }
1022
+ }
959
1023
  const hello = await socket.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.HELLO, { protocol: PROTOCOL_VERSION, profile, catalog_hash: hash, inflight: ledger.heldIds() });
960
1024
  const userLang = hello?.user_lang || hello?.lang;
961
1025
  if (userLang && mascot.enabled) {
@@ -1089,6 +1153,8 @@ export async function startRemoteClient(options = {}) {
1089
1153
  callEnv = host.envFor(call.user_scope);
1090
1154
  host.assertQuota(call.tool);
1091
1155
  }
1156
+ const authEnv = sanitizeAuthEnv(call.auth_env);
1157
+ if (authEnv) callEnv = { ...callEnv, authEnv };
1092
1158
  await localGate(call, tool);
1093
1159
  if (!tool.read_only) await waitConfirmBarrier(call);
1094
1160
  // Chủ máy có thể vừa tạm dừng trong lúc chờ hộp xác nhận (của chính lời gọi này hoặc của lời gọi khác).
@@ -1279,6 +1345,8 @@ export async function startRemoteClient(options = {}) {
1279
1345
  console.log(chalk.red('❌ Máy này đã bị thu hồi quyền điều khiển từ xa.'));
1280
1346
  stopForGood();
1281
1347
  }));
1348
+ // Gia han ve LightCode: BE gui payload { token, expiresAt? } qua socket khi ve sap het han (< 6h). Handler ghi de tep ve nguyen tu, ack {ok}.
1349
+ if (multiUser) socket.on(LICENSE_RENEW_EVENT, guarded(LICENSE_RENEW_EVENT, (payload, ack) => createLicenseRenewHandler({ log: (msg) => say(chalk.gray(msg)) })(payload, ack)));
1282
1350
  socket.on(DeviceEvent.CALLS, guarded(DeviceEvent.CALLS, (payload) => {
1283
1351
  // Chỉ nhận / ACK lời gọi đúng dạng — `{ calls: [null] }` từng làm sập daemon (null.call_id trong listener).
1284
1352
  const calls = (Array.isArray(payload?.calls) ? payload.calls : []).filter(isValidDeviceCall);