@unionschool/easy-agents 1.0.1 → 1.0.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1257 @@
1
+ """工具适配器:复用进程管理,按工具解析回复、会话与用量。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import os
8
+ import re
9
+ import signal
10
+ import subprocess
11
+ import sys
12
+ import threading
13
+ import time
14
+ from concurrent.futures import Future as ConcurrentFuture
15
+ from contextlib import suppress
16
+ from pathlib import Path
17
+ from shutil import which
18
+ from typing import Protocol
19
+ from uuid import UUID
20
+
21
+ from . import __version__
22
+ from .process_support import ToolResult, _start_kwargs, terminate_process_group
23
+
24
+
25
+ STEER_CAPABILITIES = {
26
+ "claude_code": True,
27
+ "codex": True,
28
+ "cursor": False, # 实测只能取消当前一轮再发新的,不算补充(2026-11-23)
29
+ "antigravity": True, # 当前一轮结束后同一进程接着处理(2026-11-23 接入)
30
+ }
31
+
32
+
33
+ class SteerError(RuntimeError):
34
+ """运行中补充消息失败,status 对应协议 run.steer.ack 状态。"""
35
+
36
+ def __init__(self, status: str, detail: str):
37
+ super().__init__(detail)
38
+ self.status = status
39
+ self.detail = detail
40
+
41
+
42
+ ACTIVITY_DETAIL_LIMIT = 300
43
+ _SECRET = re.compile(
44
+ r"""(?ix)(?:\b(?:sk-|ghp_)[\w.-]+|(?:\bBearer\s+|--token(?:\s+|=)|"""
45
+ r"""\b(?:[\w-]*(?:key|token|secret|password)[\w-]*)\s*=\s*)"""
46
+ r"""(?:"(?:\\.|[^"\\])*(?:"|$)|'(?:[^'])*(?:'|$)|[^\s;&|]+))"""
47
+ )
48
+
49
+
50
+ def activity_detail(value) -> tuple[str, bool]:
51
+ if not isinstance(value, str):
52
+ return '', False
53
+ text = ' '.join(_SECRET.sub('***', value).split())
54
+ return text[:ACTIVITY_DETAIL_LIMIT], len(text) > ACTIVITY_DETAIL_LIMIT
55
+
56
+
57
+ def _activities(tool, event):
58
+ if not isinstance(event, dict):
59
+ return
60
+ if tool == 'claude_code' and event.get('type') == 'assistant':
61
+ message = event.get('message')
62
+ blocks = message.get('content') if isinstance(message, dict) else None
63
+ for block in blocks if isinstance(blocks, list) else ():
64
+ if not isinstance(block, dict):
65
+ continue
66
+ kind = block.get('type')
67
+ if kind == 'tool_use':
68
+ name = block.get('name')
69
+ args = block.get('input')
70
+ args = args if isinstance(args, dict) else {}
71
+ mapping = {'Bash': ('command', 'command'), 'Read': ('read', 'file_path'),
72
+ 'Edit': ('edit', 'file_path'), 'Write': ('edit', 'file_path'),
73
+ 'MultiEdit': ('edit', 'file_path'), 'Glob': ('search', 'pattern'),
74
+ 'Grep': ('search', 'pattern'), 'WebSearch': ('search', 'query')}
75
+ category, field = mapping.get(name, ('tool', None)) if isinstance(name, str) else ('other', None)
76
+ yield (category, *activity_detail(args.get(field) if field else name))
77
+ elif kind in ('thinking', 'redacted_thinking', 'text'):
78
+ yield ('reply' if kind == 'text' else 'thinking'), '', False
79
+ elif tool == 'codex' and event.get('method') in ('item/started', 'item/completed'):
80
+ item = event.get('item')
81
+ if not isinstance(item, dict):
82
+ return
83
+ kind = item.get('type')
84
+ if kind == 'fileChange':
85
+ changes = item.get('changes')
86
+ first = changes[0] if isinstance(changes, list) and changes else None
87
+ yield ('edit', *activity_detail(first.get('path') if isinstance(first, dict) else ''))
88
+ elif isinstance(kind, str):
89
+ category, field = {'commandExecution': ('command', 'command'), 'webSearch': ('search', 'query'),
90
+ 'mcpToolCall': ('tool', 'tool'), 'reasoning': ('thinking', None),
91
+ 'agentMessage': ('reply', None)}.get(kind, ('other', None))
92
+ yield (category, *activity_detail(item.get(field)))
93
+
94
+
95
+ # 斜杠命令成功但工具不输出文字时的回复(用户 2026-11-23 去掉了“(无输出)”)。
96
+ NO_OUTPUT_TEXT = "命令已执行"
97
+
98
+ class ToolAdapter(Protocol):
99
+ tool_type: str
100
+
101
+ def version(self) -> str | None: ...
102
+
103
+ def invoke(
104
+ self,
105
+ *,
106
+ prompt: str,
107
+ cwd: Path,
108
+ resume_session_ref: str | None,
109
+ timeout_seconds: int,
110
+ cancel_event: threading.Event,
111
+ on_started=None,
112
+ on_activity=None,
113
+ model: str | None = None,
114
+ platform_run_id: str | None = None,
115
+ ) -> ToolResult: ...
116
+
117
+
118
+ def _usage_from_payload(payload: dict) -> dict:
119
+ usage = payload.get("usage")
120
+ if not isinstance(usage, dict):
121
+ return {
122
+ "measurement_kind": "unavailable",
123
+ "input_tokens": None,
124
+ "output_tokens": None,
125
+ "cached_input_tokens": None,
126
+ "total_tokens": None,
127
+ "cost_amount": None,
128
+ "currency": None,
129
+ }
130
+ def count(*keys):
131
+ value = next((usage[k] for k in keys if k in usage), None)
132
+ return value if type(value) is int and value >= 0 else None
133
+
134
+ input_tokens = count("input_tokens", "inputTokens")
135
+ output_tokens = count("output_tokens", "outputTokens")
136
+ cached = count("cache_read_input_tokens", "cached_input_tokens", "cacheReadTokens", "cache_read_tokens", "cachedInputTokens")
137
+ written = count("cache_creation_input_tokens", "cache_write_input_tokens", "cache_write_tokens", "cacheWriteTokens", "cacheWriteInputTokens")
138
+ # Codex/Cursor 的 input 已含缓存;统一存为未缓存输入,展示时再合并一次。
139
+ if (payload.get("_input_includes_cache") or "inputTokens" in usage) and input_tokens is not None and cached is not None:
140
+ input_tokens = max(0, input_tokens - cached - (written or 0))
141
+ total = count("total_tokens", "totalTokens")
142
+ if total is None and input_tokens is not None and output_tokens is not None:
143
+ total = input_tokens + output_tokens + (cached or 0) + (written or 0)
144
+ return dict(measurement_kind="actual" if any(v is not None for v in (input_tokens, output_tokens, cached, written, total)) else "unavailable",
145
+ input_tokens=input_tokens, output_tokens=output_tokens, cached_input_tokens=cached,
146
+ cache_write_tokens=written, total_tokens=total,
147
+ cost_amount=usage.get("cost_amount") if isinstance(usage.get("cost_amount"), (int, float)) else None,
148
+ currency=usage.get("currency") if isinstance(usage.get("currency"), str) else None)
149
+
150
+
151
+ def _context_from_payload(payload: dict) -> dict | None:
152
+ if payload.get("_context"):
153
+ return payload["_context"]
154
+ usage = payload.get("usage")
155
+ iterations = usage.get("iterations") if isinstance(usage, dict) else None
156
+ last = iterations[-1] if isinstance(iterations, list) and iterations else None
157
+ tokens = None
158
+ if isinstance(last, dict):
159
+ values = [last.get(k, 0) for k in ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens")]
160
+ if all(type(v) is int and v >= 0 for v in values):
161
+ tokens = sum(values)
162
+ models = payload.get("modelUsage")
163
+ models = models if isinstance(models, dict) else {}
164
+ # 多模型时仅取明确匹配的模型;窗口相同也可安全取值。
165
+ windows = {v.get("contextWindow") for v in models.values() if isinstance(v, dict) and type(v.get("contextWindow")) is int and v["contextWindow"] >= 0}
166
+ model = models.get(_model_name(payload), {})
167
+ window = model.get("contextWindow") if isinstance(model, dict) else None
168
+ if type(window) is not int or window < 0:
169
+ window = next(iter(windows)) if len(windows) == 1 else None
170
+ return {"tokens": tokens, "window": window} if tokens is not None or window is not None else None
171
+
172
+
173
+ def _model_name(payload: dict) -> str | None:
174
+ models = payload.get("modelUsage")
175
+ if isinstance(models, dict):
176
+ scores = {}
177
+ for name, usage in models.items():
178
+ if isinstance(name, str) and isinstance(usage, dict):
179
+ scores[name] = sum(v for k, v in usage.items() if k in (
180
+ "inputTokens", "outputTokens", "cacheReadInputTokens", "cacheCreationInputTokens",
181
+ "input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens") and type(v) is int and v >= 0)
182
+ if scores and (len(scores) == 1 or max(scores.values()) > 0):
183
+ return max(scores, key=scores.get)
184
+ for key in ("model", "model_name", "modelName"):
185
+ value = payload.get(key)
186
+ if isinstance(value, str) and value:
187
+ return value
188
+ return None
189
+
190
+
191
+ def _invocation_env(cwd: Path, model: str | None, platform_run_id: str | None) -> dict | ToolResult:
192
+ if not cwd.is_dir():
193
+ return ToolResult(status="failed", failure_code="workspace_missing", failure_detail="工作目录不存在")
194
+ if model is not None and (not isinstance(model, str) or not model.strip() or len(model) > 128
195
+ or any(ord(c) < 32 or ord(c) == 127 for c in model)):
196
+ return ToolResult(status="failed", failure_code="bad_model", failure_detail="模型名称无效")
197
+ env = os.environ.copy()
198
+ if platform_run_id is not None:
199
+ if not isinstance(platform_run_id, str) or not platform_run_id.strip():
200
+ return ToolResult(status="failed", failure_code="bad_dispatch_context",
201
+ failure_detail="平台调度缺少运行编号")
202
+ env.update(EASYAGENTS_DISPATCH_MODE="platform", EASYAGENTS_RUN_ID=platform_run_id)
203
+ elif env.get("EASYAGENTS_DISPATCH_MODE") == "platform":
204
+ if not env.get("EASYAGENTS_RUN_ID", "").strip():
205
+ return ToolResult(status="failed", failure_code="bad_dispatch_context", failure_detail="平台调度缺少运行编号")
206
+ env.pop("EASYAGENTS_DISPATCH_MODE")
207
+ env.pop("EASYAGENTS_RUN_ID")
208
+ return env
209
+
210
+
211
+ class _ProcessAdapter:
212
+ executable_name: str
213
+ # 附加的系统级说明(对话用:聊天模式无工具提示、建议回复格式);Claude 走 --append-system-prompt,
214
+ # Codex 走 thread/start、thread/resume 的 developerInstructions(2026-11-23)。
215
+ instructions: str | None = None
216
+
217
+ def __init__(self, executable: str | None = None):
218
+ self.executable = executable or which(self.executable_name) or self.executable_name
219
+
220
+ def _command(self, resume_session_ref: str | None) -> list[str]:
221
+ raise NotImplementedError
222
+
223
+ def _payload(self, raw: str) -> dict:
224
+ return json.loads(raw)
225
+
226
+ def _input(self, prompt: str) -> str:
227
+ return prompt
228
+
229
+ def steer(self, text: str):
230
+ raise SteerError("unsupported", "该工具暂不支持补充消息")
231
+
232
+ def version(self) -> str | None:
233
+ try:
234
+ completed = subprocess.run(
235
+ [self.executable, "--version"],
236
+ check=False,
237
+ capture_output=True,
238
+ text=True,
239
+ timeout=10,
240
+ )
241
+ except (OSError, subprocess.SubprocessError):
242
+ return None
243
+ if completed.returncode != 0:
244
+ return None
245
+ text = (completed.stdout or completed.stderr or "").strip()
246
+ return text.splitlines()[0] if text else None
247
+
248
+ def invoke(
249
+ self,
250
+ *,
251
+ prompt: str,
252
+ cwd: Path,
253
+ resume_session_ref: str | None,
254
+ timeout_seconds: int,
255
+ cancel_event: threading.Event,
256
+ on_started=None,
257
+ on_activity=None,
258
+ model: str | None = None,
259
+ allow_empty: bool = False,
260
+ platform_run_id: str | None = None,
261
+ ) -> ToolResult:
262
+ env = _invocation_env(cwd, model, platform_run_id)
263
+ if isinstance(env, ToolResult):
264
+ return env
265
+ command = self._command(resume_session_ref)
266
+ if model is not None:
267
+ command[1:1] = ["--model", model]
268
+ started = time.monotonic()
269
+ try:
270
+ process = subprocess.Popen(
271
+ command,
272
+ cwd=str(cwd),
273
+ env=env,
274
+ stdin=subprocess.PIPE,
275
+ stdout=subprocess.PIPE,
276
+ stderr=subprocess.PIPE,
277
+ text=True,
278
+ **_start_kwargs(),
279
+ )
280
+ except OSError:
281
+ return ToolResult(
282
+ status="failed",
283
+ failure_code="tool_start_failed",
284
+ failure_detail="无法启动工具",
285
+ elapsed_seconds=time.monotonic() - started,
286
+ )
287
+ if on_started is not None:
288
+ on_started(process.pid)
289
+
290
+ # stdout 单独逐行消费;communicate 仍负责并发写 stdin、排空 stderr 和超时回收。
291
+ lines = []
292
+ reader = None
293
+ if self.tool_type == 'claude_code':
294
+ output, process.stdout = process.stdout, None
295
+
296
+ def read_events():
297
+ with output:
298
+ for line in output:
299
+ try:
300
+ event = json.loads(line)
301
+ except ValueError:
302
+ event = None
303
+ # Claude verbose 也输出提示、工具入参和结果;沿用原日志范围,仅保留最终结果。
304
+ if isinstance(event, dict) and ('type' not in event or event['type'] == 'result'):
305
+ lines[:] = [line]
306
+ if on_activity:
307
+ for activity in _activities(self.tool_type, event):
308
+ on_activity(activity)
309
+
310
+ reader = threading.Thread(target=read_events, daemon=True)
311
+ reader.start()
312
+
313
+ # communicate 边写提示边读输出;只轮询等待会在输出超过管道缓冲(约64KB)时让工具卡住写不出去。
314
+ # 首次调用传入提示,超时后再调用会接着之前的读写继续。
315
+ deadline = started + max(1, int(timeout_seconds))
316
+ pending_input: str | None = self._input(prompt)
317
+ communicated = False
318
+ while True:
319
+ try:
320
+ if not communicated:
321
+ stdout, stderr = process.communicate(input=pending_input, timeout=0.2)
322
+ communicated = True
323
+ if reader:
324
+ reader.join(timeout=0.2)
325
+ if reader is None or not reader.is_alive():
326
+ break
327
+ except subprocess.TimeoutExpired:
328
+ pending_input = None
329
+ except (OSError, ValueError):
330
+ terminate_process_group(process)
331
+ return ToolResult(
332
+ status="failed",
333
+ failure_code="tool_stdin_failed",
334
+ failure_detail="无法写入提示",
335
+ elapsed_seconds=time.monotonic() - started,
336
+ )
337
+ stopped = None
338
+ if cancel_event.is_set():
339
+ stopped = ("cancelled", "cancelled", "已取消")
340
+ elif time.monotonic() >= deadline:
341
+ stopped = ("failed", "timeout", "超时")
342
+ if stopped:
343
+ terminate_process_group(process)
344
+ if not communicated:
345
+ stdout, stderr = _collect_after_stop(process)
346
+ if reader:
347
+ reader.join(timeout=2)
348
+ stdout = "".join(lines)
349
+ return ToolResult(
350
+ status=stopped[0],
351
+ failure_code=stopped[1],
352
+ failure_detail=stopped[2],
353
+ exit_code=process.poll(),
354
+ raw_output=stdout or stderr or "",
355
+ elapsed_seconds=time.monotonic() - started,
356
+ )
357
+
358
+ if reader:
359
+ stdout = "".join(lines)
360
+ return self._finalize_result(process, stdout, stderr, started, allow_empty)
361
+
362
+ def _finalize_result(
363
+ self,
364
+ process: subprocess.Popen,
365
+ stdout: str | None,
366
+ stderr: str | None,
367
+ started: float,
368
+ allow_empty: bool,
369
+ ) -> ToolResult:
370
+ stdout, stderr = stdout or "", stderr or ""
371
+ raw = stdout
372
+ elapsed = time.monotonic() - started
373
+ version = self.version()
374
+ if process.returncode != 0:
375
+ detail = _nonzero_detail(stderr, stdout)
376
+ return ToolResult(
377
+ status="failed",
378
+ failure_code="tool_exit",
379
+ failure_detail=detail,
380
+ tool_version=version,
381
+ exit_code=process.returncode,
382
+ raw_output=raw or stderr or "",
383
+ elapsed_seconds=elapsed,
384
+ )
385
+ try:
386
+ payload = self._payload(raw)
387
+ except (ValueError, TypeError):
388
+ return ToolResult(
389
+ status="failed",
390
+ failure_code="bad_output",
391
+ failure_detail="工具输出无法解析",
392
+ tool_version=version,
393
+ exit_code=process.returncode,
394
+ raw_output=raw,
395
+ elapsed_seconds=elapsed,
396
+ )
397
+ if not isinstance(payload, dict):
398
+ return ToolResult(
399
+ status="failed",
400
+ failure_code="bad_output",
401
+ failure_detail="工具输出无法解析",
402
+ tool_version=version,
403
+ exit_code=process.returncode,
404
+ raw_output=raw,
405
+ elapsed_seconds=elapsed,
406
+ )
407
+ result_text = payload.get("result")
408
+ session_id = payload.get("session_id")
409
+ if payload.get("is_error"):
410
+ return ToolResult(
411
+ status="failed", failure_code="tool_error", failure_detail="工具返回错误",
412
+ tool_version=version, exit_code=process.returncode, raw_output=raw,
413
+ elapsed_seconds=elapsed,
414
+ )
415
+ if allow_empty and isinstance(result_text, str) and not result_text.strip():
416
+ result_text = NO_OUTPUT_TEXT # 如 /compact 成功时工具不输出文字
417
+ if not isinstance(result_text, str) or not result_text.strip() or not isinstance(session_id, str) or not session_id:
418
+ return ToolResult(
419
+ status="failed", failure_code="bad_output", failure_detail="工具未返回有效回复或会话",
420
+ tool_version=version, exit_code=process.returncode, raw_output=raw,
421
+ elapsed_seconds=elapsed,
422
+ )
423
+ return ToolResult(
424
+ status="succeeded",
425
+ reply_text=result_text if isinstance(result_text, str) else None,
426
+ tool_session_ref=session_id if isinstance(session_id, str) else None,
427
+ tool_version=version,
428
+ model_name=_model_name(payload),
429
+ usage=_usage_from_payload(payload),
430
+ context=_context_from_payload(payload),
431
+ exit_code=process.returncode,
432
+ raw_output=raw,
433
+ elapsed_seconds=elapsed,
434
+ )
435
+
436
+
437
+ class ClaudeCodeAdapter(_ProcessAdapter):
438
+ tool_type = "claude_code"
439
+ executable_name = "claude"
440
+
441
+ def __init__(self, executable: str | None = None):
442
+ super().__init__(executable)
443
+ self._stdin_lock = threading.Lock()
444
+ self._steer_lock = threading.Lock()
445
+ self._active_stdin = None
446
+ self._accepting_steer = False
447
+
448
+ def _command(self, resume_session_ref: str | None) -> list[str]:
449
+ command = [
450
+ self.executable, "-p",
451
+ "--input-format", "stream-json",
452
+ "--output-format", "stream-json",
453
+ "--verbose",
454
+ "--dangerously-skip-permissions",
455
+ ]
456
+ if self.instructions:
457
+ command += ["--append-system-prompt", self.instructions]
458
+ return command + (["--resume", resume_session_ref] if resume_session_ref else [])
459
+
460
+ def _input(self, prompt: str) -> str:
461
+ return json.dumps({"type": "user", "message": {"role": "user", "content": prompt}}, ensure_ascii=False) + "\n"
462
+
463
+ def _close_stdin(self) -> None:
464
+ with self._stdin_lock:
465
+ self._accepting_steer = False
466
+ stream = self._active_stdin
467
+ self._active_stdin = None
468
+ if stream is not None:
469
+ with suppress(OSError, ValueError):
470
+ stream.close()
471
+
472
+ def steer(self, text: str) -> None:
473
+ if not isinstance(text, str) or not text.strip():
474
+ raise ValueError("补充消息不能为空")
475
+ remaining = memoryview(self._input(text).encode("utf-8"))
476
+ deadline = time.monotonic() + 0.5
477
+ with self._stdin_lock:
478
+ stream = self._active_stdin
479
+ if not self._accepting_steer or stream is None:
480
+ raise SteerError("too_late", "当前回复已结束")
481
+ if not self._steer_lock.acquire(timeout=max(0, deadline - time.monotonic())):
482
+ raise SteerError("failed", "补充消息写入超时")
483
+ written = 0
484
+ try:
485
+ while remaining and time.monotonic() < deadline:
486
+ with self._stdin_lock:
487
+ if not self._accepting_steer or self._active_stdin is not stream:
488
+ raise SteerError("too_late", "当前回复已结束")
489
+ try:
490
+ count = os.write(stream.fileno(), remaining)
491
+ except BlockingIOError:
492
+ count = 0
493
+ except (BrokenPipeError, ValueError):
494
+ raise SteerError("too_late", "当前回复已结束") from None
495
+ except OSError:
496
+ raise SteerError("failed", "无法发送补充消息") from None
497
+ if count:
498
+ written += count
499
+ remaining = remaining[count:]
500
+ else:
501
+ time.sleep(0.01)
502
+ if remaining:
503
+ raise SteerError("failed", "补充消息写入超时")
504
+ finally:
505
+ if written and remaining:
506
+ # An incomplete NDJSON frame cannot be followed by another message.
507
+ with self._stdin_lock:
508
+ if self._active_stdin is stream:
509
+ self._active_stdin = None
510
+ self._accepting_steer = False
511
+ with suppress(OSError, ValueError):
512
+ stream.close()
513
+ self._steer_lock.release()
514
+
515
+ def invoke(
516
+ self,
517
+ *,
518
+ prompt: str,
519
+ cwd: Path,
520
+ resume_session_ref: str | None,
521
+ timeout_seconds: int,
522
+ cancel_event: threading.Event,
523
+ on_started=None,
524
+ on_activity=None,
525
+ model: str | None = None,
526
+ allow_empty: bool = False,
527
+ platform_run_id: str | None = None,
528
+ ) -> ToolResult:
529
+ env = _invocation_env(cwd, model, platform_run_id)
530
+ if isinstance(env, ToolResult):
531
+ return env
532
+ command = self._command(resume_session_ref)
533
+ if model is not None:
534
+ command[1:1] = ["--model", model]
535
+ started = time.monotonic()
536
+ try:
537
+ process = subprocess.Popen(
538
+ command,
539
+ cwd=str(cwd),
540
+ env=env,
541
+ stdin=subprocess.PIPE,
542
+ stdout=subprocess.PIPE,
543
+ stderr=subprocess.PIPE,
544
+ text=True,
545
+ bufsize=1,
546
+ **_start_kwargs(),
547
+ )
548
+ except OSError:
549
+ return ToolResult(
550
+ status="failed",
551
+ failure_code="tool_start_failed",
552
+ failure_detail="无法启动工具",
553
+ elapsed_seconds=time.monotonic() - started,
554
+ )
555
+ if on_started is not None:
556
+ on_started(process.pid)
557
+
558
+ lines: list[str] = []
559
+ stderr_chunks: list[str] = []
560
+ output, process.stdout = process.stdout, None
561
+ err_stream, process.stderr = process.stderr, None
562
+ stdin_stream, process.stdin = process.stdin, None
563
+
564
+ with self._stdin_lock:
565
+ self._active_stdin = stdin_stream
566
+ self._accepting_steer = False
567
+
568
+ seen = {} # 运行中见到的会话号:被 /stop 停下时也回传,下一条消息续接同一会话(docs/消息链路.md 第 3.2 节)
569
+
570
+ def read_events():
571
+ with output:
572
+ for line in output:
573
+ try:
574
+ event = json.loads(line)
575
+ except ValueError:
576
+ event = None
577
+ if isinstance(event, dict) and isinstance(event.get('session_id'), str):
578
+ seen['session'] = event['session_id']
579
+ # Claude verbose 也输出提示、工具入参和结果;沿用原日志范围,仅保留最终结果。
580
+ if isinstance(event, dict) and ('type' not in event or event['type'] == 'result'):
581
+ lines[:] = [line]
582
+ # 收到结果事件后立刻停止接收补充并关闭 stdin,让进程干净退出。
583
+ self._close_stdin()
584
+ if on_activity:
585
+ for activity in _activities(self.tool_type, event):
586
+ on_activity(activity)
587
+
588
+ def read_stderr():
589
+ with err_stream:
590
+ while chunk := err_stream.read(8192):
591
+ stderr_chunks.append(chunk)
592
+
593
+ reader = threading.Thread(target=read_events, daemon=True)
594
+ err_reader = threading.Thread(target=read_stderr, daemon=True)
595
+ reader.start()
596
+ err_reader.start()
597
+
598
+ try:
599
+ initial = self._input(prompt)
600
+ with self._stdin_lock:
601
+ if self._active_stdin is not None and not self._active_stdin.closed:
602
+ self._active_stdin.write(initial)
603
+ self._active_stdin.flush()
604
+ fd = self._active_stdin.fileno()
605
+ if os.name == "nt" and sys.version_info < (3, 12):
606
+ import ctypes
607
+ import msvcrt
608
+ mode = ctypes.c_ulong(1) # PIPE_NOWAIT
609
+ handle = ctypes.c_void_p(msvcrt.get_osfhandle(fd))
610
+ self._accepting_steer = bool(ctypes.windll.kernel32.SetNamedPipeHandleState(
611
+ handle, ctypes.byref(mode), None, None))
612
+ else:
613
+ os.set_blocking(fd, False)
614
+ self._accepting_steer = True
615
+ except (OSError, ValueError):
616
+ # 某些非零退出的 CLI 在读 stdin 前就会退出;若进程已退出或已有输出,按退出处理。
617
+ if process.poll() is None and not lines:
618
+ self._close_stdin()
619
+ terminate_process_group(process)
620
+ reader.join(timeout=2)
621
+ err_reader.join(timeout=2)
622
+ return ToolResult(
623
+ status="failed",
624
+ failure_code="tool_stdin_failed",
625
+ failure_detail="无法写入提示",
626
+ elapsed_seconds=time.monotonic() - started,
627
+ )
628
+
629
+ deadline = started + max(1, int(timeout_seconds))
630
+ try:
631
+ while True:
632
+ stopped = None
633
+ if cancel_event.is_set():
634
+ stopped = ("cancelled", "cancelled", "已取消")
635
+ elif time.monotonic() >= deadline:
636
+ stopped = ("failed", "timeout", "超时")
637
+ if stopped:
638
+ self._close_stdin()
639
+ terminate_process_group(process)
640
+ reader.join(timeout=2)
641
+ err_reader.join(timeout=2)
642
+ return ToolResult(
643
+ status=stopped[0],
644
+ failure_code=stopped[1],
645
+ failure_detail=stopped[2],
646
+ tool_session_ref=seen.get('session') if stopped[0] == "cancelled" else None,
647
+ exit_code=process.poll(),
648
+ raw_output="".join(lines) or "".join(stderr_chunks) or "",
649
+ elapsed_seconds=time.monotonic() - started,
650
+ )
651
+ try:
652
+ process.wait(timeout=0.05)
653
+ except subprocess.TimeoutExpired:
654
+ continue
655
+ if not reader.is_alive() and not err_reader.is_alive():
656
+ break
657
+ reader.join(timeout=0.1)
658
+ err_reader.join(timeout=0.1)
659
+ if not reader.is_alive() and not err_reader.is_alive():
660
+ break
661
+ finally:
662
+ self._close_stdin()
663
+
664
+ reader.join(timeout=2)
665
+ err_reader.join(timeout=2)
666
+ return self._finalize_result(process, "".join(lines), "".join(stderr_chunks), started, allow_empty)
667
+
668
+
669
+
670
+ _CODEX_UPGRADE = "Codex app-server 不可用,请安装或升级 Codex CLI(已验证 0.169.0)"
671
+ _CODEX_PROTOCOL = "Codex app-server 协议响应无效"
672
+
673
+
674
+ class _CodexFailure(Exception):
675
+ def __init__(self, code, detail):
676
+ self.code = code
677
+ self.detail = detail
678
+
679
+
680
+ class _CodexTurn:
681
+ def __init__(self, process, on_activity):
682
+ self.process = process
683
+ self.on_activity = on_activity
684
+ self.loop = asyncio.get_running_loop()
685
+ self.requests: dict[int, asyncio.Future] = {}
686
+ self.request_id = 0
687
+ self.version = self.thread_id = self.turn_id = self.model = None
688
+ self.completed = asyncio.Event()
689
+ self.turn_status = None
690
+ self.initialized = False
691
+ self.reply = None
692
+ self.token_usage = {}
693
+ self.error_detail = None
694
+ self.accepting_steer = False
695
+ self.instructions = None
696
+
697
+ async def send(self, message):
698
+ self.process.stdin.write((json.dumps(message) + "\n").encode())
699
+ await self.process.stdin.drain()
700
+
701
+ async def request(self, method, params):
702
+ # 同一读取循环处理通知和多条请求的响应,包括运行中提交的 steer。
703
+ self.request_id += 1
704
+ request_id = self.request_id
705
+ future = self.requests[request_id] = self.loop.create_future()
706
+ try:
707
+ await self.send({"id": request_id, "method": method, "params": params})
708
+ return await future
709
+ finally:
710
+ self.requests.pop(request_id, None)
711
+
712
+ async def read(self):
713
+ while line := await self.process.stdout.readline():
714
+ message = json.loads(line)
715
+ if not isinstance(message, dict):
716
+ raise ValueError(_CODEX_PROTOCOL)
717
+ method = message.get("method")
718
+ if "id" in message:
719
+ if isinstance(method, str):
720
+ await self.send({"id": message["id"], "error": {"code": -32601, "message": "Unsupported server request"}})
721
+ continue
722
+ identifier = message["id"]
723
+ if type(identifier) is not int or ("result" in message) == ("error" in message):
724
+ raise ValueError(_CODEX_PROTOCOL)
725
+ future = self.requests.get(identifier)
726
+ if future and not future.done():
727
+ future.set_result(message)
728
+ await asyncio.sleep(0) # 请求方先接收响应,再处理随后到达的通知。
729
+ continue
730
+ if not isinstance(method, str) or not isinstance(message.get("params", {}), dict):
731
+ raise ValueError(_CODEX_PROTOCOL)
732
+ self.event(method, message.get("params", {}))
733
+ await asyncio.sleep(0) # 已收到的最终响应先交给等待者,再报告 EOF。
734
+ raise EOFError
735
+
736
+ def event(self, method, params):
737
+ if not self.thread_id or params.get("threadId") != self.thread_id:
738
+ return
739
+ event_turn_id = params["turn"]["id"] if method in ("turn/started", "turn/completed") else params.get("turnId")
740
+ if method == "turn/started" and self.turn_id is None:
741
+ self.turn_id = event_turn_id
742
+ if not self.turn_id or event_turn_id != self.turn_id:
743
+ return
744
+ if method == "turn/completed":
745
+ self.accepting_steer = False
746
+ self.turn_status = params["turn"]["status"]
747
+ self.completed.set()
748
+ elif method == "thread/tokenUsage/updated":
749
+ self.token_usage = params["tokenUsage"]
750
+ elif method == "model/rerouted":
751
+ model = params.get("toModel")
752
+ if not isinstance(model, str) or not model:
753
+ raise ValueError(_CODEX_PROTOCOL)
754
+ self.model = model
755
+ elif method == "error" and not params.get("willRetry"):
756
+ self.error_detail = _nonzero_detail(params["error"].get("message"), "")
757
+ if self.error_detail == "工具非零退出":
758
+ self.error_detail = "Codex 回合失败"
759
+ elif method in ("item/started", "item/completed"):
760
+ item = params["item"]
761
+ if method == "item/completed" and item.get("type") == "agentMessage":
762
+ self.reply = item.get("text")
763
+ if self.on_activity:
764
+ for activity in _activities("codex", {"method": method, "item": item}):
765
+ self.on_activity(activity)
766
+
767
+ async def result(self, method, params, failure_code, failure_detail):
768
+ response = await self.request(method, params)
769
+ if "error" in response:
770
+ error = response["error"]
771
+ if not isinstance(error, dict) or type(error.get("code")) is not int:
772
+ raise ValueError(_CODEX_PROTOCOL)
773
+ if error["code"] == -32601 and method in ("thread/start", "thread/resume", "turn/start"):
774
+ raise _CodexFailure("tool_start_failed", _CODEX_UPGRADE)
775
+ raise _CodexFailure(failure_code, failure_detail)
776
+ result = response["result"]
777
+ if not isinstance(result, dict):
778
+ raise ValueError(_CODEX_PROTOCOL)
779
+ return result
780
+
781
+ async def run(self, prompt, cwd, resume, model, sandbox_policy, allow_empty, compact=False):
782
+ initialized = await self.result("initialize", {"clientInfo": {
783
+ "name": "easyagents", "version": __version__,
784
+ }}, "tool_start_failed", _CODEX_UPGRADE)
785
+ self.initialized = True
786
+ agent = initialized.get("userAgent")
787
+ match = re.match(r"easyagents/([0-9]+\.[0-9]+\.[0-9]+(?:[-+][a-zA-Z0-9.-]+)?)(?:\s|$)", agent or "")
788
+ self.version = "codex-cli " + match[1] if match else None
789
+ await self.send({"method": "initialized"})
790
+
791
+ thread_sandbox = {"readOnly": "read-only", "workspaceWrite": "workspace-write"}.get(
792
+ sandbox_policy.get("type"), "danger-full-access")
793
+ params = {"cwd": str(cwd.resolve()), "sandbox": thread_sandbox, "approvalPolicy": "never"}
794
+ if self.instructions:
795
+ params["developerInstructions"] = self.instructions
796
+ if model is not None:
797
+ params["model"] = model
798
+ if resume:
799
+ params.update(threadId=resume, excludeTurns=True)
800
+ thread = await self.result("thread/resume" if resume else "thread/start", params,
801
+ "bad_session" if resume else "tool_error",
802
+ "Codex 无法恢复指定会话" if resume else "Codex 无法创建会话")
803
+ self.thread_id = thread["thread"]["id"]
804
+ if resume and UUID(self.thread_id) != UUID(resume):
805
+ raise ValueError(_CODEX_PROTOCOL)
806
+ UUID(self.thread_id)
807
+ self.model = _model_name(thread)
808
+ if compact:
809
+ return await self.compact()
810
+ turn_params = {"threadId": self.thread_id, "input": [{"type": "text", "text": prompt}],
811
+ "approvalPolicy": "never", "sandboxPolicy": sandbox_policy}
812
+ if model is not None:
813
+ turn_params["model"] = model
814
+ started = await self.result("turn/start", turn_params, "tool_error", "Codex 无法开始回合")
815
+ turn_id = started["turn"]["id"]
816
+ if not isinstance(turn_id, str) or not turn_id or self.turn_id not in (None, turn_id):
817
+ raise ValueError(_CODEX_PROTOCOL)
818
+ self.turn_id = turn_id
819
+ self.accepting_steer = not self.completed.is_set()
820
+ await self.completed.wait()
821
+ status = self.turn_status
822
+ if status == "interrupted":
823
+ raise _CodexFailure("cancelled", "已取消")
824
+ if self.error_detail or status == "failed":
825
+ raise _CodexFailure("tool_error", self.error_detail or "Codex 回合失败")
826
+ if status != "completed":
827
+ raise ValueError(_CODEX_PROTOCOL)
828
+ if allow_empty and (self.reply is None or isinstance(self.reply, str) and not self.reply.strip()):
829
+ self.reply = NO_OUTPUT_TEXT
830
+ if not isinstance(self.reply, str) or not self.reply.strip():
831
+ raise _CodexFailure("bad_output", "工具未返回有效回复或会话")
832
+
833
+ context = None
834
+ if self.token_usage:
835
+ tokens = self.token_usage["last"].get("totalTokens")
836
+ window = self.token_usage.get("modelContextWindow")
837
+ context = {"tokens": tokens if type(tokens) is int and tokens >= 0 else None,
838
+ "window": window if type(window) is int and window >= 0 else None}
839
+ return ToolResult(status="succeeded", reply_text=self.reply, tool_session_ref=self.thread_id,
840
+ model_name=self.model, usage=_usage_from_payload({"usage": self.token_usage.get("total")}),
841
+ context=context)
842
+
843
+ async def compact(self):
844
+ """/compact:thread/compact/start 让 Codex 压缩当前会话,压缩以一个回合进行,等 turn/completed。"""
845
+ await self.result("thread/compact/start", {"threadId": self.thread_id}, "tool_error", "Codex 无法压缩上下文")
846
+ await self.completed.wait()
847
+ if self.turn_status == "interrupted":
848
+ raise _CodexFailure("cancelled", "已取消")
849
+ if self.error_detail or self.turn_status == "failed":
850
+ raise _CodexFailure("tool_error", self.error_detail or "Codex 压缩失败")
851
+ # 压缩回合上报的 tokenUsage 是这一回合自己的用量,不是压缩后的上下文大小,不拿来当 ctx(2026-11-23 实测)。
852
+ context, reply = None, "已压缩上下文,下一条消息起使用压缩后的内容。"
853
+ return ToolResult(status="succeeded", reply_text=reply, tool_session_ref=self.thread_id,
854
+ model_name=self.model, usage=_usage_from_payload({"usage": self.token_usage.get("total")}),
855
+ context=context)
856
+
857
+ async def steer(self, text):
858
+ if not self.accepting_steer:
859
+ raise SteerError("too_late", "Codex 当前没有运行中的回合")
860
+ params = {"threadId": self.thread_id, "expectedTurnId": self.turn_id,
861
+ "input": [{"type": "text", "text": text}]}
862
+ response = await self.request("turn/steer", params)
863
+ if "error" in response:
864
+ error = response["error"]
865
+ if not isinstance(error, dict) or type(error.get("code")) is not int:
866
+ raise ValueError(_CODEX_PROTOCOL)
867
+ message = str(error.get("message") or "").lower()
868
+ if error["code"] == -32600 and any(
869
+ marker in message for marker in ("no active turn", "expected", "mismatch", "completed", "finished", "turn")
870
+ ):
871
+ raise SteerError("too_late", "Codex 当前回合已结束")
872
+ raise SteerError("failed", "Codex 未能补充消息")
873
+ result = response["result"]
874
+ if not isinstance(result, dict) or result.get("turnId") != self.turn_id:
875
+ raise ValueError(_CODEX_PROTOCOL)
876
+ return self.turn_id
877
+
878
+ async def interrupt(self):
879
+ if self.turn_id and not self.completed.is_set():
880
+ await self.result("turn/interrupt", {"threadId": self.thread_id, "turnId": self.turn_id},
881
+ "tool_error", "Codex 无法中断回合")
882
+ await self.completed.wait()
883
+
884
+
885
+ async def _stop_codex(process, successful):
886
+ async def drain():
887
+ while await process.stdout.read(65536):
888
+ pass
889
+
890
+ reader = asyncio.create_task(drain())
891
+ process.stdin.close()
892
+ try:
893
+ if successful:
894
+ try:
895
+ await asyncio.wait_for(process.wait(), 1)
896
+ return
897
+ except TimeoutError:
898
+ pass
899
+ if os.name == "nt":
900
+ if process.returncode is None:
901
+ await asyncio.to_thread(subprocess.run, ["taskkill", "/PID", str(process.pid), "/T", "/F"],
902
+ capture_output=True, timeout=2, check=False)
903
+ else:
904
+ with suppress(ProcessLookupError):
905
+ os.killpg(process.pid, signal.SIGTERM)
906
+ with suppress(TimeoutError):
907
+ await asyncio.wait_for(process.wait(), 1)
908
+ if os.name != "nt":
909
+ with suppress(ProcessLookupError):
910
+ os.killpg(process.pid, signal.SIGKILL)
911
+ except (OSError, subprocess.SubprocessError):
912
+ pass
913
+ finally:
914
+ if process.returncode is None:
915
+ with suppress(ProcessLookupError):
916
+ process.kill()
917
+ with suppress(TimeoutError):
918
+ await asyncio.wait_for(process.wait(), 1)
919
+ reader.cancel()
920
+ await asyncio.gather(reader, return_exceptions=True)
921
+
922
+
923
+ class CodexAdapter(_ProcessAdapter):
924
+ tool_type = "codex"
925
+ executable_name = "codex"
926
+
927
+ def __init__(self, executable=None):
928
+ super().__init__(executable)
929
+ self._active_turn = None
930
+
931
+ def steer(self, text: str):
932
+ """从运行线程以外发送补充,返回等待服务器确认的 Future。"""
933
+ turn = self._active_turn
934
+ if turn is None or not turn.accepting_steer:
935
+ raise SteerError("too_late", "Codex 当前没有运行中的回合")
936
+ if not isinstance(text, str) or not text.strip():
937
+ raise ValueError("补充消息不能为空")
938
+ pending = turn.steer(text)
939
+ try:
940
+ return asyncio.run_coroutine_threadsafe(pending, turn.loop)
941
+ except RuntimeError:
942
+ pending.close()
943
+ raise SteerError("too_late", "Codex 当前没有运行中的回合") from None
944
+
945
+ def invoke(self, *, prompt, cwd, resume_session_ref, timeout_seconds, cancel_event, on_started=None,
946
+ on_activity=None, model=None, allow_empty=False, platform_run_id=None, sandbox_policy=None,
947
+ compact=False) -> ToolResult:
948
+ env = _invocation_env(cwd, model, platform_run_id)
949
+ if isinstance(env, ToolResult):
950
+ return env
951
+ if resume_session_ref:
952
+ try:
953
+ UUID(resume_session_ref)
954
+ except (ValueError, TypeError, AttributeError):
955
+ return ToolResult(status="failed", failure_code="bad_session", failure_detail="工具会话标识无效")
956
+ if cancel_event.is_set():
957
+ return ToolResult(status="cancelled", failure_code="cancelled", failure_detail="已取消")
958
+ if compact and not resume_session_ref:
959
+ return ToolResult(status="succeeded", reply_text="当前对话还没有 Codex 会话,无需压缩。")
960
+ return asyncio.run(self._run(prompt, cwd, resume_session_ref, model, allow_empty, env,
961
+ {"type": "dangerFullAccess"} if sandbox_policy is None else sandbox_policy,
962
+ on_started, on_activity, cancel_event, timeout_seconds, compact))
963
+
964
+ async def _run(self, prompt, cwd, resume, model, allow_empty, env, sandbox_policy, on_started, on_activity,
965
+ cancel_event, timeout_seconds, compact=False):
966
+ started = time.monotonic()
967
+ try:
968
+ process = await asyncio.create_subprocess_exec(
969
+ self.executable, "app-server", "--listen", "stdio://",
970
+ cwd=cwd, env=env, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
971
+ stderr=asyncio.subprocess.DEVNULL, limit=16 * 1024 * 1024, **_start_kwargs(),
972
+ )
973
+ except OSError:
974
+ return ToolResult(status="failed", failure_code="tool_start_failed", failure_detail=_CODEX_UPGRADE)
975
+ turn = self._active_turn = _CodexTurn(process, on_activity)
976
+ turn.instructions = self.instructions
977
+ reader = asyncio.create_task(turn.read())
978
+ run = asyncio.create_task(turn.run(prompt, cwd, resume, model, sandbox_policy, allow_empty, compact))
979
+ result = None
980
+ try:
981
+ if on_started:
982
+ on_started(process.pid)
983
+ deadline = started + max(1, int(timeout_seconds))
984
+ while True:
985
+ cancelled = cancel_event.is_set()
986
+ remaining = deadline - time.monotonic()
987
+ if cancelled or remaining <= 0:
988
+ turn.accepting_steer = False
989
+ if not reader.done():
990
+ with suppress(TimeoutError, _CodexFailure, OSError, ValueError):
991
+ await asyncio.wait_for(turn.interrupt(), 0.75)
992
+ raise _CodexFailure("cancelled", "已取消") if cancelled else _CodexFailure("timeout", "超时")
993
+ done, _ = await asyncio.wait((reader, run), timeout=min(remaining, 0.05),
994
+ return_when=asyncio.FIRST_COMPLETED)
995
+ if run in done:
996
+ result = run.result()
997
+ break
998
+ if reader in done:
999
+ reader.result()
1000
+ except _CodexFailure as exc:
1001
+ result = ToolResult(status="cancelled" if exc.code == "cancelled" else "failed",
1002
+ failure_code=exc.code, failure_detail=exc.detail,
1003
+ tool_session_ref=turn.thread_id if exc.code == "cancelled" else None)
1004
+ except (EOFError, OSError):
1005
+ result = ToolResult(status="failed", failure_code="tool_exit" if turn.initialized else "tool_start_failed",
1006
+ failure_detail="Codex app-server 提前退出" if turn.initialized else _CODEX_UPGRADE)
1007
+ except (ValueError, KeyError, TypeError, AttributeError):
1008
+ result = ToolResult(status="failed", failure_code="bad_output", failure_detail=_CODEX_PROTOCOL)
1009
+ finally:
1010
+ self._active_turn = None
1011
+ turn.accepting_steer = False
1012
+ for future in tuple(turn.requests.values()):
1013
+ future.cancel()
1014
+ reader.cancel()
1015
+ run.cancel()
1016
+ await asyncio.gather(reader, run, return_exceptions=True)
1017
+ await _stop_codex(process, result is not None and result.status == "succeeded")
1018
+ result.tool_version = turn.version
1019
+ result.exit_code = process.returncode
1020
+ result.elapsed_seconds = time.monotonic() - started
1021
+ return result
1022
+
1023
+
1024
+ class CursorAdapter(_ProcessAdapter):
1025
+ tool_type = "cursor"
1026
+ executable_name = "cursor-agent"
1027
+
1028
+ def _command(self, resume_session_ref: str | None) -> list[str]:
1029
+ command = [self.executable, "-p", "--trust", "--force", "--sandbox", "disabled", "--approve-mcps", "--output-format", "json"]
1030
+ if resume_session_ref:
1031
+ command.append("--resume=" + resume_session_ref)
1032
+ return command
1033
+
1034
+
1035
+ class AntigravityAdapter(_ProcessAdapter):
1036
+ """Agy:stream-json 每条 user 事件跑一轮。运行中补充追加一行 user 事件,Agy 在当前一轮结束后、同一进程同一会话里
1037
+ 接着处理并多出一个 result(T-150 实测,2026-11-23 agy 1.5.14 复测);收齐与已发条数相同的 result 才关输入、结束,
1038
+ 最终回复取最后一个 result(它已结合补充)。"""
1039
+ tool_type = "antigravity"
1040
+ executable_name = "agy"
1041
+
1042
+ def __init__(self, executable: str | None = None):
1043
+ super().__init__(executable)
1044
+ self._lock = threading.Lock()
1045
+ self._stdin = None
1046
+ self._sent = 0
1047
+ self._done = 0
1048
+
1049
+ def steer(self, text: str) -> None:
1050
+ if not isinstance(text, str) or not text.strip():
1051
+ raise ValueError("补充消息不能为空")
1052
+ with self._lock:
1053
+ if self._stdin is None or self._stdin.closed:
1054
+ raise SteerError("too_late", "Agy 当前没有运行中的回合")
1055
+ try:
1056
+ self._stdin.write(self._input(text))
1057
+ self._stdin.flush()
1058
+ except (OSError, ValueError):
1059
+ raise SteerError("failed", "补充消息写入失败") from None
1060
+ self._sent += 1
1061
+
1062
+ def _close_input(self) -> None:
1063
+ with self._lock:
1064
+ stream, self._stdin = self._stdin, None
1065
+ if stream is not None:
1066
+ with suppress(OSError, ValueError):
1067
+ stream.close()
1068
+
1069
+ def invoke(self, *, prompt, cwd, resume_session_ref, timeout_seconds, cancel_event, on_started=None,
1070
+ on_activity=None, model=None, allow_empty=False, platform_run_id=None) -> ToolResult:
1071
+ env = _invocation_env(cwd, model, platform_run_id)
1072
+ if isinstance(env, ToolResult):
1073
+ return env
1074
+ command = self._command(resume_session_ref)
1075
+ if model is not None:
1076
+ command[1:1] = ["--model", model]
1077
+ started = time.monotonic()
1078
+ try:
1079
+ process = subprocess.Popen(command, cwd=str(cwd), env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1080
+ stderr=subprocess.PIPE, text=True, **_start_kwargs())
1081
+ except OSError:
1082
+ return ToolResult(status="failed", failure_code="tool_start_failed", failure_detail="无法启动工具",
1083
+ elapsed_seconds=time.monotonic() - started)
1084
+ if on_started is not None:
1085
+ on_started(process.pid)
1086
+ results: list[str] = []
1087
+ stderr_chunks: list[str] = []
1088
+ seen = {}
1089
+ output, process.stdout = process.stdout, None
1090
+ err_stream, process.stderr = process.stderr, None
1091
+ with self._lock:
1092
+ self._stdin, process.stdin = process.stdin, None
1093
+ self._sent = self._done = 0
1094
+
1095
+ def read_events():
1096
+ with output:
1097
+ for line in output:
1098
+ try:
1099
+ event = json.loads(line)
1100
+ except ValueError:
1101
+ continue
1102
+ if not isinstance(event, dict):
1103
+ continue
1104
+ if event.get("event") == "result":
1105
+ results.append(line)
1106
+ reply = event.get("result")
1107
+ if isinstance(reply, dict) and isinstance(reply.get("conversation_id"), str):
1108
+ seen["session"] = reply["conversation_id"]
1109
+ with self._lock:
1110
+ self._done += 1
1111
+ finished = self._done >= self._sent
1112
+ if finished:
1113
+ self._close_input()
1114
+
1115
+ def read_stderr():
1116
+ with err_stream:
1117
+ while chunk := err_stream.read(8192):
1118
+ stderr_chunks.append(chunk)
1119
+
1120
+ reader = threading.Thread(target=read_events, daemon=True)
1121
+ err_reader = threading.Thread(target=read_stderr, daemon=True)
1122
+ reader.start()
1123
+ err_reader.start()
1124
+ try:
1125
+ with self._lock:
1126
+ self._stdin.write(self._input(prompt))
1127
+ self._stdin.flush()
1128
+ self._sent = 1
1129
+ except (OSError, ValueError, AttributeError):
1130
+ self._close_input()
1131
+ terminate_process_group(process)
1132
+ return ToolResult(status="failed", failure_code="tool_stdin_failed", failure_detail="无法写入提示",
1133
+ elapsed_seconds=time.monotonic() - started)
1134
+ deadline = started + max(1, int(timeout_seconds))
1135
+ try:
1136
+ while True:
1137
+ stopped = ("cancelled", "cancelled", "已取消") if cancel_event.is_set() else (
1138
+ ("failed", "timeout", "超时") if time.monotonic() >= deadline else None)
1139
+ if stopped:
1140
+ self._close_input()
1141
+ terminate_process_group(process)
1142
+ reader.join(timeout=2)
1143
+ err_reader.join(timeout=2)
1144
+ return ToolResult(status=stopped[0], failure_code=stopped[1], failure_detail=stopped[2],
1145
+ tool_session_ref=seen.get("session") if stopped[0] == "cancelled" else None,
1146
+ exit_code=process.poll(), raw_output="".join(results) or "".join(stderr_chunks),
1147
+ elapsed_seconds=time.monotonic() - started)
1148
+ try:
1149
+ process.wait(timeout=0.05)
1150
+ except subprocess.TimeoutExpired:
1151
+ continue
1152
+ reader.join(timeout=2)
1153
+ err_reader.join(timeout=2)
1154
+ break
1155
+ finally:
1156
+ self._close_input()
1157
+ return self._finalize_result(process, "".join(results), "".join(stderr_chunks), started, allow_empty)
1158
+
1159
+ 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"]
1161
+ if resume_session_ref:
1162
+ command.append("--conversation=" + resume_session_ref)
1163
+ # 文本打印模式不读 stdin;空 -p 开启事件模式,提示由标准输入的 user 事件传入。
1164
+ return command + ["-p="]
1165
+
1166
+ def _input(self, prompt: str) -> str:
1167
+ return json.dumps({"event": "user", "message": {"role": "user", "content": prompt}}, ensure_ascii=False) + "\n"
1168
+
1169
+ def _payload(self, raw: str) -> dict:
1170
+ payload = None
1171
+ for line in raw.splitlines():
1172
+ if not line.strip():
1173
+ continue
1174
+ event = json.loads(line)
1175
+ if not isinstance(event, dict):
1176
+ raise ValueError("事件必须为对象")
1177
+ if event.get("event") == "result":
1178
+ payload = event.get("result")
1179
+ if not isinstance(payload, dict):
1180
+ raise ValueError("缺少最终结果")
1181
+ if payload.get("status") == "ERROR":
1182
+ return {"is_error": True}
1183
+ if payload.get("status") != "SUCCESS":
1184
+ raise ValueError("结果状态无效")
1185
+ return payload | {"result": payload.get("response"), "session_id": payload.get("conversation_id")}
1186
+
1187
+
1188
+ def _collect_after_stop(process: subprocess.Popen) -> tuple[str, str]:
1189
+ """进程组已终止后收尾读取剩余输出;孙进程仍占着管道时最多等 2 秒。"""
1190
+ try:
1191
+ stdout, stderr = process.communicate(timeout=2)
1192
+ except (subprocess.TimeoutExpired, OSError, ValueError):
1193
+ return "", ""
1194
+ return stdout or "", stderr or ""
1195
+
1196
+
1197
+ def _nonzero_detail(stderr: str | None, stdout: str | None) -> str:
1198
+ text = (stderr or stdout or "").strip()
1199
+ lowered = text.lower()
1200
+ for marker, detail in (
1201
+ ("keychain is locked", "登录钥匙串已锁定,请在设备本机解锁"),
1202
+ ("rate_limit", "工具请求受限,请稍后再试"),
1203
+ ("quota", "工具额度不足"),
1204
+ ("credit", "工具额度不足"),
1205
+ ("billing", "工具账单受限"),
1206
+ ("authentication", "工具认证失败,请在设备本机登录"),
1207
+ ):
1208
+ if marker in lowered:
1209
+ return detail
1210
+ return "工具非零退出"
1211
+
1212
+
1213
+ class UnsupportedAdapter:
1214
+ def __init__(self, tool_type: str):
1215
+ self.tool_type = tool_type
1216
+
1217
+ def version(self) -> str | None:
1218
+ return None
1219
+
1220
+ def steer(self, text: str):
1221
+ raise SteerError("unsupported", "该工具暂不支持补充消息")
1222
+
1223
+ def invoke(
1224
+ self,
1225
+ *,
1226
+ prompt: str,
1227
+ cwd: Path,
1228
+ resume_session_ref: str | None,
1229
+ timeout_seconds: int,
1230
+ cancel_event: threading.Event,
1231
+ on_started=None,
1232
+ on_activity=None,
1233
+ model: str | None = None,
1234
+ platform_run_id: str | None = None,
1235
+ ) -> ToolResult:
1236
+ return ToolResult(
1237
+ status="failed",
1238
+ failure_code="tool_not_supported",
1239
+ failure_detail="阶段四接入",
1240
+ )
1241
+
1242
+
1243
+ def get_adapter(tool_type: str, claude_executable: str | None = None) -> ToolAdapter:
1244
+ if tool_type == "claude_code":
1245
+ return ClaudeCodeAdapter(executable=claude_executable)
1246
+ if tool_type == "codex":
1247
+ return CodexAdapter()
1248
+ if tool_type == "cursor":
1249
+ return CursorAdapter()
1250
+ if tool_type == "antigravity":
1251
+ return AntigravityAdapter()
1252
+ return UnsupportedAdapter(tool_type)
1253
+
1254
+
1255
+ def claude_available(executable: str | None = None) -> bool:
1256
+ path = executable or which("claude")
1257
+ return bool(path)