@aivin-labs/cli 1.0.47 → 1.0.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,124 +1,164 @@
1
- import { DEFAULT_GROUP_LIMITS, DeviceErrorCode } from './constants.mjs';
2
- import { DeviceToolError } from './sandbox.mjs';
3
-
4
- function createSemaphore(limit) {
5
- let active = 0;
6
- const queue = [];
7
- const release = () => {
8
- active--;
9
- const next = queue.shift();
10
- if (next) { active++; next(); }
11
- };
12
- return {
13
- async acquire() {
14
- if (active < limit) { active++; return release; }
15
- await new Promise((resolve) => queue.push(resolve));
16
- return release;
17
- },
18
- stats: () => ({ active, queued: queue.length, limit }),
19
- };
20
- }
21
-
22
- function groupLimit(group) {
23
- const fromEnv = Number(process.env[`AIVIN_REMOTE_LIMIT_${String(group).toUpperCase()}`]);
24
- return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : (DEFAULT_GROUP_LIMITS[group] ?? 4);
25
- }
26
-
27
- /**
28
- * Bộ điều phối lời gọi trên máy: mỗi nhóm công cụ một semaphore (đọc tệp 16, chạy lệnh 3…), thao tác ghi khoá theo từng đường dẫn
29
- * (hai lệnh ghi cùng tệp chạy lần lượt, khác tệp chạy song song), mỗi lời gọi một AbortController (huỷ / hết giờ → dừng cả cây tiến
30
- * trình con).
31
- *
32
- * `scopeLimits` (máy tính tổ chức): thêm trần theo từng thành viên (`call.user_scope`) trong mỗi nhóm. Lấy chỗ của vùng TRƯỚC rồi mới
33
- * tới chỗ chung — lời gọi đang chờ trần của riêng mình không giữ chỗ chung của người khác. Không truyền → như máy một người.
34
- */
35
- export function createScheduler({ scopeLimits = null } = {}) {
36
- const semaphores = new Map();
37
- const scopeSemaphores = new Map();
38
- const pathLocks = new Map();
39
- const inflight = new Map();
40
-
41
- const semaphoreOf = (group) => {
42
- if (!semaphores.has(group)) semaphores.set(group, createSemaphore(groupLimit(group)));
43
- return semaphores.get(group);
44
- };
45
-
46
- const scopeSemaphoreOf = (scope, group) => {
47
- const fromEnv = Number(process.env[`AIVIN_REMOTE_SCOPE_LIMIT_${String(group).toUpperCase()}`]);
48
- const limit = Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : scopeLimits?.[group];
49
- if (!limit || typeof scope !== 'string' || !scope) return null;
50
- const key = `${scope}\u0000${group}`;
51
- if (!scopeSemaphores.has(key)) scopeSemaphores.set(key, createSemaphore(limit));
52
- return scopeSemaphores.get(key);
53
- };
54
-
55
- async function withPathLocks(keys, fn) {
56
- const sorted = [...new Set(keys)].sort();
57
- const previous = sorted.map((k) => pathLocks.get(k) || Promise.resolve());
58
- let done;
59
- const mine = new Promise((resolve) => { done = resolve; });
60
- sorted.forEach((k) => pathLocks.set(k, mine));
61
- try {
62
- await Promise.all(previous);
63
- return await fn();
64
- } finally {
65
- done();
66
- sorted.forEach((k) => { if (pathLocks.get(k) === mine) pathLocks.delete(k); });
67
- }
68
- }
69
-
70
- /**
71
- * Chạy một lời gọi. `spec`: { group, lockKeys?(args) }, `handler(args, ctx)`; ctx = { signal, onOutput }.
72
- * Không ném lỗi: trả { ok, result } hoặc { ok:false, error, error_code }.
73
- */
74
- async function run(call, spec, handler, { onOutput } = {}) {
75
- const controller = new AbortController();
76
- inflight.set(call.call_id, controller);
77
- const startedAt = Date.now();
78
- const timeoutMs = Math.max(1000, Number(call.timeout_ms) || 60_000);
79
- const timer = setTimeout(() => controller.abort(new DeviceToolError(DeviceErrorCode.CALL_TIMEOUT, `Timed out after ${timeoutMs} ms`)), timeoutMs);
80
- const releaseScope = scopeLimits ? await scopeSemaphoreOf(call.user_scope, spec.group)?.acquire() : null;
81
- const release = await semaphoreOf(spec.group).acquire();
82
- try {
83
- if (controller.signal.aborted) throw controller.signal.reason;
84
- const exec = () => handler(call.args || {}, { signal: controller.signal, onOutput, timeoutMs });
85
- const keys = spec.lockKeys ? spec.lockKeys(call.args || {}) : [];
86
- const result = keys.length ? await withPathLocks(keys, exec) : await exec();
87
- return { ok: true, result, duration_ms: Date.now() - startedAt };
88
- } catch (error) {
89
- const reason = controller.signal.aborted ? controller.signal.reason : error;
90
- return {
91
- ok: false,
92
- error: reason?.message || String(reason),
93
- error_code: reason?.code || DeviceErrorCode.EXECUTION_FAILED,
94
- duration_ms: Date.now() - startedAt,
95
- };
96
- } finally {
97
- clearTimeout(timer);
98
- release();
99
- releaseScope?.();
100
- inflight.delete(call.call_id);
101
- }
102
- }
103
-
104
- function cancel(callIds) {
105
- for (const id of callIds || []) {
106
- inflight.get(id)?.abort(new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled by server'));
107
- }
108
- }
109
-
110
- /** Huỷ mọi lời gọi đang chạy; chờ tối đa `waitMs` cho chúng dọn xong (giết cây tiến trình con) — dùng khi tạm dừng / dừng / bị thu hồi. */
111
- async function cancelAll(message = 'Cancelled on this device', { waitMs = 5000 } = {}) {
112
- for (const controller of inflight.values()) controller.abort(new DeviceToolError(DeviceErrorCode.CANCELLED, message));
113
- const deadline = Date.now() + waitMs;
114
- while (inflight.size && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50));
115
- }
116
-
117
- return {
118
- run,
119
- cancel,
120
- cancelAll,
121
- stats: () => Object.fromEntries([...semaphores.entries()].map(([g, s]) => [g, s.stats()])),
122
- inflightCount: () => inflight.size,
123
- };
124
- }
1
+ import path from 'path';
2
+ import { DEFAULT_GROUP_LIMITS, DeviceErrorCode } from './constants.mjs';
3
+ import { DeviceToolError } from './sandbox.mjs';
4
+
5
+ function createSemaphore(limit) {
6
+ let active = 0;
7
+ const queue = [];
8
+ const release = () => {
9
+ active--;
10
+ const next = queue.shift();
11
+ if (next) { active++; next(); }
12
+ };
13
+ return {
14
+ async acquire() {
15
+ if (active < limit) { active++; return release; }
16
+ await new Promise((resolve) => queue.push(resolve));
17
+ return release;
18
+ },
19
+ stats: () => ({ active, queued: queue.length, limit }),
20
+ };
21
+ }
22
+
23
+ function groupLimit(group) {
24
+ const fromEnv = Number(process.env[`AIVIN_REMOTE_LIMIT_${String(group).toUpperCase()}`]);
25
+ return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : (DEFAULT_GROUP_LIMITS[group] ?? 4);
26
+ }
27
+
28
+ /**
29
+ * Khoá đường dẫn so theo dạng chuẩn hoá: Windows / macOS không phân biệt hoa thường (`A.txt` và `a.txt` là một tệp), và có dấu phân cách cuối
30
+ * để so cha – con (`C:\a` chứa `C:\a\b`, không chứa `C:\ab`).
31
+ */
32
+ export function lockKeyOf(key, platform = process.platform) {
33
+ const p = path.resolve(String(key));
34
+ const folded = platform === 'win32' || platform === 'darwin' ? p.toLowerCase() : p;
35
+ return folded.endsWith(path.sep) ? folded : folded + path.sep;
36
+ }
37
+
38
+ /** Hai khoá đụng nhau khi là cùng đường hoặc một bên nằm trong bên kia (xoá thư mục `a` và ghi `a/b.txt` phải chạy lần lượt). */
39
+ const overlaps = (a, b) => a.startsWith(b) || b.startsWith(a);
40
+
41
+ /** Lỗi trả về khi lời gọi bị huỷ / hết giờ TRƯỚC khi công cụ chạy: chưa có gì xảy ra, Planner làm lại được. */
42
+ function notStarted(reason) {
43
+ const why = reason?.code === DeviceErrorCode.CALL_TIMEOUT ? 'timed out' : 'was cancelled';
44
+ return new DeviceToolError(DeviceErrorCode.NOT_STARTED, `The step ${why} while waiting for its turn on this device — it did not run, nothing changed`);
45
+ }
46
+
47
+ /**
48
+ * Bộ điều phối lời gọi trên máy: mỗi nhóm công cụ một semaphore (đọc tệp 16, chạy lệnh 3…), thao tác ghi khoá theo đường dẫn (hai lệnh ghi
49
+ * cùng tệp — hoặc tệp nằm trong thư mục đang bị xoá / chuyển — chạy lần lượt, không liên quan thì song song), mỗi lời gọi một AbortController
50
+ * (huỷ / hết giờ → dừng cả cây tiến trình con).
51
+ *
52
+ * Kết quả lỗi mang `ran`: công cụ đã bắt đầu chạy chưa. Huỷ / hết giờ lúc còn xếp hàng (semaphore, khoá đường dẫn) → `NOT_STARTED`, công cụ
53
+ * không bao giờ chạy sau đó; huỷ / hết giờ giữa chừng → mã gốc (`CALL_TIMEOUT` / `CANCELLED`) với `ran: true` — có thể đã làm một phần
54
+ * (idempotency.mjs không cho chạy lại mù quáng).
55
+ *
56
+ * `scopeLimits` (máy tính tổ chức): thêm trần theo từng thành viên (`call.user_scope`) trong mỗi nhóm. Lấy chỗ của vùng TRƯỚC rồi mới
57
+ * tới chỗ chung — lời gọi đang chờ trần của riêng mình không giữ chỗ chung của người khác. Không truyền → như máy một người.
58
+ */
59
+ export function createScheduler({ scopeLimits = null } = {}) {
60
+ const semaphores = new Map();
61
+ const scopeSemaphores = new Map();
62
+ const lockEntries = new Set();
63
+ const inflight = new Map();
64
+
65
+ const semaphoreOf = (group) => {
66
+ if (!semaphores.has(group)) semaphores.set(group, createSemaphore(groupLimit(group)));
67
+ return semaphores.get(group);
68
+ };
69
+
70
+ const scopeSemaphoreOf = (scope, group) => {
71
+ const fromEnv = Number(process.env[`AIVIN_REMOTE_SCOPE_LIMIT_${String(group).toUpperCase()}`]);
72
+ const limit = Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : scopeLimits?.[group];
73
+ if (!limit || typeof scope !== 'string' || !scope) return null;
74
+ const key = `${scope}\u0000${group}`;
75
+ if (!scopeSemaphores.has(key)) scopeSemaphores.set(key, createSemaphore(limit));
76
+ return scopeSemaphores.get(key);
77
+ };
78
+
79
+ /** Chờ mọi khoá vào TRƯỚC mà đụng nhau (thứ tự vào hàng — không có vòng chờ), rồi mới chạy. Bị huỷ trong lúc chờ → không chạy. */
80
+ async function withPathLocks(keys, fn, signal) {
81
+ const mine = [...new Set(keys.map((k) => lockKeyOf(k)))];
82
+ const blockers = [...lockEntries].filter((e) => e.keys.some((k) => mine.some((m) => overlaps(k, m)))).map((e) => e.promise);
83
+ let done;
84
+ const entry = { keys: mine, promise: new Promise((resolve) => { done = resolve; }) };
85
+ lockEntries.add(entry);
86
+ try {
87
+ if (blockers.length) await Promise.race([Promise.all(blockers), abortPromise(signal)]);
88
+ if (signal.aborted) throw notStarted(signal.reason);
89
+ return await fn();
90
+ } finally {
91
+ done();
92
+ lockEntries.delete(entry);
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Chạy một lời gọi. `spec`: { group, lockKeys?(args) }, `handler(args, ctx)`; ctx = { signal, onOutput }.
98
+ * Không ném lỗi: trả { ok, result } hoặc { ok:false, error, error_code, ran }.
99
+ */
100
+ async function run(call, spec, handler, { onOutput } = {}) {
101
+ const controller = new AbortController();
102
+ inflight.set(call.call_id, controller);
103
+ const startedAt = Date.now();
104
+ const timeoutMs = Math.max(1000, Number(call.timeout_ms) || 60_000);
105
+ const timer = setTimeout(() => controller.abort(new DeviceToolError(DeviceErrorCode.CALL_TIMEOUT, `Timed out after ${timeoutMs} ms`)), timeoutMs);
106
+ let ran = false;
107
+ let releaseScope = null;
108
+ let release = null;
109
+ try {
110
+ releaseScope = scopeLimits ? await scopeSemaphoreOf(call.user_scope, spec.group)?.acquire() : null;
111
+ release = await semaphoreOf(spec.group).acquire();
112
+ if (controller.signal.aborted) throw notStarted(controller.signal.reason);
113
+ const exec = () => {
114
+ ran = true;
115
+ return handler(call.args || {}, { signal: controller.signal, onOutput, timeoutMs });
116
+ };
117
+ const keys = spec.lockKeys ? spec.lockKeys(call.args || {}) : [];
118
+ const result = keys.length ? await withPathLocks(keys, exec, controller.signal) : await exec();
119
+ return { ok: true, result, duration_ms: Date.now() - startedAt };
120
+ } catch (error) {
121
+ const reason = !ran && error?.code === DeviceErrorCode.NOT_STARTED ? error : controller.signal.aborted ? controller.signal.reason : error;
122
+ return {
123
+ ok: false,
124
+ error: reason?.message || String(reason),
125
+ error_code: reason?.code || DeviceErrorCode.EXECUTION_FAILED,
126
+ duration_ms: Date.now() - startedAt,
127
+ ran,
128
+ };
129
+ } finally {
130
+ clearTimeout(timer);
131
+ release?.();
132
+ releaseScope?.();
133
+ inflight.delete(call.call_id);
134
+ }
135
+ }
136
+
137
+ function cancel(callIds) {
138
+ for (const id of callIds || []) {
139
+ inflight.get(id)?.abort(new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled by server'));
140
+ }
141
+ }
142
+
143
+ /** Huỷ mọi lời gọi đang chạy; chờ tối đa `waitMs` cho chúng dọn xong (giết cây tiến trình con) — dùng khi tạm dừng / dừng / bị thu hồi. */
144
+ async function cancelAll(message = 'Cancelled on this device', { waitMs = 5000 } = {}) {
145
+ for (const controller of inflight.values()) controller.abort(new DeviceToolError(DeviceErrorCode.CANCELLED, message));
146
+ const deadline = Date.now() + waitMs;
147
+ while (inflight.size && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50));
148
+ }
149
+
150
+ return {
151
+ run,
152
+ cancel,
153
+ cancelAll,
154
+ stats: () => Object.fromEntries([...semaphores.entries()].map(([g, s]) => [g, s.stats()])),
155
+ inflightCount: () => inflight.size,
156
+ };
157
+ }
158
+
159
+ function abortPromise(signal) {
160
+ return new Promise((resolve) => {
161
+ if (signal.aborted) return resolve();
162
+ signal.addEventListener('abort', () => resolve(), { once: true });
163
+ });
164
+ }
@@ -29,6 +29,7 @@ import { buildTransferTools } from './httpTransfer.mjs';
29
29
  import { safeGitArgv, safeGitEnv } from './gitSafe.mjs';
30
30
  import { buildMeetingTools } from './meeting/index.mjs';
31
31
  import { buildClipboardTools } from './clipboard.mjs';
32
+ import { killWindowsTree } from './winTree.mjs';
32
33
 
33
34
  /**
34
35
  * Công cụ trên máy, chia gói theo năng lực phát hiện được (git chỉ có khi máy cài git, tìm nội dung dùng ripgrep nếu có…). Mỗi công cụ
@@ -356,8 +357,8 @@ function runProcess(cmd, argv, { cwd, signal, onOutput, env, maxOutput = MAX_EXE
356
357
  const killTree = () => {
357
358
  if (killed) return;
358
359
  killed = true;
359
- // Shell đã thoát mà cháu còn chạy: trên Linux / macOS vẫn giết được cả nhóm tiến trình; Windows mất dấu cây, taskkill báo lỗi vô hại.
360
- if (process.platform === 'win32') { if (child.exitCode === null) spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true }).on('error', () => undefined); }
360
+ // Shell đã thoát mà cháu còn chạy: Linux / macOS giết cả nhóm tiến trình; Windows lần theo PID cha (cả phần mồ côi — winTree.mjs).
361
+ if (process.platform === 'win32') killWindowsTree(child, startedAt);
361
362
  else { try { process.kill(-child.pid, 'SIGKILL'); } catch { try { child.kill('SIGKILL'); } catch { /* đã thoát */ } } }
362
363
  };
363
364
  const onAbort = () => {
@@ -0,0 +1,29 @@
1
+ import { spawn } from 'child_process';
2
+
3
+ /**
4
+ * Giết cả cây tiến trình trên Windows, kể cả phần đã "mồ côi" (09/11/2026). `taskkill /T` chỉ đi theo cây còn sống: shell đã thoát (lệnh dùng
5
+ * `start`, `Start-Process`, script tự tách nền) thì các tiến trình cháu không còn nối với cây — huỷ / hết giờ là chúng chạy tiếp mãi. Windows không
6
+ * đổi `ParentProcessId` của tiến trình mồ côi, nên vẫn lần ra được từ PID gốc; lọc theo giờ tạo (≥ lúc chạy lệnh) để không giết nhầm tiến trình
7
+ * lạ dùng lại PID cũ.
8
+ */
9
+ export function orphanSweepScript(rootPid, sinceMs) {
10
+ const pid = Math.trunc(Number(rootPid));
11
+ const since = Math.trunc(Number(sinceMs)) - 1000;
12
+ if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isSafeInteger(since)) return null;
13
+ return [
14
+ '$all = Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId, CreationDate',
15
+ `$since = [DateTimeOffset]::FromUnixTimeMilliseconds(${since}).LocalDateTime`,
16
+ `$q = New-Object System.Collections.Queue; $q.Enqueue([uint32]${pid}); $kill = New-Object System.Collections.Generic.List[uint32]`,
17
+ 'while ($q.Count) { $p = $q.Dequeue(); foreach ($c in $all) { if ($c.ParentProcessId -eq $p -and $c.CreationDate -ge $since -and -not $kill.Contains($c.ProcessId)) { $kill.Add($c.ProcessId); $q.Enqueue($c.ProcessId) } } }',
18
+ 'foreach ($k in $kill) { Stop-Process -Id $k -Force -ErrorAction SilentlyContinue }',
19
+ ].join('; ');
20
+ }
21
+
22
+ /** `child`: tiến trình Node đã spawn; `startedAt`: ms lúc chạy. Cây còn sống → taskkill /T; luôn quét thêm phần mồ côi. */
23
+ export function killWindowsTree(child, startedAt, { spawnImpl = spawn } = {}) {
24
+ const run = (cmd, args) => { try { spawnImpl(cmd, args, { windowsHide: true, stdio: 'ignore' }).on('error', () => undefined); } catch { /* bỏ qua */ } };
25
+ if (!child?.pid) return;
26
+ if (child.exitCode === null && child.signalCode === null) run('taskkill', ['/pid', String(child.pid), '/T', '/F']);
27
+ const script = orphanSweepScript(child.pid, startedAt);
28
+ if (script) run('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script]);
29
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aivin-labs/cli",
3
- "version": "1.0.47",
3
+ "version": "1.0.50",
4
4
  "description": "aivin CLI - scaffold, run, and deploy Aivin plugins built on @aivin-labs/sdk",
5
5
  "type": "module",
6
6
  "bin": {