@unionschool/easy-agents 0.3.0 → 0.4.0
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 +72 -23
- package/bin/easy-agents.js +121 -11
- package/bin/mac-reports.js +149 -0
- package/bin/mac-service.js +119 -0
- package/bin/portable-service.js +66 -0
- package/bin/run.js +114 -26
- package/bin/tasks.js +84 -5
- package/package.json +13 -4
- package/runtime/desktop_chat.py +105 -0
- package/runtime/easyagents_core/file_delivery.py +166 -0
- package/runtime/easyagents_core/git_sync.py +18 -2
- package/runtime/easyagents_core/mcp_call.py +187 -0
- package/runtime/mcp.py +16 -0
- package/runtime/sync.py +4 -1
- package/runtime/task_run.py +134 -0
|
@@ -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
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
-
import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
3
4
|
import { join } from 'node:path';
|
|
4
5
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
5
6
|
import WebSocket from 'ws';
|
|
@@ -17,15 +18,16 @@ class GatewayError extends Error {
|
|
|
17
18
|
}
|
|
18
19
|
}
|
|
19
20
|
|
|
20
|
-
export async function runDevice(device, configDir, version, signal) {
|
|
21
|
+
export async function runDevice(device, configDir, version, signal, { reporter, drain, onDrained, terminalProbe = terminalAvailable } = {}) {
|
|
21
22
|
const url = new URL(device.gateway);
|
|
22
23
|
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname))) {
|
|
23
24
|
throw new Error('远程网关需要 HTTPS');
|
|
24
25
|
}
|
|
25
26
|
const wsUrl = new URL('/ws/client', url);
|
|
26
27
|
wsUrl.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
27
|
-
|
|
28
|
-
|
|
28
|
+
const wsOverride = process.env.EASYAGENTS_WS_ORIGIN || device.ws_origin;
|
|
29
|
+
if (wsOverride) {
|
|
30
|
+
const wsOrigin = new URL(wsOverride);
|
|
29
31
|
if (wsOrigin.protocol !== 'wss:' || wsOrigin.username || wsOrigin.password ||
|
|
30
32
|
wsOrigin.pathname !== '/' || wsOrigin.search || wsOrigin.hash) throw new Error('WebSocket 网关须为 WSS 地址');
|
|
31
33
|
wsUrl.href = new URL('/ws/client', wsOrigin).href;
|
|
@@ -35,19 +37,83 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
35
37
|
const folder = join(configDir, 'npm-runs', binding);
|
|
36
38
|
mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
37
39
|
const queue = new Map();
|
|
38
|
-
const terminal = terminalAvailable();
|
|
39
40
|
const sessions = new Map();
|
|
40
41
|
let socket, worker, online = false, active, fatal;
|
|
41
|
-
const
|
|
42
|
-
const res = await fetch(new URL(
|
|
43
|
-
|
|
44
|
-
|
|
42
|
+
const gatewayRequest = async (method, path, body, extraSignal) => {
|
|
43
|
+
const res = await fetch(new URL(path, url), { method,
|
|
44
|
+
// Without the Git delivery header the platform withholds task-branch runs (42298).
|
|
45
|
+
headers: { ...headers, 'X-EasyAgents-Git-Delivery': '1', 'Content-Type': 'application/json' }, redirect: 'error',
|
|
46
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(20000), ...(extraSignal ? [extraSignal] : [])]),
|
|
45
47
|
body: body === undefined ? undefined : JSON.stringify(body) });
|
|
46
48
|
const data = await res.json().catch(() => null);
|
|
47
49
|
if (!res.ok) throw new GatewayError(res.status, data?.code);
|
|
48
50
|
if (data?.code !== 0) throw new Error('无效的平台响应');
|
|
49
51
|
return data.data;
|
|
50
52
|
};
|
|
53
|
+
const request = (method, path, body) => gatewayRequest(method, '/api/client/runs/' + path, body);
|
|
54
|
+
const reportQuota = (id, body, cancel) => gatewayRequest('POST', '/api/client/agents/' + id + '/quota', body, cancel);
|
|
55
|
+
function workCredential(content) {
|
|
56
|
+
const id = content.agent?.agent_id;
|
|
57
|
+
if (!/^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/i.test(id)) throw new Error('Agent 编号无效');
|
|
58
|
+
const dir = join(configDir, 'agents');
|
|
59
|
+
const file = join(dir, id + '.json');
|
|
60
|
+
const files = [file];
|
|
61
|
+
if (process.platform === 'darwin' && configDir === join(homedir(), 'Library/Application Support/EasyAgents Client')) {
|
|
62
|
+
files.push(join(homedir(), '.easyagents', 'agents', id + '.json'));
|
|
63
|
+
}
|
|
64
|
+
for (const path of files) {
|
|
65
|
+
try {
|
|
66
|
+
const info = lstatSync(path);
|
|
67
|
+
if (!info.isFile() || info.uid !== process.getuid() || (info.mode & 0o077)) throw new Error('Agent 凭据文件无效');
|
|
68
|
+
return { file: path, gateway: url.origin };
|
|
69
|
+
} catch (err) { if (err.code !== 'ENOENT') throw err; }
|
|
70
|
+
}
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
async function credentialWorks(file) {
|
|
74
|
+
let auth;
|
|
75
|
+
try { auth = JSON.parse(readFileSync(file, 'utf8')); } catch { return false; }
|
|
76
|
+
if (typeof auth?.server !== 'string' || auth.server.replace(/\/+$/, '') !== url.origin || !auth.agent_token) return false;
|
|
77
|
+
try {
|
|
78
|
+
const res = await fetch(new URL('/mcp', url), { method: 'POST', redirect: 'error',
|
|
79
|
+
headers: { Authorization: 'Bearer ' + auth.agent_token, 'Content-Type': 'application/json',
|
|
80
|
+
Accept: 'application/json, text/event-stream' },
|
|
81
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26',
|
|
82
|
+
capabilities: {}, clientInfo: { name: 'easyagents-client', version } } }),
|
|
83
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(20000)]) });
|
|
84
|
+
await res.body?.cancel();
|
|
85
|
+
return ![401, 403].includes(res.status);
|
|
86
|
+
} catch {
|
|
87
|
+
return true; // Network trouble is not proof of a revoked credential; the run reports what fails.
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
// Task runs need a working Agent credential for the platform tools. A missing, mismatched or
|
|
91
|
+
// revoked one is replaced; the platform revokes the previous credential when it issues a new one.
|
|
92
|
+
async function agentCredential(content) {
|
|
93
|
+
const id = content.agent?.agent_id;
|
|
94
|
+
if (!/^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/i.test(id)) throw new Error('Agent 编号无效');
|
|
95
|
+
let found = null;
|
|
96
|
+
try { found = workCredential(content); } catch {}
|
|
97
|
+
if (found && await credentialWorks(found.file)) return found.file;
|
|
98
|
+
const issued = await gatewayRequest('POST', '/api/client/agents/' + id + '/credential', {});
|
|
99
|
+
if (typeof issued?.agent_token !== 'string' || !issued.agent_token) throw new Error('Agent 凭据响应无效');
|
|
100
|
+
const dir = join(configDir, 'agents');
|
|
101
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
102
|
+
const file = join(dir, id + '.json');
|
|
103
|
+
const tmp = join(dir, '.agent-' + randomUUID());
|
|
104
|
+
try {
|
|
105
|
+
writeFileSync(tmp, '', { flag: 'wx', mode: 0o600 });
|
|
106
|
+
protectDeviceFile(tmp);
|
|
107
|
+
writeFileSync(tmp, JSON.stringify({ server: url.origin, agent_token: issued.agent_token }));
|
|
108
|
+
renameSync(tmp, file);
|
|
109
|
+
} finally {
|
|
110
|
+
rmSync(tmp, { force: true });
|
|
111
|
+
}
|
|
112
|
+
return file;
|
|
113
|
+
}
|
|
114
|
+
function checkDrained() {
|
|
115
|
+
if (drain?.aborted && !active && !queue.size && !readdirSync(folder).some(f => f.endsWith('.json'))) onDrained?.();
|
|
116
|
+
}
|
|
51
117
|
function checkpoint(id, data) {
|
|
52
118
|
const tmp = join(folder, randomUUID() + '.tmp');
|
|
53
119
|
try {
|
|
@@ -76,24 +142,20 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
76
142
|
rmSync(join(folder, id + '.json'), { force: true });
|
|
77
143
|
return;
|
|
78
144
|
}
|
|
79
|
-
|
|
80
|
-
try { content = await request('GET', id); }
|
|
81
|
-
catch (err) {
|
|
82
|
-
if (err.code !== 42298) throw err;
|
|
83
|
-
result = { status: 'failed', failure_code: 'git_delivery_unsupported', failure_detail: '此版尚不支持 Git 任务分支交付' };
|
|
84
|
-
}
|
|
145
|
+
const content = await request('GET', id);
|
|
85
146
|
await request('POST', id + '/start', { tool_version: version });
|
|
86
147
|
checkpoint(id, { started: true });
|
|
87
148
|
if (ack?.status === 'running') result = { status: 'interrupted', failure_code: 'client_interrupted' };
|
|
88
|
-
try { result ??= await execute(content, controller.signal); }
|
|
149
|
+
try { result ??= await execute(content, controller.signal, workCredential, { agentCredential, configDir }); }
|
|
89
150
|
catch { result = controller.signal.aborted ? { status: 'cancelled', failure_code: 'cancelled' } :
|
|
90
151
|
{ status: 'failed', failure_code: 'client_error', failure_detail: '客户端执行失败' }; }
|
|
91
152
|
}
|
|
92
|
-
result.tool_version
|
|
153
|
+
result.tool_version ??= version;
|
|
93
154
|
checkpoint(id, { result });
|
|
94
155
|
}
|
|
95
156
|
await request('POST', id + '/finish', result);
|
|
96
157
|
rmSync(join(folder, id + '.json'), { force: true });
|
|
158
|
+
reporter?.patch({ lastResult: { id, status: result.status, at: Date.now() } });
|
|
97
159
|
console.log('运行 ' + id + ' 已回传 ' + result.status);
|
|
98
160
|
}
|
|
99
161
|
function startQueue() {
|
|
@@ -102,6 +164,7 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
102
164
|
while (online && !signal.aborted && queue.size) {
|
|
103
165
|
const [id, controller] = queue.entries().next().value;
|
|
104
166
|
active = controller;
|
|
167
|
+
reporter?.patch({ task: id });
|
|
105
168
|
try { await processRun(id, controller); }
|
|
106
169
|
catch (err) {
|
|
107
170
|
if (err.status === 404 || err.status === 409) rmSync(join(folder, id + '.json'), { force: true });
|
|
@@ -111,9 +174,9 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
111
174
|
socket?.terminate();
|
|
112
175
|
return;
|
|
113
176
|
}
|
|
114
|
-
} finally { queue.delete(id); active = undefined; }
|
|
177
|
+
} finally { queue.delete(id); active = undefined; reporter?.patch({ task: null }); }
|
|
115
178
|
}
|
|
116
|
-
})().finally(() => { worker = undefined; if (online) startQueue(); });
|
|
179
|
+
})().finally(() => { worker = undefined; checkDrained(); if (online) startQueue(); });
|
|
117
180
|
}
|
|
118
181
|
function enqueue(id, cancelled = false) {
|
|
119
182
|
if (!validId(id)) return;
|
|
@@ -126,9 +189,27 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
126
189
|
socket?.terminate();
|
|
127
190
|
}
|
|
128
191
|
signal.addEventListener('abort', stop, { once: true });
|
|
192
|
+
drain?.addEventListener('abort', checkDrained);
|
|
193
|
+
reporter?.patch({ connected: false, task: null, gateway: url.origin, deviceId: device.device_id });
|
|
129
194
|
let delay = 1000;
|
|
130
195
|
try {
|
|
131
196
|
while (!signal.aborted && !fatal) {
|
|
197
|
+
const terminalSetting = reporter?.terminalEnabled?.() ?? true;
|
|
198
|
+
const terminal = terminalSetting && terminalProbe();
|
|
199
|
+
let metadata = {};
|
|
200
|
+
if (reporter) {
|
|
201
|
+
try { metadata = await reporter.hello(signal); }
|
|
202
|
+
catch {
|
|
203
|
+
if (signal.aborted) break;
|
|
204
|
+
console.error('本机工具信息暂时不可用,正在重试');
|
|
205
|
+
reporter.disconnect();
|
|
206
|
+
await sleep(delay, undefined, { signal }).catch(() => {});
|
|
207
|
+
delay = Math.min(60000, delay * 2);
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
if (signal.aborted) break;
|
|
212
|
+
const hello = { type: 'hello', client_version: version, tools: [], terminal, ...metadata };
|
|
132
213
|
let lastSeen = Date.now(), welcomed = false;
|
|
133
214
|
socket = new WebSocket(wsUrl, { headers, followRedirects: false, handshakeTimeout: 15000, maxPayload: 1048576 });
|
|
134
215
|
const current = socket;
|
|
@@ -137,7 +218,7 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
137
218
|
if ([401, 403].includes(res.statusCode)) fatal = new Error('设备认证失败,请重新配对');
|
|
138
219
|
res.destroy(); current.terminate();
|
|
139
220
|
});
|
|
140
|
-
current.on('open', () => current.send(JSON.stringify(
|
|
221
|
+
current.on('open', () => current.send(JSON.stringify(hello)));
|
|
141
222
|
current.on('message', async raw => {
|
|
142
223
|
try {
|
|
143
224
|
const msg = JSON.parse(raw.toString());
|
|
@@ -146,26 +227,32 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
146
227
|
if (!welcomed) {
|
|
147
228
|
if (msg.type !== 'welcome' || msg.device_id !== device.device_id) throw new Error();
|
|
148
229
|
welcomed = online = true; delay = 1000;
|
|
230
|
+
reporter?.welcome(hello, msg, reportQuota, () => current.terminate());
|
|
149
231
|
console.log('设备已上线');
|
|
150
232
|
const pending = await request('GET', 'pending');
|
|
151
233
|
if (current !== socket || current.readyState !== WebSocket.OPEN) return;
|
|
152
234
|
for (const f of readdirSync(folder)) if (f.endsWith('.json')) enqueue(f.slice(0, -5));
|
|
153
|
-
for (const row of pending) enqueue(row.run_id);
|
|
235
|
+
if (!drain?.aborted) for (const row of pending) enqueue(row.run_id);
|
|
154
236
|
startQueue();
|
|
155
|
-
|
|
156
|
-
else if (msg.type === '
|
|
157
|
-
else if (msg.type === '
|
|
158
|
-
else if (msg.type === '
|
|
237
|
+
checkDrained();
|
|
238
|
+
} else if (msg.type === 'ping') { current.send(JSON.stringify({ type: 'pong' })); reporter?.patch({ heartbeat: Date.now() }); }
|
|
239
|
+
else if (msg.type === 'agent.quota.config') reporter?.configure(msg, reportQuota);
|
|
240
|
+
else if (msg.type === 'terminal.open' && terminal && (reporter?.terminalEnabled?.() ?? true)) openTerminal(wsUrl, headers, msg.session_id, sessions);
|
|
241
|
+
else if (msg.type === 'run.available' && !drain?.aborted) enqueue(msg.run_id);
|
|
242
|
+
else if (msg.type === 'run.cancel' && (!drain?.aborted || queue.has(msg.run_id))) enqueue(msg.run_id, true);
|
|
159
243
|
} catch (error) {
|
|
160
244
|
if ([401, 403].includes(error.status)) fatal = new Error('设备认证失败,请重新配对');
|
|
161
245
|
current.terminate();
|
|
162
246
|
}
|
|
163
247
|
});
|
|
164
|
-
const timer = setInterval(() => {
|
|
248
|
+
const timer = setInterval(() => {
|
|
249
|
+
if (terminalSetting !== (reporter?.terminalEnabled?.() ?? true) || Date.now() - lastSeen > (welcomed ? 90000 : 15000)) current.terminate();
|
|
250
|
+
}, 2000);
|
|
165
251
|
try { await new Promise(resolve => current.once('close', resolve)); }
|
|
166
252
|
finally {
|
|
167
253
|
clearInterval(timer);
|
|
168
254
|
online = false;
|
|
255
|
+
reporter?.disconnect();
|
|
169
256
|
for (const session of sessions.values()) session.terminate();
|
|
170
257
|
}
|
|
171
258
|
if (!signal.aborted && !fatal) {
|
|
@@ -176,6 +263,7 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
176
263
|
}
|
|
177
264
|
} finally {
|
|
178
265
|
signal.removeEventListener('abort', stop);
|
|
266
|
+
drain?.removeEventListener('abort', checkDrained);
|
|
179
267
|
active?.abort();
|
|
180
268
|
await worker;
|
|
181
269
|
}
|
package/bin/tasks.js
CHANGED
|
@@ -14,6 +14,58 @@ function invoke(file, args, cwd, input, signal, timeout) {
|
|
|
14
14
|
});
|
|
15
15
|
}
|
|
16
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
|
+
const TASK_KINDS = ['execute', 'review', 'deploy', 'clarify'];
|
|
43
|
+
|
|
44
|
+
// Mac and Ubuntu desktop installs: Git task-branch runs go to the packaged Python runner.
|
|
45
|
+
function desktopTask(resources, content, signal, options) {
|
|
46
|
+
const runner = fileURLToPath(new URL('../runtime/task_run.py', import.meta.url));
|
|
47
|
+
const seconds = content.timeout_seconds;
|
|
48
|
+
const timeout = Number.isSafeInteger(seconds) && seconds > 0 ? Math.min(seconds, 3600) : 3600;
|
|
49
|
+
const input = { content, timeout, credential: options.credential, worktrees: join(options.configDir, 'worktrees') };
|
|
50
|
+
return new Promise(resolveResult => {
|
|
51
|
+
// Fetch, checkout and push get their own Git timeouts on top of the tool's.
|
|
52
|
+
const child = execFile(join(resources, 'python/bin/python3'), ['-I', '-B', '-X', 'utf8', runner],
|
|
53
|
+
{ timeout: (timeout + 600) * 1000, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => {
|
|
54
|
+
signal.removeEventListener('abort', cancel);
|
|
55
|
+
if (signal.aborted) return resolveResult({ status: 'cancelled', failure_code: 'cancelled' });
|
|
56
|
+
if (!error) {
|
|
57
|
+
try { return resolveResult(JSON.parse(stdout)); } catch {}
|
|
58
|
+
}
|
|
59
|
+
resolveResult({ status: 'failed', failure_code: 'tool_start_failed', failure_detail: '设备任务执行器异常,请检查客户端安装' });
|
|
60
|
+
});
|
|
61
|
+
const cancel = () => child.kill('SIGTERM');
|
|
62
|
+
signal.addEventListener('abort', cancel, { once: true });
|
|
63
|
+
child.stdin.on('error', () => {});
|
|
64
|
+
child.stdin.end(JSON.stringify(input));
|
|
65
|
+
if (signal.aborted) cancel();
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
17
69
|
async function workspace(content) {
|
|
18
70
|
const local = content.workspace?.local_path;
|
|
19
71
|
if (!local || typeof local !== 'string') throw new Error('缺少工作目录');
|
|
@@ -40,15 +92,31 @@ async function sync(content, signal) {
|
|
|
40
92
|
}
|
|
41
93
|
}
|
|
42
94
|
|
|
43
|
-
export async function execute(content, signal) {
|
|
95
|
+
export async function execute(content, signal, workCredential, { agentCredential, configDir } = {}) {
|
|
44
96
|
signal.throwIfAborted();
|
|
45
97
|
if (content.run_kind === 'sync') return sync(content, signal);
|
|
98
|
+
const resources = process.platform === 'darwin' ? process.env.EASYAGENTS_MAC_RESOURCES
|
|
99
|
+
: process.platform === 'linux' ? process.env.EASYAGENTS_DESKTOP_RESOURCES : undefined;
|
|
100
|
+
const versioned = content.task && (content.task.git_delivery || content.task.file_delivery || content.task.document_commit_sha);
|
|
101
|
+
if (TASK_KINDS.includes(content.run_kind) && (versioned || content.run_kind !== 'execute')) {
|
|
102
|
+
// Windows, Android and the plain npm install do not run task branches yet (user 2026-11-22).
|
|
103
|
+
if (!resources || !agentCredential || !configDir) {
|
|
104
|
+
return { status: 'failed', failure_code: 'handoff_unsupported', failure_detail: '任务分支运行目前只支持 Mac 和 Ubuntu 桌面版客户端' };
|
|
105
|
+
}
|
|
106
|
+
if (!['codex', 'claude_code'].includes(content.agent?.tool_type)) {
|
|
107
|
+
return { status: 'failed', failure_code: 'unsupported_task', failure_detail: '此工具尚未接入独立客户端的任务运行' };
|
|
108
|
+
}
|
|
109
|
+
let credential;
|
|
110
|
+
try { credential = await agentCredential(content); }
|
|
111
|
+
catch {
|
|
112
|
+
if (signal.aborted) return { status: 'cancelled', failure_code: 'cancelled' };
|
|
113
|
+
return { status: 'failed', failure_code: 'mcp_credential', failure_detail: '无法取得操作入口凭据,请检查设备认证及平台状态' };
|
|
114
|
+
}
|
|
115
|
+
return desktopTask(resources, content, signal, { credential, configDir });
|
|
116
|
+
}
|
|
46
117
|
let prompt = content.prompt;
|
|
47
118
|
const task = content.run_kind === 'execute' && content.task;
|
|
48
119
|
if (task) {
|
|
49
|
-
if (task.git_delivery || task.file_delivery || task.document_commit_sha) {
|
|
50
|
-
return { status: 'failed', failure_code: 'handoff_unsupported', failure_detail: '当前运行入口尚不支持版本化任务文件交付' };
|
|
51
|
-
}
|
|
52
120
|
const root = await workspace(content);
|
|
53
121
|
const path = task.document_path;
|
|
54
122
|
if (typeof path !== 'string' || isAbsolute(path) || !path.endsWith('.md')) throw new Error('任务文档路径无效');
|
|
@@ -64,13 +132,24 @@ export async function execute(content, signal) {
|
|
|
64
132
|
const digest = createHash('sha256').update(prompt.slice('/sha256 '.length), 'utf8').digest('hex');
|
|
65
133
|
return { status: 'succeeded', reply_text: digest };
|
|
66
134
|
}
|
|
135
|
+
if (task && content.prompt) prompt = content.prompt + '\n\n' + prompt;
|
|
136
|
+
if (resources && ['codex', 'claude_code'].includes(content.agent?.tool_type) && (task || content.run_kind === 'chat')) {
|
|
137
|
+
let credential;
|
|
138
|
+
if (content.chat_mode === 'work' && !content.passthrough && workCredential) {
|
|
139
|
+
try {
|
|
140
|
+
credential = workCredential(content);
|
|
141
|
+
} catch {
|
|
142
|
+
credential = null;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return desktopConversation(resources, content, prompt, signal, credential);
|
|
146
|
+
}
|
|
67
147
|
if ((!task && (content.run_kind !== 'chat' || content.chat_mode !== 'chat')) || content.agent?.tool_type !== 'claude_code') {
|
|
68
148
|
return { status: 'failed', failure_code: 'unsupported_task', failure_detail: '当前独立客户端支持计算、成员同步及 Claude 文本任务' };
|
|
69
149
|
}
|
|
70
150
|
if (content.resume_session_ref) {
|
|
71
151
|
return { status: 'failed', failure_code: 'unsupported_session', failure_detail: '此版本仅支持独立文本任务' };
|
|
72
152
|
}
|
|
73
|
-
if (task && content.prompt) prompt = content.prompt + '\n\n' + prompt;
|
|
74
153
|
// No host tools, workspace instructions or MCP servers are needed for a text task.
|
|
75
154
|
const cwd = await mkdtemp(join(tmpdir(), 'easy-agents-text-'));
|
|
76
155
|
try {
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unionschool/easy-agents",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "EasyAgents Client",
|
|
5
|
+
"easyAgentsDesktop": 1,
|
|
5
6
|
"type": "module",
|
|
6
7
|
"bin": {
|
|
7
8
|
"easy-agents": "bin/easy-agents.js"
|
|
@@ -12,9 +13,19 @@
|
|
|
12
13
|
"bin/run.js",
|
|
13
14
|
"bin/terminal.js",
|
|
14
15
|
"bin/tasks.js",
|
|
16
|
+
"bin/mac-reports.js",
|
|
17
|
+
"bin/mac-service.js",
|
|
18
|
+
"bin/portable-service.js",
|
|
15
19
|
"runtime/sync.py",
|
|
16
20
|
"runtime/ssh_terminal.py",
|
|
17
|
-
"runtime/
|
|
21
|
+
"runtime/desktop_chat.py",
|
|
22
|
+
"runtime/task_run.py",
|
|
23
|
+
"runtime/mcp.py",
|
|
24
|
+
"runtime/easyagents_core/git_sync.py",
|
|
25
|
+
"runtime/easyagents_core/member_sync.py",
|
|
26
|
+
"runtime/easyagents_core/process_support.py",
|
|
27
|
+
"runtime/easyagents_core/file_delivery.py",
|
|
28
|
+
"runtime/easyagents_core/mcp_call.py"
|
|
18
29
|
],
|
|
19
30
|
"engines": {
|
|
20
31
|
"node": ">=22"
|
|
@@ -30,8 +41,6 @@
|
|
|
30
41
|
"ws"
|
|
31
42
|
],
|
|
32
43
|
"scripts": {
|
|
33
|
-
"prepack": "node scripts/bundle-core.js",
|
|
34
|
-
"pretest": "node scripts/bundle-core.js",
|
|
35
44
|
"test": "node --test"
|
|
36
45
|
}
|
|
37
46
|
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Run a project message with the tool adapters shipped in the desktop installation."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import shutil
|
|
5
|
+
import signal
|
|
6
|
+
import sys
|
|
7
|
+
import threading
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from uuid import UUID
|
|
10
|
+
|
|
11
|
+
resources = os.environ.get("EASYAGENTS_MAC_RESOURCES") or os.environ["EASYAGENTS_DESKTOP_RESOURCES"]
|
|
12
|
+
sys.path.insert(0, str(Path(resources) / "lib"))
|
|
13
|
+
from easyagents_core.tools import ClaudeCodeAdapter, CodexAdapter
|
|
14
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TextClaude(ClaudeCodeAdapter):
|
|
18
|
+
def _command(self, resume_session_ref):
|
|
19
|
+
command = [self.executable, "--safe-mode", "--print", "--input-format", "stream-json",
|
|
20
|
+
"--output-format", "stream-json", "--verbose", "--tools", "", "--strict-mcp-config",
|
|
21
|
+
"--disable-slash-commands"]
|
|
22
|
+
if resume_session_ref:
|
|
23
|
+
command.extend(["--resume", resume_session_ref])
|
|
24
|
+
return command
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def failed(code, detail):
|
|
28
|
+
return {"status": "failed", "failure_code": code, "failure_detail": detail}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def workflow_guide(binding, run_id):
|
|
32
|
+
from runtime.easyagents_core.mcp_call import MCPError, request
|
|
33
|
+
|
|
34
|
+
auth = json.loads(Path(binding["file"]).read_text())
|
|
35
|
+
if auth["server"].rstrip("/") != binding["gateway"] or not auth["agent_token"]:
|
|
36
|
+
raise ValueError("Agent 凭据与已配对网关不一致")
|
|
37
|
+
auth["server"] = binding["gateway"]
|
|
38
|
+
os.environ["EASYAGENTS_RUN_ID"] = run_id
|
|
39
|
+
try:
|
|
40
|
+
result = request(auth, "tools/call", {"name": "get_workflow_guide", "arguments": {}})
|
|
41
|
+
except MCPError:
|
|
42
|
+
raise ValueError("平台规程读取失败") from None
|
|
43
|
+
if result.get("isError"):
|
|
44
|
+
raise ValueError("平台规程读取失败")
|
|
45
|
+
text = "\n".join(item["text"] for item in result["content"] if item.get("type") == "text")
|
|
46
|
+
if not text.strip():
|
|
47
|
+
raise ValueError("平台返回的规程为空")
|
|
48
|
+
return text
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def run(content, cancelled):
|
|
52
|
+
tool = content["tool"]
|
|
53
|
+
if tool == "codex":
|
|
54
|
+
adapter = CodexAdapter()
|
|
55
|
+
options = {"sandbox_policy": {"type": "readOnly", "networkAccess": False}}
|
|
56
|
+
elif tool == "claude_code":
|
|
57
|
+
adapter = TextClaude()
|
|
58
|
+
options = {}
|
|
59
|
+
else:
|
|
60
|
+
return failed("unsupported_task", "此工具尚未接入设备文本对话")
|
|
61
|
+
if not shutil.which(adapter.executable):
|
|
62
|
+
return failed("tool_missing", "本机未找到 " + adapter.executable_name)
|
|
63
|
+
|
|
64
|
+
resume = content.get("resume")
|
|
65
|
+
if resume is not None:
|
|
66
|
+
try:
|
|
67
|
+
UUID(resume)
|
|
68
|
+
except (ValueError, AttributeError, TypeError):
|
|
69
|
+
return failed("bad_session", "工具会话标识无效")
|
|
70
|
+
local = content.get("workspace")
|
|
71
|
+
if local:
|
|
72
|
+
cwd = (Path.home() / Path(local).expanduser()).resolve()
|
|
73
|
+
if not cwd.is_dir() or cwd == Path(cwd.anchor):
|
|
74
|
+
return failed("workspace_missing", "请核对该 Agent 在设备上登记的工作目录")
|
|
75
|
+
else:
|
|
76
|
+
# Claude locates earlier conversations by directory even when all tools are disabled.
|
|
77
|
+
cwd = Path(os.environ["EASYAGENTS_CONFIG_DIR"]) / "chat-workspace"
|
|
78
|
+
cwd.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
79
|
+
|
|
80
|
+
prompt = content["prompt"]
|
|
81
|
+
run_id = content.get("workRunId")
|
|
82
|
+
if run_id and not content.get("passthrough"):
|
|
83
|
+
guidance = "平台任务规程当前不可用。可回复普通项目消息;涉及平台登记、派发或审批时,须明确说明未办理。"
|
|
84
|
+
if content.get("credential"):
|
|
85
|
+
try:
|
|
86
|
+
guide = workflow_guide(content["credential"], run_id)
|
|
87
|
+
except (OSError, ValueError, KeyError, TypeError, RuntimeError):
|
|
88
|
+
pass
|
|
89
|
+
else:
|
|
90
|
+
guidance = "平台任务规程:\n" + guide
|
|
91
|
+
prompt = f"本次调度模式:platform;运行编号:{run_id}\n{guidance}\n\n{prompt}"
|
|
92
|
+
result = adapter.invoke(prompt=prompt, cwd=cwd, resume_session_ref=resume,
|
|
93
|
+
timeout_seconds=content["timeout"], cancel_event=cancelled,
|
|
94
|
+
model=content.get("model"), platform_run_id=run_id, **options)
|
|
95
|
+
if result.reply_text and len(result.reply_text) > 1_000_000:
|
|
96
|
+
return failed("bad_output", "工具回复超过平台长度上限")
|
|
97
|
+
fields = ("status", "reply_text", "tool_session_ref", "tool_version", "model_name",
|
|
98
|
+
"usage", "context", "failure_code", "failure_detail")
|
|
99
|
+
return {name: getattr(result, name) for name in fields if getattr(result, name) is not None}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
if __name__ == "__main__":
|
|
103
|
+
cancelled = threading.Event()
|
|
104
|
+
signal.signal(signal.SIGTERM, lambda *_: cancelled.set())
|
|
105
|
+
print(json.dumps(run(json.load(sys.stdin), cancelled), ensure_ascii=False))
|