@aivin-labs/cli 1.0.13 → 1.0.21

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 (72) hide show
  1. package/README.md +325 -304
  2. package/bin/cli.mjs +97 -18
  3. package/bin/lib/localPreview.mjs +437 -0
  4. package/bin/lib/openFile.mjs +235 -0
  5. package/bin/lib/previewCache.mjs +71 -0
  6. package/bin/lib/remote/atomicFile.mjs +32 -0
  7. package/bin/lib/remote/autoStart.mjs +2 -1
  8. package/bin/lib/remote/autoUpdate.mjs +12 -0
  9. package/bin/lib/remote/callLedger.mjs +21 -0
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -2
  11. package/bin/lib/remote/client.mjs +1024 -889
  12. package/bin/lib/remote/codingAgents.mjs +2 -2
  13. package/bin/lib/remote/constants.mjs +261 -251
  14. package/bin/lib/remote/credentials.mjs +81 -4
  15. package/bin/lib/remote/daemonLock.mjs +57 -17
  16. package/bin/lib/remote/desktop/castInput.mjs +98 -0
  17. package/bin/lib/remote/desktop/desktopCast.mjs +334 -198
  18. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
  19. package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -514
  20. package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -95
  21. package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
  22. package/bin/lib/remote/desktop/index.mjs +21 -7
  23. package/bin/lib/remote/desktop/linuxTraySource.mjs +1 -8
  24. package/bin/lib/remote/desktop/macTraySource.mjs +0 -2
  25. package/bin/lib/remote/desktop/strings.mjs +28 -2
  26. package/bin/lib/remote/desktop/traySource.mjs +380 -16
  27. package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
  28. package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
  29. package/bin/lib/remote/fileIndexer.mjs +30 -14
  30. package/bin/lib/remote/folderRules.mjs +3 -0
  31. package/bin/lib/remote/gitSafe.mjs +31 -0
  32. package/bin/lib/remote/gui/index.mjs +66 -24
  33. package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
  34. package/bin/lib/remote/gui/windowsHost.mjs +3 -1
  35. package/bin/lib/remote/gui/windowsHostSource.mjs +291 -60
  36. package/bin/lib/remote/httpTransfer.mjs +64 -3
  37. package/bin/lib/remote/localPolicy.mjs +73 -7
  38. package/bin/lib/remote/mascot/ask.mjs +207 -42
  39. package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
  40. package/bin/lib/remote/mascot/askHostSource.mjs +658 -530
  41. package/bin/lib/remote/mascot/blocks.mjs +201 -0
  42. package/bin/lib/remote/mascot/bot.mjs +26 -2
  43. package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
  44. package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
  45. package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
  46. package/bin/lib/remote/mascot/fileChips.mjs +62 -0
  47. package/bin/lib/remote/mascot/hostSource.mjs +328 -49
  48. package/bin/lib/remote/mascot/hotkey.mjs +31 -7
  49. package/bin/lib/remote/mascot/images.mjs +111 -0
  50. package/bin/lib/remote/mascot/index.mjs +663 -493
  51. package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
  52. package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
  53. package/bin/lib/remote/mascot/mood.mjs +57 -0
  54. package/bin/lib/remote/mascot/rigSource.mjs +643 -609
  55. package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
  56. package/bin/lib/remote/mascot/strings.mjs +456 -375
  57. package/bin/lib/remote/mascot/ui.mjs +27 -7
  58. package/bin/lib/remote/multiUser.mjs +7 -2
  59. package/bin/lib/remote/notify.mjs +4 -1
  60. package/bin/lib/remote/office/index.mjs +12 -6
  61. package/bin/lib/remote/processes.mjs +5 -2
  62. package/bin/lib/remote/sandbox.mjs +26 -0
  63. package/bin/lib/remote/secretPaths.mjs +21 -0
  64. package/bin/lib/remote/tokenRotation.mjs +28 -0
  65. package/bin/lib/remote/toolHandlers.mjs +79 -15
  66. package/bin/lib/remote/watchBatcher.mjs +56 -0
  67. package/bin/lib/selfUpdate.mjs +12 -2
  68. package/bin/lib/update/binarySwap.mjs +15 -1
  69. package/bin/lib/update/state.mjs +10 -0
  70. package/docs/CLI.md +42 -1
  71. package/docs/media/aivin-ecosystem.jpg +0 -0
  72. package/package.json +7 -3
@@ -0,0 +1,154 @@
1
+ import { spawn } from 'child_process';
2
+ import { createHash } from 'crypto';
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import { gunzipSync } from 'zlib';
6
+ import { REMOTE_CONFIG_DIR } from '../constants.mjs';
7
+
8
+ /**
9
+ * Dựng sơ đồ và mở công cụ tương tác cho linh vật (03/11/2026). WPF không chạy được JavaScript hiện đại nên dùng trình duyệt có sẵn trên máy (Edge luôn có trên
10
+ * Windows 10/11, không có thì Chrome):
11
+ * - Sơ đồ: Mermaid (cùng thư viện với web, đóng gói trong CLI) chạy trong trình duyệt không giao diện, chặn hẳn mạng (`--host-resolver-rules`), hồ sơ riêng,
12
+ * `securityLevel: strict`; đo cỡ rồi chụp thành PNG. Không dựng được → null, nơi gọi đổi thành nút mở trên web.
13
+ * - Công cụ tương tác: cửa sổ ứng dụng riêng (`--app`), HTML của AI nằm trong iframe `sandbox="allow-scripts allow-modals"` — cùng cờ với web: origin riêng, không
14
+ * đọc được tệp trên máy, không điều hướng được trang ngoài, không mở cửa sổ khác. Chỉ mở khi chủ máy bấm.
15
+ */
16
+ export const MASCOT_RENDER_DIR = path.join(REMOTE_CONFIG_DIR, 'mascot-render');
17
+ const RENDER_TIMEOUT_MS = 20000;
18
+ const KEEP_IMAGES = 40;
19
+ const DIAGRAM_PADDING = 16;
20
+ const MAX_SIDE = 4000;
21
+ const BROWSER_PATHS = [
22
+ ['ProgramFiles(x86)', 'Microsoft\\Edge\\Application\\msedge.exe'],
23
+ ['ProgramFiles', 'Microsoft\\Edge\\Application\\msedge.exe'],
24
+ ['LOCALAPPDATA', 'Microsoft\\Edge\\Application\\msedge.exe'],
25
+ ['ProgramFiles', 'Google\\Chrome\\Application\\chrome.exe'],
26
+ ['ProgramFiles(x86)', 'Google\\Chrome\\Application\\chrome.exe'],
27
+ ['LOCALAPPDATA', 'Google\\Chrome\\Application\\chrome.exe'],
28
+ ];
29
+ const SIZE_MARK = /<title>OK (\d+) (\d+)<\/title>/;
30
+
31
+ export function findBrowser(env = process.env, exists = fs.existsSync) {
32
+ for (const [base, rel] of BROWSER_PATHS) {
33
+ const file = env[base] ? path.win32.join(env[base], rel) : null;
34
+ if (file && exists(file)) return file;
35
+ }
36
+ return null;
37
+ }
38
+
39
+ const fileUrl = (file) => `file:///${path.resolve(file).replace(/\\/g, '/').split('/').map(encodeURIComponent).join('/').replace(/^([A-Za-z])%3A/, '$1:')}`;
40
+
41
+ /** Chạy trình duyệt không giao diện, trả stdout; quá giờ / lỗi → ném. */
42
+ function runHeadless(browser, args, { spawnImpl, timeoutMs }) {
43
+ return new Promise((resolve, reject) => {
44
+ const child = spawnImpl(browser, args, { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
45
+ let out = '';
46
+ const timer = setTimeout(() => { child.kill(); reject(new Error('timeout')); }, timeoutMs);
47
+ timer.unref?.();
48
+ child.stdout?.on('data', (d) => { out += d; });
49
+ child.on('error', (e) => { clearTimeout(timer); reject(e); });
50
+ child.on('close', () => { clearTimeout(timer); resolve(out); });
51
+ });
52
+ }
53
+
54
+ /** Chuỗi JSON đặt được trong thẻ script: `</script>` trong sơ đồ không thoát ra ngoài. */
55
+ const scriptSafeJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');
56
+
57
+ function diagramPage(source, mermaidFile, size) {
58
+ return `<!doctype html><html><head><meta charset="utf-8"><title>WAIT</title><style>html,body{margin:0;background:#fff}#d{display:inline-block;padding:${DIAGRAM_PADDING / 2}px}</style></head><body><div id="d"></div>
59
+ <script src="${path.basename(mermaidFile)}"></script>
60
+ <script>
61
+ var source = ${scriptSafeJson(source)};
62
+ mermaid.initialize({ startOnLoad: false, securityLevel: 'strict', theme: 'base', fontFamily: 'Segoe UI, sans-serif',
63
+ themeVariables: { fontFamily: 'Segoe UI, sans-serif', fontSize: '14px', primaryColor: '#EFF6FF', primaryBorderColor: '#93C5FD', primaryTextColor: '#1D2129', lineColor: '#86909C', secondaryColor: '#F5F3FF', tertiaryColor: '#F7F8FA' } });
64
+ mermaid.render('g', source).then(function (r) {
65
+ var d = document.getElementById('d'); d.innerHTML = r.svg;
66
+ var svg = d.querySelector('svg'); var box = svg.viewBox.baseVal; var w = Math.ceil(box.width || svg.getBoundingClientRect().width); var h = Math.ceil(box.height || svg.getBoundingClientRect().height);
67
+ svg.style.maxWidth = 'none'; svg.setAttribute('width', w); svg.setAttribute('height', h);
68
+ document.title = 'OK ' + w + ' ' + h;
69
+ }).catch(function (e) { document.title = 'FAIL'; });
70
+ </script>${size ? '' : ''}</body></html>`;
71
+ }
72
+
73
+ /** Tệp mermaid.min.js trong thư mục dựng: giải nén một lần theo phiên bản, chỉ khi gặp sơ đồ đầu tiên (bộ nén nặng ~1 MB, không nạp lúc daemon khởi động). */
74
+ async function ensureMermaid(dir) {
75
+ const { MERMAID_GZ_BASE64, MERMAID_VERSION } = await import('./mermaidBundle.mjs');
76
+ const file = path.join(dir, `mermaid-${MERMAID_VERSION}.min.js`);
77
+ if (!fs.existsSync(file)) {
78
+ const tmp = `${file}.tmp${process.pid}`;
79
+ fs.writeFileSync(tmp, gunzipSync(Buffer.from(MERMAID_GZ_BASE64, 'base64')));
80
+ fs.renameSync(tmp, file);
81
+ }
82
+ return file;
83
+ }
84
+
85
+ function pruneImages(dir) {
86
+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.png')).map((name) => {
87
+ const file = path.join(dir, name);
88
+ return { file, at: fs.statSync(file).mtimeMs };
89
+ }).sort((a, b) => b.at - a.at);
90
+ for (const { file } of files.slice(KEEP_IMAGES)) fs.rmSync(file, { force: true });
91
+ }
92
+
93
+ /** Mỗi lúc một sơ đồ: mỗi lần dựng mở một tiến trình trình duyệt. */
94
+ let queue = Promise.resolve();
95
+
96
+ /** Mã Mermaid → đường dẫn PNG (dùng lại nếu đã dựng), không dựng được → null. Không ném lỗi. */
97
+ export function renderDiagram(source, { dir = MASCOT_RENDER_DIR, browser = findBrowser(), spawnImpl = spawn, timeoutMs = RENDER_TIMEOUT_MS } = {}) {
98
+ const run = async () => {
99
+ if (!browser) return null;
100
+ const name = createHash('sha256').update(String(source)).digest('hex').slice(0, 32);
101
+ const png = path.join(dir, `${name}.png`);
102
+ const page = path.join(dir, `${name}.html`);
103
+ try {
104
+ fs.mkdirSync(dir, { recursive: true });
105
+ if (fs.existsSync(png)) return png;
106
+ const mermaidFile = await ensureMermaid(dir);
107
+ fs.writeFileSync(page, diagramPage(String(source), mermaidFile));
108
+ const base = [
109
+ '--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check', '--disable-extensions', '--disable-sync', '--disable-background-networking',
110
+ '--disable-component-update', '--host-resolver-rules=MAP * ~NOTFOUND', `--user-data-dir=${path.join(dir, 'profile')}`, '--virtual-time-budget=8000',
111
+ ];
112
+ // Lượt đầu đo cỡ sơ đồ, lượt sau chụp đúng cỡ đó, độ phân giải gấp đôi để thu nhỏ trong ô hỏi vẫn nét.
113
+ const dom = await runHeadless(browser, [...base, '--dump-dom', fileUrl(page)], { spawnImpl, timeoutMs });
114
+ const size = String(dom).match(SIZE_MARK);
115
+ if (!size) return null;
116
+ const w = Math.min(MAX_SIDE, Number(size[1]) + DIAGRAM_PADDING);
117
+ const h = Math.min(MAX_SIDE, Number(size[2]) + DIAGRAM_PADDING);
118
+ await runHeadless(browser, [...base, '--force-device-scale-factor=2', '--hide-scrollbars', `--window-size=${w},${h}`, `--screenshot=${png}`, fileUrl(page)], { spawnImpl, timeoutMs });
119
+ if (!fs.existsSync(png)) return null;
120
+ pruneImages(dir);
121
+ return png;
122
+ } catch {
123
+ return null;
124
+ } finally {
125
+ fs.rmSync(page, { force: true });
126
+ }
127
+ };
128
+ const result = queue.then(run, run);
129
+ queue = result.catch(() => null);
130
+ return result;
131
+ }
132
+
133
+ const escapeAttr = (s) => String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
134
+
135
+ /** Trang bọc công cụ tương tác: bản thân trang không có script, mọi thứ của AI nằm trong iframe sandbox (cùng cờ `WebViewRenderer` trên web). */
136
+ export function webviewPage(html, title) {
137
+ return `<!doctype html><html><head><meta charset="utf-8"><title>${escapeAttr(title)}</title><style>html,body{margin:0;height:100%;background:#fff}iframe{border:0;width:100%;height:100%;display:block}</style></head><body><iframe sandbox="allow-scripts allow-modals" referrerpolicy="no-referrer" srcdoc="${escapeAttr(html)}"></iframe></body></html>`;
138
+ }
139
+
140
+ /** Mở công cụ tương tác trong cửa sổ riêng. Không có trình duyệt → false, nơi gọi mở phiên trên web. */
141
+ export function openWebview(html, title, { dir = MASCOT_RENDER_DIR, browser = findBrowser(), spawnImpl = spawn } = {}) {
142
+ if (!browser) return false;
143
+ try {
144
+ fs.mkdirSync(dir, { recursive: true });
145
+ const file = path.join(dir, `webview-${createHash('sha256').update(html).digest('hex').slice(0, 24)}.html`);
146
+ fs.writeFileSync(file, webviewPage(html, title));
147
+ const child = spawnImpl(browser, [`--app=${fileUrl(file)}`, '--window-size=560,720', '--no-first-run', '--no-default-browser-check'], { stdio: 'ignore', detached: true, windowsHide: false });
148
+ child.on?.('error', () => {});
149
+ child.unref?.();
150
+ return true;
151
+ } catch {
152
+ return false;
153
+ }
154
+ }
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Emoji màu trong cửa sổ linh vật (03/11/2026) — mã C# biên dịch trong host.ps1 (cùng khối Add-Type với AivinMascot.Native).
3
+ *
4
+ * WPF trên .NET Framework không vẽ được font màu: emoji trong TextBlock ra một màu theo chữ, kể cả khi đặt font Segoe UI Emoji. DirectWrite /
5
+ * Direct2D vẽ được nhưng phải gọi COM qua PowerShell, dễ sập cả tiến trình; nên ở đây đọc thẳng bảng màu của font (COLR + CPAL):
6
+ * mỗi emoji là vài lớp glyph, mỗi lớp một màu, vẽ chồng thành hình vector rồi đặt vào dòng chữ bằng InlineUIContainer.
7
+ *
8
+ * - Ghép chuỗi emoji (tông da, ZWJ, keycap) theo các bảng ghép mặc định của font (GSUB); không ghép được thì vẽ từng emoji rời.
9
+ * - Chỉ đọc font khi gặp emoji đầu tiên. Máy không có font / font không có bảng màu → chữ thường như trước, không bao giờ làm hỏng cửa sổ.
10
+ * - Ký hiệu không phải emoji (✓ ✕ → ●) không có lớp màu nên vẫn là chữ. Ký tự có hai dạng (©, mũi tên, số) chỉ thành emoji khi có U+FE0F.
11
+ * - Ô nhập (TextBox) không chứa được hình: emoji chủ máy đang gõ vẫn một màu, gửi đi hiện dòng chat thì có màu.
12
+ * Giữ toàn ASCII (xem hostSource.mjs).
13
+ */
14
+ export const EMOJI_CS = String.raw`
15
+ public static class Emoji {
16
+ const int VS15 = 0xFE0E, VS16 = 0xFE0F, ZWJ = 0x200D, KEYCAP = 0x20E3;
17
+ /** Bang mac dinh cua shaper: ngoai cac feature nay la bien the tuy chon, khong tu ap dung. */
18
+ static readonly HashSet<string> LigFeatures = new HashSet<string> { "ccmp", "liga", "rlig", "clig" };
19
+ /** Ke hoach mot lan doc font: false = chua doc, face == null sau khi doc = khong co bang mau. */
20
+ static bool loaded;
21
+ static GlyphTypeface face;
22
+ static IDictionary<int, ushort> cmap;
23
+ static Dictionary<ushort, int> baseFirst, baseCount;
24
+ static ushort[] layerGlyphs, layerPalette;
25
+ static byte[] colors;
26
+ static List<Dictionary<ushort, List<ushort[]>>> ligLookups;
27
+ static readonly Dictionary<ushort, DrawingImage> images = new Dictionary<ushort, DrawingImage>();
28
+ /** Cao / rong hinh so voi co chu: nhich lon hon chu mot chut nhu emoji tren web. */
29
+ const double ImageScale = 1.2;
30
+ const double MinBoxOfAdvance = 0.8;
31
+
32
+ static int U16(byte[] f, long o) { return (f[o] << 8) | f[o + 1]; }
33
+ static long U32(byte[] f, long o) { return ((long)f[o] << 24) | ((long)f[o + 1] << 16) | ((long)f[o + 2] << 8) | f[o + 3]; }
34
+
35
+ static void Load() {
36
+ loaded = true;
37
+ try {
38
+ string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "seguiemj.ttf");
39
+ if (!File.Exists(file)) return;
40
+ byte[] f = File.ReadAllBytes(file);
41
+ var tables = new Dictionary<string, long>();
42
+ int n = U16(f, 4);
43
+ for (int i = 0; i < n; i++) { long r = 12 + 16 * i; tables[Encoding.ASCII.GetString(f, (int)r, 4)] = U32(f, r + 8); }
44
+ if (!tables.ContainsKey("COLR") || !tables.ContainsKey("CPAL")) return;
45
+ if (!ReadColors(f, tables["COLR"], tables["CPAL"])) return;
46
+ ligLookups = new List<Dictionary<ushort, List<ushort[]>>>();
47
+ if (tables.ContainsKey("GSUB")) { try { ReadLigatures(f, tables["GSUB"]); } catch { ligLookups.Clear(); } }
48
+ var g = new GlyphTypeface(new Uri(file));
49
+ cmap = g.CharacterToGlyphMap;
50
+ face = g;
51
+ } catch { face = null; }
52
+ }
53
+
54
+ static bool ReadColors(byte[] f, long colr, long cpal) {
55
+ int bases = U16(f, colr + 2); long baseAt = colr + U32(f, colr + 4); long layerAt = colr + U32(f, colr + 8); int layers = U16(f, colr + 12);
56
+ if (bases == 0 || layers == 0) return false;
57
+ baseFirst = new Dictionary<ushort, int>(bases); baseCount = new Dictionary<ushort, int>(bases);
58
+ for (int i = 0; i < bases; i++) {
59
+ long r = baseAt + 6 * i; ushort g = (ushort)U16(f, r);
60
+ baseFirst[g] = U16(f, r + 2); baseCount[g] = U16(f, r + 4);
61
+ }
62
+ layerGlyphs = new ushort[layers]; layerPalette = new ushort[layers];
63
+ for (int i = 0; i < layers; i++) { long r = layerAt + 4 * i; layerGlyphs[i] = (ushort)U16(f, r); layerPalette[i] = (ushort)U16(f, r + 2); }
64
+ int entries = U16(f, cpal + 2);
65
+ long recordsAt = cpal + U32(f, cpal + 8) + 4L * U16(f, cpal + 12);
66
+ colors = new byte[entries * 4];
67
+ Array.Copy(f, recordsAt, colors, 0, colors.Length);
68
+ return true;
69
+ }
70
+
71
+ static void ReadLigatures(byte[] f, long gsub) {
72
+ long features = gsub + U16(f, gsub + 6), lookups = gsub + U16(f, gsub + 8);
73
+ var on = new SortedSet<int>();
74
+ int nf = U16(f, features);
75
+ for (int i = 0; i < nf; i++) {
76
+ long r = features + 2 + 6 * i;
77
+ if (!LigFeatures.Contains(Encoding.ASCII.GetString(f, (int)r, 4))) continue;
78
+ long table = features + U16(f, r + 4); int count = U16(f, table + 2);
79
+ for (int k = 0; k < count; k++) on.Add(U16(f, table + 4 + 2 * k));
80
+ }
81
+ foreach (int li in on) {
82
+ long lookup = lookups + U16(f, lookups + 2 + 2 * li);
83
+ int type = U16(f, lookup), subs = U16(f, lookup + 4);
84
+ var map = new Dictionary<ushort, List<ushort[]>>();
85
+ for (int s = 0; s < subs; s++) {
86
+ long st = lookup + U16(f, lookup + 6 + 2 * s); int t = type;
87
+ if (t == 7) { t = U16(f, st + 2); st += U32(f, st + 4); }
88
+ if (t == 4) ReadLigatureSubtable(f, st, map);
89
+ }
90
+ if (map.Count > 0) ligLookups.Add(map);
91
+ }
92
+ }
93
+
94
+ static void ReadLigatureSubtable(byte[] f, long st, Dictionary<ushort, List<ushort[]>> map) {
95
+ ushort[] covered = ReadCoverage(f, st + U16(f, st + 2));
96
+ int sets = U16(f, st + 4);
97
+ for (int i = 0; i < sets && i < covered.Length; i++) {
98
+ long set = st + U16(f, st + 6 + 2 * i); int count = U16(f, set);
99
+ List<ushort[]> list;
100
+ if (!map.TryGetValue(covered[i], out list)) { list = new List<ushort[]>(); map[covered[i]] = list; }
101
+ for (int k = 0; k < count; k++) {
102
+ long lig = set + U16(f, set + 2 + 2 * k); int comps = U16(f, lig + 2);
103
+ // [ket qua, thanh phan 2, thanh phan 3, ...] - thanh phan dau la khoa cua map.
104
+ var entry = new ushort[comps]; entry[0] = (ushort)U16(f, lig);
105
+ for (int c = 1; c < comps; c++) entry[c] = (ushort)U16(f, lig + 4 + 2 * (c - 1));
106
+ list.Add(entry);
107
+ }
108
+ }
109
+ }
110
+
111
+ static ushort[] ReadCoverage(byte[] f, long c) {
112
+ int format = U16(f, c), count = U16(f, c + 2);
113
+ var list = new List<ushort>();
114
+ if (format == 1) { for (int i = 0; i < count; i++) list.Add((ushort)U16(f, c + 4 + 2 * i)); }
115
+ else if (format == 2) {
116
+ for (int i = 0; i < count; i++) {
117
+ long r = c + 4 + 6 * i; int a = U16(f, r), b = U16(f, r + 2);
118
+ for (int g = a; g <= b; g++) list.Add((ushort)g);
119
+ }
120
+ }
121
+ return list.ToArray();
122
+ }
123
+
124
+ /** Khoi Misc Symbols / Dingbats va dai emoji mo rong: co lop mau la emoji. Ngoai ra mot it ky tu BMP mac dinh hien dang emoji (Emoji_Presentation). */
125
+ static bool DefaultEmoji(int cp) {
126
+ if (cp >= 0x1F000 && cp <= 0x1FAFF) return !(cp >= 0x1F1E6 && cp <= 0x1F1FF) && !(cp >= 0x1F3FB && cp <= 0x1F3FF);
127
+ if (cp >= 0x2600 && cp <= 0x27BF) return true;
128
+ return cp == 0x231A || cp == 0x231B || (cp >= 0x23E9 && cp <= 0x23EC) || cp == 0x23F0 || cp == 0x23F3 || cp == 0x25FD || cp == 0x25FE
129
+ || cp == 0x2B1B || cp == 0x2B1C || cp == 0x2B50 || cp == 0x2B55;
130
+ }
131
+ static bool KeycapBase(int cp) { return (cp >= 0x30 && cp <= 0x39) || cp == 0x23 || cp == 0x2A; }
132
+ static bool Regional(int cp) { return cp >= 0x1F1E6 && cp <= 0x1F1FF; }
133
+
134
+ /** Khong can doc font: chuoi khong co gi co the la emoji thi di duong TextBlock.Text nhu cu. */
135
+ static bool MayHaveEmoji(string s) {
136
+ for (int i = 0; i < s.Length; i++) {
137
+ char c = s[i];
138
+ if (char.IsSurrogate(c) || c == VS16 || c == KEYCAP) return true;
139
+ if (DefaultEmoji(c)) return true;
140
+ }
141
+ return false;
142
+ }
143
+
144
+ /** Doc mot cum emoji tu vi tri i. Khong phai emoji / font khong co mau cho no: tra null, i khong doi. */
145
+ static List<ushort> ReadCluster(string s, ref int i) {
146
+ int at = i, cp = char.ConvertToUtf32(s, at); at += char.IsSurrogatePair(s, at) ? 2 : 1;
147
+ int next = at < s.Length && !char.IsSurrogate(s[at]) ? s[at] : 0;
148
+ if (next == VS15) return null;
149
+ bool keycap = KeycapBase(cp) && ((next == KEYCAP) || (next == VS16 && at + 1 < s.Length && s[at + 1] == KEYCAP));
150
+ if (KeycapBase(cp) && !keycap) return null;
151
+ if (!keycap && !Regional(cp) && !DefaultEmoji(cp) && next != VS16) return null;
152
+ ushort first; if (!cmap.TryGetValue(cp, out first)) return null;
153
+ var run = new List<ushort> { first };
154
+ if (Regional(cp) && at < s.Length && char.IsSurrogatePair(s, at) && Regional(char.ConvertToUtf32(s, at))) {
155
+ ushort second; if (cmap.TryGetValue(char.ConvertToUtf32(s, at), out second)) { run.Add(second); at += 2; }
156
+ }
157
+ while (at < s.Length) {
158
+ int c = char.ConvertToUtf32(s, at); int len = char.IsSurrogatePair(s, at) ? 2 : 1; ushort g;
159
+ if (c == VS16) { at += len; continue; }
160
+ if ((c == KEYCAP || (c >= 0x1F3FB && c <= 0x1F3FF)) && cmap.TryGetValue(c, out g)) { run.Add(g); at += len; continue; }
161
+ if (c == ZWJ && at + 1 < s.Length) {
162
+ int after = char.ConvertToUtf32(s, at + 1); ushort zwj, afterGlyph;
163
+ if (cmap.TryGetValue(ZWJ, out zwj) && cmap.TryGetValue(after, out afterGlyph)) {
164
+ run.Add(zwj); run.Add(afterGlyph); at += 1 + (char.IsSurrogatePair(s, at + 1) ? 2 : 1); continue;
165
+ }
166
+ }
167
+ break;
168
+ }
169
+ Ligate(run);
170
+ bool any = false;
171
+ foreach (ushort g in run) if (baseFirst.ContainsKey(g)) { any = true; break; }
172
+ if (!any) return null;
173
+ i = at;
174
+ return run;
175
+ }
176
+
177
+ /** Ap cac bang ghep theo dung thu tu trong font, nhu shaper: moi bang quet mot luot, tai moi vi tri lay ban ghep dau tien khop. */
178
+ static void Ligate(List<ushort> run) {
179
+ if (run.Count < 2) return;
180
+ foreach (var map in ligLookups) {
181
+ for (int p = 0; p < run.Count; p++) {
182
+ List<ushort[]> ligs; if (!map.TryGetValue(run[p], out ligs)) continue;
183
+ foreach (ushort[] lig in ligs) {
184
+ if (p + lig.Length > run.Count) continue;
185
+ bool same = true;
186
+ for (int k = 1; k < lig.Length; k++) if (run[p + k] != lig[k]) { same = false; break; }
187
+ if (!same) continue;
188
+ run[p] = lig[0]; run.RemoveRange(p + 1, lig.Length - 1);
189
+ break;
190
+ }
191
+ }
192
+ }
193
+ }
194
+
195
+ static DrawingImage Picture(ushort glyph) {
196
+ DrawingImage img;
197
+ if (images.TryGetValue(glyph, out img)) return img;
198
+ const double em = 256;
199
+ var group = new DrawingGroup();
200
+ int first = baseFirst[glyph], count = baseCount[glyph];
201
+ Rect ink = Rect.Empty;
202
+ for (int i = first; i < first + count && i < layerGlyphs.Length; i++) {
203
+ var outline = face.GetGlyphOutline(layerGlyphs[i], em, em);
204
+ ink.Union(outline.Bounds);
205
+ var brush = new SolidColorBrush(LayerColor(layerPalette[i])); brush.Freeze();
206
+ group.Children.Add(new GeometryDrawing(brush, null, outline));
207
+ }
208
+ // O vuong om sat net ve (khoang trong trong o em cua font lam emoji nho + cach xa chu); emoji nho hon han (vd o vuong nho) khong bi phong
209
+ // len: o toi thieu theo be ngang cua font.
210
+ double side = Math.Max(Math.Max(ink.Width, ink.Height), face.AdvanceWidths[glyph] * em * MinBoxOfAdvance);
211
+ var box = new Rect(ink.X + ink.Width / 2 - side / 2, ink.Y + ink.Height / 2 - side / 2, side, side);
212
+ group.Children.Insert(0, new GeometryDrawing(Brushes.Transparent, null, new RectangleGeometry(box)));
213
+ group.Freeze();
214
+ img = new DrawingImage(group); img.Freeze();
215
+ images[glyph] = img;
216
+ return img;
217
+ }
218
+
219
+ static Color LayerColor(ushort index) {
220
+ // 0xFFFF = mau chu; font emoji gan nhu khong dung, cho toi cho doc duoc tren nen trang.
221
+ if (index == 0xFFFF || index * 4 + 3 >= colors.Length) return Color.FromRgb(0x1D, 0x21, 0x29);
222
+ int o = index * 4;
223
+ return Color.FromArgb(colors[o + 3], colors[o + 2], colors[o + 1], colors[o]);
224
+ }
225
+
226
+ /** Hinh cua mot glyph, cao / rong theo co chu. */
227
+ static System.Windows.Documents.InlineUIContainer PictureInline(ushort glyph, double fontSize) {
228
+ double side = Math.Round(fontSize * ImageScale);
229
+ var image = new System.Windows.Controls.Image { Source = Picture(glyph), Width = side, Height = side, Margin = new Thickness(1, 0, 1, 0), Stretch = Stretch.Uniform, IsHitTestVisible = false };
230
+ return new System.Windows.Documents.InlineUIContainer(image) { BaselineAlignment = BaselineAlignment.Center };
231
+ }
232
+
233
+ /** Dat chu vao TextBlock: emoji thanh hinh mau, con lai la chu. Loi gi cung lui ve chu thuong. Tag giu chu goc (xem Text). */
234
+ public static void Set(System.Windows.Controls.TextBlock block, string text) {
235
+ string s = text ?? "";
236
+ block.Tag = s;
237
+ try {
238
+ if (MayHaveEmoji(s)) {
239
+ if (!loaded) Load();
240
+ if (face != null && SetInlines(block, s)) return;
241
+ }
242
+ } catch { }
243
+ block.Text = s;
244
+ }
245
+
246
+ /** Chu goc da dat bang Set (TextBlock.Text cua khoi co hinh khong tra lai dung chu). */
247
+ public static string Text(System.Windows.Controls.TextBlock block) {
248
+ string tag = block.Tag as string;
249
+ return tag ?? block.Text;
250
+ }
251
+
252
+ static bool SetInlines(System.Windows.Controls.TextBlock block, string s) {
253
+ var parts = new List<System.Windows.Documents.Inline>(); var plain = new StringBuilder(); bool any = false;
254
+ for (int i = 0; i < s.Length; ) {
255
+ if (char.IsHighSurrogate(s[i]) && !(i + 1 < s.Length && char.IsLowSurrogate(s[i + 1])) || char.IsLowSurrogate(s[i])) { plain.Append(s[i]); i++; continue; }
256
+ int before = i;
257
+ List<ushort> run = ReadCluster(s, ref i);
258
+ if (run == null) {
259
+ int len = char.IsSurrogatePair(s, before) ? 2 : 1;
260
+ plain.Append(s, before, len); i = before + len; continue;
261
+ }
262
+ any = true;
263
+ 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, block.FontSize));
265
+ }
266
+ if (!any) return false;
267
+ if (plain.Length > 0) parts.Add(new System.Windows.Documents.Run(plain.ToString()));
268
+ block.Inlines.Clear();
269
+ block.Inlines.AddRange(parts);
270
+ return true;
271
+ }
272
+ }
273
+ `;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Chip tệp đính kèm trong ô hỏi của linh vật: tệp / thư mục thả vào bot hiện thành chip (icon + màu theo loại tệp, nút × để bỏ) phía trên
3
+ * dòng nhập — không phải một dòng chat. Daemon phân loại (cửa sổ chỉ vẽ): `fileChip(path)` → `{ path, name, kind, icon_path, ink, bg }`.
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { lucidePath } from './lucideIcons.mjs';
8
+
9
+ /** Loại tệp → icon Lucide + màu chữ / icon (`ink`) + nền chip rất nhạt cùng tông (`bg`, viền mảnh cùng tông do cửa sổ vẽ). */
10
+ export const FILE_KINDS = Object.freeze({
11
+ folder: { icon: 'folder', ink: '#B45309', bg: '#FFFBEB' },
12
+ image: { icon: 'file-image', ink: '#C026D3', bg: '#FDF4FF' },
13
+ pdf: { icon: 'file-text', ink: '#DC2626', bg: '#FEF2F2' },
14
+ doc: { icon: 'file-text', ink: '#2563EB', bg: '#EFF6FF' },
15
+ sheet: { icon: 'file-spreadsheet', ink: '#059669', bg: '#ECFDF5' },
16
+ slides: { icon: 'presentation', ink: '#EA580C', bg: '#FFF7ED' },
17
+ video: { icon: 'file-video', ink: '#7C3AED', bg: '#F5F3FF' },
18
+ audio: { icon: 'file-audio', ink: '#DB2777', bg: '#FDF2F8' },
19
+ archive: { icon: 'file-archive', ink: '#92400E', bg: '#FBF6F0' },
20
+ code: { icon: 'file-code', ink: '#4F46E5', bg: '#EEF2FF' },
21
+ data: { icon: 'file-json', ink: '#0D9488', bg: '#F0FDFA' },
22
+ text: { icon: 'file-text', ink: '#475569', bg: '#F8FAFC' },
23
+ file: { icon: 'file', ink: '#64748B', bg: '#F8FAFC' },
24
+ });
25
+
26
+ const EXT_KINDS = Object.freeze({
27
+ image: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg', 'ico', 'heic', 'heif', 'tif', 'tiff', 'avif', 'psd', 'raw'],
28
+ pdf: ['pdf'],
29
+ doc: ['doc', 'docx', 'docm', 'dot', 'dotx', 'odt', 'rtf', 'pages'],
30
+ sheet: ['xls', 'xlsx', 'xlsm', 'xlsb', 'xlt', 'xltx', 'ods', 'csv', 'tsv', 'numbers'],
31
+ slides: ['ppt', 'pptx', 'pptm', 'pps', 'ppsx', 'pot', 'potx', 'odp', 'key'],
32
+ video: ['mp4', 'mov', 'avi', 'mkv', 'webm', 'wmv', 'flv', 'm4v', '3gp', 'mpg', 'mpeg'],
33
+ audio: ['mp3', 'wav', 'm4a', 'flac', 'ogg', 'oga', 'aac', 'wma', 'opus', 'amr'],
34
+ archive: ['zip', 'rar', '7z', 'tar', 'gz', 'tgz', 'bz2', 'xz', 'zst', 'iso', 'cab'],
35
+ code: ['js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'py', 'java', 'kt', 'c', 'h', 'cpp', 'hpp', 'cs', 'go', 'rs', 'rb', 'php', 'swift', 'dart',
36
+ 'html', 'htm', 'css', 'scss', 'vue', 'svelte', 'sh', 'bash', 'ps1', 'bat', 'cmd', 'sql', 'lua', 'r'],
37
+ data: ['json', 'xml', 'yaml', 'yml', 'toml', 'ini', 'env', 'db', 'sqlite', 'parquet'],
38
+ text: ['txt', 'md', 'markdown', 'log', 'rst', 'nfo'],
39
+ });
40
+ const KIND_OF_EXT = new Map(Object.entries(EXT_KINDS).flatMap(([kind, exts]) => exts.map((e) => [e, kind])));
41
+
42
+ const isDir = (p) => {
43
+ if (/[\\/]$/.test(p)) return true;
44
+ try { return fs.statSync(p).isDirectory(); } catch { return false; }
45
+ };
46
+
47
+ /** Tên hiện trên chip: tên tệp / thư mục (bỏ dấu gạch cuối); ổ đĩa trống tên → cả đường dẫn. */
48
+ export const fileName = (p) => path.basename(String(p).replace(/[\\/]+$/, '')) || String(p);
49
+
50
+ /** Loại của một đường dẫn: thư mục → folder; còn lại theo đuôi tệp (không biết → file). */
51
+ export function fileKind(p, { dir = isDir } = {}) {
52
+ if (dir(p)) return 'folder';
53
+ const ext = path.extname(fileName(p)).slice(1).toLowerCase();
54
+ return KIND_OF_EXT.get(ext) || 'file';
55
+ }
56
+
57
+ /** Chip cho cửa sổ vẽ. */
58
+ export function fileChip(p, opts) {
59
+ const kind = fileKind(p, opts);
60
+ const { icon, ink, bg } = FILE_KINDS[kind];
61
+ return { path: p, name: fileName(p), kind, icon_path: lucidePath(icon), ink, bg };
62
+ }