@unionschool/easy-agents 0.2.2 → 0.3.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 CHANGED
@@ -1,23 +1,47 @@
1
1
  # @unionschool/easy-agents
2
2
 
3
- This local CLI preview of the EasyAgents device client saves a gateway address and port, shows your local configuration, and displays the installed CLI version.
3
+ The EasyAgents device client pairs this computer with a gateway, receives runs and returns their results.
4
4
 
5
5
  ## Install
6
6
 
7
- Requires Node.js 22 or later. Install the npm package in the project where you want to use the preview.
7
+ Requires Node.js 22 or later. Install the npm package in the project where you want to use the client.
8
8
 
9
9
  ```sh
10
10
  npm install @unionschool/easy-agents
11
11
  npm exec --offline -- easy-agents --version
12
12
  ```
13
13
 
14
- ## Configure a gateway
14
+ ## Pair a device
15
+
16
+ Run the following command and enter the gateway, port and one-time pairing code for this device's operating system. A hostname uses HTTPS by default. Press Enter to accept a displayed default. The terminal hides the code.
17
+
18
+ ```sh
19
+ npm exec --offline -- easy-agents pair
20
+ npm exec --offline -- easy-agents status
21
+ ```
22
+
23
+ Pairing saves the gateway and device credentials in the user-private `npm-device.json`. To change the paired gateway, run `pair` again with a new code. Failed pairing keeps the saved binding. Pairing a device that already exists on the platform rotates that device's token for all installations using its identity.
24
+
25
+ ## Set the initial gateway
15
26
 
16
27
  ```sh
17
28
  npm exec --offline -- easy-agents configure https://gateway.example.com 443
18
29
  npm exec --offline -- easy-agents status
19
30
  ```
20
31
 
21
- The CLI saves the gateway URL in `npm-config.json`. The default directory is `~/.easyagents/` on macOS and Linux and `%APPDATA%\EasyAgents\` on Windows. Set `EASYAGENTS_CONFIG_DIR` to use a different directory.
32
+ The CLI saves the initial gateway URL in `npm-config.json`. The default configuration directory is `~/.easyagents/` on macOS and Linux and `%APPDATA%\EasyAgents\` on Windows. Set `EASYAGENTS_CONFIG_DIR` to use a different directory.
33
+
34
+ ## Run the paired device
35
+
36
+ Run `npm exec --offline -- easy-agents run` in the foreground. Wait for `设备已上线`. Ctrl+C stops the connection. The worker uses the identity created by `pair` and keeps pending results in `npm-runs/` for retry. The `status` command reports the local binding.
37
+
38
+ The default WebSocket path is `/ws/client` on the paired gateway. For deployments with a separate WebSocket host, set `EASYAGENTS_WS_ORIGIN` to its trusted `wss://` origin before starting the worker. That host receives the device credential.
39
+
40
+ On Unix, the workbench terminal is offered by default when Python 3, OpenSSH, readable local SSH host public keys and an SSH service on loopback port 22 are available. In the workbench, open **AI → 设备管理 → 终端**. The terminal presents an SSH login for the non-root account running the client. The device verifies its local host key and uses keyboard-interactive or password authentication. Set `EASYAGENTS_TERMINAL=0` before starting the worker to disable the terminal.
41
+
42
+ - Send `/sha256 hello` to compute a UTF-8 text digest on the device. This needs only the npm package and Node.js.
43
+ - For a local document execution run, start the worker from the workspace registered for this device, or point `EASYAGENTS_WORKSPACE` at it. The worker reads the assigned Markdown file within that directory. A document containing `/sha256 <text>` returns the digest. Other text jobs assigned to Claude Code require a locally configured Claude CLI with credentials supported in bare mode. The text backend runs without host tools. Versioned Git task delivery, code editing and deployment workflows are outside this release.
44
+ - Platform member-sync runs use the bundled EasyAgents sync implementation, system Git and Python 3.10+. Python is launched in isolated mode without site packages. The registered workspace must match the locally selected repository. This operation updates an existing checkout.
45
+ - A missing executor or unsupported job produces a failure result. Receiving a run result is separate from approval or acceptance of a project task.
22
46
 
23
- This preview saves configuration locally. Device pairing, background operation, and task execution are planned for later releases.
47
+ To build from this repository, run `npm ci` and `npm pack` in `new-client/`. The prepack script includes the shared client modules. The published tarball includes its WebSocket dependency and installs offline without a source checkout.
@@ -1,14 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { closeSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { dirname, join } from 'node:path';
5
5
  import { randomUUID } from 'node:crypto';
6
+ import { enroll, promptPairing, protectDeviceFile } from './pair.js';
6
7
 
7
8
  const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
8
9
  const configDir = process.env.EASYAGENTS_CONFIG_DIR || (process.platform === 'win32'
9
10
  ? join(process.env.APPDATA || join(homedir(), 'AppData', 'Roaming'), 'EasyAgents')
10
11
  : join(homedir(), '.easyagents'));
11
12
  const configPath = join(configDir, 'npm-config.json');
13
+ const devicePath = join(configDir, 'npm-device.json');
12
14
 
13
15
  function gatewayOrigin(address, port) {
14
16
  const url = new URL(address);
@@ -21,12 +23,38 @@ function gatewayOrigin(address, port) {
21
23
  return url.origin;
22
24
  }
23
25
 
24
- function saveGateway(gateway) {
26
+ function readSettings(path) {
27
+ let raw;
28
+ try {
29
+ raw = readFileSync(path, 'utf8');
30
+ } catch (error) {
31
+ if (error.code === 'ENOENT') return null;
32
+ throw error;
33
+ }
34
+ try {
35
+ const data = JSON.parse(raw);
36
+ const url = new URL(data.gateway);
37
+ if (!['http:', 'https:'].includes(url.protocol) || url.origin !== data.gateway) throw new Error();
38
+ if (path === devicePath && !['device_id', 'device_key', 'device_token'].every(
39
+ key => typeof data[key] === 'string' && data[key].trim())) throw new Error();
40
+ return data;
41
+ } catch {
42
+ throw new Error('本地配置无效,请检查配置文件');
43
+ }
44
+ }
45
+
46
+ async function saveSettings(path, getData) {
25
47
  mkdirSync(dirname(configPath), { recursive: true, mode: 0o700 });
26
48
  const temporary = join(configDir, '.' + randomUUID() + '.tmp');
27
- writeFileSync(temporary, JSON.stringify({ gateway }, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
49
+ const fd = openSync(temporary, 'wx', 0o600);
28
50
  try {
29
- renameSync(temporary, configPath);
51
+ try {
52
+ if (path === devicePath) protectDeviceFile(temporary);
53
+ writeFileSync(fd, JSON.stringify(await getData(), null, 2) + '\n');
54
+ } finally {
55
+ closeSync(fd);
56
+ }
57
+ renameSync(temporary, path);
30
58
  } catch (error) {
31
59
  unlinkSync(temporary);
32
60
  throw error;
@@ -39,21 +67,37 @@ try {
39
67
  console.log('EasyAgents CLI 预览版\n\n'
40
68
  + 'easy-agents --version\n'
41
69
  + 'easy-agents configure <网关地址> <端口>\n'
70
+ + 'easy-agents pair\n'
71
+ + 'easy-agents run\n'
42
72
  + 'easy-agents status');
43
73
  } else if (['--version', '-v'].includes(command) && !args.length) {
44
74
  console.log(version);
45
75
  } else if (command === 'configure' && args.length === 2) {
46
- saveGateway(gatewayOrigin(...args));
76
+ const gateway = gatewayOrigin(...args);
77
+ const device = readSettings(devicePath);
78
+ if (device && device.gateway !== gateway) throw new Error('更换已配对网关请运行 easy-agents pair');
79
+ await saveSettings(configPath, () => ({ gateway }));
47
80
  console.log('网关已保存');
81
+ } else if (command === 'pair' && !args.length) {
82
+ const current = readSettings(devicePath) ?? readSettings(configPath);
83
+ const [address, port, code] = await promptPairing(current?.gateway);
84
+ const gateway = gatewayOrigin(address.includes('://') ? address : 'https://' + address, port);
85
+ await saveSettings(devicePath, () => enroll(gateway, code, version));
86
+ console.log('设备配对成功');
87
+ } else if (command === 'run' && !args.length) {
88
+ const device = readSettings(devicePath);
89
+ if (!device) throw new Error('请先运行 easy-agents pair');
90
+ const { runDevice } = await import('./run.js');
91
+ const controller = new AbortController();
92
+ const stop = () => controller.abort();
93
+ process.once('SIGINT', stop);
94
+ process.once('SIGTERM', stop);
95
+ try { await runDevice(device, configDir, version, controller.signal); }
96
+ finally { process.off('SIGINT', stop); process.off('SIGTERM', stop); }
48
97
  } else if (command === 'status' && !args.length) {
49
- let gateway = '未配置';
50
- try {
51
- gateway = JSON.parse(readFileSync(configPath, 'utf8')).gateway;
52
- if (typeof gateway !== 'string') throw new Error('配置文件中的网关无效');
53
- } catch (error) {
54
- if (error.code !== 'ENOENT') throw error;
55
- }
56
- console.log('版本:' + version + '\n网关:' + gateway + '\n设备连接:预览版尚未支持配对');
98
+ const device = readSettings(devicePath);
99
+ const gateway = (device ?? readSettings(configPath))?.gateway ?? '未配置';
100
+ console.log('版本:' + version + '\n网关:' + gateway + '\n设备配对:' + (device ? '已配对(本机已保存凭据)' : '未配对'));
57
101
  } else {
58
102
  throw new Error('命令或参数无效。请运行 easy-agents --help');
59
103
  }
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
+ }
package/bin/run.js ADDED
@@ -0,0 +1,183 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { setTimeout as sleep } from 'node:timers/promises';
5
+ import WebSocket from 'ws';
6
+ import { execute } from './tasks.js';
7
+ import { openTerminal, terminalAvailable } from './terminal.js';
8
+ import { protectDeviceFile } from './pair.js';
9
+
10
+ const validId = id => typeof id === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(id);
11
+
12
+ class GatewayError extends Error {
13
+ constructor(status, code) {
14
+ super('平台请求失败 HTTP ' + status);
15
+ this.status = status;
16
+ this.code = code;
17
+ }
18
+ }
19
+
20
+ export async function runDevice(device, configDir, version, signal) {
21
+ const url = new URL(device.gateway);
22
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname))) {
23
+ throw new Error('远程网关需要 HTTPS');
24
+ }
25
+ const wsUrl = new URL('/ws/client', url);
26
+ wsUrl.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
27
+ if (process.env.EASYAGENTS_WS_ORIGIN) {
28
+ const wsOrigin = new URL(process.env.EASYAGENTS_WS_ORIGIN);
29
+ if (wsOrigin.protocol !== 'wss:' || wsOrigin.username || wsOrigin.password ||
30
+ wsOrigin.pathname !== '/' || wsOrigin.search || wsOrigin.hash) throw new Error('WebSocket 网关须为 WSS 地址');
31
+ wsUrl.href = new URL('/ws/client', wsOrigin).href;
32
+ }
33
+ const headers = { Authorization: 'Bearer ' + device.device_token };
34
+ const binding = createHash('sha256').update(JSON.stringify([url.origin, device.device_id])).digest('hex');
35
+ const folder = join(configDir, 'npm-runs', binding);
36
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
37
+ const queue = new Map();
38
+ const terminal = terminalAvailable();
39
+ const sessions = new Map();
40
+ let socket, worker, online = false, active, fatal;
41
+ const request = async (method, path, body) => {
42
+ const res = await fetch(new URL('/api/client/runs/' + path, url), { method,
43
+ headers: { ...headers, 'Content-Type': 'application/json' }, redirect: 'error',
44
+ signal: AbortSignal.any([signal, AbortSignal.timeout(20000)]),
45
+ body: body === undefined ? undefined : JSON.stringify(body) });
46
+ const data = await res.json().catch(() => null);
47
+ if (!res.ok) throw new GatewayError(res.status, data?.code);
48
+ if (data?.code !== 0) throw new Error('无效的平台响应');
49
+ return data.data;
50
+ };
51
+ function checkpoint(id, data) {
52
+ const tmp = join(folder, randomUUID() + '.tmp');
53
+ try {
54
+ writeFileSync(tmp, '', { flag: 'wx', mode: 0o600 });
55
+ protectDeviceFile(tmp);
56
+ writeFileSync(tmp, JSON.stringify(data));
57
+ renameSync(tmp, join(folder, id + '.json'));
58
+ } finally {
59
+ rmSync(tmp, { force: true });
60
+ }
61
+ }
62
+ function readRecord(id) {
63
+ try { return JSON.parse(readFileSync(join(folder, id + '.json'), 'utf8')); }
64
+ catch (error) { if (error.code !== 'ENOENT') throw error; return null; }
65
+ }
66
+ async function processRun(id, controller) {
67
+ const record = readRecord(id);
68
+ let result = record?.result;
69
+ if (!result) {
70
+ if (record?.started) {
71
+ result = { status: 'interrupted', failure_code: 'client_interrupted', failure_detail: '客户端在运行期间退出' };
72
+ } else {
73
+ checkpoint(id, { started: false });
74
+ const ack = await request('POST', id + '/ack', {});
75
+ if (['succeeded', 'failed', 'cancelled', 'interrupted'].includes(ack?.status)) {
76
+ rmSync(join(folder, id + '.json'), { force: true });
77
+ return;
78
+ }
79
+ let content;
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
+ }
85
+ await request('POST', id + '/start', { tool_version: version });
86
+ checkpoint(id, { started: true });
87
+ if (ack?.status === 'running') result = { status: 'interrupted', failure_code: 'client_interrupted' };
88
+ try { result ??= await execute(content, controller.signal); }
89
+ catch { result = controller.signal.aborted ? { status: 'cancelled', failure_code: 'cancelled' } :
90
+ { status: 'failed', failure_code: 'client_error', failure_detail: '客户端执行失败' }; }
91
+ }
92
+ result.tool_version = version;
93
+ checkpoint(id, { result });
94
+ }
95
+ await request('POST', id + '/finish', result);
96
+ rmSync(join(folder, id + '.json'), { force: true });
97
+ console.log('运行 ' + id + ' 已回传 ' + result.status);
98
+ }
99
+ function startQueue() {
100
+ if (worker || !online || !queue.size || signal.aborted) return;
101
+ worker = (async () => {
102
+ while (online && !signal.aborted && queue.size) {
103
+ const [id, controller] = queue.entries().next().value;
104
+ active = controller;
105
+ try { await processRun(id, controller); }
106
+ catch (err) {
107
+ if (err.status === 404 || err.status === 409) rmSync(join(folder, id + '.json'), { force: true });
108
+ else {
109
+ if ([401, 403].includes(err.status)) fatal = new Error('设备认证失败,请重新配对');
110
+ online = false;
111
+ socket?.terminate();
112
+ return;
113
+ }
114
+ } finally { queue.delete(id); active = undefined; }
115
+ }
116
+ })().finally(() => { worker = undefined; if (online) startQueue(); });
117
+ }
118
+ function enqueue(id, cancelled = false) {
119
+ if (!validId(id)) return;
120
+ if (!queue.has(id)) queue.set(id, new AbortController());
121
+ if (cancelled) queue.get(id).abort();
122
+ startQueue();
123
+ }
124
+ function stop() {
125
+ active?.abort();
126
+ socket?.terminate();
127
+ }
128
+ signal.addEventListener('abort', stop, { once: true });
129
+ let delay = 1000;
130
+ try {
131
+ while (!signal.aborted && !fatal) {
132
+ let lastSeen = Date.now(), welcomed = false;
133
+ socket = new WebSocket(wsUrl, { headers, followRedirects: false, handshakeTimeout: 15000, maxPayload: 1048576 });
134
+ const current = socket;
135
+ current.on('error', () => {});
136
+ current.on('unexpected-response', (_req, res) => {
137
+ if ([401, 403].includes(res.statusCode)) fatal = new Error('设备认证失败,请重新配对');
138
+ res.destroy(); current.terminate();
139
+ });
140
+ current.on('open', () => current.send(JSON.stringify({ type: 'hello', client_version: version, tools: [], terminal })));
141
+ current.on('message', async raw => {
142
+ try {
143
+ const msg = JSON.parse(raw.toString());
144
+ lastSeen = Date.now();
145
+ if (msg.type === 'credential.revoked') { fatal = new Error('设备凭据已撤销'); current.terminate(); return; }
146
+ if (!welcomed) {
147
+ if (msg.type !== 'welcome' || msg.device_id !== device.device_id) throw new Error();
148
+ welcomed = online = true; delay = 1000;
149
+ console.log('设备已上线');
150
+ const pending = await request('GET', 'pending');
151
+ if (current !== socket || current.readyState !== WebSocket.OPEN) return;
152
+ 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);
154
+ startQueue();
155
+ } else if (msg.type === 'ping') current.send(JSON.stringify({ type: 'pong' }));
156
+ else if (msg.type === 'terminal.open' && terminal) openTerminal(wsUrl, headers, msg.session_id, sessions);
157
+ else if (msg.type === 'run.available') enqueue(msg.run_id);
158
+ else if (msg.type === 'run.cancel') enqueue(msg.run_id, true);
159
+ } catch (error) {
160
+ if ([401, 403].includes(error.status)) fatal = new Error('设备认证失败,请重新配对');
161
+ current.terminate();
162
+ }
163
+ });
164
+ const timer = setInterval(() => { if (Date.now() - lastSeen > (welcomed ? 90000 : 15000)) current.terminate(); }, 5000);
165
+ try { await new Promise(resolve => current.once('close', resolve)); }
166
+ finally {
167
+ clearInterval(timer);
168
+ online = false;
169
+ for (const session of sessions.values()) session.terminate();
170
+ }
171
+ if (!signal.aborted && !fatal) {
172
+ console.error('连接中断,正在重连');
173
+ await sleep(delay, undefined, { signal }).catch(() => {});
174
+ delay = Math.min(delay * 2, 60000);
175
+ }
176
+ }
177
+ } finally {
178
+ signal.removeEventListener('abort', stop);
179
+ active?.abort();
180
+ await worker;
181
+ }
182
+ if (fatal) throw fatal;
183
+ }
package/bin/tasks.js ADDED
@@ -0,0 +1,96 @@
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
+ async function workspace(content) {
18
+ const local = content.workspace?.local_path;
19
+ if (!local || typeof local !== 'string') throw new Error('缺少工作目录');
20
+ const selected = await realpath(process.env.EASYAGENTS_WORKSPACE || process.cwd());
21
+ const directory = await realpath(resolve(homedir(), local.replace(/^~\//, '')));
22
+ if (selected !== directory || selected === homedir() || selected === parse(selected).root) {
23
+ throw new Error('派发目录与本机启动时指定的工作目录不同');
24
+ }
25
+ return directory;
26
+ }
27
+
28
+ async function sync(content, signal) {
29
+ const directory = await workspace(content);
30
+ const gitRoot = (await invoke('git', ['rev-parse', '--show-toplevel'], directory, '', signal, 10000)).trim();
31
+ if (await realpath(gitRoot) !== directory) throw new Error('工作目录不是仓库根目录');
32
+ const script = fileURLToPath(new URL('../runtime/sync.py', import.meta.url));
33
+ try {
34
+ const python = process.platform === 'win32' ? 'python' : 'python3';
35
+ const result = await invoke(python, ['-I', '-S', '-B', script], directory, JSON.stringify(content), signal, 600000);
36
+ return JSON.parse(result);
37
+ } catch (error) {
38
+ if (signal.aborted) return { status: 'cancelled', failure_code: 'cancelled' };
39
+ return { status: 'failed', failure_code: error.code === 'ENOENT' ? 'python_missing' : 'sync_failed', failure_detail: '未能运行包内 Git 同步程序' };
40
+ }
41
+ }
42
+
43
+ export async function execute(content, signal) {
44
+ signal.throwIfAborted();
45
+ if (content.run_kind === 'sync') return sync(content, signal);
46
+ let prompt = content.prompt;
47
+ const task = content.run_kind === 'execute' && content.task;
48
+ 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
+ const root = await workspace(content);
53
+ const path = task.document_path;
54
+ if (typeof path !== 'string' || isAbsolute(path) || !path.endsWith('.md')) throw new Error('任务文档路径无效');
55
+ const file = await realpath(resolve(root, path));
56
+ const rel = relative(root, file);
57
+ if (isAbsolute(rel) || rel === '..' || rel.startsWith('..' + sep)) throw new Error('任务文档在工作目录外');
58
+ const info = await stat(file);
59
+ if (!info.isFile() || info.size > 256 * 1024) throw new Error('任务文档无效');
60
+ prompt = (await readFile(file, 'utf8')).trim();
61
+ }
62
+ if (typeof prompt !== 'string' || !prompt.trim()) throw new Error('运行内容为空');
63
+ if ((content.run_kind === 'chat' || task) && prompt.startsWith('/sha256 ')) {
64
+ const digest = createHash('sha256').update(prompt.slice('/sha256 '.length), 'utf8').digest('hex');
65
+ return { status: 'succeeded', reply_text: digest };
66
+ }
67
+ if ((!task && (content.run_kind !== 'chat' || content.chat_mode !== 'chat')) || content.agent?.tool_type !== 'claude_code') {
68
+ return { status: 'failed', failure_code: 'unsupported_task', failure_detail: '当前独立客户端支持计算、成员同步及 Claude 文本任务' };
69
+ }
70
+ if (content.resume_session_ref) {
71
+ return { status: 'failed', failure_code: 'unsupported_session', failure_detail: '此版本仅支持独立文本任务' };
72
+ }
73
+ if (task && content.prompt) prompt = content.prompt + '\n\n' + prompt;
74
+ // No host tools, workspace instructions or MCP servers are needed for a text task.
75
+ const cwd = await mkdtemp(join(tmpdir(), 'easy-agents-text-'));
76
+ try {
77
+ const args = ['--bare', '--print', '--output-format', 'json', '--tools', '', '--strict-mcp-config',
78
+ '--disable-slash-commands', '--no-session-persistence'];
79
+ if (content.requested_model) {
80
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9.:/_-]{0,127}$/.test(content.requested_model)) throw new Error('模型名称无效');
81
+ args.push('--model', content.requested_model);
82
+ }
83
+ const seconds = Number.isSafeInteger(content.timeout_seconds) && content.timeout_seconds > 0 ? content.timeout_seconds : 3600;
84
+ const raw = await invoke('claude', args, cwd, prompt, signal, Math.min(seconds, 3600) * 1000);
85
+ const result = JSON.parse(raw);
86
+ if (result.type !== 'result' || result.subtype !== 'success' || result.is_error ||
87
+ typeof result.result !== 'string' || !result.result || result.result.length > 1000000) throw new Error('工具输出无效');
88
+ return { status: 'succeeded', reply_text: result.result };
89
+ } catch (err) {
90
+ if (signal.aborted) return { status: 'cancelled', failure_code: 'cancelled' };
91
+ return { status: 'failed', failure_code: err.code === 'ENOENT' ? 'tool_missing' : 'tool_failed',
92
+ failure_detail: err.code === 'ENOENT' ? '设备未安装 Claude CLI' : '文本执行工具未完成任务' };
93
+ } finally {
94
+ await rm(cwd, { recursive: true, force: true });
95
+ }
96
+ }
@@ -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.