222 行
11 KiB
Python
222 行
11 KiB
Python
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import json
|
|||
|
|
import re
|
|||
|
|
from typing import Any
|
|||
|
|
from urllib.parse import quote
|
|||
|
|
|
|||
|
|
from astrbot.api import AstrBotConfig, logger
|
|||
|
|
from astrbot.api.event import AstrMessageEvent, filter
|
|||
|
|
from astrbot.api.star import Context, Star, register
|
|||
|
|
|
|||
|
|
from .client import HandoffClient, HandoffClientError
|
|||
|
|
|
|||
|
|
|
|||
|
|
TOOLS = {"dev_handoff_projects", "dev_handoff_machines", "dev_handoff_tasks", "dev_handoff_status", "dev_handoff_plan"}
|
|||
|
|
ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")
|
|||
|
|
|
|||
|
|
|
|||
|
|
@register("astrbot_plugin_dev_handoff", "Dev Handoff", "桌面 Codex 与 VM Codex 双向开发交接", "0.3.0")
|
|||
|
|
class DevHandoffPlugin(Star):
|
|||
|
|
def __init__(self, context: Context, config: AstrBotConfig):
|
|||
|
|
super().__init__(context)
|
|||
|
|
self.context = context
|
|||
|
|
self.client = HandoffClient(str(config.get("socket_path") or "/run/dev-handoff/controller.sock"))
|
|||
|
|
self.enable_llm_tools = bool(config.get("enable_llm_tools", True))
|
|||
|
|
|
|||
|
|
async def initialize(self):
|
|||
|
|
await self.client.open()
|
|||
|
|
logger.info("Dev Handoff 插件已初始化")
|
|||
|
|
|
|||
|
|
async def terminate(self):
|
|||
|
|
await self.client.close()
|
|||
|
|
|
|||
|
|
def _admin(self, event: AstrMessageEvent) -> bool:
|
|||
|
|
try:
|
|||
|
|
cfg = self.context.get_config(event.unified_msg_origin)
|
|||
|
|
return str(event.get_sender_id()) in {str(item) for item in cfg.get("admins_id", [])}
|
|||
|
|
except Exception:
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
@staticmethod
|
|||
|
|
def _id(value: str) -> str:
|
|||
|
|
value = str(value or "").strip()
|
|||
|
|
if not ID_RE.fullmatch(value):
|
|||
|
|
raise ValueError("ID 格式无效")
|
|||
|
|
return value
|
|||
|
|
|
|||
|
|
async def _call(self, method: str, path: str, body: dict[str, Any] | None = None) -> dict[str, Any]:
|
|||
|
|
try:
|
|||
|
|
return await self.client.request(method, path, body)
|
|||
|
|
except (HandoffClientError, ValueError) as exc:
|
|||
|
|
return {"ok": False, "message": str(exc)}
|
|||
|
|
|
|||
|
|
@staticmethod
|
|||
|
|
def _render(payload: dict[str, Any]) -> str:
|
|||
|
|
if not payload.get("ok", False):
|
|||
|
|
return "⚠️ " + str(payload.get("message") or "操作失败")
|
|||
|
|
lines = [str(payload.get("message") or "开发交接状态")]
|
|||
|
|
for key in ("task_id", "handoff_id", "state", "owner_machine_id", "current_epoch", "current_head_sha", "branch_name", "workspace_path"):
|
|||
|
|
if payload.get(key) is not None:
|
|||
|
|
lines.append(f"{key}: {payload[key]}")
|
|||
|
|
for group in ("projects", "tasks", "history", "events", "alerts", "jobs"):
|
|||
|
|
for item in payload.get(group, []):
|
|||
|
|
if group == "projects":
|
|||
|
|
lines.append(f"- {item.get('id')}:{item.get('name')}({item.get('repo')})")
|
|||
|
|
elif group == "tasks":
|
|||
|
|
lines.append(f"- {item.get('id')}:{item.get('title')}|{item.get('state')}|{item.get('owner_machine_id')}|e{item.get('current_epoch')}")
|
|||
|
|
elif group == "events":
|
|||
|
|
lines.append(f"- #{item.get('seq')} {item.get('created_at')} {item.get('action')} {item.get('subject_type')}={item.get('subject_id')}")
|
|||
|
|
elif group == "alerts":
|
|||
|
|
lines.append(f"- [{item.get('severity')}] {item.get('kind')} {item.get('subject_id')}:{item.get('last_error') or item.get('title') or ''}")
|
|||
|
|
elif group == "jobs":
|
|||
|
|
lines.append(f"- {item.get('id')} {item.get('state')} task={item.get('task_id')} machine={item.get('machine_id')} attempts={item.get('attempts')}")
|
|||
|
|
else:
|
|||
|
|
lines.append(f"- {item.get('created_at')} {item.get('action')} by {item.get('actor')}")
|
|||
|
|
task = payload.get("task")
|
|||
|
|
if isinstance(task, dict):
|
|||
|
|
lines.extend([
|
|||
|
|
f"项目:{task.get('project_id')}", f"任务:{task.get('id')} {task.get('title')}",
|
|||
|
|
f"当前开发端:{task.get('owner_machine_id')}", f"阶段:e{task.get('current_epoch')} {task.get('state')}",
|
|||
|
|
f"远端检查点:{task.get('current_head_sha')}",
|
|||
|
|
])
|
|||
|
|
return "\n".join(lines[:80])
|
|||
|
|
|
|||
|
|
@filter.on_llm_request()
|
|||
|
|
async def on_llm_request(self, event: AstrMessageEvent, request):
|
|||
|
|
if self.enable_llm_tools and self._admin(event):
|
|||
|
|
return
|
|||
|
|
tool_set = getattr(request, "func_tool", None)
|
|||
|
|
if tool_set:
|
|||
|
|
for name in TOOLS:
|
|||
|
|
try:
|
|||
|
|
tool_set.remove_tool(name)
|
|||
|
|
except Exception:
|
|||
|
|
pass
|
|||
|
|
|
|||
|
|
@filter.command_group("dev")
|
|||
|
|
def dev(self):
|
|||
|
|
pass
|
|||
|
|
|
|||
|
|
@dev.command("projects")
|
|||
|
|
async def projects(self, event: AstrMessageEvent):
|
|||
|
|
yield event.plain_result(self._render(await self._call("GET", "/v1/projects")))
|
|||
|
|
|
|||
|
|
@dev.command("tasks")
|
|||
|
|
async def tasks(self, event: AstrMessageEvent, project_id: str = ""):
|
|||
|
|
suffix = f"?project_id={quote(self._id(project_id))}" if project_id else ""
|
|||
|
|
yield event.plain_result(self._render(await self._call("GET", "/v1/tasks" + suffix)))
|
|||
|
|
|
|||
|
|
@dev.command("status")
|
|||
|
|
async def status(self, event: AstrMessageEvent, task_id: str):
|
|||
|
|
yield event.plain_result(self._render(await self._call("GET", f"/v1/tasks/{quote(self._id(task_id))}")))
|
|||
|
|
|
|||
|
|
@dev.command("history")
|
|||
|
|
async def history(self, event: AstrMessageEvent, task_id: str):
|
|||
|
|
yield event.plain_result(self._render(await self._call("GET", f"/v1/tasks/{quote(self._id(task_id))}/history")))
|
|||
|
|
|
|||
|
|
@dev.command("events")
|
|||
|
|
async def events(self, event: AstrMessageEvent, after_seq: int = 0, limit: int = 30):
|
|||
|
|
after_seq = max(0, int(after_seq))
|
|||
|
|
limit = max(1, min(int(limit), 100))
|
|||
|
|
yield event.plain_result(self._render(await self._call("GET", f"/v1/events?after_seq={after_seq}&limit={limit}")))
|
|||
|
|
|
|||
|
|
@dev.command("alerts")
|
|||
|
|
async def alerts(self, event: AstrMessageEvent):
|
|||
|
|
yield event.plain_result(self._render(await self._call("GET", "/v1/alerts")))
|
|||
|
|
|
|||
|
|
@dev.command("cleanup")
|
|||
|
|
async def cleanup(self, event: AstrMessageEvent):
|
|||
|
|
yield event.plain_result(self._render(await self._call("GET", "/v1/cleanup")))
|
|||
|
|
|
|||
|
|
def _button_gateway(self) -> Any | None:
|
|||
|
|
"""BUTTON_GATEWAY_WIRED: shared button plugin, absent is a normal (text-only) state."""
|
|||
|
|
meta = self.context.get_registered_star("astrbot_plugin_button_gateway")
|
|||
|
|
return getattr(meta, "star_cls", None) if meta else None
|
|||
|
|
|
|||
|
|
async def on_button(self, action: str, payload: dict[str, Any], identity: dict[str, str]) -> tuple[bool, str]:
|
|||
|
|
"""Button gateway callback for handoff confirmation."""
|
|||
|
|
handoff_id = str(payload.get("handoff_id") or "")
|
|||
|
|
if action == "cancel":
|
|||
|
|
return True, f"已取消。交接 {handoff_id} 未确认,计划仍在,可稍后用 /dev approve 处理。"
|
|||
|
|
expected_sha = str(payload.get("expected_sha") or "")
|
|||
|
|
if not handoff_id or not expected_sha:
|
|||
|
|
return False, "缺少交接信息,请重新生成计划。"
|
|||
|
|
result = await self._call(
|
|||
|
|
"POST",
|
|||
|
|
f"/v1/handoffs/{quote(handoff_id)}/approve",
|
|||
|
|
{"expected_sha": expected_sha, "actor": str(identity.get("user_id") or "button")},
|
|||
|
|
)
|
|||
|
|
return bool(result.get("ok")), self._render(result)
|
|||
|
|
|
|||
|
|
@filter.permission_type(filter.PermissionType.ADMIN)
|
|||
|
|
@dev.command("handoff")
|
|||
|
|
async def handoff(self, event: AstrMessageEvent, task_id: str, to_machine_id: str):
|
|||
|
|
if not self._admin(event):
|
|||
|
|
yield event.plain_result("⚠️ 仅管理员可生成交接计划")
|
|||
|
|
return
|
|||
|
|
payload = await self._call("POST", f"/v1/tasks/{quote(self._id(task_id))}/handoff-plan", {"to_machine_id": self._id(to_machine_id), "actor": str(event.get_sender_id())})
|
|||
|
|
text = self._render(payload)
|
|||
|
|
handoff_id = str(payload.get("handoff_id") or "")
|
|||
|
|
expected_sha = str(payload.get("expected_sha") or "")
|
|||
|
|
gateway = self._button_gateway()
|
|||
|
|
if payload.get("ok") and handoff_id and expected_sha and gateway is not None:
|
|||
|
|
sent = await gateway.send_buttons(
|
|||
|
|
event,
|
|||
|
|
(
|
|||
|
|
f"# 交接计划已生成\n"
|
|||
|
|
f"任务:`{task_id}`\n"
|
|||
|
|
f"目标:`{to_machine_id}`\n"
|
|||
|
|
f"Commit:`{expected_sha[:12]}…`\n"
|
|||
|
|
f"交接号:`{handoff_id}`\n\n"
|
|||
|
|
"确认后来源端执行段会被冻结,目标端才能接手。"
|
|||
|
|
),
|
|||
|
|
[
|
|||
|
|
{"label": "确认交接", "action": "approve", "style": 1},
|
|||
|
|
{"label": "取消", "action": "cancel", "style": 0},
|
|||
|
|
],
|
|||
|
|
owner="astrbot_plugin_dev_handoff",
|
|||
|
|
handler="on_button",
|
|||
|
|
payload={"handoff_id": handoff_id, "expected_sha": expected_sha, "task_id": task_id},
|
|||
|
|
allowed_user_id=str(event.get_sender_id()),
|
|||
|
|
ttl_seconds=900,
|
|||
|
|
)
|
|||
|
|
if sent:
|
|||
|
|
yield event.plain_result(text + "\n\n已发送确认按钮。")
|
|||
|
|
return
|
|||
|
|
yield event.plain_result(text)
|
|||
|
|
|
|||
|
|
@filter.permission_type(filter.PermissionType.ADMIN)
|
|||
|
|
@dev.command("approve")
|
|||
|
|
async def approve(self, event: AstrMessageEvent, handoff_id: str, expected_sha: str):
|
|||
|
|
payload = await self._call("POST", f"/v1/handoffs/{quote(self._id(handoff_id))}/approve", {"expected_sha": expected_sha, "actor": str(event.get_sender_id())})
|
|||
|
|
yield event.plain_result(self._render(payload))
|
|||
|
|
|
|||
|
|
@filter.llm_tool(name="dev_handoff_projects")
|
|||
|
|
async def tool_projects(self, event: AstrMessageEvent) -> str:
|
|||
|
|
"""列出受控开发项目及其仓库与默认分支。"""
|
|||
|
|
return json.dumps(await self._call("GET", "/v1/projects"), ensure_ascii=False)
|
|||
|
|
|
|||
|
|
@filter.llm_tool(name="dev_handoff_machines")
|
|||
|
|
async def tool_machines(self, event: AstrMessageEvent) -> str:
|
|||
|
|
"""列出可接受交接的机器。capabilities.agent 标明该机器跑的编码 Agent:codex 或 claude。生成交接计划前用它确认 to_machine_id。"""
|
|||
|
|
return json.dumps(await self._call("GET", "/v1/machines"), ensure_ascii=False)
|
|||
|
|
|
|||
|
|
@filter.llm_tool(name="dev_handoff_tasks")
|
|||
|
|
async def tool_tasks(self, event: AstrMessageEvent, project_id: str = "") -> str:
|
|||
|
|
"""列出受控开发任务。project_id 可选。"""
|
|||
|
|
suffix = f"?project_id={quote(self._id(project_id))}" if project_id else ""
|
|||
|
|
return json.dumps(await self._call("GET", "/v1/tasks" + suffix), ensure_ascii=False)
|
|||
|
|
|
|||
|
|
@filter.llm_tool(name="dev_handoff_status")
|
|||
|
|
async def tool_status(self, event: AstrMessageEvent, task_id: str) -> str:
|
|||
|
|
"""读取一个开发任务、执行段和交接历史。"""
|
|||
|
|
return json.dumps(await self._call("GET", f"/v1/tasks/{quote(self._id(task_id))}"), ensure_ascii=False)
|
|||
|
|
|
|||
|
|
@filter.llm_tool(name="dev_handoff_plan")
|
|||
|
|
async def tool_handoff(self, event: AstrMessageEvent, task_id: str, to_machine_id: str) -> str:
|
|||
|
|
"""仅生成交接计划;不会创建工作区或开始编码。"""
|
|||
|
|
if not self._admin(event):
|
|||
|
|
return json.dumps({"ok": False, "message": "仅管理员可生成交接计划"}, ensure_ascii=False)
|
|||
|
|
return json.dumps(await self._call("POST", f"/v1/tasks/{quote(self._id(task_id))}/handoff-plan", {"to_machine_id": self._id(to_machine_id), "actor": str(event.get_sender_id())}), ensure_ascii=False)
|