@aivin-labs/cli 1.0.5 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +288 -216
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +551 -5
  4. package/bin/lib/browserAutomation.mjs +384 -614
  5. package/bin/lib/browserTui.mjs +276 -251
  6. package/bin/lib/cancellation.mjs +61 -0
  7. package/bin/lib/localBrowser.mjs +345 -0
  8. package/bin/lib/mcpProxy.mjs +869 -837
  9. package/bin/lib/missionStream.mjs +696 -691
  10. package/bin/lib/releaseKeys.mjs +9 -0
  11. package/bin/lib/remote/activityLog.mjs +68 -0
  12. package/bin/lib/remote/autoStart.mjs +617 -0
  13. package/bin/lib/remote/autoUpdate.mjs +129 -0
  14. package/bin/lib/remote/brand.mjs +60 -0
  15. package/bin/lib/remote/browserTunnel.mjs +403 -0
  16. package/bin/lib/remote/callLedger.mjs +134 -0
  17. package/bin/lib/remote/cdpPolicy.mjs +79 -0
  18. package/bin/lib/remote/client.mjs +808 -0
  19. package/bin/lib/remote/clipboard.mjs +138 -0
  20. package/bin/lib/remote/codingAgents.mjs +293 -0
  21. package/bin/lib/remote/constants.mjs +234 -0
  22. package/bin/lib/remote/credentials.mjs +208 -0
  23. package/bin/lib/remote/daemonLock.mjs +86 -0
  24. package/bin/lib/remote/dailyBrowser.mjs +371 -0
  25. package/bin/lib/remote/desktop/index.mjs +272 -0
  26. package/bin/lib/remote/desktop/linux.mjs +144 -0
  27. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
  28. package/bin/lib/remote/desktop/mac.mjs +187 -0
  29. package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
  30. package/bin/lib/remote/desktop/strings.mjs +74 -0
  31. package/bin/lib/remote/desktop/traySource.mjs +527 -0
  32. package/bin/lib/remote/deviceMemory.mjs +246 -0
  33. package/bin/lib/remote/deviceProfile.mjs +142 -0
  34. package/bin/lib/remote/deviceWatches.mjs +138 -0
  35. package/bin/lib/remote/docText.mjs +117 -0
  36. package/bin/lib/remote/fileIndexer.mjs +399 -0
  37. package/bin/lib/remote/gui/index.mjs +326 -0
  38. package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
  39. package/bin/lib/remote/gui/windowsHost.mjs +109 -0
  40. package/bin/lib/remote/gui/windowsHostSource.mjs +1156 -0
  41. package/bin/lib/remote/httpTransfer.mjs +89 -0
  42. package/bin/lib/remote/idempotency.mjs +135 -0
  43. package/bin/lib/remote/keepAwake.mjs +100 -0
  44. package/bin/lib/remote/localConfirm.mjs +268 -0
  45. package/bin/lib/remote/localPolicy.mjs +256 -0
  46. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  47. package/bin/lib/remote/mascot/ask.mjs +768 -0
  48. package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
  49. package/bin/lib/remote/mascot/assets.mjs +827 -0
  50. package/bin/lib/remote/mascot/bot.mjs +372 -0
  51. package/bin/lib/remote/mascot/hostSource.mjs +759 -0
  52. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  53. package/bin/lib/remote/mascot/index.mjs +493 -0
  54. package/bin/lib/remote/mascot/labels.mjs +82 -0
  55. package/bin/lib/remote/mascot/rigSource.mjs +609 -0
  56. package/bin/lib/remote/mascot/strings.mjs +375 -0
  57. package/bin/lib/remote/mascot/ui.mjs +104 -0
  58. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  59. package/bin/lib/remote/meeting/index.mjs +415 -0
  60. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  61. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  62. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  63. package/bin/lib/remote/memberFsPool.mjs +134 -0
  64. package/bin/lib/remote/memberFsWorker.mjs +60 -0
  65. package/bin/lib/remote/mission.mjs +156 -0
  66. package/bin/lib/remote/missionQuestion.mjs +63 -0
  67. package/bin/lib/remote/multiUser.mjs +344 -0
  68. package/bin/lib/remote/netProxy.mjs +145 -0
  69. package/bin/lib/remote/notify.mjs +58 -0
  70. package/bin/lib/remote/office/index.mjs +90 -0
  71. package/bin/lib/remote/policyCommand.mjs +93 -0
  72. package/bin/lib/remote/processes.mjs +217 -0
  73. package/bin/lib/remote/sandbox.mjs +221 -0
  74. package/bin/lib/remote/schedule.mjs +213 -0
  75. package/bin/lib/remote/scheduler.mjs +124 -0
  76. package/bin/lib/remote/tabGroups.mjs +209 -0
  77. package/bin/lib/remote/textIndex.mjs +131 -0
  78. package/bin/lib/remote/tokenStore.mjs +77 -0
  79. package/bin/lib/remote/toolHandlers.mjs +741 -0
  80. package/bin/lib/remote/undoStore.mjs +242 -0
  81. package/bin/lib/remoteControl.mjs +26 -0
  82. package/bin/lib/scaffold.mjs +654 -653
  83. package/bin/lib/selfUpdate.mjs +71 -0
  84. package/bin/lib/update/binarySwap.mjs +63 -0
  85. package/bin/lib/update/constants.mjs +56 -0
  86. package/bin/lib/update/download.mjs +145 -0
  87. package/bin/lib/update/signature.mjs +42 -0
  88. package/bin/lib/update/state.mjs +205 -0
  89. package/bin/lib/update/versions.mjs +60 -0
  90. package/docs/AIVIN_MASCOT.md +116 -0
  91. package/docs/CLI.md +1484 -1299
  92. package/docs/media/aivin-mascot-states.mp4 +0 -0
  93. package/package.json +71 -62
@@ -0,0 +1,344 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { execFile, execFileSync } from 'child_process';
4
+ import { DeviceErrorCode, REMOTE_CONFIG_DIR } from './constants.mjs';
5
+ import { DeviceToolError, scrubEnv } from './sandbox.mjs';
6
+ import { createMemberFsPool, runsInMemberWorker } from './memberFsPool.mjs';
7
+ import { deleteMemoryItems, getMemoryItem, listMemoryItems, putMemoryItems, searchMemory } from './deviceMemory.mjs';
8
+
9
+ /**
10
+ * Chế độ nhiều người dùng (`aivin remote start --multi-user`) — máy tính đám mây của tổ chức: một container, mọi thành viên org dùng
11
+ * chung. BE gắn `user_scope` (băm client + user id, dạng `u<12 hex>`) vào từng lời gọi; mỗi vùng là một tài khoản Linux riêng với thư
12
+ * mục nhà riêng (700) — lệnh shell / git / ripgrep chạy dưới tài khoản đó, công cụ tệp chạy trong tiến trình con cũng dưới tài khoản
13
+ * đó (memberFsPool.mjs) và chỉ thấy thư mục nhà của họ + thư mục chung,
14
+ * bộ nhớ trên máy tách theo vùng. Tiến trình CLI chạy root (cần để tạo tài khoản và đổi sang tài khoản đó khi chạy lệnh); thư mục cấu
15
+ * hình (token) chỉ root đọc được.
16
+ *
17
+ * Khớp BE: `src/official-plugins/device-agent/helper/OrgComputerHelper.ts` (thư mục nhà, thư mục chung, dạng vùng).
18
+ */
19
+
20
+ export const HOME_BASE = '/home';
21
+ export const SHARED_DIR = '/shared';
22
+ /**
23
+ * Nhóm CHÍNH của mọi tài khoản thành viên — tệp mới ở /shared tự thuộc nhóm này (không cần setgid: container không có CAP_FSETID nên nhân
24
+ * Linux xoá bit setgid khi chmod). Thư mục nhà thì không cho nhóm vào (700).
25
+ */
26
+ export const MEMBER_GROUP = 'aivin';
27
+ export const MEMBER_GID = 10000;
28
+ const FIRST_UID = 10001;
29
+ const USERS_FILE = path.join(REMOTE_CONFIG_DIR, 'users.json');
30
+ const SCOPE_RE = /^u[0-9a-f]{12}$/;
31
+
32
+ export function isValidUserScope(scope) {
33
+ return typeof scope === 'string' && SCOPE_RE.test(scope);
34
+ }
35
+
36
+ export function isMultiUserMode(options = {}, env = process.env) {
37
+ return !!options.multiUser || env.AIVIN_MULTI_USER === '1';
38
+ }
39
+
40
+ function run(cmd, args) {
41
+ execFileSync(cmd, args, { stdio: 'ignore' });
42
+ }
43
+
44
+ function readUsers() {
45
+ try {
46
+ const data = JSON.parse(fs.readFileSync(USERS_FILE, 'utf8'));
47
+ return data && typeof data === 'object' && data.users ? data : { users: {} };
48
+ } catch {
49
+ return { users: {} };
50
+ }
51
+ }
52
+
53
+ function writeUsers(data) {
54
+ fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
55
+ const tmp = `${USERS_FILE}.tmp-${process.pid}`;
56
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
57
+ fs.renameSync(tmp, USERS_FILE);
58
+ }
59
+
60
+ /** Tài khoản đã có trong /etc/passwd của container chưa (container tạo lại thì mất, sổ uid trên volume thì còn). */
61
+ function linuxUserExists(name) {
62
+ try {
63
+ return fs.readFileSync('/etc/passwd', 'utf8').split('\n').some((line) => line.startsWith(`${name}:`));
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Bộ nhớ trên máy theo vùng: khoá mục mang tiền tố `<vùng>:` (một kho YAML chung, không đổi định dạng tệp). Đọc ra bỏ tiền tố và chỉ
71
+ * trả mục của vùng — thành viên này không thấy quy trình / ghi nhớ của thành viên khác.
72
+ */
73
+ export function scopedMemory(scope) {
74
+ const prefix = `${scope}:`;
75
+ const own = (item) => item && String(item.key || '').startsWith(prefix);
76
+ const strip = (item) => ({ ...item, key: String(item.key).slice(prefix.length) });
77
+ const all = (kind) => {
78
+ const out = [];
79
+ for (let cursor = 0; cursor !== null;) {
80
+ const page = listMemoryItems({ kind, cursor, limit: 200 });
81
+ out.push(...page.items);
82
+ cursor = page.next_cursor;
83
+ }
84
+ return out.filter(own);
85
+ };
86
+ return {
87
+ put: (items = []) => putMemoryItems((Array.isArray(items) ? items : []).map((i) => ({ ...i, key: `${prefix}${String(i?.key || '')}` }))),
88
+ search: ({ query, vector, kinds, limit = 8 } = {}) => searchMemory({ query, vector, kinds, limit: Math.min(limit * 8, 200) })
89
+ .filter(own).slice(0, limit).map(strip),
90
+ get: ({ id, kind, key } = {}) => {
91
+ const item = getMemoryItem(id ? { id } : { kind, key: `${prefix}${key || ''}` });
92
+ return own(item) ? strip(item) : null;
93
+ },
94
+ list: ({ kind, cursor = 0, limit = 50 } = {}) => {
95
+ const items = all(kind);
96
+ const start = Math.max(0, Number(cursor) || 0);
97
+ const size = Math.min(Math.max(1, Number(limit) || 50), 200);
98
+ return { total: items.length, items: items.slice(start, start + size).map(strip), next_cursor: start + size < items.length ? start + size : null };
99
+ },
100
+ delete: ({ ids = [], kind, key } = {}) => {
101
+ const mine = new Set(all().map((i) => i.id));
102
+ return deleteMemoryItems({ ids: ids.filter((id) => mine.has(id)), ...(kind && key ? { kind, key: `${prefix}${key}` } : {}) });
103
+ },
104
+ };
105
+ }
106
+
107
+ /**
108
+ * Máy chủ nhiều người dùng: chuẩn bị nhóm + thư mục chung lúc khởi động, cấp tài khoản Linux cho từng vùng theo yêu cầu (uid ổn định
109
+ * ghi ở sổ trên volume cấu hình), dựng `env` riêng cho lời gọi của vùng đó.
110
+ */
111
+ export function createMultiUserHost({ baseEnv, say = () => {} }) {
112
+ const users = readUsers();
113
+ const ready = new Map();
114
+
115
+ function prepare() {
116
+ process.umask(0o002);
117
+ try { run('groupadd', ['-f', '-g', String(MEMBER_GID), MEMBER_GROUP]); } catch { /* đã có */ }
118
+ for (const dir of [HOME_BASE, SHARED_DIR]) fs.mkdirSync(dir, { recursive: true });
119
+ fs.chownSync(SHARED_DIR, 0, MEMBER_GID);
120
+ // Sticky: mọi thành viên ghi / sửa được tệp chung (umask 002), nhưng chỉ chủ tệp xoá / đổi tên được — AI của người này không xoá
121
+ // nhầm tệp của người khác.
122
+ fs.chmodSync(SHARED_DIR, 0o1775);
123
+ fs.chmodSync(HOME_BASE, 0o711);
124
+ fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
125
+ fs.chmodSync(REMOTE_CONFIG_DIR, 0o700);
126
+ say(` Nhiều người dùng: ${Object.keys(users.users).length} tài khoản thành viên, thư mục chung ${SHARED_DIR}`);
127
+ }
128
+
129
+ function allocateUid() {
130
+ const used = Object.values(users.users).map((u) => u.uid);
131
+ return used.length ? Math.max(...used) + 1 : FIRST_UID;
132
+ }
133
+
134
+ /** Tài khoản + thư mục nhà của vùng (tạo lần đầu; container tạo lại thì dựng lại tài khoản theo đúng uid cũ). */
135
+ function ensureUser(scope) {
136
+ if (ready.has(scope)) return ready.get(scope);
137
+ let entry = users.users[scope];
138
+ if (!entry) {
139
+ entry = { uid: allocateUid(), created_at: new Date().toISOString() };
140
+ users.users[scope] = entry;
141
+ writeUsers(users);
142
+ }
143
+ const home = path.join(HOME_BASE, scope);
144
+ if (!linuxUserExists(scope)) {
145
+ run('useradd', ['-M', '-N', '-u', String(entry.uid), '-g', String(MEMBER_GID), '-d', home, '-s', '/bin/bash', scope]);
146
+ }
147
+ if (!fs.existsSync(home)) fs.mkdirSync(home, { recursive: true });
148
+ fs.chownSync(home, entry.uid, MEMBER_GID);
149
+ fs.chmodSync(home, 0o700);
150
+ const account = { uid: entry.uid, gid: MEMBER_GID, home, name: scope };
151
+ ready.set(scope, account);
152
+ return account;
153
+ }
154
+
155
+ /** `env` cho một lời gọi: gốc = thư mục nhà của vùng + thư mục chung, lệnh chạy dưới tài khoản vùng, bộ nhớ của vùng. */
156
+ function envFor(scope) {
157
+ if (!isValidUserScope(scope)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'This shared computer needs a user scope for every call');
158
+ const account = ensureUser(scope);
159
+ return {
160
+ ...baseEnv,
161
+ roots: [account.home, SHARED_DIR],
162
+ projects: [],
163
+ fileIndex: null,
164
+ browserTunnels: null,
165
+ runAs: account,
166
+ memory: scopedMemory(scope),
167
+ };
168
+ }
169
+
170
+ // Công cụ tệp chạy trong tiến trình của chính thành viên (memberFsPool.mjs) — root không tự đụng tệp trong vùng người dùng nữa, tệp
171
+ // mới cũng tự thuộc về họ (không cần chown lại).
172
+ const fsPool = createMemberFsPool({
173
+ binaries: baseEnv?.binaries || [],
174
+ rootsOf: (account) => [account.home, SHARED_DIR],
175
+ envOf: (account) => ({ ...accountEnv(account, scrubEnv()), AIVIN_REMOTE_HOME: REMOTE_CONFIG_DIR }),
176
+ });
177
+ const quota = createDiskQuota({ say });
178
+
179
+ function start() {
180
+ prepare();
181
+ quota.start();
182
+ }
183
+
184
+ /** Lời gọi `fs.*` của một vùng → tiến trình tệp của vùng đó. */
185
+ function runFs(scope, tool, args, ctx) {
186
+ return fsPool.call(ensureUser(scope), tool, args, ctx);
187
+ }
188
+
189
+ function close() {
190
+ quota.stop();
191
+ fsPool.closeAll();
192
+ }
193
+
194
+ return { prepare, start, envFor, ensureUser, runFs, runsInWorker: runsInMemberWorker, assertQuota: quota.assertAllowed, close };
195
+ }
196
+
197
+ /** Biến môi trường cho lệnh chạy dưới tài khoản thành viên (HOME / USER đúng tài khoản, không mang biến của tiến trình root). */
198
+ export function accountEnv(account, base) {
199
+ return { ...base, HOME: account.home, USER: account.name, LOGNAME: account.name, SHELL: '/bin/bash', PATH: `${account.home}/.local/bin:${base.PATH || '/usr/local/bin:/usr/bin:/bin'}` };
200
+ }
201
+
202
+ // ── trần tài nguyên mỗi thành viên ──────────────────────────────────────────────────────────────
203
+
204
+ const PRLIMIT = '/usr/bin/prlimit';
205
+ const DEFAULT_MEMBER_MAX_PROCS = 128;
206
+ let nprocHardLimit;
207
+
208
+ /** Trần cứng RLIMIT_NPROC hiện tại của daemon (tiến trình con thừa hưởng) — không đặt cao hơn, prlimit của người thường sẽ lỗi. */
209
+ function currentNprocHard() {
210
+ if (nprocHardLimit !== undefined) return nprocHardLimit;
211
+ nprocHardLimit = Infinity;
212
+ try {
213
+ const m = fs.readFileSync('/proc/self/limits', 'utf8').match(/^Max processes\s+\S+\s+(\S+)/m);
214
+ if (m && m[1] !== 'unlimited' && Number(m[1]) > 0) nprocHardLimit = Number(m[1]);
215
+ } catch { /* không phải Linux */ }
216
+ return nprocHardLimit;
217
+ }
218
+
219
+ export function memberMaxProcs(env = process.env) {
220
+ const n = Math.floor(Number(env.AIVIN_MEMBER_MAX_PROCS));
221
+ return n > 0 ? n : DEFAULT_MEMBER_MAX_PROCS;
222
+ }
223
+
224
+ /**
225
+ * Lệnh chạy dưới tài khoản thành viên → bọc `prlimit --nproc=N:N -- <lệnh>` (Linux, có prlimit). RLIMIT_NPROC tính theo uid nên đây là
226
+ * trần cho từng thành viên — fork bomb của một người không làm cạn bảng tiến trình của cả container.
227
+ */
228
+ export function withProcessCap(cmd, argv, { platform = process.platform, exists = fs.existsSync, limit = memberMaxProcs(), hard } = {}) {
229
+ if (platform !== 'linux' || !exists(PRLIMIT)) return [cmd, argv];
230
+ const n = Math.min(limit, hard ?? currentNprocHard());
231
+ return [PRLIMIT, [`--nproc=${n}:${n}`, '--', cmd, ...argv]];
232
+ }
233
+
234
+ /** Công cụ bị chặn khi hết dung lượng — đọc, liệt kê, xoá vẫn chạy để người dùng tự dọn chỗ. */
235
+ export const QUOTA_GUARDED_TOOLS = new Set(['fs.write', 'fs.edit', 'fs.move', 'fs.move_many', 'fs.undo', 'shell.exec', 'proc.start']);
236
+ const DISK_MEASURE_MS = 60_000;
237
+ const DISK_RESERVE_MB = 64;
238
+ const DISK_WARN_RATIO = 0.9;
239
+
240
+ /**
241
+ * Cơ chế dung lượng service-manager đã dựng cho máy (env `AIVIN_DISK_MODE`, khớp service OrgComputerDiskMechanism):
242
+ * - `loop_ext4`: /home + /shared nằm trên một đĩa ext4 cỡ theo gói — nhân Linux chặn cứng (ENOSPC). CLI chỉ đo nhẹ bằng statfs để báo lỗi
243
+ * dễ hiểu trước khi lệnh gặp ENOSPC.
244
+ * - `soft` (hoặc không đặt): volume thường không giới hạn — CLI đo bằng du và chặn công cụ ghi khi đầy (tiến trình đang chạy vẫn ghi được
245
+ * tới lần đo sau).
246
+ */
247
+ export const DiskMode = Object.freeze({ LOOP_EXT4: 'loop_ext4', SOFT: 'soft', NONE: 'none' });
248
+
249
+ const positiveNumber = (raw, fallback) => {
250
+ const n = Number(raw);
251
+ return Number.isFinite(n) && n > 0 ? n : fallback;
252
+ };
253
+
254
+ /** Đĩa riêng (statfs): byte đã dùng + tổng cỡ của filesystem chứa `dir`. */
255
+ export async function measureFsUsage(dir) {
256
+ const s = await fs.promises.statfs(dir);
257
+ return { used: (s.blocks - s.bavail) * s.bsize, total: s.blocks * s.bsize };
258
+ }
259
+
260
+ /** Tổng byte của các thư mục (`du -sx -B1`, mỗi thư mục một dòng). */
261
+ export function measureDiskUsage(dirs) {
262
+ return new Promise((resolve, reject) => {
263
+ execFile('du', ['-sx', '-B1', ...dirs], { timeout: 50_000, maxBuffer: 1024 * 1024 }, (err, stdout) => {
264
+ const lines = String(stdout || '').split('\n').map((l) => Number(l.split(/\s+/)[0])).filter((n) => Number.isFinite(n) && n >= 0);
265
+ // du vẫn in tổng khi gặp vài tệp không đọc được (mã thoát ≠ 0) → còn số thì dùng.
266
+ if (!lines.length) return reject(err || new Error('du printed nothing'));
267
+ resolve(lines.reduce((a, b) => a + b, 0));
268
+ });
269
+ });
270
+ }
271
+
272
+ /**
273
+ * Hạn mức đĩa của máy tính tổ chức (`AIVIN_ORG_COMPUTER_DISK_GB` do BE đặt theo gói; cơ chế + nhịp đo do service-manager đặt qua
274
+ * `AIVIN_DISK_*`, tham số ở service config/org_computer_host.json): đo nền theo nhịp, lời gọi dùng số đã đo (không chờ du).
275
+ * - soft: hạn = số GB của gói, đo bằng du cả /home + /shared.
276
+ * - loop_ext4: hạn = min(gói, cỡ đĩa) − phần dự trữ (`AIVIN_DISK_RESERVE_MB`) — chặn công cụ ghi trước khi đĩa đầy hẳn để AI nhận lỗi rõ
277
+ * ràng thay vì ENOSPC giữa lệnh. Gói vừa giảm (đĩa không thu nhỏ) → vẫn chặn theo số GB mới.
278
+ * Không có hạn mức / chưa đo được → không chặn. Vượt `AIVIN_DISK_WARN_RATIO` → ghi cảnh báo (một lần mỗi lần vượt).
279
+ */
280
+ export function createDiskQuota({
281
+ dirs = [HOME_BASE, SHARED_DIR],
282
+ env = process.env,
283
+ quotaGb = Number(env.AIVIN_ORG_COMPUTER_DISK_GB),
284
+ mode = env.AIVIN_DISK_MODE === DiskMode.LOOP_EXT4 ? DiskMode.LOOP_EXT4 : DiskMode.SOFT,
285
+ intervalMs = positiveNumber(env.AIVIN_DISK_MEASURE_MS, DISK_MEASURE_MS),
286
+ reserveMb = positiveNumber(env.AIVIN_DISK_RESERVE_MB, DISK_RESERVE_MB),
287
+ warnRatio = Math.min(positiveNumber(env.AIVIN_DISK_WARN_RATIO, DISK_WARN_RATIO), 1),
288
+ measure = measureDiskUsage,
289
+ statfs = measureFsUsage,
290
+ say = () => {},
291
+ } = {}) {
292
+ const hard = mode === DiskMode.LOOP_EXT4;
293
+ const planLimit = Number.isFinite(quotaGb) && quotaGb > 0 ? quotaGb * 1024 ** 3 : 0;
294
+ let limit = hard ? 0 : planLimit;
295
+ let used = null;
296
+ let running = false;
297
+ let timer = null;
298
+ let warned = false;
299
+
300
+ async function measureOnce() {
301
+ if (!hard) return measure(dirs);
302
+ const fsUsage = await statfs(dirs[0]);
303
+ limit = Math.max(0, Math.min(planLimit || Infinity, fsUsage.total) - reserveMb * 1024 ** 2);
304
+ return fsUsage.used;
305
+ }
306
+
307
+ function noteLevel() {
308
+ if (!limit || used === null) return;
309
+ const ratio = used / limit;
310
+ if (ratio >= warnRatio && !warned) {
311
+ warned = true;
312
+ say(` Ổ đĩa máy dùng chung đã dùng ${(used / 1024 ** 3).toFixed(1)} / ${(limit / 1024 ** 3).toFixed(1)} GB (${Math.round(ratio * 100)}%)${ratio >= 1 ? ' — ĐẦY: chặn ghi / chạy lệnh tới khi dọn bớt' : ''}`);
313
+ } else if (ratio < warnRatio) warned = false;
314
+ }
315
+
316
+ async function refresh() {
317
+ if ((!hard && !limit) || running) return used;
318
+ running = true;
319
+ try { used = await measureOnce(); noteLevel(); } catch { /* giữ số đo trước */ } finally { running = false; }
320
+ return used;
321
+ }
322
+
323
+ function start() {
324
+ if ((!hard && !limit) || timer) return;
325
+ say(` Hạn mức đĩa: ${hard ? `CỨNG (đĩa ext4 riêng của máy, đo statfs mỗi ${Math.round(intervalMs / 1000)} s)` : `mềm ${quotaGb} GB (đo du mỗi ${Math.round(intervalMs / 1000)} s, chặn ghi khi đầy)`}`);
326
+ void refresh();
327
+ timer = setInterval(() => void refresh(), intervalMs);
328
+ timer.unref?.();
329
+ }
330
+
331
+ function stop() {
332
+ clearInterval(timer);
333
+ timer = null;
334
+ }
335
+
336
+ function assertAllowed(toolName) {
337
+ if (!limit || used === null || used < limit || !QUOTA_GUARDED_TOOLS.has(toolName)) return;
338
+ const gb = (used / 1024 ** 3).toFixed(1);
339
+ const of = (limit / 1024 ** 3).toFixed(1);
340
+ throw new DeviceToolError(DeviceErrorCode.QUOTA_EXCEEDED, `Disk of this shared computer is full (${gb} GB used of ${hard ? of : quotaGb} GB) — delete files to free space, then retry`);
341
+ }
342
+
343
+ return { start, stop, refresh, assertAllowed, mode, usage: () => ({ used, limit }) };
344
+ }
@@ -0,0 +1,145 @@
1
+ import { execFileSync } from 'child_process';
2
+ import axios from 'axios';
3
+ import { HttpsProxyAgent } from 'https-proxy-agent';
4
+
5
+ /**
6
+ * Proxy của mạng công ty (29/10/2026). Trước đây daemon nối websocket thẳng, không đọc proxy → sau proxy công ty máy không bao giờ online.
7
+ * Thứ tự: `--proxy` / `AIVIN_PROXY` → biến môi trường `HTTPS_PROXY` / `ALL_PROXY` → proxy hệ thống (Windows: Internet Settings, macOS:
8
+ * `scutil --proxy`). Tệp PAC (tự cấu hình theo địa chỉ) chưa đọc được — khi đó nêu `--proxy` tường minh.
9
+ *
10
+ * Chỉ áp cho máy chủ Aivin qua https/wss (đường hầm CONNECT); địa chỉ nội bộ (localhost, NO_PROXY) đi thẳng.
11
+ */
12
+
13
+ export const ProxySource = Object.freeze({ EXPLICIT: 'explicit', ENV: 'env', SYSTEM: 'system' });
14
+
15
+ const NONE = new Set(['none', 'off', 'direct', 'false', '0']);
16
+ const ALWAYS_DIRECT = ['localhost', '127.0.0.1', '::1', '[::1]'];
17
+
18
+ let active = null;
19
+ let interceptorInstalled = false;
20
+
21
+ function withScheme(value) {
22
+ const v = String(value || '').trim();
23
+ if (!v) return '';
24
+ return /^[a-z][a-z0-9+.-]*:\/\//i.test(v) ? v : `http://${v}`;
25
+ }
26
+
27
+ /** `ProxyServer` của Windows: `host:port` hoặc `http=h:p;https=h:p;…` → ưu tiên https, rồi http. */
28
+ export function parseWindowsProxyServer(value) {
29
+ const v = String(value || '').trim();
30
+ if (!v) return '';
31
+ if (!v.includes('=')) return withScheme(v.split(';')[0]);
32
+ const parts = Object.fromEntries(v.split(';').map((p) => p.split('=').map((s) => s.trim())).filter(([k, x]) => k && x));
33
+ return withScheme(parts.https || parts.http || '');
34
+ }
35
+
36
+ /** Bảng `reg query …\Internet Settings` → `{ enabled, server, override, pac }`. */
37
+ export function parseWindowsInternetSettings(text) {
38
+ const read = (name) => String(text || '').match(new RegExp(`^\\s*${name}\\s+REG_\\w+\\s+(.*)$`, 'mi'))?.[1]?.trim() || '';
39
+ const enabled = /^0x0*1$/i.test(read('ProxyEnable'));
40
+ return { enabled, server: parseWindowsProxyServer(read('ProxyServer')), override: read('ProxyOverride'), pac: read('AutoConfigURL') };
41
+ }
42
+
43
+ /** Kết quả `scutil --proxy` (macOS) → URL proxy HTTPS (hoặc HTTP) đang bật + danh sách bỏ qua. */
44
+ export function parseScutilProxy(text) {
45
+ const read = (name) => String(text || '').match(new RegExp(`^\\s*${name}\\s*:\\s*(.+)$`, 'mi'))?.[1]?.trim() || '';
46
+ const pick = (kind) => (read(`${kind}Enable`) === '1' && read(`${kind}Proxy`) ? `http://${read(`${kind}Proxy`)}:${read(`${kind}Port`) || 80}` : '');
47
+ const exceptions = [...String(text || '').matchAll(/^\s*\d+\s*:\s*(\S+)\s*$/gm)].map((m) => m[1]);
48
+ return { server: pick('HTTPS') || pick('HTTP'), override: exceptions.join(';'), pac: read('ProxyAutoConfigURLString') };
49
+ }
50
+
51
+ function systemProxy(platform) {
52
+ try {
53
+ if (platform === 'win32') {
54
+ const out = execFileSync('reg', ['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'], { encoding: 'utf8', timeout: 3000, windowsHide: true });
55
+ const s = parseWindowsInternetSettings(out);
56
+ return { server: s.enabled ? s.server : '', bypass: s.override, pac: s.pac };
57
+ }
58
+ if (platform === 'darwin') {
59
+ const s = parseScutilProxy(execFileSync('scutil', ['--proxy'], { encoding: 'utf8', timeout: 3000 }));
60
+ return { server: s.server, bypass: s.override, pac: s.pac };
61
+ }
62
+ } catch { /* không đọc được → không dùng proxy hệ thống */ }
63
+ return { server: '', bypass: '', pac: '' };
64
+ }
65
+
66
+ /** Chọn proxy theo thứ tự ở đầu tệp. Trả `{ url, source, bypass, pac }` — `url` rỗng = đi thẳng. */
67
+ export function resolveProxy({ explicit, env = process.env, platform = process.platform, readSystem = systemProxy } = {}) {
68
+ const chosen = explicit ?? env.AIVIN_PROXY;
69
+ const bypass = env.NO_PROXY || env.no_proxy || '';
70
+ if (chosen !== undefined && chosen !== null && String(chosen).trim() !== '') {
71
+ return NONE.has(String(chosen).trim().toLowerCase())
72
+ ? { url: '', source: ProxySource.EXPLICIT, bypass, pac: '' }
73
+ : { url: withScheme(chosen), source: ProxySource.EXPLICIT, bypass, pac: '' };
74
+ }
75
+ const fromEnv = env.HTTPS_PROXY || env.https_proxy || env.ALL_PROXY || env.all_proxy;
76
+ if (fromEnv) return { url: withScheme(fromEnv), source: ProxySource.ENV, bypass, pac: '' };
77
+ const sys = readSystem(platform);
78
+ return { url: sys.server, source: sys.server ? ProxySource.SYSTEM : null, bypass: [bypass, sys.bypass].filter(Boolean).join(';'), pac: sys.pac };
79
+ }
80
+
81
+ const escapeRegex = (s) => s.replace(/[.+?^$()|[\]{}\\]/g, '\\$&');
82
+ /** Mẫu kiểu Windows `10.*` / `*internal*` → regex khớp trọn tên máy. */
83
+ const wildcardRegex = (rule) => new RegExp(`^${rule.split('*').map(escapeRegex).join('.*')}$`);
84
+
85
+ /** Địa chỉ đi thẳng: localhost, mạng nội bộ của Windows (`<local>` = tên không có dấu chấm), danh sách NO_PROXY / ProxyOverride. */
86
+ export function shouldBypass(targetUrl, bypass = '') {
87
+ let host;
88
+ try { host = new URL(targetUrl).hostname.toLowerCase(); } catch { return true; }
89
+ if (ALWAYS_DIRECT.includes(host)) return true;
90
+ for (const raw of String(bypass).split(/[;,\s]+/)) {
91
+ const rule = raw.trim().toLowerCase();
92
+ if (!rule) continue;
93
+ if (rule === '*') return true;
94
+ if (rule === '<local>') {
95
+ if (!host.includes('.')) return true;
96
+ continue;
97
+ }
98
+ if (rule.includes('*') && !rule.startsWith('*.')) {
99
+ if (wildcardRegex(rule).test(host)) return true;
100
+ continue;
101
+ }
102
+ const domain = rule.replace(/^\*?\./, '');
103
+ if (host === domain || host.endsWith(`.${domain}`)) return true;
104
+ }
105
+ return false;
106
+ }
107
+
108
+ /**
109
+ * Bật proxy cho cả tiến trình: axios (đăng ký máy, tệp lớn, `remote do`) dùng agent CONNECT thay cách tự đọc biến môi trường của axios (gửi
110
+ * URL đầy đủ cho proxy, nhiều proxy công ty từ chối với https). Trả thông tin để in ra màn hình.
111
+ */
112
+ export function configureProxy(opts = {}) {
113
+ const resolved = resolveProxy(opts);
114
+ active = resolved.url ? { ...resolved, agent: new HttpsProxyAgent(resolved.url) } : { ...resolved, agent: null };
115
+ // Proxy do tệp này quyết (kể cả `--proxy none` khi môi trường có HTTPS_PROXY) — tắt cách tự đọc biến môi trường của axios.
116
+ axios.defaults.proxy = false;
117
+ if (!interceptorInstalled) {
118
+ interceptorInstalled = true;
119
+ axios.interceptors.request.use((config) => {
120
+ const agent = proxyAgentFor(axios.getUri(config));
121
+ if (agent) config.httpsAgent = agent;
122
+ return config;
123
+ });
124
+ }
125
+ return { url: redact(resolved.url), source: resolved.source, pac: resolved.pac };
126
+ }
127
+
128
+ /** Agent cho một kết nối tới máy chủ Aivin (socket.io / ws) — `undefined` = đi thẳng. */
129
+ export function proxyAgentFor(targetUrl) {
130
+ if (!active?.agent) return undefined;
131
+ if (!/^(https|wss):/i.test(String(targetUrl)) || shouldBypass(targetUrl, active.bypass)) return undefined;
132
+ return active.agent;
133
+ }
134
+
135
+ /** URL proxy để in: bỏ mật khẩu. */
136
+ export function redact(url) {
137
+ if (!url) return '';
138
+ try {
139
+ const u = new URL(url);
140
+ if (u.password) u.password = '***';
141
+ return u.toString().replace(/\/$/, '');
142
+ } catch {
143
+ return url;
144
+ }
145
+ }
@@ -0,0 +1,58 @@
1
+ import { spawn } from 'child_process';
2
+ import { AIVIN_NOTIF_AUMID, ensureWindowsNotificationIdentity } from '../missionStream.mjs';
3
+
4
+ /**
5
+ * Thông báo của hệ điều hành khi AI cần người dùng (27/10/2026): AI Browser chạy trên trình duyệt của máy này mà gặp đăng nhập / captcha / cần duyệt
6
+ * thao tác → BE gọi `notify.show`. Windows: toast có biểu tượng Aivin, bấm vào mở đúng cuộc trò chuyện (`url`); macOS / Linux: thông báo chữ.
7
+ * Chữ và đường dẫn đi qua biến môi trường, không ghép vào script (không trích dẫn / chèn lệnh được). Không bao giờ ném lỗi.
8
+ */
9
+
10
+ const MAX_TITLE = 120;
11
+ const MAX_BODY = 400;
12
+
13
+ /** Chỉ nhận http(s) — toast mở đường dẫn này bằng trình duyệt mặc định khi bấm. */
14
+ export function safeNotifyUrl(url) {
15
+ try {
16
+ const u = new URL(String(url || ''));
17
+ return u.protocol === 'https:' || u.protocol === 'http:' ? u.toString() : '';
18
+ } catch {
19
+ return '';
20
+ }
21
+ }
22
+
23
+ export function showOSNotification({ title, body, url } = {}) {
24
+ const t = String(title || 'Aivin').slice(0, MAX_TITLE);
25
+ const m = String(body || '').slice(0, MAX_BODY);
26
+ const link = safeNotifyUrl(url);
27
+ try {
28
+ if (process.platform === 'win32') {
29
+ ensureWindowsNotificationIdentity();
30
+ const script = [
31
+ "[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null",
32
+ "[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",
33
+ "$t = [System.Security.SecurityElement]::Escape($env:AIVIN_NOTIF_TITLE)",
34
+ "$m = [System.Security.SecurityElement]::Escape($env:AIVIN_NOTIF_MSG)",
35
+ "$u = [System.Security.SecurityElement]::Escape($env:AIVIN_NOTIF_URL)",
36
+ "$launch = if ($u) { \" activationType='protocol' launch='$u'\" } else { '' }",
37
+ "$xml = New-Object Windows.Data.Xml.Dom.XmlDocument",
38
+ "$xml.LoadXml(\"<toast scenario='reminder'$launch><visual><binding template='ToastGeneric'><text>$t</text><text>$m</text></binding></visual><actions><action content='OK' arguments='dismiss' activationType='system'/></actions></toast>\")",
39
+ "$toast = New-Object Windows.UI.Notifications.ToastNotification($xml)",
40
+ `[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('${AIVIN_NOTIF_AUMID}').Show($toast)`,
41
+ ].join('; ');
42
+ spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
43
+ env: { ...process.env, AIVIN_NOTIF_TITLE: t, AIVIN_NOTIF_MSG: m, AIVIN_NOTIF_URL: link },
44
+ stdio: 'ignore', detached: true, windowsHide: true,
45
+ }).unref();
46
+ } else if (process.platform === 'darwin') {
47
+ spawn('osascript', ['-e', 'display notification (system attribute "AIVIN_NOTIF_MSG") with title (system attribute "AIVIN_NOTIF_TITLE") sound name "Glass"'], {
48
+ env: { ...process.env, AIVIN_NOTIF_TITLE: t, AIVIN_NOTIF_MSG: m },
49
+ stdio: 'ignore', detached: true,
50
+ }).unref();
51
+ } else {
52
+ spawn('notify-send', ['--urgency=critical', t, m], { stdio: 'ignore', detached: true }).unref();
53
+ }
54
+ } catch {
55
+ // best-effort
56
+ }
57
+ return { shown: true };
58
+ }
@@ -0,0 +1,90 @@
1
+ import path from 'path';
2
+ import { spawnSync } from 'child_process';
3
+ import { DeviceErrorCode, ToolGroup } from '../constants.mjs';
4
+ import { DeviceToolError, resolveInRoots } from '../sandbox.mjs';
5
+
6
+ /**
7
+ * Đầu nối Office (28/10/2026): máy Windows có Excel / Word / Outlook thì tự bật công cụ `office.*` — người dùng không cài, không cấu hình
8
+ * gì. Làm việc qua API của ứng dụng (COM, trong tiến trình host của gui/) thay vì bấm giao diện: nhanh, chính xác, chạy nền (tệp chưa mở thì
9
+ * mở bằng bản Excel / Word ẩn). Đường dẫn tệp và tệp đính kèm luôn trong vùng được phép của máy.
10
+ */
11
+
12
+ const PROG_IDS = { excel: 'Excel.Application', word: 'Word.Application', outlook: 'Outlook.Application' };
13
+ const EXCEL_EXT = /\.(xlsx|xlsm|xlsb|xls|csv)$/i;
14
+ const WORD_EXT = /\.(docx|docm|doc|rtf)$/i;
15
+ const MAX_ATTACHMENTS = 10;
16
+
17
+ const str = (description) => ({ type: 'string', description });
18
+ const num = (description) => ({ type: 'number', description });
19
+ const bool = (description) => ({ type: 'boolean', description });
20
+ const schema = (properties, required = []) => ({ type: 'object', properties, required });
21
+
22
+ /** Ứng dụng Office có trên máy (ProgID COM đăng ký trong registry). Không phải Windows / máy tính tổ chức → không có. */
23
+ export function detectOfficeApps({ multiUser = false, platform = process.platform, query = regHasKey } = {}) {
24
+ if (multiUser || platform !== 'win32') return [];
25
+ return Object.entries(PROG_IDS).filter(([, progId]) => query(`HKCR\\${progId}\\CLSID`)).map(([app]) => app);
26
+ }
27
+
28
+ function regHasKey(key) {
29
+ try { return spawnSync('reg', ['query', key], { windowsHide: true, timeout: 5000 }).status === 0; } catch { return false; }
30
+ }
31
+
32
+ function officePath(env, value, ext, kind) {
33
+ if (!value) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Missing argument: path');
34
+ const abs = resolveInRoots(env.roots, String(value));
35
+ if (!ext.test(abs)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Not a ${kind} file: ${path.basename(abs)}`);
36
+ return abs;
37
+ }
38
+
39
+ function attachments(env, list) {
40
+ const files = Array.isArray(list) ? list.slice(0, MAX_ATTACHMENTS + 1) : [];
41
+ if (files.length > MAX_ATTACHMENTS) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `At most ${MAX_ATTACHMENTS} attachments`);
42
+ return files.map((f) => resolveInRoots(env.roots, String(f)));
43
+ }
44
+
45
+ /** Công cụ Office cho danh mục của Planner — chỉ các ứng dụng máy có. */
46
+ export function buildOfficeTools(host, apps) {
47
+ const call = (op, args, ctx) => host.call('office', { ...args, op }, ctx);
48
+ const tools = [];
49
+ if (apps.includes('excel')) {
50
+ tools.push(
51
+ { name: 'office.excel.read', group: ToolGroup.OFFICE, read_only: true,
52
+ handler: async (a, c, e) => call('excel.read', { path: officePath(e, a.path, EXCEL_EXT, 'Excel'), sheet: a.sheet, range: a.range, formulas: !!a.formulas }, c),
53
+ description: 'Read cells of an Excel workbook through Excel itself (exact values, every sheet name; works on a workbook the user has open). Default: the used range of the active sheet.',
54
+ input_schema: schema({ path: str('workbook path'), sheet: str('sheet name, default the active sheet'), range: str('e.g. "A1:D20", default the used range'), formulas: bool('also return formulas') }, ['path']) },
55
+ { name: 'office.excel.write', group: ToolGroup.OFFICE,
56
+ handler: async (a, c, e) => call('excel.write', { path: officePath(e, a.path, EXCEL_EXT, 'Excel'), sheet: a.sheet, cells: a.cells, range: a.range, values: a.values, create: !!a.create, save: a.save !== false }, c),
57
+ description: 'Write cells through Excel: cells {"B2": value or "=formula"} and/or range (top-left cell) + values (rows). Keeps formatting and recalculates formulas; saves by default. Returns the displayed text of written cells. A workbook the user has open is edited in place.',
58
+ input_schema: schema({ path: str('workbook path'), sheet: str('sheet name'), cells: { type: 'object', description: '{"A1": value, "C3": "=SUM(A1:A2)"}' }, range: str('top-left cell for values, e.g. "A2"'), values: { type: 'array', description: 'rows of values', items: { type: 'array' } }, create: bool('create the workbook if missing'), save: bool('save after writing (default true)') }, ['path']) },
59
+ );
60
+ }
61
+ if (apps.includes('word')) {
62
+ tools.push(
63
+ { name: 'office.word.read', group: ToolGroup.OFFICE, read_only: true,
64
+ handler: async (a, c, e) => call('word.read', { path: officePath(e, a.path, WORD_EXT, 'Word'), max_chars: a.max_chars }, c),
65
+ description: 'Read the full text of a Word document through Word (also .doc/.rtf; works on a document the user has open).',
66
+ input_schema: schema({ path: str('document path'), max_chars: num('default 20000') }, ['path']) },
67
+ { name: 'office.word.edit', group: ToolGroup.OFFICE,
68
+ handler: async (a, c, e) => call('word.edit', { path: officePath(e, a.path, WORD_EXT, 'Word'), find: a.find, replace: a.replace, append: a.append, create: !!a.create, save: a.save !== false }, c),
69
+ description: 'Edit a Word document through Word, keeping its formatting: replace every occurrence of find with replace, and/or append a paragraph at the end. Saves by default; returns how many were replaced.',
70
+ input_schema: schema({ path: str('document path'), find: str('exact text to replace'), replace: str('replacement text'), append: str('paragraph to add at the end'), create: bool('create the document if missing'), save: bool('default true') }, ['path']) },
71
+ );
72
+ }
73
+ if (apps.includes('outlook')) {
74
+ tools.push(
75
+ { name: 'office.outlook.list', group: ToolGroup.OFFICE, read_only: true,
76
+ handler: async (a, c) => call('outlook.list', { folder: a.folder, limit: a.limit, unread_only: !!a.unread_only, preview_chars: a.preview_chars }, c),
77
+ description: "Newest emails in the user's Outlook (inbox or sent): subject, sender, time, unread, start of the body.",
78
+ input_schema: schema({ folder: str('inbox | sent (default inbox)'), limit: num('default 20, max 100'), unread_only: bool('only unread'), preview_chars: num('body preview length, default 300') }) },
79
+ { name: 'office.outlook.draft', group: ToolGroup.OFFICE,
80
+ handler: async (a, c, e) => call('outlook.compose', { to: a.to, cc: a.cc, subject: a.subject, body: a.body, attachments: attachments(e, a.attachments), send: false }, c),
81
+ description: "Create an email in Outlook's Drafts (not sent) with optional attachments from this computer.",
82
+ input_schema: schema({ to: str('recipients, ; separated'), cc: str('cc'), subject: str('subject'), body: str('plain text body'), attachments: { type: 'array', items: { type: 'string' }, description: 'file paths' } }, ['to', 'subject']) },
83
+ { name: 'office.outlook.send', group: ToolGroup.OFFICE,
84
+ handler: async (a, c, e) => call('outlook.compose', { to: a.to, cc: a.cc, subject: a.subject, body: a.body, attachments: attachments(e, a.attachments), send: true }, c),
85
+ description: 'Send an email from the user\'s Outlook now. Use only when the user asked to send; otherwise office.outlook.draft.',
86
+ input_schema: schema({ to: str('recipients, ; separated'), cc: str('cc'), subject: str('subject'), body: str('plain text body'), attachments: { type: 'array', items: { type: 'string' }, description: 'file paths' } }, ['to', 'subject']) },
87
+ );
88
+ }
89
+ return tools;
90
+ }