166 lines
7.7 KiB
Python
166 lines
7.7 KiB
Python
"""workbuddy adapter —— 对接 WorkBuddy 自带 CLI `codebuddy -p --output-format stream-json`。
|
||
|
||
CLI 不在 PATH 里,只能按绝对路径找(或 WORKBUDDY_BIN 覆盖)。实测 2.137.1 的 stdout
|
||
是 Claude Code 同款事件流,另多塞了 `__timestamp` / `_requestId` / `_meta` 和
|
||
`file-history-snapshot` 这类噪音:
|
||
|
||
{"type":"system","subtype":"init","session_id":"a96ab55b-…","model":"auto",…}
|
||
{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Read",…}]},"session_id":…}
|
||
{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"…","content":[…]}]}}
|
||
{"type":"result","subtype":"success","is_error":false,"result":"紫色水壶","usage":{…}}
|
||
|
||
和 claude 的两个差别:不需要 `--verbose`(WB 的 --verbose 是另一个意思);`user` 消息里的
|
||
tool_result 值得还原成 tool 事件,于是 hub 能看到每次工具调用的成败。
|
||
|
||
续话实测可用:`--resume <session_id>` 无头可用且沿用同一个 session_id。
|
||
中途下达指令没有原生注入(`attach` 只能进 TUI),所以 deliver() 如实拒绝。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import json
|
||
import os
|
||
import subprocess
|
||
from pathlib import Path
|
||
from shutil import which
|
||
|
||
name = "workbuddy"
|
||
PERMISSION = {"readonly": "plan", "write": "acceptEdits"}
|
||
_FALLBACK = ("/Applications/WorkBuddy.app/Contents/Resources/app.asar.unpacked"
|
||
"/cli/bin/codebuddy")
|
||
_last: dict[str, object] = {}
|
||
_version = ""
|
||
|
||
|
||
def _bin() -> str:
|
||
path = os.environ.get("WORKBUDDY_BIN") or which("codebuddy") or _FALLBACK
|
||
if not path or not Path(path).exists():
|
||
raise RuntimeError("找不到 codebuddy 可执行文件;用环境变量 WORKBUDDY_BIN 指定绝对路径")
|
||
return path
|
||
|
||
|
||
def argv(*, prompt: str, run, workdir: str, mode: str) -> list[str]:
|
||
# 与 claude 同款坑:--add-dir 是变长参数(<directories...>),会把后面的 prompt 一起吞掉。
|
||
# 子进程 cwd 本来就是 workdir,不需要它;末尾 -- 防 prompt 以 - 开头。
|
||
args = [_bin(), "-p", "--output-format", "stream-json",
|
||
"--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]
|
||
|
||
|
||
def _blocks(obj: dict) -> list[dict]:
|
||
message = obj.get("message") if isinstance(obj.get("message"), dict) else {}
|
||
return [b for b in (message.get("content") or []) if isinstance(b, dict)]
|
||
|
||
|
||
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({
|
||
"wb_model": obj.get("model"),
|
||
"wb_permission_mode": obj.get("permissionMode"),
|
||
"wb_tools": len(obj.get("tools") or []),
|
||
"wb_mcp_servers": len(obj.get("mcp_servers") or []),
|
||
"wb_auth_source": obj.get("apiKeySource"),
|
||
})
|
||
await emit("status", message="workbuddy 会话 " + run.session_id, session_id=run.session_id,
|
||
model=str(obj.get("model") or ""))
|
||
elif kind == "assistant":
|
||
await _assistant(obj, run, emit)
|
||
elif kind == "user":
|
||
await _tool_results(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, {}, [])})
|
||
denials = obj.get("permission_denials") or []
|
||
if denials: # 无头模式没人应答授权:被拒的工具不会重试,只能从这儿看出来
|
||
await emit("log", text="workbuddy 权限被拒 " + str(len(denials)) + " 次: " + _brief(denials, 800))
|
||
if obj.get("is_error"): # 和 claude 一样,subtype 可能是 success,别看它
|
||
raise RuntimeError("workbuddy 返回错误:" + _brief(obj.get("result") or obj, 800))
|
||
run.final_text = str(obj.get("result") or "".join(run.parts))
|
||
else: # system/status、file-history-snapshot 之类:是噪音,但排障时是唯一线索
|
||
await emit("log", text="workbuddy " + kind + "/" + str(obj.get("subtype") or "")
|
||
+ ": " + _brief(obj, 300))
|
||
|
||
|
||
async def _assistant(obj: dict, run, emit) -> None:
|
||
names: dict[str, str] = run.extra.setdefault("tool_names", {})
|
||
for block in _blocks(obj):
|
||
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":
|
||
tool = str(block.get("name") or "tool")
|
||
names[str(block.get("id") or "")] = tool
|
||
await emit("tool", name=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 _tool_results(obj: dict, run, emit) -> None:
|
||
names: dict[str, str] = run.extra.setdefault("tool_names", {})
|
||
for block in _blocks(obj):
|
||
if block.get("type") != "tool_result":
|
||
continue
|
||
tool_id = str(block.get("tool_use_id") or "")
|
||
body = block.get("content")
|
||
if isinstance(body, list): # [{type:text,text:"…"}] 才是正文
|
||
body = " ".join(str(b.get("text") or "") for b in body if isinstance(b, dict))
|
||
await emit("tool", name=names.get(tool_id, "tool"), state="completed",
|
||
failed=bool(block.get("is_error")), detail=_brief(body, 400))
|
||
|
||
|
||
async def deliver(session_id: str, text: str) -> tuple[bool, str]:
|
||
return False, ("workbuddy 没有会话内注入(`cbc attach` 只能进 TUI);"
|
||
f"请用同一个 session_key 再发一个 task(会自动 --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 - describe 不该因为版本探测挂掉
|
||
_version = "unknown (" + type(exc).__name__ + ")"
|
||
return _version
|
||
|
||
|
||
def status() -> dict[str, object]:
|
||
return dict(_last)
|
||
|
||
|
||
def host() -> tuple[bool, str]:
|
||
"""WorkBuddy 桌面 App 是否在运行。
|
||
|
||
这是产品语义,不是技术必需:无头 CLI 不依赖 App,App 关着任务照样跑得动。
|
||
但桌面端都关了、hub 上还挂着"已接入",看的人会被误导,所以宁可报不可用。
|
||
装在 .app 之外的独立 CLI 没有 App 可跟随,直接返回可用。
|
||
"""
|
||
bundle = next((p for p in Path(_bin()).resolve().parents if p.suffix == ".app"), None)
|
||
if bundle is None:
|
||
return True, ""
|
||
# 只匹配 "<Bundle>.app/Contents/MacOS/":安装路径带软链时(/tmp → /private/tmp、
|
||
# 外置盘)resolve() 出来的前缀和真实 argv 对不上,用名字匹配两种都认。
|
||
probe = subprocess.run(["pgrep", "-f", bundle.name + "/Contents/MacOS/"], # noqa: S603
|
||
stdout=subprocess.DEVNULL)
|
||
if probe.returncode == 0:
|
||
return True, ""
|
||
return False, bundle.name + " 没有运行"
|