@unionschool/easy-agents 0.2.3 → 0.3.1

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 (37) hide show
  1. package/README.md +81 -10
  2. package/bin/easy-agents.js +170 -16
  3. package/bin/mac-reports.js +149 -0
  4. package/bin/mac-service.js +119 -0
  5. package/bin/pair.js +79 -0
  6. package/bin/portable-service.js +66 -0
  7. package/bin/run.js +234 -0
  8. package/bin/tasks.js +134 -0
  9. package/bin/terminal.js +66 -0
  10. package/node_modules/ws/LICENSE +20 -0
  11. package/node_modules/ws/README.md +539 -0
  12. package/node_modules/ws/browser.js +8 -0
  13. package/node_modules/ws/index.js +22 -0
  14. package/node_modules/ws/lib/buffer-util.js +142 -0
  15. package/node_modules/ws/lib/constants.js +19 -0
  16. package/node_modules/ws/lib/event-target.js +292 -0
  17. package/node_modules/ws/lib/extension.js +203 -0
  18. package/node_modules/ws/lib/limiter.js +55 -0
  19. package/node_modules/ws/lib/permessage-deflate.js +530 -0
  20. package/node_modules/ws/lib/receiver.js +751 -0
  21. package/node_modules/ws/lib/sender.js +610 -0
  22. package/node_modules/ws/lib/stream.js +161 -0
  23. package/node_modules/ws/lib/subprotocol.js +62 -0
  24. package/node_modules/ws/lib/validation.js +152 -0
  25. package/node_modules/ws/lib/websocket-server.js +565 -0
  26. package/node_modules/ws/lib/websocket.js +1471 -0
  27. package/node_modules/ws/package.json +74 -0
  28. package/node_modules/ws/wrapper.mjs +21 -0
  29. package/package.json +25 -2
  30. package/runtime/desktop_chat.py +105 -0
  31. package/runtime/easyagents_core/file_delivery.py +166 -0
  32. package/runtime/easyagents_core/git_sync.py +272 -0
  33. package/runtime/easyagents_core/mcp_call.py +165 -0
  34. package/runtime/easyagents_core/member_sync.py +128 -0
  35. package/runtime/easyagents_core/process_support.py +60 -0
  36. package/runtime/ssh_terminal.py +89 -0
  37. package/runtime/sync.py +17 -0
package/bin/pair.js ADDED
@@ -0,0 +1,79 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createInterface } from 'node:readline';
3
+ import { Writable } from 'node:stream';
4
+
5
+ export function promptPairing(defaultGateway) {
6
+ const saved = defaultGateway ? new URL(defaultGateway) : null;
7
+ const address = saved ? saved.protocol + '//' + saved.hostname : '';
8
+ const port = saved?.port || (saved?.protocol === 'http:' ? '80' : '443');
9
+ const prompts = [`网关地址${address ? ' [' + address + ']' : ''}:`, `端口 [${port}]:`, '配对码(隐藏输入):'];
10
+ const values = [];
11
+ const output = new Writable({
12
+ write(chunk, encoding, done) {
13
+ if (values.length < 2) process.stderr.write(chunk);
14
+ done();
15
+ },
16
+ });
17
+ return new Promise((resolve, reject) => {
18
+ const rl = createInterface({ input: process.stdin, output, terminal: Boolean(process.stdin.isTTY), historySize: 0 });
19
+ process.stderr.write(prompts[0]);
20
+ rl.on('line', line => {
21
+ if (values.length >= prompts.length) return;
22
+ values.push(line.trim());
23
+ if (values.length === prompts.length) {
24
+ process.stderr.write('\n');
25
+ rl.close();
26
+ resolve([values[0] || address, values[1] || port, values[2].toUpperCase()]);
27
+ } else {
28
+ process.stderr.write(prompts[values.length]);
29
+ }
30
+ });
31
+ rl.on('SIGINT', () => rl.close());
32
+ rl.on('close', () => {
33
+ if (values.length < prompts.length) reject(new Error('配对已取消'));
34
+ });
35
+ });
36
+ }
37
+
38
+ // Restrict the empty staging file before requesting or writing a device token.
39
+ export function protectDeviceFile(path) {
40
+ if (process.platform !== 'win32') return;
41
+ const options = { windowsHide: true, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] };
42
+ try {
43
+ const user = execFileSync('whoami.exe', ['/user', '/fo', 'csv', '/nh'], options);
44
+ const sid = user.match(/S-1-[0-9-]+/i)?.[0];
45
+ if (!sid) throw new Error();
46
+ execFileSync('icacls.exe', [path, '/inheritance:r', '/grant:r', '*' + sid + ':F'], options);
47
+ } catch {
48
+ throw new Error('无法限制设备凭据的文件权限,请检查配置目录');
49
+ }
50
+ }
51
+
52
+ export async function enroll(gateway, code, version) {
53
+ const url = new URL(gateway);
54
+ if (url.protocol !== 'https:' && !['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname)) {
55
+ throw new Error('远程网关配对需要 HTTPS');
56
+ }
57
+ if (!/^[A-HJ-NP-Z2-9]{8}$/.test(code)) throw new Error('配对码应为 8 位字母或数字');
58
+ const osType = { darwin: 'macos', linux: 'linux', win32: 'windows' }[process.platform];
59
+ if (!osType) throw new Error('当前系统不支持配对');
60
+ let response;
61
+ try {
62
+ response = await fetch(new URL('/api/client/enroll', url), {
63
+ method: 'POST', redirect: 'manual', signal: AbortSignal.timeout(15000),
64
+ headers: { 'Content-Type': 'application/json' },
65
+ body: JSON.stringify({ code, os_type: osType, client_version: version }),
66
+ });
67
+ } catch {
68
+ throw new Error('无法连接配对网关,请检查地址、端口、网络和证书');
69
+ }
70
+ const result = await response.json().catch(() => null);
71
+ if (response.status === 429 || result?.code === 42903) throw new Error('配对尝试过多,请稍后重试');
72
+ if (result?.code === 40002) throw new Error('配对码无效、已过期或与本机系统不匹配');
73
+ if (!response.ok || result?.code !== 0) throw new Error('网关未接受配对请求,请检查配对接口');
74
+ const { device_id, device_key, device_token } = result.data ?? {};
75
+ if (![device_id, device_key, device_token].every(v => typeof v === 'string' && v.trim())) {
76
+ throw new Error('网关返回的设备凭据不完整');
77
+ }
78
+ return { gateway, device_id, device_key, device_token };
79
+ }
@@ -0,0 +1,66 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { closeSync, mkdirSync, openSync } from 'node:fs';
4
+ import net from 'node:net';
5
+ import { join, resolve } from 'node:path';
6
+ import { setTimeout as sleep } from 'node:timers/promises';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { readSnapshot, terminalEnabled, writeSnapshot } from './mac-reports.js';
9
+
10
+ function endpoint(folder) {
11
+ const id = createHash('sha256').update(resolve(folder)).digest('hex').slice(0, 28);
12
+ return process.platform === 'win32' ? '\\\\.\\pipe\\unionschool-easyagents-' + id : '\0unionschool-easyagents-' + id;
13
+ }
14
+
15
+ // The socket is only a live instance identifier. It never accepts commands or credentials.
16
+ async function instance(folder) {
17
+ return new Promise(resolve => {
18
+ const socket = net.connect(endpoint(folder));
19
+ let value = '';
20
+ socket.setTimeout(1200, () => socket.destroy());
21
+ socket.on('error', () => {});
22
+ socket.on('data', data => { value += data; if (value.length > 64) socket.destroy(); });
23
+ socket.once('close', () => resolve(/^[a-f0-9-]{36}$/.test(value) ? value : null));
24
+ });
25
+ }
26
+
27
+ export async function claim(folder, drain) {
28
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
29
+ const session = randomUUID();
30
+ const server = net.createServer(s => { s.on('error', () => {}); s.end(session); });
31
+ await new Promise((ok, fail) => {
32
+ server.once('error', fail);
33
+ server.listen(endpoint(folder), () => { server.off('error', fail); ok(); });
34
+ }).catch(() => { throw new Error('该设备已有运行实例,或后台套接字不可用'); });
35
+ const timer = setInterval(() => {
36
+ if (readSnapshot(folder, 'desktop-stop.json')?.session === session) drain.abort();
37
+ }, 400);
38
+ return () => { clearInterval(timer); server.close(); };
39
+ }
40
+
41
+ export async function desktopStatus(folder) {
42
+ const session = await instance(folder);
43
+ const report = readSnapshot(folder, 'mac-worker.json') ?? {};
44
+ return { running: Boolean(session), connected: Boolean(session && report.connected && Date.now() - report.updated < 95000),
45
+ pid: session ? report.pid : 0, report, task: session ? report.task : null, terminalEnabled: terminalEnabled(folder) };
46
+ }
47
+
48
+ export async function serviceCommand(command, folder) {
49
+ let session = await instance(folder);
50
+ if (session && ['restart', 'stop'].includes(command)) {
51
+ writeSnapshot(folder, 'desktop-stop.json', { session });
52
+ while (await instance(folder) === session) await sleep(200);
53
+ session = await instance(folder);
54
+ }
55
+ if (command === 'stop' || session) return;
56
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
57
+ const fd = openSync(join(folder, 'worker.log'), 'a', 0o600);
58
+ try {
59
+ const processFile = process.env.EASYAGENTS_DESKTOP_ENTRY || fileURLToPath(new URL('./easy-agents.js', import.meta.url));
60
+ const child = spawn(process.execPath, [processFile, 'run'], { env: process.env, detached: true, windowsHide: true, stdio: ['ignore', fd, fd] });
61
+ await new Promise((ok, fail) => { child.once('spawn', ok); child.once('error', fail); });
62
+ child.unref();
63
+ } finally { closeSync(fd); }
64
+ for (let i = 0; i < 60; i++) { if (await instance(folder)) return; await sleep(100); }
65
+ throw new Error('后台未启动,请查看 worker.log');
66
+ }
package/bin/run.js ADDED
@@ -0,0 +1,234 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { setTimeout as sleep } from 'node:timers/promises';
6
+ import WebSocket from 'ws';
7
+ import { execute } from './tasks.js';
8
+ import { openTerminal, terminalAvailable } from './terminal.js';
9
+ import { protectDeviceFile } from './pair.js';
10
+
11
+ const validId = id => typeof id === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(id);
12
+
13
+ class GatewayError extends Error {
14
+ constructor(status, code) {
15
+ super('平台请求失败 HTTP ' + status);
16
+ this.status = status;
17
+ this.code = code;
18
+ }
19
+ }
20
+
21
+ export async function runDevice(device, configDir, version, signal, { reporter, drain, onDrained, terminalProbe = terminalAvailable } = {}) {
22
+ const url = new URL(device.gateway);
23
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname))) {
24
+ throw new Error('远程网关需要 HTTPS');
25
+ }
26
+ const wsUrl = new URL('/ws/client', url);
27
+ wsUrl.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
28
+ const wsOverride = process.env.EASYAGENTS_WS_ORIGIN || device.ws_origin;
29
+ if (wsOverride) {
30
+ const wsOrigin = new URL(wsOverride);
31
+ if (wsOrigin.protocol !== 'wss:' || wsOrigin.username || wsOrigin.password ||
32
+ wsOrigin.pathname !== '/' || wsOrigin.search || wsOrigin.hash) throw new Error('WebSocket 网关须为 WSS 地址');
33
+ wsUrl.href = new URL('/ws/client', wsOrigin).href;
34
+ }
35
+ const headers = { Authorization: 'Bearer ' + device.device_token };
36
+ const binding = createHash('sha256').update(JSON.stringify([url.origin, device.device_id])).digest('hex');
37
+ const folder = join(configDir, 'npm-runs', binding);
38
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
39
+ const queue = new Map();
40
+ const sessions = new Map();
41
+ let socket, worker, online = false, active, fatal;
42
+ const gatewayRequest = async (method, path, body, extraSignal) => {
43
+ const res = await fetch(new URL(path, url), { method,
44
+ headers: { ...headers, 'Content-Type': 'application/json' }, redirect: 'error',
45
+ signal: AbortSignal.any([signal, AbortSignal.timeout(20000), ...(extraSignal ? [extraSignal] : [])]),
46
+ body: body === undefined ? undefined : JSON.stringify(body) });
47
+ const data = await res.json().catch(() => null);
48
+ if (!res.ok) throw new GatewayError(res.status, data?.code);
49
+ if (data?.code !== 0) throw new Error('无效的平台响应');
50
+ return data.data;
51
+ };
52
+ const request = (method, path, body) => gatewayRequest(method, '/api/client/runs/' + path, body);
53
+ const reportQuota = (id, body, cancel) => gatewayRequest('POST', '/api/client/agents/' + id + '/quota', body, cancel);
54
+ function workCredential(content) {
55
+ const id = content.agent?.agent_id;
56
+ if (!/^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/i.test(id)) throw new Error('Agent 编号无效');
57
+ const dir = join(configDir, 'agents');
58
+ const file = join(dir, id + '.json');
59
+ const files = [file];
60
+ if (process.platform === 'darwin' && configDir === join(homedir(), 'Library/Application Support/EasyAgents Client')) {
61
+ files.push(join(homedir(), '.easyagents', 'agents', id + '.json'));
62
+ }
63
+ for (const path of files) {
64
+ try {
65
+ const info = lstatSync(path);
66
+ if (!info.isFile() || info.uid !== process.getuid() || (info.mode & 0o077)) throw new Error('Agent 凭据文件无效');
67
+ return { file: path, gateway: url.origin };
68
+ } catch (err) { if (err.code !== 'ENOENT') throw err; }
69
+ }
70
+ return null;
71
+ }
72
+ function checkDrained() {
73
+ if (drain?.aborted && !active && !queue.size && !readdirSync(folder).some(f => f.endsWith('.json'))) onDrained?.();
74
+ }
75
+ function checkpoint(id, data) {
76
+ const tmp = join(folder, randomUUID() + '.tmp');
77
+ try {
78
+ writeFileSync(tmp, '', { flag: 'wx', mode: 0o600 });
79
+ protectDeviceFile(tmp);
80
+ writeFileSync(tmp, JSON.stringify(data));
81
+ renameSync(tmp, join(folder, id + '.json'));
82
+ } finally {
83
+ rmSync(tmp, { force: true });
84
+ }
85
+ }
86
+ function readRecord(id) {
87
+ try { return JSON.parse(readFileSync(join(folder, id + '.json'), 'utf8')); }
88
+ catch (error) { if (error.code !== 'ENOENT') throw error; return null; }
89
+ }
90
+ async function processRun(id, controller) {
91
+ const record = readRecord(id);
92
+ let result = record?.result;
93
+ if (!result) {
94
+ if (record?.started) {
95
+ result = { status: 'interrupted', failure_code: 'client_interrupted', failure_detail: '客户端在运行期间退出' };
96
+ } else {
97
+ checkpoint(id, { started: false });
98
+ const ack = await request('POST', id + '/ack', {});
99
+ if (['succeeded', 'failed', 'cancelled', 'interrupted'].includes(ack?.status)) {
100
+ rmSync(join(folder, id + '.json'), { force: true });
101
+ return;
102
+ }
103
+ let content;
104
+ try { content = await request('GET', id); }
105
+ catch (err) {
106
+ if (err.code !== 42298) throw err;
107
+ result = { status: 'failed', failure_code: 'git_delivery_unsupported', failure_detail: '此版尚不支持 Git 任务分支交付' };
108
+ }
109
+ await request('POST', id + '/start', { tool_version: version });
110
+ checkpoint(id, { started: true });
111
+ if (ack?.status === 'running') result = { status: 'interrupted', failure_code: 'client_interrupted' };
112
+ try { result ??= await execute(content, controller.signal, workCredential); }
113
+ catch { result = controller.signal.aborted ? { status: 'cancelled', failure_code: 'cancelled' } :
114
+ { status: 'failed', failure_code: 'client_error', failure_detail: '客户端执行失败' }; }
115
+ }
116
+ result.tool_version ??= version;
117
+ checkpoint(id, { result });
118
+ }
119
+ await request('POST', id + '/finish', result);
120
+ rmSync(join(folder, id + '.json'), { force: true });
121
+ reporter?.patch({ lastResult: { id, status: result.status, at: Date.now() } });
122
+ console.log('运行 ' + id + ' 已回传 ' + result.status);
123
+ }
124
+ function startQueue() {
125
+ if (worker || !online || !queue.size || signal.aborted) return;
126
+ worker = (async () => {
127
+ while (online && !signal.aborted && queue.size) {
128
+ const [id, controller] = queue.entries().next().value;
129
+ active = controller;
130
+ reporter?.patch({ task: id });
131
+ try { await processRun(id, controller); }
132
+ catch (err) {
133
+ if (err.status === 404 || err.status === 409) rmSync(join(folder, id + '.json'), { force: true });
134
+ else {
135
+ if ([401, 403].includes(err.status)) fatal = new Error('设备认证失败,请重新配对');
136
+ online = false;
137
+ socket?.terminate();
138
+ return;
139
+ }
140
+ } finally { queue.delete(id); active = undefined; reporter?.patch({ task: null }); }
141
+ }
142
+ })().finally(() => { worker = undefined; checkDrained(); if (online) startQueue(); });
143
+ }
144
+ function enqueue(id, cancelled = false) {
145
+ if (!validId(id)) return;
146
+ if (!queue.has(id)) queue.set(id, new AbortController());
147
+ if (cancelled) queue.get(id).abort();
148
+ startQueue();
149
+ }
150
+ function stop() {
151
+ active?.abort();
152
+ socket?.terminate();
153
+ }
154
+ signal.addEventListener('abort', stop, { once: true });
155
+ drain?.addEventListener('abort', checkDrained);
156
+ reporter?.patch({ connected: false, task: null, gateway: url.origin, deviceId: device.device_id });
157
+ let delay = 1000;
158
+ try {
159
+ while (!signal.aborted && !fatal) {
160
+ const terminalSetting = reporter?.terminalEnabled?.() ?? true;
161
+ const terminal = terminalSetting && terminalProbe();
162
+ let metadata = {};
163
+ if (reporter) {
164
+ try { metadata = await reporter.hello(signal); }
165
+ catch {
166
+ if (signal.aborted) break;
167
+ console.error('本机工具信息暂时不可用,正在重试');
168
+ reporter.disconnect();
169
+ await sleep(delay, undefined, { signal }).catch(() => {});
170
+ delay = Math.min(60000, delay * 2);
171
+ continue;
172
+ }
173
+ }
174
+ if (signal.aborted) break;
175
+ const hello = { type: 'hello', client_version: version, tools: [], terminal, ...metadata };
176
+ let lastSeen = Date.now(), welcomed = false;
177
+ socket = new WebSocket(wsUrl, { headers, followRedirects: false, handshakeTimeout: 15000, maxPayload: 1048576 });
178
+ const current = socket;
179
+ current.on('error', () => {});
180
+ current.on('unexpected-response', (_req, res) => {
181
+ if ([401, 403].includes(res.statusCode)) fatal = new Error('设备认证失败,请重新配对');
182
+ res.destroy(); current.terminate();
183
+ });
184
+ current.on('open', () => current.send(JSON.stringify(hello)));
185
+ current.on('message', async raw => {
186
+ try {
187
+ const msg = JSON.parse(raw.toString());
188
+ lastSeen = Date.now();
189
+ if (msg.type === 'credential.revoked') { fatal = new Error('设备凭据已撤销'); current.terminate(); return; }
190
+ if (!welcomed) {
191
+ if (msg.type !== 'welcome' || msg.device_id !== device.device_id) throw new Error();
192
+ welcomed = online = true; delay = 1000;
193
+ reporter?.welcome(hello, msg, reportQuota, () => current.terminate());
194
+ console.log('设备已上线');
195
+ const pending = await request('GET', 'pending');
196
+ if (current !== socket || current.readyState !== WebSocket.OPEN) return;
197
+ for (const f of readdirSync(folder)) if (f.endsWith('.json')) enqueue(f.slice(0, -5));
198
+ if (!drain?.aborted) for (const row of pending) enqueue(row.run_id);
199
+ startQueue();
200
+ checkDrained();
201
+ } else if (msg.type === 'ping') { current.send(JSON.stringify({ type: 'pong' })); reporter?.patch({ heartbeat: Date.now() }); }
202
+ else if (msg.type === 'agent.quota.config') reporter?.configure(msg, reportQuota);
203
+ else if (msg.type === 'terminal.open' && terminal && (reporter?.terminalEnabled?.() ?? true)) openTerminal(wsUrl, headers, msg.session_id, sessions);
204
+ else if (msg.type === 'run.available' && !drain?.aborted) enqueue(msg.run_id);
205
+ else if (msg.type === 'run.cancel' && (!drain?.aborted || queue.has(msg.run_id))) enqueue(msg.run_id, true);
206
+ } catch (error) {
207
+ if ([401, 403].includes(error.status)) fatal = new Error('设备认证失败,请重新配对');
208
+ current.terminate();
209
+ }
210
+ });
211
+ const timer = setInterval(() => {
212
+ if (terminalSetting !== (reporter?.terminalEnabled?.() ?? true) || Date.now() - lastSeen > (welcomed ? 90000 : 15000)) current.terminate();
213
+ }, 2000);
214
+ try { await new Promise(resolve => current.once('close', resolve)); }
215
+ finally {
216
+ clearInterval(timer);
217
+ online = false;
218
+ reporter?.disconnect();
219
+ for (const session of sessions.values()) session.terminate();
220
+ }
221
+ if (!signal.aborted && !fatal) {
222
+ console.error('连接中断,正在重连');
223
+ await sleep(delay, undefined, { signal }).catch(() => {});
224
+ delay = Math.min(delay * 2, 60000);
225
+ }
226
+ }
227
+ } finally {
228
+ signal.removeEventListener('abort', stop);
229
+ drain?.removeEventListener('abort', checkDrained);
230
+ active?.abort();
231
+ await worker;
232
+ }
233
+ if (fatal) throw fatal;
234
+ }
package/bin/tasks.js ADDED
@@ -0,0 +1,134 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { execFile } from 'node:child_process';
3
+ import { mkdtemp, readFile, realpath, rm, stat } from 'node:fs/promises';
4
+ import { homedir, tmpdir } from 'node:os';
5
+ import { isAbsolute, join, parse, relative, resolve, sep } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ function invoke(file, args, cwd, input, signal, timeout) {
9
+ return new Promise((done, reject) => {
10
+ const child = execFile(file, args, { cwd, signal, timeout, maxBuffer: 4 * 1024 * 1024,
11
+ windowsHide: true }, (err, stdout) => err ? reject(err) : done(stdout));
12
+ child.stdin.on('error', () => {});
13
+ child.stdin.end(input);
14
+ });
15
+ }
16
+
17
+ function desktopConversation(resources, content, prompt, signal, credential) {
18
+ const bridge = fileURLToPath(new URL('../runtime/desktop_chat.py', import.meta.url));
19
+ const seconds = content.timeout_seconds;
20
+ const timeout = Number.isSafeInteger(seconds) && seconds > 0 ? Math.min(seconds, 3600) : 3600;
21
+ const input = { tool: content.agent.tool_type, prompt, model: content.requested_model,
22
+ resume: content.resume_session_ref, workspace: content.workspace?.local_path, timeout,
23
+ workRunId: content.chat_mode === 'work' ? content.run_id : undefined, passthrough: content.passthrough === true, credential };
24
+ return new Promise(resolveResult => {
25
+ const child = execFile(join(resources, 'python/bin/python3'), ['-I', '-B', '-X', 'utf8', bridge],
26
+ { timeout: (timeout + 12) * 1000, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => {
27
+ signal.removeEventListener('abort', cancel);
28
+ if (signal.aborted) return resolveResult({ status: 'cancelled', failure_code: 'cancelled' });
29
+ if (!error) {
30
+ try { return resolveResult(JSON.parse(stdout)); } catch {}
31
+ }
32
+ resolveResult({ status: 'failed', failure_code: 'tool_start_failed', failure_detail: '设备对话执行器异常,请检查客户端安装' });
33
+ });
34
+ const cancel = () => child.kill('SIGTERM');
35
+ signal.addEventListener('abort', cancel, { once: true });
36
+ child.stdin.on('error', () => {});
37
+ child.stdin.end(JSON.stringify(input));
38
+ if (signal.aborted) cancel();
39
+ });
40
+ }
41
+
42
+ async function workspace(content) {
43
+ const local = content.workspace?.local_path;
44
+ if (!local || typeof local !== 'string') throw new Error('缺少工作目录');
45
+ const selected = await realpath(process.env.EASYAGENTS_WORKSPACE || process.cwd());
46
+ const directory = await realpath(resolve(homedir(), local.replace(/^~\//, '')));
47
+ if (selected !== directory || selected === homedir() || selected === parse(selected).root) {
48
+ throw new Error('派发目录与本机启动时指定的工作目录不同');
49
+ }
50
+ return directory;
51
+ }
52
+
53
+ async function sync(content, signal) {
54
+ const directory = await workspace(content);
55
+ const gitRoot = (await invoke('git', ['rev-parse', '--show-toplevel'], directory, '', signal, 10000)).trim();
56
+ if (await realpath(gitRoot) !== directory) throw new Error('工作目录不是仓库根目录');
57
+ const script = fileURLToPath(new URL('../runtime/sync.py', import.meta.url));
58
+ try {
59
+ const python = process.platform === 'win32' ? 'python' : 'python3';
60
+ const result = await invoke(python, ['-I', '-S', '-B', script], directory, JSON.stringify(content), signal, 600000);
61
+ return JSON.parse(result);
62
+ } catch (error) {
63
+ if (signal.aborted) return { status: 'cancelled', failure_code: 'cancelled' };
64
+ return { status: 'failed', failure_code: error.code === 'ENOENT' ? 'python_missing' : 'sync_failed', failure_detail: '未能运行包内 Git 同步程序' };
65
+ }
66
+ }
67
+
68
+ export async function execute(content, signal, workCredential) {
69
+ signal.throwIfAborted();
70
+ if (content.run_kind === 'sync') return sync(content, signal);
71
+ let prompt = content.prompt;
72
+ const task = content.run_kind === 'execute' && content.task;
73
+ if (task) {
74
+ if (task.git_delivery || task.file_delivery || task.document_commit_sha) {
75
+ return { status: 'failed', failure_code: 'handoff_unsupported', failure_detail: '当前运行入口尚不支持版本化任务文件交付' };
76
+ }
77
+ const root = await workspace(content);
78
+ const path = task.document_path;
79
+ if (typeof path !== 'string' || isAbsolute(path) || !path.endsWith('.md')) throw new Error('任务文档路径无效');
80
+ const file = await realpath(resolve(root, path));
81
+ const rel = relative(root, file);
82
+ if (isAbsolute(rel) || rel === '..' || rel.startsWith('..' + sep)) throw new Error('任务文档在工作目录外');
83
+ const info = await stat(file);
84
+ if (!info.isFile() || info.size > 256 * 1024) throw new Error('任务文档无效');
85
+ prompt = (await readFile(file, 'utf8')).trim();
86
+ }
87
+ if (typeof prompt !== 'string' || !prompt.trim()) throw new Error('运行内容为空');
88
+ if ((content.run_kind === 'chat' || task) && prompt.startsWith('/sha256 ')) {
89
+ const digest = createHash('sha256').update(prompt.slice('/sha256 '.length), 'utf8').digest('hex');
90
+ return { status: 'succeeded', reply_text: digest };
91
+ }
92
+ if (task && content.prompt) prompt = content.prompt + '\n\n' + prompt;
93
+ const resources = process.platform === 'darwin' ? process.env.EASYAGENTS_MAC_RESOURCES
94
+ : process.platform === 'linux' ? process.env.EASYAGENTS_DESKTOP_RESOURCES : undefined;
95
+ if (resources && ['codex', 'claude_code'].includes(content.agent?.tool_type) && (task || content.run_kind === 'chat')) {
96
+ let credential;
97
+ if (content.chat_mode === 'work' && !content.passthrough && workCredential) {
98
+ try {
99
+ credential = workCredential(content);
100
+ } catch {
101
+ credential = null;
102
+ }
103
+ }
104
+ return desktopConversation(resources, content, prompt, signal, credential);
105
+ }
106
+ if ((!task && (content.run_kind !== 'chat' || content.chat_mode !== 'chat')) || content.agent?.tool_type !== 'claude_code') {
107
+ return { status: 'failed', failure_code: 'unsupported_task', failure_detail: '当前独立客户端支持计算、成员同步及 Claude 文本任务' };
108
+ }
109
+ if (content.resume_session_ref) {
110
+ return { status: 'failed', failure_code: 'unsupported_session', failure_detail: '此版本仅支持独立文本任务' };
111
+ }
112
+ // No host tools, workspace instructions or MCP servers are needed for a text task.
113
+ const cwd = await mkdtemp(join(tmpdir(), 'easy-agents-text-'));
114
+ try {
115
+ const args = ['--bare', '--print', '--output-format', 'json', '--tools', '', '--strict-mcp-config',
116
+ '--disable-slash-commands', '--no-session-persistence'];
117
+ if (content.requested_model) {
118
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9.:/_-]{0,127}$/.test(content.requested_model)) throw new Error('模型名称无效');
119
+ args.push('--model', content.requested_model);
120
+ }
121
+ const seconds = Number.isSafeInteger(content.timeout_seconds) && content.timeout_seconds > 0 ? content.timeout_seconds : 3600;
122
+ const raw = await invoke('claude', args, cwd, prompt, signal, Math.min(seconds, 3600) * 1000);
123
+ const result = JSON.parse(raw);
124
+ if (result.type !== 'result' || result.subtype !== 'success' || result.is_error ||
125
+ typeof result.result !== 'string' || !result.result || result.result.length > 1000000) throw new Error('工具输出无效');
126
+ return { status: 'succeeded', reply_text: result.result };
127
+ } catch (err) {
128
+ if (signal.aborted) return { status: 'cancelled', failure_code: 'cancelled' };
129
+ return { status: 'failed', failure_code: err.code === 'ENOENT' ? 'tool_missing' : 'tool_failed',
130
+ failure_detail: err.code === 'ENOENT' ? '设备未安装 Claude CLI' : '文本执行工具未完成任务' };
131
+ } finally {
132
+ await rm(cwd, { recursive: true, force: true });
133
+ }
134
+ }
@@ -0,0 +1,66 @@
1
+ import { spawn, spawnSync } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+ import WebSocket from 'ws';
4
+
5
+ const script = fileURLToPath(new URL('../runtime/ssh_terminal.py', import.meta.url));
6
+ const args = ['-I', '-S', '-B', script];
7
+ const uuid = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
8
+ const dimension = n => Number.isInteger(n) && n >= 1 && n <= 1000;
9
+
10
+ export function terminalAvailable() {
11
+ return process.env.EASYAGENTS_TERMINAL !== '0' && process.platform !== 'win32' &&
12
+ spawnSync('python3', [...args, '--check'], { timeout: 3000, stdio: 'ignore' }).status === 0;
13
+ }
14
+
15
+ export function openTerminal(origin, headers, id, sessions) {
16
+ if (typeof id !== 'string' || !uuid.test(id) || sessions.has(id) || sessions.size >= 4) return;
17
+ const ws = new WebSocket(new URL('/ws/client/terminal/' + id, origin),
18
+ { headers, handshakeTimeout: 10000, followRedirects: false, maxPayload: 65536 });
19
+ sessions.set(id, ws);
20
+ let child;
21
+ let lastSeen = Date.now();
22
+ const close = () => ws.terminate();
23
+ const idle = setInterval(() => { if (Date.now() - lastSeen > 90000) close(); }, 10000);
24
+ ws.on('error', close);
25
+ ws.once('close', () => {
26
+ clearInterval(idle);
27
+ sessions.delete(id);
28
+ child?.kill();
29
+ });
30
+ ws.on('message', (raw, binary) => {
31
+ lastSeen = Date.now();
32
+ if (binary) {
33
+ if (!child || child.stdin.writableLength > 262144) return close();
34
+ child.stdin.write(raw);
35
+ return;
36
+ }
37
+ try {
38
+ const msg = JSON.parse(raw.toString());
39
+ if (msg.type === 'ping') return ws.send(JSON.stringify({ type: 'pong' }));
40
+ if (msg.type === 'close') return ws.close();
41
+ if (!dimension(msg.cols) || !dimension(msg.rows)) return close();
42
+ if (msg.type === 'start' && !child) {
43
+ child = spawn('python3', [...args, String(msg.cols), String(msg.rows)], {
44
+ stdio: ['pipe', 'pipe', 'ignore', 'pipe'],
45
+ });
46
+ child.on('error', close);
47
+ child.stdin.on('error', close);
48
+ child.stdio[3].on('error', close);
49
+ child.stdout.on('data', chunk => {
50
+ if (ws.readyState !== WebSocket.OPEN) return;
51
+ child.stdout.pause();
52
+ ws.send(chunk, err => err ? close() : child.stdout.resume());
53
+ });
54
+ child.once('close', code => {
55
+ if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'exit', code: code ?? 1 }), () => ws.close());
56
+ });
57
+ } else if (msg.type === 'resize' && child) {
58
+ if (child.stdio[3].writableLength > 4096) return close();
59
+ const size = Buffer.alloc(4);
60
+ size.writeUInt16BE(msg.cols);
61
+ size.writeUInt16BE(msg.rows, 2);
62
+ child.stdio[3].write(size);
63
+ } else close();
64
+ } catch { close(); }
65
+ });
66
+ }
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
2
+ Copyright (c) 2013 Arnout Kazemier and contributors
3
+ Copyright (c) 2016 Luigi Pinca and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.