【从0到1构建一个ClaudeAgent】协作-团队协议 _
·
Java代码
java
public class TeamProtocolsSystem {
// --- 配置 ---
private static final Path WORKDIR = Paths.get(System.getProperty("user.dir"));
private static final Path TEAM_DIR = WORKDIR.resolve(".team");
private static final Path INBOX_DIR = TEAM_DIR.resolve("inbox");
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
// 有效消息类型
private static final Set<String> VALID_MSG_TYPES = Set.of(
"message", "broadcast", "shutdown_request",
"shutdown_response", "plan_approval_response"
);
// --- 请求追踪器 ---
private static final Map<String, ShutdownRequest> shutdownRequests = new ConcurrentHashMap<>();
private static final Map<String, PlanRequest> planRequests = new ConcurrentHashMap<>();
private static final Object trackerLock = new Object();
static class ShutdownRequest {
String requestId;
String target; // 目标智能体
String status; // pending, approved, rejected
long timestamp;
}
static class PlanRequest {
String requestId;
String from; // 提交者
String plan; // 计划内容
String status; // pending, approved, rejected
long timestamp;
}
// --- 消息系统(MessageBus)---
static class MessageBus {
private final Path inboxDir;
private final AtomicInteger requestIdCounter = new AtomicInteger(1);
public MessageBus(Path inboxDir) {
this.inboxDir = inboxDir;
try {
Files.createDirectories(inboxDir);
} catch (IOException e) {
throw new RuntimeException("Failed to create inbox directory", e);
}
}
/**
* 生成唯一的请求ID
*/
public String generateRequestId() {
return "req_" + requestIdCounter.getAndIncrement() + "_" +
System.currentTimeMillis() % 10000;
}
/**
* 发送消息到指定智能体
*/
public String send(String sender, String to, String content,
String msgType, Map<String, Object> extra) {
if (!VALID_MSG_TYPES.contains(msgType)) {
return String.format("Error: Invalid type '%s'. Valid: %s",
msgType, String.join(", ", VALID_MSG_TYPES));
}
Map<String, Object> message = new LinkedHashMap<>();
message.put("type", msgType);
message.put("from", sender);
message.put("content", content);
message.put("timestamp", System.currentTimeMillis() / 1000.0);
if (extra != null) {
message.putAll(extra);
}
// ... 省略相同的发送逻辑
}
}
// 初始化消息总线
private static final MessageBus BUS = new MessageBus(INBOX_DIR);
// --- 智能体管理器(TeammateManager)---
static class TeammateManager {
// ... 省略相同的配置加载、保存逻辑
private void teammateLoop(String name, String role, String prompt, AtomicBoolean stopFlag) {
String systemPrompt = String.format(
"You are '%s', role: %s, at %s. " +
"Submit plans via plan_approval before major work. " +
"Respond to shutdown_request with shutdown_response.",
name, role, WORKDIR
);
// 增强系统提示:明确协议要求
// 计划审批:重要工作前需要提交计划
// 关机响应:需要响应关机请求
List<Map<String, Object>> messages = new ArrayList<>();
messages.add(Map.of("role", "user", "content", prompt));
boolean shouldExit = false;
// 最大迭代次数限制
for (int i = 0; i < 50 && !stopFlag.get(); i++) {
try {
// 检查邮箱
List<Map<String, Object>> inbox = BUS.readInbox(name);
for (Map<String, Object> msg : inbox) {
messages.add(Map.of("role", "user", "content", gson.toJson(msg)));
}
if (shouldExit) {
break;
}
// ... 省略相同的LLM调用和执行逻辑
for (Map<String, Object> block : content) {
if ("tool_use".equals(block.get("type"))) {
String toolName = (String) block.get("name");
String toolId = (String) block.get("id");
@SuppressWarnings("unchecked")
Map<String, Object> args = (Map<String, Object>) block.get("input");
String output = executeTeammateTool(name, toolName, args);
// 如果批准了关机,设置退出标志
if ("shutdown_response".equals(toolName) &&
Boolean.TRUE.equals(args.get("approve"))) {
shouldExit = true;
}
}
}
}
}
// 更新状态
Map<String, Object> member = findMember(name);
if (member != null) {
member.put("status", shouldExit ? "shutdown" : "idle");
saveConfig();
}
// 状态更新:根据退出原因设置不同状态
}
private String executeTeammateTool(String sender, String toolName, Map<String, Object> args) {
try {
switch (toolName) {
// ... 省略基础工具
case "shutdown_response":
String reqId = (String) args.get("request_id");
Boolean approve = (Boolean) args.get("approve");
if (approve == null) approve = false;
synchronized (trackerLock) {
ShutdownRequest req = shutdownRequests.get(reqId);
if (req != null) {
req.status = approve ? "approved" : "rejected";
}
}
// 状态更新:在追踪器中更新请求状态
String reason = (String) args.get("reason");
if (reason == null) reason = "";
BUS.send(
sender, "lead", reason, "shutdown_response",
Map.of("request_id", reqId, "approve", approve)
);
// 回复领导:通知领导审批结果
return String.format("Shutdown %s", approve ? "approved" : "rejected");
case "plan_approval":
String planText = (String) args.get("plan");
String planReqId = BUS.generateRequestId();
synchronized (trackerLock) {
planRequests.put(planReqId, new PlanRequest(planReqId, sender, planText));
}
// 计划提交:创建新的计划请求
BUS.send(
sender, "lead", planText, "plan_approval_response",
Map.of("request_id", planReqId, "plan", planText)
);
// 通知领导:发送计划审批请求
return String.format("Plan submitted (request_id=%s). Waiting for lead approval.", planReqId);
}
}
}
}
// --- 领导特定的协议处理器 ---
/**
* 处理关机请求
*/
private static String handleShutdownRequest(String teammate) {
String reqId = BUS.generateRequestId();
synchronized (trackerLock) {
shutdownRequests.put(reqId, new ShutdownRequest(reqId, teammate));
}
// 创建请求:在追踪器中记录关机请求
BUS.send(
"lead", teammate, "Please shut down gracefully.",
"shutdown_request", Map.of("request_id", reqId)
);
// 发送请求:向目标智能体发送关机请求
return String.format("Shutdown request %s sent to '%s' (status: pending)", reqId, teammate);
}
/**
* 处理计划审批
*/
private static String handlePlanReview(String requestId, boolean approve, String feedback) {
PlanRequest req;
synchronized (trackerLock) {
req = planRequests.get(requestId);
}
if (req == null) {
return String.format("Error: Unknown plan request_id '%s'", requestId);
}
synchronized (trackerLock) {
req.status = approve ? "approved" : "rejected";
}
// 状态更新:更新计划审批状态
BUS.send(
"lead", req.from, feedback, "plan_approval_response",
Map.of("request_id", requestId, "approve", approve, "feedback", feedback)
);
// 回复提交者:发送审批结果和反馈
return String.format("Plan %s for '%s'", approve ? "approved" : "rejected", req.from);
}
/**
* 检查关机请求状态
*/
private static String checkShutdownStatus(String requestId) {
synchronized (trackerLock) {
ShutdownRequest req = shutdownRequests.get(requestId);
if (req == null) {
return gson.toJson(Map.of("error", "not found"));
}
return gson.toJson(Map.of(
"request_id", req.requestId,
"target", req.target,
"status", req.status,
"timestamp", req.timestamp更多推荐



所有评论(0)