@aivin-labs/cli 1.0.47 → 1.0.51
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/README.md +1 -1
- package/bin/cli.mjs +1 -1
- package/bin/lib/auth.mjs +1 -1
- package/bin/lib/context.mjs +3 -3
- package/bin/lib/openFile.mjs +3 -2
- package/bin/lib/remote/client.mjs +1418 -1221
- package/bin/lib/remote/confirmBarrier.mjs +45 -0
- package/bin/lib/remote/constants.mjs +3 -1
- package/bin/lib/remote/desktop/aivinIco.mjs +696 -0
- package/bin/lib/remote/desktop/castAuth.mjs +23 -9
- package/bin/lib/remote/desktop/castConsent.mjs +37 -6
- package/bin/lib/remote/desktop/castFileDrop.mjs +24 -0
- package/bin/lib/remote/desktop/castInput.mjs +63 -19
- package/bin/lib/remote/desktop/castTouchViewers.mjs +26 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +25 -2
- package/bin/lib/remote/desktop/desktopCastSource.mjs +298 -101
- package/bin/lib/remote/desktop/index.mjs +5 -3
- package/bin/lib/remote/desktop/traySource.mjs +1385 -1343
- package/bin/lib/remote/desktop/webrtcWorker.mjs +3 -0
- package/bin/lib/remote/deviceProfile.mjs +2 -0
- package/bin/lib/remote/gui/index.mjs +485 -480
- package/bin/lib/remote/humanInput.mjs +117 -0
- package/bin/lib/remote/idempotency.mjs +19 -2
- package/bin/lib/remote/keepAwake.mjs +15 -9
- package/bin/lib/remote/localConfirm.mjs +26 -7
- package/bin/lib/remote/mascot/ask.mjs +23 -4
- package/bin/lib/remote/mascot/askHostSource.mjs +10 -4
- package/bin/lib/remote/processes.mjs +231 -230
- package/bin/lib/remote/scheduler.mjs +164 -124
- package/bin/lib/remote/toolHandlers.mjs +3 -2
- package/bin/lib/remote/winTree.mjs +29 -0
- package/bin/lib/servers.mjs +31 -1
- package/docs/CLI.md +2 -2
- package/package.json +1 -1
|
@@ -1,230 +1,231 @@
|
|
|
1
|
-
import { spawn } from 'child_process';
|
|
2
|
-
import { StringDecoder } from 'string_decoder';
|
|
3
|
-
import { DeviceErrorCode, ToolGroup } from './constants.mjs';
|
|
4
|
-
import { DeviceToolError, agentEnv, assertCommandAllowed, displayPath, resolveInRoots } from './sandbox.mjs';
|
|
5
|
-
import { accountEnv, withProcessCap } from './multiUser.mjs';
|
|
6
|
-
import { hasPwsh } from './deviceProfile.mjs';
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
const
|
|
17
|
-
const
|
|
18
|
-
const
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
const
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
*
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
*
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
if (
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
//
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
child.
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
for (const s of ['stdout', 'stderr'])
|
|
125
|
-
p.
|
|
126
|
-
p.
|
|
127
|
-
p.
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
child.on('
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
const
|
|
138
|
-
const
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
*
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
const
|
|
156
|
-
const
|
|
157
|
-
const
|
|
158
|
-
const
|
|
159
|
-
const
|
|
160
|
-
|
|
161
|
-
if (
|
|
162
|
-
return
|
|
163
|
-
|
|
164
|
-
const
|
|
165
|
-
const
|
|
166
|
-
const
|
|
167
|
-
const
|
|
168
|
-
p.
|
|
169
|
-
p.
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
*
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
if (
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
1
|
+
import { spawn } from 'child_process';
|
|
2
|
+
import { StringDecoder } from 'string_decoder';
|
|
3
|
+
import { DeviceErrorCode, ToolGroup } from './constants.mjs';
|
|
4
|
+
import { DeviceToolError, agentEnv, assertCommandAllowed, displayPath, resolveInRoots } from './sandbox.mjs';
|
|
5
|
+
import { accountEnv, withProcessCap } from './multiUser.mjs';
|
|
6
|
+
import { hasPwsh } from './deviceProfile.mjs';
|
|
7
|
+
import { killWindowsTree } from './winTree.mjs';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Tiến trình nền + đọc log thời gian thực (28/10/2026): `proc.start` chạy lệnh dài (dev server, build / test watch, `claude -p …`, tail log)
|
|
11
|
+
* KHÔNG giữ vòng Planner; `proc.wait_for` chờ tới khi một dòng khớp mẫu ("ready", "error", "compiled") hoặc tiến trình thoát; `proc.read`
|
|
12
|
+
* đọc phần log mới theo con trỏ; `proc.stop` dừng cả cây tiến trình. Lệnh đi qua cùng sàn với `shell.exec` (chặn `.aivin`, lọc bí mật
|
|
13
|
+
* khỏi biến môi trường, thư mục trong vùng được phép, máy tính tổ chức chạy dưới tài khoản thành viên).
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const MAX_PROCS = 8;
|
|
17
|
+
const MAX_LINES = 5000;
|
|
18
|
+
const MAX_LINE_CHARS = 2000;
|
|
19
|
+
const DEFAULT_READ_LINES = 200;
|
|
20
|
+
const MAX_WAIT_MS = 10 * 60_000;
|
|
21
|
+
/** Tiến trình đã thoát giữ log bấy nhiêu lâu rồi bỏ. */
|
|
22
|
+
const KEEP_EXITED_MS = 30 * 60_000;
|
|
23
|
+
|
|
24
|
+
const str = (description) => ({ type: 'string', description });
|
|
25
|
+
const num = (description) => ({ type: 'number', description });
|
|
26
|
+
const schema = (properties, required = []) => ({ type: 'object', properties, required });
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Chương trình + tham số chạy một dòng lệnh trong shell của máy. PowerShell 5.1 trả mã thoát 1 cho mọi lỗi của chương trình ngoài (mất mã
|
|
30
|
+
* thật — `node` thoát 2 thành 1): bọc để trả đúng `$LASTEXITCODE`, lệnh PowerShell lỗi (không có mã) thì 1.
|
|
31
|
+
*/
|
|
32
|
+
/**
|
|
33
|
+
* PowerShell 5 chạy không có console (daemon) ghi đầu ra theo bảng mã OEM (437/850…): chữ Việt thành `?` ngay tại máy, BE không cứu được
|
|
34
|
+
* (05/11/2026: `Tiếng Việt` → `Ti?ng Vi?t`, tên thư mục `Thư mục` → `Thu m?c`). Đặt UTF-8 (không BOM) cho cả console lẫn ống tới chương trình con.
|
|
35
|
+
*/
|
|
36
|
+
export const PS_UTF8_PREFIX = '$__aivinUtf8 = New-Object System.Text.UTF8Encoding($false); try { [Console]::OutputEncoding = $__aivinUtf8; [Console]::InputEncoding = $__aivinUtf8 } catch {}; $OutputEncoding = $__aivinUtf8; ';
|
|
37
|
+
|
|
38
|
+
export function shellCommand(command, platform = process.platform) {
|
|
39
|
+
if (platform === 'win32') {
|
|
40
|
+
const wrapped = `${PS_UTF8_PREFIX}& {
|
|
41
|
+
${command}
|
|
42
|
+
}; if ($LASTEXITCODE) { exit $LASTEXITCODE } elseif (-not $?) { exit 1 }`;
|
|
43
|
+
return [hasPwsh() ? 'pwsh.exe' : 'powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', wrapped]];
|
|
44
|
+
}
|
|
45
|
+
return [process.env.SHELL || '/bin/bash', ['-c', command]];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function createProcessManager() {
|
|
49
|
+
const procs = new Map();
|
|
50
|
+
let seq = 0;
|
|
51
|
+
|
|
52
|
+
const prune = () => {
|
|
53
|
+
for (const [id, p] of procs) if (p.status !== 'running' && Date.now() - p.endedAt > KEEP_EXITED_MS) procs.delete(id);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
function killTree(p) {
|
|
57
|
+
if (p.status !== 'running') return;
|
|
58
|
+
if (process.platform === 'win32') killWindowsTree(p.child, p.startedAt);
|
|
59
|
+
else { try { process.kill(-p.child.pid, 'SIGTERM'); } catch { try { p.child.kill('SIGTERM'); } catch { /* đã thoát */ } } }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Ghi log theo dòng vào bộ đệm vòng (giữ MAX_LINES dòng cuối); `cursor` tăng mãi để đọc tiếp không sót / không lặp. */
|
|
63
|
+
function pushOutput(p, stream, chunk) {
|
|
64
|
+
// StringDecoder giữ byte dở của ký tự nhiều byte sang chunk sau (toString() từng chunk ra `Ti���ng`).
|
|
65
|
+
const text = p.partial[stream] + p.decoders[stream].write(chunk);
|
|
66
|
+
const parts = text.split(/\r?\n/);
|
|
67
|
+
p.partial[stream] = parts.pop();
|
|
68
|
+
for (const line of parts) addLine(p, stream, line);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function addLine(p, stream, line) {
|
|
72
|
+
p.lines.push({ n: p.cursor++, s: stream === 'stderr' ? 'e' : 'o', t: line.length > MAX_LINE_CHARS ? `${line.slice(0, MAX_LINE_CHARS)}…` : line });
|
|
73
|
+
if (p.lines.length > MAX_LINES) p.lines.splice(0, p.lines.length - MAX_LINES);
|
|
74
|
+
for (const w of [...p.waiters]) w(p.lines[p.lines.length - 1]);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Máy tính tổ chức: mỗi tiến trình thuộc một thành viên (`env.runAs`) — người khác không thấy / đọc / dừng được. */
|
|
78
|
+
const ownerOf = (env) => env?.runAs?.name || '';
|
|
79
|
+
|
|
80
|
+
function get(id, env) {
|
|
81
|
+
const p = procs.get(String(id || ''));
|
|
82
|
+
if (!p || p.owner !== ownerOf(env)) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No background process ${id} (see proc.list)`);
|
|
83
|
+
return p;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const view = (p) => ({
|
|
87
|
+
id: p.id, name: p.name, command: p.command.slice(0, 300), cwd: p.cwdDisplay, status: p.status, exitCode: p.exitCode,
|
|
88
|
+
pid: p.child.pid, started_at: new Date(p.startedAt).toISOString(), lines: p.cursor,
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
async function start(args, _ctx, env) {
|
|
92
|
+
prune();
|
|
93
|
+
if ([...procs.values()].filter((p) => p.status === 'running' && p.owner === ownerOf(env)).length >= MAX_PROCS) {
|
|
94
|
+
throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `At most ${MAX_PROCS} background processes — stop one first (proc.list)`);
|
|
95
|
+
}
|
|
96
|
+
const command = String(args.command || '').trim();
|
|
97
|
+
if (!command) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Missing argument: command');
|
|
98
|
+
assertCommandAllowed(command);
|
|
99
|
+
const cwd = resolveInRoots(env.roots, args.cwd || '');
|
|
100
|
+
// Cần gõ vào (trả lời câu hỏi): PowerShell không chuyển stdin sang chương trình con → Windows chạy qua cmd.exe (chương trình con dùng
|
|
101
|
+
// chung stdin, mã thoát giữ nguyên); nơi khác shell vốn đã chuyển.
|
|
102
|
+
const interactive = !!args.interactive && process.platform === 'win32';
|
|
103
|
+
let [cmd, argv] = interactive ? ['cmd.exe', ['/d', '/s', '/c', `"chcp 65001 >nul & ${command}"`]] : shellCommand(command);
|
|
104
|
+
const runAs = env.runAs;
|
|
105
|
+
if (runAs) [cmd, argv] = withProcessCap(cmd, argv);
|
|
106
|
+
const baseEnv = agentEnv();
|
|
107
|
+
const child = spawn(cmd, argv, {
|
|
108
|
+
cwd, env: runAs ? accountEnv(runAs, baseEnv) : baseEnv, windowsHide: true, detached: process.platform !== 'win32',
|
|
109
|
+
stdio: ['pipe', 'pipe', 'pipe'], windowsVerbatimArguments: interactive, ...(runAs ? { uid: runAs.uid, gid: runAs.gid } : {}),
|
|
110
|
+
});
|
|
111
|
+
const id = `p${++seq}`;
|
|
112
|
+
const p = {
|
|
113
|
+
id, owner: ownerOf(env), name: String(args.name || '').slice(0, 60) || undefined, command, cwdDisplay: displayPath(env.roots, cwd), child, status: 'running', exitCode: null,
|
|
114
|
+
startedAt: Date.now(), endedAt: 0, lines: [], cursor: 0, partial: { stdout: '', stderr: '' },
|
|
115
|
+
decoders: { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') }, waiters: new Set(), exitWaiters: new Set(),
|
|
116
|
+
};
|
|
117
|
+
procs.set(id, p);
|
|
118
|
+
child.stdout.on('data', (c) => pushOutput(p, 'stdout', c));
|
|
119
|
+
child.stderr.on('data', (c) => pushOutput(p, 'stderr', c));
|
|
120
|
+
// Ghi vào stdin đã đóng (EPIPE, sau `close`): không có listener là sập cả daemon.
|
|
121
|
+
child.stdin.on('error', (e) => addLine(p, 'stderr', `Cannot write to input: ${e.message}`));
|
|
122
|
+
const finish = (code) => {
|
|
123
|
+
if (p.status !== 'running') return;
|
|
124
|
+
for (const s of ['stdout', 'stderr']) p.partial[s] += p.decoders[s].end();
|
|
125
|
+
for (const s of ['stdout', 'stderr']) if (p.partial[s]) { addLine(p, s, p.partial[s]); p.partial[s] = ''; }
|
|
126
|
+
p.status = 'exited';
|
|
127
|
+
p.exitCode = code ?? -1;
|
|
128
|
+
p.endedAt = Date.now();
|
|
129
|
+
for (const w of [...p.exitWaiters]) w();
|
|
130
|
+
};
|
|
131
|
+
child.on('error', (e) => { addLine(p, 'stderr', `Cannot start: ${e.message}`); finish(-1); });
|
|
132
|
+
child.on('close', (code) => finish(code));
|
|
133
|
+
return view(p);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function read(args, env) {
|
|
137
|
+
const p = get(args.id, env);
|
|
138
|
+
const since = Number.isFinite(Number(args.since)) ? Number(args.since) : null;
|
|
139
|
+
const max = Math.min(Number(args.lines) || DEFAULT_READ_LINES, 1000);
|
|
140
|
+
let lines = since === null ? p.lines.slice(-max) : p.lines.filter((l) => l.n >= since).slice(0, max);
|
|
141
|
+
const filter = args.filter ? new RegExp(String(args.filter), 'i') : null;
|
|
142
|
+
if (filter) lines = lines.filter((l) => filter.test(l.t));
|
|
143
|
+
const last = lines[lines.length - 1];
|
|
144
|
+
return {
|
|
145
|
+
...view(p), output: lines.map((l) => (l.s === 'e' ? `[err] ${l.t}` : l.t)).join('\n'),
|
|
146
|
+
next_since: last ? last.n + 1 : (since ?? p.cursor), dropped_before: p.lines[0]?.n || 0,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Chờ tới khi một dòng log MỚI (từ `since`, mặc định từ đầu bộ đệm) khớp `pattern` (regex, không phân biệt hoa thường), hoặc tiến trình
|
|
152
|
+
* thoát, hoặc hết `timeoutMs`. Trả dòng khớp + vài dòng trước nó làm ngữ cảnh.
|
|
153
|
+
*/
|
|
154
|
+
function waitFor(args, ctx, env) {
|
|
155
|
+
const p = get(args.id, env);
|
|
156
|
+
const pattern = args.pattern ? new RegExp(String(args.pattern), 'i') : null;
|
|
157
|
+
const since = Number.isFinite(Number(args.since)) ? Number(args.since) : 0;
|
|
158
|
+
const timeoutMs = Math.min(Math.max(1000, Number(args.timeoutMs) || 60_000), MAX_WAIT_MS);
|
|
159
|
+
const contextOf = (n) => p.lines.filter((l) => l.n < n && l.n >= n - 10).map((l) => l.t).join('\n');
|
|
160
|
+
const already = pattern && p.lines.find((l) => l.n >= since && pattern.test(l.t));
|
|
161
|
+
if (already) return Promise.resolve({ ...view(p), matched: true, line: already.t, context: contextOf(already.n), next_since: already.n + 1 });
|
|
162
|
+
if (p.status !== 'running') return Promise.resolve({ ...view(p), matched: false, reason: 'exited', tail: p.lines.slice(-30).map((l) => l.t).join('\n'), next_since: p.cursor });
|
|
163
|
+
return new Promise((resolve, reject) => {
|
|
164
|
+
const cleanup = () => { clearTimeout(timer); p.waiters.delete(onLine); p.exitWaiters.delete(onExit); ctx?.signal?.removeEventListener('abort', onAbort); };
|
|
165
|
+
const onLine = (l) => { if (pattern?.test(l.t)) { cleanup(); resolve({ ...view(p), matched: true, line: l.t, context: contextOf(l.n), next_since: l.n + 1 }); } };
|
|
166
|
+
const onExit = () => { cleanup(); resolve({ ...view(p), matched: false, reason: 'exited', tail: p.lines.slice(-30).map((l) => l.t).join('\n'), next_since: p.cursor }); };
|
|
167
|
+
const onAbort = () => { cleanup(); reject(ctx.signal.reason); };
|
|
168
|
+
const timer = setTimeout(() => { cleanup(); resolve({ ...view(p), matched: false, reason: 'timeout', tail: p.lines.slice(-20).map((l) => l.t).join('\n'), next_since: p.cursor }); }, timeoutMs);
|
|
169
|
+
p.waiters.add(onLine);
|
|
170
|
+
p.exitWaiters.add(onExit);
|
|
171
|
+
ctx?.signal?.addEventListener('abort', onAbort, { once: true });
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Gõ vào tiến trình đang chạy (trả lời câu hỏi "Continue? [y/N]", nhập lựa chọn của trình cài, lệnh cho REPL). Chữ gõ vào xét như một
|
|
177
|
+
* lệnh: chạm `.aivin` bị chặn ở đây; BE xét cùng cổng duyệt / sàn nội dung như shell.exec. `close` = đóng stdin (báo hết dữ liệu).
|
|
178
|
+
*/
|
|
179
|
+
function write(args, env) {
|
|
180
|
+
const p = get(args.id, env);
|
|
181
|
+
if (p.status !== 'running') throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Process ${p.id} has exited`);
|
|
182
|
+
const text = String(args.text ?? '');
|
|
183
|
+
assertCommandAllowed(text);
|
|
184
|
+
if (p.child.stdin.destroyed || p.child.stdin.writableEnded) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Input of process ${p.id} is already closed`);
|
|
185
|
+
if (text) p.child.stdin.write(args.newline === false ? text : `${text}
|
|
186
|
+
`);
|
|
187
|
+
if (args.close) p.child.stdin.end();
|
|
188
|
+
return { ...view(p), written: text.length, closed_input: !!args.close || undefined, next_since: p.cursor };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function stop(args, env) {
|
|
192
|
+
const p = get(args.id, env);
|
|
193
|
+
killTree(p);
|
|
194
|
+
return { ...view(p), stopping: p.status === 'running' };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return {
|
|
198
|
+
start, read, waitFor, write, stop,
|
|
199
|
+
list: (env) => { prune(); return { processes: [...procs.values()].filter((p) => p.owner === ownerOf(env)).map(view) }; },
|
|
200
|
+
stopAll: () => { for (const p of procs.values()) killTree(p); },
|
|
201
|
+
/** Còn tiến trình nền chạy (mọi người dùng) — Cloud Computer báo BE qua heartbeat để máy không bị tắt vì "rảnh" giữa lúc đang chạy. */
|
|
202
|
+
hasRunning: () => [...procs.values()].some((p) => p.status === 'running'),
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Công cụ tiến trình nền cho danh mục của Planner. */
|
|
207
|
+
export function buildProcessTools(pm) {
|
|
208
|
+
return [
|
|
209
|
+
{ name: 'proc.start', group: ToolGroup.PROC, handler: (a, c, e) => pm.start(a, c, e),
|
|
210
|
+
description: `Start a long-running command in the background (dev server, build/test watcher, long script, \`claude -p "…"\`, tail -f) in ${process.platform === 'win32' ? 'PowerShell' : 'the login shell'}; returns an id at once. Then use proc.wait_for / proc.read; stop it with proc.stop. Prefer shell.exec for short commands.`,
|
|
211
|
+
input_schema: schema({
|
|
212
|
+
command: str('command line'), cwd: str('working folder, default the root'), name: str('short label'),
|
|
213
|
+
interactive: { type: 'boolean', description: `the program will ask for input you answer with proc.write${process.platform === 'win32' ? ' (runs through cmd.exe: plain program + arguments, not PowerShell syntax)' : ''}` },
|
|
214
|
+
}, ['command']) },
|
|
215
|
+
{ name: 'proc.wait_for', group: ToolGroup.PROC, read_only: true, handler: (a, c, e) => pm.waitFor(a, c, e),
|
|
216
|
+
description: 'Wait until a NEW output line of a background process matches pattern (case-insensitive regex, e.g. "ready|listening", "error|failed"), or it exits, or timeoutMs passes. Returns the matched line with context and next_since for the next call.',
|
|
217
|
+
input_schema: schema({ id: str('process id'), pattern: str('regex to wait for; omit to wait for exit'), since: num('line cursor from a previous call'), timeoutMs: num('max 600000, default 60000') }, ['id']) },
|
|
218
|
+
{ name: 'proc.read', group: ToolGroup.PROC, read_only: true, handler: (a, _c, e) => pm.read(a, e),
|
|
219
|
+
description: 'Read output of a background process: the last lines, or new lines since a cursor; filter keeps matching lines only.',
|
|
220
|
+
input_schema: schema({ id: str('process id'), since: num('line cursor (next_since)'), lines: num('max lines, default 200'), filter: str('regex filter') }, ['id']) },
|
|
221
|
+
{ name: 'proc.write', group: ToolGroup.PROC, handler: (a, _c, e) => pm.write(a, e),
|
|
222
|
+
description: 'Type into a running background process (answer a prompt like "Continue? [y/N]", an installer choice, a line for a REPL). Adds Enter unless newline is false; close ends the input. Then proc.wait_for from the returned next_since.',
|
|
223
|
+
input_schema: schema({ id: str('process id'), text: str('what to type'), newline: { type: 'boolean', description: 'press Enter after the text (default true)' }, close: { type: 'boolean', description: 'close the input after writing' } }, ['id']) },
|
|
224
|
+
{ name: 'proc.stop', group: ToolGroup.PROC, handler: (a, _c, e) => pm.stop(a, e),
|
|
225
|
+
description: 'Stop a background process and all its children.',
|
|
226
|
+
input_schema: schema({ id: str('process id') }, ['id']) },
|
|
227
|
+
{ name: 'proc.list', group: ToolGroup.PROC, read_only: true, handler: (_a, _c, e) => pm.list(e),
|
|
228
|
+
description: 'Background processes started by the AI on this computer: status, exit code, command.',
|
|
229
|
+
input_schema: schema({}) },
|
|
230
|
+
];
|
|
231
|
+
}
|