@unionschool/easy-agents 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,47 +1,96 @@
1
- # @unionschool/easy-agents
1
+ # EasyAgents Client
2
2
 
3
- The EasyAgents device client pairs this computer with a gateway, receives runs and returns their results.
3
+ 在要接任务的设备上单独安装客户端,首次用工作台生成的配对码绑定设备。Mac、Windows 和 Ubuntu 安装包自带 Node、Python 和客户端核心。设备要使用 Codex 或 Claude 时,还需安装并登录对应的工具。
4
4
 
5
- ## Install
5
+ ## 选择安装包
6
6
 
7
- Requires Node.js 22 or later. Install the npm package in the project where you want to use the client.
7
+ | 设备 | 安装和打开 | 设备配置位置 |
8
+ | --- | --- | --- |
9
+ | macOS 14+ | 解压与处理器匹配的包,把 `EasyAgents Client.app` 拖入「应用程序」并打开,点菜单栏图标。当前交付的 `EasyAgents-Mac-Intel.zip` 为 Intel 构建。 | `~/Library/Application Support/EasyAgents Client/` |
10
+ | Windows x64 | 双击 `EasyAgents-Setup.exe`,按当前用户安装。从开始菜单打开 **EasyAgents Client**,以后可点托盘图标。在新终端输入 `easy-agents` 也可打开面板。 | `%APPDATA%\EasyAgents\` |
11
+ | Ubuntu x64 | 在压缩包所在目录执行下面两行,以运行客户端的普通用户安装。 | `~/.easyagents/` |
12
+ | Android 8+ | 安装交付的 `EasyAgents-Android-test.apk`,打开应用,用 Linux 设备配对码接入,点「上线接任务」。前台通知显示服务状态。 | 应用私有存储和 Android Keystore |
8
13
 
9
14
  ```sh
10
- npm install @unionschool/easy-agents
11
- npm exec --offline -- easy-agents --version
15
+ tar -xzf EasyAgents-Ubuntu-x64.tar.gz
16
+ sh EasyAgents-Client/install.sh
12
17
  ```
13
18
 
14
- ## Pair a device
19
+ Ubuntu 的程序入口是 `~/.local/share/easyagents-client/current/easy-agents`。安装器在 `~/.local/bin/` 建立 `easy-agents`。如果已有其他同名程序,安装器会保留它,此时请用新版的完整路径。
20
+
21
+ ### 在 Mac 终端直接使用 easy-agents
15
22
 
16
- Run the following command and enter the gateway, port and one-time pairing code for this device's operating system. A hostname uses HTTPS by default. Press Enter to accept a displayed default. The terminal hides the code.
23
+ 应用内的命令是 `"/Applications/EasyAgents Client.app/Contents/Resources/easy-agents"`。用 `command -v easy-agents` 核对现有入口。以下命令为当前用户创建启动脚本,已有入口时会跳过创建。
17
24
 
18
25
  ```sh
19
- npm exec --offline -- easy-agents pair
20
- npm exec --offline -- easy-agents status
26
+ mkdir -p "$HOME/.local/bin"
27
+ launcher="$HOME/.local/bin/easy-agents"
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"
30
+ fi
31
+ export PATH="$HOME/.local/bin:$PATH"
32
+ command -v easy-agents
33
+ easy-agents --version
34
+ ```
35
+
36
+ 如果新开的终端找不到命令,将上面的 `export PATH=…` 一行加入 `~/.zprofile`。已有旧 Python 客户端的设备先按下文交接,再创建入口。Mac 面板右上角的「退出面板」会关闭菜单栏图标,后台继续接任务;再次输入 `easy-agents` 可打开面板。
37
+
38
+ ## 首次配对和上线
39
+
40
+ 1. 在工作台的设备管理中,给目标设备生成一次性配对码。Mac、Windows、Ubuntu 选择对应系统,Android 选择 Linux。
41
+ 2. Mac 或 Windows 打开连接设置,填 API 网关、端口和配对码。若平台单独提供 WebSocket 网关,也填入管理员提供的 `wss://` 地址。保存配对后启动后台。Android 在应用内完成相同步骤。
42
+ 3. Ubuntu 在终端运行 `easy-agents pair`,按提示输入网关、端口和配对码。独立 WebSocket 主机部署在配对后运行下方 `websocket` 命令,然后执行 `easy-agents start`。
43
+ 4. 用桌面面板或 `easy-agents status --json` 确认已配对且网关已连接,再到工作台确认这台设备在线、心跳在更新。
44
+
45
+ 独立 WebSocket 网关示例(替换为这台设备已配对的 API 地址和实际 WSS 地址):
46
+
47
+ ```sh
48
+ easy-agents websocket https://api.example.com wss://ws.example.com
21
49
  ```
22
50
 
23
- Pairing saves the gateway and device credentials in the user-private `npm-device.json`. To change the paired gateway, run `pair` again with a new code. Failed pairing keeps the saved binding. Pairing a device that already exists on the platform rotates that device's token for all installations using its identity.
51
+ 升级现有独立版时沿用原配置,日常断线会自动重连。旧 Python 版迁到独立版时,先确认旧服务空闲并停止。Mac 独立版使用专用配置目录,Ubuntu 同目录下的旧 `config.json` 和新版 `npm-device.json` 也分别保存。目标是接管已有设备时,用工作台为**该设备**签发的配对码,原设备令牌会失效。保留旧配置目录中的 Agent 凭据、运行记录和项目工作树。
52
+
53
+ ## 目录内安装 npm 命令行
24
54
 
25
- ## Set the initial gateway
55
+ 普通 npm 版需要 Node.js 22 或以上。在选定的空目录执行以下命令,本机只在该目录安装 `@unionschool/easy-agents`。
26
56
 
27
57
  ```sh
28
- npm exec --offline -- easy-agents configure https://gateway.example.com 443
58
+ npm init -y
59
+ npm install @unionschool/easy-agents
60
+ npm exec --offline -- easy-agents pair
29
61
  npm exec --offline -- easy-agents status
62
+ npm exec --offline -- easy-agents run
30
63
  ```
31
64
 
32
- The CLI saves the initial gateway URL in `npm-config.json`. The default configuration directory is `~/.easyagents/` on macOS and Linux and `%APPDATA%\EasyAgents\` on Windows. Set `EASYAGENTS_CONFIG_DIR` to use a different directory.
65
+ `pair` 在终端隐藏输入配对码。普通 npm 的 `status` 显示本地绑定,`run` 前台上线。看到「设备已上线」表示网关已接受连接。若使用独立 WSS 主机,把最后一行换成 `EASYAGENTS_WS_ORIGIN=wss://ws.example.com npm exec --offline -- easy-agents run`(Unix)。普通 npm 版还提供 `--version` 和 `configure <网关地址> <端口>`。设备配置可由 `EASYAGENTS_CONFIG_DIR` 指定,默认在 macOS/Linux 的 `~/.easyagents/` 或 Windows 的 `%APPDATA%\EasyAgents\`。
66
+
67
+ ## 桌面安装包的日常命令
68
+
69
+ | 命令 | 用途 |
70
+ | --- | --- |
71
+ | `easy-agents` | Mac 和 Windows 打开面板,Ubuntu 显示状态 |
72
+ | `easy-agents start`、`stop`、`restart` | 管理后台,停止与重启会等待在途结果回传 |
73
+ | `easy-agents status --json`、`logs`、`doctor` | 查看连接、运行记录或本机工具状态 |
74
+ | `easy-agents autostart on` / `off` | 切换开机启动。系统可能要求管理员授权 |
75
+ | `easy-agents update`、`auto-update on` / `off` | 检查兼容的 npm 稳定版核心或切换自动检查。重连验证失败会回退,原生面板和内置解释器通过安装包升级 |
76
+ | `easy-agents terminal on` / `off` | 在支持的 Unix 设备上切换工作台网页终端 |
33
77
 
34
- ## Run the paired device
78
+ ## 已安装设备怎么升级
35
79
 
36
- Run `npm exec --offline -- easy-agents run` in the foreground. Wait for `设备已上线`. Ctrl+C stops the connection. The worker uses the identity created by `pair` and keeps pending results in `npm-runs/` for retry. The `status` command reports the local binding.
80
+ - **Mac、Windows、Ubuntu 安装包**:设备空闲时运行 `easy-agents update` 更新核心。再用 `easy-agents --version` 和 `easy-agents status --json` 检查,并在工作台确认设备在线。若更新的是面板或内置运行环境,保留配置并使用新版安装包覆盖安装,随后启动后台。
81
+ - **目录内 npm**:在原安装目录运行 `npm install --save-exact @unionschool/easy-agents@latest`。随后运行 `npm exec --offline -- easy-agents --version`,沿用原来的配置和 WebSocket 环境,重新执行 `npm exec --offline -- easy-agents run`。
82
+ - **Android**:安装同签名、同包名的新版 APK,打开应用后上线。常规覆盖升级沿用原配对,无需重新生成配对码。
37
83
 
38
- The default WebSocket path is `/ws/client` on the paired gateway. For deployments with a separate WebSocket host, set `EASYAGENTS_WS_ORIGIN` to its trusted `wss://` origin before starting the worker. That host receives the device credential.
84
+ 服务接管、升级前检查及回退见[客户端升级技能](../skills/easyagents-client/SKILL.md)(仓库内)。
39
85
 
40
- On Unix, the workbench terminal is offered by default when Python 3, OpenSSH, readable local SSH host public keys and an SSH service on loopback port 22 are available. In the workbench, open **AI → 设备管理 → 终端**. The terminal presents an SSH login for the non-root account running the client. The device verifies its local host key and uses keyboard-interactive or password authentication. Set `EASYAGENTS_TERMINAL=0` before starting the worker to disable the terminal.
86
+ ## 各端能执行什么
41
87
 
42
- - Send `/sha256 hello` to compute a UTF-8 text digest on the device. This needs only the npm package and Node.js.
43
- - For a local document execution run, start the worker from the workspace registered for this device, or point `EASYAGENTS_WORKSPACE` at it. The worker reads the assigned Markdown file within that directory. A document containing `/sha256 <text>` returns the digest. Other text jobs assigned to Claude Code require a locally configured Claude CLI with credentials supported in bare mode. The text backend runs without host tools. Versioned Git task delivery, code editing and deployment workflows are outside this release.
44
- - Platform member-sync runs use the bundled EasyAgents sync implementation, system Git and Python 3.10+. Python is launched in isolated mode without site packages. The registered workspace must match the locally selected repository. This operation updates an existing checkout.
45
- - A missing executor or unsupported job produces a failure result. Receiving a run result is separate from approval or acceptance of a project task.
88
+ - Mac 和 Ubuntu 安装包能接平台任务分支上的执行、审核、部署和澄清运行(Codex、Claude,完整权限,与旧 Python 客户端的规则一致):执行在任务分支上工作并在成功后推送;审核和部署检出本轮交付的提交;工作目录有未提交改动时,在客户端配置目录的 `worktrees/` 里另建工作树,原目录不动,合并后的成员同步会清理这些工作树。Agent 通过提示里给出的平台命令调用工具;Agent 凭据缺失或已被平台撤销时,客户端自动领取新凭据(平台会同时撤销旧凭据)。旧的同目录文件交付和用户发布命令(`publish`)不支持。
89
+ - **未完成**:Windows、Android 和单独运行的普通 npm 版还不能接任务分支运行,会回报 `handoff_unsupported`。这几端暂时用不上(用户 2026-11-22 定),以后需要时再单独升级。
90
+ - Mac 和 Ubuntu 安装包支持 Codex、Claude 的文本对话、续聊和本地文本任务。它们可从项目卡片或对话页接收聊天和工作消息。工作消息可用已有 Agent 凭据读取平台任务规程。Codex 使用只读会话,Claude 使用纯文本会话。可用的会话编号、模型与用量会随结果回传。
91
+ - Mac 和 Windows 面板可显示检测到的 Codex、Claude、Cursor、Agy 登录和上报状态。平台控制额度上报开关,绿色胶囊显示已获得的剩余额度,测得零时显示零。Windows 和单独运行的普通 npm 版支持单次 Claude 文本任务,使用 bare 模式可用的认证。桌面对话功能需要安装包提供的工具适配和内置运行环境。
92
+ - 在支持的 Unix 主机上,网页终端使用本机运行用户进行 SSH 登录,需要 Python 3、OpenSSH、可读的本机 SSH 公钥和监听回环端口 22 的 SSH 服务。可在工作台的「AI → 设备管理 → 终端」打开。普通 npm 可在启动前用 `EASYAGENTS_TERMINAL=0` 关闭。
93
+ - Node 核心支持 `/sha256 <文本>`、本地 Markdown 文档里的同类计算和成员同步。文档与同步的目录需与本机选定工作目录相符,可用 `EASYAGENTS_WORKSPACE` 指定。成员同步使用包内实现、系统 Git 和 Python 3.10+,更新已有检出目录。Android 首版可执行 SHA-256 消息和用户选择目录里的计算文档。
94
+ - 客户端保存待回传结果,重连后补传。独立版尚未接入运行中 `/steer`、手动 `/sync`、平台远程读文档和编辑设备上的工具规则。
46
95
 
47
- To build from this repository, run `npm ci` and `npm pack` in `new-client/`. The prepack script includes the shared client modules. The published tarball includes its WebSocket dependency and installs offline without a source checkout.
96
+ 开发者在 `new-client/` 中执行 `npm ci`、`npm pack` 构建通用包。包内包含 `runtime/easyagents_core/` 中的 Git、文件交付和 MCP 模块及其进程支持,并随包附带 WebSocket 依赖。桌面安装器从同一目录取工具、模型、额度和平台 API 模块,按 `scripts/desktop-requirements.txt` 安装固定版本的 Python 依赖。
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { closeSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { dirname, join } from 'node:path';
5
+ import { execFileSync, spawn, spawnSync } from 'node:child_process';
5
6
  import { randomUUID } from 'node:crypto';
6
7
  import { enroll, promptPairing, protectDeviceFile } from './pair.js';
7
8
 
@@ -23,6 +24,13 @@ function gatewayOrigin(address, port) {
23
24
  return url.origin;
24
25
  }
25
26
 
27
+ function websocketOrigin(value) {
28
+ const target = new URL(value.trim());
29
+ if (target.protocol !== 'wss:' || target.pathname !== '/' || target.search || target.hash ||
30
+ target.username || target.password) throw new Error('WebSocket 网关须为 WSS 地址');
31
+ return target.origin;
32
+ }
33
+
26
34
  function readSettings(path) {
27
35
  let raw;
28
36
  try {
@@ -61,15 +69,30 @@ async function saveSettings(path, getData) {
61
69
  }
62
70
  }
63
71
 
64
- const [command = '--help', ...args] = process.argv.slice(2);
72
+ const mac = process.platform === 'darwin' && Boolean(process.env.EASYAGENTS_MAC_RESOURCES);
73
+ const desktop = mac || Boolean(process.env.EASYAGENTS_DESKTOP_RESOURCES);
74
+ const resources = process.env.EASYAGENTS_MAC_RESOURCES || process.env.EASYAGENTS_DESKTOP_RESOURCES;
75
+ const controls = () => mac ? import('./mac-service.js') : import('./portable-service.js');
76
+ const desktopState = () => import('./mac-reports.js');
77
+ function updater(automatic) {
78
+ const python = join(resources, process.platform === 'win32' ? 'python/python.exe' : 'python/bin/python3');
79
+ const args = ['-I','-B','-X','utf8',join(resources,'update.py'), ...(automatic ? ['--automatic'] : [])];
80
+ const separateUnit = automatic && process.platform === 'linux' && Boolean(process.env.INVOCATION_ID);
81
+ const child = spawn(separateUnit ? 'systemd-run' : python, separateUnit
82
+ ? ['--user','--quiet','--collect','--setenv=EASYAGENTS_CONFIG_DIR='+configDir,python,...args] : args,
83
+ { env: { ...process.env, EASYAGENTS_CONFIG_DIR: configDir }, detached: automatic, windowsHide: true, stdio: automatic ? 'ignore' : 'inherit' });
84
+ if (automatic) { child.on('error', () => {}); child.unref(); return; }
85
+ return new Promise((ok, fail) => { child.once('error', fail); child.once('exit', code => code === 0 ? ok() : fail(new Error('请查看设置中的更新状态'))); });
86
+ }
87
+ const [command = desktop ? (process.platform === 'linux' ? 'status' : 'show') : '--help', ...args] = process.argv.slice(2);
65
88
  try {
66
89
  if (['--help', '-h'].includes(command) && !args.length) {
67
- console.log('EasyAgents CLI 预览版\n\n'
90
+ console.log('EasyAgents Client\n\n'
68
91
  + 'easy-agents --version\n'
69
92
  + 'easy-agents configure <网关地址> <端口>\n'
70
93
  + 'easy-agents pair\n'
71
94
  + 'easy-agents run\n'
72
- + 'easy-agents status');
95
+ + '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' : ''));
73
96
  } else if (['--version', '-v'].includes(command) && !args.length) {
74
97
  console.log(version);
75
98
  } else if (command === 'configure' && args.length === 2) {
@@ -78,26 +101,113 @@ try {
78
101
  if (device && device.gateway !== gateway) throw new Error('更换已配对网关请运行 easy-agents pair');
79
102
  await saveSettings(configPath, () => ({ gateway }));
80
103
  console.log('网关已保存');
81
- } else if (command === 'pair' && !args.length) {
104
+ } else if (command === 'pair' && (!args.length || (desktop && args.length === 1 && args[0] === '--panel'))) {
105
+ if (desktop && (await (await controls()).desktopStatus(configDir)).running) throw new Error('请先停止后台,再重新配对');
82
106
  const current = readSettings(devicePath) ?? readSettings(configPath);
83
- const [address, port, code] = await promptPairing(current?.gateway);
107
+ let address, port, code, wsOrigin;
108
+ if (args[0] === '--panel') {
109
+ const input = [];
110
+ let bytes = 0;
111
+ for await (const chunk of process.stdin) {
112
+ bytes += chunk.length;
113
+ if (bytes > 4096) throw new Error('配对设置过长');
114
+ input.push(chunk);
115
+ }
116
+ const values = JSON.parse(Buffer.concat(input).toString());
117
+ address = values.address.trim(); port = values.port.trim(); code = values.code.trim().toUpperCase();
118
+ if (values.wsOrigin?.trim()) wsOrigin = websocketOrigin(values.wsOrigin);
119
+ } else [address, port, code] = await promptPairing(current?.gateway);
84
120
  const gateway = gatewayOrigin(address.includes('://') ? address : 'https://' + address, port);
85
- await saveSettings(devicePath, () => enroll(gateway, code, version));
121
+ await saveSettings(devicePath, async () => ({ ...await enroll(gateway, code, version), ...(wsOrigin ? { ws_origin: wsOrigin } : {}) }));
86
122
  console.log('设备配对成功');
123
+ } else if (desktop && command === 'websocket' && args.length === 2) {
124
+ const ws_origin = websocketOrigin(args[1]);
125
+ await saveSettings(devicePath, () => {
126
+ const paired = readSettings(devicePath);
127
+ if (!paired || paired.gateway !== args[0]) throw new Error('网关与当前设备绑定不符');
128
+ return { ...paired, ws_origin };
129
+ });
130
+ console.log('WebSocket 地址已保存,下次连接使用新地址');
131
+ } else if (desktop && command === 'terminal' && args.length === 1 && ['on','off'].includes(args[0])) {
132
+ const { writeSnapshot } = await import('./mac-reports.js');
133
+ writeSnapshot(configDir, 'mac-terminal.json', { enabled: args[0] === 'on' });
134
+ console.log(args[0] === 'on' ? '网页终端已开启' : '网页终端已关闭');
135
+ } else if (desktop && command === 'update' && !args.length) {
136
+ await updater(false);
137
+ } else if (desktop && command === 'auto-update' && args.length === 1 && ['on','off'].includes(args[0])) {
138
+ (await desktopState()).writeSnapshot(configDir, 'auto-update.json', { enabled: args[0] === 'on' });
139
+ console.log(args[0] === 'on' ? '自动更新已开启' : '自动更新已关闭');
140
+ } else if (desktop && command === 'autostart' && args.length === 1 && ['on','off'].includes(args[0])) {
141
+ if (args[0] === 'on' && !readSettings(devicePath)) throw new Error('请先配对设备,再设置开机启动');
142
+ if (mac) await (await controls()).autostart(configDir, args[0] === 'on');
143
+ else if (process.platform === 'win32') {
144
+ execFileSync(join(process.env.SystemRoot,'System32/WindowsPowerShell/v1.0/powershell.exe'),
145
+ ['-NoProfile','-STA','-ExecutionPolicy','RemoteSigned','-File',join(resources,'Autostart.ps1'),args[0]], { stdio: 'inherit', windowsHide: true });
146
+ } else throw new Error('请通过安装目录的 easy-agents 设置系统服务');
147
+ (await desktopState()).writeSnapshot(configDir, 'desktop-autostart.json', { enabled: args[0] === 'on' });
148
+ console.log(args[0] === 'on' ? '已启用开机启动' : '已关闭开机启动');
87
149
  } else if (command === 'run' && !args.length) {
88
150
  const device = readSettings(devicePath);
89
151
  if (!device) throw new Error('请先运行 easy-agents pair');
90
152
  const { runDevice } = await import('./run.js');
91
153
  const controller = new AbortController();
154
+ const drain = new AbortController();
155
+ const requestDrain = () => drain.abort();
156
+ const reporter = desktop ? (await import('./mac-reports.js')).macReporter(configDir) : undefined;
157
+ if (mac) process.on('SIGUSR2', requestDrain);
158
+ const release = desktop && !mac ? await (await controls()).claim(configDir, drain) : undefined;
159
+ // The updater must outlive the worker it may gracefully restart.
160
+ let firstCheck, periodic;
161
+ if (desktop && existsSync(join(resources,'update.py'))) {
162
+ const check = () => { if (!drain.signal.aborted) updater(true); };
163
+ firstCheck = setTimeout(check, 60000); firstCheck.unref();
164
+ periodic = setInterval(check, 6 * 3600000); periodic.unref();
165
+ }
92
166
  const stop = () => controller.abort();
93
167
  process.once('SIGINT', stop);
94
168
  process.once('SIGTERM', stop);
95
- try { await runDevice(device, configDir, version, controller.signal); }
96
- finally { process.off('SIGINT', stop); process.off('SIGTERM', stop); }
97
- } else if (command === 'status' && !args.length) {
169
+ try { await runDevice(device, configDir, version, controller.signal, { reporter, drain: drain.signal, onDrained: stop }); }
170
+ finally {
171
+ process.off('SIGINT', stop); process.off('SIGTERM', stop);
172
+ if (mac) process.off('SIGUSR2', requestDrain);
173
+ clearTimeout(firstCheck); clearInterval(periodic);
174
+ release?.();
175
+ }
176
+ } else if (desktop && ['show','start','stop','restart','logs'].includes(command) && !args.length) {
177
+ if (['start','restart'].includes(command) && !readSettings(devicePath)) throw new Error('请先配对设备');
178
+ if (!mac && command === 'show' && process.platform === 'win32') {
179
+ const exe = join(process.env.SystemRoot, 'System32/WindowsPowerShell/v1.0/powershell.exe');
180
+ const child = spawn(exe, ['-NoProfile','-STA','-WindowStyle','Hidden','-ExecutionPolicy','RemoteSigned','-File',
181
+ join(process.env.EASYAGENTS_DESKTOP_RESOURCES, 'Tray.ps1')], { detached: true, windowsHide: true, stdio: 'ignore' });
182
+ await new Promise((ok, fail) => { child.once('spawn', ok); child.once('error', fail); }); child.unref();
183
+ } else if (!mac && command === 'logs') {
184
+ try { console.log(readFileSync(join(configDir,'worker.log'),'utf8').split('\n').slice(-100).join('\n')); }
185
+ catch (error) { if (error.code !== 'ENOENT') throw error; console.log('暂无日志'); }
186
+ } else if (!mac && command === 'show') console.log('本机运行状态请使用 easy-agents status');
187
+ else await (await controls()).serviceCommand(command, configDir);
188
+ } else if (desktop && ['accounts','doctor'].includes(command) && (args.length === 0 || (args.length === 1 && args[0] === '--json'))) {
189
+ console.log(JSON.stringify(await (await import('./mac-reports.js')).localAccounts(configDir)));
190
+ } else if (command === 'status' && (!args.length || (desktop && args.length === 1 && args[0] === '--json'))) {
98
191
  const device = readSettings(devicePath);
99
192
  const gateway = (device ?? readSettings(configPath))?.gateway ?? '未配置';
100
- console.log('版本:' + version + '\n网关:' + gateway + '\n设备配对:' + (device ? '已配对(本机已保存凭据)' : '未配对'));
193
+ const status = desktop ? await (await controls()).desktopStatus(configDir) : null;
194
+ if (status) {
195
+ const { readSnapshot } = await desktopState();
196
+ status.autoUpdate = readSnapshot(configDir, 'auto-update.json')?.enabled !== false;
197
+ status.updateMessage = readSnapshot(configDir, 'updates/last.json')?.message ?? '';
198
+ status.autostart = mac ? (await controls()).bootEnabled(configDir) : readSnapshot(configDir,'desktop-autostart.json')?.enabled === true;
199
+ if (process.platform === 'linux') status.autostart = configDir === join(homedir(), '.easyagents') &&
200
+ spawnSync('systemctl',['--user','is-enabled','--quiet','easyagents-npm.service'],{timeout:3000,stdio:'ignore'}).status === 0 &&
201
+ spawnSync('loginctl',['show-user',String(process.getuid()),'--property=Linger','--value'],{timeout:3000,encoding:'utf8'}).stdout?.trim() === 'yes';
202
+ }
203
+ if (desktop && (status.report.gateway !== device?.gateway || status.report.deviceId !== device?.device_id)) status.report = {};
204
+ if (args[0] === '--json') console.log(JSON.stringify({ version, gateway, wsOrigin: device?.ws_origin ?? '', paired: Boolean(device),
205
+ device: device?.device_key ?? '', ...status }));
206
+ else console.log('版本:' + version + '\n网关:' + gateway + '\n设备配对:' + (device ? '已配对(本机已保存凭据)' : '未配对')
207
+ + (desktop ? '\n后台:' + (status.running ? '运行中' : '已停止') + '\n网关连接:' + (status.connected ? '已连接' : '未连接')
208
+ + '\n当前任务:' + (status.task || '空闲') + '\n最近回传:' + (status.report.lastResult?.status || '暂无')
209
+ + '\n开机启动:' + (status.autostart ? '开启' : '关闭') + '\n自动更新:' + (status.autoUpdate ? '开启' : '关闭')
210
+ + (status.updateMessage ? '\n更新:' + status.updateMessage : '') : ''));
101
211
  } else {
102
212
  throw new Error('命令或参数无效。请运行 easy-agents --help');
103
213
  }
@@ -0,0 +1,149 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { join } from 'node:path';
6
+
7
+ export const toolNames = ['codex', 'claude_code', 'cursor', 'antigravity'];
8
+ export const macResources = process.env.EASYAGENTS_MAC_RESOURCES || process.env.EASYAGENTS_DESKTOP_RESOURCES;
9
+
10
+ export function readSnapshot(folder, file) {
11
+ try { return JSON.parse(readFileSync(join(folder, file), 'utf8')); }
12
+ catch (err) { if (err.code === 'ENOENT') return null; throw err; }
13
+ }
14
+
15
+ export function writeSnapshot(folder, file, value) {
16
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
17
+ const temp = join(folder, '.' + randomUUID() + '.tmp');
18
+ writeFileSync(temp, JSON.stringify(value), { mode: 0o600, flag: 'wx' });
19
+ renameSync(temp, join(folder, file));
20
+ }
21
+
22
+ export function terminalEnabled(folder) {
23
+ return readSnapshot(folder, 'mac-terminal.json')?.enabled !== false;
24
+ }
25
+
26
+ function helper(folder, mode, input, signal) {
27
+ return new Promise((resolve, reject) => {
28
+ const python = process.platform === 'win32' ? join(macResources, 'python/python.exe')
29
+ : process.platform === 'darwin' ? join(macResources, 'python/bin/python3') : 'python3';
30
+ const proc = execFile(python, ['-I', '-B', '-X', 'utf8', join(macResources, 'accounts.py'), mode],
31
+ { cwd: homedir(), env: { ...process.env, EASYAGENTS_CONFIG_DIR: folder }, timeout: 45000,
32
+ windowsHide: true, maxBuffer: 512 * 1024, signal }, (err, stdout) => {
33
+ if (err) { reject(new Error('无法读取本机工具状态')); return; }
34
+ try { resolve(JSON.parse(stdout)); } catch { reject(new Error('工具状态格式无效')); }
35
+ });
36
+ proc.stdin.on('error', () => {});
37
+ proc.stdin.end(JSON.stringify(input ?? {}));
38
+ });
39
+ }
40
+
41
+ export async function inventory(folder, signal) {
42
+ const data = await helper(folder, 'inventory', undefined, signal);
43
+ const detected = toolNames.filter(tool => data.accounts[tool]?.login !== 'missing');
44
+ const logins = {};
45
+ for (const tool of detected) {
46
+ const { login, email, plan } = data.accounts[tool];
47
+ if (login === 'yes') logins[tool] = { email, plan };
48
+ }
49
+ return { accounts: data.accounts, hello: { timezone: data.timezone, quota_tools: detected, logins } };
50
+ }
51
+
52
+ async function readQuota(folder, tool, model, account, signal) {
53
+ return helper(folder, 'quota', { tool, model, identity: [account?.login, account?.email, account?.plan] }, signal);
54
+ }
55
+
56
+ export async function localAccounts(folder) {
57
+ const { accounts, hello } = await inventory(folder);
58
+ await Promise.all(hello.quota_tools.map(async tool => {
59
+ const row = accounts[tool];
60
+ if (row.login === 'no') return;
61
+ row.quota = await readQuota(folder, tool, null, row).catch(() => ({ status: 'error', failure_code: 'unknown' }));
62
+ if (row.login === 'unknown' && row.quota.status === 'ok') row.login = 'yes';
63
+ }));
64
+ return { accounts, timezone: hello.timezone };
65
+ }
66
+
67
+ export function macReporter(folder, read = inventory, usage = readQuota, models = signal => helper(folder, 'models', null, signal)) {
68
+ let current, state = {}, timer, refreshing = false, generation;
69
+ const subscriptions = new Map();
70
+ const patch = fields => {
71
+ if (!state.pid && fields.deviceId) {
72
+ const previous = readSnapshot(folder, 'mac-worker.json');
73
+ if (previous?.gateway === fields.gateway && previous?.deviceId === fields.deviceId && previous.lastResult) {
74
+ state.lastResult = previous.lastResult;
75
+ }
76
+ }
77
+ Object.assign(state, fields, { pid: process.pid, updated: Date.now() });
78
+ writeSnapshot(folder, 'mac-worker.json', state);
79
+ };
80
+ function disconnect() {
81
+ clearInterval(timer);
82
+ generation?.abort();
83
+ for (const job of subscriptions.values()) { clearTimeout(job.timer); job.controller.abort(); }
84
+ subscriptions.clear();
85
+ patch({ connected: false });
86
+ }
87
+ function configure(setting, post) {
88
+ const id = setting?.agent_id;
89
+ if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(id)) return;
90
+ const before = subscriptions.get(id);
91
+ if (before) { clearTimeout(before.timer); before.controller.abort(); subscriptions.delete(id); }
92
+ if (setting.enabled !== true || !Number.isInteger(setting.interval_seconds) ||
93
+ setting.interval_seconds < 60 || setting.interval_seconds > 3600) {
94
+ state.reports[id] = { tool: toolNames.includes(setting.tool_type) ? setting.tool_type : 'unknown',
95
+ delivery: setting.enabled === true ? 'invalid' : 'disabled' };
96
+ patch({ reports: state.reports }); return;
97
+ }
98
+ const tool = setting.tool_type;
99
+ const job = { controller: new AbortController() };
100
+ subscriptions.set(id, job);
101
+ state.reports[id] = { tool: toolNames.includes(tool) ? tool : 'unknown', delivery: 'pending' };
102
+ patch({ reports: state.reports });
103
+ async function send() {
104
+ const { signal } = job.controller;
105
+ let body;
106
+ try {
107
+ body = toolNames.includes(tool)
108
+ ? await usage(folder, tool, setting.default_model, current.accounts[tool], signal)
109
+ : { status: 'unavailable', failure_code: 'unsupported', reported_at: new Date().toISOString() };
110
+ if (signal.aborted) return;
111
+ if (current.accounts[tool]?.plan && !body.plan) body = { ...body, plan: current.accounts[tool].plan };
112
+ await post(id, body, signal);
113
+ if (!signal.aborted) state.reports[id] = { tool, delivery: 'accepted', at: Date.now(), body };
114
+ } catch {
115
+ if (!signal.aborted) state.reports[id] = { tool, delivery: 'failed', at: Date.now(), body };
116
+ } finally {
117
+ if (!signal.aborted) {
118
+ patch({ reports: state.reports });
119
+ job.timer = setTimeout(send, setting.interval_seconds * 1000);
120
+ }
121
+ }
122
+ }
123
+ void send();
124
+ }
125
+ return {
126
+ patch, configure, disconnect, terminalEnabled: () => terminalEnabled(folder),
127
+ async hello(signal) {
128
+ generation = new AbortController();
129
+ const joined = AbortSignal.any([generation.signal, signal]);
130
+ const [found, available_models] = await Promise.all([read(folder, joined), models(joined)]);
131
+ current = found;
132
+ return { ...found.hello, available_models };
133
+ },
134
+ welcome(hello, msg, post, reconnect) {
135
+ patch({ connected: true, accepted: Date.now(), hello, reports: {}, deviceId: msg.device_id });
136
+ for (const setting of msg.quota_settings ?? []) configure(setting, post);
137
+ const controller = generation;
138
+ timer = setInterval(async () => {
139
+ if (refreshing || controller.signal.aborted) return;
140
+ refreshing = true;
141
+ try {
142
+ const fresh = await read(folder, controller.signal);
143
+ if (!controller.signal.aborted && JSON.stringify(fresh.hello) !== JSON.stringify(current.hello)) reconnect();
144
+ } catch { /* Retry the inventory on the next tick. */ }
145
+ finally { refreshing = false; }
146
+ }, 60000);
147
+ }
148
+ };
149
+ }
@@ -0,0 +1,119 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, mkdirSync, openSync, closeSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { homedir, userInfo } from 'node:os';
5
+ import { dirname, join } from 'node:path';
6
+ import { setTimeout as sleep } from 'node:timers/promises';
7
+ import { macResources, readSnapshot, terminalEnabled } from './mac-reports.js';
8
+
9
+ const xml = s => s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
10
+ const label = folder => 'com.unionschool.easyagents.mac.' + createHash('sha256').update(folder).digest('hex').slice(0, 12);
11
+ const domain = 'gui/' + process.getuid();
12
+ const service = folder => domain + '/' + label(folder);
13
+ const bootLabel = folder => label(folder) + '.boot';
14
+ const bootFile = folder => '/Library/LaunchDaemons/' + bootLabel(folder) + '.plist';
15
+ export const bootEnabled = folder => existsSync(bootFile(folder));
16
+ const launcher = () => join(macResources, 'easy-agents');
17
+ const launch = (...args) => execFileSync('/bin/launchctl', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10000 });
18
+
19
+ function lookup(name) {
20
+ try {
21
+ const description = launch('print', name);
22
+ return { loaded: true, pid: Number(description.match(/^\s*pid = (\d+)$/m)?.[1] || 0), name };
23
+ } catch { return { loaded: false, pid: 0 }; }
24
+ }
25
+
26
+ function job(folder) {
27
+ const system = lookup('system/' + bootLabel(folder));
28
+ if (system.pid) return system;
29
+ const gui = lookup(service(folder));
30
+ if (gui.pid || !existsSync(join(folder,'mac-worker.lock'))) return gui;
31
+ const owner = execFileSync(join(macResources,'python/bin/python3'),['-I','-B',join(macResources,'worker.py'),'status'],
32
+ { encoding:'utf8', env:{ ...process.env, EASYAGENTS_CONFIG_DIR:folder }, timeout:3000 }).trim();
33
+ return /^[1-9]\d*$/.test(owner) ? { loaded: true, name:'foreground', pid:Number(owner) } : gui;
34
+ }
35
+
36
+ const plist = body => '<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>' + body + '</dict></plist>';
37
+ const str = value => '<string>' + xml(value) + '</string>';
38
+ const entry = (key, value) => '<key>' + key + '</key>' + value;
39
+
40
+ export function bootPlist(folder, resource, user, home) {
41
+ if (!user || user === 'root') throw new Error('请选择普通用户作为设备运行账户');
42
+ return plist(entry('Label',str(bootLabel(folder))) + entry('UserName',str(user))
43
+ + entry('ProgramArguments','<array>' + str(join(resource,'easy-agents')) + str('run') + '</array>')
44
+ + entry('EnvironmentVariables','<dict>' + entry('HOME',str(home)) + entry('EASYAGENTS_CONFIG_DIR',str(folder)) + entry('EASYAGENTS_BOOT_LOG',str('1')) + '</dict>')
45
+ + entry('WorkingDirectory',str(home)) + entry('RunAtLoad','<true/>') + entry('ThrottleInterval','<integer>30</integer>')
46
+ + entry('KeepAlive','<dict><key>SuccessfulExit</key><false/></dict>'));
47
+ }
48
+
49
+ export async function autostart(folder, enabled) {
50
+ const name = bootLabel(folder), target = bootFile(folder);
51
+ const agent = join(homedir(),'Library/LaunchAgents',name + '.panel.plist');
52
+ if (enabled && !bootEnabled(folder)) {
53
+ const data = Buffer.from(bootPlist(folder, macResources, userInfo().username, homedir())).toString('base64');
54
+ // The root shell receives only base64 and a hash-derived system path. The job runs as its owner.
55
+ const cmd = 'set -eu; t=$(/usr/bin/mktemp /Library/LaunchDaemons/.' + name + '.XXXXXX); '
56
+ + 'trap \'/bin/rm -f "$t"\' EXIT; /bin/echo ' + data + ' | /usr/bin/base64 -D > "$t"; /usr/bin/plutil -lint "$t" >/dev/null; '
57
+ + '/usr/sbin/chown root:wheel "$t"; /bin/chmod 644 "$t"; /bin/mv -f "$t" ' + target;
58
+ admin(cmd);
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});
68
+ }
69
+
70
+ function admin(command) {
71
+ const script = 'do shell script ' + JSON.stringify(command) + ' with administrator privileges';
72
+ try { execFileSync('/usr/bin/osascript',['-e',script], {stdio:'pipe'}); }
73
+ catch { throw new Error('系统未保存开机启动设置,请检查 Mac 管理员授权'); }
74
+ }
75
+
76
+ export function desktopStatus(folder) {
77
+ const { pid } = job(folder);
78
+ const saved = readSnapshot(folder, 'mac-worker.json');
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),
81
+ report: saved || {}, task: fresh ? saved.task : null };
82
+ }
83
+
84
+ export async function serviceCommand(command, folder) {
85
+ const bundle = dirname(dirname(macResources));
86
+ if (command === 'show') { execFileSync('/usr/bin/open', [bundle]); return; }
87
+ const log = join(folder, 'worker.log');
88
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
89
+ if (command === 'logs') {
90
+ closeSync(openSync(log, 'a', 0o600));
91
+ execFileSync('/usr/bin/open', ['-t', log]); return;
92
+ }
93
+ let current = job(folder);
94
+ if (current.pid && (command === 'stop' || command === 'restart')) {
95
+ if (current.name === service(folder)) launch('kill', 'SIGUSR2', service(folder));
96
+ else process.kill(current.pid, 'SIGUSR2');
97
+ while (job(folder).pid === current.pid) await sleep(250);
98
+ current = job(folder);
99
+ }
100
+ if (command === 'stop') return;
101
+ if (current.pid) return;
102
+ if (!current.loaded) {
103
+ const file = join(folder, 'mac-worker.plist');
104
+ const env = { EASYAGENTS_CONFIG_DIR: folder };
105
+ for (const key of ['EASYAGENTS_WS_ORIGIN', 'EASYAGENTS_WORKSPACE', 'EASYAGENTS_TERMINAL']) {
106
+ if (process.env[key]) env[key] = process.env[key];
107
+ }
108
+ const values = Object.entries(env).map(([k,v]) => '<key>' + k + '</key><string>' + xml(v) + '</string>').join('');
109
+ closeSync(openSync(log, 'a', 0o600));
110
+ writeFileSync(file, '<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>'
111
+ + '<key>Label</key><string>' + label(folder) + '</string><key>ProgramArguments</key><array><string>' + xml(launcher())
112
+ + '</string><string>run</string></array><key>EnvironmentVariables</key><dict>' + values + '</dict>'
113
+ + '<key>WorkingDirectory</key><string>' + xml(homedir()) + '</string><key>RunAtLoad</key><true/>'
114
+ + '<key>StandardOutPath</key><string>' + xml(log) + '</string><key>StandardErrorPath</key><string>'
115
+ + xml(log) + '</string></dict></plist>', { mode: 0o600 });
116
+ try { launch('bootstrap', domain, file); }
117
+ catch { if (!job(folder).loaded) throw new Error('无法启动本机后台,请检查 launchd 日志'); }
118
+ } else { launch('kickstart', service(folder)); }
119
+ }