@unionschool/easy-agents 0.3.0 → 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.
- package/README.md +70 -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 +70 -19
- package/bin/tasks.js +40 -2
- package/package.json +6 -1
- 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 +165 -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,41 @@ 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(
|
|
42
|
+
const gatewayRequest = async (method, path, body, extraSignal) => {
|
|
43
|
+
const res = await fetch(new URL(path, url), { method,
|
|
43
44
|
headers: { ...headers, 'Content-Type': 'application/json' }, redirect: 'error',
|
|
44
|
-
signal: AbortSignal.any([signal, AbortSignal.timeout(20000)]),
|
|
45
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(20000), ...(extraSignal ? [extraSignal] : [])]),
|
|
45
46
|
body: body === undefined ? undefined : JSON.stringify(body) });
|
|
46
47
|
const data = await res.json().catch(() => null);
|
|
47
48
|
if (!res.ok) throw new GatewayError(res.status, data?.code);
|
|
48
49
|
if (data?.code !== 0) throw new Error('无效的平台响应');
|
|
49
50
|
return data.data;
|
|
50
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
|
+
}
|
|
51
75
|
function checkpoint(id, data) {
|
|
52
76
|
const tmp = join(folder, randomUUID() + '.tmp');
|
|
53
77
|
try {
|
|
@@ -85,15 +109,16 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
85
109
|
await request('POST', id + '/start', { tool_version: version });
|
|
86
110
|
checkpoint(id, { started: true });
|
|
87
111
|
if (ack?.status === 'running') result = { status: 'interrupted', failure_code: 'client_interrupted' };
|
|
88
|
-
try { result ??= await execute(content, controller.signal); }
|
|
112
|
+
try { result ??= await execute(content, controller.signal, workCredential); }
|
|
89
113
|
catch { result = controller.signal.aborted ? { status: 'cancelled', failure_code: 'cancelled' } :
|
|
90
114
|
{ status: 'failed', failure_code: 'client_error', failure_detail: '客户端执行失败' }; }
|
|
91
115
|
}
|
|
92
|
-
result.tool_version
|
|
116
|
+
result.tool_version ??= version;
|
|
93
117
|
checkpoint(id, { result });
|
|
94
118
|
}
|
|
95
119
|
await request('POST', id + '/finish', result);
|
|
96
120
|
rmSync(join(folder, id + '.json'), { force: true });
|
|
121
|
+
reporter?.patch({ lastResult: { id, status: result.status, at: Date.now() } });
|
|
97
122
|
console.log('运行 ' + id + ' 已回传 ' + result.status);
|
|
98
123
|
}
|
|
99
124
|
function startQueue() {
|
|
@@ -102,6 +127,7 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
102
127
|
while (online && !signal.aborted && queue.size) {
|
|
103
128
|
const [id, controller] = queue.entries().next().value;
|
|
104
129
|
active = controller;
|
|
130
|
+
reporter?.patch({ task: id });
|
|
105
131
|
try { await processRun(id, controller); }
|
|
106
132
|
catch (err) {
|
|
107
133
|
if (err.status === 404 || err.status === 409) rmSync(join(folder, id + '.json'), { force: true });
|
|
@@ -111,9 +137,9 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
111
137
|
socket?.terminate();
|
|
112
138
|
return;
|
|
113
139
|
}
|
|
114
|
-
} finally { queue.delete(id); active = undefined; }
|
|
140
|
+
} finally { queue.delete(id); active = undefined; reporter?.patch({ task: null }); }
|
|
115
141
|
}
|
|
116
|
-
})().finally(() => { worker = undefined; if (online) startQueue(); });
|
|
142
|
+
})().finally(() => { worker = undefined; checkDrained(); if (online) startQueue(); });
|
|
117
143
|
}
|
|
118
144
|
function enqueue(id, cancelled = false) {
|
|
119
145
|
if (!validId(id)) return;
|
|
@@ -126,9 +152,27 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
126
152
|
socket?.terminate();
|
|
127
153
|
}
|
|
128
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 });
|
|
129
157
|
let delay = 1000;
|
|
130
158
|
try {
|
|
131
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 };
|
|
132
176
|
let lastSeen = Date.now(), welcomed = false;
|
|
133
177
|
socket = new WebSocket(wsUrl, { headers, followRedirects: false, handshakeTimeout: 15000, maxPayload: 1048576 });
|
|
134
178
|
const current = socket;
|
|
@@ -137,7 +181,7 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
137
181
|
if ([401, 403].includes(res.statusCode)) fatal = new Error('设备认证失败,请重新配对');
|
|
138
182
|
res.destroy(); current.terminate();
|
|
139
183
|
});
|
|
140
|
-
current.on('open', () => current.send(JSON.stringify(
|
|
184
|
+
current.on('open', () => current.send(JSON.stringify(hello)));
|
|
141
185
|
current.on('message', async raw => {
|
|
142
186
|
try {
|
|
143
187
|
const msg = JSON.parse(raw.toString());
|
|
@@ -146,26 +190,32 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
146
190
|
if (!welcomed) {
|
|
147
191
|
if (msg.type !== 'welcome' || msg.device_id !== device.device_id) throw new Error();
|
|
148
192
|
welcomed = online = true; delay = 1000;
|
|
193
|
+
reporter?.welcome(hello, msg, reportQuota, () => current.terminate());
|
|
149
194
|
console.log('设备已上线');
|
|
150
195
|
const pending = await request('GET', 'pending');
|
|
151
196
|
if (current !== socket || current.readyState !== WebSocket.OPEN) return;
|
|
152
197
|
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);
|
|
198
|
+
if (!drain?.aborted) for (const row of pending) enqueue(row.run_id);
|
|
154
199
|
startQueue();
|
|
155
|
-
|
|
156
|
-
else if (msg.type === '
|
|
157
|
-
else if (msg.type === '
|
|
158
|
-
else if (msg.type === '
|
|
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);
|
|
159
206
|
} catch (error) {
|
|
160
207
|
if ([401, 403].includes(error.status)) fatal = new Error('设备认证失败,请重新配对');
|
|
161
208
|
current.terminate();
|
|
162
209
|
}
|
|
163
210
|
});
|
|
164
|
-
const timer = setInterval(() => {
|
|
211
|
+
const timer = setInterval(() => {
|
|
212
|
+
if (terminalSetting !== (reporter?.terminalEnabled?.() ?? true) || Date.now() - lastSeen > (welcomed ? 90000 : 15000)) current.terminate();
|
|
213
|
+
}, 2000);
|
|
165
214
|
try { await new Promise(resolve => current.once('close', resolve)); }
|
|
166
215
|
finally {
|
|
167
216
|
clearInterval(timer);
|
|
168
217
|
online = false;
|
|
218
|
+
reporter?.disconnect();
|
|
169
219
|
for (const session of sessions.values()) session.terminate();
|
|
170
220
|
}
|
|
171
221
|
if (!signal.aborted && !fatal) {
|
|
@@ -176,6 +226,7 @@ export async function runDevice(device, configDir, version, signal) {
|
|
|
176
226
|
}
|
|
177
227
|
} finally {
|
|
178
228
|
signal.removeEventListener('abort', stop);
|
|
229
|
+
drain?.removeEventListener('abort', checkDrained);
|
|
179
230
|
active?.abort();
|
|
180
231
|
await worker;
|
|
181
232
|
}
|
package/bin/tasks.js
CHANGED
|
@@ -14,6 +14,31 @@ 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
|
+
|
|
17
42
|
async function workspace(content) {
|
|
18
43
|
const local = content.workspace?.local_path;
|
|
19
44
|
if (!local || typeof local !== 'string') throw new Error('缺少工作目录');
|
|
@@ -40,7 +65,7 @@ async function sync(content, signal) {
|
|
|
40
65
|
}
|
|
41
66
|
}
|
|
42
67
|
|
|
43
|
-
export async function execute(content, signal) {
|
|
68
|
+
export async function execute(content, signal, workCredential) {
|
|
44
69
|
signal.throwIfAborted();
|
|
45
70
|
if (content.run_kind === 'sync') return sync(content, signal);
|
|
46
71
|
let prompt = content.prompt;
|
|
@@ -64,13 +89,26 @@ export async function execute(content, signal) {
|
|
|
64
89
|
const digest = createHash('sha256').update(prompt.slice('/sha256 '.length), 'utf8').digest('hex');
|
|
65
90
|
return { status: 'succeeded', reply_text: digest };
|
|
66
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
|
+
}
|
|
67
106
|
if ((!task && (content.run_kind !== 'chat' || content.chat_mode !== 'chat')) || content.agent?.tool_type !== 'claude_code') {
|
|
68
107
|
return { status: 'failed', failure_code: 'unsupported_task', failure_detail: '当前独立客户端支持计算、成员同步及 Claude 文本任务' };
|
|
69
108
|
}
|
|
70
109
|
if (content.resume_session_ref) {
|
|
71
110
|
return { status: 'failed', failure_code: 'unsupported_session', failure_detail: '此版本仅支持独立文本任务' };
|
|
72
111
|
}
|
|
73
|
-
if (task && content.prompt) prompt = content.prompt + '\n\n' + prompt;
|
|
74
112
|
// No host tools, workspace instructions or MCP servers are needed for a text task.
|
|
75
113
|
const cwd = await mkdtemp(join(tmpdir(), 'easy-agents-text-'));
|
|
76
114
|
try {
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unionschool/easy-agents",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "EasyAgents Client",
|
|
5
|
+
"easyAgentsDesktop": 1,
|
|
5
6
|
"type": "module",
|
|
6
7
|
"bin": {
|
|
7
8
|
"easy-agents": "bin/easy-agents.js"
|
|
@@ -12,8 +13,12 @@
|
|
|
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",
|
|
21
|
+
"runtime/desktop_chat.py",
|
|
17
22
|
"runtime/easyagents_core/*.py"
|
|
18
23
|
],
|
|
19
24
|
"engines": {
|
|
@@ -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))
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""运行前只核对本地文件;不依赖同步软件或 Git 元数据。"""
|
|
2
|
+
import hashlib
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import re
|
|
6
|
+
import stat
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
from .git_sync import GitError
|
|
10
|
+
|
|
11
|
+
INTERVAL = 10
|
|
12
|
+
TIMEOUT = 60
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def validate_name(name):
|
|
16
|
+
if (not isinstance(name, str) or not name or len(name) > 512
|
|
17
|
+
or '\\' in name or ':' in name or any(ord(c) < 32 or ord(c) == 127 for c in name)
|
|
18
|
+
or any(p in ('', '.', '..') or p.casefold() == '.git' for p in name.split('/'))):
|
|
19
|
+
raise GitError('file_delivery_invalid', '文件交付路径无效')
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def target(root: Path, name: str) -> Path:
|
|
23
|
+
validate_name(name)
|
|
24
|
+
root = root.resolve()
|
|
25
|
+
path = root / name
|
|
26
|
+
if any(p.is_symlink() for p in (path, *path.parents) if p != root and root in p.parents):
|
|
27
|
+
raise GitError('file_delivery_invalid', '文件交付不能经过符号链接')
|
|
28
|
+
if not path.resolve().is_relative_to(root):
|
|
29
|
+
raise GitError('file_delivery_invalid', '文件交付路径超出工作目录')
|
|
30
|
+
return path
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def digest(path: Path, *, task_content=False, deadline=None, cancel=None) -> str | None:
|
|
34
|
+
try:
|
|
35
|
+
fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0))
|
|
36
|
+
with os.fdopen(fd, 'rb') as stream:
|
|
37
|
+
info = os.fstat(stream.fileno())
|
|
38
|
+
if not stat.S_ISREG(info.st_mode):
|
|
39
|
+
raise GitError('file_delivery_read', '交付对象须为普通文件')
|
|
40
|
+
task_content = task_content and info.st_size <= 512 * 1024
|
|
41
|
+
hashed = hashlib.sha256()
|
|
42
|
+
blocks = iter(stream.readline, b'') if task_content else iter(lambda: stream.read(1024 * 1024), b'')
|
|
43
|
+
for index, line in enumerate(blocks):
|
|
44
|
+
if cancel is not None and cancel.is_set():
|
|
45
|
+
raise GitError('cancelled', '已取消')
|
|
46
|
+
if deadline is not None and time.monotonic() > deadline:
|
|
47
|
+
raise GitError('file_delivery_timeout', '文件核验等待到期')
|
|
48
|
+
if task_content:
|
|
49
|
+
# 发布后只回填平台任务ID,不应使同一份任务正文失配。
|
|
50
|
+
if index < 32 and line.startswith('- 平台任务 ID:'.encode()):
|
|
51
|
+
value = line.decode('utf-8', errors='replace').split(':', 1)[1].strip()
|
|
52
|
+
if value in ('待回填', '—') or re.fullmatch(r'[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}', value):
|
|
53
|
+
continue
|
|
54
|
+
hashed.update(line)
|
|
55
|
+
return hashed.hexdigest()
|
|
56
|
+
except FileNotFoundError:
|
|
57
|
+
return None
|
|
58
|
+
except OSError:
|
|
59
|
+
raise GitError('file_delivery_read', '暂时无法核对交付文件') from None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def manifest(root: Path, paths: list[str]) -> list[dict]:
|
|
63
|
+
# shortcut: 只核对声明的本次文件;需要自动发现漏报时再增加受控工作区快照。
|
|
64
|
+
if (not isinstance(paths, list) or not 1 <= len(paths) <= 5000
|
|
65
|
+
or not all(isinstance(p, str) for p in paths) or len(set(paths)) != len(paths)):
|
|
66
|
+
raise GitError('file_delivery_invalid', '须提供不重复的本次变更文件清单')
|
|
67
|
+
files = []
|
|
68
|
+
for name in paths:
|
|
69
|
+
path = target(root, name)
|
|
70
|
+
item = dict(path=name, sha256=digest(path))
|
|
71
|
+
if item['sha256'] and path.name in ('任务.md', 'task.md'):
|
|
72
|
+
item['task_sha256'] = digest(path, task_content=True)
|
|
73
|
+
files.append(item)
|
|
74
|
+
return files
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def validate(root: Path, files: list[dict], *, check_target=True):
|
|
78
|
+
if not isinstance(files, list) or not 1 <= len(files) <= 5000:
|
|
79
|
+
raise GitError('file_delivery_invalid', '缺少本次文件交付依据')
|
|
80
|
+
seen = set()
|
|
81
|
+
for item in files:
|
|
82
|
+
if (not isinstance(item, dict) or not {'path', 'sha256'} <= set(item)
|
|
83
|
+
or set(item) - {'path', 'sha256', 'task_sha256'}
|
|
84
|
+
or not isinstance(item['path'], str) or item['path'] in seen
|
|
85
|
+
or (item['sha256'] is not None and
|
|
86
|
+
(not isinstance(item['sha256'], str) or not re.fullmatch('[0-9a-f]{64}', item['sha256'])))):
|
|
87
|
+
raise GitError('file_delivery_invalid', '本次文件交付依据无效')
|
|
88
|
+
if 'task_sha256' in item and (Path(item['path']).name not in ('任务.md', 'task.md')
|
|
89
|
+
or not item['sha256'] or not isinstance(item['task_sha256'], str)
|
|
90
|
+
or not re.fullmatch('[0-9a-f]{64}', item['task_sha256'])):
|
|
91
|
+
raise GitError('file_delivery_invalid', '任务正文摘要无效')
|
|
92
|
+
if check_target:
|
|
93
|
+
target(root, item['path'])
|
|
94
|
+
else:
|
|
95
|
+
validate_name(item['path'])
|
|
96
|
+
seen.add(item['path'])
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def observed(root, item, *, deadline, cancel):
|
|
100
|
+
path = target(root, item['path'])
|
|
101
|
+
actual = digest(path, deadline=deadline, cancel=cancel)
|
|
102
|
+
matches = actual == item['sha256'] or (actual and item.get('task_sha256') and
|
|
103
|
+
digest(path, task_content=True, deadline=deadline, cancel=cancel) == item['task_sha256'])
|
|
104
|
+
return matches, actual
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def ready(root: Path, files: list[dict], *, deadline=None, cancel=None) -> bool:
|
|
108
|
+
validate(root, files)
|
|
109
|
+
try:
|
|
110
|
+
return all(observed(root, item, deadline=deadline, cancel=cancel)[0] for item in files)
|
|
111
|
+
except GitError as exc:
|
|
112
|
+
if exc.code not in ('file_delivery_read', 'file_delivery_timeout'):
|
|
113
|
+
raise
|
|
114
|
+
return False
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def differences(root, files, *, deadline, cancel):
|
|
118
|
+
results = []
|
|
119
|
+
for item in files:
|
|
120
|
+
if cancel.is_set():
|
|
121
|
+
raise GitError('cancelled', '已取消')
|
|
122
|
+
try:
|
|
123
|
+
if deadline is not None and time.monotonic() > deadline:
|
|
124
|
+
raise GitError('file_delivery_timeout', '文件核验等待到期')
|
|
125
|
+
matched, actual = observed(root, item, deadline=deadline, cancel=cancel)
|
|
126
|
+
if matched:
|
|
127
|
+
continue
|
|
128
|
+
results.append(dict(path=item['path'], reason='changed' if actual else 'missing', sha256=actual))
|
|
129
|
+
except GitError as exc:
|
|
130
|
+
if exc.code not in ('file_delivery_invalid', 'file_delivery_read', 'file_delivery_timeout'):
|
|
131
|
+
raise
|
|
132
|
+
results.append(dict(path=item['path'], reason='unreadable', sha256=None))
|
|
133
|
+
except (OSError, RuntimeError):
|
|
134
|
+
results.append(dict(path=item['path'], reason='unreadable', sha256=None))
|
|
135
|
+
return results
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def wait(root: Path, files: list[dict], cancel, *, timeout=TIMEOUT, interval=INTERVAL,
|
|
139
|
+
report: list | None = None) -> bool:
|
|
140
|
+
validate(root, files, check_target=report is None)
|
|
141
|
+
deadline = time.monotonic() + timeout
|
|
142
|
+
final_check = deadline - min(0.25, timeout / 2)
|
|
143
|
+
while True:
|
|
144
|
+
if cancel.is_set():
|
|
145
|
+
raise GitError('cancelled', '已取消')
|
|
146
|
+
if report is not None:
|
|
147
|
+
last = time.monotonic() >= final_check
|
|
148
|
+
report[:] = differences(root, files, deadline=deadline if timeout else None,
|
|
149
|
+
cancel=cancel)
|
|
150
|
+
if not report:
|
|
151
|
+
return True
|
|
152
|
+
if last:
|
|
153
|
+
cancel.wait(max(0, deadline - time.monotonic()))
|
|
154
|
+
if cancel.is_set():
|
|
155
|
+
raise GitError('cancelled', '已取消')
|
|
156
|
+
return False
|
|
157
|
+
cancel.wait(max(0, min(interval, final_check - time.monotonic())))
|
|
158
|
+
continue
|
|
159
|
+
else:
|
|
160
|
+
is_ready = ready(root, files, deadline=deadline, cancel=cancel)
|
|
161
|
+
if is_ready:
|
|
162
|
+
return True
|
|
163
|
+
remaining = deadline - time.monotonic()
|
|
164
|
+
if remaining <= 0:
|
|
165
|
+
return False
|
|
166
|
+
cancel.wait(min(interval, remaining))
|