@unionschool/easy-agents 1.0.44 → 1.0.51

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,6 +1,6 @@
1
1
  # EasyAgents
2
2
 
3
- 在要接任务的设备上单独安装客户端,首次用工作台生成的配对码绑定设备。Mac、Windows 和 Ubuntu 安装包自带 Node、Python 和客户端核心。设备要使用 Codex 或 Claude 时,还需安装并登录对应的工具。
3
+ 在要接任务的设备上单独安装客户端,首次用工作台生成的配对码绑定设备。Mac、Windows 和 Ubuntu 安装包自带 Node、Python 和客户端核心。设备要使用 Codex、Claude、Cursor 或 Agy 时,还需安装并登录对应的命令行工具(`codex`、`claude`、`cursor-agent`、`agy`),客户端在系统路径里查找。
4
4
 
5
5
  ## 选择安装包
6
6
 
@@ -86,10 +86,10 @@ npm exec --offline -- easy-agents run
86
86
 
87
87
  ## 各端能执行什么
88
88
 
89
- - Mac 和 Ubuntu 安装包能接平台任务分支上的执行、审核、部署和澄清运行(Codex、Claude,完整权限,与旧 Python 客户端的规则一致):执行在任务分支上工作并在成功后推送;审核和部署检出本轮交付的提交;工作目录有未提交改动时,在客户端配置目录的 `worktrees/` 里另建工作树,原目录不动,合并后的成员同步会清理这些工作树。Agent 通过提示里给出的平台命令调用工具;Agent 凭据缺失或已被平台撤销时,客户端自动领取新凭据(平台会同时撤销旧凭据)。旧的同目录文件交付和用户发布命令(`publish`)不支持。工作台读取任务、需求文档(“阅读”抽屉)也由这两种设备应答,只读 Git,不切分支、不改工作区。
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 的文本对话、续聊和本地文本任务;Agy、Cursor 只接对话,不接任务运行(2026-11-23,1.0.34 起含 Cursor)。它们可从项目卡片或对话页接收聊天和工作消息。普通聊天是纯文本:Codex 只读会话、Claude 不开工具。工作消息(负责人与任务角色的对话、平台的流程通知)与任务运行一样用完整权限,带平台操作入口,Agent 凭据缺失或被撤销时自动领取,所以负责人能在对话里登记需求、发布任务、合并上报。可用的会话编号、模型与用量会随结果回传。
92
- - Mac 和 Windows 面板可显示检测到的 Codex、Claude、Cursor、Agy 登录和上报状态。平台控制额度上报开关,绿色胶囊显示已获得的剩余额度,测得零时显示零。Windows 和单独运行的普通 npm 版支持单次 Claude 文本任务,使用 bare 模式可用的认证。桌面对话功能需要安装包提供的工具适配和内置运行环境。
91
+ - Mac 和 Ubuntu 安装包支持 Codex、Claude、Cursor、Agy 的文本对话与续聊,Codex、Claude 还支持本地文本任务。客户端上线时按工具上报能否接任务分支运行,平台据此派发;1.0.49 及更早的客户端不接 Cursor、Agy 的任务运行,平台会把派给它们的任务运行留在排队。Cursor、Agy 在 Ubuntu 上的任务运行尚未实测。它们可从项目卡片或对话页接收聊天和工作消息。普通聊天是纯文本:Codex 只读会话、Claude 不开工具。工作消息(负责人与任务角色的对话、平台的流程通知)与任务运行一样用完整权限,带平台操作入口,Agent 凭据缺失或被撤销时自动领取,所以负责人能在对话里登记需求、发布任务、合并上报。可用的会话编号、模型与用量会随结果回传。
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
94
  - Node 核心支持 `/sha256 <文本>`、本地 Markdown 文档里的同类计算和成员同步。文档与同步的目录需与本机选定工作目录相符,可用 `EASYAGENTS_WORKSPACE` 指定。成员同步使用包内实现、系统 Git 和 Python 3.10+,更新已有检出目录。Android 首版可执行 SHA-256 消息和用户选择目录里的计算文档。
95
95
  - 客户端保存待回传结果,重连后补传。独立版尚未接入运行中 `/steer`、手动 `/sync`、平台远程读文档和编辑设备上的工具规则。
@@ -138,7 +138,8 @@ export function macReporter(folder, read = inventory, usage = readQuota, models
138
138
  return { ...found.hello, available_models };
139
139
  },
140
140
  welcome(hello, msg, post, reconnect) {
141
- patch({ connected: true, accepted: Date.now(), hello, reports: {}, deviceId: msg.device_id });
141
+ const workbenchUrl = typeof msg.workbench_url === 'string' && msg.workbench_url.trim() ? msg.workbench_url.trim() : null;
142
+ patch({ connected: true, accepted: Date.now(), hello, reports: {}, deviceId: msg.device_id, workbenchUrl });
142
143
  for (const setting of msg.quota_settings ?? []) configure(setting, post);
143
144
  const controller = generation;
144
145
  timer = setInterval(async () => {
@@ -140,6 +140,7 @@ export function desktopStatus(folder) {
140
140
  const saved = readSnapshot(folder, 'mac-worker.json');
141
141
  const fresh = pid > 0 && saved?.pid === pid && Date.now() - saved.updated < 95000;
142
142
  return { running: Boolean(pid), connected: Boolean(fresh && saved.connected), pid, terminalEnabled: terminalEnabled(folder), compactAt: compactAt(folder), moved: moved(folder),
143
+ workbenchUrl: typeof saved?.workbenchUrl === 'string' && saved.workbenchUrl ? saved.workbenchUrl : null,
143
144
  report: saved || {}, task: fresh ? saved.task : null };
144
145
  }
145
146
 
package/bin/run.js CHANGED
@@ -251,10 +251,12 @@ export async function runDevice(device, configDir, version, signal, { reporter,
251
251
  }
252
252
  }
253
253
  if (signal.aborted) break;
254
- // steer(协议第 16 节):桌面版的 Claude、Codex、Agy 对话,以及 Claude、Codex 的任务运行(2026-11-23)支持运行中补充;纯 npm 不支持。
254
+ // steer(协议第 16 节):桌面版的 Claude、Codex、Agy 对话与任务运行支持运行中补充;纯 npm 不支持。
255
255
  // Cursor 实测只能取消当前一轮再发新的,不算补充(2026-11-23)。
256
- const steer = { claude_code: taskDelivery(), codex: taskDelivery(), cursor: false, antigravity: taskDelivery() };
257
- const hello = { type: 'hello', client_version: version, tools: [], terminal, task_delivery: taskDelivery(), doc_read: taskDelivery(), steer, ...metadata };
256
+ const canDeliver = taskDelivery();
257
+ const steer = { claude_code: canDeliver, codex: canDeliver, cursor: false, antigravity: canDeliver };
258
+ const task_delivery_tools = { claude_code: canDeliver, codex: canDeliver, cursor: canDeliver, antigravity: canDeliver };
259
+ const hello = { type: 'hello', client_version: version, tools: [], terminal, task_delivery: canDeliver, task_delivery_tools, doc_read: canDeliver, steer, ...metadata };
258
260
  let lastSeen = Date.now(), welcomed = false;
259
261
  socket = new WebSocket(wsUrl, { headers, followRedirects: false, handshakeTimeout: 15000, maxPayload: 1048576 });
260
262
  const current = socket;
package/bin/tasks.js CHANGED
@@ -16,6 +16,7 @@ function invoke(file, args, cwd, input, signal, timeout) {
16
16
 
17
17
  // 对话桥:首行 JSON 是运行内容,之后 stdin 保持打开,运行中补充(/steer)按行写入;
18
18
  // 子进程从 fd 3 逐行回执 {"message_id","status"},stdout 只放最终结果。
19
+ // resources 为空时是普通 npm 版的聊天(用户 2026-11-27):用本机 python3 跑同一个对话桥,适配器只依赖标准库。
19
20
  function desktopConversation(resources, content, prompt, signal, credential, tools = false, onSteer) {
20
21
  const bridge = fileURLToPath(new URL('../runtime/desktop_chat.py', import.meta.url));
21
22
  const seconds = content.timeout_seconds;
@@ -24,7 +25,8 @@ function desktopConversation(resources, content, prompt, signal, credential, too
24
25
  resume: content.resume_session_ref, workspace: content.workspace?.local_path, timeout,
25
26
  workRunId: content.chat_mode !== 'chat' ? content.run_id : undefined, passthrough: content.passthrough === true, credential, tools };
26
27
  return new Promise(resolveResult => {
27
- const child = spawn(join(resources, 'python/bin/python3'), ['-I', '-B', '-X', 'utf8', bridge],
28
+ const python = resources ? join(resources, 'python/bin/python3') : 'python3';
29
+ const child = spawn(python, ['-I', '-B', '-X', 'utf8', bridge],
28
30
  { stdio: ['pipe', 'pipe', 'ignore', 'pipe'], windowsHide: true });
29
31
  const waiting = new Map();
30
32
  let stdout = '', size = 0, settled = false, acks = '';
@@ -58,7 +60,8 @@ function desktopConversation(resources, content, prompt, signal, credential, too
58
60
  } catch {}
59
61
  }
60
62
  });
61
- child.on('error', () => finish(failed));
63
+ child.on('error', error => finish(!resources && error.code === 'ENOENT'
64
+ ? { status: 'failed', failure_code: 'python_missing', failure_detail: NPM_PYTHON_NOTE } : failed));
62
65
  child.on('close', () => {
63
66
  if (signal.aborted) {
64
67
  // 被 /stop 停下:带回工具会话号,下一条消息续接同一会话(docs/消息链路.md 第 3.2 节)。
@@ -84,6 +87,12 @@ function desktopConversation(resources, content, prompt, signal, credential, too
84
87
  }
85
88
 
86
89
  const TASK_KINDS = ['execute', 'review', 'deploy', 'clarify'];
90
+ // 普通 npm 版(没有安装包运行环境)只接这三种工具的聊天模式;工作模式要平台操作入口(依赖安装包里的 httpx),任务运行要安装包(用户 2026-11-27)。
91
+ // Windows 的工具启动方式没验证过,暂不开放。Claude 照旧走下面的单次文本任务。
92
+ const NPM_CHAT_TOOLS = ['codex', 'antigravity', 'cursor'];
93
+ const NPM_PYTHON_NOTE = '普通 npm 版的聊天需要本机 python3(3.10 及以上),请先安装';
94
+ const NPM_LIMIT_NOTE = '此设备是普通 npm 版客户端:Codex、Agy、Cursor 只接聊天模式,Claude 只接纯聊天;工作模式和任务运行请安装 Mac 或 Ubuntu 安装包';
95
+ const DESKTOP_TASK_TOOLS = ['codex', 'claude_code', 'antigravity', 'cursor'];
87
96
 
88
97
  // Mac and Ubuntu desktop installs: Git task-branch runs go to the packaged Python runner.
89
98
  // 任务运行(执行、审核、部署、答疑):首行 JSON 是运行内容;之后 stdin 保持打开,任务对话里发给正在干活的人员的话
@@ -193,7 +202,7 @@ export async function execute(content, signal, workCredential, { agentCredential
193
202
  if (!resources || !agentCredential || !configDir) {
194
203
  return { status: 'failed', failure_code: 'handoff_unsupported', failure_detail: '任务分支运行目前只支持 Mac 和 Ubuntu 桌面版客户端' };
195
204
  }
196
- if (!['codex', 'claude_code'].includes(content.agent?.tool_type)) {
205
+ if (!DESKTOP_TASK_TOOLS.includes(content.agent?.tool_type)) {
197
206
  return { status: 'failed', failure_code: 'unsupported_task', failure_detail: '此工具尚未接入独立客户端的任务运行' };
198
207
  }
199
208
  let credential;
@@ -223,9 +232,7 @@ export async function execute(content, signal, workCredential, { agentCredential
223
232
  return { status: 'succeeded', reply_text: digest };
224
233
  }
225
234
  if (task && content.prompt) prompt = content.prompt + '\n\n' + prompt;
226
- // Agy、Cursor 只接对话(2026-11-23),任务运行仍只有 Codex、Claude。
227
- if (resources && (['codex', 'claude_code'].includes(content.agent?.tool_type) && (task || content.run_kind === 'chat')
228
- || ['antigravity', 'cursor'].includes(content.agent?.tool_type) && content.run_kind === 'chat')) {
235
+ if (resources && DESKTOP_TASK_TOOLS.includes(content.agent?.tool_type) && (task || content.run_kind === 'chat')) {
229
236
  let credential;
230
237
  // Same rule as the platform: only chat_mode 'chat' is a plain conversation. Workflow notifications to the lead
231
238
  // (merge after deploy, answers, sync handoff) arrive with an empty chat_mode and must be able to act.
@@ -243,8 +250,12 @@ export async function execute(content, signal, workCredential, { agentCredential
243
250
  }
244
251
  return desktopConversation(resources, content, prompt, signal, credential, workMode, onSteer);
245
252
  }
253
+ if (!resources && process.platform !== 'win32' && !task && content.run_kind === 'chat' && content.chat_mode === 'chat'
254
+ && NPM_CHAT_TOOLS.includes(content.agent?.tool_type)) {
255
+ return desktopConversation(null, content, prompt, signal, null, false, onSteer);
256
+ }
246
257
  if ((!task && (content.run_kind !== 'chat' || content.chat_mode !== 'chat')) || content.agent?.tool_type !== 'claude_code') {
247
- return { status: 'failed', failure_code: 'unsupported_task', failure_detail: '当前独立客户端支持计算、成员同步及 Claude 文本任务' };
258
+ return { status: 'failed', failure_code: 'unsupported_task', failure_detail: NPM_LIMIT_NOTE };
248
259
  }
249
260
  if (content.resume_session_ref) {
250
261
  return { status: 'failed', failure_code: 'unsupported_session', failure_detail: '此版本仅支持独立文本任务' };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unionschool/easy-agents",
3
- "version": "1.0.44",
3
+ "version": "1.0.51",
4
4
  "description": "EasyAgents",
5
5
  "easyAgentsDesktop": 1,
6
6
  "type": "module",
@@ -8,8 +8,14 @@ import threading
8
8
  from pathlib import Path
9
9
  from uuid import UUID
10
10
 
11
- resources = os.environ.get("EASYAGENTS_MAC_RESOURCES") or os.environ["EASYAGENTS_DESKTOP_RESOURCES"]
12
- sys.path.insert(0, str(Path(resources) / "lib"))
11
+ if sys.version_info < (3, 10):
12
+ print(json.dumps({"status": "failed", "failure_code": "python_missing",
13
+ "failure_detail": "普通 npm 版的聊天需要本机 python3(3.10 及以上),请先升级"}, ensure_ascii=False))
14
+ sys.exit(0)
15
+ # 安装包带运行环境目录;普通 npm 版的聊天(2026-11-27)没有,用本机 python3,适配器只依赖标准库。
16
+ resources = os.environ.get("EASYAGENTS_MAC_RESOURCES") or os.environ.get("EASYAGENTS_DESKTOP_RESOURCES")
17
+ if resources:
18
+ sys.path.insert(0, str(Path(resources) / "lib"))
13
19
  sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
14
20
  # 工具适配器用 npm 核心包自带的那份(只依赖标准库),不用安装包 lib 里打包时的旧副本:
15
21
  # 这样 /compact、/steer 等适配器修复随核心更新生效,不必重装应用(2026-11-23)。
@@ -37,6 +43,48 @@ SUGGEST = ("回复末尾可以附两样东西,平台会拆出来单独展示
37
43
 
38
44
  NEW_SESSION_COMMANDS = ("/new", "/clear")
39
45
  NEW_SESSION_TEXT = "已开始新会话:智能体不再记得之前的内容,聊天记录仍保留。"
46
+ SOFT_COMPACT_TOOLS = ("antigravity", "cursor")
47
+ SOFT_COMPACT_SUMMARIZE = (
48
+ "请将我们当前会话的上下文精炼压缩成一份交接摘要(纯文本 Markdown,不超过 800 字),"
49
+ "只保留后续继续工作必需的信息:1. 当前目标与范围;2. 已确认的结论与决策;"
50
+ "3. 已改动或关键的文件路径;4. 尚未完成的待办。不要寒暄,不要执行修改命令。"
51
+ )
52
+ SOFT_COMPACT_SEED = (
53
+ "以下是上一阶段会话压缩后的交接摘要,请先记住作为后续对话的上下文背景,只需简短回复“已接续上下文”:\n\n"
54
+ )
55
+
56
+
57
+ def _format_result(result):
58
+ if result.reply_text and len(result.reply_text) > 1_000_000:
59
+ return failed("bad_output", "工具回复超过平台长度上限")
60
+ if isinstance(result.context, dict):
61
+ result.context = {**result.context, "compact_at": compact_at()}
62
+ fields = ("status", "reply_text", "tool_session_ref", "tool_version", "model_name",
63
+ "usage", "context", "failure_code", "failure_detail")
64
+ return {name: getattr(result, name) for name in fields if getattr(result, name) is not None}
65
+
66
+
67
+ def _soft_compact(adapter, cwd, resume, content, cancelled):
68
+ """Agy、Cursor 原生不支持 /compact:先在旧会话提炼交接摘要,再开新会话写入摘要拿回新会话号。"""
69
+ if not resume:
70
+ return {"status": "succeeded", "reply_text": "当前是新会话,无需压缩。"}
71
+ timeout = content["timeout"]
72
+ model = content.get("model")
73
+ summary_result = adapter.invoke(
74
+ prompt=SOFT_COMPACT_SUMMARIZE, cwd=cwd, resume_session_ref=resume,
75
+ timeout_seconds=timeout, cancel_event=cancelled, model=model,
76
+ )
77
+ if summary_result.status != "succeeded":
78
+ return _format_result(summary_result)
79
+ summary = (summary_result.reply_text or "").strip()
80
+ seed_result = adapter.invoke(
81
+ prompt=SOFT_COMPACT_SEED + summary, cwd=cwd, resume_session_ref=None,
82
+ timeout_seconds=timeout, cancel_event=cancelled, model=model,
83
+ )
84
+ if seed_result.status != "succeeded":
85
+ return _format_result(seed_result)
86
+ seed_result.reply_text = f"上下文已压缩,已开启新会话接续。\n\n**交接摘要**\n{summary}"
87
+ return _format_result(seed_result)
40
88
 
41
89
 
42
90
  def instructions_for(tool, tools, command):
@@ -134,19 +182,23 @@ def run(content, cancelled):
134
182
  options = {}
135
183
  elif tool == "antigravity":
136
184
  # Agy 对话(2026-11-23 接入独立客户端):聊天、工作同一套参数(T-158 聊天不限权限);运行中补充见适配器说明。
137
- # Agy 没有附加系统说明的参数,建议回复格式暂不告知。
185
+ # Agy 没有附加系统说明的参数,由下文拼在 prompt 头部。
138
186
  adapter = AntigravityAdapter()
139
187
  options = {}
140
188
  elif tool == "cursor":
141
- # Cursor 对话(2026-11-23:飞书私聊给 Cursor 发消息,独立客户端连回四次“不支持”):cursor-agent -p,
142
- # 聊天、工作同一套参数。没有附加系统说明的参数,建议回复格式暂不告知;不支持运行中补充(平台改为排队)。
189
+ # Cursor 对话(2026-11-23 接入):cursor-agent -p stream-json,聊天、工作同一套参数。
190
+ # 没有附加系统说明的参数,由下文拼在 prompt 头部;不支持运行中补充(平台改为排队)。
143
191
  adapter = CursorAdapter()
144
192
  options = {}
145
193
  else:
146
194
  return failed("unsupported_task", "此工具尚未接入设备文本对话")
195
+ if command in NEW_SESSION_COMMANDS and tool != "claude_code":
196
+ # 实测 Agy print mode 透传 /new 会 exit 2 报错,Cursor 当普通聊天文字,Codex 无斜杠命令;统一直接清空会话。
197
+ return {"status": "succeeded", "reply_text": NEW_SESSION_TEXT}
147
198
  if not shutil.which(adapter.executable):
148
199
  return failed("tool_missing", "本机未找到 " + adapter.executable_name)
149
- adapter.instructions = instructions_for(tool, tools, command) if tool not in ("antigravity", "cursor") else None
200
+ extra_instructions = instructions_for(tool, tools, command)
201
+ adapter.instructions = extra_instructions if tool not in ("antigravity", "cursor") else None
150
202
  if content.get("_on_adapter"):
151
203
  content["_on_adapter"](adapter)
152
204
 
@@ -166,6 +218,9 @@ def run(content, cancelled):
166
218
  cwd = Path(os.environ["EASYAGENTS_CONFIG_DIR"]) / "chat-workspace"
167
219
  cwd.mkdir(mode=0o700, parents=True, exist_ok=True)
168
220
 
221
+ if command == "/compact" and tool in SOFT_COMPACT_TOOLS:
222
+ return _soft_compact(adapter, cwd, resume, content, cancelled)
223
+
169
224
  prompt = content["prompt"]
170
225
  run_id = content.get("workRunId")
171
226
  if run_id and not content.get("passthrough"):
@@ -180,6 +235,8 @@ def run(content, cancelled):
180
235
  prompt = f"本次调度模式:platform;运行编号:{run_id}\n{guidance}\n\n{prompt}"
181
236
  if tools and content.get("credential"):
182
237
  prompt += platform_entry(content["credential"]["file"])
238
+ if extra_instructions and tool in ("antigravity", "cursor"):
239
+ prompt = f"[系统说明]\n{extra_instructions}\n[/系统说明]\n\n{prompt}"
183
240
  if command:
184
241
  options["allow_empty"] = True # /compact 成功时 Claude 不输出文字,回“命令已执行”
185
242
  result = adapter.invoke(prompt=prompt, cwd=cwd, resume_session_ref=resume,
@@ -188,13 +245,7 @@ def run(content, cancelled):
188
245
  if command in NEW_SESSION_COMMANDS and result.status == "succeeded" and result.reply_text == NO_OUTPUT_TEXT:
189
246
  # Claude 的 /new、/clear 会换一个空会话(会话号随回传更新),默认的“命令已执行”看不出发生了什么(用户 2026-11-23)。
190
247
  result.reply_text = NEW_SESSION_TEXT
191
- if result.reply_text and len(result.reply_text) > 1_000_000:
192
- return failed("bad_output", "工具回复超过平台长度上限")
193
- if isinstance(result.context, dict):
194
- result.context = {**result.context, "compact_at": compact_at()}
195
- fields = ("status", "reply_text", "tool_session_ref", "tool_version", "model_name",
196
- "usage", "context", "failure_code", "failure_detail")
197
- return {name: getattr(result, name) for name in fields if getattr(result, name) is not None}
248
+ return _format_result(result)
198
249
 
199
250
 
200
251
  def main():
@@ -90,6 +90,58 @@ def _activities(tool, event):
90
90
  'mcpToolCall': ('tool', 'tool'), 'reasoning': ('thinking', None),
91
91
  'agentMessage': ('reply', None)}.get(kind, ('other', None))
92
92
  yield (category, *activity_detail(item.get(field)))
93
+ elif tool == 'antigravity' and event.get('event') == 'step_update':
94
+ step = event.get('step_update')
95
+ if not isinstance(step, dict):
96
+ return
97
+ stype = step.get('step_type')
98
+ if stype == 'tool' and step.get('state') in ('ACTIVE', 'DONE'):
99
+ name = step.get('tool_name')
100
+ info = step.get('tool_info')
101
+ params = info.get('parameters') if isinstance(info, dict) and isinstance(info.get('parameters'), dict) else {}
102
+ mapping = {
103
+ 'run_command': ('command', ('CommandLine', 'command')),
104
+ 'read_file': ('read', ('Path', 'AbsolutePath', 'path')),
105
+ 'view_file': ('read', ('AbsolutePath', 'Path', 'path')),
106
+ 'edit_file': ('edit', ('Path', 'TargetFile', 'path')),
107
+ 'write_file': ('edit', ('Path', 'TargetFile', 'path')),
108
+ 'replace_file_content': ('edit', ('TargetFile', 'Path', 'path')),
109
+ 'multi_replace_file_content': ('edit', ('TargetFile', 'Path', 'path')),
110
+ 'grep_search': ('search', ('Query', 'Pattern', 'query')),
111
+ 'find_by_name': ('search', ('Pattern', 'SearchDirectory', 'pattern')),
112
+ 'search_web': ('search', ('query', 'Query')),
113
+ }
114
+ category, fields = mapping.get(name, ('tool', ())) if isinstance(name, str) else ('other', ())
115
+ detail = next((params.get(f) for f in fields if isinstance(params.get(f), str) and params.get(f)), None)
116
+ yield (category, *activity_detail(detail if detail is not None else (name if isinstance(name, str) else '')))
117
+ elif stype == 'agent_response' and step.get('state') == 'ACTIVE' and step.get('text_delta'):
118
+ yield ('reply', '', False)
119
+ elif tool == 'cursor' and event.get('type') == 'tool_call' and event.get('subtype') in ('started', 'completed'):
120
+ tc = event.get('tool_call')
121
+ if not isinstance(tc, dict):
122
+ return
123
+ name, body = next(((k, v) for k, v in tc.items() if k.endswith('ToolCall') and isinstance(v, dict)), (None, None))
124
+ if not name:
125
+ return
126
+ args = body.get('args') if isinstance(body.get('args'), dict) else {}
127
+ mapping = {
128
+ 'shellToolCall': ('command', ('command', 'cmd')),
129
+ 'bashToolCall': ('command', ('command', 'cmd')),
130
+ 'readToolCall': ('read', ('path', 'file_path', 'targetFile')),
131
+ 'editToolCall': ('edit', ('path', 'file_path', 'targetFile')),
132
+ 'writeToolCall': ('edit', ('path', 'file_path', 'targetFile')),
133
+ 'grepToolCall': ('search', ('pattern', 'query')),
134
+ 'globToolCall': ('search', ('pattern', 'globPattern')),
135
+ 'searchToolCall': ('search', ('query', 'pattern')),
136
+ 'webSearchToolCall': ('search', ('query', 'searchTerm')),
137
+ }
138
+ category, fields = mapping.get(name, ('tool', ()))
139
+ detail = next((args.get(f) for f in fields if isinstance(args.get(f), str) and args.get(f)), None)
140
+ yield (category, *activity_detail(detail if detail is not None else name))
141
+ elif tool == 'cursor' and event.get('type') == 'thinking' and event.get('subtype') == 'completed':
142
+ yield ('thinking', '', False)
143
+ elif tool == 'cursor' and event.get('type') == 'assistant':
144
+ yield ('reply', '', False)
93
145
 
94
146
 
95
147
  # 斜杠命令成功但工具不输出文字时的回复(用户 2026-11-23 去掉了“(无输出)”)。
@@ -289,8 +341,9 @@ class _ProcessAdapter:
289
341
 
290
342
  # stdout 单独逐行消费;communicate 仍负责并发写 stdin、排空 stderr 和超时回收。
291
343
  lines = []
344
+ seen = {}
292
345
  reader = None
293
- if self.tool_type == 'claude_code':
346
+ if self.tool_type in ('claude_code', 'cursor'):
294
347
  output, process.stdout = process.stdout, None
295
348
 
296
349
  def read_events():
@@ -300,9 +353,15 @@ class _ProcessAdapter:
300
353
  event = json.loads(line)
301
354
  except ValueError:
302
355
  event = None
303
- # Claude verbose 也输出提示、工具入参和结果;沿用原日志范围,仅保留最终结果。
304
- if isinstance(event, dict) and ('type' not in event or event['type'] == 'result'):
305
- lines[:] = [line]
356
+ if isinstance(event, dict):
357
+ if isinstance(event.get('session_id'), str) and event['session_id']:
358
+ seen.setdefault('session', event['session_id'])
359
+ if self.tool_type == 'cursor' and event.get('type') == 'system' and event.get('subtype') == 'init':
360
+ if isinstance(event.get('model'), str) and event['model']:
361
+ seen['model'] = event['model']
362
+ # 沿用原日志范围,仅保留最终结果(兼容单行 json 无 type 字段)。
363
+ if 'type' not in event or event['type'] == 'result':
364
+ lines[:] = [line]
306
365
  if on_activity:
307
366
  for activity in _activities(self.tool_type, event):
308
367
  on_activity(activity)
@@ -350,6 +409,7 @@ class _ProcessAdapter:
350
409
  status=stopped[0],
351
410
  failure_code=stopped[1],
352
411
  failure_detail=stopped[2],
412
+ tool_session_ref=seen.get("session") if stopped[0] == "cancelled" else None,
353
413
  exit_code=process.poll(),
354
414
  raw_output=stdout or stderr or "",
355
415
  elapsed_seconds=time.monotonic() - started,
@@ -357,7 +417,10 @@ class _ProcessAdapter:
357
417
 
358
418
  if reader:
359
419
  stdout = "".join(lines)
360
- return self._finalize_result(process, stdout, stderr, started, allow_empty)
420
+ result = self._finalize_result(process, stdout, stderr, started, allow_empty)
421
+ if result.status == "succeeded" and not result.model_name and seen.get("model"):
422
+ result.model_name = seen["model"]
423
+ return result
361
424
 
362
425
  def _finalize_result(
363
426
  self,
@@ -1026,11 +1089,30 @@ class CursorAdapter(_ProcessAdapter):
1026
1089
  executable_name = "cursor-agent"
1027
1090
 
1028
1091
  def _command(self, resume_session_ref: str | None) -> list[str]:
1029
- command = [self.executable, "-p", "--trust", "--force", "--sandbox", "disabled", "--approve-mcps", "--output-format", "json"]
1092
+ command = [self.executable, "-p", "--trust", "--force", "--sandbox", "disabled", "--approve-mcps", "--output-format", "stream-json"]
1030
1093
  if resume_session_ref:
1031
1094
  command.append("--resume=" + resume_session_ref)
1032
1095
  return command
1033
1096
 
1097
+ def _payload(self, raw: str) -> dict:
1098
+ payload = None
1099
+ model = None
1100
+ for line in raw.splitlines():
1101
+ if not line.strip():
1102
+ continue
1103
+ event = json.loads(line)
1104
+ if not isinstance(event, dict):
1105
+ raise ValueError("事件必须为对象")
1106
+ if event.get("type") == "system" and event.get("subtype") == "init" and isinstance(event.get("model"), str):
1107
+ model = event["model"]
1108
+ elif "type" not in event or event.get("type") == "result":
1109
+ payload = event
1110
+ if not isinstance(payload, dict):
1111
+ raise ValueError("缺少最终结果")
1112
+ if model and not payload.get("model"):
1113
+ payload = payload | {"model": model}
1114
+ return payload
1115
+
1034
1116
 
1035
1117
  class AntigravityAdapter(_ProcessAdapter):
1036
1118
  """Agy:stream-json 每条 user 事件跑一轮。运行中补充追加一行 user 事件,Agy 在当前一轮结束后、同一进程同一会话里
@@ -1101,6 +1183,11 @@ class AntigravityAdapter(_ProcessAdapter):
1101
1183
  continue
1102
1184
  if not isinstance(event, dict):
1103
1185
  continue
1186
+ if event.get("event") == "init" and isinstance(event.get("conversation_id"), str) and event["conversation_id"]:
1187
+ seen.setdefault("session", event["conversation_id"])
1188
+ if on_activity:
1189
+ for activity in _activities(self.tool_type, event):
1190
+ on_activity(activity)
1104
1191
  if event.get("event") == "result":
1105
1192
  results.append(line)
1106
1193
  reply = event.get("result")
@@ -1157,7 +1244,7 @@ class AntigravityAdapter(_ProcessAdapter):
1157
1244
  return self._finalize_result(process, "".join(results), "".join(stderr_chunks), started, allow_empty)
1158
1245
 
1159
1246
  def _command(self, resume_session_ref: str | None) -> list[str]:
1160
- command = [self.executable, "--input-format", "stream-json", "--output-format", "stream-json", "--mode", "auto", "--dangerously-skip-permissions"]
1247
+ command = [self.executable, "--input-format", "stream-json", "--output-format", "stream-json", "--dangerously-skip-permissions"]
1161
1248
  if resume_session_ref:
1162
1249
  command.append("--conversation=" + resume_session_ref)
1163
1250
  # 文本打印模式不读 stdin;空 -p 开启事件模式,提示由标准输入的 user 事件传入。
@@ -18,7 +18,7 @@ sys.path.insert(0, str(Path(resources) / "lib"))
18
18
  PACKAGE = Path(__file__).resolve().parents[1]
19
19
  sys.path.insert(0, str(PACKAGE))
20
20
  # 适配器同 desktop_chat:用核心包自带的,随 npm 更新生效(2026-11-23)。
21
- from runtime.easyagents_core.tools import ClaudeCodeAdapter, CodexAdapter
21
+ from runtime.easyagents_core.tools import UnsupportedAdapter, get_adapter
22
22
  from runtime.easyagents_core.git_sync import GitError, GitWorkspace
23
23
  from runtime.platform_prompt import platform_entry
24
24
 
@@ -58,11 +58,8 @@ def run(request, cancelled):
58
58
  if isinstance(task.get("file_delivery"), dict):
59
59
  return failed("handoff_unsupported", "独立客户端只支持任务分支交付,不支持旧的同目录文件交付")
60
60
  tool = (content.get("agent") or {}).get("tool_type")
61
- if tool == "codex":
62
- adapter = CodexAdapter()
63
- elif tool == "claude_code":
64
- adapter = ClaudeCodeAdapter()
65
- else:
61
+ adapter = get_adapter(tool) if isinstance(tool, str) else UnsupportedAdapter(str(tool))
62
+ if isinstance(adapter, UnsupportedAdapter):
66
63
  return failed("unsupported_task", "此工具尚未接入独立客户端的任务运行")
67
64
  if not shutil.which(adapter.executable):
68
65
  return failed("tool_missing", "本机未找到 " + adapter.executable_name)