@aivin-labs/cli 1.0.47 → 1.0.50

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.
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Chốt "chỉ người thật bấm được" cho các hộp xác nhận của Aivin trên Windows (hộp xác nhận tại máy, hộp đồng ý chia sẻ màn hình) — 09/11/2026.
3
+ *
4
+ * Hộp là cửa sổ WPF thường: AI bấm được nút "Cho phép" bằng `gui.do` / `gui.act` (lệnh Invoke của UI Automation — không sinh thao tác nào),
5
+ * bằng script `SendInput` / UIAutomation chạy qua `shell.exec`, hay một tiến trình nền đã cài sẵn. Chốt này cài hook chuột / phím mức thấp
6
+ * (WH_MOUSE_LL / WH_KEYBOARD_LL) trong tiến trình của hộp và chỉ nhận "Cho phép" khi vừa có thao tác THẬT trên chính hộp:
7
+ * - phím / chuột phần cứng (không mang cờ `INJECTED`), bấm trong hộp (chuột) hoặc lúc hộp đang ở trước (phím);
8
+ * - hoặc thao tác do tiến trình xem + điều khiển màn hình của Aivin bơm vào mang đúng `tag` bí mật của phiên (`dwExtraInfo`), để chủ máy đang
9
+ * điều khiển từ xa vẫn duyệt được hộp xác nhận (hộp đồng ý chia sẻ màn hình thì không nhận tag: chỉ người thật ở máy).
10
+ * Lệnh Invoke qua UI Automation không có thao tác nào đi kèm → bị bỏ. "Từ chối" không cần chốt.
11
+ *
12
+ * Không cài được hook (máy không biên dịch được C#) → hộp hoạt động như trước (không chặn ai) — kẻ tấn công không tự gây ra được tình huống này.
13
+ * Giới hạn: mã độc cùng tài khoản đọc được bộ nhớ tiến trình (lấy `tag`) vẫn lách được — cách ly thật cần tài khoản hệ điều hành riêng.
14
+ */
15
+
16
+ import { randomInt } from 'crypto';
17
+
18
+ /** Tiêu đề cửa sổ các hộp chỉ người ở máy trả lời — công cụ GUI của AI không thao tác lên chúng (gui/index.mjs). */
19
+ export const CONFIRM_WINDOW_TITLE = 'Aivin — xác nhận trên máy này';
20
+ export const CAST_CONSENT_WINDOW_TITLE = 'Aivin — Xác nhận chia sẻ màn hình';
21
+ const PROTECTED_TITLES = new Set([CONFIRM_WINDOW_TITLE, CAST_CONSENT_WINDOW_TITLE].map((t) => t.toLowerCase()));
22
+
23
+ export function isProtectedPromptWindow(title) {
24
+ return PROTECTED_TITLES.has(String(title ?? '').trim().toLowerCase());
25
+ }
26
+
27
+ /** C# 5 (Add-Type của PowerShell 5.1). Cờ: LLMHF_INJECTED 0x1 | LLMHF_LOWER_IL_INJECTED 0x2; LLKHF_INJECTED 0x10 | LLKHF_LOWER_IL_INJECTED 0x2. */
28
+ export const HUMAN_GUARD_CSHARP = String.raw`
29
+ using System;
30
+ using System.Diagnostics;
31
+ using System.Runtime.InteropServices;
32
+ public static class AivinHumanGuard {
33
+ public delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam);
34
+ [DllImport("user32.dll", SetLastError = true)] static extern IntPtr SetWindowsHookEx(int idHook, HookProc fn, IntPtr hMod, uint threadId);
35
+ [DllImport("user32.dll")] static extern IntPtr CallNextHookEx(IntPtr hhk, int code, IntPtr wParam, IntPtr lParam);
36
+ [DllImport("user32.dll")] static extern bool UnhookWindowsHookEx(IntPtr hhk);
37
+ [DllImport("kernel32.dll")] static extern IntPtr GetModuleHandle(string name);
38
+ [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
39
+ [DllImport("user32.dll")] static extern IntPtr WindowFromPhysicalPoint(POINT p);
40
+ [DllImport("user32.dll")] static extern IntPtr GetAncestor(IntPtr h, uint flags);
41
+ [StructLayout(LayoutKind.Sequential)] public struct POINT { public int x; public int y; }
42
+ [StructLayout(LayoutKind.Sequential)] struct MSLL { public POINT pt; public uint mouseData; public uint flags; public uint time; public IntPtr extra; }
43
+ [StructLayout(LayoutKind.Sequential)] struct KBLL { public uint vk; public uint scan; public uint flags; public uint time; public IntPtr extra; }
44
+ static HookProc mouseProc;
45
+ static HookProc keyProc;
46
+ static IntPtr mouseHook = IntPtr.Zero;
47
+ static IntPtr keyHook = IntPtr.Zero;
48
+ static readonly Stopwatch clock = Stopwatch.StartNew();
49
+ static long lastTrusted = -1;
50
+ static IntPtr window = IntPtr.Zero;
51
+ static long tag = 0;
52
+ static bool Trusted(bool injected, IntPtr extra) { return !injected || (tag != 0 && (extra.ToInt64() & 0xFFFFFFFFL) == tag); }
53
+ static IntPtr OnMouse(int code, IntPtr w, IntPtr l) {
54
+ if (code >= 0) {
55
+ int m = w.ToInt32();
56
+ if (m == 0x0201 || m == 0x0204 || m == 0x0207) {
57
+ MSLL s = (MSLL)Marshal.PtrToStructure(l, typeof(MSLL));
58
+ if (Trusted((s.flags & 0x3) != 0, s.extra) && window != IntPtr.Zero && GetAncestor(WindowFromPhysicalPoint(s.pt), 2) == window) lastTrusted = clock.ElapsedMilliseconds;
59
+ }
60
+ }
61
+ return CallNextHookEx(mouseHook, code, w, l);
62
+ }
63
+ static IntPtr OnKey(int code, IntPtr w, IntPtr l) {
64
+ if (code >= 0) {
65
+ int m = w.ToInt32();
66
+ if (m == 0x0100 || m == 0x0104) {
67
+ KBLL s = (KBLL)Marshal.PtrToStructure(l, typeof(KBLL));
68
+ if (Trusted((s.flags & 0x12) != 0, s.extra) && window != IntPtr.Zero && GetForegroundWindow() == window) lastTrusted = clock.ElapsedMilliseconds;
69
+ }
70
+ }
71
+ return CallNextHookEx(keyHook, code, w, l);
72
+ }
73
+ public static bool Install(IntPtr hwnd, long trustedTag) {
74
+ window = hwnd;
75
+ tag = trustedTag;
76
+ mouseProc = OnMouse;
77
+ keyProc = OnKey;
78
+ IntPtr mod = GetModuleHandle(null);
79
+ mouseHook = SetWindowsHookEx(14, mouseProc, mod, 0);
80
+ keyHook = SetWindowsHookEx(13, keyProc, mod, 0);
81
+ return mouseHook != IntPtr.Zero && keyHook != IntPtr.Zero;
82
+ }
83
+ public static bool Recent(int ms) { return lastTrusted >= 0 && clock.ElapsedMilliseconds - lastTrusted <= ms; }
84
+ }
85
+ `;
86
+
87
+ /**
88
+ * `tag` cho một phiên điều khiển màn hình: số 31 bit ngẫu nhiên khác 0. Windows chỉ chuyển 32 bit thấp của `dwExtraInfo` tới hook mức thấp (đo
89
+ * 09/11/2026: tag 48 bit tới nơi bị cắt còn 32 bit) — nên tag không vượt 32 bit, so đúng 32 bit thấp.
90
+ */
91
+ export function newInputTag() {
92
+ return randomInt(0x1000_0000, 0x7fff_ffff);
93
+ }
94
+
95
+ /** Bấm "Cho phép" được tính khi thao tác thật cuối cùng trên hộp cách đó không quá bấy nhiêu ms (nhấn giữ chuột lâu vẫn qua). */
96
+ export const HUMAN_RECENT_MS = 4000;
97
+
98
+ /** Biến môi trường của hộp: mã C# + `tag` tin cậy (chuỗi rỗng = chỉ phím / chuột phần cứng). */
99
+ export function humanGuardEnv(trustTag = null) {
100
+ return {
101
+ AIVIN_GUARD_CS: Buffer.from(HUMAN_GUARD_CSHARP, 'utf8').toString('base64'),
102
+ AIVIN_GUARD_TAG: trustTag ? String(trustTag) : '',
103
+ AIVIN_GUARD_HINT: Buffer.from('Chỉ nhận bấm bằng chuột / bàn phím thật trên máy này', 'utf8').toString('base64'),
104
+ };
105
+ }
106
+
107
+ /**
108
+ * Dòng PowerShell dùng chung (cần hàm `D` giải base64 của script hộp): nạp chốt, `Install-Guard $w` sau khi cửa sổ hiện, `Test-Human` trong
109
+ * nút "Cho phép", `Guard-Hint` → chữ nhắc khi bị bỏ.
110
+ */
111
+ export const HUMAN_GUARD_PS = [
112
+ '$script:guard = $false',
113
+ "try { Add-Type -TypeDefinition (D 'AIVIN_GUARD_CS') -ErrorAction Stop; $script:guard = $true } catch { }",
114
+ 'function Install-Guard($win) { if (-not $script:guard) { return }; try { $h = (New-Object System.Windows.Interop.WindowInteropHelper($win)).Handle; $tg = [long]0; [void][long]::TryParse([string]$env:AIVIN_GUARD_TAG, [ref]$tg); if (-not [AivinHumanGuard]::Install($h, $tg)) { $script:guard = $false } } catch { $script:guard = $false } }',
115
+ `function Test-Human { if (-not $script:guard) { return $true }; return [AivinHumanGuard]::Recent(${HUMAN_RECENT_MS}) }`,
116
+ "$script:hintLeft = 0; $script:hint = D 'AIVIN_GUARD_HINT'",
117
+ ];
@@ -5,7 +5,8 @@ import { DeviceErrorCode } from './constants.mjs';
5
5
  /**
6
6
  * Chống làm trùng (28/10/2026): BE gắn `idem_key` cho mỗi bước có tác dụng (theo nhiệm vụ + lượt + bước + tham số). BE khởi động lại giữa
7
7
  * chừng → agentic chạy tiếp → lô bước dở được gửi lại: bước đã làm (hoặc đang làm) trả lại đúng kết quả cũ thay vì ghi / gửi / chạy lần hai.
8
- * Bước hỏng thì quên khoá — lần sau được chạy lại.
8
+ * Bước hỏng thì quên khoá — lần sau được chạy lại; trừ khi bị dừng GIỮA CHỪNG (hết giờ / huỷ sau khi đã bắt đầu, `ran` của scheduler) → lần
9
+ * gửi lại nhận `INTERRUPTED` thay vì làm lần hai.
9
10
  *
10
11
  * Sổ trên đĩa (29/10/2026, `file`): daemon khởi động lại (sập, máy khởi động lại, tự cập nhật) vẫn nhớ. Bước xong → trả kết quả cũ; bước
11
12
  * ĐANG chạy lúc daemon chết → `INTERRUPTED` (không biết đã làm tới đâu — không tự làm lần hai, Planner kiểm lại rồi mới làm).
@@ -35,6 +36,17 @@ const interruptedOutcome = () => ({
35
36
  duration_ms: 0,
36
37
  });
37
38
 
39
+ /** Bước bị dừng giữa chừng (hết giờ / huỷ / tạm dừng) SAU khi đã bắt đầu: có thể đã làm một phần — lần gửi lại không chạy mù lần hai. */
40
+ const STOPPED_MIDWAY = new Set([DeviceErrorCode.CALL_TIMEOUT, DeviceErrorCode.CANCELLED]);
41
+ export const stoppedMidway = (outcome) => !outcome?.ok && outcome?.ran === true && STOPPED_MIDWAY.has(outcome.error_code);
42
+
43
+ const stoppedOutcome = (outcome) => ({
44
+ ok: false,
45
+ error: `This step was stopped after it had started on this device (${outcome.error_code === DeviceErrorCode.CALL_TIMEOUT ? 'timed out' : 'cancelled'}) — it may have partly run. Check its effect before doing it again.`,
46
+ error_code: DeviceErrorCode.INTERRUPTED,
47
+ duration_ms: 0,
48
+ });
49
+
38
50
  /** Sổ khoá trên đĩa, mỗi dòng một sự kiện `{ k, s, at, o? }`. Đọc: dòng sau đè dòng trước; `start` không có `done` / `fail` → bị ngắt. */
39
51
  export function createIdemLog(file, { now = () => Date.now() } = {}) {
40
52
  const entries = new Map();
@@ -151,7 +163,12 @@ export function createIdempotentRunner(run, isReadOnly, { onDuplicate, now = ()
151
163
  const rawPromise = run(call, ...rest, ...(deferStart ? [{ started }] : []));
152
164
  const promise = rawPromise.then(async (r) => {
153
165
  if (r.outcome.ok) await log?.done(key, r.outcome);
154
- else { seen.delete(key); await log?.failed(key); }
166
+ else if (stoppedMidway(r.outcome)) {
167
+ // Lần này trả đúng lỗi gốc; lần gửi lại cùng khoá nhận INTERRUPTED (như bước đang chạy lúc daemon chết).
168
+ const kept = stoppedOutcome(r.outcome);
169
+ seen.set(key, { promise: Promise.resolve({ tool: r.tool, outcome: kept }), at: t });
170
+ await log?.done(key, kept);
171
+ } else { seen.delete(key); await log?.failed(key); }
155
172
  return r;
156
173
  }, async (err) => {
157
174
  seen.delete(key);
@@ -14,11 +14,15 @@ const START_DELAY_MS = 5_000;
14
14
  /** Rảnh bấy nhiêu lâu rồi mới thả cờ (lô bước kế thường tới ngay sau). */
15
15
  const IDLE_RELEASE_MS = 60_000;
16
16
 
17
- const WINDOWS_SCRIPT = [
17
+ /**
18
+ * ES_CONTINUOUS | ES_SYSTEM_REQUIRED (2147483649): chặn ngủ do rảnh, KHÔNG giữ màn hình sáng. `display` (phiên xem + điều khiển màn hình từ xa,
19
+ * 09/11/2026): thêm ES_DISPLAY_REQUIRED (2147483651) — người xem chỉ nhìn không thao tác thì màn hình không tắt / không khoá giữa phiên
20
+ * (màn hình khoá là secure desktop: từ xa không mở lại được).
21
+ */
22
+ const windowsScript = (display) => [
18
23
  "$sig = '[DllImport(\"kernel32.dll\")] public static extern uint SetThreadExecutionState(uint esFlags);'",
19
24
  "$k = Add-Type -MemberDefinition $sig -Name AivinAwake -Namespace Aivin -PassThru",
20
- // ES_CONTINUOUS | ES_SYSTEM_REQUIRED: chặn ngủ do rảnh, KHÔNG giữ màn hình sáng.
21
- '[void]$k::SetThreadExecutionState([uint32]2147483649)',
25
+ `[void]$k::SetThreadExecutionState([uint32]${display ? 2147483651 : 2147483649})`,
22
26
  '[void][Console]::In.ReadToEnd()',
23
27
  ].join('; ');
24
28
 
@@ -27,9 +31,9 @@ function hasLinuxInhibit() {
27
31
  }
28
32
 
29
33
  /** Lệnh giữ máy thức theo hệ điều hành — `null` khi không có cách nào. */
30
- export function keepAwakeCommand(platform = process.platform, { pid = process.pid, linuxInhibit = hasLinuxInhibit } = {}) {
31
- if (platform === 'win32') return { cmd: 'powershell.exe', args: ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WINDOWS_SCRIPT] };
32
- if (platform === 'darwin') return { cmd: 'caffeinate', args: ['-i', '-w', String(pid)] };
34
+ export function keepAwakeCommand(platform = process.platform, { pid = process.pid, linuxInhibit = hasLinuxInhibit, display = false } = {}) {
35
+ if (platform === 'win32') return { cmd: 'powershell.exe', args: ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', windowsScript(display)] };
36
+ if (platform === 'darwin') return { cmd: 'caffeinate', args: [...(display ? ['-d'] : []), '-i', '-w', String(pid)] };
33
37
  if (platform === 'linux' && linuxInhibit()) {
34
38
  return { cmd: 'systemd-inhibit', args: ['--what=idle:sleep', '--who=Aivin', '--why=Aivin agent is working on this computer', '--mode=block', 'cat'] };
35
39
  }
@@ -40,8 +44,10 @@ export function keepAwakeCommand(platform = process.platform, { pid = process.pi
40
44
  * `hold(reason)` / `release(reason)` đếm theo lý do (mỗi lời gọi đang chạy một lần, tiến trình nền một lần). Bận liên tục quá
41
45
  * `startDelayMs` → bật; hết bận `idleMs` → tắt.
42
46
  */
43
- export function createKeepAwake({ enabled = true, platform = process.platform, spawnImpl = spawn, startDelayMs = START_DELAY_MS, idleMs = IDLE_RELEASE_MS, say } = {}) {
44
- const command = enabled ? keepAwakeCommand(platform) : null;
47
+ export function createKeepAwake({
48
+ enabled = true, platform = process.platform, spawnImpl = spawn, startDelayMs = START_DELAY_MS, idleMs = IDLE_RELEASE_MS, display = false, say,
49
+ } = {}) {
50
+ const command = enabled ? keepAwakeCommand(platform, { display }) : null;
45
51
  let holds = 0;
46
52
  let child = null;
47
53
  let startTimer = null;
@@ -54,7 +60,7 @@ export function createKeepAwake({ enabled = true, platform = process.platform, s
54
60
  child = spawnImpl(command.cmd, command.args, { stdio: ['pipe', 'ignore', 'ignore'], windowsHide: true });
55
61
  child.on('error', () => { child = null; });
56
62
  child.on('exit', () => { child = null; });
57
- say?.('☕ Đang có việc — giữ máy không tự ngủ');
63
+ say?.(display ? '☕ Đang có người xem màn hình từ xa — giữ màn hình sáng' : '☕ Đang có việc — giữ máy không tự ngủ');
58
64
  } catch {
59
65
  child = null;
60
66
  }
@@ -2,6 +2,7 @@ import { spawn } from 'child_process';
2
2
  import fs from 'fs';
3
3
  import readline from 'readline';
4
4
  import { AIVIN_BRAND, AIVIN_LOGO_PNG_BASE64 } from './brand.mjs';
5
+ import { CONFIRM_WINDOW_TITLE, HUMAN_GUARD_PS, humanGuardEnv } from './humanInput.mjs';
5
6
 
6
7
  /**
7
8
  * Hộp "Cho phép / Từ chối" NGAY TRÊN MÁY cho việc sàn luật tại máy đòi xác nhận (localPolicy.mjs). BE không trả lời thay được: chỉ người
@@ -14,7 +15,7 @@ import { AIVIN_BRAND, AIVIN_LOGO_PNG_BASE64 } from './brand.mjs';
14
15
  /** `CANCELLED`: lời gọi bị huỷ (BE huỷ / hết giờ, tạm dừng, daemon dừng) trong lúc hộp đang chờ hoặc còn xếp hàng — hộp đóng, việc không chạy. */
15
16
  export const ConfirmResult = Object.freeze({ ALLOW: 'allow', REJECT: 'reject', TIMEOUT: 'timeout', UNAVAILABLE: 'unavailable', CANCELLED: 'cancelled' });
16
17
 
17
- const TITLE = 'Aivin — xác nhận trên máy này';
18
+ const TITLE = CONFIRM_WINDOW_TITLE;
18
19
  const HEADING = 'Agent Aivin xin chạy một việc trên máy này';
19
20
  const ALLOW_LABEL = 'Cho phép';
20
21
  const REJECT_LABEL = 'Từ chối';
@@ -73,6 +74,20 @@ const WINDOWS_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xam
73
74
  <Window.Resources>
74
75
  ${buttonStyle('Btn', 10)}
75
76
  ${buttonStyle('IconBtn', 8)}
77
+ <Style TargetType="ScrollBar">
78
+ <Setter Property="Width" Value="5"/>
79
+ <Setter Property="MinWidth" Value="5"/>
80
+ <Setter Property="Template"><Setter.Value>
81
+ <ControlTemplate TargetType="ScrollBar">
82
+ <Track x:Name="PART_Track" IsDirectionReversed="True">
83
+ <Track.Thumb><Thumb><Thumb.Template><ControlTemplate TargetType="Thumb">
84
+ <Border x:Name="ThumbBar" CornerRadius="2.5" Background="#D5D8DE" Margin="0,1"/>
85
+ <ControlTemplate.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter TargetName="ThumbBar" Property="Background" Value="#9EA4AF"/></Trigger></ControlTemplate.Triggers>
86
+ </ControlTemplate></Thumb.Template></Thumb></Track.Thumb>
87
+ </Track>
88
+ </ControlTemplate>
89
+ </Setter.Value></Setter>
90
+ </Style>
76
91
  ${cardMotion('In', 1, 1, 180, 'EaseOut')}
77
92
  ${cardMotion('Out', 0, 0.97, 120, 'EaseIn')}
78
93
  </Window.Resources>
@@ -95,15 +110,15 @@ const WINDOWS_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xam
95
110
  <TextBlock x:Name="DetailLabel" Margin="0,16,0,6" FontSize="12" Foreground="${B.muted}"/>
96
111
  <Border CornerRadius="10" Background="#F4F6FA" BorderBrush="#E8ECF3" BorderThickness="1" Padding="14,11">
97
112
  <ScrollViewer MaxHeight="150" VerticalScrollBarVisibility="Auto">
98
- <TextBlock x:Name="Detail" FontFamily="Cascadia Mono, Consolas" FontSize="13" Foreground="${B.ink}" TextWrapping="Wrap"/>
113
+ <TextBlock x:Name="Detail" Margin="0,0,8,0" FontFamily="Cascadia Mono, Consolas" FontSize="13" Foreground="${B.ink}" TextWrapping="Wrap"/>
99
114
  </ScrollViewer>
100
115
  </Border>
101
- <DockPanel Margin="0,24,0,0" LastChildFill="False">
102
- <TextBlock x:Name="Countdown" VerticalAlignment="Center" FontSize="12" Foreground="${B.muted}"/>
116
+ <DockPanel Margin="0,24,0,0" LastChildFill="True">
103
117
  <Button x:Name="Allow" DockPanel.Dock="Right" Style="{StaticResource Btn}" Height="40" MinWidth="116" Padding="20,0" Margin="10,0,0,0"
104
118
  Background="${B.brand}" Foreground="White" BorderThickness="0" Tag="#26000000"/>
105
119
  <Button x:Name="Reject" DockPanel.Dock="Right" Style="{StaticResource Btn}" Height="40" MinWidth="116" Padding="20,0"
106
120
  Background="White" Foreground="${B.ink}" BorderBrush="#C9CDD4" BorderThickness="1" Tag="#0F000000" IsCancel="True" IsDefault="True"/>
121
+ <TextBlock x:Name="Countdown" VerticalAlignment="Center" Margin="0,0,12,0" FontSize="12" Foreground="${B.muted}" TextWrapping="Wrap"/>
107
122
  </DockPanel>
108
123
  </StackPanel>
109
124
  </Border>
@@ -113,6 +128,8 @@ const WINDOWS_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xam
113
128
  const WINDOWS_SCRIPT = [
114
129
  'Add-Type -AssemblyName PresentationFramework, PresentationCore, WindowsBase',
115
130
  'function D($n) { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Environment]::GetEnvironmentVariable($n))) }',
131
+ // Chỉ nhận "Cho phép" từ thao tác thật (humanInput.mjs) — AI không tự bấm được bằng UI Automation / SendInput.
132
+ ...HUMAN_GUARD_PS,
116
133
  "$w = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader ([xml](D 'AIVIN_C_XAML'))))",
117
134
  "$w.Title = D 'AIVIN_C_TITLE'",
118
135
  "foreach ($n in 'Sub', 'Heading', 'Reason', 'Purpose', 'DetailLabel', 'Detail') { $w.FindName($n).Text = D ('AIVIN_C_' + $n.ToUpper()) }",
@@ -124,12 +141,12 @@ const WINDOWS_SCRIPT = [
124
141
  '$tm = New-Object Windows.Threading.DispatcherTimer; $tm.Interval = [TimeSpan]::FromSeconds(1)',
125
142
  // Đóng có hiệu ứng: chạy storyboard "Out" rồi mới đóng cửa sổ; bấm liên tiếp chỉ tính lần đầu.
126
143
  "function Finish($r) { if ($script:closing) { return }; $script:closing = $true; $script:result = $r; $tm.Stop(); $sb = $w.FindResource('Out').Clone(); $sb.Add_Completed({ $w.Close() }); $sb.Begin($card) }",
127
- "$w.FindName('Allow').Add_Click({ Finish 'Yes' })",
144
+ "$w.FindName('Allow').Add_Click({ if (Test-Human) { Finish 'Yes' } else { $script:hintLeft = 3; $cd.Text = $script:hint } })",
128
145
  "$w.FindName('Reject').Add_Click({ Finish 'No' }); $w.FindName('Close').Add_Click({ Finish 'No' })",
129
146
  "$w.FindName('Head').Add_MouseLeftButtonDown({ $w.DragMove() })",
130
147
  "$script:left = [int]$env:AIVIN_C_SECONDS; $fmt = D 'AIVIN_C_COUNTDOWN'; $cd = $w.FindName('Countdown'); $cd.Text = $fmt -f $script:left",
131
- "$tm.Add_Tick({ $script:left--; $cd.Text = $fmt -f $script:left; if ($script:left -le 0) { Finish 'Timeout' } })",
132
- "$w.Add_ContentRendered({ $w.FindResource('In').Begin($card); $w.Activate(); [void]$w.FindName('Reject').Focus(); $tm.Start() })",
148
+ "$tm.Add_Tick({ $script:left--; if ($script:hintLeft -gt 0) { $script:hintLeft--; $cd.Text = $script:hint } else { $cd.Text = $fmt -f $script:left }; if ($script:left -le 0) { Finish 'Timeout' } })",
149
+ "$w.Add_ContentRendered({ Install-Guard $w; $w.FindResource('In').Begin($card); $w.Activate(); [void]$w.FindName('Reject').Focus(); $tm.Start() })",
133
150
  '[void]$w.ShowDialog(); $tm.Stop(); $script:result',
134
151
  ].join('\n');
135
152
 
@@ -153,6 +170,8 @@ export function confirmCommand({ request, timeoutSec, platform = process.platfor
153
170
  AIVIN_C_DETAILLABEL: b64('SẼ THỰC HIỆN'), AIVIN_C_DETAIL: b64(request.detail),
154
171
  AIVIN_C_ALLOW: b64(`_${ALLOW_LABEL}`), AIVIN_C_REJECT: b64(`_${REJECT_LABEL}`),
155
172
  AIVIN_C_COUNTDOWN: b64('Tự từ chối sau {0} giây'), AIVIN_C_SECONDS: String(timeoutSec),
173
+ // `trustTag`: phiên điều khiển màn hình chủ máy đã bấm đồng ý → thao tác từ phiên đó cũng duyệt được (humanInput.mjs).
174
+ ...humanGuardEnv(request.trustTag),
156
175
  },
157
176
  parse: (out, code) => (code !== 0 ? ConfirmResult.UNAVAILABLE : /\bYes\b/.test(out) ? ConfirmResult.ALLOW
158
177
  : /\bTimeout\b/.test(out) ? ConfirmResult.TIMEOUT : ConfirmResult.REJECT),
@@ -199,7 +199,7 @@ export function createMascotChat({
199
199
  const setPending = (sessionId, question, text, url = null, payload = null) => {
200
200
  if (!question?.reply_id) return answerLine(ChatRole.ASSISTANT, text, undefined, payload, url ? { url } : {});
201
201
  const blocks = readBlocks(payload);
202
- const entry = { session_id: sessionId, reply_id: question.reply_id, kind: question.kind, options: Array.isArray(question.options) ? question.options : [], multiple: question.multiple === true, text, ...(url ? { url } : {}), ...linkButtons(payload), ...(blocks ? { blocks } : {}) };
202
+ const entry = { session_id: sessionId, reply_id: question.reply_id, kind: question.kind, options: Array.isArray(question.options) ? question.options : [], multiple: question.multiple === true, buttonsOnly: question.buttons_only === true, text, ...(url ? { url } : {}), ...linkButtons(payload), ...(blocks ? { blocks } : {}) };
203
203
  // Ảnh tải xong sau khi câu hỏi đã hiện: cập nhật dòng câu hỏi (cửa sổ dựng lại cũng nhận bản có ảnh).
204
204
  if (blocks) whenImagesLoaded(blocks, (loaded) => {
205
205
  entry.blocks = loaded;
@@ -415,6 +415,7 @@ export function createMascotChat({
415
415
  if (!s?.connected) return row(ChatRole.ERROR, t(MascotText.ASK_OFFLINE));
416
416
  const id = `ask-${randomUUID()}`;
417
417
  current = id;
418
+ answering = extra?.reply_id || null;
418
419
  streaming = null;
419
420
  setBusy(true);
420
421
  row(ChatRole.PROGRESS, t(MascotText.ASK_THINKING), PROGRESS_ROW, { typing: true });
@@ -425,9 +426,11 @@ export function createMascotChat({
425
426
  ack = await s.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.CHAT, { text, request_id: current, stream: true, links: true, blocks: true, ...context(), ...workContext(), ...extra });
426
427
  if (ack?.session_id) { currentSessionId = ack.session_id; noteDeviceSession(ack.session_id); }
427
428
  } catch (e) {
429
+ answering = null;
428
430
  finish();
429
431
  return row(ChatRole.ERROR, failedSend(e));
430
432
  }
433
+ answering = null;
431
434
  if (!ack?.ok) {
432
435
  finish();
433
436
  // Câu hỏi đã hết hạn / có người trả lời ở nơi khác → bỏ nút; trả lời sai dạng → giữ để chọn lại.
@@ -510,7 +513,7 @@ export function createMascotChat({
510
513
  syncFiles();
511
514
  const shown = answer || t(MascotText.ASK_FILES_DEFAULT);
512
515
  const body = `${shown}\n\n${t(MascotText.ASK_FILES_LABEL)}\n${sent.map((f) => `- ${f}`).join('\n')}`;
513
- return turn(body, shown, pending ? { session_id: pending.session_id, reply_id: pending.reply_id } : {}, window);
516
+ return turn(body, shown, pending && !pending.buttonsOnly ? { session_id: pending.session_id, reply_id: pending.reply_id } : {}, window);
514
517
  }
515
518
  if (!answer) return;
516
519
  if (!pending) return ask(answer, window);
@@ -519,6 +522,8 @@ export function createMascotChat({
519
522
  // Chọn nhiều: gõ tên các mục cách nhau dấu phẩy — khớp hết mới tính như tích các nút đó.
520
523
  const matches = (pending.multiple ? answer.split(/\s*[,;]\s*/).filter(Boolean) : [answer]).map(byText);
521
524
  const ids = matches.every(Boolean) ? [...new Set(matches.map((o) => String(o.id)))] : [];
525
+ // Câu chỉ nhận nút (việc chờ duyệt của kênh canh): chữ không khớp nút là câu hỏi mới, nút vẫn ở đó — không chặn ô hỏi tới khi bấm hết hàng.
526
+ if (pending.buttonsOnly && !ids.length) return ask(answer, window);
522
527
  await turn(answer, answer, { session_id: pending.session_id, reply_id: pending.reply_id, ...(ids.length ? { option_ids: ids } : {}) }, window);
523
528
  }
524
529
 
@@ -661,7 +666,8 @@ export function createMascotChat({
661
666
  /** Câu hỏi đang ghim đã đóng ở nơi khác (trả lời trên web / máy khác, hết hạn) → bỏ nút, báo một dòng. Đang gửi câu trả lời thì thôi. */
662
667
  async function checkQuestions() {
663
668
  const s = socket();
664
- const items = queue.filter((q) => q.session_id).map((q) => ({ session_id: q.session_id, reply_id: q.reply_id }));
669
+ // Câu hỏi không gắn phiên (việc chờ duyệt của kênh canh, `watch-draft:<id>`): BE hỏi nguồn của nó — BE cũ chỉ đọc mục có phiên.
670
+ const items = queue.map((q) => ({ ...(q.session_id ? { session_id: q.session_id } : {}), reply_id: q.reply_id }));
665
671
  if (!features.inbox || !s?.connected || !items.length || current) return;
666
672
  let ack;
667
673
  try {
@@ -677,6 +683,19 @@ export function createMascotChat({
677
683
  row(ChatRole.ASSISTANT, t(MascotText.ASK_ANSWERED_ELSEWHERE));
678
684
  }
679
685
  }
686
+ /** Câu hỏi máy này đang gửi câu trả lời (chờ ack) — BE báo đóng câu đó là do chính máy này, lượt tự bỏ nút. */
687
+ let answering = null;
688
+ /**
689
+ * BE báo câu hỏi đã xử lý ở nơi khác (`device:question_closed`: duyệt trên web / máy khác) → bỏ nút ngay, không chờ lần kiểm định kỳ.
690
+ */
691
+ function onQuestionClosed(payload) {
692
+ const ids = Array.isArray(payload?.reply_ids) ? payload.reply_ids.filter((x) => typeof x === 'string') : [];
693
+ for (const id of ids) {
694
+ if (id === answering || !queue.some((q) => q.reply_id === id)) continue;
695
+ resolve(id);
696
+ row(ChatRole.ASSISTANT, t(MascotText.ASK_ANSWERED_ELSEWHERE));
697
+ }
698
+ }
680
699
  let questionTimer = null;
681
700
  const watchQuestions = () => {
682
701
  if (questionTimer || !queue.length) return;
@@ -973,7 +992,7 @@ export function createMascotChat({
973
992
 
974
993
  return {
975
994
  openTool,
976
- 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,
995
+ ask, reply, choose, attach, detach, setWorkDir, workDirDenied, workDir: () => workDir, cancel, newChat, onChatEvent, onNotify, onQuestionClosed, syncInbox, checkQuestions, setServerFeatures, busy: () => !!current || !!call, hasPending: () => queue.length > 0, userWindow: () => target,
977
996
  voiceStart, voiceAudio, voiceInterrupt, voiceStop, voiceMicLost, voiceDisconnected, onVoiceEvent, setVoiceSupported, inCall: () => !!call,
978
997
  setNotifyFreq: (val) => { const v = Number(val); if (Number.isInteger(v) && v >= 0 && v <= 2) currentNotifyFreq = v; },
979
998
  setLang: (l) => { if (l) currentLang = l; },
@@ -41,6 +41,11 @@ const CHOICE_INK = '#3B4256';
41
41
  const CHOICE_HOVER = '#0F1E1B4B';
42
42
  /** Viền chấm tròn / ô vuông đầu mỗi lựa chọn (chưa tích). */
43
43
  const CHOICE_MARK = '#9AA1B2';
44
+ /**
45
+ * Bề rộng nội dung nút lựa chọn / nút link. Trong ô hỏi (240) nút rộng 213, còn 207 khi thanh cuộn hiện; trừ lề trong 10 + 10 còn 187. Rộng hơn
46
+ * thì mép phải bị cắt — đúng chỗ icon (05/11/2026: 192 làm mất nửa icon khi hội thoại đủ dài để cuộn).
47
+ */
48
+ export const CHOICE_ROW_WIDTH = 186;
44
49
  /** Nút mở link: icon Lucide + màu đậm cùng tông với nền nút (`CHOICE_CARDS[2]`, xanh trời). */
45
50
  const LINK_ICON_PATH = lucidePath('external-link');
46
51
  /** Nút x trên chip tệp đính kèm. */
@@ -295,8 +300,8 @@ function TypingDots {
295
300
  }
296
301
  # Link buttons under a bubble (the answer's "open this page" buttons, "view on Aivin"): a click opens the browser, nothing goes to the agent.
297
302
  function LinkCard($text, $url, $iconPath = '${LINK_ICON_PATH}') {
298
- $dock = New-Object Windows.Controls.DockPanel; $dock.MaxWidth = 192
299
- $icon = LucideIcon $(if ($iconPath) { $iconPath } else { '${LINK_ICON_PATH}' }) 13 '${ICON_INKS[2]}'; $icon.Margin = '8,3,0,0'; $icon.VerticalAlignment = 'Top'; [Windows.Controls.DockPanel]::SetDock($icon, 'Right'); [void]$dock.Children.Add($icon)
303
+ $dock = New-Object Windows.Controls.DockPanel; $dock.MaxWidth = ${CHOICE_ROW_WIDTH}
304
+ $icon = LucideIcon $(if ($iconPath) { $iconPath } else { '${LINK_ICON_PATH}' }) 13 '${ICON_INKS[2]}'; $icon.Margin = '8,2,0,0'; $icon.VerticalAlignment = 'Top'; [Windows.Controls.DockPanel]::SetDock($icon, 'Right'); [void]$dock.Children.Add($icon)
300
305
  $tb = New-Object Windows.Controls.TextBlock; $tb.TextWrapping = 'Wrap'; $tb.Foreground = Brush '${CHOICE_INK}'; SetText $tb $text; [void]$dock.Children.Add($tb)
301
306
  $btn = New-Object Windows.Controls.Button; $btn.Style = $w.FindResource('Btn'); $btn.Content = $dock; $btn.CommandParameter = [string]$url; $btn.ToolTip = [string]$url
302
307
  $btn.FontSize = 13; $btn.FontWeight = 'Normal'; $btn.Padding = '10,6,10,6'; $btn.Margin = '0,0,0,3'; $btn.HorizontalAlignment = 'Left'
@@ -376,8 +381,9 @@ function ChatRow($m) {
376
381
  # unticks, a confirm button sends the ticked ones), the text, the option's icon at the end when it has one we can draw.
377
382
  # Soft look: each card filled with a light pastel (cycling the ask box's glow colors), no border, dark-grey text; hover deepens it.
378
383
  # Icon at the end of an option: the daemon looks up the Lucide name (the set Aivin's web uses) and sends its outline; an emoji is drawn as is.
384
+ # Top margin 2 centres it on the first line of text (17 high), so it stays level with the tick mark.
379
385
  function ChoiceIcon($o, $ink) {
380
- if ($o.icon_path) { $i = LucideIcon $o.icon_path 14 $ink; $i.Margin = '8,3,0,0'; $i.VerticalAlignment = 'Top'; return $i }
386
+ if ($o.icon_path) { $i = LucideIcon $o.icon_path 14 $ink; $i.Margin = '8,2,0,0'; $i.VerticalAlignment = 'Top'; return $i }
381
387
  if (-not $o.icon) { return $null }
382
388
  $tb = New-Object Windows.Controls.TextBlock; $tb.FontSize = 13; $tb.Margin = '8,1,0,0'; $tb.VerticalAlignment = 'Top'; SetText $tb $o.icon; $tb
383
389
  }
@@ -406,7 +412,7 @@ function ChoiceButtons($options, $multiple) {
406
412
  foreach ($o in @($options)) {
407
413
  if (-not $o) { continue }
408
414
  $c = $cards[$k % $cards.Count]; $k++; $id = [string]$o.id
409
- $row = New-Object Windows.Controls.DockPanel; $row.Width = 192
415
+ $row = New-Object Windows.Controls.DockPanel; $row.Width = ${CHOICE_ROW_WIDTH}
410
416
  $mark = ChoiceMark $multi; [Windows.Controls.DockPanel]::SetDock($mark, 'Left'); [void]$row.Children.Add($mark)
411
417
  $icon = ChoiceIcon $o $inks[($k - 1) % $inks.Count]; if ($icon) { [Windows.Controls.DockPanel]::SetDock($icon, 'Right'); [void]$row.Children.Add($icon) }
412
418
  $tb = New-Object Windows.Controls.TextBlock; SetText $tb $o.text; $tb.TextWrapping = 'Wrap'; $tb.Foreground = Brush '${CHOICE_INK}'; [void]$row.Children.Add($tb)