@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.
- package/bin/cli.mjs +74 -2
- package/bin/lib/docHandoff.mjs +111 -0
- package/bin/lib/openFile.mjs +41 -10
- package/bin/lib/remote/agentContract.mjs +26 -0
- package/bin/lib/remote/agentEvidence.mjs +2 -1
- package/bin/lib/remote/agentPreview.mjs +151 -0
- package/bin/lib/remote/client.mjs +75 -7
- package/bin/lib/remote/codingAgents.mjs +372 -106
- package/bin/lib/remote/constants.mjs +2 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +3 -1
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +23 -4
- package/bin/lib/remote/desktop/desktopCastSource.mjs +2 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +2 -3
- package/bin/lib/remote/ephemeralAuth.mjs +99 -0
- package/bin/lib/remote/lightcodeAgent.mjs +1615 -0
- package/bin/lib/remote/localLlm.mjs +748 -576
- package/bin/lib/remote/localLlmLogin.mjs +293 -0
- package/bin/lib/remote/localLlmMembers.mjs +115 -0
- package/bin/lib/remote/localPolicy.mjs +345 -341
- package/bin/lib/remote/mascot/ask.mjs +30 -9
- package/bin/lib/remote/mascot/askHostSource.mjs +22 -8
- package/bin/lib/remote/mascot/emojiSource.mjs +60 -3
- package/bin/lib/remote/mascot/hostSource.mjs +9 -3
- package/bin/lib/remote/mascot/index.mjs +4 -2
- package/bin/lib/remote/mascot/localOpen.mjs +79 -0
- package/bin/lib/remote/mascot/strings.mjs +8 -5
- package/bin/lib/remote/orgComputerLicense.mjs +99 -0
- package/bin/lib/remote/toolHandlers.mjs +44 -4
- package/package.json +1 -1
|
@@ -7,6 +7,7 @@ import { fetchMascotImage } from './images.mjs';
|
|
|
7
7
|
import { fileChip } from './fileChips.mjs';
|
|
8
8
|
import { lucidePath } from './lucideIcons.mjs';
|
|
9
9
|
import { safeLinkUrl, safeWebUrl } from './safeUrl.mjs';
|
|
10
|
+
import { createLocalLinkRegistry, LOCAL_LINK_PREFIX, localOpenTarget, LocalOpenKind, openLocal as openLocalPath } from './localOpen.mjs';
|
|
10
11
|
import { MascotText, mascotText } from './strings.mjs';
|
|
11
12
|
|
|
12
13
|
/**
|
|
@@ -151,6 +152,8 @@ export function createMascotChat({
|
|
|
151
152
|
const features = { inbox: false, cancel: false, newChat: false, parallel: false };
|
|
152
153
|
/** Câu hỏi đang chờ theo thứ tự đến: `{ session_id, reply_id, kind, options, text }`; đầu hàng = câu đang có nút. */
|
|
153
154
|
const queue = [];
|
|
155
|
+
/** Nút mở tệp / thư mục trên máy (`links[].path`): cửa sổ chỉ cầm mã `local:<id>`, daemon tra ra đường dẫn rồi kiểm (localOpen.mjs). */
|
|
156
|
+
const localLinks = createLocalLinkRegistry();
|
|
154
157
|
const head = () => queue[0] || null;
|
|
155
158
|
const seenNotify = new Set();
|
|
156
159
|
/** Tệp thả vào bot, chờ đi kèm câu kế tiếp. */
|
|
@@ -191,9 +194,12 @@ export function createMascotChat({
|
|
|
191
194
|
if (iconPath) return { icon_path: iconPath };
|
|
192
195
|
return /\p{Extended_Pictographic}/u.test(icon) ? { icon } : {};
|
|
193
196
|
};
|
|
194
|
-
/**
|
|
195
|
-
|
|
196
|
-
|
|
197
|
+
/**
|
|
198
|
+
* Nút lựa chọn: `multiple` = câu chọn nhiều (cửa sổ cho tích nhiều mục rồi xác nhận); `icon` của mục (nếu có) đi kèm để hiện cuối nút.
|
|
199
|
+
* `hint`: gợi ý mờ trong ô nhập cho câu / trường đang hỏi (gợi ý nhập của trường biểu mẫu) — lần gửi nút kế (kể cả bỏ nút) thay / xoá nó.
|
|
200
|
+
*/
|
|
201
|
+
const showChoices = (options, multiple = false, hint = '') => send({
|
|
202
|
+
t: AskCommand.CHOICES, multiple, ...(hint ? { hint } : {}),
|
|
197
203
|
options: options.map((o) => ({ id: String(o.id), text: String(o.text), ...choiceIcon(o.icon) })),
|
|
198
204
|
});
|
|
199
205
|
const setPending = (sessionId, question, text, url = null, payload = null) => {
|
|
@@ -251,12 +257,14 @@ export function createMascotChat({
|
|
|
251
257
|
const total = q.fields.length;
|
|
252
258
|
const options = fieldOptions(f);
|
|
253
259
|
// Một trường bắt buộc không có lựa chọn: câu hỏi đã đủ, không cần dòng tên trường.
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
260
|
+
// Dòng trường: tên trường đậm (`field`), bên dưới một dòng phụ nhạt "Bước 1/3 · Không bắt buộc" (`sub`) — không nhồi ngoặc vào câu.
|
|
261
|
+
// Gợi ý nhập (`placeholder`) hiện mờ trong ô nhập (`hint` của nút), không nằm trong bong bóng.
|
|
262
|
+
if (total > 1 || options.length || !f.required) {
|
|
263
|
+
const sub = [total > 1 ? t(MascotText.FORM_STEP, { n: q.step + 1, total }) : '', f.required ? '' : t(MascotText.FORM_OPTIONAL)].filter(Boolean).join(' · ');
|
|
264
|
+
row(ChatRole.ASSISTANT, String(f.label || f.name), `${QUESTION_ROW}${q.reply_id}-${q.step}`, { field: true, ...(sub ? { sub } : {}) });
|
|
258
265
|
}
|
|
259
|
-
|
|
266
|
+
const hint = typeof f.placeholder === 'string' ? f.placeholder.trim() : '';
|
|
267
|
+
showChoices(f.required ? options : [...options, { id: FORM_SKIP_ID, text: t(MascotText.FORM_SKIP) }], false, hint);
|
|
260
268
|
}
|
|
261
269
|
/** Ghi giá trị trường hiện tại (`null` = bỏ qua) → trường kế, hoặc gửi cả biểu mẫu một lần. */
|
|
262
270
|
async function fillField(q, value, shown) {
|
|
@@ -317,6 +325,13 @@ export function createMascotChat({
|
|
|
317
325
|
const linkButtons = (payload) => {
|
|
318
326
|
const web = payload?.session_id ? safeWebUrl(webUrlForSession(payload.session_id, serverUrl)) : null;
|
|
319
327
|
const links = (Array.isArray(payload?.links) ? payload.links : []).map((l) => {
|
|
328
|
+
// (18/11/2026) Tệp / thư mục TRÊN MÁY (thẻ duyệt việc lập trình: thư mục dự án, TEST_CHECK.md): chỉ khi đường dẫn có thật trên máy này.
|
|
329
|
+
if (typeof l?.path === 'string' && l.path) {
|
|
330
|
+
const target = localOpenTarget(l.path);
|
|
331
|
+
if (!target) return { text: '', url: null };
|
|
332
|
+
const icon = lucidePath(l?.icon) || lucidePath(target.kind === LocalOpenKind.FOLDER ? 'folder-open' : 'file-text') || lucidePath('folder');
|
|
333
|
+
return { text: typeof l?.text === 'string' ? l.text.trim() : '', url: `${LOCAL_LINK_PREFIX}${localLinks.register(target.path)}`, icon_path: icon };
|
|
334
|
+
}
|
|
320
335
|
const url = l?.web === true ? web : safeLinkUrl(l?.url);
|
|
321
336
|
const scheme = String(url || '').split(':')[0].toLowerCase();
|
|
322
337
|
return { text: typeof l?.text === 'string' ? l.text.trim() : '', url, icon_path: lucidePath(l?.icon) || lucidePath(LINK_SCHEME_ICONS[scheme] || LINK_SCHEME_ICONS.https) };
|
|
@@ -1000,8 +1015,14 @@ export function createMascotChat({
|
|
|
1000
1015
|
}
|
|
1001
1016
|
}
|
|
1002
1017
|
|
|
1018
|
+
/** Cửa sổ bấm nút mở trên máy: tra mã → đường dẫn đã đăng ký, kiểm lại (có thể đã bị xoá) rồi mới mở. */
|
|
1019
|
+
const openLocal = (id) => {
|
|
1020
|
+
const p = localLinks.pathOf(id);
|
|
1021
|
+
if (!p || !openLocalPath(p)) send({ t: AskCommand.STATUS, text: t(MascotText.ASK_LOCAL_OPEN_FAILED) });
|
|
1022
|
+
};
|
|
1023
|
+
|
|
1003
1024
|
return {
|
|
1004
|
-
openTool,
|
|
1025
|
+
openTool, openLocal,
|
|
1005
1026
|
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,
|
|
1006
1027
|
voiceStart, voiceAudio, voiceInterrupt, voiceStop, voiceMicLost, voiceDisconnected, onVoiceEvent, setVoiceSupported, inCall: () => !!call,
|
|
1007
1028
|
setNotifyFreq: (val) => { const v = Number(val); if (Number.isInteger(v) && v >= 0 && v <= 2) currentNotifyFreq = v; },
|
|
@@ -269,12 +269,17 @@ $script:clickCheckTimer.Start()
|
|
|
269
269
|
(E 'Mascot').Add_MouseRightButtonUp({ param($s, $e) CloseAsk; OpenPanel; $e.Handled = $true })
|
|
270
270
|
# One button: empty box = mic, typed text = send.
|
|
271
271
|
# Waiting on a turn the server can stop (chat_busy { cancel }): the empty-box button is a stop button instead of the mic.
|
|
272
|
+
$script:fieldHint = ''
|
|
272
273
|
function StopMode { $script:chatBusy -and $script:canCancel -and -not $script:voiceLive -and -not (E 'AskBox').Text.Trim() -and -not $script:files }
|
|
273
274
|
function SyncAction {
|
|
274
275
|
# Files waiting (chips above the input): the button sends even with nothing typed, and the hint asks what to do with them.
|
|
275
276
|
$typed = [bool](E 'AskBox').Text.Trim() -or ($script:files -gt 0 -and -not $script:voiceLive)
|
|
276
277
|
$stop = StopMode
|
|
277
|
-
|
|
278
|
+
# A form field being asked: its own input hint ("pick a member or type an email") instead of the generic one; may wrap to a second line.
|
|
279
|
+
$field = $script:fieldHint -and $script:files -le 0
|
|
280
|
+
(E 'AskHint').Text = if ($script:files -gt 0) { $T.ask_attached } elseif ($field) { $script:fieldHint } else { $T.ask_hint }
|
|
281
|
+
(E 'AskHint').TextWrapping = if ($field) { 'Wrap' } else { 'NoWrap' }
|
|
282
|
+
(E 'AskHint').FontSize = if ($field) { 13 } else { 14 }
|
|
278
283
|
(E 'AskHint').Visibility = if ((E 'AskBox').Text) { 'Collapsed' } else { 'Visible' }
|
|
279
284
|
(E 'SendIcon').Visibility = if ($typed) { 'Visible' } else { 'Collapsed' }; (E 'MicIcon').Visibility = if ($typed -or $stop) { 'Collapsed' } else { 'Visible' }
|
|
280
285
|
(E 'StopIcon').Visibility = if ($stop) { 'Visible' } else { 'Collapsed' }
|
|
@@ -340,10 +345,11 @@ function LinkCard($text, $url, $iconPath = '${LINK_ICON_PATH}') {
|
|
|
340
345
|
$dock = New-Object Windows.Controls.DockPanel; $dock.MaxWidth = ${CHOICE_ROW_WIDTH}
|
|
341
346
|
$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)
|
|
342
347
|
$tb = New-Object Windows.Controls.TextBlock; $tb.TextWrapping = 'Wrap'; $tb.Foreground = Brush '${CHOICE_INK}'; SetText $tb $text; [void]$dock.Children.Add($tb)
|
|
343
|
-
$btn = New-Object Windows.Controls.Button; $btn.Style = $w.FindResource('Btn'); $btn.Content = $dock; $btn.CommandParameter = [string]$url; $btn.ToolTip = [string]$url
|
|
348
|
+
$btn = New-Object Windows.Controls.Button; $btn.Style = $w.FindResource('Btn'); $btn.Content = $dock; $btn.CommandParameter = [string]$url; if (-not ([string]$url).StartsWith('local:')) { $btn.ToolTip = [string]$url }
|
|
344
349
|
$btn.FontSize = 13; $btn.FontWeight = 'Normal'; $btn.Padding = '10,6,10,6'; $btn.Margin = '0,0,0,3'; $btn.HorizontalAlignment = 'Left'
|
|
345
350
|
$btn.Background = Brush '${CHOICE_CARDS[2]}'; $btn.BorderThickness = '0'; $btn.Tag = Brush '${CHOICE_HOVER}'
|
|
346
|
-
|
|
351
|
+
# Open-on-this-computer buttons (url 'local:<id>'): the window never opens them itself - it sends the id, the daemon checks the path first (localOpen.mjs).
|
|
352
|
+
$btn.Add_Click({ param($s) $u = [string]$s.CommandParameter; if ($u.StartsWith('local:')) { Send @{ t = 'open_local'; id = $u.Substring(6) } } else { OpenWebUrl $u } })
|
|
347
353
|
$btn
|
|
348
354
|
}
|
|
349
355
|
function ChatLinks($row, $links) {
|
|
@@ -367,13 +373,18 @@ function ChatRow($m) {
|
|
|
367
373
|
# the same on all four sides.
|
|
368
374
|
$b = New-Object Windows.Controls.Border; $b.Padding = '10,5,10,5'; $b.Margin = '0,0,0,4'; $b.MaxWidth = $script:bubbleMax
|
|
369
375
|
$tb = New-Object Windows.Controls.TextBlock; $tb.TextWrapping = 'Wrap'; $tb.FontSize = 14; $tb.LineHeight = 20; $tb.LineStackingStrategy = 'BlockLineHeight'
|
|
370
|
-
|
|
376
|
+
# Links in the text (Emoji.SetLinked): a click opens the browser (http/https only, OpenWebUrl), not the bubble's own link.
|
|
377
|
+
$tb.AddHandler([Windows.Documents.Hyperlink]::RequestNavigateEvent, [Windows.Navigation.RequestNavigateEventHandler]{ param($s, $e) $e.Handled = $true; OpenWebUrl $e.Uri.AbsoluteUri })
|
|
378
|
+
# Second line under the text (a form field's "Step 1/3 - Optional"): smaller, muted.
|
|
379
|
+
$sub = New-Object Windows.Controls.TextBlock; $sub.TextWrapping = 'Wrap'; $sub.FontSize = 12; $sub.Margin = '0,1,0,1'; $sub.Foreground = Brush $P.muted; $sub.Visibility = 'Collapsed'
|
|
380
|
+
$body = New-Object Windows.Controls.StackPanel; [void]$body.Children.Add($tb); [void]$body.Children.Add($sub)
|
|
381
|
+
$b.Child = $body; [void]$list.Children.Add($b)
|
|
371
382
|
$slide = New-Object Windows.Media.TranslateTransform 0, 6; $b.RenderTransform = $slide
|
|
372
383
|
$ease = New-Object Windows.Media.Animation.CubicEase; $ease.EasingMode = 'EaseOut'
|
|
373
384
|
$fade = New-Object Windows.Media.Animation.DoubleAnimation 0, 1, ([TimeSpan]::FromMilliseconds(200)); $fade.EasingFunction = $ease
|
|
374
385
|
$rise = New-Object Windows.Media.Animation.DoubleAnimation 6, 0, ([TimeSpan]::FromMilliseconds(240)); $rise.EasingFunction = $ease
|
|
375
386
|
$b.BeginAnimation([Windows.UIElement]::OpacityProperty, $fade); $slide.BeginAnimation([Windows.Media.TranslateTransform]::YProperty, $rise)
|
|
376
|
-
$row = @{ box = $b; text = $tb; url = $null }
|
|
387
|
+
$row = @{ box = $b; body = $body; text = $tb; sub = $sub; url = $null }
|
|
377
388
|
# The link rides on the bubble itself (Tag, updated below): the handler is not a closure, $row at click time is not this row.
|
|
378
389
|
$b.Add_MouseLeftButtonUp({ param($s) OpenWebUrl $s.Tag })
|
|
379
390
|
if ($id) { $script:chatRows[$id] = $row }
|
|
@@ -396,7 +407,10 @@ function ChatRow($m) {
|
|
|
396
407
|
$fg = if ($role -eq 'progress') { $P.muted } elseif ($role -eq 'error') { '#CB2634' } else { $P.ink }
|
|
397
408
|
$row.box.Background = Brush $bg; $row.text.Foreground = Brush $fg
|
|
398
409
|
$row.text.FontStyle = if ($role -eq 'progress') { 'Italic' } else { 'Normal' }
|
|
399
|
-
SetText $row.text $m.text
|
|
410
|
+
if ($role -eq 'progress') { SetText $row.text $m.text } else { [AivinMascot.Emoji]::SetLinked($row.text, [string]$m.text) }
|
|
411
|
+
# A form field's row: the field name in bold, the step / "optional" under it.
|
|
412
|
+
$row.text.FontWeight = if ($m.field) { 'SemiBold' } else { 'Normal' }
|
|
413
|
+
if ($m.sub) { SetText $row.sub $m.sub; $row.sub.Visibility = 'Visible' } else { $row.sub.Visibility = 'Collapsed' }
|
|
400
414
|
ChatLinks $row $null
|
|
401
415
|
ChatBlocks $row $m.blocks
|
|
402
416
|
ChatLinks $row $m.links
|
|
@@ -405,7 +419,7 @@ function ChatRow($m) {
|
|
|
405
419
|
if ($m.typing) {
|
|
406
420
|
if (-not $row.dots) { $row.dots = TypingDots }
|
|
407
421
|
$row.box.Child = $row.dots; $row.box.Background = Brush '#F4F6FA'; $row.box.CornerRadius = '10,10,10,3'
|
|
408
|
-
} elseif ($row.dots -and $row.box.Child -ne $row.
|
|
422
|
+
} elseif ($row.dots -and $row.box.Child -ne $row.body) { $row.box.Child = $row.body }
|
|
409
423
|
# Words the owner is still saying: lighter until the sentence is settled (the box's own opacity is the fade-in).
|
|
410
424
|
$row.text.Opacity = if ($m.partial) { 0.55 } else { 1 }
|
|
411
425
|
$script:scrollRow = if ($row.blocks) { $row } else { $null }
|
|
@@ -634,7 +648,7 @@ function Handle($m) {
|
|
|
634
648
|
return
|
|
635
649
|
}
|
|
636
650
|
'ask_status' { AskStatus $m.text; return }
|
|
637
|
-
'ask_choices' { ChoiceButtons $m.options $m.multiple; return }
|
|
651
|
+
'ask_choices' { ChoiceButtons $m.options $m.multiple; $script:fieldHint = [string]$m.hint; SyncAction; return }
|
|
638
652
|
# Files waiting for the next question: chips above the input; then on to the bot's tray (no return).
|
|
639
653
|
'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} } }
|
|
640
654
|
'ask_pin' {
|
|
@@ -249,7 +249,65 @@ export const EMOJI_CS = String.raw`
|
|
|
249
249
|
return tag ?? block.Text;
|
|
250
250
|
}
|
|
251
251
|
|
|
252
|
+
static readonly System.Text.RegularExpressions.Regex UrlPattern = new System.Text.RegularExpressions.Regex(@"https?://[^\s<>""']+", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
|
253
|
+
static readonly Brush LinkBrush = MakeLinkBrush();
|
|
254
|
+
static Brush MakeLinkBrush() { var b = new SolidColorBrush(Color.FromRgb(0x16, 0x5D, 0xFF)); b.Freeze(); return b; }
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Nhu Set, them: dia chi http(s) trong chu thanh link (xanh, gach duoi, tay tro). Bam link noi su kien Hyperlink.RequestNavigate len
|
|
258
|
+
* TextBlock - host bat su kien do va mo trinh duyet (qua OpenWebUrl, chi http/https). Dau cau dinh cuoi dia chi (. , ) ...) khong tinh vao link.
|
|
259
|
+
*/
|
|
260
|
+
public static void SetLinked(System.Windows.Controls.TextBlock block, string text) {
|
|
261
|
+
string s = text ?? "";
|
|
262
|
+
var found = UrlPattern.Matches(s);
|
|
263
|
+
if (found.Count == 0) { Set(block, s); return; }
|
|
264
|
+
block.Tag = s;
|
|
265
|
+
try {
|
|
266
|
+
bool emoji = MayHaveEmoji(s);
|
|
267
|
+
if (emoji && !loaded) Load();
|
|
268
|
+
emoji = emoji && face != null;
|
|
269
|
+
var parts = new List<System.Windows.Documents.Inline>(); int at = 0;
|
|
270
|
+
foreach (System.Text.RegularExpressions.Match m in found) {
|
|
271
|
+
string url = m.Value.TrimEnd('.', ',', ';', ':', '!', '?', ')', ']', '}', '"', '\'');
|
|
272
|
+
Uri uri;
|
|
273
|
+
if (url.Length < 9 || !Uri.TryCreate(url, UriKind.Absolute, out uri)) continue;
|
|
274
|
+
if (m.Index > at) AddText(parts, s.Substring(at, m.Index - at), block.FontSize, emoji);
|
|
275
|
+
var link = new System.Windows.Documents.Hyperlink(new System.Windows.Documents.Run(LinkLabel(url))) { NavigateUri = uri, Foreground = LinkBrush, ToolTip = url };
|
|
276
|
+
link.TextDecorations = System.Windows.TextDecorations.Underline;
|
|
277
|
+
parts.Add(link); at = m.Index + url.Length;
|
|
278
|
+
}
|
|
279
|
+
if (at < s.Length) AddText(parts, s.Substring(at), block.FontSize, emoji);
|
|
280
|
+
block.Inlines.Clear();
|
|
281
|
+
block.Inlines.AddRange(parts);
|
|
282
|
+
} catch { block.Text = s; }
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Chu hien cua link: bo "https://" / "www." / "/" cuoi; dai qua thi cat (dia chi day du o ToolTip, bam van mo dung dia chi). */
|
|
286
|
+
public static string LinkLabel(string url) {
|
|
287
|
+
string s = url;
|
|
288
|
+
int scheme = s.IndexOf("://", StringComparison.Ordinal);
|
|
289
|
+
if (scheme > 0) s = s.Substring(scheme + 3);
|
|
290
|
+
if (s.StartsWith("www.", StringComparison.OrdinalIgnoreCase)) s = s.Substring(4);
|
|
291
|
+
if (s.EndsWith("/", StringComparison.Ordinal)) s = s.Substring(0, s.Length - 1);
|
|
292
|
+
if (s.Length > LinkMax) s = s.Substring(0, LinkMax - 1) + (char)0x2026;
|
|
293
|
+
return s.Length > 0 ? s : url;
|
|
294
|
+
}
|
|
295
|
+
const int LinkMax = 42;
|
|
296
|
+
|
|
297
|
+
static void AddText(List<System.Windows.Documents.Inline> parts, string s, double fontSize, bool emoji) {
|
|
298
|
+
if (!emoji || !AppendPieces(parts, s, fontSize)) parts.Add(new System.Windows.Documents.Run(s));
|
|
299
|
+
}
|
|
300
|
+
|
|
252
301
|
static bool SetInlines(System.Windows.Controls.TextBlock block, string s) {
|
|
302
|
+
var parts = new List<System.Windows.Documents.Inline>();
|
|
303
|
+
if (!AppendPieces(parts, s, block.FontSize)) return false;
|
|
304
|
+
block.Inlines.Clear();
|
|
305
|
+
block.Inlines.AddRange(parts);
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Chu + hinh emoji cua s vao parts; false (parts khong doi) khi s khong co emoji nao ve duoc. */
|
|
310
|
+
static bool AppendPieces(List<System.Windows.Documents.Inline> outParts, string s, double fontSize) {
|
|
253
311
|
var parts = new List<System.Windows.Documents.Inline>(); var plain = new StringBuilder(); bool any = false;
|
|
254
312
|
for (int i = 0; i < s.Length; ) {
|
|
255
313
|
if (char.IsHighSurrogate(s[i]) && !(i + 1 < s.Length && char.IsLowSurrogate(s[i + 1])) || char.IsLowSurrogate(s[i])) { plain.Append(s[i]); i++; continue; }
|
|
@@ -261,12 +319,11 @@ export const EMOJI_CS = String.raw`
|
|
|
261
319
|
}
|
|
262
320
|
any = true;
|
|
263
321
|
if (plain.Length > 0) { parts.Add(new System.Windows.Documents.Run(plain.ToString())); plain.Clear(); }
|
|
264
|
-
foreach (ushort g in run) if (baseFirst.ContainsKey(g)) parts.Add(PictureInline(g,
|
|
322
|
+
foreach (ushort g in run) if (baseFirst.ContainsKey(g)) parts.Add(PictureInline(g, fontSize));
|
|
265
323
|
}
|
|
266
324
|
if (!any) return false;
|
|
267
325
|
if (plain.Length > 0) parts.Add(new System.Windows.Documents.Run(plain.ToString()));
|
|
268
|
-
|
|
269
|
-
block.Inlines.AddRange(parts);
|
|
326
|
+
outParts.AddRange(parts);
|
|
270
327
|
return true;
|
|
271
328
|
}
|
|
272
329
|
}
|
|
@@ -199,8 +199,14 @@ export const MASCOT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/20
|
|
|
199
199
|
<Button x:Name="PanelClose" DockPanel.Dock="Right" Style="{StaticResource IconBtn}" Content="✕" Width="30" Height="30" FontSize="11"
|
|
200
200
|
FontWeight="Normal" Background="Transparent" BorderThickness="0" Tag="#F2F3F5" Foreground="${B.muted}"/>
|
|
201
201
|
</DockPanel>
|
|
202
|
-
|
|
203
|
-
<
|
|
202
|
+
<!-- "Đang làm": nhãn bên trái, việc hiện tại là tag bên phải (dài thì xuống dòng trong tag, căn phải). -->
|
|
203
|
+
<Grid DockPanel.Dock="Top" Margin="0,14,6,0">
|
|
204
|
+
<Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions>
|
|
205
|
+
<TextBlock x:Name="NowLabel" FontSize="11" FontWeight="SemiBold" Foreground="${B.muted}" VerticalAlignment="Center" Margin="0,0,12,0"/>
|
|
206
|
+
<Border Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center" CornerRadius="10" Background="#F2F3F5" Padding="10,3,10,4">
|
|
207
|
+
<TextBlock x:Name="NowText" FontSize="12.5" FontWeight="SemiBold" Foreground="${B.ink}" TextWrapping="Wrap" TextAlignment="Right" LineHeight="18"/>
|
|
208
|
+
</Border>
|
|
209
|
+
</Grid>
|
|
204
210
|
<!-- Tần suất thông báo: 3 nấc (Ít = phiên này + cần xử lý, Vừa = thêm việc trên máy, Tất cả), khối trắng trượt tới nấc đang chọn -->
|
|
205
211
|
<TextBlock x:Name="NotifyFreqLabel" DockPanel.Dock="Top" Margin="0,14,0,6" FontSize="11" FontWeight="SemiBold" Foreground="${B.muted}"/>
|
|
206
212
|
<Grid x:Name="NotifySteps" DockPanel.Dock="Top" Margin="0,0,6,0" Height="30">
|
|
@@ -298,7 +304,7 @@ ${[0, 1, 2].map((i) => ` <Border x:Name="NotifyStep${i}" Tag="${i}" Backgro
|
|
|
298
304
|
<TextBlock x:Name="AskStatus" Visibility="Collapsed" FontSize="13" Foreground="${B.muted}" Margin="0,2,4,1" TextTrimming="CharacterEllipsis"/>
|
|
299
305
|
</StackPanel>
|
|
300
306
|
<!-- Dau x mo o goc phai tren: cat o hoi di ngay, ke ca khi Aivin dang cho tra loi (cau hoi van con, mo lai bang cach re vao bot). -->
|
|
301
|
-
<Button x:Name="AskClose" Visibility="Collapsed" Style="{StaticResource IconBtn}" Width="18" Height="18" Padding="0" Margin="0,
|
|
307
|
+
<Button x:Name="AskClose" Visibility="Collapsed" Style="{StaticResource IconBtn}" Width="18" Height="18" Padding="0" Margin="0,5,5,0" Opacity="0.3"
|
|
302
308
|
HorizontalAlignment="Right" VerticalAlignment="Top" Background="#E8FFFFFF" BorderThickness="0" Tag="#F2F3F5">
|
|
303
309
|
<Path Data="${ICON_CLOSE_X}" Stroke="${B.muted}" StrokeThickness="1.5" StrokeStartLineCap="Round" StrokeEndLineCap="Round"
|
|
304
310
|
Width="9" Height="9" Stretch="Uniform"/>
|
|
@@ -122,7 +122,7 @@ export function requestMascotHide(file = MASCOT_HIDE_FILE) {
|
|
|
122
122
|
fs.writeFileSync(file, String(Date.now()));
|
|
123
123
|
}
|
|
124
124
|
export const HostEvent = Object.freeze({
|
|
125
|
-
READY: 'ready', POS: 'pos', PAUSE: 'pause', RESUME: 'resume', HIDE: 'hide', OFF: 'off', ASK: 'ask', CHOOSE: 'choose', CANCEL: 'cancel', NEW_CHAT: 'new_chat', OPEN_WEBVIEW: 'open_webview',
|
|
125
|
+
READY: 'ready', POS: 'pos', PAUSE: 'pause', RESUME: 'resume', HIDE: 'hide', OFF: 'off', ASK: 'ask', CHOOSE: 'choose', CANCEL: 'cancel', NEW_CHAT: 'new_chat', OPEN_WEBVIEW: 'open_webview', OPEN_LOCAL: 'open_local',
|
|
126
126
|
DROP: 'drop', DETACH: 'detach', AWAY: 'away', BACK: 'back', NOTIFY_FREQ: 'notify_freq', HOTKEYS: 'hotkeys',
|
|
127
127
|
VOICE_START: 'voice_start', VOICE_AUDIO: 'voice_audio', VOICE_INTERRUPT: 'voice_interrupt', VOICE_STOP: 'voice_stop', VOICE_MIC_LOST: 'voice_mic_lost',
|
|
128
128
|
});
|
|
@@ -240,7 +240,7 @@ export function userWindow(w) {
|
|
|
240
240
|
*/
|
|
241
241
|
export function createMascot({
|
|
242
242
|
enabled = true, platform = process.platform, env = process.env, lang: preferredLang, onPause = () => {}, onResume = () => {}, say = () => {},
|
|
243
|
-
onAsk = () => {}, onVoice = () => {}, onChoose = () => {}, onCancel = () => {}, onNewChat = () => {}, onOpenTool = () => {}, onDrop = () => {}, onWorkFolder = () => {}, onDetach = () => {}, onNotifyFreq = () => {},
|
|
243
|
+
onAsk = () => {}, onVoice = () => {}, onChoose = () => {}, onCancel = () => {}, onNewChat = () => {}, onOpenTool = () => {}, onOpenLocal = () => {}, onDrop = () => {}, onWorkFolder = () => {}, onDetach = () => {}, onNotifyFreq = () => {},
|
|
244
244
|
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,
|
|
245
245
|
attachDir = MASCOT_ATTACH_DIR, now = Date.now, timers = { setTimeout, clearTimeout },
|
|
246
246
|
thinkMs = THINK_MS, resultMs = RESULT_MS, mainThrottleMs = MAIN_THROTTLE_MS, offlineGraceMs = OFFLINE_GRACE_MS, restartDelaysMs = RESTART_DELAYS_MS, awayWaveMs = AWAY_WAVE_MS,
|
|
@@ -352,6 +352,8 @@ export function createMascot({
|
|
|
352
352
|
// Nút "Chat mới" trên bảng: phiên chat mới cho linh vật.
|
|
353
353
|
if (msg.t === HostEvent.NEW_CHAT) return onNewChat();
|
|
354
354
|
if (msg.t === HostEvent.OPEN_WEBVIEW) return onOpenTool(msg);
|
|
355
|
+
// Nút mở tệp / thư mục trên máy (thẻ duyệt việc lập trình): cửa sổ chỉ gửi mã, daemon tra + kiểm rồi mới mở (localOpen.mjs).
|
|
356
|
+
if (msg.t === HostEvent.OPEN_LOCAL && typeof msg.id === 'string' && msg.id) return onOpenLocal(msg.id);
|
|
355
357
|
if (msg.t === HostEvent.NOTIFY_FREQ && Number.isFinite(msg.value)) {
|
|
356
358
|
const val = Number(msg.value);
|
|
357
359
|
if (val >= 0 && val <= 2) {
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mở tệp / thư mục TRÊN MÁY từ nút của linh vật (18/11/2026) — thẻ duyệt việc lập trình: "Mở thư mục" dự án, "TEST_CHECK.md".
|
|
3
|
+
*
|
|
4
|
+
* An toàn: đường dẫn đến từ BE, nên cửa sổ không bao giờ tự mở — nó chỉ gửi lại MÃ nút; daemon tra mã ra đường dẫn đã đăng ký rồi kiểm:
|
|
5
|
+
* tuyệt đối, có thật trên máy, không phải đường mạng (\\máy\chia-sẻ — mở là gửi thông tin đăng nhập Windows ra ngoài). Thư mục → mở bằng trình
|
|
6
|
+
* quản lý tệp; tệp TÀI LIỆU (đuôi trong danh sách) → ứng dụng mặc định; mọi tệp khác (exe, bat, ps1, lnk…) KHÔNG chạy — chỉ hiện trong thư mục
|
|
7
|
+
* chứa nó (Explorer /select).
|
|
8
|
+
*/
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { spawn } from 'node:child_process';
|
|
12
|
+
|
|
13
|
+
/** Đuôi tệp mở thẳng bằng ứng dụng mặc định — tài liệu / ảnh / dữ liệu chỉ đọc; không có gì chạy được mã. */
|
|
14
|
+
export const DOCUMENT_EXTS = new Set([
|
|
15
|
+
'md', 'markdown', 'txt', 'log', 'pdf', 'csv', 'tsv', 'json', 'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp',
|
|
16
|
+
'docx', 'xlsx', 'pptx', 'odt', 'ods', 'odp', 'rtf',
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
export const LocalOpenKind = Object.freeze({ FOLDER: 'folder', DOCUMENT: 'document', REVEAL: 'reveal' });
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Hàm thuần (stat tiêm vào được): đường dẫn mở được không và mở kiểu gì. `null` = từ chối (không tuyệt đối / đường mạng / không có trên máy).
|
|
23
|
+
*/
|
|
24
|
+
export function localOpenTarget(p, { stat = fs.statSync, platform = process.platform } = {}) {
|
|
25
|
+
if (typeof p !== 'string' || !p.trim()) return null;
|
|
26
|
+
const raw = p.trim();
|
|
27
|
+
const win = platform === 'win32';
|
|
28
|
+
if (win ? /^[\\/]{2}/.test(raw) : raw.startsWith('//')) return null;
|
|
29
|
+
if (!(win ? path.win32.isAbsolute(raw) && /^[a-z]:[\\/]/i.test(raw) : path.posix.isAbsolute(raw))) return null;
|
|
30
|
+
let st;
|
|
31
|
+
try { st = stat(raw); } catch { return null; }
|
|
32
|
+
if (st.isDirectory()) return { path: raw, kind: LocalOpenKind.FOLDER };
|
|
33
|
+
if (!st.isFile()) return null;
|
|
34
|
+
const ext = path.extname(raw).slice(1).toLowerCase();
|
|
35
|
+
return { path: raw, kind: DOCUMENT_EXTS.has(ext) ? LocalOpenKind.DOCUMENT : LocalOpenKind.REVEAL };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Lệnh mở theo hệ điều hành — hàm thuần. */
|
|
39
|
+
export function localOpenCommand(target, platform = process.platform) {
|
|
40
|
+
if (platform === 'win32') {
|
|
41
|
+
if (target.kind === LocalOpenKind.REVEAL) return { cmd: 'explorer.exe', args: [`/select,"${target.path}"`], verbatim: true };
|
|
42
|
+
return { cmd: 'explorer.exe', args: [`"${target.path}"`], verbatim: true };
|
|
43
|
+
}
|
|
44
|
+
if (platform === 'darwin') return { cmd: 'open', args: target.kind === LocalOpenKind.REVEAL ? ['-R', target.path] : [target.path] };
|
|
45
|
+
return { cmd: 'xdg-open', args: [target.kind === LocalOpenKind.REVEAL ? path.posix.dirname(target.path) : target.path] };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Mở (đã kiểm). Trả loại đã mở, hoặc null khi bị từ chối. */
|
|
49
|
+
export function openLocal(p, { stat, platform = process.platform, spawnImpl = spawn } = {}) {
|
|
50
|
+
const target = localOpenTarget(p, { stat, platform });
|
|
51
|
+
if (!target) return null;
|
|
52
|
+
const { cmd, args, verbatim } = localOpenCommand(target, platform);
|
|
53
|
+
try {
|
|
54
|
+
const child = spawnImpl(cmd, args, { detached: true, stdio: 'ignore', windowsHide: false, ...(verbatim ? { windowsVerbatimArguments: true } : {}) });
|
|
55
|
+
child?.on?.('error', () => undefined);
|
|
56
|
+
child?.unref?.();
|
|
57
|
+
} catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
return target.kind;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Mã nút → đường dẫn đã đăng ký (cửa sổ chỉ cầm mã). Giữ tối đa `max` mục gần nhất. */
|
|
64
|
+
export function createLocalLinkRegistry(max = 200) {
|
|
65
|
+
const byId = new Map();
|
|
66
|
+
let seq = 0;
|
|
67
|
+
return {
|
|
68
|
+
register(p) {
|
|
69
|
+
const id = `l${++seq}`;
|
|
70
|
+
byId.set(id, p);
|
|
71
|
+
if (byId.size > max) byId.delete(byId.keys().next().value);
|
|
72
|
+
return id;
|
|
73
|
+
},
|
|
74
|
+
pathOf: (id) => byId.get(String(id)) ?? null,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Tiền tố url của nút mở trên máy trong lệnh gửi cửa sổ: `local:<mã>`. */
|
|
79
|
+
export const LOCAL_LINK_PREFIX = 'local:';
|
|
@@ -101,6 +101,7 @@ export const MascotText = Object.freeze({
|
|
|
101
101
|
AWAY_NEEDS: 'away_needs',
|
|
102
102
|
ASK_MORE: 'ask_more',
|
|
103
103
|
ASK_OPEN_WEB: 'ask_open_web',
|
|
104
|
+
ASK_LOCAL_OPEN_FAILED: 'ask_local_open_failed',
|
|
104
105
|
ASK_OPEN_IMAGE: 'ask_open_image',
|
|
105
106
|
ASK_OPEN_DIAGRAM: 'ask_open_diagram',
|
|
106
107
|
ASK_WEBVIEW_TITLE: 'ask_webview_title',
|
|
@@ -124,7 +125,7 @@ export const MascotText = Object.freeze({
|
|
|
124
125
|
ASK_NEW_CHAT_DONE: 'ask_new_chat_done',
|
|
125
126
|
ASK_CANCELLED: 'ask_cancelled',
|
|
126
127
|
ASK_ANSWERED_ELSEWHERE: 'ask_answered_elsewhere',
|
|
127
|
-
|
|
128
|
+
FORM_STEP: 'form_step',
|
|
128
129
|
FORM_OPTIONAL: 'form_optional',
|
|
129
130
|
FORM_SKIP: 'form_skip',
|
|
130
131
|
ASK_CONFIRM: 'ask_confirm',
|
|
@@ -250,6 +251,7 @@ const STRINGS = {
|
|
|
250
251
|
[MascotText.AWAY_NEEDS]: "{n} cần bạn",
|
|
251
252
|
[MascotText.ASK_MORE]: "(chi tiết trên Aivin)",
|
|
252
253
|
[MascotText.ASK_OPEN_WEB]: "Xem đầy đủ trên Aivin",
|
|
254
|
+
[MascotText.ASK_LOCAL_OPEN_FAILED]: "Không mở được — tệp / thư mục không còn trên máy này",
|
|
253
255
|
[MascotText.ASK_OPEN_IMAGE]: "Mở ảnh",
|
|
254
256
|
[MascotText.ASK_OPEN_DIAGRAM]: "Xem sơ đồ trên Aivin",
|
|
255
257
|
[MascotText.ASK_WEBVIEW_TITLE]: "Công cụ tương tác",
|
|
@@ -273,8 +275,8 @@ const STRINGS = {
|
|
|
273
275
|
[MascotText.ASK_NEW_CHAT_DONE]: "Đã mở phiên chat mới",
|
|
274
276
|
[MascotText.ASK_CANCELLED]: "Đã dừng",
|
|
275
277
|
[MascotText.ASK_ANSWERED_ELSEWHERE]: "Câu hỏi này đã được trả lời ở nơi khác",
|
|
276
|
-
[MascotText.
|
|
277
|
-
[MascotText.FORM_OPTIONAL]: "
|
|
278
|
+
[MascotText.FORM_STEP]: "Bước {n}/{total}",
|
|
279
|
+
[MascotText.FORM_OPTIONAL]: "Không bắt buộc",
|
|
278
280
|
[MascotText.FORM_SKIP]: "Bỏ qua",
|
|
279
281
|
[MascotText.ASK_CONFIRM]: "Xác nhận ({n})",
|
|
280
282
|
[MascotText.NOTIFY_DONE]: "Xong",
|
|
@@ -390,6 +392,7 @@ const STRINGS = {
|
|
|
390
392
|
[MascotText.AWAY_NEEDS]: "{n} need you",
|
|
391
393
|
[MascotText.ASK_MORE]: "(details in Aivin)",
|
|
392
394
|
[MascotText.ASK_OPEN_WEB]: "View in Aivin",
|
|
395
|
+
[MascotText.ASK_LOCAL_OPEN_FAILED]: "Can't open — the file or folder is no longer on this computer",
|
|
393
396
|
[MascotText.ASK_OPEN_IMAGE]: "Open image",
|
|
394
397
|
[MascotText.ASK_OPEN_DIAGRAM]: "View diagram in Aivin",
|
|
395
398
|
[MascotText.ASK_WEBVIEW_TITLE]: "Interactive tool",
|
|
@@ -413,8 +416,8 @@ const STRINGS = {
|
|
|
413
416
|
[MascotText.ASK_NEW_CHAT_DONE]: "Started a new chat",
|
|
414
417
|
[MascotText.ASK_CANCELLED]: "Stopped",
|
|
415
418
|
[MascotText.ASK_ANSWERED_ELSEWHERE]: "This question was already answered elsewhere",
|
|
416
|
-
[MascotText.
|
|
417
|
-
[MascotText.FORM_OPTIONAL]: "
|
|
419
|
+
[MascotText.FORM_STEP]: "Step {n} of {total}",
|
|
420
|
+
[MascotText.FORM_OPTIONAL]: "Optional",
|
|
418
421
|
[MascotText.FORM_SKIP]: "Skip",
|
|
419
422
|
[MascotText.ASK_CONFIRM]: "Confirm ({n})",
|
|
420
423
|
[MascotText.NOTIFY_DONE]: "Done",
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { writeFileAtomic } from './atomicFile.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Vé LightCode của Cloud Computer (24/11/2026). BE cấp vé loại managed (Ed25519, hạn tối đa 6 giờ, ràng machine-id của lần bật máy này):
|
|
7
|
+
* - Lúc tạo container: env AIVIN_LIGHTCODE_LICENSE_KEY — entrypoint.sh ghi vào tệp rồi xoá env (thành viên không đọc được).
|
|
8
|
+
* - Giữa chừng: sự kiện socket BE → CLI `org_computer.license_renew` { token, expiresAt? } — module này ghi đè tệp nguyên tử.
|
|
9
|
+
*
|
|
10
|
+
* Tệp vé thuộc tài khoản daemon LightCode (không phải root, không phải thành viên), thư mục chứa 0700 → LightCode đọc được, thành viên
|
|
11
|
+
* không. CLI chạy root (có DAC_OVERRIDE/CHOWN) nên ghi + đổi chủ được. Token KHÔNG bao giờ vào log / ack / thông báo lỗi.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export const LICENSE_RENEW_EVENT = 'org_computer.license_renew';
|
|
15
|
+
export const LOG_TAG = '[ORG_COMPUTER_LICENSE]';
|
|
16
|
+
/** Khớp LCAGENT_LICENSE_FILE mà entrypoint.sh đặt cho daemon LightCode. */
|
|
17
|
+
export const DEFAULT_LICENSE_FILE = '/var/lib/aivin-lc/lightcode-license.key';
|
|
18
|
+
/** LightCode (server/src/license/license.ts readManagedLicenseKey) chỉ nhận khoá bắt đầu `LCA1.` và dài ≤ 2000 ký tự. */
|
|
19
|
+
export const TICKET_PREFIX = 'LCA1.';
|
|
20
|
+
export const TICKET_MAX_LENGTH = 2000;
|
|
21
|
+
const TICKET_RE = /^LCA1\.[A-Za-z0-9._~+/=-]+$/;
|
|
22
|
+
|
|
23
|
+
export const RenewReason = Object.freeze({
|
|
24
|
+
BAD_PAYLOAD: 'bad_payload',
|
|
25
|
+
BAD_TOKEN: 'bad_token',
|
|
26
|
+
BAD_EXPIRES: 'bad_expires',
|
|
27
|
+
EXPIRED: 'expired',
|
|
28
|
+
NOT_ENABLED: 'not_enabled',
|
|
29
|
+
WRITE_FAILED: 'write_failed',
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
export function licenseFilePath(env = process.env) {
|
|
33
|
+
return String(env.AIVIN_LIGHTCODE_LICENSE_FILE || '').trim() || DEFAULT_LICENSE_FILE;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** `expiresAt` (ISO hoặc mili-giây) → mili-giây, hoặc null nếu không phải thời điểm hợp lệ. */
|
|
37
|
+
function toMillis(value) {
|
|
38
|
+
if (typeof value === 'number') return Number.isFinite(value) && value > 0 ? value : null;
|
|
39
|
+
if (typeof value === 'string' && value.trim()) {
|
|
40
|
+
const ms = Date.parse(value);
|
|
41
|
+
return Number.isFinite(ms) ? ms : null;
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Kiểm tra payload — trả { ok: true, token } hoặc { ok: false, reason }. Không ném lỗi, kết quả lỗi không chứa token. */
|
|
47
|
+
export function validateRenewPayload(payload, now = Date.now()) {
|
|
48
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return { ok: false, reason: RenewReason.BAD_PAYLOAD };
|
|
49
|
+
const token = typeof payload.token === 'string' ? payload.token.trim() : '';
|
|
50
|
+
if (!token || token.length > TICKET_MAX_LENGTH || !TICKET_RE.test(token)) return { ok: false, reason: RenewReason.BAD_TOKEN };
|
|
51
|
+
if (payload.expiresAt !== undefined && payload.expiresAt !== null) {
|
|
52
|
+
const exp = toMillis(payload.expiresAt);
|
|
53
|
+
if (exp === null) return { ok: false, reason: RenewReason.BAD_EXPIRES };
|
|
54
|
+
if (exp <= now) return { ok: false, reason: RenewReason.EXPIRED };
|
|
55
|
+
}
|
|
56
|
+
return { ok: true, token };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Chủ của thư mục chứa vé = tài khoản daemon LightCode; chưa có thư mục này = image không bật LightCode. */
|
|
60
|
+
function daemonOwner(dir) {
|
|
61
|
+
try {
|
|
62
|
+
const st = fs.statSync(dir);
|
|
63
|
+
return st.isDirectory() ? { uid: st.uid, gid: st.gid } : null;
|
|
64
|
+
} catch { return null; }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Ghi vé ra tệp: nguyên tử (tệp tạm cạnh bên + đổi tên đè), 0600, đổi chủ cho tài khoản daemon. Trả { ok } hoặc { ok:false, reason }.
|
|
69
|
+
* Tệp tạm cũng 0600 và nằm trong thư mục 0700 nên không có lúc nào thành viên đọc được. Nếu đổi chủ lỗi, tệp vẫn thuộc root (daemon
|
|
70
|
+
* không đọc được) → báo write_failed để BE thử lại, không im lặng.
|
|
71
|
+
*/
|
|
72
|
+
export function writeLicenseFile(file, token, { ownerOf = daemonOwner, chown = fs.chownSync, writeAtomic = writeFileAtomic } = {}) {
|
|
73
|
+
const owner = ownerOf(path.dirname(file));
|
|
74
|
+
if (!owner) return { ok: false, reason: RenewReason.NOT_ENABLED };
|
|
75
|
+
try {
|
|
76
|
+
writeAtomic(file, `${token}\n`, { mode: 0o600 });
|
|
77
|
+
if (process.platform !== 'win32') chown(file, owner.uid, owner.gid);
|
|
78
|
+
return { ok: true };
|
|
79
|
+
} catch {
|
|
80
|
+
return { ok: false, reason: RenewReason.WRITE_FAILED };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Bộ xử lý sự kiện `org_computer.license_renew`: (payload, ack). Luôn ack — `{ ok: true }` hoặc `{ ok: false, reason }` (mã cố định,
|
|
86
|
+
* không có token / đường dẫn).
|
|
87
|
+
*/
|
|
88
|
+
export function createLicenseRenewHandler({ file = licenseFilePath(), now = () => Date.now(), write = writeLicenseFile, log = () => {} } = {}) {
|
|
89
|
+
return (payload, ack) => {
|
|
90
|
+
const reply = typeof ack === 'function' ? ack : () => {};
|
|
91
|
+
const checked = validateRenewPayload(payload, now());
|
|
92
|
+
if (!checked.ok) { log(`${LOG_TAG} từ chối: ${checked.reason}`); reply({ ok: false, reason: checked.reason }); return checked; }
|
|
93
|
+
const res = write(file, checked.token);
|
|
94
|
+
// Chỉ ghi mã lý do cố định — không bao giờ token / đường dẫn.
|
|
95
|
+
log(res.ok ? `${LOG_TAG} đã gia hạn vé LightCode` : `${LOG_TAG} ghi vé thất bại: ${res.reason}`);
|
|
96
|
+
reply(res.ok ? { ok: true } : { ok: false, reason: res.reason });
|
|
97
|
+
return res;
|
|
98
|
+
};
|
|
99
|
+
}
|
|
@@ -21,15 +21,25 @@ import { buildOfficeTools } from './office/index.mjs';
|
|
|
21
21
|
import { measurePath } from './undoStore.mjs';
|
|
22
22
|
import { buildProcessTools, shellCommand } from './processes.mjs';
|
|
23
23
|
import { buildAgentTools, createAgentRunner } from './codingAgents.mjs';
|
|
24
|
+
import { buildLightcodeTools } from './lightcodeAgent.mjs';
|
|
24
25
|
import { buildLocalLlmTools, createLocalLlm } from './localLlm.mjs';
|
|
26
|
+
import { buildLlmLoginTools, createLlmLogin } from './localLlmLogin.mjs';
|
|
27
|
+
import { buildCommandAuthEnv, redactAuthText } from './ephemeralAuth.mjs';
|
|
25
28
|
|
|
26
29
|
/** Một bộ chạy agent lập trình cho cả tiến trình (việc đang chạy sống qua các lần dựng lại danh mục công cụ). */
|
|
27
30
|
let sharedAgents = null;
|
|
31
|
+
/** Máy tính tổ chức: một runner job lập trình cho mỗi thành viên (tiến trình con dưới tài khoản của họ, thư mục job riêng). */
|
|
32
|
+
const memberAgents = new Map();
|
|
33
|
+
/** Thư mục job của thành viên trên máy tổ chức (ngoài HOME của họ — không tính vào hạn mức đĩa, không lẫn tệp của họ). */
|
|
34
|
+
const MEMBER_JOBS_ROOT = '/var/lib/aivin-jobs';
|
|
28
35
|
/** Bộ chạy agent đã dựng (null khi máy chưa có danh mục agent) — daemon hỏi để biết còn job chạy không, và dừng chúng khi tắt. */
|
|
29
36
|
export const activeAgentRunner = () => sharedAgents;
|
|
30
37
|
/** Mô hình trên máy cho BE (`llm.complete`) — giữ tiến trình sẵn qua các lần dựng lại danh mục. */
|
|
31
38
|
let sharedLlm = null;
|
|
32
39
|
export const activeLocalLlm = () => sharedLlm;
|
|
40
|
+
/** Đăng nhập agent cho thành viên máy tính tổ chức (localLlmLogin.mjs) — lần đăng nhập đang chờ sống qua các lần dựng lại danh mục. */
|
|
41
|
+
let sharedLlmLogin = null;
|
|
42
|
+
export const activeLlmLogin = () => sharedLlmLogin;
|
|
33
43
|
import { buildScheduleTools } from './schedule.mjs';
|
|
34
44
|
import { buildWatchTools } from './deviceWatches.mjs';
|
|
35
45
|
import { buildTransferTools } from './httpTransfer.mjs';
|
|
@@ -682,7 +692,16 @@ async function shellExec(args, ctx, env) {
|
|
|
682
692
|
assertCommandAllowed(command);
|
|
683
693
|
const cwd = resolveInRoots(env.roots, args.cwd || '');
|
|
684
694
|
const [cmd, argv] = shellCommand(command);
|
|
685
|
-
const
|
|
695
|
+
const { env: authExtra, secrets } = buildCommandAuthEnv(env.authEnv, command);
|
|
696
|
+
const procEnv = secrets.length || Object.keys(authExtra).length ? { ...agentEnv(), ...authExtra } : undefined;
|
|
697
|
+
const onOutput = secrets.length && ctx.onOutput
|
|
698
|
+
? (stream, chunk) => ctx.onOutput(stream, redactAuthText(chunk, secrets))
|
|
699
|
+
: ctx.onOutput;
|
|
700
|
+
const result = await runProcess(cmd, argv, { cwd, signal: ctx.signal, onOutput, runAs: env.runAs, ...(procEnv ? { env: procEnv } : {}) });
|
|
701
|
+
if (secrets.length) {
|
|
702
|
+
result.stdout = redactAuthText(result.stdout, secrets);
|
|
703
|
+
result.stderr = redactAuthText(result.stderr, secrets);
|
|
704
|
+
}
|
|
686
705
|
return { command, cwd: displayPath(env.roots, cwd), ...result };
|
|
687
706
|
}
|
|
688
707
|
|
|
@@ -844,10 +863,31 @@ export function buildTools(env) {
|
|
|
844
863
|
// Giao việc cho agent lập trình trên máy (Claude Code…, chế độ không giao diện, có phiên nói tiếp) — máy cá nhân có cài ít nhất một agent.
|
|
845
864
|
if (env.processes && env.schedules && !env.runAs) {
|
|
846
865
|
sharedAgents ||= env.codingAgents || createAgentRunner();
|
|
847
|
-
|
|
848
|
-
//
|
|
866
|
+
// LightCode (20/11/2026): xem / cài bên thực thi cho hợp đồng lập trình — máy Windows của một người (cài cần người đồng ý: sàn luật
|
|
867
|
+
// tại máy luôn hỏi lightcode.install, BE luôn hỏi duyệt trong chat). Có LightCode thì agent.run luôn có mặt: máy chưa có agent nào
|
|
868
|
+
// cài LightCode giữa chừng vẫn nhận được hợp đồng ngay (agent.run tự định vị lại LightCode lúc giao).
|
|
869
|
+
const lightcode = process.platform === 'win32' && !env.noLightcode;
|
|
870
|
+
if (sharedAgents.installed().length || lightcode) tools.push(...buildAgentTools(sharedAgents));
|
|
871
|
+
if (lightcode) tools.push(...buildLightcodeTools({ onInstalled: env.announceProfile, roots: env.roots }));
|
|
872
|
+
} else if (env.processes && env.runAs && env.localLlm?.memberMode) {
|
|
873
|
+
// Máy tính tổ chức (17/11/2026): thành viên giao việc lập trình chạy bằng agent họ đã đăng nhập (Claude Code / Codex cài sẵn trong image),
|
|
874
|
+
// dưới tài khoản Linux của họ, trong thư mục của họ.
|
|
875
|
+
const name = env.runAs.name;
|
|
876
|
+
if (!memberAgents.has(name)) memberAgents.set(name, env.codingAgents || createAgentRunner({ runAs: env.runAs, jobsDir: path.join(MEMBER_JOBS_ROOT, name) }));
|
|
877
|
+
const runner = memberAgents.get(name);
|
|
878
|
+
if (runner.installed().length) tools.push(...buildAgentTools(runner));
|
|
879
|
+
}
|
|
880
|
+
// Claude Code / Codex làm mô hình cho BE (không công cụ, không tệp) — BE chọn khi phiên chat gắn với máy này. Máy tính tổ chức
|
|
881
|
+
// (`env.localLlm.memberMode`): mỗi lời gọi chạy dưới tài khoản của thành viên, bằng đăng nhập agent của chính họ (+ công cụ đăng nhập).
|
|
882
|
+
if (env.processes && !env.runAs && (env.schedules || env.localLlm?.memberMode)) {
|
|
849
883
|
sharedLlm ||= env.localLlm || createLocalLlm();
|
|
850
|
-
if (sharedLlm.available())
|
|
884
|
+
if (sharedLlm.available()) {
|
|
885
|
+
tools.push(...buildLocalLlmTools(sharedLlm));
|
|
886
|
+
if (sharedLlm.memberMode) {
|
|
887
|
+
sharedLlmLogin ||= createLlmLogin({ llm: sharedLlm });
|
|
888
|
+
tools.push(...buildLlmLoginTools(sharedLlmLogin));
|
|
889
|
+
}
|
|
890
|
+
}
|
|
851
891
|
}
|
|
852
892
|
// Lịch chạy định kỳ (Task Scheduler / crontab) — máy cá nhân; máy tính tổ chức không đặt lịch cho thành viên.
|
|
853
893
|
if (env.schedules) tools.push(...buildScheduleTools(env.schedules));
|