@unionschool/easy-agents 0.4.2 → 1.0.23
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 +2 -2
- package/bin/easy-agents.js +6 -1
- package/bin/mac-reports.js +6 -0
- package/bin/mac-service.js +2 -2
- package/bin/portable-service.js +2 -2
- package/bin/run.js +119 -33
- package/bin/tasks.js +70 -17
- package/package.json +5 -1
- package/runtime/desktop_chat.py +118 -13
- package/runtime/doc_read.py +181 -0
- package/runtime/easyagents_core/__init__.py +4 -0
- package/runtime/easyagents_core/git_sync.py +7 -2
- package/runtime/easyagents_core/member_sync.py +6 -0
- package/runtime/easyagents_core/tools.py +1257 -0
- package/runtime/platform_prompt.py +21 -0
- package/runtime/task_run.py +3 -16
package/README.md
CHANGED
|
@@ -86,9 +86,9 @@ npm exec --offline -- easy-agents run
|
|
|
86
86
|
|
|
87
87
|
## 各端能执行什么
|
|
88
88
|
|
|
89
|
-
- Mac 和 Ubuntu 安装包能接平台任务分支上的执行、审核、部署和澄清运行(Codex、Claude,完整权限,与旧 Python 客户端的规则一致):执行在任务分支上工作并在成功后推送;审核和部署检出本轮交付的提交;工作目录有未提交改动时,在客户端配置目录的 `worktrees/` 里另建工作树,原目录不动,合并后的成员同步会清理这些工作树。Agent 通过提示里给出的平台命令调用工具;Agent 凭据缺失或已被平台撤销时,客户端自动领取新凭据(平台会同时撤销旧凭据)。旧的同目录文件交付和用户发布命令(`publish
|
|
89
|
+
- Mac 和 Ubuntu 安装包能接平台任务分支上的执行、审核、部署和澄清运行(Codex、Claude,完整权限,与旧 Python 客户端的规则一致):执行在任务分支上工作并在成功后推送;审核和部署检出本轮交付的提交;工作目录有未提交改动时,在客户端配置目录的 `worktrees/` 里另建工作树,原目录不动,合并后的成员同步会清理这些工作树。Agent 通过提示里给出的平台命令调用工具;Agent 凭据缺失或已被平台撤销时,客户端自动领取新凭据(平台会同时撤销旧凭据)。旧的同目录文件交付和用户发布命令(`publish`)不支持。工作台读取任务、需求文档(“阅读”抽屉)也由这两种设备应答,只读 Git,不切分支、不改工作区。
|
|
90
90
|
- **未完成**:Windows、Android 和单独运行的普通 npm 版还不能接任务分支运行,会回报 `handoff_unsupported`。这几端暂时用不上(用户 2026-11-22 定),以后需要时再单独升级。
|
|
91
|
-
- Mac 和 Ubuntu 安装包支持 Codex、Claude
|
|
91
|
+
- Mac 和 Ubuntu 安装包支持 Codex、Claude 的文本对话、续聊和本地文本任务。它们可从项目卡片或对话页接收聊天和工作消息。普通聊天是纯文本:Codex 只读会话、Claude 不开工具。工作消息(负责人与任务角色的对话、平台的流程通知)与任务运行一样用完整权限,带平台操作入口,Agent 凭据缺失或被撤销时自动领取,所以负责人能在对话里登记需求、发布任务、合并上报。可用的会话编号、模型与用量会随结果回传。
|
|
92
92
|
- Mac 和 Windows 面板可显示检测到的 Codex、Claude、Cursor、Agy 登录和上报状态。平台控制额度上报开关,绿色胶囊显示已获得的剩余额度,测得零时显示零。Windows 和单独运行的普通 npm 版支持单次 Claude 文本任务,使用 bare 模式可用的认证。桌面对话功能需要安装包提供的工具适配和内置运行环境。
|
|
93
93
|
- 在支持的 Unix 主机上,网页终端使用本机运行用户进行 SSH 登录,需要 Python 3、OpenSSH、可读的本机 SSH 公钥和监听回环端口 22 的 SSH 服务。可在工作台的「AI → 设备管理 → 终端」打开。普通 npm 可在启动前用 `EASYAGENTS_TERMINAL=0` 关闭。
|
|
94
94
|
- Node 核心支持 `/sha256 <文本>`、本地 Markdown 文档里的同类计算和成员同步。文档与同步的目录需与本机选定工作目录相符,可用 `EASYAGENTS_WORKSPACE` 指定。成员同步使用包内实现、系统 Git 和 Python 3.10+,更新已有检出目录。Android 首版可执行 SHA-256 消息和用户选择目录里的计算文档。
|
package/bin/easy-agents.js
CHANGED
|
@@ -93,7 +93,7 @@ try {
|
|
|
93
93
|
+ 'easy-agents pair\n'
|
|
94
94
|
+ 'easy-agents run\n'
|
|
95
95
|
+ 'easy-agents agent-credential <Agent编号>\n'
|
|
96
|
-
+ 'easy-agents status' + (desktop ? '\neasy-agents show | start | stop | restart | logs | doctor | update\neasy-agents auto-update on|off\neasy-agents autostart on|off\neasy-agents terminal on|off\neasy-agents accounts --json' : ''));
|
|
96
|
+
+ 'easy-agents status' + (desktop ? '\neasy-agents show | start | stop | restart | logs | doctor | update\neasy-agents auto-update on|off\neasy-agents autostart on|off\neasy-agents terminal on|off\neasy-agents compact-at 50|60|70|80|off\neasy-agents accounts --json' : ''));
|
|
97
97
|
} else if (['--version', '-v'].includes(command) && !args.length) {
|
|
98
98
|
console.log(version);
|
|
99
99
|
} else if (command === 'configure' && args.length === 2) {
|
|
@@ -133,6 +133,11 @@ try {
|
|
|
133
133
|
const { writeSnapshot } = await import('./mac-reports.js');
|
|
134
134
|
writeSnapshot(configDir, 'mac-terminal.json', { enabled: args[0] === 'on' });
|
|
135
135
|
console.log(args[0] === 'on' ? '网页终端已开启' : '网页终端已关闭');
|
|
136
|
+
} else if (desktop && command === 'compact-at' && args.length === 1 && /^(off|\d{1,2})$/.test(args[0])) {
|
|
137
|
+
const { writeSnapshot } = await import('./mac-reports.js');
|
|
138
|
+
const percent = args[0] === 'off' ? 0 : Number(args[0]);
|
|
139
|
+
writeSnapshot(configDir, 'mac-compact.json', { percent });
|
|
140
|
+
console.log(percent ? `上下文用到 ${percent}% 时提示压缩` : '已关闭压缩提示');
|
|
136
141
|
} else if (desktop && command === 'update' && !args.length) {
|
|
137
142
|
await updater(false);
|
|
138
143
|
} else if (desktop && command === 'auto-update' && args.length === 1 && ['on','off'].includes(args[0])) {
|
package/bin/mac-reports.js
CHANGED
|
@@ -23,6 +23,12 @@ export function terminalEnabled(folder) {
|
|
|
23
23
|
return readSnapshot(folder, 'mac-terminal.json')?.enabled !== false;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
+
// 压缩提示门槛(百分比,0 关闭,默认 60),desktop_chat.py 回传时一起带上(docs/消息链路.md 第 3.2 节)。
|
|
27
|
+
export function compactAt(folder) {
|
|
28
|
+
const value = readSnapshot(folder, 'mac-compact.json')?.percent;
|
|
29
|
+
return Number.isInteger(value) && value >= 0 && value <= 100 ? value : 60;
|
|
30
|
+
}
|
|
31
|
+
|
|
26
32
|
function helper(folder, mode, input, signal) {
|
|
27
33
|
return new Promise((resolve, reject) => {
|
|
28
34
|
const python = process.platform === 'win32' ? join(macResources, 'python/python.exe')
|
package/bin/mac-service.js
CHANGED
|
@@ -4,7 +4,7 @@ import { existsSync, mkdirSync, openSync, closeSync, renameSync, rmSync, writeFi
|
|
|
4
4
|
import { homedir, userInfo } from 'node:os';
|
|
5
5
|
import { dirname, join } from 'node:path';
|
|
6
6
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
7
|
-
import { macResources, readSnapshot, terminalEnabled } from './mac-reports.js';
|
|
7
|
+
import { macResources, readSnapshot, terminalEnabled, compactAt } from './mac-reports.js';
|
|
8
8
|
|
|
9
9
|
const xml = s => s.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');
|
|
10
10
|
const label = folder => 'com.unionschool.easyagents.mac.' + createHash('sha256').update(folder).digest('hex').slice(0, 12);
|
|
@@ -77,7 +77,7 @@ export function desktopStatus(folder) {
|
|
|
77
77
|
const { pid } = job(folder);
|
|
78
78
|
const saved = readSnapshot(folder, 'mac-worker.json');
|
|
79
79
|
const fresh = pid > 0 && saved?.pid === pid && Date.now() - saved.updated < 95000;
|
|
80
|
-
return { running: Boolean(pid), connected: Boolean(fresh && saved.connected), pid, terminalEnabled: terminalEnabled(folder),
|
|
80
|
+
return { running: Boolean(pid), connected: Boolean(fresh && saved.connected), pid, terminalEnabled: terminalEnabled(folder), compactAt: compactAt(folder),
|
|
81
81
|
report: saved || {}, task: fresh ? saved.task : null };
|
|
82
82
|
}
|
|
83
83
|
|
package/bin/portable-service.js
CHANGED
|
@@ -5,7 +5,7 @@ import net from 'node:net';
|
|
|
5
5
|
import { join, resolve } from 'node:path';
|
|
6
6
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
7
7
|
import { fileURLToPath } from 'node:url';
|
|
8
|
-
import { readSnapshot, terminalEnabled, writeSnapshot } from './mac-reports.js';
|
|
8
|
+
import { compactAt, readSnapshot, terminalEnabled, writeSnapshot } from './mac-reports.js';
|
|
9
9
|
|
|
10
10
|
function endpoint(folder) {
|
|
11
11
|
const id = createHash('sha256').update(resolve(folder)).digest('hex').slice(0, 28);
|
|
@@ -42,7 +42,7 @@ export async function desktopStatus(folder) {
|
|
|
42
42
|
const session = await instance(folder);
|
|
43
43
|
const report = readSnapshot(folder, 'mac-worker.json') ?? {};
|
|
44
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) };
|
|
45
|
+
pid: session ? report.pid : 0, report, task: session ? report.task : null, terminalEnabled: terminalEnabled(folder), compactAt: compactAt(folder) };
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
export async function serviceCommand(command, folder) {
|
package/bin/run.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
2
3
|
import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
4
|
import { join } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
4
6
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
5
7
|
import WebSocket from 'ws';
|
|
6
8
|
import { execute } from './tasks.js';
|
|
@@ -8,8 +10,45 @@ import { openTerminal, terminalAvailable } from './terminal.js';
|
|
|
8
10
|
import { protectDeviceFile } from './pair.js';
|
|
9
11
|
import { ensureAgentCredential, findAgentCredential } from './credentials.js';
|
|
10
12
|
|
|
13
|
+
// Reported in hello so the platform stops dispatching task-branch runs this device would reject (T-163).
|
|
14
|
+
// Keep in step with the desktop-resources check in execute() of bin/tasks.js: only Mac and Ubuntu desktop builds qualify.
|
|
15
|
+
const desktopResources = () => process.platform === 'darwin' ? process.env.EASYAGENTS_MAC_RESOURCES
|
|
16
|
+
: process.platform === 'linux' ? process.env.EASYAGENTS_DESKTOP_RESOURCES : undefined;
|
|
17
|
+
const taskDelivery = () => Boolean(desktopResources());
|
|
18
|
+
|
|
19
|
+
// doc.read (T-172): the workbench's document drawer. Same devices as task_delivery: the packaged Python does the Git reading.
|
|
20
|
+
const DOC_READER = fileURLToPath(new URL('../runtime/doc_read.py', import.meta.url));
|
|
21
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
22
|
+
const DOC_FAILED = { status: 'error', error: 'document_read_failed' };
|
|
23
|
+
function readDocument(message, signal) {
|
|
24
|
+
return new Promise(done => {
|
|
25
|
+
const child = execFile(join(desktopResources(), 'python/bin/python3'), ['-I', '-B', '-X', 'utf8', DOC_READER],
|
|
26
|
+
{ timeout: 60000, maxBuffer: 2 * 1024 * 1024, signal }, (error, stdout) => {
|
|
27
|
+
if (!error) {
|
|
28
|
+
try {
|
|
29
|
+
const body = JSON.parse(stdout);
|
|
30
|
+
if (body?.status === 'ok' || body?.status === 'error') return done(body);
|
|
31
|
+
} catch {}
|
|
32
|
+
}
|
|
33
|
+
done(DOC_FAILED);
|
|
34
|
+
});
|
|
35
|
+
child.stdin.on('error', () => {});
|
|
36
|
+
child.stdin.end(JSON.stringify(message));
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
11
40
|
const validId = id => typeof id === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(id);
|
|
12
41
|
|
|
42
|
+
// 并发处理(用户 2026-11-23):原先一台设备一次只跑一个运行,一个 14 分钟的聊天把其他智能体、其他渠道的消息全挡住。
|
|
43
|
+
// 平台已保证同一智能体同一子项目串行;这里再按工作目录加锁:工作模式、任务运行、同步会改目录,同一目录一次一个;
|
|
44
|
+
// 纯聊天(chat_mode=chat)只读,不加锁。
|
|
45
|
+
export const MAX_PARALLEL_RUNS = 4;
|
|
46
|
+
export function runLockKey(content) {
|
|
47
|
+
if (content?.run_kind === 'chat' && content.chat_mode === 'chat' && !content.passthrough) return null;
|
|
48
|
+
const path = content?.workspace?.local_path;
|
|
49
|
+
return typeof path === 'string' && path ? 'dir:' + path.replace(/\/+$/, '') : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
13
52
|
class GatewayError extends Error {
|
|
14
53
|
constructor(status, code) {
|
|
15
54
|
super('平台请求失败 HTTP ' + status);
|
|
@@ -32,13 +71,32 @@ export async function runDevice(device, configDir, version, signal, { reporter,
|
|
|
32
71
|
wsOrigin.pathname !== '/' || wsOrigin.search || wsOrigin.hash) throw new Error('WebSocket 网关须为 WSS 地址');
|
|
33
72
|
wsUrl.href = new URL('/ws/client', wsOrigin).href;
|
|
34
73
|
}
|
|
35
|
-
|
|
74
|
+
// X-EasyAgents-Manual-Sync:本客户端能执行用户在对话里发的 /sync(runtime/sync.py);平台据此放行手动同步(2026-11-23 补)。
|
|
75
|
+
const headers = { Authorization: 'Bearer ' + device.device_token, 'X-EasyAgents-Manual-Sync': '1' };
|
|
36
76
|
const binding = createHash('sha256').update(JSON.stringify([url.origin, device.device_id])).digest('hex');
|
|
37
77
|
const folder = join(configDir, 'npm-runs', binding);
|
|
38
78
|
mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
39
|
-
const queue = new Map();
|
|
79
|
+
const queue = new Map(); // 等待开始的运行:id → AbortController
|
|
80
|
+
const running = new Map(); // 正在处理的运行:id → { controller, promise }
|
|
81
|
+
const locks = new Map(); // 工作目录锁:key → 前一个持有者结束的 Promise
|
|
82
|
+
const steers = new Map(); // 运行中补充:run_id → (message_id, 正文) => Promise<回执状态>
|
|
40
83
|
const sessions = new Map();
|
|
41
|
-
let socket,
|
|
84
|
+
let socket, online = false, fatal;
|
|
85
|
+
async function withLock(key, work) {
|
|
86
|
+
if (!key) return work();
|
|
87
|
+
const previous = locks.get(key) || Promise.resolve();
|
|
88
|
+
let release;
|
|
89
|
+
const mine = new Promise(resolve => { release = resolve; });
|
|
90
|
+
const tail = previous.then(() => mine);
|
|
91
|
+
locks.set(key, tail);
|
|
92
|
+
await previous;
|
|
93
|
+
try { return await work(); }
|
|
94
|
+
finally { release(); if (locks.get(key) === tail) locks.delete(key); }
|
|
95
|
+
}
|
|
96
|
+
const reportRunning = () => {
|
|
97
|
+
const ids = [...running.keys()];
|
|
98
|
+
reporter?.patch({ task: ids.length ? ids.join(', ') : null });
|
|
99
|
+
};
|
|
42
100
|
const gatewayRequest = async (method, path, body, extraSignal) => {
|
|
43
101
|
const res = await fetch(new URL(path, url), { method,
|
|
44
102
|
// Without the Git delivery header the platform withholds task-branch runs (42298).
|
|
@@ -59,8 +117,27 @@ export async function runDevice(device, configDir, version, signal, { reporter,
|
|
|
59
117
|
// Task runs need a working Agent credential for the platform tools (credentials.js).
|
|
60
118
|
const agentCredential = content => ensureAgentCredential({ configDir, origin: url.origin, id: content.agent?.agent_id,
|
|
61
119
|
version, signal, issue: id => gatewayRequest('POST', '/api/client/agents/' + id + '/credential', {}) });
|
|
120
|
+
// Read-only Git work in its own process: it never waits for, or blocks, a task run.
|
|
121
|
+
async function answerDocument(msg) {
|
|
122
|
+
const id = msg.request_id;
|
|
123
|
+
if (typeof id !== 'string' || !UUID.test(id) || !desktopResources()) return;
|
|
124
|
+
const body = await readDocument(msg, signal);
|
|
125
|
+
try { await gatewayRequest('POST', '/api/client/documents/' + id, body); }
|
|
126
|
+
catch { if (!signal.aborted) console.error('文档读取结果回传失败'); }
|
|
127
|
+
}
|
|
128
|
+
async function answerSteer(target, msg) {
|
|
129
|
+
if (!UUID.test(msg.run_id || '') || !UUID.test(msg.message_id || '')) return;
|
|
130
|
+
const send = status => {
|
|
131
|
+
if (target.readyState === WebSocket.OPEN)
|
|
132
|
+
target.send(JSON.stringify({ type: 'run.steer.ack', run_id: msg.run_id, message_id: msg.message_id, status }));
|
|
133
|
+
};
|
|
134
|
+
const fn = steers.get(msg.run_id);
|
|
135
|
+
if (typeof msg.content !== 'string' || !msg.content.trim() || msg.content.length > 65536) return send('failed');
|
|
136
|
+
if (!fn) return send(running.has(msg.run_id) ? 'unsupported' : 'too_late');
|
|
137
|
+
try { send(await fn(msg.message_id, msg.content)); } catch { send('failed'); }
|
|
138
|
+
}
|
|
62
139
|
function checkDrained() {
|
|
63
|
-
if (drain?.aborted && !
|
|
140
|
+
if (drain?.aborted && !running.size && !queue.size && !readdirSync(folder).some(f => f.endsWith('.json'))) onDrained?.();
|
|
64
141
|
}
|
|
65
142
|
function checkpoint(id, data) {
|
|
66
143
|
const tmp = join(folder, randomUUID() + '.tmp');
|
|
@@ -91,12 +168,16 @@ export async function runDevice(device, configDir, version, signal, { reporter,
|
|
|
91
168
|
return;
|
|
92
169
|
}
|
|
93
170
|
const content = await request('GET', id);
|
|
94
|
-
await
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
{
|
|
171
|
+
result = await withLock(ack?.status === 'running' ? null : runLockKey(content), async () => {
|
|
172
|
+
if (controller.signal.aborted) return { status: 'cancelled', failure_code: 'cancelled' };
|
|
173
|
+
await request('POST', id + '/start', { tool_version: version });
|
|
174
|
+
checkpoint(id, { started: true });
|
|
175
|
+
if (ack?.status === 'running') return { status: 'interrupted', failure_code: 'client_interrupted' };
|
|
176
|
+
const onSteer = fn => { if (fn) steers.set(id, fn); else steers.delete(id); };
|
|
177
|
+
try { return await execute(content, controller.signal, workCredential, { agentCredential, configDir, onSteer }); }
|
|
178
|
+
catch { return controller.signal.aborted ? { status: 'cancelled', failure_code: 'cancelled' } :
|
|
179
|
+
{ status: 'failed', failure_code: 'client_error', failure_detail: '客户端执行失败' }; }
|
|
180
|
+
});
|
|
100
181
|
}
|
|
101
182
|
result.tool_version ??= version;
|
|
102
183
|
checkpoint(id, { result });
|
|
@@ -107,33 +188,33 @@ export async function runDevice(device, configDir, version, signal, { reporter,
|
|
|
107
188
|
console.log('运行 ' + id + ' 已回传 ' + result.status);
|
|
108
189
|
}
|
|
109
190
|
function startQueue() {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
if (
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
}
|
|
127
|
-
})().finally(() => { worker = undefined; checkDrained(); if (online) startQueue(); });
|
|
191
|
+
while (online && !signal.aborted && running.size < MAX_PARALLEL_RUNS) {
|
|
192
|
+
const next = [...queue.entries()].find(([id]) => !running.has(id));
|
|
193
|
+
if (!next) return;
|
|
194
|
+
const [id, controller] = next;
|
|
195
|
+
queue.delete(id);
|
|
196
|
+
const promise = processRun(id, controller).catch(err => {
|
|
197
|
+
if (err.status === 404 || err.status === 409) rmSync(join(folder, id + '.json'), { force: true });
|
|
198
|
+
else {
|
|
199
|
+
if ([401, 403].includes(err.status)) fatal = new Error('设备认证失败,请重新配对');
|
|
200
|
+
online = false;
|
|
201
|
+
socket?.terminate();
|
|
202
|
+
}
|
|
203
|
+
}).finally(() => { running.delete(id); reportRunning(); checkDrained(); startQueue(); });
|
|
204
|
+
running.set(id, { controller, promise });
|
|
205
|
+
reportRunning();
|
|
206
|
+
}
|
|
128
207
|
}
|
|
129
208
|
function enqueue(id, cancelled = false) {
|
|
130
209
|
if (!validId(id)) return;
|
|
210
|
+
const current = running.get(id)?.controller;
|
|
211
|
+
if (current) { if (cancelled) current.abort(); return; }
|
|
131
212
|
if (!queue.has(id)) queue.set(id, new AbortController());
|
|
132
213
|
if (cancelled) queue.get(id).abort();
|
|
133
214
|
startQueue();
|
|
134
215
|
}
|
|
135
216
|
function stop() {
|
|
136
|
-
|
|
217
|
+
for (const { controller } of running.values()) controller.abort();
|
|
137
218
|
socket?.terminate();
|
|
138
219
|
}
|
|
139
220
|
signal.addEventListener('abort', stop, { once: true });
|
|
@@ -157,7 +238,10 @@ export async function runDevice(device, configDir, version, signal, { reporter,
|
|
|
157
238
|
}
|
|
158
239
|
}
|
|
159
240
|
if (signal.aborted) break;
|
|
160
|
-
|
|
241
|
+
// steer(协议第 16 节):桌面版的 Claude、Codex、Agy 对话支持运行中补充;纯 npm 与任务运行不支持。
|
|
242
|
+
// Cursor 实测只能取消当前一轮再发新的,不算补充(2026-11-23)。
|
|
243
|
+
const steer = { claude_code: taskDelivery(), codex: taskDelivery(), cursor: false, antigravity: taskDelivery() };
|
|
244
|
+
const hello = { type: 'hello', client_version: version, tools: [], terminal, task_delivery: taskDelivery(), doc_read: taskDelivery(), steer, ...metadata };
|
|
161
245
|
let lastSeen = Date.now(), welcomed = false;
|
|
162
246
|
socket = new WebSocket(wsUrl, { headers, followRedirects: false, handshakeTimeout: 15000, maxPayload: 1048576 });
|
|
163
247
|
const current = socket;
|
|
@@ -186,8 +270,10 @@ export async function runDevice(device, configDir, version, signal, { reporter,
|
|
|
186
270
|
} else if (msg.type === 'ping') { current.send(JSON.stringify({ type: 'pong' })); reporter?.patch({ heartbeat: Date.now() }); }
|
|
187
271
|
else if (msg.type === 'agent.quota.config') reporter?.configure(msg, reportQuota);
|
|
188
272
|
else if (msg.type === 'terminal.open' && terminal && (reporter?.terminalEnabled?.() ?? true)) openTerminal(wsUrl, headers, msg.session_id, sessions);
|
|
273
|
+
else if (msg.type === 'doc.read') answerDocument(msg);
|
|
274
|
+
else if (msg.type === 'run.steer') answerSteer(current, msg);
|
|
189
275
|
else if (msg.type === 'run.available' && !drain?.aborted) enqueue(msg.run_id);
|
|
190
|
-
else if (msg.type === 'run.cancel' && (!drain?.aborted || queue.has(msg.run_id))) enqueue(msg.run_id, true);
|
|
276
|
+
else if (msg.type === 'run.cancel' && (!drain?.aborted || queue.has(msg.run_id) || running.has(msg.run_id))) enqueue(msg.run_id, true);
|
|
191
277
|
} catch (error) {
|
|
192
278
|
if ([401, 403].includes(error.status)) fatal = new Error('设备认证失败,请重新配对');
|
|
193
279
|
current.terminate();
|
|
@@ -212,8 +298,8 @@ export async function runDevice(device, configDir, version, signal, { reporter,
|
|
|
212
298
|
} finally {
|
|
213
299
|
signal.removeEventListener('abort', stop);
|
|
214
300
|
drain?.removeEventListener('abort', checkDrained);
|
|
215
|
-
|
|
216
|
-
await
|
|
301
|
+
for (const { controller } of running.values()) controller.abort();
|
|
302
|
+
await Promise.all([...running.values()].map(r => r.promise));
|
|
217
303
|
}
|
|
218
304
|
if (fatal) throw fatal;
|
|
219
305
|
}
|
package/bin/tasks.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import { execFile } from 'node:child_process';
|
|
2
|
+
import { execFile, spawn } from 'node:child_process';
|
|
3
3
|
import { mkdtemp, readFile, realpath, rm, stat } from 'node:fs/promises';
|
|
4
4
|
import { homedir, tmpdir } from 'node:os';
|
|
5
5
|
import { isAbsolute, join, parse, relative, resolve, sep } from 'node:path';
|
|
@@ -14,27 +14,71 @@ function invoke(file, args, cwd, input, signal, timeout) {
|
|
|
14
14
|
});
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
// 对话桥:首行 JSON 是运行内容,之后 stdin 保持打开,运行中补充(/steer)按行写入;
|
|
18
|
+
// 子进程从 fd 3 逐行回执 {"message_id","status"},stdout 只放最终结果。
|
|
19
|
+
function desktopConversation(resources, content, prompt, signal, credential, tools = false, onSteer) {
|
|
18
20
|
const bridge = fileURLToPath(new URL('../runtime/desktop_chat.py', import.meta.url));
|
|
19
21
|
const seconds = content.timeout_seconds;
|
|
20
22
|
const timeout = Number.isSafeInteger(seconds) && seconds > 0 ? Math.min(seconds, 3600) : 3600;
|
|
21
23
|
const input = { tool: content.agent.tool_type, prompt, model: content.requested_model,
|
|
22
24
|
resume: content.resume_session_ref, workspace: content.workspace?.local_path, timeout,
|
|
23
|
-
workRunId: content.chat_mode
|
|
25
|
+
workRunId: content.chat_mode !== 'chat' ? content.run_id : undefined, passthrough: content.passthrough === true, credential, tools };
|
|
24
26
|
return new Promise(resolveResult => {
|
|
25
|
-
const child =
|
|
26
|
-
{
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
27
|
+
const child = spawn(join(resources, 'python/bin/python3'), ['-I', '-B', '-X', 'utf8', bridge],
|
|
28
|
+
{ stdio: ['pipe', 'pipe', 'ignore', 'pipe'], windowsHide: true });
|
|
29
|
+
const waiting = new Map();
|
|
30
|
+
let stdout = '', size = 0, settled = false, acks = '';
|
|
31
|
+
const finish = result => {
|
|
32
|
+
if (settled) return;
|
|
33
|
+
settled = true;
|
|
34
|
+
clearTimeout(timer);
|
|
35
|
+
signal.removeEventListener('abort', cancel);
|
|
36
|
+
onSteer?.(null);
|
|
37
|
+
for (const done of waiting.values()) done('too_late');
|
|
38
|
+
waiting.clear();
|
|
39
|
+
resolveResult(result);
|
|
40
|
+
};
|
|
41
|
+
const failed = { status: 'failed', failure_code: 'tool_start_failed', failure_detail: '设备对话执行器异常,请检查客户端安装' };
|
|
42
|
+
const timer = setTimeout(() => child.kill('SIGTERM'), (timeout + 12) * 1000);
|
|
34
43
|
const cancel = () => child.kill('SIGTERM');
|
|
44
|
+
child.stdout.on('data', chunk => {
|
|
45
|
+
size += chunk.length;
|
|
46
|
+
if (size > 8 * 1024 * 1024) { child.kill('SIGTERM'); return; }
|
|
47
|
+
stdout += chunk;
|
|
48
|
+
});
|
|
49
|
+
child.stdio[3].on('data', chunk => {
|
|
50
|
+
acks += chunk;
|
|
51
|
+
let line;
|
|
52
|
+
while ((line = acks.indexOf('\n')) >= 0) {
|
|
53
|
+
const raw = acks.slice(0, line); acks = acks.slice(line + 1);
|
|
54
|
+
try {
|
|
55
|
+
const ack = JSON.parse(raw);
|
|
56
|
+
waiting.get(ack.message_id)?.(ack.status);
|
|
57
|
+
waiting.delete(ack.message_id);
|
|
58
|
+
} catch {}
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
child.on('error', () => finish(failed));
|
|
62
|
+
child.on('close', () => {
|
|
63
|
+
if (signal.aborted) {
|
|
64
|
+
// 被 /stop 停下:带回工具会话号,下一条消息续接同一会话(docs/消息链路.md 第 3.2 节)。
|
|
65
|
+
let ref;
|
|
66
|
+
try { ref = JSON.parse(stdout).tool_session_ref; } catch {}
|
|
67
|
+
return finish({ status: 'cancelled', failure_code: 'cancelled', ...(typeof ref === 'string' && ref ? { tool_session_ref: ref } : {}) });
|
|
68
|
+
}
|
|
69
|
+
try { return finish(JSON.parse(stdout)); } catch {}
|
|
70
|
+
finish(failed);
|
|
71
|
+
});
|
|
35
72
|
signal.addEventListener('abort', cancel, { once: true });
|
|
36
73
|
child.stdin.on('error', () => {});
|
|
37
|
-
child.stdin.
|
|
74
|
+
child.stdin.write(JSON.stringify(input) + '\n');
|
|
75
|
+
// 运行中补充:返回回执状态 accepted | too_late | failed(10 秒内没回执算失败)。
|
|
76
|
+
onSteer?.((messageId, text) => new Promise(done => {
|
|
77
|
+
if (settled || !child.stdin.writable) return done('too_late');
|
|
78
|
+
const timeoutAck = setTimeout(() => { waiting.delete(messageId); done('failed'); }, 9000);
|
|
79
|
+
waiting.set(messageId, status => { clearTimeout(timeoutAck); done(status); });
|
|
80
|
+
child.stdin.write(JSON.stringify({ type: 'steer', message_id: messageId, content: text }) + '\n');
|
|
81
|
+
}));
|
|
38
82
|
if (signal.aborted) cancel();
|
|
39
83
|
});
|
|
40
84
|
}
|
|
@@ -100,7 +144,7 @@ async function sync(content, signal, resources) {
|
|
|
100
144
|
}
|
|
101
145
|
}
|
|
102
146
|
|
|
103
|
-
export async function execute(content, signal, workCredential, { agentCredential, configDir } = {}) {
|
|
147
|
+
export async function execute(content, signal, workCredential, { agentCredential, configDir, onSteer } = {}) {
|
|
104
148
|
signal.throwIfAborted();
|
|
105
149
|
const resources = process.platform === 'darwin' ? process.env.EASYAGENTS_MAC_RESOURCES
|
|
106
150
|
: process.platform === 'linux' ? process.env.EASYAGENTS_DESKTOP_RESOURCES : undefined;
|
|
@@ -141,16 +185,25 @@ export async function execute(content, signal, workCredential, { agentCredential
|
|
|
141
185
|
return { status: 'succeeded', reply_text: digest };
|
|
142
186
|
}
|
|
143
187
|
if (task && content.prompt) prompt = content.prompt + '\n\n' + prompt;
|
|
144
|
-
|
|
188
|
+
// Agy 只接对话(2026-11-23),任务运行仍只有 Codex、Claude。
|
|
189
|
+
if (resources && (['codex', 'claude_code'].includes(content.agent?.tool_type) && (task || content.run_kind === 'chat')
|
|
190
|
+
|| content.agent?.tool_type === 'antigravity' && content.run_kind === 'chat')) {
|
|
145
191
|
let credential;
|
|
146
|
-
|
|
192
|
+
// Same rule as the platform: only chat_mode 'chat' is a plain conversation. Workflow notifications to the lead
|
|
193
|
+
// (merge after deploy, answers, sync handoff) arrive with an empty chat_mode and must be able to act.
|
|
194
|
+
// 斜杠命令(passthrough)原样交给工具:工作模式保留工具权限,但不带平台规程和凭据(2026-11-23)。
|
|
195
|
+
const workMode = content.chat_mode !== 'chat';
|
|
196
|
+
const work = workMode && !content.passthrough;
|
|
197
|
+
if (work && workCredential) {
|
|
198
|
+
// A revoked or missing credential would leave the lead unable to register, publish or merge.
|
|
199
|
+
try { if (agentCredential) await agentCredential(content); } catch {}
|
|
147
200
|
try {
|
|
148
201
|
credential = workCredential(content);
|
|
149
202
|
} catch {
|
|
150
203
|
credential = null;
|
|
151
204
|
}
|
|
152
205
|
}
|
|
153
|
-
return desktopConversation(resources, content, prompt, signal, credential);
|
|
206
|
+
return desktopConversation(resources, content, prompt, signal, credential, workMode, onSteer);
|
|
154
207
|
}
|
|
155
208
|
if ((!task && (content.run_kind !== 'chat' || content.chat_mode !== 'chat')) || content.agent?.tool_type !== 'claude_code') {
|
|
156
209
|
return { status: 'failed', failure_code: 'unsupported_task', failure_detail: '当前独立客户端支持计算、成员同步及 Claude 文本任务' };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unionschool/easy-agents",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.23",
|
|
4
4
|
"description": "EasyAgents Client",
|
|
5
5
|
"easyAgentsDesktop": 1,
|
|
6
6
|
"type": "module",
|
|
@@ -21,10 +21,14 @@
|
|
|
21
21
|
"runtime/ssh_terminal.py",
|
|
22
22
|
"runtime/desktop_chat.py",
|
|
23
23
|
"runtime/task_run.py",
|
|
24
|
+
"runtime/doc_read.py",
|
|
24
25
|
"runtime/mcp.py",
|
|
26
|
+
"runtime/platform_prompt.py",
|
|
25
27
|
"runtime/easyagents_core/git_sync.py",
|
|
26
28
|
"runtime/easyagents_core/member_sync.py",
|
|
29
|
+
"runtime/easyagents_core/__init__.py",
|
|
27
30
|
"runtime/easyagents_core/process_support.py",
|
|
31
|
+
"runtime/easyagents_core/tools.py",
|
|
28
32
|
"runtime/easyagents_core/file_delivery.py",
|
|
29
33
|
"runtime/easyagents_core/mcp_call.py"
|
|
30
34
|
],
|