@aivin-labs/cli 1.0.24 → 1.0.27

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.
@@ -131,7 +131,7 @@ const MAX_PENDING = 20;
131
131
  * một lần `fields` (+ `text` = giá trị khi chỉ một trường — BE cũ chưa nhận `fields` vẫn hiểu). BE từ chối → hỏi lại từ trường đầu.
132
132
  */
133
133
  export function createMascotChat({
134
- socket, send, lang, timers = { setTimeout, clearTimeout }, now = Date.now, onAlert = () => {}, onPending = () => {}, micBusy = () => false,
134
+ socket, send, lang, timers = { setTimeout, clearTimeout }, now = Date.now, onAlert = () => {}, onPending = () => {}, micBusy = () => false, onWorkDir = () => {},
135
135
  serverUrl = '', notifyFreq = 1, fetchImage = (url) => fetchMascotImage(url, { serverUrl }), renderDiagramImage = (source) => renderDiagram(source), openToolWindow = openWebview,
136
136
  }) {
137
137
  let currentLang = lang || 'vi';
@@ -155,7 +155,17 @@ export function createMascotChat({
155
155
  /** Tệp thả vào bot, chờ đi kèm câu kế tiếp. */
156
156
  const files = [];
157
157
  /** Tệp đang chờ → cửa sổ: số tệp (thùng trong tay bot + huy hiệu) + chip từng tệp trên dòng nhập (icon / màu theo loại, nút × để bỏ). */
158
- const syncFiles = () => send({ t: AskCommand.FILES, n: files.length, files: files.map((f) => fileChip(f)) });
158
+ const syncFiles = () => send({ t: AskCommand.FILES, n: files.length, files: [...(workDir ? [workDirChip()] : []), ...files.map((f) => fileChip(f))] });
159
+ /**
160
+ * Thư mục làm việc ("Làm việc ở đây với AIVIN Bot"): đi kèm MỌI câu (`working_dir`, BE đưa vào ngữ cảnh của agent, không hiện trong chat) tới khi
161
+ * chủ máy bấm × trên chip. Không tính vào `n` — `n` là số tệp chờ gửi (nút gửi không có chữ, thùng trong tay bot).
162
+ */
163
+ let workDir = null;
164
+ const workDirChip = () => {
165
+ const chip = fileChip(workDir, { dir: () => true });
166
+ return { ...chip, name: t(MascotText.ASK_WORKDIR_CHIP, { name: chip.name || workDir }), pinned: true, detach_tip: t(MascotText.ASK_WORKDIR_DETACH) };
167
+ };
168
+ const workContext = () => (workDir ? { working_dir: workDir } : {});
159
169
  /** Cửa sổ chủ máy đang dùng khi hỏi (mascot/index.mjs `userWindow`) của lượt / cuộc nói chuyện gần nhất, hoặc null. */
160
170
  let target = null;
161
171
  const context = () => (target ? { context: { window: target } } : {});
@@ -411,7 +421,7 @@ export function createMascotChat({
411
421
  let ack;
412
422
  try {
413
423
  // `stream`: xin chữ chạy của câu trả lời (`delta`); `links` / `blocks`: hiện được nút mở link, bảng, thẻ, ảnh — BE cũ bỏ qua các trường này.
414
- ack = await s.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.CHAT, { text, request_id: current, stream: true, links: true, blocks: true, ...context(), ...extra });
424
+ ack = await s.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.CHAT, { text, request_id: current, stream: true, links: true, blocks: true, ...context(), ...workContext(), ...extra });
415
425
  if (ack?.session_id) { currentSessionId = ack.session_id; noteDeviceSession(ack.session_id); }
416
426
  } catch (e) {
417
427
  finish();
@@ -438,7 +448,7 @@ export function createMascotChat({
438
448
  if (!s?.connected) return row(ChatRole.ERROR, t(MascotText.ASK_OFFLINE));
439
449
  try {
440
450
  const ack = await s.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.CHAT, {
441
- text, request_id: `ask-par-${randomUUID()}`, parallel: true, links: true, blocks: true, ...(window ? { context: { window } } : context()),
451
+ text, request_id: `ask-par-${randomUUID()}`, parallel: true, links: true, blocks: true, ...(window ? { context: { window } } : context()), ...workContext(),
442
452
  });
443
453
  if (!ack?.ok) return row(ChatRole.ERROR, errorText(ack?.error));
444
454
  if (ack.session_id) noteDeviceSession(ack.session_id);
@@ -458,11 +468,28 @@ export function createMascotChat({
458
468
  /** Bấm × trên chip: bỏ tệp đó khỏi lượt kế tiếp. */
459
469
  function detach(file) {
460
470
  const at = files.indexOf(file);
461
- if (at < 0) return;
471
+ if (at < 0) {
472
+ if (file === workDir) setWorkDir(null);
473
+ return;
474
+ }
462
475
  files.splice(at, 1);
463
476
  syncFiles();
464
477
  }
465
478
 
479
+ /** Đặt / bỏ thư mục làm việc. `quiet`: khôi phục lúc daemon khởi động — không báo, không lưu lại. */
480
+ function setWorkDir(dir, { quiet = false } = {}) {
481
+ workDir = dir || null;
482
+ syncFiles();
483
+ if (quiet) return;
484
+ onWorkDir(workDir);
485
+ send({ t: AskCommand.STATUS, text: workDir ? t(MascotText.ASK_WORKDIR_SET, { path: workDir }) : t(MascotText.ASK_WORKDIR_CLEARED) });
486
+ }
487
+
488
+ /** Thư mục được chọn không dùng được (ngoài quyền và chủ máy không đồng ý, ổ mạng, không còn tồn tại). */
489
+ function workDirDenied(dir) {
490
+ send({ t: AskCommand.STATUS, text: t(MascotText.ASK_WORKDIR_DENIED, { path: dir }) });
491
+ }
492
+
466
493
  /** Câu hỏi mới như chủ máy gõ (luôn vào phiên riêng của máy, kể cả khi đang có câu hỏi chờ). */
467
494
  async function ask(text, window = null) {
468
495
  const question = String(text || '').trim();
@@ -945,7 +972,7 @@ export function createMascotChat({
945
972
 
946
973
  return {
947
974
  openTool,
948
- ask, reply, choose, attach, detach, cancel, newChat, onChatEvent, onNotify, syncInbox, checkQuestions, setServerFeatures, busy: () => !!current || !!call, hasPending: () => queue.length > 0, userWindow: () => target,
975
+ ask, reply, choose, attach, detach, setWorkDir, workDirDenied, workDir: () => workDir, cancel, newChat, onChatEvent, onNotify, syncInbox, checkQuestions, setServerFeatures, busy: () => !!current || !!call, hasPending: () => queue.length > 0, userWindow: () => target,
949
976
  voiceStart, voiceAudio, voiceInterrupt, voiceStop, voiceMicLost, voiceDisconnected, onVoiceEvent, setVoiceSupported, inCall: () => !!call,
950
977
  setNotifyFreq: (val) => { const v = Number(val); if (Number.isInteger(v) && v >= 0 && v <= 2) currentNotifyFreq = v; },
951
978
  setLang: (l) => { if (l) currentLang = l; },
@@ -443,6 +443,8 @@ function AttachChips($chips) {
443
443
  if (-not $c -or -not $c.path) { continue }
444
444
  $ink = [string]$c.ink; if (-not $ink) { $ink = '#64748B' }
445
445
  $chip = New-Object Windows.Controls.Border; $chip.CornerRadius = '8'; $chip.Padding = '6,2,2,2'; $chip.Margin = '4,0,0,4'; $chip.ToolTip = [string]$c.path
446
+ # The working folder's chip stays after a question goes out and is not a waiting file (ask_files).
447
+ if ($c.pinned) { $chip.Tag = 'pinned' }
446
448
  $chip.Background = Brush $(if ($c.bg) { [string]$c.bg } else { '#F8FAFC' })
447
449
  # Hairline in the type's colour (ink at ~20 %): keeps the very light chip readable on the white box.
448
450
  $chip.BorderThickness = '1'; $chip.BorderBrush = Brush ('#33' + $ink.TrimStart('#'))
@@ -451,7 +453,7 @@ function AttachChips($chips) {
451
453
  $tb = New-Object Windows.Controls.TextBlock; $tb.Text = [string]$c.name; $tb.FontSize = 12; $tb.Foreground = Brush $ink; $tb.MaxWidth = 140
452
454
  $tb.TextTrimming = 'CharacterEllipsis'; $tb.VerticalAlignment = 'Center'; [void]$row.Children.Add($tb)
453
455
  $x = New-Object Windows.Controls.Button; $x.Style = $w.FindResource('IconBtn'); $x.Width = 18; $x.Height = 18; $x.Margin = '3,0,0,0'
454
- $x.Background = Brush '#00000000'; $x.BorderThickness = '0'; $x.Tag = Brush '#1F000000'; $x.ToolTip = $T.ask_detach
456
+ $x.Background = Brush '#00000000'; $x.BorderThickness = '0'; $x.Tag = Brush '#1F000000'; $x.ToolTip = $(if ($c.detach_tip) { [string]$c.detach_tip } else { $T.ask_detach })
455
457
  $x.Content = LucideIcon '${DETACH_ICON_PATH}' 10 $ink; $x.CommandParameter = [string]$c.path
456
458
  $x.Add_Click({ param($s) Send @{ t = 'detach'; path = [string]$s.CommandParameter } })
457
459
  [void]$row.Children.Add($x); $chip.Child = $row; [void]$bar.Children.Add($chip)
@@ -590,7 +592,7 @@ function Handle($m) {
590
592
  'ask_status' { AskStatus $m.text; return }
591
593
  'ask_choices' { ChoiceButtons $m.options $m.multiple; return }
592
594
  # Files waiting for the next question: chips above the input; then on to the bot's tray (no return).
593
- 'ask_files' { $chips = @($m.files | Where-Object { $_ }); $more = $chips.Count -gt (E 'AttachBar').Children.Count; $script:files = [int]$m.n; AttachChips $chips; SyncAction; if ($more) { PeekAsk; HideAskLater ${ASK_IDLE_MS} } }
595
+ 'ask_files' { $chips = @($m.files | Where-Object { $_ }); $more = @($chips | Where-Object { -not $_.pinned }).Count -gt @((E 'AttachBar').Children | Where-Object { $_.Tag -ne 'pinned' }).Count; $script:files = [int]$m.n; AttachChips $chips; SyncAction; if ($more) { PeekAsk; HideAskLater ${ASK_IDLE_MS} } }
594
596
  'ask_pin' {
595
597
  $script:askPinned = [bool]$m.on
596
598
  if ($script:askPinned) { $script:userHidden = $false; ApplyVisibility; AskHide 'Panel'; PeekAsk; (E 'ChatScroll').ScrollToEnd() }
@@ -1,7 +1,7 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
3
  import readline from 'readline';
4
- import { createHash } from 'crypto';
4
+ import { createHash, randomBytes } from 'crypto';
5
5
  import { spawn } from 'child_process';
6
6
  import { NotifyKind, REMOTE_CONFIG_DIR, ToolGroup } from '../constants.mjs';
7
7
  import { AIVIN_LOGO_PNG_BASE64 } from '../brand.mjs';
@@ -43,9 +43,60 @@ export const MASCOT_HIDE_FILE = path.join(REMOTE_CONFIG_DIR, 'mascot-hide');
43
43
  export const MASCOT_VOICE_FILE = path.join(REMOTE_CONFIG_DIR, 'mascot-voice');
44
44
  /** Phím tắt cửa sổ linh vật đang giữ thật (`{ chat, voice }`, tổ hợp đầu tiên còn trống) — khay đọc để hiện cạnh mục menu; cửa sổ đóng thì xoá. */
45
45
  export const MASCOT_HOTKEYS_FILE = path.join(REMOTE_CONFIG_DIR, 'mascot-hotkeys.json');
46
+ /**
47
+ * "Gửi cho AIVIN Bot" (chuột phải tệp / Send to, Aivin.exe --share; `aivin share`): mỗi yêu cầu một tệp `<mốc>-<pid>.txt`, mỗi dòng một đường
48
+ * dẫn — Explorer chạy một tiến trình cho mỗi tệp được chọn, nên không ghi chung một tệp. Daemon đọc xong xoá, đính vào ô hỏi như kéo thả.
49
+ */
50
+ export const MASCOT_ATTACH_DIR = path.join(REMOTE_CONFIG_DIR, 'mascot-attach');
51
+ /** Yêu cầu cũ hơn chừng này (daemon không chạy lúc đó) thì bỏ — không bật ô hỏi với tệp gửi từ hôm qua. Đủ cho khay mở daemon từ đầu. */
52
+ const ATTACH_REQUEST_GRACE_MS = 2 * 60_000;
46
53
  const SHOW_POLL_MS = 250;
47
54
  const SHOW_REQUEST_GRACE_MS = 30_000;
48
55
 
56
+ let attachRequestSeq = 0;
57
+
58
+ /** Ghi yêu cầu đính tệp cho daemon đang chạy (hoặc sắp chạy). Số thứ tự giữ đúng thứ tự gửi khi trùng mili giây (nơi đọc xếp theo tên tệp). */
59
+ export function requestMascotAttach(paths, dir = MASCOT_ATTACH_DIR) {
60
+ const list = (paths || []).filter((p) => typeof p === 'string' && p).map((p) => path.resolve(p));
61
+ if (!list.length) return;
62
+ fs.mkdirSync(dir, { recursive: true });
63
+ const seq = String(++attachRequestSeq).padStart(6, '0');
64
+ const file = path.join(dir, `${Date.now()}-${process.pid}-${seq}-${randomBytes(4).toString('hex')}.txt`);
65
+ fs.writeFileSync(`${file}.tmp`, list.join('\r\n'));
66
+ fs.renameSync(`${file}.tmp`, file);
67
+ }
68
+
69
+ /** Đọc + xoá mọi yêu cầu có đuôi `ext`; trả các dòng còn trong hạn (theo thứ tự gửi, không trùng). */
70
+ function takeRequests(dir, ext, now) {
71
+ let names;
72
+ try { names = fs.readdirSync(dir).filter((n) => n.endsWith(ext)).sort(); } catch { return []; }
73
+ const lines = [];
74
+ for (const name of names) {
75
+ const file = path.join(dir, name);
76
+ try {
77
+ const fresh = now - fs.statSync(file).mtimeMs <= ATTACH_REQUEST_GRACE_MS;
78
+ const text = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
79
+ fs.rmSync(file, { force: true });
80
+ if (!fresh) continue;
81
+ for (const line of text.split(/\r?\n/)) {
82
+ const p = line.trim();
83
+ if (p && !lines.includes(p)) lines.push(p);
84
+ }
85
+ } catch { /* đang ghi dở / vừa bị xoá — lần quét sau */ }
86
+ }
87
+ return lines;
88
+ }
89
+
90
+ /** Các đường dẫn "Gửi cho AIVIN Bot" đang chờ. */
91
+ export function takeAttachRequests(dir = MASCOT_ATTACH_DIR, now = Date.now()) {
92
+ return takeRequests(dir, '.txt', now);
93
+ }
94
+
95
+ /** "Làm việc ở đây với AIVIN Bot" (Aivin.exe --workdir, cùng thư mục yêu cầu, đuôi `.workdir`): chọn nhiều lần thì lần sau cùng thắng. */
96
+ export function takeWorkFolderRequest(dir = MASCOT_ATTACH_DIR, now = Date.now()) {
97
+ return takeRequests(dir, '.workdir', now).at(-1) || null;
98
+ }
99
+
49
100
  /** Ghi yêu cầu hiện linh vật cho daemon đang chạy (hoặc sắp chạy). */
50
101
  export function requestMascotShow(file = MASCOT_SHOW_FILE) {
51
102
  fs.mkdirSync(path.dirname(file), { recursive: true });
@@ -89,9 +140,11 @@ function normalizeMascotSettings(data) {
89
140
  const pos = Number.isFinite(data.x) && Number.isFinite(data.y) ? { x: data.x, y: data.y } : {};
90
141
  const freq = Number.isInteger(data.notify_freq) && data.notify_freq >= 0 && data.notify_freq <= 2 ? { notify_freq: data.notify_freq } : {};
91
142
  // `aivin remote mascot hotkey …` (cli.mjs): tổ hợp chủ máy đặt / 'off'; trước đây bị bỏ khi đọc → lượt lưu vị trí kế tiếp xoá mất.
143
+ // Thư mục làm việc của ô hỏi ("Làm việc ở đây với AIVIN Bot"): giữ qua các lần khởi động lại, tới khi chủ máy bấm × trên chip.
144
+ const workDir = typeof data.work_dir === 'string' && data.work_dir ? { work_dir: data.work_dir } : {};
92
145
  const hotkey = typeof data.hotkey === 'string' && data.hotkey ? { hotkey: data.hotkey } : {};
93
146
  const chatHotkey = typeof data.chat_hotkey === 'string' && data.chat_hotkey ? { chat_hotkey: data.chat_hotkey } : {};
94
- return { enabled: data.enabled !== false, ...freq, ...hotkey, ...chatHotkey, ...pos };
147
+ return { enabled: data.enabled !== false, ...freq, ...workDir, ...hotkey, ...chatHotkey, ...pos };
95
148
  }
96
149
 
97
150
  export function loadMascotSettings(file = MASCOT_SETTINGS_FILE) {
@@ -172,8 +225,9 @@ export function userWindow(w) {
172
225
  */
173
226
  export function createMascot({
174
227
  enabled = true, platform = process.platform, env = process.env, lang: preferredLang, onPause = () => {}, onResume = () => {}, say = () => {},
175
- onAsk = () => {}, onVoice = () => {}, onChoose = () => {}, onCancel = () => {}, onNewChat = () => {}, onOpenTool = () => {}, onDrop = () => {}, onDetach = () => {}, onNotifyFreq = () => {},
176
- spawnImpl = spawn, dir = MASCOT_DIR, settingsFile = MASCOT_SETTINGS_FILE, showFile = MASCOT_SHOW_FILE, hideFile = MASCOT_HIDE_FILE, voiceFile = MASCOT_VOICE_FILE, hotkeysFile = MASCOT_HOTKEYS_FILE, now = Date.now, timers = { setTimeout, clearTimeout },
228
+ onAsk = () => {}, onVoice = () => {}, onChoose = () => {}, onCancel = () => {}, onNewChat = () => {}, onOpenTool = () => {}, onDrop = () => {}, onWorkFolder = () => {}, onDetach = () => {}, onNotifyFreq = () => {},
229
+ spawnImpl = spawn, dir = MASCOT_DIR, settingsFile = MASCOT_SETTINGS_FILE, showFile = MASCOT_SHOW_FILE, hideFile = MASCOT_HIDE_FILE, voiceFile = MASCOT_VOICE_FILE, hotkeysFile = MASCOT_HOTKEYS_FILE,
230
+ attachDir = MASCOT_ATTACH_DIR, now = Date.now, timers = { setTimeout, clearTimeout },
177
231
  thinkMs = THINK_MS, resultMs = RESULT_MS, mainThrottleMs = MAIN_THROTTLE_MS, restartDelaysMs = RESTART_DELAYS_MS, awayWaveMs = AWAY_WAVE_MS,
178
232
  } = {}) {
179
233
  if (!enabled || platform !== 'win32') return NOOP;
@@ -254,7 +308,7 @@ export function createMascot({
254
308
  if (lastChoices) write(lastChoices);
255
309
  write(lastPin);
256
310
  }
257
- if (lastFiles?.n) write(lastFiles);
311
+ if (lastFiles?.files?.length) write(lastFiles);
258
312
  if (commandOnReady) { write({ t: commandOnReady }); commandOnReady = null; }
259
313
  };
260
314
 
@@ -382,6 +436,16 @@ export function createMascot({
382
436
  fs.rmSync(voiceFile, { force: true });
383
437
  if (voiceAt > voiceSeenAt) wake(HostCommand.VOICE_TOGGLE);
384
438
  } catch {}
439
+ const shared = takeAttachRequests(attachDir, now());
440
+ if (shared.length) {
441
+ onDrop(shared);
442
+ wake();
443
+ }
444
+ const workFolder = takeWorkFolderRequest(attachDir, now());
445
+ if (workFolder) {
446
+ onWorkFolder(workFolder);
447
+ wake();
448
+ }
385
449
  }, SHOW_POLL_MS);
386
450
  showWatch.unref?.();
387
451
 
@@ -81,6 +81,11 @@ export const MascotText = Object.freeze({
81
81
  ASK_ERR_INVALID_ANSWER: 'ask_err_invalid_answer',
82
82
  ASK_ATTACHED: 'ask_attached',
83
83
  ASK_DETACH: 'ask_detach',
84
+ ASK_WORKDIR_CHIP: 'ask_workdir_chip',
85
+ ASK_WORKDIR_DETACH: 'ask_workdir_detach',
86
+ ASK_WORKDIR_SET: 'ask_workdir_set',
87
+ ASK_WORKDIR_CLEARED: 'ask_workdir_cleared',
88
+ ASK_WORKDIR_DENIED: 'ask_workdir_denied',
84
89
  ASK_FILES_LABEL: 'ask_files_label',
85
90
  ASK_FILES_DEFAULT: 'ask_files_default',
86
91
  DROP_ONE: 'drop_one',
@@ -221,6 +226,11 @@ const STRINGS = {
221
226
  [MascotText.ASK_ERR_INVALID_ANSWER]: "Chọn một nút hoặc trả lời đúng câu hỏi",
222
227
  [MascotText.ASK_ATTACHED]: "Gõ việc cần làm với tệp…",
223
228
  [MascotText.ASK_DETACH]: "Bỏ tệp này",
229
+ [MascotText.ASK_WORKDIR_CHIP]: "Làm việc ở: {name}",
230
+ [MascotText.ASK_WORKDIR_DETACH]: "Thôi làm việc ở thư mục này",
231
+ [MascotText.ASK_WORKDIR_SET]: "Từ giờ bot làm việc trong: {path}",
232
+ [MascotText.ASK_WORKDIR_CLEARED]: "Đã bỏ thư mục làm việc",
233
+ [MascotText.ASK_WORKDIR_DENIED]: "Không đặt được thư mục làm việc: {path}",
224
234
  [MascotText.ASK_FILES_LABEL]: "Tệp trên máy này:",
225
235
  [MascotText.ASK_FILES_DEFAULT]: "Xem giúp tôi các tệp này",
226
236
  [MascotText.DROP_ONE]: "Thả vào để hỏi về {name}",
@@ -352,6 +362,11 @@ const STRINGS = {
352
362
  [MascotText.ASK_ERR_INVALID_ANSWER]: "Pick a button or answer the question",
353
363
  [MascotText.ASK_ATTACHED]: "Type what to do with the files…",
354
364
  [MascotText.ASK_DETACH]: "Remove this file",
365
+ [MascotText.ASK_WORKDIR_CHIP]: "Working in: {name}",
366
+ [MascotText.ASK_WORKDIR_DETACH]: "Stop working in this folder",
367
+ [MascotText.ASK_WORKDIR_SET]: "The bot now works in: {path}",
368
+ [MascotText.ASK_WORKDIR_CLEARED]: "Working folder removed",
369
+ [MascotText.ASK_WORKDIR_DENIED]: "Could not set the working folder: {path}",
355
370
  [MascotText.ASK_FILES_LABEL]: "Files on this computer:",
356
371
  [MascotText.ASK_FILES_DEFAULT]: "Take a look at these files",
357
372
  [MascotText.DROP_ONE]: "Drop to ask about {name}",
@@ -181,8 +181,8 @@ export function agentEnv(env = process.env) {
181
181
  return { ...scrubEnv(env), [AGENT_CALL_ENV]: '1' };
182
182
  }
183
183
 
184
- const HUMAN_ONLY_REMOTE_COMMANDS = new Set(['start', 'pair', 'unpair', 'pause', 'resume', 'enable', 'disable', 'reset-id', 'do']);
185
- const HUMAN_ONLY_COMMANDS = new Set(['do', 'login', 'logout']);
184
+ const HUMAN_ONLY_REMOTE_COMMANDS = new Set(['start', 'pair', 'unpair', 'pause', 'resume', 'enable', 'disable', 'reset-id', 'do', 'forget-folder']);
185
+ const HUMAN_ONLY_COMMANDS = new Set(['do', 'login', 'logout', 'uninstall']);
186
186
 
187
187
  /** Lệnh chỉ người ngồi trước máy được chạy. `parent` / `name`: lệnh cha + lệnh con của CLI. */
188
188
  export function assertHumanCommand(parent, name, env = process.env) {
@@ -211,7 +211,7 @@ const CATASTROPHIC_COMMANDS = [
211
211
  const AIVIN_DIR_SEGMENT = /(?:^|[\\/\s'"`~=:(;,|&])\.aivin(?:-release)?(?=[\\/\s'"`);,|&]|$)/i;
212
212
 
213
213
  /** Agent gọi chính CLI Aivin để đổi việc ghép máy / luật / giao việc mới. Khớp chuỗi — `assertHumanCommand` là chốt thứ hai trong tiến trình CLI. */
214
- const AIVIN_SELF_COMMAND = /\baivin(\.exe)?["']?\s+(remote\s+(pair|start|unpair|pause|resume|enable|disable|reset-id|do)\b|do\b|login\b|logout\b)/i;
214
+ const AIVIN_SELF_COMMAND = /\baivin(\.exe)?["']?\s+(remote\s+(pair|start|unpair|pause|resume|enable|disable|reset-id|do|forget-folder)\b|do\b|login\b|logout\b|uninstall\b|desktop\s+uninstall\b)/i;
215
215
 
216
216
  function mentionsProtectedDir(command) {
217
217
  if (AIVIN_DIR_SEGMENT.test(command)) return true;
@@ -0,0 +1,100 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { lockHolder } from './daemonLock.mjs';
4
+ import { loadDeviceCredentials, saveDeviceCredentials } from './credentials.mjs';
5
+ import { isNetworkPath, resolveInRoots } from './sandbox.mjs';
6
+ import { DeviceErrorCode } from './constants.mjs';
7
+ import { MASCOT_ATTACH_DIR, MASCOT_SETTINGS_FILE, loadMascotSettings, saveMascotSettings } from './mascot/index.mjs';
8
+
9
+ /**
10
+ * Thư mục làm việc của ô hỏi (05/11/2026, "Làm việc ở đây với AIVIN Bot"). Yêu cầu tới từ một tệp trong thư mục cấu hình nên không đủ để mở
11
+ * quyền: thư mục nằm ngoài các thư mục được phép thì phải có người bấm đồng ý trên máy, kể cả khi yêu cầu do agent tự ghi qua lệnh shell.
12
+ * Thư mục đã đồng ý nằm ở `extra_roots` của device-credentials.json — `--dir` trong launch.cfg không ghi đè, `aivin remote forget-folder` thu lại.
13
+ */
14
+
15
+ export const WorkFolderStatus = Object.freeze({ OK: 'ok', NEEDS_ROOT: 'needs_root', DENIED: 'denied' });
16
+ export const WORK_FOLDER_CONFIRM_SEC = 120;
17
+
18
+ const CONFIRM_TEXT = Object.freeze({
19
+ vi: {
20
+ reason: 'Thư mục này nằm ngoài các thư mục Aivin được phép. Chỉ đồng ý nếu chính bạn vừa chọn nó.',
21
+ detail: 'Cho Aivin đọc, ghi và chạy lệnh trong thư mục: {path}',
22
+ },
23
+ en: {
24
+ reason: 'This folder is outside the folders Aivin may use. Only allow it if you just picked it yourself.',
25
+ detail: 'Let Aivin read, write and run commands in this folder: {path}',
26
+ },
27
+ });
28
+
29
+ export function workFolderConfirmText(folder, lang = 'en') {
30
+ const text = CONFIRM_TEXT[lang] || CONFIRM_TEXT.en;
31
+ return { reason: text.reason, detail: text.detail.replace('{path}', folder) };
32
+ }
33
+
34
+ /** Danh sách thư mục khi chạy: thư mục gốc + các thư mục chủ máy đã đồng ý thêm, không trùng. */
35
+ export function withExtraRoots(base, extra) {
36
+ const list = [...base];
37
+ for (const dir of Array.isArray(extra) ? extra : []) {
38
+ if (typeof dir !== 'string' || !dir) continue;
39
+ if (!list.some((r) => path.resolve(r) === path.resolve(dir))) list.push(path.resolve(dir));
40
+ }
41
+ return list;
42
+ }
43
+
44
+ const isFolder = (dir) => { try { return fs.statSync(dir).isDirectory(); } catch { return false; } };
45
+
46
+ /** Thư mục còn tồn tại, trong quyền và không phải vùng cấm. */
47
+ export function isAllowedWorkFolder(dir, roots) {
48
+ if (!isFolder(dir)) return false;
49
+ try { resolveInRoots(roots, dir); return true; } catch { return false; }
50
+ }
51
+
52
+ /**
53
+ * `confirm(path)` → có đồng ý mở thêm không; chỉ hỏi khi lý do từ chối đúng là "ngoài quyền". Ổ mạng và thư mục chứa khoá của Aivin thì đồng ý
54
+ * cũng không dùng được (resolveInRoots chặn cứng), nên từ chối luôn. Trả `{ status, path }`; NEEDS_ROOT = đã đồng ý, nơi gọi thêm vào danh sách.
55
+ */
56
+ export async function resolveWorkFolder(dir, { roots, confirm }) {
57
+ const abs = path.resolve(String(dir));
58
+ if (isNetworkPath(String(dir)) || !isFolder(abs)) return { status: WorkFolderStatus.DENIED, path: abs };
59
+ try {
60
+ resolveInRoots(roots, abs);
61
+ return { status: WorkFolderStatus.OK, path: abs };
62
+ } catch (e) {
63
+ if (e?.code !== DeviceErrorCode.ROOT_DENIED) return { status: WorkFolderStatus.DENIED, path: abs };
64
+ }
65
+ try { resolveInRoots([abs], abs); } catch { return { status: WorkFolderStatus.DENIED, path: abs }; }
66
+ return { status: (await confirm(abs)) ? WorkFolderStatus.NEEDS_ROOT : WorkFolderStatus.DENIED, path: abs };
67
+ }
68
+
69
+ /**
70
+ * `aivin desktop uninstall`: bỏ hết những gì các mục chuột phải để lại — yêu cầu còn chờ, thư mục làm việc đã lưu, quyền thư mục đã đồng ý. Thư mục
71
+ * cấu hình giữ nguyên (lệnh `aivin` và việc ghép máy vẫn còn), nên không dọn thì cài lại là quyền cũ tự có hiệu lực mà không ai hỏi lại.
72
+ */
73
+ export function clearWorkFolderState({ attachDir = MASCOT_ATTACH_DIR, settingsFile = MASCOT_SETTINGS_FILE } = {}) {
74
+ fs.rmSync(attachDir, { recursive: true, force: true });
75
+ if (loadMascotSettings(settingsFile).work_dir) {
76
+ try { saveMascotSettings({ work_dir: null }, settingsFile); } catch { /* mascot.json hỏng: lần khởi động vẫn kiểm lại quyền trước khi khôi phục */ }
77
+ }
78
+ const creds = loadDeviceCredentials();
79
+ if (!creds?.extra_roots) return;
80
+ const granted = creds.extra_roots.map((p) => path.resolve(p));
81
+ delete creds.extra_roots;
82
+ creds.roots = (creds.roots || []).filter((p) => !granted.includes(path.resolve(p)));
83
+ saveDeviceCredentials(creds);
84
+ const running = lockHolder();
85
+ if (running) try { process.kill(running); } catch { /* vừa tự thoát */ }
86
+ }
87
+
88
+ /** `aivin remote forget-folder`: thu lại thư mục đã đồng ý, dừng daemon để khay mở lại với danh sách mới. Trả `{ removed, stopped }`. */
89
+ export function forgetWorkFolder(dir) {
90
+ const creds = loadDeviceCredentials();
91
+ const abs = path.resolve(String(dir));
92
+ const same = (p) => path.resolve(p) === abs;
93
+ if (!creds?.extra_roots?.some(same)) return { removed: false, stopped: null };
94
+ creds.extra_roots = creds.extra_roots.filter((p) => !same(p));
95
+ creds.roots = (creds.roots || []).filter((p) => !same(p));
96
+ saveDeviceCredentials(creds);
97
+ const stopped = lockHolder();
98
+ if (stopped) try { process.kill(stopped); } catch { /* vừa tự thoát */ }
99
+ return { removed: true, stopped };
100
+ }
package/docs/CLI.md CHANGED
@@ -1289,8 +1289,39 @@ aivin desktop # status
1289
1289
  `HKCU\Software` is written (no admin). Windows doesn't let apps make themselves the default, so to open those files with a double-click
1290
1290
  either pick Open with → AIVIN Bot → "Always", or run `aivin desktop defaults` to go straight to AIVIN Bot's page in Settings → Default
1291
1291
  apps. For a whole company, `aivin desktop defaults --export-xml <file> [--all]` writes a file IT can push with the Group Policy "Set a
1292
- default associations configuration file" or Intune (`md txt csv` by default, `--all` adds Office formats). Installed before this
1293
- version? Run `aivin desktop install` again.
1292
+ default associations configuration file" or Intune (`md txt csv` by default, `--all` adds Office formats).
1293
+ - **Share with AIVIN Bot** (Windows): right-click any file or folder (one or many) → "Share with AIVIN Bot", or Send to → AIVIN Bot.
1294
+ The items are attached to the bot's chat box on screen, the same as dropping them on the mascot (see [`aivin share`](#aivin-share-paths)).
1295
+ - **Work here with AIVIN Bot** (Windows): right-click the empty space inside a folder, or the folder itself. The folder becomes the bot's
1296
+ working folder: a chip above the chat box shows it, every question you type goes out with it, and it stays across restarts until you
1297
+ click × on the chip. If the folder is outside the folders Aivin may use, a dialog on this computer asks first; once you allow it, Aivin can
1298
+ read, write and run commands there. Take that back with `aivin remote forget-folder <path>`. Network folders can't be used. Live voice
1299
+ conversations don't use the working folder.
1300
+ - Machines that installed Aivin earlier and only auto-update get all these menu items without reinstalling: each time `aivin remote start`
1301
+ starts, it rebuilds `Aivin.exe` if its code changed, rewrites the registry entries if they changed or were removed, and adds the
1302
+ Send to shortcut if it's missing.
1303
+
1304
+ ## `aivin uninstall` (Windows)
1305
+
1306
+ Removes Aivin from this computer: the app and everything `aivin desktop uninstall` removes, the `aivin` command and its PATH entry, and this
1307
+ computer's connection to your account (device token, sign-in key). `aivin desktop install` also adds **AIVIN Bot** to Programs & Features and
1308
+ Settings → Apps, and uninstalling there does the same thing after asking whether to delete your data.
1309
+
1310
+ ```bash
1311
+ aivin uninstall # asks first
1312
+ aivin uninstall --yes # keeps your data in .aivin
1313
+ aivin uninstall --yes --delete-data
1314
+ ```
1315
+
1316
+ Your data in `.aivin` (the bot's memory, file copies kept for undo, browser sign-ins, logs) stays unless you choose to delete it; deleting cannot
1317
+ be undone. If you weren't signed in on this computer or the server can't be reached, the computer stays listed on your account as offline, with no
1318
+ token left here; revoke it in Aivin if you want it gone. An install from npm keeps the command: run `npm rm -g @aivin-labs/cli`.
1319
+
1320
+ ## `aivin share <paths...>`
1321
+
1322
+ Attaches files or folders to the AIVIN Bot chat box on this computer, the same as dropping them on the mascot. Type your question and
1323
+ they go with it (up to 10 items). This needs `aivin remote start` running, and requests older than 2 minutes are dropped. On Windows,
1324
+ right-click → "Share with AIVIN Bot" does the same thing and also starts the tray app if it isn't running.
1294
1325
 
1295
1326
  ## `aivin open <files...>`
1296
1327
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aivin-labs/cli",
3
- "version": "1.0.24",
3
+ "version": "1.0.27",
4
4
  "description": "aivin CLI - scaffold, run, and deploy Aivin plugins built on @aivin-labs/sdk",
5
5
  "type": "module",
6
6
  "bin": {