@unionschool/easy-agents 1.0.1 → 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 CHANGED
@@ -86,7 +86,7 @@ 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
91
  - Mac 和 Ubuntu 安装包支持 Codex、Claude 的文本对话、续聊和本地文本任务。它们可从项目卡片或对话页接收聊天和工作消息。普通聊天是纯文本:Codex 只读会话、Claude 不开工具。工作消息(负责人与任务角色的对话、平台的流程通知)与任务运行一样用完整权限,带平台操作入口,Agent 凭据缺失或被撤销时自动领取,所以负责人能在对话里登记需求、发布任务、合并上报。可用的会话编号、模型与用量会随结果回传。
92
92
  - Mac 和 Windows 面板可显示检测到的 Codex、Claude、Cursor、Agy 登录和上报状态。平台控制额度上报开关,绿色胶囊显示已获得的剩余额度,测得零时显示零。Windows 和单独运行的普通 npm 版支持单次 Claude 文本任务,使用 bare 模式可用的认证。桌面对话功能需要安装包提供的工具适配和内置运行环境。
@@ -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])) {
@@ -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')
@@ -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('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
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
 
@@ -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
- const headers = { Authorization: 'Bearer ' + device.device_token };
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, worker, online = false, active, fatal;
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 && !active && !queue.size && !readdirSync(folder).some(f => f.endsWith('.json'))) onDrained?.();
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 request('POST', id + '/start', { tool_version: version });
95
- checkpoint(id, { started: true });
96
- if (ack?.status === 'running') result = { status: 'interrupted', failure_code: 'client_interrupted' };
97
- try { result ??= await execute(content, controller.signal, workCredential, { agentCredential, configDir }); }
98
- catch { result = controller.signal.aborted ? { status: 'cancelled', failure_code: 'cancelled' } :
99
- { status: 'failed', failure_code: 'client_error', failure_detail: '客户端执行失败' }; }
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
- if (worker || !online || !queue.size || signal.aborted) return;
111
- worker = (async () => {
112
- while (online && !signal.aborted && queue.size) {
113
- const [id, controller] = queue.entries().next().value;
114
- active = controller;
115
- reporter?.patch({ task: id });
116
- try { await processRun(id, controller); }
117
- catch (err) {
118
- if (err.status === 404 || err.status === 409) rmSync(join(folder, id + '.json'), { force: true });
119
- else {
120
- if ([401, 403].includes(err.status)) fatal = new Error('设备认证失败,请重新配对');
121
- online = false;
122
- socket?.terminate();
123
- return;
124
- }
125
- } finally { queue.delete(id); active = undefined; reporter?.patch({ task: null }); }
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
- active?.abort();
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
- const hello = { type: 'hello', client_version: version, tools: [], terminal, ...metadata };
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
- active?.abort();
216
- await worker;
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,7 +14,9 @@ function invoke(file, args, cwd, input, signal, timeout) {
14
14
  });
15
15
  }
16
16
 
17
- function desktopConversation(resources, content, prompt, signal, credential, tools = false) {
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;
@@ -22,19 +24,61 @@ function desktopConversation(resources, content, prompt, signal, credential, too
22
24
  resume: content.resume_session_ref, workspace: content.workspace?.local_path, timeout,
23
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 = 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
- });
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.end(JSON.stringify(input));
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,11 +185,15 @@ 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
- if (resources && ['codex', 'claude_code'].includes(content.agent?.tool_type) && (task || content.run_kind === 'chat')) {
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
147
193
  // (merge after deploy, answers, sync handoff) arrive with an empty chat_mode and must be able to act.
148
- const work = content.chat_mode !== 'chat' && !content.passthrough;
194
+ // 斜杠命令(passthrough)原样交给工具:工作模式保留工具权限,但不带平台规程和凭据(2026-11-23)。
195
+ const workMode = content.chat_mode !== 'chat';
196
+ const work = workMode && !content.passthrough;
149
197
  if (work && workCredential) {
150
198
  // A revoked or missing credential would leave the lead unable to register, publish or merge.
151
199
  try { if (agentCredential) await agentCredential(content); } catch {}
@@ -155,7 +203,7 @@ export async function execute(content, signal, workCredential, { agentCredential
155
203
  credential = null;
156
204
  }
157
205
  }
158
- return desktopConversation(resources, content, prompt, signal, credential, work);
206
+ return desktopConversation(resources, content, prompt, signal, credential, workMode, onSteer);
159
207
  }
160
208
  if ((!task && (content.run_kind !== 'chat' || content.chat_mode !== 'chat')) || content.agent?.tool_type !== 'claude_code') {
161
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": "1.0.1",
3
+ "version": "1.0.23",
4
4
  "description": "EasyAgents Client",
5
5
  "easyAgentsDesktop": 1,
6
6
  "type": "module",
@@ -21,11 +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",
25
26
  "runtime/platform_prompt.py",
26
27
  "runtime/easyagents_core/git_sync.py",
27
28
  "runtime/easyagents_core/member_sync.py",
29
+ "runtime/easyagents_core/__init__.py",
28
30
  "runtime/easyagents_core/process_support.py",
31
+ "runtime/easyagents_core/tools.py",
29
32
  "runtime/easyagents_core/file_delivery.py",
30
33
  "runtime/easyagents_core/mcp_call.py"
31
34
  ],
@@ -10,19 +10,87 @@ from uuid import UUID
10
10
 
11
11
  resources = os.environ.get("EASYAGENTS_MAC_RESOURCES") or os.environ["EASYAGENTS_DESKTOP_RESOURCES"]
12
12
  sys.path.insert(0, str(Path(resources) / "lib"))
13
- from easyagents_core.tools import ClaudeCodeAdapter, CodexAdapter
14
13
  sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
14
+ # 工具适配器用 npm 核心包自带的那份(只依赖标准库),不用安装包 lib 里打包时的旧副本:
15
+ # 这样 /compact、/steer 等适配器修复随核心更新生效,不必重装应用(2026-11-23)。
16
+ from runtime.easyagents_core.tools import NO_OUTPUT_TEXT, AntigravityAdapter, ClaudeCodeAdapter, CodexAdapter, SteerError
15
17
  from runtime.platform_prompt import platform_entry
16
18
 
19
+ # 聊天模式不是限制、是为了快(用户 2026-11-23:“chat 模式是为了减少聊天时间,不用花时间去看项目”“chat 的模式不是限制,是不用 agent 去看项目内容,除非用户有要求看项目”“聊天要使用工具”):
20
+ # 工具与工作模式一样齐全(可联网、可看文件),只是默认当普通对话、不主动翻项目;与工作模式的区别在平台侧
21
+ # (不附加任务规程、项目上下文和平台操作凭据)。之前关掉全部工具时,模型会把命令写成 <invoke> 文字假装执行。
22
+ CHAT_NOTE = ("这是 EasyAgents 的聊天模式,目的是快:当普通对话直接回答,不要花时间去看项目。工具都可以用(包括联网查资料),"
23
+ "但不要主动去读项目代码、文件或运行命令;用户明确要你看项目、查代码或动手时再做。"
24
+ "需要平台登记、派发或审批这类平台操作时,告诉用户发 /work 切到工作模式。")
25
+ # 建议回复(用户 2026-11-20 需求,2026-11-23 落地)与选项按钮(用户 2026-11-23):都写在回复最后,平台拆出来单独展示,
26
+ # 不自动发送。有推荐方案时建议回复填推荐的那个(用户在“1.0.14 消息链路测试”对话里定)。
27
+ SUGGEST = ("回复末尾可以附两样东西,平台会拆出来单独展示,都不会自动发送:\n"
28
+ "1. 选项按钮:需要用户在几个方案里选一个时,一定在最后写(渠道里显示成按钮,只在正文列 A/B/C 用户点不了)\n"
29
+ "<reply_options>\nA. 方案一句话\nB. 方案一句话\n</reply_options>\n"
30
+ "最多 6 个,每个不超过 40 字,写成用户会说的话(如“A. 继续,只检查 Mac 客户端”)。"
31
+ "用户点哪个,就等于发出那一行。正文里照常把方案讲清楚,选项只是快捷回答。\n"
32
+ "2. 建议回复:用户接下来很可能要确认授权、选择下一步或补充信息时,在最后单独一行写 "
33
+ "<suggested_reply>建议文字</suggested_reply>:只写一条,纯文本,不超过 200 字,用户会修改后自己发送。"
34
+ "给出多个方案并有明确推荐时,建议回复填选推荐方案的那句话(如“选 A,……”);没有明确推荐时不要替用户选。\n"
35
+ "涉及授权时,选项和建议都要写清操作对象和范围。没有合适的就不写。")
17
36
 
18
- class TextClaude(ClaudeCodeAdapter):
19
- def _command(self, resume_session_ref):
20
- command = [self.executable, "--safe-mode", "--print", "--input-format", "stream-json",
21
- "--output-format", "stream-json", "--verbose", "--tools", "", "--strict-mcp-config",
22
- "--disable-slash-commands"]
23
- if resume_session_ref:
24
- command.extend(["--resume", resume_session_ref])
25
- return command
37
+
38
+ NEW_SESSION_COMMANDS = ("/new", "/clear")
39
+ NEW_SESSION_TEXT = "已开始新会话:智能体不再记得之前的内容,聊天记录仍保留。"
40
+
41
+
42
+ def instructions_for(tool, tools, command):
43
+ """对话运行附加的系统说明;斜杠命令原样交给工具,不附加。聊天模式多一段“不主动翻项目”。"""
44
+ if command:
45
+ return None
46
+ return SUGGEST if tools else CHAT_NOTE + "\n\n" + SUGGEST
47
+
48
+
49
+ # 压缩提示门槛(用户 2026-11-23):ctx 达到这个百分比、回复又没有自己的选项时,平台在回复下面放“压缩上下文”按钮。
50
+ # 在菜单栏面板设(easy-agents compact-at,存 mac-compact.json),0 关闭;没设过用 60(Claude 约 80% 多自动压缩,留出几轮)。
51
+ COMPACT_AT_DEFAULT = 60
52
+
53
+
54
+ def compact_at():
55
+ try:
56
+ value = json.loads((Path(os.environ["EASYAGENTS_CONFIG_DIR"]) / "mac-compact.json").read_text())["percent"]
57
+ except (KeyError, OSError, ValueError, TypeError):
58
+ return COMPACT_AT_DEFAULT
59
+ return value if type(value) is int and 0 <= value <= 100 else COMPACT_AT_DEFAULT
60
+
61
+
62
+ def command_of(content):
63
+ """斜杠命令名(小写,如 /compact);不是透传命令返回 None。"""
64
+ if not content.get("passthrough"):
65
+ return None
66
+ words = str(content.get("prompt") or "").strip().split()
67
+ return words[0].lower() if words and words[0].startswith("/") else None
68
+
69
+
70
+ def serve_steers(adapter, acks):
71
+ """首行之后的 stdin 每行一条补充:{"type":"steer","message_id","content"};回执写 fd 3(协议第 16 节)。"""
72
+ def ack(message_id, status):
73
+ try:
74
+ acks.write(json.dumps({"message_id": message_id, "status": status}) + "\n")
75
+ acks.flush()
76
+ except (OSError, ValueError):
77
+ pass
78
+
79
+ for line in sys.stdin:
80
+ try:
81
+ item = json.loads(line)
82
+ message_id, text = item["message_id"], item["content"]
83
+ except (ValueError, KeyError, TypeError):
84
+ continue
85
+ try:
86
+ pending = adapter.steer(text)
87
+ if pending is not None: # Codex 返回等服务器确认的 Future
88
+ pending.result(timeout=8)
89
+ ack(message_id, "accepted")
90
+ except SteerError as exc:
91
+ ack(message_id, exc.status if exc.status in ("too_late", "failed") else "failed")
92
+ except Exception:
93
+ ack(message_id, "failed")
26
94
 
27
95
 
28
96
  def failed(code, detail):
@@ -54,16 +122,28 @@ def run(content, cancelled):
54
122
  # Work messages (lead and task-role conversations) act on the platform and the repository like task runs:
55
123
  # full permissions (T-44) and the platform entry. Plain chat stays a read-only text conversation.
56
124
  tools = content.get("tools") is True
125
+ command = command_of(content)
57
126
  if tool == "codex":
58
127
  adapter = CodexAdapter()
59
- options = {} if tools else {"sandbox_policy": {"type": "readOnly", "networkAccess": False}}
128
+ options = {} # 聊天、工作同样完整权限(用户 2026-11-23:聊天要使用工具)
129
+ if command == "/compact":
130
+ # Codex 没有斜杠命令:/compact 直接调 app-server 的 thread/compact/start(2026-11-23)。
131
+ options["compact"] = True
60
132
  elif tool == "claude_code":
61
- adapter = ClaudeCodeAdapter() if tools else TextClaude()
133
+ adapter = ClaudeCodeAdapter()
134
+ options = {}
135
+ elif tool == "antigravity":
136
+ # Agy 对话(2026-11-23 接入独立客户端):聊天、工作同一套参数(T-158 聊天不限权限);运行中补充见适配器说明。
137
+ # Agy 没有附加系统说明的参数,建议回复格式暂不告知。
138
+ adapter = AntigravityAdapter()
62
139
  options = {}
63
140
  else:
64
141
  return failed("unsupported_task", "此工具尚未接入设备文本对话")
65
142
  if not shutil.which(adapter.executable):
66
143
  return failed("tool_missing", "本机未找到 " + adapter.executable_name)
144
+ adapter.instructions = instructions_for(tool, tools, command) if tool != "antigravity" else None
145
+ if content.get("_on_adapter"):
146
+ content["_on_adapter"](adapter)
67
147
 
68
148
  resume = content.get("resume")
69
149
  if resume is not None:
@@ -95,17 +175,36 @@ def run(content, cancelled):
95
175
  prompt = f"本次调度模式:platform;运行编号:{run_id}\n{guidance}\n\n{prompt}"
96
176
  if tools and content.get("credential"):
97
177
  prompt += platform_entry(content["credential"]["file"])
178
+ if command:
179
+ options["allow_empty"] = True # /compact 成功时 Claude 不输出文字,回“命令已执行”
98
180
  result = adapter.invoke(prompt=prompt, cwd=cwd, resume_session_ref=resume,
99
181
  timeout_seconds=content["timeout"], cancel_event=cancelled,
100
182
  model=content.get("model"), platform_run_id=run_id, **options)
183
+ if command in NEW_SESSION_COMMANDS and result.status == "succeeded" and result.reply_text == NO_OUTPUT_TEXT:
184
+ # Claude 的 /new、/clear 会换一个空会话(会话号随回传更新),默认的“命令已执行”看不出发生了什么(用户 2026-11-23)。
185
+ result.reply_text = NEW_SESSION_TEXT
101
186
  if result.reply_text and len(result.reply_text) > 1_000_000:
102
187
  return failed("bad_output", "工具回复超过平台长度上限")
188
+ if isinstance(result.context, dict):
189
+ result.context = {**result.context, "compact_at": compact_at()}
103
190
  fields = ("status", "reply_text", "tool_session_ref", "tool_version", "model_name",
104
191
  "usage", "context", "failure_code", "failure_detail")
105
192
  return {name: getattr(result, name) for name in fields if getattr(result, name) is not None}
106
193
 
107
194
 
108
- if __name__ == "__main__":
195
+ def main():
109
196
  cancelled = threading.Event()
110
197
  signal.signal(signal.SIGTERM, lambda *_: cancelled.set())
111
- print(json.dumps(run(json.load(sys.stdin), cancelled), ensure_ascii=False))
198
+ content = json.loads(sys.stdin.readline())
199
+ try:
200
+ acks = os.fdopen(3, "w")
201
+ except OSError:
202
+ acks = None
203
+ if acks is not None:
204
+ content["_on_adapter"] = lambda adapter: threading.Thread(
205
+ target=serve_steers, args=(adapter, acks), daemon=True).start()
206
+ print(json.dumps(run(content, cancelled), ensure_ascii=False))
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()