Back to Autonomous Agents
Team Protocols → Autonomous Agents
s10 (317 LOC) → s11 (413 LOC)
LOC Delta
+96lines
New Tools
2
idleclaim_task
New Classes
0
New Functions
4
sleepscanUnclaimedTasksclaimTaskmakeIdentityBlock
Team 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
collaborationAutonomous Agents
Scan Board, Claim Tasks
413 LOC
14 tools: bash, read_file, write_file, edit_file, send_message, read_inbox, shutdown_response, plan_approval, idle, claim_task, spawn_teammate, list_teammates, broadcast, shutdown_request
collaborationSource Code Diff
s10 (s10_team_protocols.ts) -> s11 (s11_autonomous_agents.ts)
| 1 | 1 | #!/usr/bin/env node | |
| 2 | 2 | /** | |
| 3 | - | * s10_team_protocols.ts - Team Protocols | |
| 3 | + | * s11_autonomous_agents.ts - Autonomous Agents | |
| 4 | 4 | * | |
| 5 | - | * request_id based shutdown and plan approval protocols. | |
| 5 | + | * Idle polling + auto-claim task board + identity re-injection. | |
| 6 | 6 | */ | |
| 7 | 7 | ||
| 8 | - | import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; | |
| 8 | + | import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; | |
| 9 | 9 | import { spawnSync } from "node:child_process"; | |
| 10 | 10 | import { resolve } from "node:path"; | |
| 11 | 11 | import process from "node:process"; | |
| 12 | 12 | import { randomUUID } from "node:crypto"; | |
| 13 | 13 | import { createInterface } from "node:readline/promises"; | |
| 14 | 14 | import type Anthropic from "@anthropic-ai/sdk"; | |
| 15 | 15 | import "dotenv/config"; | |
| 16 | 16 | import { buildSystemPrompt, createAnthropicClient, resolveModel, shellToolDescription } from "./shared"; | |
| 17 | 17 | ||
| 18 | 18 | type MessageType = "message" | "broadcast" | "shutdown_request" | "shutdown_response" | "plan_approval_response"; | |
| 19 | 19 | type ToolName = | |
| 20 | 20 | | "bash" | "read_file" | "write_file" | "edit_file" | |
| 21 | 21 | | "spawn_teammate" | "list_teammates" | "send_message" | "read_inbox" | "broadcast" | |
| 22 | - | | "shutdown_request" | "shutdown_response" | "plan_approval"; | |
| 22 | + | | "shutdown_request" | "shutdown_response" | "plan_approval" | "idle" | "claim_task"; | |
| 23 | 23 | type ToolUseBlock = { id: string; type: "tool_use"; name: ToolName; input: Record<string, unknown> }; | |
| 24 | 24 | type TextBlock = { type: "text"; text: string }; | |
| 25 | 25 | type ToolResultBlock = { type: "tool_result"; tool_use_id: string; content: string }; | |
| 26 | 26 | type Message = { role: "user" | "assistant"; content: string | Array<ToolUseBlock | TextBlock | ToolResultBlock> }; | |
| 27 | 27 | type TeamMember = { name: string; role: string; status: "working" | "idle" | "shutdown" }; | |
| 28 | 28 | type TeamConfig = { team_name: string; members: TeamMember[] }; | |
| 29 | + | type TaskRecord = { id: number; subject: string; description?: string; status: string; owner?: string; blockedBy?: number[] }; | |
| 29 | 30 | ||
| 30 | 31 | const WORKDIR = process.cwd(); | |
| 31 | 32 | const MODEL = resolveModel(); | |
| 32 | 33 | const TEAM_DIR = resolve(WORKDIR, ".team"); | |
| 33 | 34 | const INBOX_DIR = resolve(TEAM_DIR, "inbox"); | |
| 35 | + | const TASKS_DIR = resolve(WORKDIR, ".tasks"); | |
| 36 | + | const POLL_INTERVAL = 5_000; | |
| 37 | + | const IDLE_TIMEOUT = 60_000; | |
| 34 | 38 | const VALID_MSG_TYPES: MessageType[] = ["message", "broadcast", "shutdown_request", "shutdown_response", "plan_approval_response"]; | |
| 35 | 39 | const shutdownRequests: Record<string, { target: string; status: string }> = {}; | |
| 36 | 40 | const planRequests: Record<string, { from: string; plan: string; status: string }> = {}; | |
| 37 | 41 | const client = createAnthropicClient(); | |
| 38 | 42 | ||
| 39 | - | const SYSTEM = buildSystemPrompt(`You are a team lead at ${WORKDIR}. Manage teammates with shutdown and plan approval protocols.`); | |
| 43 | + | const SYSTEM = buildSystemPrompt(`You are a team lead at ${WORKDIR}. Teammates are autonomous -- they find work themselves.`); | |
| 40 | 44 | ||
| 45 | + | function sleep(ms: number) { | |
| 46 | + | return new Promise((resolveSleep) => setTimeout(resolveSleep, ms)); | |
| 47 | + | } | |
| 48 | + | ||
| 41 | 49 | function safePath(relativePath: string) { | |
| 42 | 50 | const filePath = resolve(WORKDIR, relativePath); | |
| 43 | 51 | const normalizedWorkdir = `${WORKDIR}${process.platform === "win32" ? "\\" : "/"}`; | |
| 44 | 52 | if (filePath !== WORKDIR && !filePath.startsWith(normalizedWorkdir)) throw new Error(`Path escapes workspace: ${relativePath}`); | |
| 45 | 53 | return filePath; | |
| 46 | 54 | } | |
| 47 | 55 | ||
| 48 | 56 | function runBash(command: string): string { | |
| 49 | 57 | const dangerous = ["rm -rf /", "sudo", "shutdown", "reboot", "> /dev/"]; | |
| 50 | 58 | if (dangerous.some((item) => command.includes(item))) return "Error: Dangerous command blocked"; | |
| 51 | 59 | const shell = process.platform === "win32" ? "cmd.exe" : "/bin/sh"; | |
| 52 | 60 | const args = process.platform === "win32" ? ["/d", "/s", "/c", command] : ["-lc", command]; | |
| 53 | 61 | const result = spawnSync(shell, args, { cwd: WORKDIR, encoding: "utf8", timeout: 120_000 }); | |
| 54 | 62 | if (result.error?.name === "TimeoutError") return "Error: Timeout (120s)"; | |
| 55 | 63 | const output = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim(); | |
| 56 | 64 | return output.slice(0, 50_000) || "(no output)"; | |
| 57 | 65 | } | |
| 58 | 66 | ||
| 59 | 67 | function runRead(path: string, limit?: number): string { | |
| 60 | 68 | try { | |
| 61 | 69 | let lines = readFileSync(safePath(path), "utf8").split(/\r?\n/); | |
| 62 | 70 | if (limit && limit < lines.length) lines = lines.slice(0, limit).concat(`... (${lines.length - limit} more)`); | |
| 63 | 71 | return lines.join("\n").slice(0, 50_000); | |
| 64 | 72 | } catch (error) { | |
| 65 | 73 | return `Error: ${error instanceof Error ? error.message : String(error)}`; | |
| 66 | 74 | } | |
| 67 | 75 | } | |
| 68 | 76 | ||
| 69 | 77 | function runWrite(path: string, content: string): string { | |
| 70 | 78 | try { | |
| 71 | 79 | const filePath = safePath(path); | |
| 72 | 80 | mkdirSync(resolve(filePath, ".."), { recursive: true }); | |
| 73 | 81 | writeFileSync(filePath, content, "utf8"); | |
| 74 | 82 | return `Wrote ${content.length} bytes`; | |
| 75 | 83 | } catch (error) { | |
| 76 | 84 | return `Error: ${error instanceof Error ? error.message : String(error)}`; | |
| 77 | 85 | } | |
| 78 | 86 | } | |
| 79 | 87 | ||
| 80 | 88 | function runEdit(path: string, oldText: string, newText: string): string { | |
| 81 | 89 | try { | |
| 82 | 90 | const filePath = safePath(path); | |
| 83 | 91 | const content = readFileSync(filePath, "utf8"); | |
| 84 | 92 | if (!content.includes(oldText)) return `Error: Text not found in ${path}`; | |
| 85 | 93 | writeFileSync(filePath, content.replace(oldText, newText), "utf8"); | |
| 86 | 94 | return `Edited ${path}`; | |
| 87 | 95 | } catch (error) { | |
| 88 | 96 | return `Error: ${error instanceof Error ? error.message : String(error)}`; | |
| 89 | 97 | } | |
| 90 | 98 | } | |
| 91 | 99 | ||
| 100 | + | function scanUnclaimedTasks() { | |
| 101 | + | mkdirSync(TASKS_DIR, { recursive: true }); | |
| 102 | + | const tasks: TaskRecord[] = []; | |
| 103 | + | for (const entry of readdirSync(TASKS_DIR, { withFileTypes: true })) { | |
| 104 | + | if (!entry.isFile() || !/^task_\d+\.json$/.test(entry.name)) continue; | |
| 105 | + | const task = JSON.parse(readFileSync(resolve(TASKS_DIR, entry.name), "utf8")) as TaskRecord; | |
| 106 | + | if (task.status === "pending" && !task.owner && !(task.blockedBy?.length)) tasks.push(task); | |
| 107 | + | } | |
| 108 | + | return tasks.sort((a, b) => a.id - b.id); | |
| 109 | + | } | |
| 110 | + | ||
| 111 | + | function claimTask(taskId: number, owner: string) { | |
| 112 | + | const path = resolve(TASKS_DIR, `task_${taskId}.json`); | |
| 113 | + | if (!existsSync(path)) return `Error: Task ${taskId} not found`; | |
| 114 | + | const task = JSON.parse(readFileSync(path, "utf8")) as TaskRecord; | |
| 115 | + | task.owner = owner; | |
| 116 | + | task.status = "in_progress"; | |
| 117 | + | writeFileSync(path, `${JSON.stringify(task, null, 2)}\n`, "utf8"); | |
| 118 | + | return `Claimed task #${taskId} for ${owner}`; | |
| 119 | + | } | |
| 120 | + | ||
| 121 | + | function makeIdentityBlock(name: string, role: string, teamName: string): Message { | |
| 122 | + | return { role: "user", content: `<identity>You are '${name}', role: ${role}, team: ${teamName}. Continue your work.</identity>` }; | |
| 123 | + | } | |
| 124 | + | ||
| 92 | 125 | class MessageBus { | |
| 93 | 126 | constructor(private inboxDir: string) { | |
| 94 | 127 | mkdirSync(inboxDir, { recursive: true }); | |
| 95 | 128 | } | |
| 96 | 129 | ||
| 97 | 130 | send(sender: string, to: string, content: string, msgType: MessageType = "message", extra?: Record<string, unknown>) { | |
| 98 | 131 | if (!VALID_MSG_TYPES.includes(msgType)) return `Error: Invalid type '${msgType}'.`; | |
| 99 | 132 | const payload = { type: msgType, from: sender, content, timestamp: Date.now() / 1000, ...(extra ?? {}) }; | |
| 100 | 133 | appendFileSync(resolve(this.inboxDir, `${to}.jsonl`), `${JSON.stringify(payload)}\n`, "utf8"); | |
| 101 | 134 | return `Sent ${msgType} to ${to}`; | |
| 102 | 135 | } | |
| 103 | 136 | ||
| 104 | 137 | readInbox(name: string) { | |
| 105 | 138 | const inboxPath = resolve(this.inboxDir, `${name}.jsonl`); | |
| 106 | 139 | if (!existsSync(inboxPath)) return []; | |
| 107 | 140 | const lines = readFileSync(inboxPath, "utf8").split(/\r?\n/).filter(Boolean); | |
| 108 | 141 | writeFileSync(inboxPath, "", "utf8"); | |
| 109 | 142 | return lines.map((line) => JSON.parse(line)); | |
| 110 | 143 | } | |
| 111 | 144 | ||
| 112 | 145 | broadcast(sender: string, content: string, teammates: string[]) { | |
| 113 | 146 | let count = 0; | |
| 114 | 147 | for (const name of teammates) { | |
| 115 | 148 | if (name === sender) continue; | |
| 116 | 149 | this.send(sender, name, content, "broadcast"); | |
| 117 | 150 | count += 1; | |
| 118 | 151 | } | |
| 119 | 152 | return `Broadcast to ${count} teammates`; | |
| 120 | 153 | } | |
| 121 | 154 | } | |
| 122 | 155 | ||
| 123 | 156 | const BUS = new MessageBus(INBOX_DIR); | |
| 124 | 157 | ||
| 125 | 158 | class TeammateManager { | |
| 126 | 159 | private configPath: string; | |
| 127 | 160 | private config: TeamConfig; | |
| 128 | 161 | ||
| 129 | 162 | constructor(private teamDir: string) { | |
| 130 | 163 | mkdirSync(teamDir, { recursive: true }); | |
| 131 | 164 | this.configPath = resolve(teamDir, "config.json"); | |
| 132 | 165 | this.config = this.loadConfig(); | |
| 133 | 166 | } | |
| 134 | 167 | ||
| 135 | 168 | private loadConfig(): TeamConfig { | |
| 136 | 169 | if (existsSync(this.configPath)) return JSON.parse(readFileSync(this.configPath, "utf8")) as TeamConfig; | |
| 137 | 170 | return { team_name: "default", members: [] }; | |
| 138 | 171 | } | |
| 139 | 172 | ||
| 140 | 173 | private saveConfig() { | |
| 141 | 174 | writeFileSync(this.configPath, `${JSON.stringify(this.config, null, 2)}\n`, "utf8"); | |
| 142 | 175 | } | |
| 143 | 176 | ||
| 144 | 177 | private findMember(name: string) { | |
| 145 | 178 | return this.config.members.find((member) => member.name === name); | |
| 146 | 179 | } | |
| 147 | 180 | ||
| 181 | + | private setStatus(name: string, status: TeamMember["status"]) { | |
| 182 | + | const member = this.findMember(name); | |
| 183 | + | if (member) { | |
| 184 | + | member.status = status; | |
| 185 | + | this.saveConfig(); | |
| 186 | + | } | |
| 187 | + | } | |
| 188 | + | ||
| 148 | 189 | spawn(name: string, role: string, prompt: string) { | |
| 149 | 190 | let member = this.findMember(name); | |
| 150 | 191 | if (member) { | |
| 151 | 192 | if (!["idle", "shutdown"].includes(member.status)) return `Error: '${name}' is currently ${member.status}`; | |
| 152 | 193 | member.status = "working"; | |
| 153 | 194 | member.role = role; | |
| 154 | 195 | } else { | |
| 155 | 196 | member = { name, role, status: "working" }; | |
| 156 | 197 | this.config.members.push(member); | |
| 157 | 198 | } | |
| 158 | 199 | this.saveConfig(); | |
| 159 | - | void this.teammateLoop(name, role, prompt); | |
| 200 | + | void this.loop(name, role, prompt); | |
| 160 | 201 | return `Spawned '${name}' (role: ${role})`; | |
| 161 | 202 | } | |
| 162 | 203 | ||
| 163 | - | private async teammateLoop(name: string, role: string, prompt: string) { | |
| 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.`); | |
| 204 | + | private async loop(name: string, role: string, prompt: string) { | |
| 205 | + | const teamName = this.config.team_name; | |
| 206 | + | const sysPrompt = buildSystemPrompt(`You are '${name}', role: ${role}, team: ${teamName}, at ${WORKDIR}. Use idle when you have no more work. You will auto-claim new tasks.`); | |
| 165 | 207 | const messages: Message[] = [{ role: "user", content: prompt }]; | |
| 166 | - | let shouldExit = false; | |
| 167 | - | for (let attempt = 0; attempt < 50; attempt += 1) { | |
| 168 | - | for (const msg of BUS.readInbox(name)) messages.push({ role: "user", content: JSON.stringify(msg) }); | |
| 169 | - | if (shouldExit) break; | |
| 170 | - | const response = await client.messages.create({ | |
| 171 | - | model: MODEL, | |
| 172 | - | system: sysPrompt, | |
| 173 | - | messages: messages as Anthropic.Messages.MessageParam[], | |
| 174 | - | tools: this.tools() as Anthropic.Messages.Tool[], | |
| 175 | - | max_tokens: 8000, | |
| 176 | - | }).catch(() => null); | |
| 177 | - | if (!response) break; | |
| 178 | - | messages.push({ role: "assistant", content: response.content as Array<ToolUseBlock | TextBlock> }); | |
| 179 | - | if (response.stop_reason !== "tool_use") break; | |
| 180 | - | const results: ToolResultBlock[] = []; | |
| 181 | - | for (const block of response.content) { | |
| 182 | - | if (block.type !== "tool_use") continue; | |
| 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; | |
| 185 | - | console.log(` [${name}] ${block.name}: ${output.slice(0, 120)}`); | |
| 186 | - | results.push({ type: "tool_result", tool_use_id: block.id, content: output }); | |
| 208 | + | while (true) { | |
| 209 | + | let idleRequested = false; | |
| 210 | + | for (let attempt = 0; attempt < 50; attempt += 1) { | |
| 211 | + | for (const msg of BUS.readInbox(name)) { | |
| 212 | + | if (msg.type === "shutdown_request") { | |
| 213 | + | this.setStatus(name, "shutdown"); | |
| 214 | + | return; | |
| 215 | + | } | |
| 216 | + | messages.push({ role: "user", content: JSON.stringify(msg) }); | |
| 217 | + | } | |
| 218 | + | const response = await client.messages.create({ | |
| 219 | + | model: MODEL, | |
| 220 | + | system: sysPrompt, | |
| 221 | + | messages: messages as Anthropic.Messages.MessageParam[], | |
| 222 | + | tools: this.tools() as Anthropic.Messages.Tool[], | |
| 223 | + | max_tokens: 8000, | |
| 224 | + | }).catch(() => null); | |
| 225 | + | if (!response) { | |
| 226 | + | this.setStatus(name, "idle"); | |
| 227 | + | return; | |
| 228 | + | } | |
| 229 | + | messages.push({ role: "assistant", content: response.content as Array<ToolUseBlock | TextBlock> }); | |
| 230 | + | if (response.stop_reason !== "tool_use") break; | |
| 231 | + | const results: ToolResultBlock[] = []; | |
| 232 | + | for (const block of response.content) { | |
| 233 | + | if (block.type !== "tool_use") continue; | |
| 234 | + | let output = ""; | |
| 235 | + | if (block.name === "idle") { | |
| 236 | + | idleRequested = true; | |
| 237 | + | output = "Entering idle phase. Will poll for new tasks."; | |
| 238 | + | } else { | |
| 239 | + | output = this.exec(name, block.name, block.input as Record<string, unknown>); | |
| 240 | + | } | |
| 241 | + | console.log(` [${name}] ${block.name}: ${output.slice(0, 120)}`); | |
| 242 | + | results.push({ type: "tool_result", tool_use_id: block.id, content: output }); | |
| 243 | + | } | |
| 244 | + | messages.push({ role: "user", content: results }); | |
| 245 | + | if (idleRequested) break; | |
| 187 | 246 | } | |
| 188 | - | messages.push({ role: "user", content: results }); | |
| 247 | + | ||
| 248 | + | this.setStatus(name, "idle"); | |
| 249 | + | let resume = false; | |
| 250 | + | const start = Date.now(); | |
| 251 | + | while (Date.now() - start < IDLE_TIMEOUT) { | |
| 252 | + | await sleep(POLL_INTERVAL); | |
| 253 | + | const inbox = BUS.readInbox(name); | |
| 254 | + | if (inbox.length) { | |
| 255 | + | for (const msg of inbox) { | |
| 256 | + | if (msg.type === "shutdown_request") { | |
| 257 | + | this.setStatus(name, "shutdown"); | |
| 258 | + | return; | |
| 259 | + | } | |
| 260 | + | messages.push({ role: "user", content: JSON.stringify(msg) }); | |
| 261 | + | } | |
| 262 | + | resume = true; | |
| 263 | + | break; | |
| 264 | + | } | |
| 265 | + | const unclaimed = scanUnclaimedTasks(); | |
| 266 | + | if (unclaimed.length) { | |
| 267 | + | const task = unclaimed[0]; | |
| 268 | + | claimTask(task.id, name); | |
| 269 | + | if (messages.length <= 3) { | |
| 270 | + | messages.unshift({ role: "assistant", content: `I am ${name}. Continuing.` }); | |
| 271 | + | messages.unshift(makeIdentityBlock(name, role, teamName)); | |
| 272 | + | } | |
| 273 | + | messages.push({ role: "user", content: `<auto-claimed>Task #${task.id}: ${task.subject}\n${task.description ?? ""}</auto-claimed>` }); | |
| 274 | + | messages.push({ role: "assistant", content: `Claimed task #${task.id}. Working on it.` }); | |
| 275 | + | resume = true; | |
| 276 | + | break; | |
| 277 | + | } | |
| 278 | + | } | |
| 279 | + | ||
| 280 | + | if (!resume) { | |
| 281 | + | this.setStatus(name, "shutdown"); | |
| 282 | + | return; | |
| 283 | + | } | |
| 284 | + | this.setStatus(name, "working"); | |
| 189 | 285 | } | |
| 190 | - | const member = this.findMember(name); | |
| 191 | - | if (member) { | |
| 192 | - | member.status = shouldExit ? "shutdown" : "idle"; | |
| 193 | - | this.saveConfig(); | |
| 194 | - | } | |
| 195 | 286 | } | |
| 196 | 287 | ||
| 197 | 288 | private tools() { | |
| 198 | 289 | return [ | |
| 199 | 290 | { name: "bash", description: shellToolDescription(), input_schema: { type: "object", properties: { command: { type: "string" } }, required: ["command"] } }, | |
| 200 | 291 | { name: "read_file", description: "Read file contents.", input_schema: { type: "object", properties: { path: { type: "string" }, limit: { type: "integer" } }, required: ["path"] } }, | |
| 201 | 292 | { name: "write_file", description: "Write content to file.", input_schema: { type: "object", properties: { path: { type: "string" }, content: { type: "string" } }, required: ["path", "content"] } }, | |
| 202 | 293 | { 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"] } }, | |
| 203 | 294 | { 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"] } }, | |
| 204 | 295 | { name: "read_inbox", description: "Read and drain your inbox.", input_schema: { type: "object", properties: {} } }, | |
| 205 | 296 | { 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 | 297 | { name: "plan_approval", description: "Submit a plan for lead approval.", input_schema: { type: "object", properties: { plan: { type: "string" } }, required: ["plan"] } }, | |
| 298 | + | { name: "idle", description: "Signal that you have no more work.", input_schema: { type: "object", properties: {} } }, | |
| 299 | + | { name: "claim_task", description: "Claim a task by ID.", input_schema: { type: "object", properties: { task_id: { type: "integer" } }, required: ["task_id"] } }, | |
| 207 | 300 | ]; | |
| 208 | 301 | } | |
| 209 | 302 | ||
| 210 | 303 | private exec(sender: string, toolName: string, input: Record<string, unknown>) { | |
| 211 | 304 | if (toolName === "bash") return runBash(String(input.command ?? "")); | |
| 212 | 305 | if (toolName === "read_file") return runRead(String(input.path ?? ""), Number(input.limit ?? 0) || undefined); | |
| 213 | 306 | if (toolName === "write_file") return runWrite(String(input.path ?? ""), String(input.content ?? "")); | |
| 214 | 307 | if (toolName === "edit_file") return runEdit(String(input.path ?? ""), String(input.old_text ?? ""), String(input.new_text ?? "")); | |
| 215 | 308 | if (toolName === "send_message") return BUS.send(sender, String(input.to ?? ""), String(input.content ?? ""), (input.msg_type as MessageType | undefined) ?? "message"); | |
| 216 | 309 | if (toolName === "read_inbox") return JSON.stringify(BUS.readInbox(sender), null, 2); | |
| 217 | 310 | if (toolName === "shutdown_response") { | |
| 218 | 311 | const requestId = String(input.request_id ?? ""); | |
| 219 | 312 | shutdownRequests[requestId] = { ...(shutdownRequests[requestId] ?? { target: sender }), status: input.approve ? "approved" : "rejected" }; | |
| 220 | 313 | BUS.send(sender, "lead", String(input.reason ?? ""), "shutdown_response", { request_id: requestId, approve: Boolean(input.approve) }); | |
| 221 | 314 | return `Shutdown ${input.approve ? "approved" : "rejected"}`; | |
| 222 | 315 | } | |
| 223 | 316 | if (toolName === "plan_approval") { | |
| 224 | 317 | const requestId = randomUUID().slice(0, 8); | |
| 225 | 318 | planRequests[requestId] = { from: sender, plan: String(input.plan ?? ""), status: "pending" }; | |
| 226 | 319 | BUS.send(sender, "lead", String(input.plan ?? ""), "plan_approval_response", { request_id: requestId, plan: String(input.plan ?? "") }); | |
| 227 | 320 | return `Plan submitted (request_id=${requestId}). Waiting for lead approval.`; | |
| 228 | 321 | } | |
| 322 | + | if (toolName === "claim_task") return claimTask(Number(input.task_id ?? 0), sender); | |
| 229 | 323 | return `Unknown tool: ${toolName}`; | |
| 230 | 324 | } | |
| 231 | 325 | listAll() { | |
| 232 | 326 | if (!this.config.members.length) return "No teammates."; | |
| 233 | 327 | return [`Team: ${this.config.team_name}`, ...this.config.members.map((m) => ` ${m.name} (${m.role}): ${m.status}`)].join("\n"); | |
| 234 | 328 | } | |
| 235 | 329 | ||
| 236 | 330 | memberNames() { | |
| 237 | 331 | return this.config.members.map((m) => m.name); | |
| 238 | 332 | } | |
| 239 | 333 | } | |
| 240 | 334 | ||
| 241 | 335 | const TEAM = new TeammateManager(TEAM_DIR); | |
| 242 | 336 | ||
| 243 | 337 | function handleShutdownRequest(teammate: string) { | |
| 244 | 338 | const requestId = randomUUID().slice(0, 8); | |
| 245 | 339 | shutdownRequests[requestId] = { target: teammate, status: "pending" }; | |
| 246 | 340 | BUS.send("lead", teammate, "Please shut down gracefully.", "shutdown_request", { request_id: requestId }); | |
| 247 | 341 | return `Shutdown request ${requestId} sent to '${teammate}' (status: pending)`; | |
| 248 | 342 | } | |
| 249 | 343 | ||
| 250 | 344 | function handlePlanReview(requestId: string, approve: boolean, feedback = "") { | |
| 251 | 345 | const request = planRequests[requestId]; | |
| 252 | 346 | if (!request) return `Error: Unknown plan request_id '${requestId}'`; | |
| 253 | 347 | request.status = approve ? "approved" : "rejected"; | |
| 254 | 348 | BUS.send("lead", request.from, feedback, "plan_approval_response", { request_id: requestId, approve, feedback }); | |
| 255 | 349 | return `Plan ${request.status} for '${request.from}'`; | |
| 256 | 350 | } | |
| 257 | 351 | ||
| 258 | 352 | const TOOL_HANDLERS: Record<ToolName, (input: Record<string, unknown>) => string> = { | |
| 259 | 353 | bash: (input) => runBash(String(input.command ?? "")), | |
| 260 | 354 | read_file: (input) => runRead(String(input.path ?? ""), Number(input.limit ?? 0) || undefined), | |
| 261 | 355 | write_file: (input) => runWrite(String(input.path ?? ""), String(input.content ?? "")), | |
| 262 | 356 | edit_file: (input) => runEdit(String(input.path ?? ""), String(input.old_text ?? ""), String(input.new_text ?? "")), | |
| 263 | 357 | spawn_teammate: (input) => TEAM.spawn(String(input.name ?? ""), String(input.role ?? ""), String(input.prompt ?? "")), | |
| 264 | 358 | list_teammates: () => TEAM.listAll(), | |
| 265 | 359 | send_message: (input) => BUS.send("lead", String(input.to ?? ""), String(input.content ?? ""), (input.msg_type as MessageType | undefined) ?? "message"), | |
| 266 | 360 | read_inbox: () => JSON.stringify(BUS.readInbox("lead"), null, 2), | |
| 267 | 361 | broadcast: (input) => BUS.broadcast("lead", String(input.content ?? ""), TEAM.memberNames()), | |
| 268 | 362 | shutdown_request: (input) => handleShutdownRequest(String(input.teammate ?? "")), | |
| 269 | 363 | shutdown_response: (input) => JSON.stringify(shutdownRequests[String(input.request_id ?? "")] ?? { error: "not found" }), | |
| 270 | 364 | plan_approval: (input) => handlePlanReview(String(input.request_id ?? ""), Boolean(input.approve), String(input.feedback ?? "")), | |
| 365 | + | idle: () => "Lead does not idle.", | |
| 366 | + | claim_task: (input) => claimTask(Number(input.task_id ?? 0), "lead"), | |
| 271 | 367 | }; | |
| 272 | 368 | ||
| 273 | 369 | const TOOLS = [ | |
| 274 | 370 | { name: "bash", description: shellToolDescription(), input_schema: { type: "object", properties: { command: { type: "string" } }, required: ["command"] } }, | |
| 275 | 371 | { name: "read_file", description: "Read file contents.", input_schema: { type: "object", properties: { path: { type: "string" }, limit: { type: "integer" } }, required: ["path"] } }, | |
| 276 | 372 | { name: "write_file", description: "Write content to file.", input_schema: { type: "object", properties: { path: { type: "string" }, content: { type: "string" } }, required: ["path", "content"] } }, | |
| 277 | 373 | { 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"] } }, | |
| 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"] } }, | |
| 374 | + | { name: "spawn_teammate", description: "Spawn an autonomous teammate.", input_schema: { type: "object", properties: { name: { type: "string" }, role: { type: "string" }, prompt: { type: "string" } }, required: ["name", "role", "prompt"] } }, | |
| 279 | 375 | { name: "list_teammates", description: "List all teammates.", input_schema: { type: "object", properties: {} } }, | |
| 280 | 376 | { 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"] } }, | |
| 281 | 377 | { name: "read_inbox", description: "Read and drain the lead inbox.", input_schema: { type: "object", properties: {} } }, | |
| 282 | 378 | { 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"] } }, | |
| 379 | + | { name: "shutdown_request", description: "Request a teammate to shut down.", input_schema: { type: "object", properties: { teammate: { type: "string" } }, required: ["teammate"] } }, | |
| 380 | + | { name: "shutdown_response", description: "Check shutdown request status.", input_schema: { type: "object", properties: { request_id: { type: "string" } }, required: ["request_id"] } }, | |
| 285 | 381 | { 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"] } }, | |
| 382 | + | { name: "idle", description: "Enter idle state.", input_schema: { type: "object", properties: {} } }, | |
| 383 | + | { name: "claim_task", description: "Claim a task from the board by ID.", input_schema: { type: "object", properties: { task_id: { type: "integer" } }, required: ["task_id"] } }, | |
| 286 | 384 | ]; | |
| 287 | 385 | ||
| 288 | 386 | function assistantText(content: Array<ToolUseBlock | TextBlock>) { | |
| 289 | 387 | return content.filter((block): block is TextBlock => block.type === "text").map((block) => block.text).join("\n"); | |
| 290 | 388 | } | |
| 291 | 389 | ||
| 292 | 390 | export async function agentLoop(messages: Message[]) { | |
| 293 | 391 | while (true) { | |
| 294 | 392 | const inbox = BUS.readInbox("lead"); | |
| 295 | 393 | if (inbox.length) { | |
| 296 | 394 | messages.push({ role: "user", content: `<inbox>${JSON.stringify(inbox, null, 2)}</inbox>` }); | |
| 297 | 395 | messages.push({ role: "assistant", content: "Noted inbox messages." }); | |
| 298 | 396 | } | |
| 299 | 397 | const response = await client.messages.create({ | |
| 300 | 398 | model: MODEL, | |
| 301 | 399 | system: SYSTEM, | |
| 302 | 400 | messages: messages as Anthropic.Messages.MessageParam[], | |
| 303 | 401 | tools: TOOLS as Anthropic.Messages.Tool[], | |
| 304 | 402 | max_tokens: 8000, | |
| 305 | 403 | }); | |
| 306 | 404 | messages.push({ role: "assistant", content: response.content as Array<ToolUseBlock | TextBlock> }); | |
| 307 | 405 | if (response.stop_reason !== "tool_use") return; | |
| 308 | 406 | const results: ToolResultBlock[] = []; | |
| 309 | 407 | for (const block of response.content) { | |
| 310 | 408 | if (block.type !== "tool_use") continue; | |
| 311 | 409 | const handler = TOOL_HANDLERS[block.name as ToolName]; | |
| 312 | 410 | const output = handler ? handler(block.input as Record<string, unknown>) : `Unknown tool: ${block.name}`; | |
| 313 | 411 | console.log(`> ${block.name}: ${output.slice(0, 200)}`); | |
| 314 | 412 | results.push({ type: "tool_result", tool_use_id: block.id, content: output }); | |
| 315 | 413 | } | |
| 316 | 414 | messages.push({ role: "user", content: results }); | |
| 317 | 415 | } | |
| 318 | 416 | } | |
| 319 | 417 | ||
| 320 | 418 | async function main() { | |
| 321 | 419 | const rl = createInterface({ input: process.stdin, output: process.stdout }); | |
| 322 | 420 | const history: Message[] = []; | |
| 323 | 421 | while (true) { | |
| 324 | 422 | let query = ""; | |
| 325 | 423 | try { | |
| 326 | - | query = await rl.question("\x1b[36ms10 >> \x1b[0m"); | |
| 424 | + | query = await rl.question("\x1b[36ms11 >> \x1b[0m"); | |
| 327 | 425 | } catch (error) { | |
| 328 | 426 | if ( | |
| 329 | 427 | error instanceof Error && | |
| 330 | 428 | (("code" in error && error.code === "ERR_USE_AFTER_CLOSE") || error.name === "AbortError") | |
| 331 | 429 | ) { | |
| 332 | 430 | break; | |
| 333 | 431 | } | |
| 334 | 432 | throw error; | |
| 335 | 433 | } | |
| 336 | 434 | if (!query.trim() || ["q", "exit"].includes(query.trim().toLowerCase())) break; | |
| 337 | 435 | if (query.trim() === "/team") { console.log(TEAM.listAll()); continue; } | |
| 338 | 436 | if (query.trim() === "/inbox") { console.log(JSON.stringify(BUS.readInbox("lead"), null, 2)); continue; } | |
| 437 | + | if (query.trim() === "/tasks") { | |
| 438 | + | mkdirSync(TASKS_DIR, { recursive: true }); | |
| 439 | + | for (const task of scanUnclaimedTasks()) console.log(` [ ] #${task.id}: ${task.subject}`); | |
| 440 | + | continue; | |
| 441 | + | } | |
| 339 | 442 | history.push({ role: "user", content: query }); | |
| 340 | 443 | await agentLoop(history); | |
| 341 | 444 | const last = history[history.length - 1]?.content; | |
| 342 | 445 | if (Array.isArray(last)) { | |
| 343 | 446 | const text = assistantText(last as Array<ToolUseBlock | TextBlock>); | |
| 344 | 447 | if (text) console.log(text); | |
| 345 | 448 | } | |
| 346 | 449 | console.log(); | |
| 347 | 450 | } | |
| 348 | 451 | rl.close(); | |
| 349 | 452 | } | |
| 350 | 453 | ||
| 351 | 454 | void main(); |