@aivin-labs/cli 1.0.8 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +25 -0
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +1912 -1780
  4. package/bin/lib/browserAutomation.mjs +232 -469
  5. package/bin/lib/localBrowser.mjs +345 -0
  6. package/bin/lib/remote/activityLog.mjs +1 -1
  7. package/bin/lib/remote/autoStart.mjs +174 -14
  8. package/bin/lib/remote/browserTunnel.mjs +142 -31
  9. package/bin/lib/remote/callLedger.mjs +1 -1
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -1
  11. package/bin/lib/remote/client.mjs +87 -5
  12. package/bin/lib/remote/clipboard.mjs +138 -0
  13. package/bin/lib/remote/codingAgents.mjs +293 -0
  14. package/bin/lib/remote/constants.mjs +61 -0
  15. package/bin/lib/remote/dailyBrowser.mjs +1 -1
  16. package/bin/lib/remote/desktop/index.mjs +272 -0
  17. package/bin/lib/remote/desktop/linux.mjs +144 -0
  18. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
  19. package/bin/lib/remote/desktop/mac.mjs +187 -0
  20. package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
  21. package/bin/lib/remote/desktop/strings.mjs +74 -0
  22. package/bin/lib/remote/desktop/traySource.mjs +527 -0
  23. package/bin/lib/remote/docText.mjs +1 -1
  24. package/bin/lib/remote/fileIndexer.mjs +1 -1
  25. package/bin/lib/remote/gui/index.mjs +93 -12
  26. package/bin/lib/remote/gui/windowsHostSource.mjs +280 -28
  27. package/bin/lib/remote/idempotency.mjs +1 -1
  28. package/bin/lib/remote/localPolicy.mjs +9 -2
  29. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  30. package/bin/lib/remote/mascot/ask.mjs +768 -0
  31. package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
  32. package/bin/lib/remote/mascot/assets.mjs +825 -216
  33. package/bin/lib/remote/mascot/bot.mjs +372 -0
  34. package/bin/lib/remote/mascot/hostSource.mjs +498 -101
  35. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  36. package/bin/lib/remote/mascot/index.mjs +199 -28
  37. package/bin/lib/remote/mascot/labels.mjs +2 -3
  38. package/bin/lib/remote/mascot/rigSource.mjs +609 -0
  39. package/bin/lib/remote/mascot/strings.mjs +204 -18
  40. package/bin/lib/remote/mascot/ui.mjs +104 -0
  41. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  42. package/bin/lib/remote/meeting/index.mjs +415 -0
  43. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  44. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  45. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  46. package/bin/lib/remote/tabGroups.mjs +209 -0
  47. package/bin/lib/remote/toolHandlers.mjs +15 -0
  48. package/docs/AIVIN_MASCOT.md +116 -0
  49. package/docs/CLI.md +142 -11
  50. package/docs/media/aivin-mascot-states.mp4 +0 -0
  51. package/package.json +1 -1
@@ -0,0 +1,66 @@
1
+ import { spawnSync } from 'child_process';
2
+
3
+ /**
4
+ * Phím tắt gọi linh vật (29/10/2026): một tổ hợp toàn hệ thống (`RegisterHotKey`, không móc bàn phím) — bấm → mở ô hỏi + nghe luôn. Mặc định
5
+ * thử lần lượt `DEFAULT_HOTKEYS`, lấy tổ hợp đầu tiên đăng ký được (mỗi máy cài app khác nhau: máy dev 29/10 có Ctrl+Alt+Space,
6
+ * Ctrl+Win+Space, Win+Shift+Space đều đã bị giữ — lỗi 1409). Chủ máy đặt riêng: `aivin remote mascot hotkey <tổ hợp> | off` (mascot.json).
7
+ */
8
+
9
+ export const HOTKEY_MODS = Object.freeze({ alt: 0x1, ctrl: 0x2, shift: 0x4, win: 0x8 });
10
+ export const MOD_NOREPEAT = 0x4000;
11
+ export const DEFAULT_HOTKEYS = Object.freeze(['Win+Alt+Space', 'Ctrl+Shift+Alt+Space', 'Ctrl+Shift+Alt+A']);
12
+
13
+ const MOD_ALIASES = { alt: 'alt', option: 'alt', ctrl: 'ctrl', control: 'ctrl', shift: 'shift', win: 'win', windows: 'win', super: 'win', meta: 'win', cmd: 'win' };
14
+ const NAMED_KEYS = { space: 0x20, enter: 0x0d, tab: 0x09, esc: 0x1b, escape: 0x1b, backspace: 0x08, insert: 0x2d, delete: 0x2e, home: 0x24, end: 0x23, pageup: 0x21, pagedown: 0x22, '`': 0xc0, '/': 0xbf, '.': 0xbe, ',': 0xbc, ';': 0xba };
15
+ const MOD_ORDER = ['win', 'ctrl', 'shift', 'alt'];
16
+
17
+ function keyCode(name) {
18
+ const k = name.toLowerCase();
19
+ if (NAMED_KEYS[k] !== undefined) return { vk: NAMED_KEYS[k], label: k.length === 1 ? k : k[0].toUpperCase() + k.slice(1) };
20
+ if (/^[a-z0-9]$/.test(k)) return { vk: k.toUpperCase().charCodeAt(0), label: k.toUpperCase() };
21
+ const f = /^f([1-9]|1\d|2[0-4])$/.exec(k);
22
+ if (f) return { vk: 0x6f + Number(f[1]), label: `F${f[1]}` };
23
+ return null;
24
+ }
25
+
26
+ /** "win+alt+space" → `{ mods, vk, label: 'Win+Alt+Space' }`; sai → ném Error có lý do. Phải có Ctrl / Alt / Win (Shift + phím = gõ chữ hoa). */
27
+ export function parseHotkey(text) {
28
+ const parts = String(text || '').split('+').map((p) => p.trim()).filter(Boolean);
29
+ if (parts.length < 2) throw new Error(`"${text}" is not a key combination — e.g. Win+Alt+Space`);
30
+ const mods = new Set();
31
+ for (const p of parts.slice(0, -1)) {
32
+ const m = MOD_ALIASES[p.toLowerCase()];
33
+ if (!m) throw new Error(`Unknown modifier "${p}" — use Ctrl, Alt, Shift, Win`);
34
+ mods.add(m);
35
+ }
36
+ if (!mods.has('ctrl') && !mods.has('alt') && !mods.has('win')) throw new Error('Use at least one of Ctrl, Alt or Win');
37
+ const key = keyCode(parts.at(-1));
38
+ if (!key) throw new Error(`Unknown key "${parts.at(-1)}" — use a letter, digit, F1–F24, Space…`);
39
+ const ordered = MOD_ORDER.filter((m) => mods.has(m));
40
+ return {
41
+ mods: ordered.reduce((acc, m) => acc | HOTKEY_MODS[m], 0),
42
+ vk: key.vk,
43
+ label: [...ordered.map((m) => m[0].toUpperCase() + m.slice(1)), key.label].join('+'),
44
+ };
45
+ }
46
+
47
+ /** Thứ tự thử: tổ hợp chủ máy đặt (nếu có) rồi mặc định; `off` → không có. */
48
+ export function hotkeyCandidates(setting) {
49
+ if (setting === 'off' || setting === false) return [];
50
+ const list = setting ? [setting, ...DEFAULT_HOTKEYS] : [...DEFAULT_HOTKEYS];
51
+ const seen = new Set();
52
+ return list.map((h) => { try { return parseHotkey(h); } catch { return null; } }).filter((h) => h && !seen.has(h.label) && seen.add(h.label));
53
+ }
54
+
55
+ /**
56
+ * Tổ hợp có đăng ký được trên máy này ngay lúc này không (đăng ký thử rồi trả lại). Chỉ Windows; nơi khác → null (không biết).
57
+ * Lúc linh vật đang chạy thì tổ hợp nó đang giữ báo "bị giữ" — chính nó giữ.
58
+ */
59
+ export function probeHotkey(hotkey, { platform = process.platform, run = spawnSync } = {}) {
60
+ if (platform !== 'win32') return null;
61
+ const script = 'Add-Type -Namespace AivinHk -Name N -MemberDefinition \'[DllImport("user32.dll", SetLastError=true)] public static extern bool RegisterHotKey(IntPtr h,int id,uint m,uint vk); [DllImport("user32.dll")] public static extern bool UnregisterHotKey(IntPtr h,int id);\'; '
62
+ + `$ok = [AivinHk.N]::RegisterHotKey([IntPtr]::Zero, 7, ${hotkey.mods | MOD_NOREPEAT}, ${hotkey.vk}); if ($ok) { [void][AivinHk.N]::UnregisterHotKey([IntPtr]::Zero, 7); 'free' } else { 'taken' }`;
63
+ const res = run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8', windowsHide: true, timeout: 15000 });
64
+ const out = String(res.stdout || '').trim();
65
+ return out === 'free' ? true : out === 'taken' ? false : null;
66
+ }
@@ -3,10 +3,14 @@ import path from 'path';
3
3
  import readline from 'readline';
4
4
  import { createHash } from 'crypto';
5
5
  import { spawn } from 'child_process';
6
- import { REMOTE_CONFIG_DIR, ToolGroup } from '../constants.mjs';
6
+ import { NotifyKind, REMOTE_CONFIG_DIR, ToolGroup } from '../constants.mjs';
7
7
  import { AIVIN_LOGO_PNG_BASE64 } from '../brand.mjs';
8
- import { MASCOT_PNG_BASE64 } from './assets.mjs';
8
+ import { MASCOT_LAYERS } from './assets.mjs';
9
9
  import { MASCOT_GLYPHS, MASCOT_PALETTE, MASCOT_PS1, MASCOT_XAML } from './hostSource.mjs';
10
+ import { ASK_PS1 } from './askHostSource.mjs';
11
+ import { AskCommand, MAX_ATTACH, QUESTION_ROW } from './ask.mjs';
12
+
13
+ const ASK_HOOK = '# @ASK_HOOK';
10
14
  import { describeStep } from './labels.mjs';
11
15
  import { MascotText, mascotLang, mascotText, windowStrings } from './strings.mjs';
12
16
 
@@ -28,14 +32,32 @@ export const MascotState = Object.freeze({
28
32
  });
29
33
  export const LogStatus = Object.freeze({ RUN: 'run', OK: 'ok', FAIL: 'fail', INFO: 'info', WARN: 'warn' });
30
34
  /** Lệnh gửi cửa sổ / sự kiện cửa sổ gửi về (một dòng JSON mỗi lệnh). */
31
- export const HostCommand = Object.freeze({ STATE: 'state', MAIN: 'main', LOG: 'log', GUI: 'gui', SHOW: 'show', QUIT: 'quit' });
32
- export const HostEvent = Object.freeze({ READY: 'ready', POS: 'pos', PAUSE: 'pause', RESUME: 'resume', HIDE: 'hide', OFF: 'off' });
35
+ export const HostCommand = Object.freeze({ STATE: 'state', MAIN: 'main', LOG: 'log', GUI: 'gui', SHOW: 'show', QUIT: 'quit', OPEN_ASK: 'open_ask', GESTURE: 'gesture' });
36
+
37
+ /** `aivin ui` (terminal khác) chạm tệp này → daemon đang chạy hiện linh vật + mở ô hỏi (mascot/ui.mjs). */
38
+ export const MASCOT_SHOW_FILE = path.join(REMOTE_CONFIG_DIR, 'mascot-show');
39
+ const SHOW_POLL_MS = 1000;
40
+ const SHOW_REQUEST_GRACE_MS = 30_000;
41
+
42
+ /** Ghi yêu cầu hiện linh vật cho daemon đang chạy (hoặc sắp chạy). */
43
+ export function requestMascotShow(file = MASCOT_SHOW_FILE) {
44
+ fs.mkdirSync(path.dirname(file), { recursive: true });
45
+ fs.writeFileSync(file, String(Date.now()));
46
+ }
47
+ export const HostEvent = Object.freeze({
48
+ READY: 'ready', POS: 'pos', PAUSE: 'pause', RESUME: 'resume', HIDE: 'hide', OFF: 'off', ASK: 'ask', CHOOSE: 'choose', CANCEL: 'cancel', NEW_CHAT: 'new_chat',
49
+ DROP: 'drop', AWAY: 'away', BACK: 'back',
50
+ VOICE_START: 'voice_start', VOICE_AUDIO: 'voice_audio', VOICE_INTERRUPT: 'voice_interrupt', VOICE_STOP: 'voice_stop', VOICE_MIC_LOST: 'voice_mic_lost',
51
+ });
52
+ const VOICE_EVENTS = new Set([HostEvent.VOICE_START, HostEvent.VOICE_AUDIO, HostEvent.VOICE_INTERRUPT, HostEvent.VOICE_STOP, HostEvent.VOICE_MIC_LOST]);
33
53
 
34
54
  const THINK_MS = 8000;
35
55
  const RESULT_MS = 6000;
36
56
  const MAIN_THROTTLE_MS = 600;
37
57
  const RESTART_DELAYS_MS = [5000, 30_000, 120_000];
38
58
  const QUEUE_LOGS = 40;
59
+ /** Vắng lâu chừng này mà không có việc gì xảy ra → quay lại vẫn được vẫy chào (không bong bóng). */
60
+ const AWAY_WAVE_MS = 30 * 60_000;
39
61
 
40
62
  export function loadMascotSettings(file = MASCOT_SETTINGS_FILE) {
41
63
  try {
@@ -54,17 +76,25 @@ export function saveMascotSettings(patch, file = MASCOT_SETTINGS_FILE) {
54
76
  return next;
55
77
  }
56
78
 
79
+ /** host.ps1 = mã cửa sổ + ô hỏi (askHostSource.mjs) chèn tại dấu `# @ASK_HOOK`; thiếu dấu thì ô hỏi không có, cửa sổ vẫn chạy. */
80
+ export function hostScript() {
81
+ return MASCOT_PS1.includes(ASK_HOOK) ? MASCOT_PS1.replace(ASK_HOOK, ASK_PS1) : MASCOT_PS1;
82
+ }
83
+
57
84
  /** Tệp của cửa sổ: mã + ảnh theo dấu vân tay (đổi bản CLI → bộ mới, dọn bộ cũ); config.json (vị trí, chữ, màu) ghi mỗi lần mở. */
58
- function writeHostFiles({ dir, lang, settings }) {
59
- const hash = createHash('sha256').update(MASCOT_PS1).update(MASCOT_XAML).update(MASCOT_PNG_BASE64).digest('hex').slice(0, 12);
85
+ export function writeHostFiles({ dir, lang, settings }) {
86
+ const hostPs1 = hostScript();
87
+ const sha = createHash('sha256').update(hostPs1).update(MASCOT_XAML);
88
+ for (const body of Object.values(MASCOT_LAYERS)) sha.update(body);
89
+ const hash = sha.digest('hex').slice(0, 12);
60
90
  const home = path.join(dir, hash);
61
91
  fs.mkdirSync(home, { recursive: true });
62
- const files = { 'host.ps1': MASCOT_PS1, 'mascot.xaml': MASCOT_XAML };
92
+ const files = { 'host.ps1': hostPs1, 'mascot.xaml': MASCOT_XAML };
63
93
  for (const [name, body] of Object.entries(files)) if (!fs.existsSync(path.join(home, name))) fs.writeFileSync(path.join(home, name), body);
64
- if (!fs.existsSync(path.join(home, 'mascot.png'))) fs.writeFileSync(path.join(home, 'mascot.png'), Buffer.from(MASCOT_PNG_BASE64, 'base64'));
94
+ for (const [name, body] of Object.entries(MASCOT_LAYERS)) if (!fs.existsSync(path.join(home, name))) fs.writeFileSync(path.join(home, name), Buffer.from(body, 'base64'));
65
95
  if (!fs.existsSync(path.join(home, 'logo.png'))) fs.writeFileSync(path.join(home, 'logo.png'), Buffer.from(AIVIN_LOGO_PNG_BASE64, 'base64'));
66
96
  fs.writeFileSync(path.join(home, 'config.json'), JSON.stringify({
67
- strings: windowStrings(lang), palette: MASCOT_PALETTE, glyphs: MASCOT_GLYPHS, x: settings.x ?? null, y: settings.y ?? null,
97
+ strings: windowStrings(lang), palette: MASCOT_PALETTE, glyphs: MASCOT_GLYPHS, x: settings.x ?? null, y: settings.y ?? null, max_files: MAX_ATTACH,
68
98
  }));
69
99
  for (const name of fs.readdirSync(dir)) {
70
100
  if (name !== hash && /^[0-9a-f]{12}$/.test(name)) fs.rmSync(path.join(dir, name), { recursive: true, force: true });
@@ -73,27 +103,42 @@ function writeHostFiles({ dir, lang, settings }) {
73
103
  }
74
104
 
75
105
  const NOOP = Object.freeze({
76
- connected() {}, disconnected() {}, paused() {}, callStarted() {}, callFinished() {}, waitingConfirm() {}, confirmDone() {}, close() {}, enabled: false,
106
+ connected() {}, disconnected() {}, paused() {}, callStarted() {}, callFinished() {}, waitingConfirm() {}, confirmDone() {}, chat() {}, close() {},
107
+ alert() {}, needsYou() {}, openAsk() {}, pid: () => null, enabled: false,
77
108
  });
78
109
 
79
110
  const hhmmss = (t) => new Date(t).toTimeString().slice(0, 8);
80
111
 
112
+ /** Cửa sổ chủ máy đang dùng khi hỏi bot (cửa sổ linh vật gửi kèm `ask` / `voice_start`): `{ window: '0x..', title, process }` hoặc null. */
113
+ export function userWindow(w) {
114
+ if (!w || typeof w !== 'object' || typeof w.window !== 'string' || !/^0x[0-9a-f]{1,16}$/.test(w.window)) return null;
115
+ const text = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '');
116
+ return { window: w.window, title: text(w.title, 200), process: text(w.process, 64) };
117
+ }
118
+
81
119
  /**
82
- * `onPause` / `onResume`: nút trên bảng nhật ký bật / tắt công tắc ngắt (như `aivin remote pause|resume`). `spawnImpl`, `timers`, `now`,
83
- * `dir`, `settingsFile`, các mốc `*Ms`: cho test.
120
+ * `onPause` / `onResume`: nút trên bảng nhật ký bật / tắt công tắc ngắt (như `aivin remote pause|resume`). `onVoice(msg)`: sự kiện nói
121
+ * chuyện của cửa sổ (`voice_*`, xem ask.mjs); cửa sổ chết giữa chừng → `voice_stop`. `onChoose(id | ids)`: bấm nút trả lời câu Aivin hỏi (câu chọn nhiều: mảng id đã tích).
122
+ * `onCancel()`: bấm nút dừng lượt chat đang chạy. `onNewChat()`: nút "Phiên chat mới" trên bảng nhật ký.
123
+ * `onAsk(text, window)`: câu gõ trong ô hỏi + cửa sổ chủ máy đang dùng (`userWindow`). `pid()`: tiến trình của cửa sổ linh vật (null khi
124
+ * chưa chạy). `spawnImpl`, `timers`, `now`, `dir`, `settingsFile`, các mốc `*Ms`: cho test.
84
125
  */
85
126
  export function createMascot({
86
127
  enabled = true, platform = process.platform, env = process.env, onPause = () => {}, onResume = () => {}, say = () => {},
87
- spawnImpl = spawn, dir = MASCOT_DIR, settingsFile = MASCOT_SETTINGS_FILE, now = Date.now, timers = { setTimeout, clearTimeout },
88
- thinkMs = THINK_MS, resultMs = RESULT_MS, mainThrottleMs = MAIN_THROTTLE_MS, restartDelaysMs = RESTART_DELAYS_MS,
128
+ onAsk = () => {}, onVoice = () => {}, onChoose = () => {}, onCancel = () => {}, onNewChat = () => {}, onDrop = () => {},
129
+ spawnImpl = spawn, dir = MASCOT_DIR, settingsFile = MASCOT_SETTINGS_FILE, showFile = MASCOT_SHOW_FILE, now = Date.now, timers = { setTimeout, clearTimeout },
130
+ thinkMs = THINK_MS, resultMs = RESULT_MS, mainThrottleMs = MAIN_THROTTLE_MS, restartDelaysMs = RESTART_DELAYS_MS, awayWaveMs = AWAY_WAVE_MS,
89
131
  } = {}) {
90
- if (!enabled || platform !== 'win32' || !loadMascotSettings(settingsFile).enabled) return NOOP;
132
+ if (!enabled || platform !== 'win32') return NOOP;
91
133
  const lang = mascotLang(env);
92
134
  const t = (key, vars) => mascotText(lang, key, vars);
93
135
 
94
136
  let child = null;
95
137
  let ready = false;
96
138
  let closed = false;
139
+ // Linh vật đang tắt (`aivin remote mascot off` / nút "Tắt linh vật"): không mở cửa sổ, chỉ chờ `aivin ui` đánh thức.
140
+ let dormant = !loadMascotSettings(settingsFile).enabled;
141
+ let openAskOnReady = false;
97
142
  let restarts = 0;
98
143
  let restartTimer = null;
99
144
  const pending = [];
@@ -103,9 +148,19 @@ export function createMascot({
103
148
  const write = (msg) => {
104
149
  try { child?.stdin?.write(`${JSON.stringify(msg)}\n`); } catch { /* cửa sổ vừa chết — lần dựng lại gửi trạng thái mới nhất */ }
105
150
  };
151
+ // Câu hỏi đang chờ (dòng câu hỏi + nút + ghim ô hỏi): cửa sổ dựng lại / chưa sẵn sàng vẫn hiện lại đúng câu hỏi để trả lời.
152
+ let lastQuestion = null;
153
+ let lastChoices = null;
154
+ let lastPin = null;
155
+ // Tệp thả vào bot đang chờ: cửa sổ dựng lại vẫn ôm thùng có số tệp.
156
+ let lastFiles = null;
106
157
  const send = (msg) => {
107
158
  if (msg.t === HostCommand.STATE) lastState = msg;
108
159
  if (msg.t === HostCommand.MAIN) lastMain = msg;
160
+ if (msg.t === AskCommand.CHAT && String(msg.id || '').startsWith(QUESTION_ROW)) lastQuestion = msg;
161
+ if (msg.t === AskCommand.CHOICES) lastChoices = msg;
162
+ if (msg.t === AskCommand.PIN) lastPin = msg;
163
+ if (msg.t === AskCommand.FILES) lastFiles = msg;
109
164
  if (ready) return write(msg);
110
165
  if (msg.t === HostCommand.LOG) {
111
166
  pending.push(msg);
@@ -117,6 +172,13 @@ export function createMascot({
117
172
  if (lastState) write(lastState);
118
173
  if (lastMain) write({ ...lastMain, quiet: true });
119
174
  if (guiActive > 0) write({ t: HostCommand.GUI, active: true });
175
+ if (lastPin?.on) {
176
+ if (lastQuestion) write(lastQuestion);
177
+ if (lastChoices) write(lastChoices);
178
+ write(lastPin);
179
+ }
180
+ if (lastFiles?.n) write(lastFiles);
181
+ if (openAskOnReady) { openAskOnReady = false; write({ t: HostCommand.OPEN_ASK }); }
120
182
  };
121
183
 
122
184
  const onEvent = (msg) => {
@@ -128,15 +190,74 @@ export function createMascot({
128
190
  if (msg.t === HostEvent.PAUSE) return onPause();
129
191
  if (msg.t === HostEvent.RESUME) return onResume();
130
192
  if (msg.t === HostEvent.HIDE) { hiddenUntilWork = true; return; }
193
+ // Ô hỏi: chủ máy gõ / nói với bot → daemon gửi lên Aivin (ask.mjs).
194
+ if (msg.t === HostEvent.ASK && typeof msg.text === 'string') return onAsk(msg.text, userWindow(msg.window));
195
+ if (msg.t === HostEvent.CHOOSE) {
196
+ // Câu chọn nhiều: `ids` = các mục đã tích; chọn một: `id`.
197
+ if (Array.isArray(msg.ids) && msg.ids.length && msg.ids.every((x) => typeof x === 'string')) return onChoose(msg.ids);
198
+ if (typeof msg.id === 'string') return onChoose(msg.id);
199
+ }
200
+ // Nút dừng (nút mic khi đang chờ lượt chat): dừng lượt đang chạy.
201
+ if (msg.t === HostEvent.CANCEL) return onCancel();
202
+ // Nút "Chat mới" trên bảng: phiên chat mới cho linh vật.
203
+ if (msg.t === HostEvent.NEW_CHAT) return onNewChat();
204
+ if (msg.t === HostEvent.DROP && Array.isArray(msg.files)) return onDrop(msg.files.filter((f) => typeof f === 'string' && f));
205
+ if (msg.t === HostEvent.AWAY) { away = { since: now(), done: 0, failed: 0, needs: 0 }; return; }
206
+ if (msg.t === HostEvent.BACK) return welcomeBack();
207
+ if (msg.t === HostEvent.VOICE_START) return onVoice({ t: msg.t, window: userWindow(msg.window) });
208
+ if (VOICE_EVENTS.has(msg.t)) return onVoice(msg);
131
209
  if (msg.t === HostEvent.OFF) {
132
210
  try { saveMascotSettings({ enabled: false }, settingsFile); } catch { /* tắt trong phiên này vẫn được */ }
133
211
  say(t(MascotText.TURNED_OFF));
134
- close();
212
+ sleep();
135
213
  }
136
214
  };
137
215
 
216
+ /** Tắt cửa sổ nhưng daemon vẫn giữ trạng thái — `aivin ui` đánh thức lại được. */
217
+ function sleep() {
218
+ dormant = true;
219
+ timers.clearTimeout(restartTimer);
220
+ quitHost();
221
+ }
222
+
223
+ function quitHost() {
224
+ const c = child;
225
+ if (!c) return;
226
+ write({ t: HostCommand.QUIT });
227
+ try { c.stdin?.end(); } catch { /* đã đóng */ }
228
+ const kill = timers.setTimeout(() => { try { c.kill(); } catch { /* đã thoát */ } }, 1500);
229
+ kill?.unref?.();
230
+ }
231
+
232
+ /** `aivin ui`: bật lại nếu đang tắt, hiện linh vật (kể cả đang "ẩn tới khi có việc"), mở ô hỏi để gõ ngay. */
233
+ function wake() {
234
+ if (closed) return;
235
+ hiddenUntilWork = false;
236
+ if (dormant || !child) {
237
+ dormant = false;
238
+ restarts = 0;
239
+ openAskOnReady = true;
240
+ return start();
241
+ }
242
+ if (!ready) { openAskOnReady = true; return; }
243
+ write({ t: HostCommand.SHOW });
244
+ write({ t: HostCommand.OPEN_ASK });
245
+ }
246
+
247
+ // Yêu cầu từ lệnh `aivin ui` (cửa sổ terminal khác): tệp đánh dấu đổi giờ sửa → đánh thức. Tính cả yêu cầu vừa ghi ngay trước khi daemon
248
+ // này khởi động (`aivin ui` tự bật daemon rồi mới chờ).
249
+ let showSeenAt = now() - SHOW_REQUEST_GRACE_MS;
250
+ const showWatch = setInterval(() => {
251
+ let at;
252
+ try { at = fs.statSync(showFile).mtimeMs; } catch { return; }
253
+ if (at <= showSeenAt) return;
254
+ showSeenAt = at;
255
+ wake();
256
+ }, SHOW_POLL_MS);
257
+ showWatch.unref?.();
258
+
138
259
  function start() {
139
- if (closed || child) return;
260
+ if (closed || dormant || child) return;
140
261
  let home;
141
262
  try {
142
263
  home = writeHostFiles({ dir, lang, settings: loadMascotSettings(settingsFile) });
@@ -162,7 +283,8 @@ export function createMascot({
162
283
  c.on('error', () => { /* xử lý ở close */ });
163
284
  c.on('close', () => {
164
285
  if (child === c) { child = null; ready = false; }
165
- if (closed) return;
286
+ onVoice({ t: HostEvent.VOICE_STOP });
287
+ if (closed || dormant) return;
166
288
  // Không có màn hình (phiên dịch vụ), WPF hỏng… → thử lại giãn dần, quá số lần thì thôi (daemon vẫn chạy bình thường).
167
289
  const delay = restartDelaysMs[restarts++];
168
290
  if (delay === undefined) { say(`(mascot: ${stderr.trim().split(/\r?\n/).pop() || 'window could not start'})`); return; }
@@ -173,16 +295,12 @@ export function createMascot({
173
295
  function close() {
174
296
  if (closed) return;
175
297
  closed = true;
298
+ clearInterval(showWatch);
176
299
  timers.clearTimeout(restartTimer);
177
300
  timers.clearTimeout(thinkTimer);
178
301
  timers.clearTimeout(resultTimer);
179
302
  timers.clearTimeout(mainTimer);
180
- const c = child;
181
- if (!c) return;
182
- write({ t: HostCommand.QUIT });
183
- try { c.stdin?.end(); } catch { /* đã đóng */ }
184
- const kill = timers.setTimeout(() => { try { c.kill(); } catch { /* đã thoát */ } }, 1500);
185
- kill?.unref?.();
303
+ quitHost();
186
304
  }
187
305
 
188
306
  // --- Trạng thái ---------------------------------------------------------------------------------------------------------------------
@@ -197,11 +315,31 @@ export function createMascot({
197
315
  let thinkTimer = null;
198
316
  let resultTimer = null;
199
317
  let hiddenUntilWork = false;
318
+ /** Aivin đang hỏi chủ máy (câu hỏi chờ trả lời trong ô hỏi) — như chờ xác nhận: "!" tới khi trả lời. */
319
+ let askingYou = false;
320
+ /** Chủ máy đi vắng (cửa sổ báo không chạm chuột / phím một lúc): mốc + đếm việc xảy ra trong lúc đó, hoặc null. */
321
+ let away = null;
322
+
323
+ /** Quay lại sau khi vắng: có việc xảy ra → vẫy chào + bong bóng tóm tắt; vắng lâu mà không có gì → chỉ vẫy chào. */
324
+ function welcomeBack() {
325
+ const was = away;
326
+ away = null;
327
+ if (!was) return;
328
+ const parts = [
329
+ was.done && t(MascotText.AWAY_DONE, { n: was.done }),
330
+ was.failed && t(MascotText.AWAY_FAILED, { n: was.failed }),
331
+ was.needs && t(MascotText.AWAY_NEEDS, { n: was.needs }),
332
+ ].filter(Boolean);
333
+ if (!parts.length && now() - was.since < awayWaveMs) return;
334
+ if (hiddenUntilWork) { hiddenUntilWork = false; send({ t: HostCommand.SHOW }); }
335
+ send({ t: HostCommand.GESTURE, g: 'wave' });
336
+ if (parts.length) main(t(MascotText.AWAY_SUMMARY, { parts: parts.join(', ') }));
337
+ }
200
338
 
201
339
  const current = () => {
202
340
  if (paused) return MascotState.PAUSED;
203
341
  if (offline) return MascotState.OFFLINE;
204
- if (waiting.size) return MascotState.WAITING;
342
+ if (waiting.size || askingYou) return MascotState.WAITING;
205
343
  if (active.size) return MascotState.WORKING;
206
344
  return phase;
207
345
  };
@@ -253,15 +391,17 @@ export function createMascot({
253
391
 
254
392
  start();
255
393
 
256
- let everConnected = false;
257
394
  return {
258
395
  enabled: true,
396
+ lang,
397
+ /** Lệnh của ô hỏi (ask.mjs: chat / chat_busy / ask_status) → cửa sổ. */
398
+ chat(cmd) { send(cmd); },
259
399
  connected() {
260
400
  offline = false;
261
401
  syncState();
262
402
  log({ status: LogStatus.INFO, title: t(MascotText.CONNECTED) });
263
- if (!everConnected) main(t(MascotText.READY));
264
- everConnected = true;
403
+ // Không bật bong bóng khi vừa nối (người dùng thấy thừa) — chỉ đặt lại mục "Đang làm" của bảng nhật ký.
404
+ send({ t: HostCommand.MAIN, text: t(MascotText.READY), quiet: true });
265
405
  },
266
406
  disconnected() {
267
407
  if (offline) return;
@@ -317,6 +457,37 @@ export function createMascot({
317
457
  syncState();
318
458
  if (!allowed) settle();
319
459
  },
460
+ /**
461
+ * Báo chủ động / câu trả lời của ô hỏi (ask.mjs `onAlert`): bong bóng ngắn + nét mặt — xong (nhảy, lấp lánh) / lỗi (lắc đầu) rồi về
462
+ * chờ việc; cần bạn thì trạng thái do `needsYou` giữ. Đang có bước chạy trên máy thì chỉ hiện bong bóng, không đổi trạng thái.
463
+ */
464
+ alert({ kind, text } = {}) {
465
+ if (!text) return;
466
+ if (hiddenUntilWork) { hiddenUntilWork = false; send({ t: HostCommand.SHOW }); }
467
+ const failed = kind === NotifyKind.FAILED;
468
+ if (away) away[failed ? 'failed' : kind === NotifyKind.NEEDS_YOU ? 'needs' : 'done']++;
469
+ log({ status: failed ? LogStatus.FAIL : kind === NotifyKind.NEEDS_YOU ? LogStatus.WARN : LogStatus.OK, title: text });
470
+ main(text);
471
+ if (kind === NotifyKind.NEEDS_YOU || active.size || waiting.size) return;
472
+ timers.clearTimeout(thinkTimer);
473
+ timers.clearTimeout(resultTimer);
474
+ phase = failed ? MascotState.ERROR : MascotState.DONE;
475
+ syncState();
476
+ resultTimer = timers.setTimeout(() => {
477
+ phase = MascotState.IDLE;
478
+ syncState();
479
+ send({ t: HostCommand.MAIN, text: t(MascotText.READY), quiet: true });
480
+ }, resultMs);
481
+ },
482
+ /** Có / hết câu hỏi Aivin đang chờ chủ máy trả lời (ask.mjs `onPending`). */
483
+ needsYou(on) {
484
+ if (askingYou === !!on) return;
485
+ askingYou = !!on;
486
+ syncState();
487
+ },
488
+ /** Hiện linh vật + mở ô hỏi để gõ ngay (như `aivin ui`) — cho phím tắt / khay hệ thống; câu hỏi đang chờ (nếu có) đã nằm sẵn trong ô. */
489
+ openAsk: wake,
490
+ pid: () => child?.pid ?? null,
320
491
  close,
321
492
  };
322
493
  }
@@ -1,4 +1,3 @@
1
- import path from 'path';
2
1
  import { ToolGroup } from '../constants.mjs';
3
2
  import { MascotVerb, mascotVerb } from './strings.mjs';
4
3
 
@@ -52,7 +51,7 @@ const clip = (s, max) => {
52
51
  /** Đích chính của bước: tên tệp / thư mục (không cả đường dẫn), lệnh, từ khoá tìm, ứng dụng. */
53
52
  export function targetOf(args = {}) {
54
53
  const file = args.path || args.file || args.src || args.from || args.source || (Array.isArray(args.paths) ? args.paths[0] : undefined) || args.dir || args.cwd;
55
- if (typeof file === 'string' && file) return clip(path.basename(file.replace(/[\\/]+$/, '')) || file, TARGET_MAX);
54
+ if (typeof file === 'string' && file) return clip(file.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || file, TARGET_MAX);
56
55
  const cmd = args.command || args.cmd;
57
56
  if (typeof cmd === 'string' && cmd) return clip(cmd, TARGET_MAX);
58
57
  const q = args.query || args.pattern || args.name;
@@ -68,7 +67,7 @@ export function argsPreview(args = {}) {
68
67
  if (CONTENT_KEYS.has(k) && v && typeof v === 'object') return [k, '‹…›'];
69
68
  return [k, v];
70
69
  }));
71
- let json = '';
70
+ let json;
72
71
  try { json = JSON.stringify(shown); } catch { json = ''; }
73
72
  return clip(json === '{}' ? '' : json, DETAIL_MAX);
74
73
  }