@unionschool/easy-agents 1.0.1 → 1.0.24

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,4 +1,4 @@
1
- # EasyAgents Client
1
+ # EasyAgents
2
2
 
3
3
  在要接任务的设备上单独安装客户端,首次用工作台生成的配对码绑定设备。Mac、Windows 和 Ubuntu 安装包自带 Node、Python 和客户端核心。设备要使用 Codex 或 Claude 时,还需安装并登录对应的工具。
4
4
 
@@ -6,8 +6,8 @@
6
6
 
7
7
  | 设备 | 安装和打开 | 设备配置位置 |
8
8
  | --- | --- | --- |
9
- | macOS 14+ | Intel 和 Apple 芯片都使用 `EasyAgents-Mac-Universal.zip`。解压后把 `EasyAgents Client.app` 拖入「应用程序」并打开,点菜单栏图标。 | `~/Library/Application Support/EasyAgents Client/` |
10
- | Windows x64 | 双击 `EasyAgents-Setup.exe`,按当前用户安装。从开始菜单打开 **EasyAgents Client**,以后可点托盘图标。在新终端输入 `easy-agents` 也可打开面板。 | `%APPDATA%\EasyAgents\` |
9
+ | macOS 14+ | Intel 和 Apple 芯片都使用 `EasyAgents-Mac-Universal.zip`。解压后把 `EasyAgents.app` 拖入「应用程序」并打开,点菜单栏图标。 | `~/Library/Application Support/EasyAgents Client/` |
10
+ | Windows x64 | 双击 `EasyAgents-Setup.exe`,按当前用户安装。从开始菜单打开 **EasyAgents**,以后可点托盘图标。在新终端输入 `easy-agents` 也可打开面板。 | `%APPDATA%\EasyAgents\` |
11
11
  | Ubuntu x64 | 在压缩包所在目录执行下面两行,以运行客户端的普通用户安装。 | `~/.easyagents/` |
12
12
  | Android 8+ | 安装交付的 `EasyAgents-Android-test.apk`,打开应用,用 Linux 设备配对码接入,点「上线接任务」。前台通知显示服务状态。 | 应用私有存储和 Android Keystore |
13
13
 
@@ -20,13 +20,13 @@ Ubuntu 的程序入口是 `~/.local/share/easyagents-client/current/easy-agents`
20
20
 
21
21
  ### 在 Mac 终端直接使用 easy-agents
22
22
 
23
- 应用内的命令是 `"/Applications/EasyAgents Client.app/Contents/Resources/easy-agents"`。用 `command -v easy-agents` 核对现有入口。以下命令为当前用户创建启动脚本,已有入口时会跳过创建。
23
+ 应用内的命令是 `"/Applications/EasyAgents.app/Contents/Resources/easy-agents"`(2026-11-23 前应用叫 `EasyAgents Client.app`,装新版后面板会自动把后台、开机启动和下面这个入口改到新应用,旧应用移到废纸篓)。用 `command -v easy-agents` 核对现有入口。以下命令为当前用户创建启动脚本,已有入口时会跳过创建。
24
24
 
25
25
  ```sh
26
26
  mkdir -p "$HOME/.local/bin"
27
27
  launcher="$HOME/.local/bin/easy-agents"
28
28
  if [ ! -e "$launcher" ] && [ ! -L "$launcher" ]; then
29
- printf '%s\n' '#!/bin/sh' 'exec "/Applications/EasyAgents Client.app/Contents/Resources/easy-agents" "$@"' > "$launcher" && chmod 755 "$launcher"
29
+ printf '%s\n' '#!/bin/sh' 'exec "/Applications/EasyAgents.app/Contents/Resources/easy-agents" "$@"' > "$launcher" && chmod 755 "$launcher"
30
30
  fi
31
31
  export PATH="$HOME/.local/bin:$PATH"
32
32
  command -v easy-agents
@@ -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 模式可用的认证。桌面对话功能需要安装包提供的工具适配和内置运行环境。
@@ -94,6 +94,6 @@ npm exec --offline -- easy-agents run
94
94
  - Node 核心支持 `/sha256 <文本>`、本地 Markdown 文档里的同类计算和成员同步。文档与同步的目录需与本机选定工作目录相符,可用 `EASYAGENTS_WORKSPACE` 指定。成员同步使用包内实现、系统 Git 和 Python 3.10+,更新已有检出目录。Android 首版可执行 SHA-256 消息和用户选择目录里的计算文档。
95
95
  - 客户端保存待回传结果,重连后补传。独立版尚未接入运行中 `/steer`、手动 `/sync`、平台远程读文档和编辑设备上的工具规则。
96
96
 
97
- 开发者在 `new-client/` 中执行 `npm ci`、`npm pack` 构建通用包。包内包含 `runtime/easyagents_core/` 中的 Git、文件交付和 MCP 模块及其进程支持,并随包附带 WebSocket 依赖。桌面安装器从同一目录取工具、模型、额度和平台 API 模块,按 `scripts/desktop-requirements.txt` 安装固定版本的 Python 依赖。
97
+ 开发者在 `client/` 中执行 `npm ci`、`npm pack` 构建通用包。包内包含 `runtime/easyagents_core/` 中的 Git、文件交付和 MCP 模块及其进程支持,并随包附带 WebSocket 依赖。桌面安装器从同一目录取工具、模型、额度和平台 API 模块,按 `scripts/desktop-requirements.txt` 安装固定版本的 Python 依赖。
98
98
 
99
- 在 Mac 上,从仓库根目录运行 `uv run --no-project --python 3.12 python new-client/macos/install.py --zip /path/to/EasyAgents-Mac-Universal.zip` 生成通用 ZIP。该模式只写出压缩包。菜单栏程序、Node 和内置 Python 都包含 `x86_64` 与 `arm64`。
99
+ 在 Mac 上,从仓库根目录运行 `uv run --no-project --python 3.12 python client/macos/install.py --zip /path/to/EasyAgents-Mac-Universal.zip` 生成通用 ZIP。该模式只写出压缩包。菜单栏程序、Node 和内置 Python 都包含 `x86_64` 与 `arm64`。
@@ -87,13 +87,13 @@ function updater(automatic) {
87
87
  const [command = desktop ? (process.platform === 'linux' ? 'status' : 'show') : '--help', ...args] = process.argv.slice(2);
88
88
  try {
89
89
  if (['--help', '-h'].includes(command) && !args.length) {
90
- console.log('EasyAgents Client\n\n'
90
+ console.log('EasyAgents\n\n'
91
91
  + 'easy-agents --version\n'
92
92
  + 'easy-agents configure <网关地址> <端口>\n'
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,11 +133,19 @@ 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])) {
139
144
  (await desktopState()).writeSnapshot(configDir, 'auto-update.json', { enabled: args[0] === 'on' });
140
145
  console.log(args[0] === 'on' ? '自动更新已开启' : '自动更新已关闭');
146
+ } else if (mac && command === 'relocate' && !args.length) {
147
+ // 应用改名或换位置后,把开机启动、面板自启、后台任务的 launchd 配置改到当前应用(安装脚本和面板会自动调用)。
148
+ console.log(await (await controls()).relocate(configDir));
141
149
  } else if (desktop && command === 'autostart' && args.length === 1 && ['on','off'].includes(args[0])) {
142
150
  if (args[0] === 'on' && !readSettings(devicePath)) throw new Error('请先配对设备,再设置开机启动');
143
151
  if (mac) await (await controls()).autostart(configDir, args[0] === 'on');
@@ -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')
@@ -1,10 +1,10 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
- import { existsSync, mkdirSync, openSync, closeSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { existsSync, mkdirSync, openSync, closeSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
4
  import { homedir, userInfo } from 'node:os';
5
- import { dirname, join } from 'node:path';
5
+ import { basename, 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);
@@ -57,14 +57,76 @@ export async function autostart(folder, enabled) {
57
57
  + '/usr/sbin/chown root:wheel "$t"; /bin/chmod 644 "$t"; /bin/mv -f "$t" ' + target;
58
58
  admin(cmd);
59
59
  } else if (!enabled && bootEnabled(folder)) admin('/bin/rm -f ' + target);
60
- if (enabled) {
61
- mkdirSync(dirname(agent), { recursive: true, mode: 0o700 });
62
- const temporary = agent + '.' + process.pid;
63
- const exe = join(dirname(macResources),'MacOS/EasyAgentsClient');
64
- writeFileSync(temporary, plist(entry('Label',str(name + '.panel')) + entry('RunAtLoad','<true/>')
65
- + entry('ProgramArguments','<array>' + str(exe) + str('--background') + '</array>')), { mode: 0o600, flag:'wx' });
66
- renameSync(temporary,agent);
67
- } else rmSync(agent,{force:true});
60
+ if (enabled) writePanel(folder);
61
+ else rmSync(agent,{force:true});
62
+ }
63
+
64
+ const panelFile = folder => join(homedir(),'Library/LaunchAgents',bootLabel(folder) + '.panel.plist');
65
+
66
+ function writePanel(folder) {
67
+ const agent = panelFile(folder);
68
+ mkdirSync(dirname(agent), { recursive: true, mode: 0o700 });
69
+ const temporary = agent + '.' + process.pid;
70
+ const exe = join(dirname(macResources),'MacOS/EasyAgentsClient');
71
+ writeFileSync(temporary, plist(entry('Label',str(bootLabel(folder) + '.panel')) + entry('RunAtLoad','<true/>')
72
+ + entry('ProgramArguments','<array>' + str(exe) + str('--background') + '</array>')), { mode: 0o600, flag:'wx' });
73
+ renameSync(temporary,agent);
74
+ }
75
+
76
+ // 应用改名或挪了位置(2026-11-23 起 EasyAgents Client.app 改名 EasyAgents.app):launchd 配置里写死了程序路径,
77
+ // 指向旧应用的要换成当前应用,否则下次开机或重启后台就找不到程序。配置目录与设备身份不变。
78
+ const unxml = s => s.replaceAll('&lt;','<').replaceAll('&gt;','>').replaceAll('&amp;','&');
79
+ export function programOf(file) {
80
+ try { const found = readFileSync(file,'utf8').match(/<key>ProgramArguments<\/key><array><string>([^<]*)<\/string>/); return found ? unxml(found[1]) : null; }
81
+ catch { return null; }
82
+ }
83
+ const currentBundle = () => dirname(dirname(macResources));
84
+ const elsewhere = file => { const program = programOf(file); return program !== null && !program.startsWith(currentBundle() + '/'); };
85
+ const launchdFiles = folder => [bootFile(folder), panelFile(folder), join(folder,'mac-worker.plist')];
86
+ export const moved = folder => launchdFiles(folder).some(elsewhere);
87
+
88
+ // 安装指南教用户建的命令行入口(一行 exec 应用内的 easy-agents),旧路径换成当前应用。
89
+ function relaunchers(old) {
90
+ for (const file of [join(homedir(),'.local/bin/easy-agents'), '/usr/local/bin/easy-agents', '/opt/homebrew/bin/easy-agents']) {
91
+ try {
92
+ const text = readFileSync(file, 'utf8');
93
+ if (text.length < 400 && text.includes('exec "' + old + '/Contents/Resources/easy-agents"'))
94
+ writeFileSync(file, text.replaceAll(old + '/Contents/Resources/', currentBundle() + '/Contents/Resources/'));
95
+ } catch {}
96
+ }
97
+ }
98
+
99
+ export async function relocate(folder) {
100
+ const stale = launchdFiles(folder).filter(elsewhere);
101
+ if (!stale.length) return '应用位置无需更新';
102
+ const old = stale.map(file => dirname(dirname(dirname(programOf(file))))).find(path => path.endsWith('.app'));
103
+ const running = job(folder).pid > 0;
104
+ await serviceCommand('stop', folder); // 先等当前任务回传
105
+ if (elsewhere(panelFile(folder))) writePanel(folder);
106
+ let bootKept = false;
107
+ if (elsewhere(bootFile(folder))) try {
108
+ const name = bootLabel(folder), target = bootFile(folder);
109
+ const data = Buffer.from(bootPlist(folder, macResources, userInfo().username, homedir())).toString('base64');
110
+ admin('set -eu; t=$(/usr/bin/mktemp /Library/LaunchDaemons/.' + name + '.XXXXXX); '
111
+ + 'trap \'/bin/rm -f "$t"\' EXIT; /bin/echo ' + data + ' | /usr/bin/base64 -D > "$t"; /usr/bin/plutil -lint "$t" >/dev/null; '
112
+ + '/usr/sbin/chown root:wheel "$t"; /bin/chmod 644 "$t"; /bin/mv -f "$t" ' + target + '; '
113
+ // 与“开机启动”开关一致:只改文件,下次开机生效;当前已载入的才重新载入(2026-11-23 本机实测时它没载入)。
114
+ + 'if /bin/launchctl print system/' + name + ' >/dev/null 2>&1; then /bin/launchctl bootout system/' + name + '; /bin/launchctl bootstrap system ' + target + '; fi');
115
+ } catch { bootKept = true; } // 没给管理员授权:其余照常迁移,旧应用留着(开机配置还指着它)
116
+ const worker = join(folder,'mac-worker.plist');
117
+ if (elsewhere(worker)) {
118
+ if (lookup(service(folder)).loaded) launch('bootout', service(folder));
119
+ rmSync(worker, { force: true });
120
+ }
121
+ if (running && !job(folder).pid) await serviceCommand('start', folder); // 原来在跑的照原样拉起
122
+ if (old) relaunchers(old);
123
+ let note = '已改用当前应用:' + basename(currentBundle());
124
+ if (bootKept) note += ';开机启动未更新(没有管理员授权),旧应用先保留,请在面板关掉再打开开机启动后再删旧应用';
125
+ else if (old && old !== currentBundle() && existsSync(old)) {
126
+ try { renameSync(old, join(homedir(), '.Trash', basename(old) + '.' + Date.now())); note += ';旧应用已移到废纸篓'; }
127
+ catch { note += ';旧应用 ' + basename(old) + ' 请手动删除'; }
128
+ }
129
+ return note;
68
130
  }
69
131
 
70
132
  function admin(command) {
@@ -77,7 +139,7 @@ export function desktopStatus(folder) {
77
139
  const { pid } = job(folder);
78
140
  const saved = readSnapshot(folder, 'mac-worker.json');
79
141
  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),
142
+ return { running: Boolean(pid), connected: Boolean(fresh && saved.connected), pid, terminalEnabled: terminalEnabled(folder), compactAt: compactAt(folder), moved: moved(folder),
81
143
  report: saved || {}, task: fresh ? saved.task : null };
82
144
  }
83
145
 
@@ -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,7 +1,7 @@
1
1
  {
2
2
  "name": "@unionschool/easy-agents",
3
- "version": "1.0.1",
4
- "description": "EasyAgents Client",
3
+ "version": "1.0.24",
4
+ "description": "EasyAgents",
5
5
  "easyAgentsDesktop": 1,
6
6
  "type": "module",
7
7
  "bin": {
@@ -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
  ],