@unionschool/easy-agents 1.0.51 → 1.0.53

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
@@ -73,7 +73,7 @@ npm exec --offline -- easy-agents run
73
73
  | `easy-agents status --json`、`logs`、`doctor` | 查看连接、运行记录或本机工具状态 |
74
74
  | `easy-agents autostart on` / `off` | 切换开机启动。系统可能要求管理员授权 |
75
75
  | `easy-agents update`、`auto-update on` / `off` | 检查兼容的 npm 稳定版核心或切换自动检查。重连验证失败会回退,原生面板和内置解释器通过安装包升级 |
76
- | `easy-agents terminal on` / `off` | 在支持的 Unix 设备上切换工作台网页终端 |
76
+ | `easy-agents terminal on` / `off` | 在支持的设备上切换工作台网页终端 |
77
77
  | `easy-agents agent-credential <Agent编号>` | 为本机设备上的 Agent 检查平台凭据,缺失或被撤销(401)时领取新凭据(旧凭据随之作废),只输出凭据文件路径。负责人在本机用 `skills/easyagents-task/register.py` 登记任务前用它 |
78
78
 
79
79
  ## 已安装设备怎么升级
@@ -88,9 +88,10 @@ npm exec --offline -- easy-agents run
88
88
 
89
89
  - Mac 和 Ubuntu 安装包能接平台任务分支上的执行、审核、部署和澄清运行(Codex、Claude、Cursor、Agy,1.0.50 起含 Cursor、Agy;完整权限,与旧 Python 客户端的规则一致):执行在任务分支上工作并在成功后推送;审核和部署检出本轮交付的提交;工作目录有未提交改动时,在客户端配置目录的 `worktrees/` 里另建工作树,原目录不动,合并后的成员同步会清理这些工作树。Agent 通过提示里给出的平台命令调用工具;Agent 凭据缺失或已被平台撤销时,客户端自动领取新凭据(平台会同时撤销旧凭据)。旧的同目录文件交付和用户发布命令(`publish`)不支持。工作台读取任务、需求文档(“阅读”抽屉)也由这两种设备应答,只读 Git,不切分支、不改工作区。
90
90
  - **未完成**:Windows、Android 和单独运行的普通 npm 版还不能接任务分支运行,会回报 `handoff_unsupported`。这几端暂时用不上(用户 2026-11-22 定),以后需要时再单独升级。
91
- - Mac 和 Ubuntu 安装包支持 Codex、Claude、Cursor、Agy 的文本对话与续聊,Codex、Claude 还支持本地文本任务。客户端上线时按工具上报能否接任务分支运行,平台据此派发;1.0.49 及更早的客户端不接 Cursor、Agy 的任务运行,平台会把派给它们的任务运行留在排队。Cursor、Agy 在 Ubuntu 上的任务运行尚未实测。它们可从项目卡片或对话页接收聊天和工作消息。普通聊天是纯文本:Codex 只读会话、Claude 不开工具。工作消息(负责人与任务角色的对话、平台的流程通知)与任务运行一样用完整权限,带平台操作入口,Agent 凭据缺失或被撤销时自动领取,所以负责人能在对话里登记需求、发布任务、合并上报。可用的会话编号、模型与用量会随结果回传。
91
+ - Mac、Ubuntu 和 Windows 安装包(Windows 1.0.53 起)支持 Codex、Claude、Cursor、Agy 的文本对话与续聊(Windows 暂不接任务分支运行和成员同步),Codex、Claude 还支持本地文本任务。客户端上线时按工具上报能否接任务分支运行,平台据此派发;1.0.49 及更早的客户端不接 Cursor、Agy 的任务运行,平台会把派给它们的任务运行留在排队。Cursor、Agy 在 Ubuntu 上的任务运行尚未实测。它们可从项目卡片或对话页接收聊天和工作消息。普通聊天是纯文本:Codex 只读会话、Claude 不开工具。工作消息(负责人与任务角色的对话、平台的流程通知)与任务运行一样用完整权限,带平台操作入口,Agent 凭据缺失或被撤销时自动领取,所以负责人能在对话里登记需求、发布任务、合并上报。可用的会话编号、模型与用量会随结果回传。
92
92
  - Mac 和 Windows 面板可显示检测到的 Codex、Claude、Cursor、Agy 登录和上报状态。平台控制额度上报开关,绿色胶囊显示已获得的剩余额度,测得零时显示零。Windows 和单独运行的普通 npm 版支持单次 Claude 文本任务,使用 bare 模式可用的认证。Mac、Linux 上的普通 npm 版还接 Codex、Agy、Cursor 的聊天模式(1.0.51 起),用本机 `python3`(3.10 及以上)运行对话,需在本机装好并登录对应工具;工作模式和任务运行仍需安装包。桌面对话功能需要安装包提供的工具适配和内置运行环境。
93
93
  - 在支持的 Unix 主机上,网页终端使用本机运行用户进行 SSH 登录,需要 Python 3、OpenSSH、可读的本机 SSH 公钥和监听回环端口 22 的 SSH 服务。可在工作台的「AI → 设备管理 → 终端」打开。普通 npm 可在启动前用 `EASYAGENTS_TERMINAL=0` 关闭。
94
+ - Windows 安装包(1.0.53 起)的网页终端同样是登录本机账号:用系统自带的 OpenSSH 客户端连 127.0.0.1,外面套 Windows 伪终端(ConPTY,Windows 10 1809 及以上)。需先用管理员身份开启「OpenSSH 服务器」:PowerShell 运行 `Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0`,再 `Start-Service sshd` 并 `Set-Service sshd -StartupType Automatic`;登录时输入 Windows 账号的密码(微软账号用账号密码,不是 PIN)。没开 sshd 时设备不报告终端能力,工作台不显示可用。普通 npm 版的 Windows 不开终端。
94
95
  - Node 核心支持 `/sha256 <文本>`、本地 Markdown 文档里的同类计算和成员同步。文档与同步的目录需与本机选定工作目录相符,可用 `EASYAGENTS_WORKSPACE` 指定。成员同步使用包内实现、系统 Git 和 Python 3.10+,更新已有检出目录。Android 首版可执行 SHA-256 消息和用户选择目录里的计算文档。
95
96
  - 客户端保存待回传结果,重连后补传。独立版尚未接入运行中 `/steer`、手动 `/sync`、平台远程读文档和编辑设备上的工具规则。
96
97
 
@@ -22,7 +22,9 @@ export function findAgentCredential(configDir, id) {
22
22
  for (const path of files) {
23
23
  try {
24
24
  const info = lstatSync(path);
25
- if (!info.isFile() || info.uid !== process.getuid() || (info.mode & 0o077)) throw new Error('Agent 凭据文件无效');
25
+ // Windows 没有属主 uid 与权限位(process.getuid 不存在);文件写入时已由 protectDeviceFile 用 icacls 限制为仅本人(2026-11-28)。
26
+ const owned = process.platform === 'win32' || (info.uid === process.getuid() && !(info.mode & 0o077));
27
+ if (!info.isFile() || !owned) throw new Error('Agent 凭据文件无效');
26
28
  return path;
27
29
  } catch (err) { if (err.code !== 'ENOENT') throw err; }
28
30
  }
package/bin/tasks.js CHANGED
@@ -16,6 +16,10 @@ function invoke(file, args, cwd, input, signal, timeout) {
16
16
 
17
17
  // 对话桥:首行 JSON 是运行内容,之后 stdin 保持打开,运行中补充(/steer)按行写入;
18
18
  // 子进程从 fd 3 逐行回执 {"message_id","status"},stdout 只放最终结果。
19
+ // 安装包自带的 Python:Windows 是 python\python.exe(嵌入版),macOS、Ubuntu 是 python/bin/python3。
20
+ const bundledPython = resources => process.platform === 'win32'
21
+ ? join(resources, 'python', 'python.exe') : join(resources, 'python/bin/python3');
22
+
19
23
  // resources 为空时是普通 npm 版的聊天(用户 2026-11-27):用本机 python3 跑同一个对话桥,适配器只依赖标准库。
20
24
  function desktopConversation(resources, content, prompt, signal, credential, tools = false, onSteer) {
21
25
  const bridge = fileURLToPath(new URL('../runtime/desktop_chat.py', import.meta.url));
@@ -25,7 +29,7 @@ function desktopConversation(resources, content, prompt, signal, credential, too
25
29
  resume: content.resume_session_ref, workspace: content.workspace?.local_path, timeout,
26
30
  workRunId: content.chat_mode !== 'chat' ? content.run_id : undefined, passthrough: content.passthrough === true, credential, tools };
27
31
  return new Promise(resolveResult => {
28
- const python = resources ? join(resources, 'python/bin/python3') : 'python3';
32
+ const python = resources ? bundledPython(resources) : 'python3';
29
33
  const child = spawn(python, ['-I', '-B', '-X', 'utf8', bridge],
30
34
  { stdio: ['pipe', 'pipe', 'ignore', 'pipe'], windowsHide: true });
31
35
  const waiting = new Map();
@@ -104,7 +108,7 @@ function desktopTask(resources, content, signal, options) {
104
108
  const input = { content, timeout, credential: options.credential, worktrees: join(options.configDir, 'worktrees') };
105
109
  const onSteer = options.onSteer;
106
110
  return new Promise(resolveResult => {
107
- const child = spawn(join(resources, 'python/bin/python3'), ['-I', '-B', '-X', 'utf8', runner],
111
+ const child = spawn(bundledPython(resources), ['-I', '-B', '-X', 'utf8', runner],
108
112
  { stdio: ['pipe', 'pipe', 'ignore', 'pipe'], windowsHide: true });
109
113
  const waiting = new Map();
110
114
  let stdout = '', size = 0, settled = false, acks = '';
@@ -182,7 +186,7 @@ async function sync(content, signal, resources) {
182
186
  }
183
187
  const script = fileURLToPath(new URL('../runtime/sync.py', import.meta.url));
184
188
  try {
185
- const python = resources ? join(resources, 'python/bin/python3') : process.platform === 'win32' ? 'python' : 'python3';
189
+ const python = resources ? bundledPython(resources) : process.platform === 'win32' ? 'python' : 'python3';
186
190
  const result = await invoke(python, ['-I', '-S', '-B', script], directory, JSON.stringify(content), signal, 600000);
187
191
  return JSON.parse(result);
188
192
  } catch (error) {
@@ -193,8 +197,9 @@ async function sync(content, signal, resources) {
193
197
 
194
198
  export async function execute(content, signal, workCredential, { agentCredential, configDir, onSteer } = {}) {
195
199
  signal.throwIfAborted();
196
- const resources = process.platform === 'darwin' ? process.env.EASYAGENTS_MAC_RESOURCES
197
- : process.platform === 'linux' ? process.env.EASYAGENTS_DESKTOP_RESOURCES : undefined;
200
+ // Windows 安装包(2026-11-28)先只开对话(聊天、工作模式):任务分支运行、成员同步还没在 Windows 实测,仍按“不支持”处理。
201
+ const desktop = process.platform === 'darwin' ? process.env.EASYAGENTS_MAC_RESOURCES : process.env.EASYAGENTS_DESKTOP_RESOURCES;
202
+ const resources = process.platform === 'win32' ? undefined : desktop;
198
203
  if (content.run_kind === 'sync') return sync(content, signal, resources);
199
204
  const versioned = content.task && (content.task.git_delivery || content.task.file_delivery || content.task.document_commit_sha);
200
205
  if (TASK_KINDS.includes(content.run_kind) && (versioned || content.run_kind !== 'execute')) {
@@ -232,7 +237,7 @@ export async function execute(content, signal, workCredential, { agentCredential
232
237
  return { status: 'succeeded', reply_text: digest };
233
238
  }
234
239
  if (task && content.prompt) prompt = content.prompt + '\n\n' + prompt;
235
- if (resources && DESKTOP_TASK_TOOLS.includes(content.agent?.tool_type) && (task || content.run_kind === 'chat')) {
240
+ if (desktop && DESKTOP_TASK_TOOLS.includes(content.agent?.tool_type) && (task || content.run_kind === 'chat')) {
236
241
  let credential;
237
242
  // Same rule as the platform: only chat_mode 'chat' is a plain conversation. Workflow notifications to the lead
238
243
  // (merge after deploy, answers, sync handoff) arrive with an empty chat_mode and must be able to act.
@@ -248,9 +253,9 @@ export async function execute(content, signal, workCredential, { agentCredential
248
253
  credential = null;
249
254
  }
250
255
  }
251
- return desktopConversation(resources, content, prompt, signal, credential, workMode, onSteer);
256
+ return desktopConversation(desktop, content, prompt, signal, credential, workMode, onSteer);
252
257
  }
253
- if (!resources && process.platform !== 'win32' && !task && content.run_kind === 'chat' && content.chat_mode === 'chat'
258
+ if (!desktop && process.platform !== 'win32' && !task && content.run_kind === 'chat' && content.chat_mode === 'chat'
254
259
  && NPM_CHAT_TOOLS.includes(content.agent?.tool_type)) {
255
260
  return desktopConversation(null, content, prompt, signal, null, false, onSteer);
256
261
  }
package/bin/terminal.js CHANGED
@@ -1,15 +1,48 @@
1
1
  import { spawn, spawnSync } from 'node:child_process';
2
+ import { join } from 'node:path';
2
3
  import { fileURLToPath } from 'node:url';
3
4
  import WebSocket from 'ws';
4
5
 
5
- const script = fileURLToPath(new URL('../runtime/ssh_terminal.py', import.meta.url));
6
- const args = ['-I', '-S', '-B', script];
7
6
  const uuid = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
8
7
  const dimension = n => Number.isInteger(n) && n >= 1 && n <= 1000;
9
8
 
9
+ // macOS and Linux: system python3 runs ssh_terminal.py on a PTY, resize goes through an extra pipe (fd 3).
10
+ // Windows (installer only, 2026-11-28): the bundled Python runs conpty_terminal.py on a ConPTY; Windows children
11
+ // cannot read extra pipes, so keyboard input and resize share stdin as frames (see that script).
12
+ export function terminalCommand(platform = process.platform, resources = process.env.EASYAGENTS_DESKTOP_RESOURCES) {
13
+ if (platform === 'win32') {
14
+ if (!resources) return null;
15
+ const script = fileURLToPath(new URL('../runtime/conpty_terminal.py', import.meta.url));
16
+ return { file: join(resources, 'python', 'python.exe'), args: ['-I', '-S', '-B', script], framed: true };
17
+ }
18
+ const script = fileURLToPath(new URL('../runtime/ssh_terminal.py', import.meta.url));
19
+ return { file: 'python3', args: ['-I', '-S', '-B', script], framed: false };
20
+ }
21
+
22
+ export function inputFrames(data) {
23
+ const frames = [];
24
+ for (let at = 0; at < data.length; at += 32768) {
25
+ const body = data.subarray(at, at + 32768), head = Buffer.alloc(3);
26
+ head[0] = 0;
27
+ head.writeUInt16BE(body.length, 1);
28
+ frames.push(head, body);
29
+ }
30
+ return Buffer.concat(frames);
31
+ }
32
+
33
+ export function resizeFrame(cols, rows) {
34
+ const frame = Buffer.alloc(5);
35
+ frame[0] = 1;
36
+ frame.writeUInt16BE(cols, 1);
37
+ frame.writeUInt16BE(rows, 3);
38
+ return frame;
39
+ }
40
+
41
+ // 10 秒:Windows 装完第一次跑内置 Python 会被杀毒扫描拖慢;Windows 还可能向本机 sshd 要公钥(见 conpty_terminal.py)。
10
42
  export function terminalAvailable() {
11
- return process.env.EASYAGENTS_TERMINAL !== '0' && process.platform !== 'win32' &&
12
- spawnSync('python3', [...args, '--check'], { timeout: 3000, stdio: 'ignore' }).status === 0;
43
+ const command = terminalCommand();
44
+ return process.env.EASYAGENTS_TERMINAL !== '0' && Boolean(command) &&
45
+ spawnSync(command.file, [...command.args, '--check'], { timeout: 10000, stdio: 'ignore', windowsHide: true }).status === 0;
13
46
  }
14
47
 
15
48
  export function openTerminal(origin, headers, id, sessions) {
@@ -17,7 +50,7 @@ export function openTerminal(origin, headers, id, sessions) {
17
50
  const ws = new WebSocket(new URL('/ws/client/terminal/' + id, origin),
18
51
  { headers, handshakeTimeout: 10000, followRedirects: false, maxPayload: 65536 });
19
52
  sessions.set(id, ws);
20
- let child;
53
+ let child, framed = false;
21
54
  let lastSeen = Date.now();
22
55
  const close = () => ws.terminate();
23
56
  const idle = setInterval(() => { if (Date.now() - lastSeen > 90000) close(); }, 10000);
@@ -31,7 +64,7 @@ export function openTerminal(origin, headers, id, sessions) {
31
64
  lastSeen = Date.now();
32
65
  if (binary) {
33
66
  if (!child || child.stdin.writableLength > 262144) return close();
34
- child.stdin.write(raw);
67
+ child.stdin.write(framed ? inputFrames(raw) : raw);
35
68
  return;
36
69
  }
37
70
  try {
@@ -40,12 +73,15 @@ export function openTerminal(origin, headers, id, sessions) {
40
73
  if (msg.type === 'close') return ws.close();
41
74
  if (!dimension(msg.cols) || !dimension(msg.rows)) return close();
42
75
  if (msg.type === 'start' && !child) {
43
- child = spawn('python3', [...args, String(msg.cols), String(msg.rows)], {
44
- stdio: ['pipe', 'pipe', 'ignore', 'pipe'],
76
+ const command = terminalCommand();
77
+ if (!command) return close();
78
+ framed = command.framed;
79
+ child = spawn(command.file, [...command.args, String(msg.cols), String(msg.rows)], {
80
+ stdio: framed ? ['pipe', 'pipe', 'ignore'] : ['pipe', 'pipe', 'ignore', 'pipe'], windowsHide: true,
45
81
  });
46
82
  child.on('error', close);
47
83
  child.stdin.on('error', close);
48
- child.stdio[3].on('error', close);
84
+ child.stdio[3]?.on('error', close);
49
85
  child.stdout.on('data', chunk => {
50
86
  if (ws.readyState !== WebSocket.OPEN) return;
51
87
  child.stdout.pause();
@@ -54,6 +90,9 @@ export function openTerminal(origin, headers, id, sessions) {
54
90
  child.once('close', code => {
55
91
  if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'exit', code: code ?? 1 }), () => ws.close());
56
92
  });
93
+ } else if (msg.type === 'resize' && child && framed) {
94
+ if (child.stdin.writableLength > 262144) return close();
95
+ child.stdin.write(resizeFrame(msg.cols, msg.rows));
57
96
  } else if (msg.type === 'resize' && child) {
58
97
  if (child.stdio[3].writableLength > 4096) return close();
59
98
  const size = Buffer.alloc(4);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unionschool/easy-agents",
3
- "version": "1.0.51",
3
+ "version": "1.0.53",
4
4
  "description": "EasyAgents",
5
5
  "easyAgentsDesktop": 1,
6
6
  "type": "module",
@@ -19,6 +19,7 @@
19
19
  "bin/portable-service.js",
20
20
  "runtime/sync.py",
21
21
  "runtime/ssh_terminal.py",
22
+ "runtime/conpty_terminal.py",
22
23
  "runtime/desktop_chat.py",
23
24
  "runtime/task_run.py",
24
25
  "runtime/doc_read.py",
@@ -0,0 +1,341 @@
1
+ """Windows: present the local SSH login on a pseudo console (ConPTY). The operating system authenticates the user.
2
+
3
+ Same rule as ssh_terminal.py on macOS and Linux: the web terminal never opens a shell directly; it runs the
4
+ system OpenSSH client against 127.0.0.1 with password login only, so having the platform account is not enough to
5
+ get a command line on this computer. Needs the Windows "OpenSSH Server" optional feature (sshd listening on port 22).
6
+
7
+ stdin carries frames from bin/terminal.js, because extra pipes are not portable to Windows children:
8
+ 0x00 + length (uint16 BE) + bytes keyboard input
9
+ 0x01 + cols (uint16 BE) + rows (uint16 BE) resize
10
+ stdout carries the raw terminal output.
11
+ """
12
+ import os
13
+ import socket
14
+ import struct
15
+ import sys
16
+ import tempfile
17
+ import threading
18
+ from contextlib import suppress
19
+ from pathlib import Path, PureWindowsPath
20
+
21
+ INPUT, RESIZE = 0, 1
22
+
23
+
24
+ def read_exact(stream, size):
25
+ data = b''
26
+ while len(data) < size:
27
+ chunk = stream.read(size - len(data))
28
+ if not chunk:
29
+ return None
30
+ data += chunk
31
+ return data
32
+
33
+
34
+ def frames(stream):
35
+ """Yield ('input', bytes) and ('resize', (cols, rows)) until EOF; stop on a malformed frame."""
36
+ while True:
37
+ kind = read_exact(stream, 1)
38
+ if kind is None:
39
+ return
40
+ if kind[0] == INPUT:
41
+ head = read_exact(stream, 2)
42
+ if head is None:
43
+ return
44
+ body = read_exact(stream, struct.unpack('!H', head)[0])
45
+ if body is None:
46
+ return
47
+ yield 'input', body
48
+ elif kind[0] == RESIZE:
49
+ body = read_exact(stream, 4)
50
+ if body is None:
51
+ return
52
+ cols, rows = struct.unpack('!HH', body)
53
+ if 1 <= cols <= 1000 and 1 <= rows <= 1000:
54
+ yield 'resize', (cols, rows)
55
+ else:
56
+ return
57
+
58
+
59
+ def known_hosts(directory):
60
+ lines = []
61
+ for path in sorted(Path(directory).glob('ssh_host_*_key.pub')):
62
+ with suppress(OSError):
63
+ fields = path.read_text().split()
64
+ if len(fields) >= 2:
65
+ lines.append('127.0.0.1 ' + ' '.join(fields[:2]))
66
+ return '\n'.join(lines) + '\n' if lines else ''
67
+
68
+
69
+ def parse_keyscan(text):
70
+ """ssh-keyscan 输出(“主机 类型 公钥”,# 开头是注释)转成 known_hosts 行。"""
71
+ lines = []
72
+ for line in text.splitlines():
73
+ fields = line.split()
74
+ if len(fields) >= 3 and not line.startswith('#') and fields[0] == '127.0.0.1':
75
+ lines.append(' '.join(fields[:3]))
76
+ return '\n'.join(lines) + '\n' if lines else ''
77
+
78
+
79
+ def sshd_pid():
80
+ """sshd 服务的进程号;服务没在跑或查不到返回 0。普通用户有查询服务状态的权限。"""
81
+ import ctypes
82
+ from ctypes import wintypes as w
83
+
84
+ class SERVICE_STATUS_PROCESS(ctypes.Structure):
85
+ _fields_ = [(name, w.DWORD) for name in ('dwServiceType', 'dwCurrentState', 'dwControlsAccepted',
86
+ 'dwWin32ExitCode', 'dwServiceSpecificExitCode', 'dwCheckPoint',
87
+ 'dwWaitHint', 'dwProcessId', 'dwServiceFlags')]
88
+
89
+ advapi = ctypes.WinDLL('advapi32', use_last_error=True)
90
+ advapi.OpenSCManagerW.restype = w.HANDLE
91
+ advapi.OpenServiceW.restype = w.HANDLE
92
+ advapi.OpenSCManagerW.argtypes = [w.LPCWSTR, w.LPCWSTR, w.DWORD]
93
+ advapi.OpenServiceW.argtypes = [w.HANDLE, w.LPCWSTR, w.DWORD]
94
+ advapi.QueryServiceStatusEx.argtypes = [w.HANDLE, ctypes.c_int, ctypes.c_void_p, w.DWORD, ctypes.POINTER(w.DWORD)]
95
+ advapi.CloseServiceHandle.argtypes = [w.HANDLE]
96
+ manager = advapi.OpenSCManagerW(None, None, 0x0001) # SC_MANAGER_CONNECT
97
+ if not manager:
98
+ return 0
99
+ try:
100
+ service = advapi.OpenServiceW(manager, 'sshd', 0x0004) # SERVICE_QUERY_STATUS
101
+ if not service:
102
+ return 0
103
+ try:
104
+ status, needed = SERVICE_STATUS_PROCESS(), w.DWORD()
105
+ if not advapi.QueryServiceStatusEx(service, 0, ctypes.byref(status), ctypes.sizeof(status), ctypes.byref(needed)):
106
+ return 0
107
+ return status.dwProcessId if status.dwCurrentState == 4 else 0 # SERVICE_RUNNING
108
+ finally:
109
+ advapi.CloseServiceHandle(service)
110
+ finally:
111
+ advapi.CloseServiceHandle(manager)
112
+
113
+
114
+ def listener_pids(port):
115
+ """在 0.0.0.0 或 127.0.0.1 上监听该 TCP 端口(IPv4)的进程号。"""
116
+ import ctypes
117
+ from ctypes import wintypes as w
118
+ iphlp = ctypes.WinDLL('iphlpapi')
119
+ size = w.DWORD(0)
120
+ iphlp.GetExtendedTcpTable(None, ctypes.byref(size), False, 2, 3, 0) # AF_INET, TCP_TABLE_OWNER_PID_LISTENER
121
+ buffer = ctypes.create_string_buffer(size.value)
122
+ if iphlp.GetExtendedTcpTable(buffer, ctypes.byref(size), False, 2, 3, 0) != 0:
123
+ return set()
124
+ count = struct.unpack_from('<I', buffer, 0)[0]
125
+ pids = set()
126
+ for index in range(count):
127
+ state, local_addr, local_port, _, _, pid = struct.unpack_from('<IIIIII', buffer, 4 + index * 24)
128
+ address = socket.inet_ntoa(struct.pack('<I', local_addr))
129
+ if socket.ntohs(local_port & 0xFFFF) == port and address in ('0.0.0.0', '127.0.0.1'):
130
+ pids.add(pid)
131
+ return pids
132
+
133
+
134
+ def trusted_hosts(host_dir, keyscan):
135
+ """本机 sshd 的主机公钥。
136
+
137
+ 能读到 ProgramData\\ssh 下的公钥文件就用它们;但这些文件默认只给管理员和 SYSTEM 读,UAC 下的普通桌面会话
138
+ 读不到(2026-11-28 Win11 实测)。这时向 127.0.0.1:22 要公钥,前提是 22 端口的监听者正是 sshd 服务进程,
139
+ 否则不信任(防止别的本机程序占着 22 端口骗密码)。
140
+ """
141
+ keys = known_hosts(host_dir)
142
+ if keys:
143
+ return keys
144
+ pid = sshd_pid()
145
+ if not pid or pid not in listener_pids(22) or not Path(keyscan).is_file():
146
+ return ''
147
+ import subprocess
148
+ result = subprocess.run([str(keyscan), '-T', '3', '-t', 'ed25519,ecdsa,rsa', '127.0.0.1'],
149
+ capture_output=True, text=True, timeout=10,
150
+ creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
151
+ return parse_keyscan(result.stdout)
152
+
153
+
154
+ def ssh_command(ssh, user, hosts_path):
155
+ # Forward slashes and quotes: ssh splits option values on spaces, and user profiles often contain spaces.
156
+ hosts = '"' + PureWindowsPath(hosts_path).as_posix() + '"'
157
+ return [ssh, '-F', 'NUL', '-tt', '-e', 'none',
158
+ '-o', 'PubkeyAuthentication=no', '-o', 'IdentityAgent=none',
159
+ '-o', 'PreferredAuthentications=keyboard-interactive,password',
160
+ '-o', 'ClearAllForwardings=yes', '-o', 'ForwardAgent=no',
161
+ '-o', 'ForwardX11=no', '-o', 'StrictHostKeyChecking=yes',
162
+ '-o', 'GlobalKnownHostsFile=NUL', '-o', 'UserKnownHostsFile=' + hosts,
163
+ '-o', 'ConnectTimeout=8', '-l', user, '127.0.0.1']
164
+
165
+
166
+ def system_paths():
167
+ root = os.environ.get('SystemRoot', r'C:\Windows')
168
+ data = os.environ.get('ProgramData', r'C:\ProgramData')
169
+ return Path(root) / 'System32' / 'OpenSSH' / 'ssh.exe', Path(data) / 'ssh'
170
+
171
+
172
+ class PseudoConsole:
173
+ """Minimal ConPTY wrapper (Windows 10 1809+) over ctypes; only the calls the terminal needs."""
174
+
175
+ def __init__(self, command, cols, rows):
176
+ import ctypes
177
+ from ctypes import wintypes as w
178
+ import msvcrt
179
+ import subprocess
180
+
181
+ self.ctypes = ctypes
182
+ k = ctypes.WinDLL('kernel32', use_last_error=True)
183
+ self.k = k
184
+
185
+ class COORD(ctypes.Structure):
186
+ _fields_ = [('X', w.SHORT), ('Y', w.SHORT)]
187
+
188
+ class STARTUPINFOW(ctypes.Structure):
189
+ _fields_ = [('cb', w.DWORD), ('lpReserved', w.LPWSTR), ('lpDesktop', w.LPWSTR), ('lpTitle', w.LPWSTR),
190
+ ('dwX', w.DWORD), ('dwY', w.DWORD), ('dwXSize', w.DWORD), ('dwYSize', w.DWORD),
191
+ ('dwXCountChars', w.DWORD), ('dwYCountChars', w.DWORD), ('dwFillAttribute', w.DWORD),
192
+ ('dwFlags', w.DWORD), ('wShowWindow', w.WORD), ('cbReserved2', w.WORD),
193
+ ('lpReserved2', ctypes.c_void_p), ('hStdInput', w.HANDLE), ('hStdOutput', w.HANDLE),
194
+ ('hStdError', w.HANDLE)]
195
+
196
+ class STARTUPINFOEXW(ctypes.Structure):
197
+ _fields_ = [('StartupInfo', STARTUPINFOW), ('lpAttributeList', ctypes.c_void_p)]
198
+
199
+ class PROCESS_INFORMATION(ctypes.Structure):
200
+ _fields_ = [('hProcess', w.HANDLE), ('hThread', w.HANDLE), ('dwProcessId', w.DWORD),
201
+ ('dwThreadId', w.DWORD)]
202
+
203
+ self.COORD = COORD
204
+ k.CreatePseudoConsole.argtypes = [COORD, w.HANDLE, w.HANDLE, w.DWORD, ctypes.POINTER(w.HANDLE)]
205
+ k.CreatePseudoConsole.restype = ctypes.c_long
206
+ k.ResizePseudoConsole.argtypes = [w.HANDLE, COORD]
207
+ k.ResizePseudoConsole.restype = ctypes.c_long
208
+ k.ClosePseudoConsole.argtypes = [w.HANDLE]
209
+ k.ClosePseudoConsole.restype = None
210
+ k.CreatePipe.argtypes = [ctypes.POINTER(w.HANDLE), ctypes.POINTER(w.HANDLE), ctypes.c_void_p, w.DWORD]
211
+ k.InitializeProcThreadAttributeList.argtypes = [ctypes.c_void_p, w.DWORD, w.DWORD, ctypes.POINTER(ctypes.c_size_t)]
212
+ k.UpdateProcThreadAttribute.argtypes = [ctypes.c_void_p, w.DWORD, ctypes.c_size_t, w.HANDLE, ctypes.c_size_t,
213
+ ctypes.c_void_p, ctypes.c_void_p]
214
+ k.DeleteProcThreadAttributeList.argtypes = [ctypes.c_void_p]
215
+ k.CreateProcessW.argtypes = [w.LPCWSTR, w.LPWSTR, ctypes.c_void_p, ctypes.c_void_p, w.BOOL, w.DWORD,
216
+ ctypes.c_void_p, w.LPCWSTR, ctypes.c_void_p, ctypes.POINTER(PROCESS_INFORMATION)]
217
+ k.WaitForSingleObject.argtypes = [w.HANDLE, w.DWORD]
218
+ k.GetExitCodeProcess.argtypes = [w.HANDLE, ctypes.POINTER(w.DWORD)]
219
+ k.TerminateProcess.argtypes = [w.HANDLE, w.UINT]
220
+ k.CloseHandle.argtypes = [w.HANDLE]
221
+
222
+ def check(ok, what):
223
+ if not ok:
224
+ raise OSError(ctypes.get_last_error(), what)
225
+
226
+ in_read, in_write, out_read, out_write = w.HANDLE(), w.HANDLE(), w.HANDLE(), w.HANDLE()
227
+ check(k.CreatePipe(ctypes.byref(in_read), ctypes.byref(in_write), None, 0), 'CreatePipe')
228
+ check(k.CreatePipe(ctypes.byref(out_read), ctypes.byref(out_write), None, 0), 'CreatePipe')
229
+ self.hpc = w.HANDLE()
230
+ result = k.CreatePseudoConsole(COORD(cols, rows), in_read, out_write, 0, ctypes.byref(self.hpc))
231
+ # The pseudo console holds its own copies; ours must go or the output pipe never reaches EOF.
232
+ k.CloseHandle(in_read)
233
+ k.CloseHandle(out_write)
234
+ if result != 0:
235
+ raise OSError(result, 'CreatePseudoConsole')
236
+
237
+ size = ctypes.c_size_t()
238
+ k.InitializeProcThreadAttributeList(None, 1, 0, ctypes.byref(size))
239
+ attributes = ctypes.create_string_buffer(size.value)
240
+ check(k.InitializeProcThreadAttributeList(attributes, 1, 0, ctypes.byref(size)), 'InitializeProcThreadAttributeList')
241
+ check(k.UpdateProcThreadAttribute(attributes, 0, 0x00020016, self.hpc, ctypes.sizeof(w.HANDLE), None, None),
242
+ 'UpdateProcThreadAttribute')
243
+ info = STARTUPINFOEXW()
244
+ info.StartupInfo.cb = ctypes.sizeof(STARTUPINFOEXW)
245
+ # Our own stdio are pipes to Node; without STARTF_USESTDHANDLES the child would inherit them, not the console.
246
+ info.StartupInfo.dwFlags = 0x00000100
247
+ info.lpAttributeList = ctypes.cast(attributes, ctypes.c_void_p)
248
+ self.process = PROCESS_INFORMATION()
249
+ line = ctypes.create_unicode_buffer(subprocess.list2cmdline(command))
250
+ try:
251
+ check(k.CreateProcessW(None, line, None, None, False, 0x00080000, None, None,
252
+ ctypes.byref(info), ctypes.byref(self.process)), 'CreateProcessW')
253
+ finally:
254
+ k.DeleteProcThreadAttributeList(attributes)
255
+ k.CloseHandle(self.process.hThread)
256
+ self.input = os.fdopen(msvcrt.open_osfhandle(in_write.value, 0), 'wb', buffering=0)
257
+ self.output = os.fdopen(msvcrt.open_osfhandle(out_read.value, os.O_RDONLY), 'rb', buffering=0)
258
+ self.closed = threading.Event()
259
+
260
+ def resize(self, cols, rows):
261
+ self.k.ResizePseudoConsole(self.hpc, self.COORD(cols, rows))
262
+
263
+ def wait(self):
264
+ self.k.WaitForSingleObject(self.process.hProcess, 0xFFFFFFFF)
265
+ code = self.ctypes.c_ulong()
266
+ self.k.GetExitCodeProcess(self.process.hProcess, self.ctypes.byref(code))
267
+ return code.value
268
+
269
+ def close(self):
270
+ if self.closed.is_set():
271
+ return
272
+ self.closed.set()
273
+ self.k.TerminateProcess(self.process.hProcess, 1)
274
+ # ClosePseudoConsole waits for its output to be drained; the reader thread keeps draining meanwhile.
275
+ self.k.ClosePseudoConsole(self.hpc)
276
+ with suppress(OSError):
277
+ self.input.close()
278
+ self.k.CloseHandle(self.process.hProcess)
279
+
280
+
281
+ def run(cols, rows):
282
+ ssh, host_dir = system_paths()
283
+ keys = trusted_hosts(host_dir, ssh.with_name('ssh-keyscan.exe'))
284
+ if not keys:
285
+ sys.stdout.buffer.write('无法确认本机 SSH 服务的主机公钥,终端未打开。\r\n'.encode('utf-8'))
286
+ return 1
287
+ stdin, stdout = sys.stdin.buffer, sys.stdout.buffer
288
+ with tempfile.TemporaryDirectory() as folder:
289
+ hosts = Path(folder) / 'known_hosts'
290
+ hosts.write_text(keys)
291
+ os.environ['TERM'] = 'xterm-256color'
292
+ user = os.environ.get('USERNAME') or os.getlogin()
293
+ console = PseudoConsole(ssh_command(str(ssh), user, hosts), cols, rows)
294
+
295
+ def pump():
296
+ with suppress(OSError, ValueError):
297
+ while True:
298
+ data = console.output.read(32768)
299
+ if not data:
300
+ break
301
+ stdout.write(data)
302
+ stdout.flush()
303
+
304
+ reader = threading.Thread(target=pump, daemon=True)
305
+ reader.start()
306
+
307
+ def keyboard():
308
+ with suppress(OSError, ValueError):
309
+ for kind, value in frames(stdin):
310
+ if kind == 'input':
311
+ console.input.write(value)
312
+ else:
313
+ console.resize(*value)
314
+ # Node closed the session (or sent garbage): end the login.
315
+ console.close()
316
+
317
+ threading.Thread(target=keyboard, daemon=True).start()
318
+ code = console.wait()
319
+ console.close()
320
+ reader.join(5)
321
+ return code
322
+
323
+
324
+ def check():
325
+ ssh, host_dir = system_paths()
326
+ if not ssh.is_file() or not trusted_hosts(host_dir, ssh.with_name('ssh-keyscan.exe')):
327
+ return 1
328
+ with socket.create_connection(('127.0.0.1', 22), timeout=1):
329
+ pass
330
+ return 0
331
+
332
+
333
+ if __name__ == '__main__':
334
+ if os.name != 'nt':
335
+ sys.exit(1)
336
+ if sys.argv[1:] == ['--check']:
337
+ try:
338
+ sys.exit(check())
339
+ except OSError:
340
+ sys.exit(1)
341
+ sys.exit(run(int(sys.argv[1]), int(sys.argv[2])))
@@ -99,9 +99,14 @@ def instructions_for(tool, tools, command):
99
99
  COMPACT_AT_DEFAULT = 60
100
100
 
101
101
 
102
+ def config_dir():
103
+ """客户端配置目录:安装包的启动器会设环境变量;普通 npm 版(2026-11-27)不设,用与 bin/easy-agents.js 相同的默认目录。"""
104
+ return Path(os.environ.get("EASYAGENTS_CONFIG_DIR") or Path.home() / ".easyagents")
105
+
106
+
102
107
  def compact_at():
103
108
  try:
104
- value = json.loads((Path(os.environ["EASYAGENTS_CONFIG_DIR"]) / "mac-compact.json").read_text())["percent"]
109
+ value = json.loads((config_dir() / "mac-compact.json").read_text())["percent"]
105
110
  except (KeyError, OSError, ValueError, TypeError):
106
111
  return COMPACT_AT_DEFAULT
107
112
  return value if type(value) is int and 0 <= value <= 100 else COMPACT_AT_DEFAULT
@@ -211,11 +216,16 @@ def run(content, cancelled):
211
216
  local = content.get("workspace")
212
217
  if local:
213
218
  cwd = (Path.home() / Path(local).expanduser()).resolve()
214
- if not cwd.is_dir() or cwd == Path(cwd.anchor):
219
+ if cwd == Path(cwd.anchor):
215
220
  return failed("workspace_missing", "请核对该 Agent 在设备上登记的工作目录")
221
+ # 登记的目录在设备上还没有就建出来,不分聊天、工作模式(用户 2026-11-27)
222
+ try:
223
+ cwd.mkdir(parents=True, exist_ok=True)
224
+ except OSError:
225
+ return failed("workspace_missing", f"无法创建该 Agent 登记的工作目录:{cwd}")
216
226
  else:
217
227
  # Claude locates earlier conversations by directory even when all tools are disabled.
218
- cwd = Path(os.environ["EASYAGENTS_CONFIG_DIR"]) / "chat-workspace"
228
+ cwd = config_dir() / "chat-workspace"
219
229
  cwd.mkdir(mode=0o700, parents=True, exist_ok=True)
220
230
 
221
231
  if command == "/compact" and tool in SOFT_COMPACT_TOOLS:
@@ -1,4 +1,5 @@
1
1
  """How an agent reaches the platform tools from a tool-enabled run (task runs and lead work messages)."""
2
+ import os
2
3
  import shlex
3
4
  import sys
4
5
  from pathlib import Path
@@ -6,10 +7,19 @@ from pathlib import Path
6
7
  PACKAGE = Path(__file__).resolve().parents[1]
7
8
 
8
9
 
9
- def platform_entry(credential_file):
10
- command = shlex.join([sys.executable, "-I", "-B", str(PACKAGE / "runtime" / "mcp.py"),
11
- "--credential", str(credential_file)])
12
- return ("\n平台操作入口:通过终端运行 " + command + " list 查看全部工具及参数;"
10
+ def entry_command(credential_file, windows=None):
11
+ parts = [sys.executable, "-I", "-B", str(PACKAGE / "runtime" / "mcp.py"), "--credential", str(credential_file)]
12
+ if not (os.name == "nt" if windows is None else windows):
13
+ return shlex.join(parts), ""
14
+ # Windows(2026-11-28):shlex 的单引号在 PowerShell、cmd 里都不认。正斜杠加双引号在 PowerShell、cmd、Git Bash 都通用;
15
+ # PowerShell 里引号开头会被当成字符串,要在最前面加 “& ”。
16
+ quoted = ['"' + part.replace("\\", "/") + '"' if "\\" in part or "/" in part or " " in part else part for part in parts]
17
+ return " ".join(quoted), "(在 PowerShell 里要在最前面加 & )"
18
+
19
+
20
+ def platform_entry(credential_file, windows=None):
21
+ command, note = entry_command(credential_file, windows)
22
+ return ("\n平台操作入口:通过终端运行 " + command + " list 查看全部工具及参数" + note + ";"
13
23
  "调用方式:同一命令后接工具名及单个 JSON 对象参数。"
14
24
  "先调用 get_workflow_guide 获取任务规程,按需用 get_project_context 获取项目编号与安排。"
15
25
  "登记需求用 register_requirement,提交方案用 submit_plan,用户同意后用 record_approval 登记批准,"
@@ -80,8 +80,13 @@ def run(request, cancelled):
80
80
  if not isinstance(local, str) or local.strip() in ("", ".", "~", "~/"):
81
81
  return failed("workspace_missing", "未配置工作目录")
82
82
  original = (Path.home() / Path(local).expanduser()).resolve()
83
- if not original.is_dir() or original == Path(original.anchor) or original == Path.home().resolve():
83
+ if original == Path(original.anchor) or original == Path.home().resolve():
84
84
  return failed("workspace_missing", "请核对该 Agent 在设备上登记的工作目录")
85
+ # 登记的目录在设备上还没有就建出来(用户 2026-11-27:不管什么模式)
86
+ try:
87
+ original.mkdir(parents=True, exist_ok=True)
88
+ except OSError:
89
+ return failed("workspace_missing", f"无法创建该 Agent 登记的工作目录:{original}")
85
90
 
86
91
  sync = None
87
92
  cwd = original