agenthub/deploy/cli-bridge/adapters/claude.py

118 lines
5.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""claude adapter —— 对接 `claude -p --output-format stream-json`。
实测 Claude Code 2.1.86 的 stdout:
{"type":"system","subtype":"init","session_id":"7ec423bd-…","model":"…","tools":[…]}
{"type":"assistant","message":{"content":[{"type":"text","text":"…"}]}, …}
{"type":"result","subtype":"success","is_error":true,"result":"API Error: 402 …"}
坑:模型报错时 subtype 仍是 "success",**只有 is_error 是真的** —— 认错了就会把
报错当成功结果上报给 hub。中途下达指令它没有原生 queue,只能靠同一 session_key
再发一个 task(本适配器会自动带上 --resume)。
"""
from __future__ import annotations
import asyncio
import json
import os
from pathlib import Path
from shutil import which
name = "claude"
PERMISSION = {"readonly": "plan", "write": "acceptEdits"}
_last: dict[str, object] = {}
_version = ""
def _bin() -> str:
path = os.environ.get("CLAUDE_BIN") or which("claude") or "/usr/local/bin/claude"
if not path or not Path(path).exists():
raise RuntimeError("找不到 claude 可执行文件;用环境变量 CLAUDE_BIN 指定绝对路径")
return path
def argv(*, prompt: str, run, workdir: str, mode: str) -> list[str]:
# 实测坑:--add-dir 是变长参数(<directories...>),会把它后面的位置参数——也就是
# prompt——一起吞掉,claude 于是报 "Input must be provided either through stdin"。
# 子进程的 cwd 本来就是 workdir,多余目录才需要 --add-dir。末尾的 -- 防 prompt 以 - 开头。
args = [_bin(), "-p", "--output-format", "stream-json", "--verbose",
"--permission-mode", PERMISSION.get(mode, "plan")]
if run.session_id:
args += ["--resume", run.session_id]
return args + ["--", prompt]
def _brief(value: object, limit: int = 600) -> str:
if isinstance(value, str):
return value[:limit]
return json.dumps(value, ensure_ascii=False, default=str)[:limit]
async def feed(obj: dict, run, emit) -> None:
kind = str(obj.get("type") or "")
if kind == "system" and obj.get("subtype") == "init":
run.session_id = str(obj.get("session_id") or run.session_id)
_last.update({
"claude_model": obj.get("model"),
"claude_permission_mode": obj.get("permissionMode"),
"claude_tools": len(obj.get("tools") or []),
"claude_mcp_servers": len(obj.get("mcp_servers") or []),
})
await emit("status", message="claude 会话 " + run.session_id, session_id=run.session_id,
model=str(obj.get("model") or ""))
elif kind == "assistant":
await _assistant(obj, run, emit)
elif kind == "result":
usage = dict(obj.get("usage") or {})
if obj.get("total_cost_usd") is not None:
usage["total_cost_usd"] = obj.get("total_cost_usd")
run.usage.update({k: v for k, v in usage.items() if v not in (None, {}, [])})
if obj.get("is_error"): # subtype 可能是 success,别看它
raise RuntimeError("claude 返回错误:" + _brief(obj.get("result") or obj, 800))
run.final_text = str(obj.get("result") or "".join(run.parts))
elif kind in ("user", "system"): # 工具回执之类,正文里没有价值,留成日志
await emit("log", text="claude " + kind + "/" + str(obj.get("subtype") or "") + ": " + _brief(obj, 400))
else:
await emit("log", text="claude " + (kind or "event") + ": " + _brief(obj, 400))
async def _assistant(obj: dict, run, emit) -> None:
message = obj.get("message") if isinstance(obj.get("message"), dict) else {}
for block in message.get("content") or []:
if not isinstance(block, dict):
continue
btype = str(block.get("type") or "")
if btype == "text":
text = str(block.get("text") or "")
if text:
run.parts.append(text)
await emit("delta", text=text)
elif btype == "tool_use":
await emit("tool", name=str(block.get("name") or "tool"), state="requested",
detail=_brief(block.get("input"), 400))
elif btype in ("thinking", "redacted_thinking"):
await emit("reasoning", text=str(block.get("thinking") or ""))
async def deliver(session_id: str, text: str) -> tuple[bool, str]:
return False, ("claude 没有原生的会话内注入;请用同一个 session_key 再发一个 task"
f"(会自动 --resume {session_id} 续上这段对话)")
async def version() -> str:
global _version
if _version:
return _version
try:
proc = await asyncio.create_subprocess_exec(_bin(), "--version",
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)
out, _ = await asyncio.wait_for(proc.communicate(), timeout=20)
_version = out.decode("utf-8", "replace").strip()
except Exception as exc: # noqa: BLE001
_version = "unknown (" + type(exc).__name__ + ")"
return _version
def status() -> dict[str, object]:
return dict(_last)