Back to Team Protocols
Agent Teams → Team Protocols
s09 (278 LOC) → s10 (317 LOC)
LOC Delta
+39lines
New Tools
3
shutdown_responseplan_approvalshutdown_request
New Classes
0
New Functions
2
handleShutdownRequesthandlePlanReview
Agent Teams
Teammates + Mailboxes
278 LOC
9 tools: bash, read_file, write_file, edit_file, send_message, read_inbox, spawn_teammate, list_teammates, broadcast
collaborationTeam Protocols
Shared Communication Rules
317 LOC
12 tools: bash, read_file, write_file, edit_file, send_message, read_inbox, shutdown_response, plan_approval, spawn_teammate, list_teammates, broadcast, shutdown_request
collaborationSource Code Diff
s09 (s09_agent_teams.ts) -> s10 (s10_team_protocols.ts)
| 1 | 1 | #!/usr/bin/env node | |
| 2 | 2 | /** | |
| 3 | - | * s09_agent_teams.ts - Agent Teams | |
| 3 | + | * s10_team_protocols.ts - Team Protocols | |
| 4 | 4 | * | |
| 5 | - | * Persistent teammates with JSONL inboxes. | |
| 5 | + | * request_id based shutdown and plan approval protocols. | |
| 6 | 6 | */ | |
| 7 | 7 | ||
| 8 | 8 | import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; | |
| 9 | + | import { spawnSync } from "node:child_process"; | |
| 9 | 10 | import { resolve } from "node:path"; | |
| 10 | 11 | import process from "node:process"; | |
| 11 | - | import { spawnSync } from "node:child_process"; | |
| 12 | + | import { randomUUID } from "node:crypto"; | |
| 12 | 13 | import { createInterface } from "node:readline/promises"; | |
| 13 | 14 | import type Anthropic from "@anthropic-ai/sdk"; | |
| 14 | 15 | import "dotenv/config"; | |
| 15 | 16 | import { buildSystemPrompt, createAnthropicClient, resolveModel, shellToolDescription } from "./shared"; | |
| 16 | 17 | ||
| 18 | + | type MessageType = "message" | "broadcast" | "shutdown_request" | "shutdown_response" | "plan_approval_response"; | |
| 17 | 19 | type ToolName = | |
| 18 | 20 | | "bash" | "read_file" | "write_file" | "edit_file" | |
| 19 | - | | "spawn_teammate" | "list_teammates" | "send_message" | "read_inbox" | "broadcast"; | |
| 20 | - | type MessageType = "message" | "broadcast" | "shutdown_request" | "shutdown_response" | "plan_approval_response"; | |
| 21 | + | | "spawn_teammate" | "list_teammates" | "send_message" | "read_inbox" | "broadcast" | |
| 22 | + | | "shutdown_request" | "shutdown_response" | "plan_approval"; | |
| 21 | 23 | type ToolUseBlock = { id: string; type: "tool_use"; name: ToolName; input: Record<string, unknown> }; | |
| 22 | 24 | type TextBlock = { type: "text"; text: string }; | |
| 23 | 25 | type ToolResultBlock = { type: "tool_result"; tool_use_id: string; content: string }; | |
| 24 | 26 | type Message = { role: "user" | "assistant"; content: string | Array<ToolUseBlock | TextBlock | ToolResultBlock> }; | |
| 25 | 27 | type TeamMember = { name: string; role: string; status: "working" | "idle" | "shutdown" }; | |
| 26 | 28 | type TeamConfig = { team_name: string; members: TeamMember[] }; | |
| 27 | 29 | ||
| 28 | 30 | const WORKDIR = process.cwd(); | |
| 29 | 31 | const MODEL = resolveModel(); | |
| 30 | 32 | const TEAM_DIR = resolve(WORKDIR, ".team"); | |
| 31 | 33 | const INBOX_DIR = resolve(TEAM_DIR, "inbox"); | |
| 32 | 34 | const VALID_MSG_TYPES: MessageType[] = ["message", "broadcast", "shutdown_request", "shutdown_response", "plan_approval_response"]; | |
| 35 | + | const shutdownRequests: Record<string, { target: string; status: string }> = {}; | |
| 36 | + | const planRequests: Record<string, { from: string; plan: string; status: string }> = {}; | |
| 33 | 37 | const client = createAnthropicClient(); | |
| 34 | 38 | ||
| 35 | - | const SYSTEM = buildSystemPrompt(`You are a team lead at ${WORKDIR}. Spawn teammates and communicate via inboxes.`); | |
| 39 | + | const SYSTEM = buildSystemPrompt(`You are a team lead at ${WORKDIR}. Manage teammates with shutdown and plan approval protocols.`); | |
| 36 | 40 | ||
| 37 | 41 | function safePath(relativePath: string) { | |
| 38 | 42 | const filePath = resolve(WORKDIR, relativePath); | |
| 39 | 43 | const normalizedWorkdir = `${WORKDIR}${process.platform === "win32" ? "\\" : "/"}`; | |
| 40 | 44 | if (filePath !== WORKDIR && !filePath.startsWith(normalizedWorkdir)) throw new Error(`Path escapes workspace: ${relativePath}`); | |
| 41 | 45 | return filePath; | |
| 42 | 46 | } | |
| 43 | 47 | ||
| 44 | 48 | function runBash(command: string): string { | |
| 45 | 49 | const dangerous = ["rm -rf /", "sudo", "shutdown", "reboot", "> /dev/"]; | |
| 46 | 50 | if (dangerous.some((item) => command.includes(item))) return "Error: Dangerous command blocked"; | |
| 47 | 51 | const shell = process.platform === "win32" ? "cmd.exe" : "/bin/sh"; | |
| 48 | 52 | const args = process.platform === "win32" ? ["/d", "/s", "/c", command] : ["-lc", command]; | |
| 49 | 53 | const result = spawnSync(shell, args, { cwd: WORKDIR, encoding: "utf8", timeout: 120_000 }); | |
| 50 | 54 | if (result.error?.name === "TimeoutError") return "Error: Timeout (120s)"; | |
| 51 | 55 | const output = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim(); | |
| 52 | 56 | return output.slice(0, 50_000) || "(no output)"; | |
| 53 | 57 | } | |
| 54 | 58 | ||
| 55 | 59 | function runRead(path: string, limit?: number): string { | |
| 56 | 60 | try { | |
| 57 | 61 | let lines = readFileSync(safePath(path), "utf8").split(/\r?\n/); | |
| 58 | 62 | if (limit && limit < lines.length) lines = lines.slice(0, limit).concat(`... (${lines.length - limit} more)`); | |
| 59 | 63 | return lines.join("\n").slice(0, 50_000); | |
| 60 | 64 | } catch (error) { | |
| 61 | 65 | return `Error: ${error instanceof Error ? error.message : String(error)}`; | |
| 62 | 66 | } | |
| 63 | 67 | } | |
| 64 | 68 | ||
| 65 | 69 | function runWrite(path: string, content: string): string { | |
| 66 | 70 | try { | |
| 67 | 71 | const filePath = safePath(path); | |
| 68 | 72 | mkdirSync(resolve(filePath, ".."), { recursive: true }); | |
| 69 | 73 | writeFileSync(filePath, content, "utf8"); | |
| 70 | 74 | return `Wrote ${content.length} bytes`; | |
| 71 | 75 | } catch (error) { | |
| 72 | 76 | return `Error: ${error instanceof Error ? error.message : String(error)}`; | |
| 73 | 77 | } | |
| 74 | 78 | } | |
| 75 | 79 | ||
| 76 | 80 | function runEdit(path: string, oldText: string, newText: string): string { | |
| 77 | 81 | try { | |
| 78 | 82 | const filePath = safePath(path); | |
| 79 | 83 | const content = readFileSync(filePath, "utf8"); | |
| 80 | 84 | if (!content.includes(oldText)) return `Error: Text not found in ${path}`; | |
| 81 | 85 | writeFileSync(filePath, content.replace(oldText, newText), "utf8"); | |
| 82 | 86 | return `Edited ${path}`; | |
| 83 | 87 | } catch (error) { | |
| 84 | 88 | return `Error: ${error instanceof Error ? error.message : String(error)}`; | |
| 85 | 89 | } | |
| 86 | 90 | } | |
| 87 | 91 | ||
| 88 | 92 | class MessageBus { | |
| 89 | 93 | constructor(private inboxDir: string) { | |
| 90 | 94 | mkdirSync(inboxDir, { recursive: true }); | |
| 91 | 95 | } | |
| 92 | 96 | ||
| 93 | 97 | send(sender: string, to: string, content: string, msgType: MessageType = "message", extra?: Record<string, unknown>) { | |
| 94 | 98 | if (!VALID_MSG_TYPES.includes(msgType)) return `Error: Invalid type '${msgType}'.`; | |
| 95 | 99 | const payload = { type: msgType, from: sender, content, timestamp: Date.now() / 1000, ...(extra ?? {}) }; | |
| 96 | 100 | appendFileSync(resolve(this.inboxDir, `${to}.jsonl`), `${JSON.stringify(payload)}\n`, "utf8"); | |
| 97 | 101 | return `Sent ${msgType} to ${to}`; | |
| 98 | 102 | } | |
| 99 | 103 | ||
| 100 | 104 | readInbox(name: string) { | |
| 101 | 105 | const inboxPath = resolve(this.inboxDir, `${name}.jsonl`); | |
| 102 | 106 | if (!existsSync(inboxPath)) return []; | |
| 103 | 107 | const lines = readFileSync(inboxPath, "utf8").split(/\r?\n/).filter(Boolean); | |
| 104 | 108 | writeFileSync(inboxPath, "", "utf8"); | |
| 105 | 109 | return lines.map((line) => JSON.parse(line)); | |
| 106 | 110 | } | |
| 107 | 111 | ||
| 108 | 112 | broadcast(sender: string, content: string, teammates: string[]) { | |
| 109 | 113 | let count = 0; | |
| 110 | 114 | for (const name of teammates) { | |
| 111 | 115 | if (name === sender) continue; | |
| 112 | 116 | this.send(sender, name, content, "broadcast"); | |
| 113 | 117 | count += 1; | |
| 114 | 118 | } | |
| 115 | 119 | return `Broadcast to ${count} teammates`; | |
| 116 | 120 | } | |
| 117 | 121 | } | |
| 118 | 122 | ||
| 119 | 123 | const BUS = new MessageBus(INBOX_DIR); | |
| 120 | 124 | ||
| 121 | 125 | class TeammateManager { | |
| 122 | 126 | private configPath: string; | |
| 123 | 127 | private config: TeamConfig; | |
| 124 | 128 | ||
| 125 | 129 | constructor(private teamDir: string) { | |
| 126 | 130 | mkdirSync(teamDir, { recursive: true }); | |
| 127 | 131 | this.configPath = resolve(teamDir, "config.json"); | |
| 128 | 132 | this.config = this.loadConfig(); | |
| 129 | 133 | } | |
| 130 | 134 | ||
| 131 | 135 | private loadConfig(): TeamConfig { | |
| 132 | 136 | if (existsSync(this.configPath)) return JSON.parse(readFileSync(this.configPath, "utf8")) as TeamConfig; | |
| 133 | 137 | return { team_name: "default", members: [] }; | |
| 134 | 138 | } | |
| 135 | 139 | ||
| 136 | 140 | private saveConfig() { | |
| 137 | 141 | writeFileSync(this.configPath, `${JSON.stringify(this.config, null, 2)}\n`, "utf8"); | |
| 138 | 142 | } | |
| 139 | 143 | ||
| 140 | 144 | private findMember(name: string) { | |
| 141 | 145 | return this.config.members.find((member) => member.name === name); | |
| 142 | 146 | } | |
| 143 | 147 | ||
| 144 | 148 | spawn(name: string, role: string, prompt: string) { | |
| 145 | 149 | let member = this.findMember(name); | |
| 146 | 150 | if (member) { | |
| 147 | 151 | if (!["idle", "shutdown"].includes(member.status)) return `Error: '${name}' is currently ${member.status}`; | |
| 148 | 152 | member.status = "working"; | |
| 149 | 153 | member.role = role; | |
| 150 | 154 | } else { | |
| 151 | 155 | member = { name, role, status: "working" }; | |
| 152 | 156 | this.config.members.push(member); | |
| 153 | 157 | } | |
| 154 | 158 | this.saveConfig(); | |
| 155 | 159 | void this.teammateLoop(name, role, prompt); | |
| 156 | 160 | return `Spawned '${name}' (role: ${role})`; | |
| 157 | 161 | } | |
| 158 | 162 | ||
| 159 | 163 | private async teammateLoop(name: string, role: string, prompt: string) { | |
| 160 | - | const sysPrompt = buildSystemPrompt(`You are '${name}', role: ${role}, at ${WORKDIR}. Use send_message to communicate. Complete your task.`); | |
| 164 | + | const sysPrompt = buildSystemPrompt(`You are '${name}', role: ${role}, at ${WORKDIR}. Submit plans via plan_approval before major work. Respond to shutdown_request with shutdown_response.`); | |
| 161 | 165 | const messages: Message[] = [{ role: "user", content: prompt }]; | |
| 162 | - | ||
| 166 | + | let shouldExit = false; | |
| 163 | 167 | for (let attempt = 0; attempt < 50; attempt += 1) { | |
| 164 | - | const inbox = BUS.readInbox(name); | |
| 165 | - | for (const message of inbox) messages.push({ role: "user", content: JSON.stringify(message) }); | |
| 166 | - | ||
| 168 | + | for (const msg of BUS.readInbox(name)) messages.push({ role: "user", content: JSON.stringify(msg) }); | |
| 169 | + | if (shouldExit) break; | |
| 167 | 170 | const response = await client.messages.create({ | |
| 168 | 171 | model: MODEL, | |
| 169 | 172 | system: sysPrompt, | |
| 170 | 173 | messages: messages as Anthropic.Messages.MessageParam[], | |
| 171 | - | tools: this.teammateTools() as Anthropic.Messages.Tool[], | |
| 174 | + | tools: this.tools() as Anthropic.Messages.Tool[], | |
| 172 | 175 | max_tokens: 8000, | |
| 173 | 176 | }).catch(() => null); | |
| 174 | 177 | if (!response) break; | |
| 175 | - | ||
| 176 | 178 | messages.push({ role: "assistant", content: response.content as Array<ToolUseBlock | TextBlock> }); | |
| 177 | 179 | if (response.stop_reason !== "tool_use") break; | |
| 178 | - | ||
| 179 | 180 | const results: ToolResultBlock[] = []; | |
| 180 | 181 | for (const block of response.content) { | |
| 181 | 182 | if (block.type !== "tool_use") continue; | |
| 182 | 183 | const output = this.exec(name, block.name, block.input as Record<string, unknown>); | |
| 184 | + | if (block.name === "shutdown_response" && block.input.approve) shouldExit = true; | |
| 183 | 185 | console.log(` [${name}] ${block.name}: ${output.slice(0, 120)}`); | |
| 184 | 186 | results.push({ type: "tool_result", tool_use_id: block.id, content: output }); | |
| 185 | 187 | } | |
| 186 | 188 | messages.push({ role: "user", content: results }); | |
| 187 | 189 | } | |
| 188 | - | ||
| 189 | 190 | const member = this.findMember(name); | |
| 190 | - | if (member && member.status !== "shutdown") { | |
| 191 | - | member.status = "idle"; | |
| 191 | + | if (member) { | |
| 192 | + | member.status = shouldExit ? "shutdown" : "idle"; | |
| 192 | 193 | this.saveConfig(); | |
| 193 | 194 | } | |
| 194 | 195 | } | |
| 195 | 196 | ||
| 196 | - | private teammateTools() { | |
| 197 | + | private tools() { | |
| 197 | 198 | return [ | |
| 198 | 199 | { name: "bash", description: shellToolDescription(), input_schema: { type: "object", properties: { command: { type: "string" } }, required: ["command"] } }, | |
| 199 | 200 | { name: "read_file", description: "Read file contents.", input_schema: { type: "object", properties: { path: { type: "string" }, limit: { type: "integer" } }, required: ["path"] } }, | |
| 200 | 201 | { name: "write_file", description: "Write content to file.", input_schema: { type: "object", properties: { path: { type: "string" }, content: { type: "string" } }, required: ["path", "content"] } }, | |
| 201 | 202 | { name: "edit_file", description: "Replace exact text in file.", input_schema: { type: "object", properties: { path: { type: "string" }, old_text: { type: "string" }, new_text: { type: "string" } }, required: ["path", "old_text", "new_text"] } }, | |
| 202 | 203 | { name: "send_message", description: "Send message to a teammate.", input_schema: { type: "object", properties: { to: { type: "string" }, content: { type: "string" }, msg_type: { type: "string", enum: VALID_MSG_TYPES } }, required: ["to", "content"] } }, | |
| 203 | 204 | { name: "read_inbox", description: "Read and drain your inbox.", input_schema: { type: "object", properties: {} } }, | |
| 205 | + | { name: "shutdown_response", description: "Respond to a shutdown request.", input_schema: { type: "object", properties: { request_id: { type: "string" }, approve: { type: "boolean" }, reason: { type: "string" } }, required: ["request_id", "approve"] } }, | |
| 206 | + | { name: "plan_approval", description: "Submit a plan for lead approval.", input_schema: { type: "object", properties: { plan: { type: "string" } }, required: ["plan"] } }, | |
| 204 | 207 | ]; | |
| 205 | 208 | } | |
| 206 | 209 | ||
| 207 | 210 | private exec(sender: string, toolName: string, input: Record<string, unknown>) { | |
| 208 | 211 | if (toolName === "bash") return runBash(String(input.command ?? "")); | |
| 209 | 212 | if (toolName === "read_file") return runRead(String(input.path ?? ""), Number(input.limit ?? 0) || undefined); | |
| 210 | 213 | if (toolName === "write_file") return runWrite(String(input.path ?? ""), String(input.content ?? "")); | |
| 211 | 214 | if (toolName === "edit_file") return runEdit(String(input.path ?? ""), String(input.old_text ?? ""), String(input.new_text ?? "")); | |
| 212 | 215 | if (toolName === "send_message") return BUS.send(sender, String(input.to ?? ""), String(input.content ?? ""), (input.msg_type as MessageType | undefined) ?? "message"); | |
| 213 | 216 | if (toolName === "read_inbox") return JSON.stringify(BUS.readInbox(sender), null, 2); | |
| 217 | + | if (toolName === "shutdown_response") { | |
| 218 | + | const requestId = String(input.request_id ?? ""); | |
| 219 | + | shutdownRequests[requestId] = { ...(shutdownRequests[requestId] ?? { target: sender }), status: input.approve ? "approved" : "rejected" }; | |
| 220 | + | BUS.send(sender, "lead", String(input.reason ?? ""), "shutdown_response", { request_id: requestId, approve: Boolean(input.approve) }); | |
| 221 | + | return `Shutdown ${input.approve ? "approved" : "rejected"}`; | |
| 222 | + | } | |
| 223 | + | if (toolName === "plan_approval") { | |
| 224 | + | const requestId = randomUUID().slice(0, 8); | |
| 225 | + | planRequests[requestId] = { from: sender, plan: String(input.plan ?? ""), status: "pending" }; | |
| 226 | + | BUS.send(sender, "lead", String(input.plan ?? ""), "plan_approval_response", { request_id: requestId, plan: String(input.plan ?? "") }); | |
| 227 | + | return `Plan submitted (request_id=${requestId}). Waiting for lead approval.`; | |
| 228 | + | } | |
| 214 | 229 | return `Unknown tool: ${toolName}`; | |
| 215 | 230 | } | |
| 216 | - | ||
| 217 | 231 | listAll() { | |
| 218 | 232 | if (!this.config.members.length) return "No teammates."; | |
| 219 | 233 | return [`Team: ${this.config.team_name}`, ...this.config.members.map((m) => ` ${m.name} (${m.role}): ${m.status}`)].join("\n"); | |
| 220 | 234 | } | |
| 221 | 235 | ||
| 222 | 236 | memberNames() { | |
| 223 | 237 | return this.config.members.map((m) => m.name); | |
| 224 | 238 | } | |
| 225 | 239 | } | |
| 226 | 240 | ||
| 227 | 241 | const TEAM = new TeammateManager(TEAM_DIR); | |
| 228 | 242 | ||
| 243 | + | function handleShutdownRequest(teammate: string) { | |
| 244 | + | const requestId = randomUUID().slice(0, 8); | |
| 245 | + | shutdownRequests[requestId] = { target: teammate, status: "pending" }; | |
| 246 | + | BUS.send("lead", teammate, "Please shut down gracefully.", "shutdown_request", { request_id: requestId }); | |
| 247 | + | return `Shutdown request ${requestId} sent to '${teammate}' (status: pending)`; | |
| 248 | + | } | |
| 249 | + | ||
| 250 | + | function handlePlanReview(requestId: string, approve: boolean, feedback = "") { | |
| 251 | + | const request = planRequests[requestId]; | |
| 252 | + | if (!request) return `Error: Unknown plan request_id '${requestId}'`; | |
| 253 | + | request.status = approve ? "approved" : "rejected"; | |
| 254 | + | BUS.send("lead", request.from, feedback, "plan_approval_response", { request_id: requestId, approve, feedback }); | |
| 255 | + | return `Plan ${request.status} for '${request.from}'`; | |
| 256 | + | } | |
| 257 | + | ||
| 229 | 258 | const TOOL_HANDLERS: Record<ToolName, (input: Record<string, unknown>) => string> = { | |
| 230 | 259 | bash: (input) => runBash(String(input.command ?? "")), | |
| 231 | 260 | read_file: (input) => runRead(String(input.path ?? ""), Number(input.limit ?? 0) || undefined), | |
| 232 | 261 | write_file: (input) => runWrite(String(input.path ?? ""), String(input.content ?? "")), | |
| 233 | 262 | edit_file: (input) => runEdit(String(input.path ?? ""), String(input.old_text ?? ""), String(input.new_text ?? "")), | |
| 234 | 263 | spawn_teammate: (input) => TEAM.spawn(String(input.name ?? ""), String(input.role ?? ""), String(input.prompt ?? "")), | |
| 235 | 264 | list_teammates: () => TEAM.listAll(), | |
| 236 | 265 | send_message: (input) => BUS.send("lead", String(input.to ?? ""), String(input.content ?? ""), (input.msg_type as MessageType | undefined) ?? "message"), | |
| 237 | 266 | read_inbox: () => JSON.stringify(BUS.readInbox("lead"), null, 2), | |
| 238 | 267 | broadcast: (input) => BUS.broadcast("lead", String(input.content ?? ""), TEAM.memberNames()), | |
| 268 | + | shutdown_request: (input) => handleShutdownRequest(String(input.teammate ?? "")), | |
| 269 | + | shutdown_response: (input) => JSON.stringify(shutdownRequests[String(input.request_id ?? "")] ?? { error: "not found" }), | |
| 270 | + | plan_approval: (input) => handlePlanReview(String(input.request_id ?? ""), Boolean(input.approve), String(input.feedback ?? "")), | |
| 239 | 271 | }; | |
| 240 | 272 | ||
| 241 | 273 | const TOOLS = [ | |
| 242 | 274 | { name: "bash", description: shellToolDescription(), input_schema: { type: "object", properties: { command: { type: "string" } }, required: ["command"] } }, | |
| 243 | 275 | { name: "read_file", description: "Read file contents.", input_schema: { type: "object", properties: { path: { type: "string" }, limit: { type: "integer" } }, required: ["path"] } }, | |
| 244 | 276 | { name: "write_file", description: "Write content to file.", input_schema: { type: "object", properties: { path: { type: "string" }, content: { type: "string" } }, required: ["path", "content"] } }, | |
| 245 | 277 | { name: "edit_file", description: "Replace exact text in file.", input_schema: { type: "object", properties: { path: { type: "string" }, old_text: { type: "string" }, new_text: { type: "string" } }, required: ["path", "old_text", "new_text"] } }, | |
| 246 | - | { name: "spawn_teammate", description: "Spawn a persistent teammate that runs in its own loop.", input_schema: { type: "object", properties: { name: { type: "string" }, role: { type: "string" }, prompt: { type: "string" } }, required: ["name", "role", "prompt"] } }, | |
| 247 | - | { name: "list_teammates", description: "List all teammates with name, role, status.", input_schema: { type: "object", properties: {} } }, | |
| 248 | - | { name: "send_message", description: "Send a message to a teammate inbox.", input_schema: { type: "object", properties: { to: { type: "string" }, content: { type: "string" }, msg_type: { type: "string", enum: VALID_MSG_TYPES } }, required: ["to", "content"] } }, | |
| 278 | + | { name: "spawn_teammate", description: "Spawn a persistent teammate.", input_schema: { type: "object", properties: { name: { type: "string" }, role: { type: "string" }, prompt: { type: "string" } }, required: ["name", "role", "prompt"] } }, | |
| 279 | + | { name: "list_teammates", description: "List all teammates.", input_schema: { type: "object", properties: {} } }, | |
| 280 | + | { name: "send_message", description: "Send a message to a teammate.", input_schema: { type: "object", properties: { to: { type: "string" }, content: { type: "string" }, msg_type: { type: "string", enum: VALID_MSG_TYPES } }, required: ["to", "content"] } }, | |
| 249 | 281 | { name: "read_inbox", description: "Read and drain the lead inbox.", input_schema: { type: "object", properties: {} } }, | |
| 250 | 282 | { name: "broadcast", description: "Send a message to all teammates.", input_schema: { type: "object", properties: { content: { type: "string" } }, required: ["content"] } }, | |
| 283 | + | { name: "shutdown_request", description: "Request a teammate to shut down gracefully.", input_schema: { type: "object", properties: { teammate: { type: "string" } }, required: ["teammate"] } }, | |
| 284 | + | { name: "shutdown_response", description: "Check shutdown request status by request_id.", input_schema: { type: "object", properties: { request_id: { type: "string" } }, required: ["request_id"] } }, | |
| 285 | + | { name: "plan_approval", description: "Approve or reject a teammate plan.", input_schema: { type: "object", properties: { request_id: { type: "string" }, approve: { type: "boolean" }, feedback: { type: "string" } }, required: ["request_id", "approve"] } }, | |
| 251 | 286 | ]; | |
| 252 | 287 | ||
| 253 | 288 | function assistantText(content: Array<ToolUseBlock | TextBlock>) { | |
| 254 | 289 | return content.filter((block): block is TextBlock => block.type === "text").map((block) => block.text).join("\n"); | |
| 255 | 290 | } | |
| 256 | 291 | ||
| 257 | 292 | export async function agentLoop(messages: Message[]) { | |
| 258 | 293 | while (true) { | |
| 259 | 294 | const inbox = BUS.readInbox("lead"); | |
| 260 | 295 | if (inbox.length) { | |
| 261 | 296 | messages.push({ role: "user", content: `<inbox>${JSON.stringify(inbox, null, 2)}</inbox>` }); | |
| 262 | 297 | messages.push({ role: "assistant", content: "Noted inbox messages." }); | |
| 263 | 298 | } | |
| 264 | - | ||
| 265 | 299 | const response = await client.messages.create({ | |
| 266 | 300 | model: MODEL, | |
| 267 | 301 | system: SYSTEM, | |
| 268 | 302 | messages: messages as Anthropic.Messages.MessageParam[], | |
| 269 | 303 | tools: TOOLS as Anthropic.Messages.Tool[], | |
| 270 | 304 | max_tokens: 8000, | |
| 271 | 305 | }); | |
| 272 | 306 | messages.push({ role: "assistant", content: response.content as Array<ToolUseBlock | TextBlock> }); | |
| 273 | 307 | if (response.stop_reason !== "tool_use") return; | |
| 274 | - | ||
| 275 | 308 | const results: ToolResultBlock[] = []; | |
| 276 | 309 | for (const block of response.content) { | |
| 277 | 310 | if (block.type !== "tool_use") continue; | |
| 278 | 311 | const handler = TOOL_HANDLERS[block.name as ToolName]; | |
| 279 | 312 | const output = handler ? handler(block.input as Record<string, unknown>) : `Unknown tool: ${block.name}`; | |
| 280 | 313 | console.log(`> ${block.name}: ${output.slice(0, 200)}`); | |
| 281 | 314 | results.push({ type: "tool_result", tool_use_id: block.id, content: output }); | |
| 282 | 315 | } | |
| 283 | 316 | messages.push({ role: "user", content: results }); | |
| 284 | 317 | } | |
| 285 | 318 | } | |
| 286 | 319 | ||
| 287 | 320 | async function main() { | |
| 288 | 321 | const rl = createInterface({ input: process.stdin, output: process.stdout }); | |
| 289 | 322 | const history: Message[] = []; | |
| 290 | 323 | while (true) { | |
| 291 | 324 | let query = ""; | |
| 292 | 325 | try { | |
| 293 | - | query = await rl.question("\x1b[36ms09 >> \x1b[0m"); | |
| 326 | + | query = await rl.question("\x1b[36ms10 >> \x1b[0m"); | |
| 294 | 327 | } catch (error) { | |
| 295 | 328 | if ( | |
| 296 | 329 | error instanceof Error && | |
| 297 | 330 | (("code" in error && error.code === "ERR_USE_AFTER_CLOSE") || error.name === "AbortError") | |
| 298 | 331 | ) { | |
| 299 | 332 | break; | |
| 300 | 333 | } | |
| 301 | 334 | throw error; | |
| 302 | 335 | } | |
| 303 | 336 | if (!query.trim() || ["q", "exit"].includes(query.trim().toLowerCase())) break; | |
| 304 | 337 | if (query.trim() === "/team") { console.log(TEAM.listAll()); continue; } | |
| 305 | 338 | if (query.trim() === "/inbox") { console.log(JSON.stringify(BUS.readInbox("lead"), null, 2)); continue; } | |
| 306 | 339 | history.push({ role: "user", content: query }); | |
| 307 | 340 | await agentLoop(history); | |
| 308 | 341 | const last = history[history.length - 1]?.content; | |
| 309 | 342 | if (Array.isArray(last)) { | |
| 310 | 343 | const text = assistantText(last as Array<ToolUseBlock | TextBlock>); | |
| 311 | 344 | if (text) console.log(text); | |
| 312 | 345 | } | |
| 313 | 346 | console.log(); | |
| 314 | 347 | } | |
| 315 | 348 | rl.close(); | |
| 316 | 349 | } | |
| 317 | 350 | ||
| 318 | 351 | void main(); |