@unionschool/easy-agents 1.0.34 → 1.0.50

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
@@ -88,7 +88,7 @@ npm exec --offline -- easy-agents run
88
88
 
89
89
  - Mac 和 Ubuntu 安装包能接平台任务分支上的执行、审核、部署和澄清运行(Codex、Claude,完整权限,与旧 Python 客户端的规则一致):执行在任务分支上工作并在成功后推送;审核和部署检出本轮交付的提交;工作目录有未提交改动时,在客户端配置目录的 `worktrees/` 里另建工作树,原目录不动,合并后的成员同步会清理这些工作树。Agent 通过提示里给出的平台命令调用工具;Agent 凭据缺失或已被平台撤销时,客户端自动领取新凭据(平台会同时撤销旧凭据)。旧的同目录文件交付和用户发布命令(`publish`)不支持。工作台读取任务、需求文档(“阅读”抽屉)也由这两种设备应答,只读 Git,不切分支、不改工作区。
90
90
  - **未完成**:Windows、Android 和单独运行的普通 npm 版还不能接任务分支运行,会回报 `handoff_unsupported`。这几端暂时用不上(用户 2026-11-22 定),以后需要时再单独升级。
91
- - Mac 和 Ubuntu 安装包支持 Codex、Claude 的文本对话、续聊和本地文本任务。它们可从项目卡片或对话页接收聊天和工作消息。普通聊天是纯文本:Codex 只读会话、Claude 不开工具。工作消息(负责人与任务角色的对话、平台的流程通知)与任务运行一样用完整权限,带平台操作入口,Agent 凭据缺失或被撤销时自动领取,所以负责人能在对话里登记需求、发布任务、合并上报。可用的会话编号、模型与用量会随结果回传。
91
+ - Mac 和 Ubuntu 安装包支持 Codex、Claude 的文本对话、续聊和本地文本任务;Agy、Cursor 只接对话,不接任务运行(2026-11-23,1.0.34 起含 Cursor)。它们可从项目卡片或对话页接收聊天和工作消息。普通聊天是纯文本:Codex 只读会话、Claude 不开工具。工作消息(负责人与任务角色的对话、平台的流程通知)与任务运行一样用完整权限,带平台操作入口,Agent 凭据缺失或被撤销时自动领取,所以负责人能在对话里登记需求、发布任务、合并上报。可用的会话编号、模型与用量会随结果回传。
92
92
  - Mac 和 Windows 面板可显示检测到的 Codex、Claude、Cursor、Agy 登录和上报状态。平台控制额度上报开关,绿色胶囊显示已获得的剩余额度,测得零时显示零。Windows 和单独运行的普通 npm 版支持单次 Claude 文本任务,使用 bare 模式可用的认证。桌面对话功能需要安装包提供的工具适配和内置运行环境。
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 消息和用户选择目录里的计算文档。
@@ -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
@@ -20,6 +20,19 @@ const taskDelivery = () => Boolean(desktopResources());
20
20
  const DOC_READER = fileURLToPath(new URL('../runtime/doc_read.py', import.meta.url));
21
21
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
22
22
  const DOC_FAILED = { status: 'error', error: 'document_read_failed' };
23
+
24
+ // worker.log 每行带本机时间;运行没成功时写出失败代码和原因,本机就能查(2026-11-26,原先只有“已回传 failed”)。
25
+ const pad = n => String(n).padStart(2, '0');
26
+ export function stamped(text, now = new Date()) {
27
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())} ${text}`;
28
+ }
29
+ export function finishLine(id, result) {
30
+ const reason = [result.failure_code, String(result.failure_detail ?? '').replace(/\s+/g, ' ').trim().slice(0, 120)]
31
+ .filter(Boolean).join(':');
32
+ return '运行 ' + id + ' 已回传 ' + result.status + (result.status !== 'succeeded' && reason ? '(' + reason + ')' : '');
33
+ }
34
+ const info = text => console.log(stamped(text));
35
+ const warn = text => console.error(stamped(text));
23
36
  function readDocument(message, signal) {
24
37
  return new Promise(done => {
25
38
  const child = execFile(join(desktopResources(), 'python/bin/python3'), ['-I', '-B', '-X', 'utf8', DOC_READER],
@@ -123,7 +136,7 @@ export async function runDevice(device, configDir, version, signal, { reporter,
123
136
  if (typeof id !== 'string' || !UUID.test(id) || !desktopResources()) return;
124
137
  const body = await readDocument(msg, signal);
125
138
  try { await gatewayRequest('POST', '/api/client/documents/' + id, body); }
126
- catch { if (!signal.aborted) console.error('文档读取结果回传失败'); }
139
+ catch { if (!signal.aborted) warn('文档读取结果回传失败'); }
127
140
  }
128
141
  async function answerSteer(target, msg) {
129
142
  if (!UUID.test(msg.run_id || '') || !UUID.test(msg.message_id || '')) return;
@@ -185,7 +198,7 @@ export async function runDevice(device, configDir, version, signal, { reporter,
185
198
  await request('POST', id + '/finish', result);
186
199
  rmSync(join(folder, id + '.json'), { force: true });
187
200
  reporter?.patch({ lastResult: { id, status: result.status, at: Date.now() } });
188
- console.log('运行 ' + id + ' 已回传 ' + result.status);
201
+ info(finishLine(id, result));
189
202
  }
190
203
  function startQueue() {
191
204
  while (online && !signal.aborted && running.size < MAX_PARALLEL_RUNS) {
@@ -230,7 +243,7 @@ export async function runDevice(device, configDir, version, signal, { reporter,
230
243
  try { metadata = await reporter.hello(signal); }
231
244
  catch {
232
245
  if (signal.aborted) break;
233
- console.error('本机工具信息暂时不可用,正在重试');
246
+ warn('本机工具信息暂时不可用,正在重试');
234
247
  reporter.disconnect();
235
248
  await sleep(delay, undefined, { signal }).catch(() => {});
236
249
  delay = Math.min(60000, delay * 2);
@@ -238,10 +251,12 @@ export async function runDevice(device, configDir, version, signal, { reporter,
238
251
  }
239
252
  }
240
253
  if (signal.aborted) break;
241
- // steer(协议第 16 节):桌面版的 Claude、Codex、Agy 对话,以及 Claude、Codex 的任务运行(2026-11-23)支持运行中补充;纯 npm 不支持。
254
+ // steer(协议第 16 节):桌面版的 Claude、Codex、Agy 对话与任务运行支持运行中补充;纯 npm 不支持。
242
255
  // Cursor 实测只能取消当前一轮再发新的,不算补充(2026-11-23)。
243
- const steer = { claude_code: taskDelivery(), codex: taskDelivery(), cursor: false, antigravity: taskDelivery() };
244
- const hello = { type: 'hello', client_version: version, tools: [], terminal, task_delivery: taskDelivery(), doc_read: taskDelivery(), steer, ...metadata };
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 };
245
260
  let lastSeen = Date.now(), welcomed = false;
246
261
  socket = new WebSocket(wsUrl, { headers, followRedirects: false, handshakeTimeout: 15000, maxPayload: 1048576 });
247
262
  const current = socket;
@@ -260,7 +275,7 @@ export async function runDevice(device, configDir, version, signal, { reporter,
260
275
  if (msg.type !== 'welcome' || msg.device_id !== device.device_id) throw new Error();
261
276
  welcomed = online = true; delay = 1000;
262
277
  reporter?.welcome(hello, msg, reportQuota, () => current.terminate());
263
- console.log('设备已上线');
278
+ info('设备已上线');
264
279
  const pending = await request('GET', 'pending');
265
280
  if (current !== socket || current.readyState !== WebSocket.OPEN) return;
266
281
  for (const f of readdirSync(folder)) if (f.endsWith('.json')) enqueue(f.slice(0, -5));
@@ -290,7 +305,7 @@ export async function runDevice(device, configDir, version, signal, { reporter,
290
305
  for (const session of sessions.values()) session.terminate();
291
306
  }
292
307
  if (!signal.aborted && !fatal) {
293
- console.error('连接中断,正在重连');
308
+ warn('连接中断,正在重连');
294
309
  await sleep(delay, undefined, { signal }).catch(() => {});
295
310
  delay = Math.min(delay * 2, 60000);
296
311
  }
package/bin/tasks.js CHANGED
@@ -84,6 +84,7 @@ function desktopConversation(resources, content, prompt, signal, credential, too
84
84
  }
85
85
 
86
86
  const TASK_KINDS = ['execute', 'review', 'deploy', 'clarify'];
87
+ const DESKTOP_TASK_TOOLS = ['codex', 'claude_code', 'antigravity', 'cursor'];
87
88
 
88
89
  // Mac and Ubuntu desktop installs: Git task-branch runs go to the packaged Python runner.
89
90
  // 任务运行(执行、审核、部署、答疑):首行 JSON 是运行内容;之后 stdin 保持打开,任务对话里发给正在干活的人员的话
@@ -193,7 +194,7 @@ export async function execute(content, signal, workCredential, { agentCredential
193
194
  if (!resources || !agentCredential || !configDir) {
194
195
  return { status: 'failed', failure_code: 'handoff_unsupported', failure_detail: '任务分支运行目前只支持 Mac 和 Ubuntu 桌面版客户端' };
195
196
  }
196
- if (!['codex', 'claude_code'].includes(content.agent?.tool_type)) {
197
+ if (!DESKTOP_TASK_TOOLS.includes(content.agent?.tool_type)) {
197
198
  return { status: 'failed', failure_code: 'unsupported_task', failure_detail: '此工具尚未接入独立客户端的任务运行' };
198
199
  }
199
200
  let credential;
@@ -223,9 +224,7 @@ export async function execute(content, signal, workCredential, { agentCredential
223
224
  return { status: 'succeeded', reply_text: digest };
224
225
  }
225
226
  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')) {
227
+ if (resources && DESKTOP_TASK_TOOLS.includes(content.agent?.tool_type) && (task || content.run_kind === 'chat')) {
229
228
  let credential;
230
229
  // Same rule as the platform: only chat_mode 'chat' is a plain conversation. Workflow notifications to the lead
231
230
  // (merge after deploy, answers, sync handoff) arrive with an empty chat_mode and must be able to act.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unionschool/easy-agents",
3
- "version": "1.0.34",
3
+ "version": "1.0.50",
4
4
  "description": "EasyAgents",
5
5
  "easyAgentsDesktop": 1,
6
6
  "type": "module",
@@ -37,6 +37,48 @@ SUGGEST = ("回复末尾可以附两样东西,平台会拆出来单独展示
37
37
 
38
38
  NEW_SESSION_COMMANDS = ("/new", "/clear")
39
39
  NEW_SESSION_TEXT = "已开始新会话:智能体不再记得之前的内容,聊天记录仍保留。"
40
+ SOFT_COMPACT_TOOLS = ("antigravity", "cursor")
41
+ SOFT_COMPACT_SUMMARIZE = (
42
+ "请将我们当前会话的上下文精炼压缩成一份交接摘要(纯文本 Markdown,不超过 800 字),"
43
+ "只保留后续继续工作必需的信息:1. 当前目标与范围;2. 已确认的结论与决策;"
44
+ "3. 已改动或关键的文件路径;4. 尚未完成的待办。不要寒暄,不要执行修改命令。"
45
+ )
46
+ SOFT_COMPACT_SEED = (
47
+ "以下是上一阶段会话压缩后的交接摘要,请先记住作为后续对话的上下文背景,只需简短回复“已接续上下文”:\n\n"
48
+ )
49
+
50
+
51
+ def _format_result(result):
52
+ if result.reply_text and len(result.reply_text) > 1_000_000:
53
+ return failed("bad_output", "工具回复超过平台长度上限")
54
+ if isinstance(result.context, dict):
55
+ result.context = {**result.context, "compact_at": compact_at()}
56
+ fields = ("status", "reply_text", "tool_session_ref", "tool_version", "model_name",
57
+ "usage", "context", "failure_code", "failure_detail")
58
+ return {name: getattr(result, name) for name in fields if getattr(result, name) is not None}
59
+
60
+
61
+ def _soft_compact(adapter, cwd, resume, content, cancelled):
62
+ """Agy、Cursor 原生不支持 /compact:先在旧会话提炼交接摘要,再开新会话写入摘要拿回新会话号。"""
63
+ if not resume:
64
+ return {"status": "succeeded", "reply_text": "当前是新会话,无需压缩。"}
65
+ timeout = content["timeout"]
66
+ model = content.get("model")
67
+ summary_result = adapter.invoke(
68
+ prompt=SOFT_COMPACT_SUMMARIZE, cwd=cwd, resume_session_ref=resume,
69
+ timeout_seconds=timeout, cancel_event=cancelled, model=model,
70
+ )
71
+ if summary_result.status != "succeeded":
72
+ return _format_result(summary_result)
73
+ summary = (summary_result.reply_text or "").strip()
74
+ seed_result = adapter.invoke(
75
+ prompt=SOFT_COMPACT_SEED + summary, cwd=cwd, resume_session_ref=None,
76
+ timeout_seconds=timeout, cancel_event=cancelled, model=model,
77
+ )
78
+ if seed_result.status != "succeeded":
79
+ return _format_result(seed_result)
80
+ seed_result.reply_text = f"上下文已压缩,已开启新会话接续。\n\n**交接摘要**\n{summary}"
81
+ return _format_result(seed_result)
40
82
 
41
83
 
42
84
  def instructions_for(tool, tools, command):
@@ -134,19 +176,23 @@ def run(content, cancelled):
134
176
  options = {}
135
177
  elif tool == "antigravity":
136
178
  # Agy 对话(2026-11-23 接入独立客户端):聊天、工作同一套参数(T-158 聊天不限权限);运行中补充见适配器说明。
137
- # Agy 没有附加系统说明的参数,建议回复格式暂不告知。
179
+ # Agy 没有附加系统说明的参数,由下文拼在 prompt 头部。
138
180
  adapter = AntigravityAdapter()
139
181
  options = {}
140
182
  elif tool == "cursor":
141
- # Cursor 对话(2026-11-23:飞书私聊给 Cursor 发消息,独立客户端连回四次“不支持”):cursor-agent -p,
142
- # 聊天、工作同一套参数。没有附加系统说明的参数,建议回复格式暂不告知;不支持运行中补充(平台改为排队)。
183
+ # Cursor 对话(2026-11-23 接入):cursor-agent -p stream-json,聊天、工作同一套参数。
184
+ # 没有附加系统说明的参数,由下文拼在 prompt 头部;不支持运行中补充(平台改为排队)。
143
185
  adapter = CursorAdapter()
144
186
  options = {}
145
187
  else:
146
188
  return failed("unsupported_task", "此工具尚未接入设备文本对话")
189
+ if command in NEW_SESSION_COMMANDS and tool != "claude_code":
190
+ # 实测 Agy print mode 透传 /new 会 exit 2 报错,Cursor 当普通聊天文字,Codex 无斜杠命令;统一直接清空会话。
191
+ return {"status": "succeeded", "reply_text": NEW_SESSION_TEXT}
147
192
  if not shutil.which(adapter.executable):
148
193
  return failed("tool_missing", "本机未找到 " + adapter.executable_name)
149
- adapter.instructions = instructions_for(tool, tools, command) if tool not in ("antigravity", "cursor") else None
194
+ extra_instructions = instructions_for(tool, tools, command)
195
+ adapter.instructions = extra_instructions if tool not in ("antigravity", "cursor") else None
150
196
  if content.get("_on_adapter"):
151
197
  content["_on_adapter"](adapter)
152
198
 
@@ -166,6 +212,9 @@ def run(content, cancelled):
166
212
  cwd = Path(os.environ["EASYAGENTS_CONFIG_DIR"]) / "chat-workspace"
167
213
  cwd.mkdir(mode=0o700, parents=True, exist_ok=True)
168
214
 
215
+ if command == "/compact" and tool in SOFT_COMPACT_TOOLS:
216
+ return _soft_compact(adapter, cwd, resume, content, cancelled)
217
+
169
218
  prompt = content["prompt"]
170
219
  run_id = content.get("workRunId")
171
220
  if run_id and not content.get("passthrough"):
@@ -180,6 +229,8 @@ def run(content, cancelled):
180
229
  prompt = f"本次调度模式:platform;运行编号:{run_id}\n{guidance}\n\n{prompt}"
181
230
  if tools and content.get("credential"):
182
231
  prompt += platform_entry(content["credential"]["file"])
232
+ if extra_instructions and tool in ("antigravity", "cursor"):
233
+ prompt = f"[系统说明]\n{extra_instructions}\n[/系统说明]\n\n{prompt}"
183
234
  if command:
184
235
  options["allow_empty"] = True # /compact 成功时 Claude 不输出文字,回“命令已执行”
185
236
  result = adapter.invoke(prompt=prompt, cwd=cwd, resume_session_ref=resume,
@@ -188,13 +239,7 @@ def run(content, cancelled):
188
239
  if command in NEW_SESSION_COMMANDS and result.status == "succeeded" and result.reply_text == NO_OUTPUT_TEXT:
189
240
  # Claude 的 /new、/clear 会换一个空会话(会话号随回传更新),默认的“命令已执行”看不出发生了什么(用户 2026-11-23)。
190
241
  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}
242
+ return _format_result(result)
198
243
 
199
244
 
200
245
  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)