Back to Tools
The Agent Loop → Tools
s01 (154 LOC) → s02 (237 LOC)
LOC Delta
+83lines
New Tools
3
read_filewrite_fileedit_file
New Classes
0
New Functions
4
safePathrunReadrunWriterunEdit
The Agent Loop
Bash is All You Need
154 LOC
1 tools: bash
toolsTools
One Handler Per Tool
237 LOC
4 tools: bash, read_file, write_file, edit_file
toolsSource Code Diff
s01 (s01_agent_loop.ts) -> s02 (s02_tool_use.ts)
| 1 | 1 | #!/usr/bin/env node | |
| 2 | 2 | /** | |
| 3 | - | * s01_agent_loop.ts - The Agent Loop | |
| 3 | + | * s02_tool_use.ts - Tools | |
| 4 | 4 | * | |
| 5 | - | * The entire secret of an AI coding agent in one pattern: | |
| 5 | + | * The loop from s01 does not change. We add more tools and a dispatch map: | |
| 6 | 6 | * | |
| 7 | - | * while (stopReason === "tool_use") { | |
| 8 | - | * response = LLM(messages, tools) | |
| 9 | - | * executeTools() | |
| 10 | - | * appendResults() | |
| 11 | - | * } | |
| 7 | + | * { tool_name: handler } | |
| 8 | + | * | |
| 9 | + | * Key insight: adding a tool means adding one handler. | |
| 12 | 10 | */ | |
| 13 | 11 | ||
| 14 | 12 | import { spawnSync } from "node:child_process"; | |
| 13 | + | import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; | |
| 15 | 14 | import process from "node:process"; | |
| 16 | 15 | import { createInterface } from "node:readline/promises"; | |
| 16 | + | import { resolve } from "node:path"; | |
| 17 | 17 | import type Anthropic from "@anthropic-ai/sdk"; | |
| 18 | 18 | import "dotenv/config"; | |
| 19 | 19 | import { buildSystemPrompt, createAnthropicClient, resolveModel, shellToolDescription } from "./shared"; | |
| 20 | 20 | ||
| 21 | - | type ToolUseName = "bash"; | |
| 21 | + | type ToolUseName = "bash" | "read_file" | "write_file" | "edit_file"; | |
| 22 | 22 | ||
| 23 | 23 | type ToolUseBlock = { | |
| 24 | 24 | id: string; | |
| 25 | 25 | type: "tool_use"; | |
| 26 | 26 | name: ToolUseName; | |
| 27 | 27 | input: Record<string, unknown>; | |
| 28 | 28 | }; | |
| 29 | 29 | ||
| 30 | 30 | type TextBlock = { | |
| 31 | 31 | type: "text"; | |
| 32 | 32 | text: string; | |
| 33 | 33 | }; | |
| 34 | 34 | ||
| 35 | 35 | type ToolResultBlock = { | |
| 36 | 36 | type: "tool_result"; | |
| 37 | 37 | tool_use_id: string; | |
| 38 | 38 | content: string; | |
| 39 | 39 | }; | |
| 40 | 40 | ||
| 41 | 41 | type MessageContent = string | Array<ToolUseBlock | TextBlock | ToolResultBlock>; | |
| 42 | 42 | ||
| 43 | 43 | type Message = { | |
| 44 | 44 | role: "user" | "assistant"; | |
| 45 | 45 | content: MessageContent; | |
| 46 | 46 | }; | |
| 47 | 47 | ||
| 48 | 48 | const WORKDIR = process.cwd(); | |
| 49 | 49 | const MODEL = resolveModel(); | |
| 50 | 50 | const client = createAnthropicClient(); | |
| 51 | 51 | ||
| 52 | - | const SYSTEM = buildSystemPrompt(`You are a coding agent at ${WORKDIR}. Use bash to solve tasks. Act, don't explain.`); | |
| 52 | + | const SYSTEM = buildSystemPrompt(`You are a coding agent at ${WORKDIR}. Use tools to solve tasks. Act, don't explain.`); | |
| 53 | 53 | ||
| 54 | + | function safePath(relativePath: string): string { | |
| 55 | + | const filePath = resolve(WORKDIR, relativePath); | |
| 56 | + | const normalizedWorkdir = `${WORKDIR}${process.platform === "win32" ? "\\" : "/"}`; | |
| 57 | + | if (filePath !== WORKDIR && !filePath.startsWith(normalizedWorkdir)) { | |
| 58 | + | throw new Error(`Path escapes workspace: ${relativePath}`); | |
| 59 | + | } | |
| 60 | + | return filePath; | |
| 61 | + | } | |
| 62 | + | ||
| 54 | 63 | function runBash(command: string): string { | |
| 55 | 64 | const dangerous = ["rm -rf /", "sudo", "shutdown", "reboot", "> /dev/"]; | |
| 56 | 65 | if (dangerous.some((item) => command.includes(item))) { | |
| 57 | 66 | return "Error: Dangerous command blocked"; | |
| 58 | 67 | } | |
| 59 | 68 | ||
| 60 | 69 | const shell = process.platform === "win32" ? "cmd.exe" : "/bin/sh"; | |
| 61 | 70 | const args = process.platform === "win32" | |
| 62 | 71 | ? ["/d", "/s", "/c", command] | |
| 63 | 72 | : ["-lc", command]; | |
| 64 | 73 | ||
| 65 | 74 | const result = spawnSync(shell, args, { | |
| 66 | 75 | cwd: WORKDIR, | |
| 67 | 76 | encoding: "utf8", | |
| 68 | 77 | timeout: 120_000, | |
| 69 | 78 | }); | |
| 70 | 79 | ||
| 71 | 80 | if (result.error?.name === "TimeoutError") { | |
| 72 | 81 | return "Error: Timeout (120s)"; | |
| 73 | 82 | } | |
| 74 | 83 | ||
| 75 | 84 | const output = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim(); | |
| 76 | 85 | return output.slice(0, 50_000) || "(no output)"; | |
| 77 | 86 | } | |
| 78 | 87 | ||
| 88 | + | function runRead(path: string, limit?: number): string { | |
| 89 | + | try { | |
| 90 | + | let lines = readFileSync(safePath(path), "utf8").split(/\r?\n/); | |
| 91 | + | if (limit && limit < lines.length) { | |
| 92 | + | lines = lines.slice(0, limit).concat(`... (${lines.length - limit} more)`); | |
| 93 | + | } | |
| 94 | + | return lines.join("\n").slice(0, 50_000); | |
| 95 | + | } catch (error) { | |
| 96 | + | return `Error: ${error instanceof Error ? error.message : String(error)}`; | |
| 97 | + | } | |
| 98 | + | } | |
| 99 | + | ||
| 100 | + | function runWrite(path: string, content: string): string { | |
| 101 | + | try { | |
| 102 | + | const filePath = safePath(path); | |
| 103 | + | mkdirSync(resolve(filePath, ".."), { recursive: true }); | |
| 104 | + | writeFileSync(filePath, content, "utf8"); | |
| 105 | + | return `Wrote ${content.length} bytes`; | |
| 106 | + | } catch (error) { | |
| 107 | + | return `Error: ${error instanceof Error ? error.message : String(error)}`; | |
| 108 | + | } | |
| 109 | + | } | |
| 110 | + | ||
| 111 | + | function runEdit(path: string, oldText: string, newText: string): string { | |
| 112 | + | try { | |
| 113 | + | const filePath = safePath(path); | |
| 114 | + | const content = readFileSync(filePath, "utf8"); | |
| 115 | + | if (!content.includes(oldText)) { | |
| 116 | + | return `Error: Text not found in ${path}`; | |
| 117 | + | } | |
| 118 | + | writeFileSync(filePath, content.replace(oldText, newText), "utf8"); | |
| 119 | + | return `Edited ${path}`; | |
| 120 | + | } catch (error) { | |
| 121 | + | return `Error: ${error instanceof Error ? error.message : String(error)}`; | |
| 122 | + | } | |
| 123 | + | } | |
| 124 | + | ||
| 79 | 125 | const TOOL_HANDLERS: Record<ToolUseName, (input: Record<string, unknown>) => string> = { | |
| 80 | 126 | bash: (input) => runBash(String(input.command ?? "")), | |
| 127 | + | read_file: (input) => runRead(String(input.path ?? ""), Number(input.limit ?? 0) || undefined), | |
| 128 | + | write_file: (input) => runWrite(String(input.path ?? ""), String(input.content ?? "")), | |
| 129 | + | edit_file: (input) => | |
| 130 | + | runEdit(String(input.path ?? ""), String(input.old_text ?? ""), String(input.new_text ?? "")), | |
| 81 | 131 | }; | |
| 82 | 132 | ||
| 83 | 133 | const TOOLS = [ | |
| 84 | 134 | { | |
| 85 | 135 | name: "bash", | |
| 86 | 136 | description: shellToolDescription(), | |
| 87 | 137 | input_schema: { | |
| 88 | 138 | type: "object", | |
| 89 | 139 | properties: { | |
| 90 | 140 | command: { type: "string" }, | |
| 91 | 141 | }, | |
| 92 | 142 | required: ["command"], | |
| 93 | 143 | }, | |
| 94 | 144 | }, | |
| 145 | + | { | |
| 146 | + | name: "read_file", | |
| 147 | + | description: "Read file contents.", | |
| 148 | + | input_schema: { | |
| 149 | + | type: "object", | |
| 150 | + | properties: { | |
| 151 | + | path: { type: "string" }, | |
| 152 | + | limit: { type: "integer" }, | |
| 153 | + | }, | |
| 154 | + | required: ["path"], | |
| 155 | + | }, | |
| 156 | + | }, | |
| 157 | + | { | |
| 158 | + | name: "write_file", | |
| 159 | + | description: "Write content to file.", | |
| 160 | + | input_schema: { | |
| 161 | + | type: "object", | |
| 162 | + | properties: { | |
| 163 | + | path: { type: "string" }, | |
| 164 | + | content: { type: "string" }, | |
| 165 | + | }, | |
| 166 | + | required: ["path", "content"], | |
| 167 | + | }, | |
| 168 | + | }, | |
| 169 | + | { | |
| 170 | + | name: "edit_file", | |
| 171 | + | description: "Replace exact text in file.", | |
| 172 | + | input_schema: { | |
| 173 | + | type: "object", | |
| 174 | + | properties: { | |
| 175 | + | path: { type: "string" }, | |
| 176 | + | old_text: { type: "string" }, | |
| 177 | + | new_text: { type: "string" }, | |
| 178 | + | }, | |
| 179 | + | required: ["path", "old_text", "new_text"], | |
| 180 | + | }, | |
| 181 | + | }, | |
| 95 | 182 | ]; | |
| 96 | 183 | ||
| 97 | 184 | function assistantText(content: Array<ToolUseBlock | TextBlock | ToolResultBlock>) { | |
| 98 | 185 | return content | |
| 99 | 186 | .filter((block): block is TextBlock => block.type === "text") | |
| 100 | 187 | .map((block) => block.text) | |
| 101 | 188 | .join("\n"); | |
| 102 | 189 | } | |
| 103 | 190 | ||
| 104 | 191 | export async function agentLoop(messages: Message[]) { | |
| 105 | 192 | while (true) { | |
| 106 | 193 | const response = await client.messages.create({ | |
| 107 | 194 | model: MODEL, | |
| 108 | 195 | system: SYSTEM, | |
| 109 | 196 | messages: messages as Anthropic.Messages.MessageParam[], | |
| 110 | 197 | tools: TOOLS as Anthropic.Messages.Tool[], | |
| 111 | 198 | max_tokens: 8000, | |
| 112 | 199 | }); | |
| 113 | 200 | ||
| 114 | 201 | messages.push({ | |
| 115 | 202 | role: "assistant", | |
| 116 | 203 | content: response.content as Array<ToolUseBlock | TextBlock>, | |
| 117 | 204 | }); | |
| 118 | 205 | ||
| 119 | 206 | if (response.stop_reason !== "tool_use") { | |
| 120 | 207 | return; | |
| 121 | 208 | } | |
| 122 | 209 | ||
| 123 | 210 | const results: ToolResultBlock[] = []; | |
| 124 | 211 | ||
| 125 | 212 | for (const block of response.content) { | |
| 126 | 213 | if (block.type !== "tool_use") continue; | |
| 127 | 214 | ||
| 128 | 215 | const handler = TOOL_HANDLERS[block.name as ToolUseName]; | |
| 129 | 216 | const output = handler | |
| 130 | 217 | ? handler(block.input as Record<string, unknown>) | |
| 131 | 218 | : `Unknown tool: ${block.name}`; | |
| 132 | 219 | ||
| 133 | 220 | console.log(`> ${block.name}: ${output.slice(0, 200)}`); | |
| 134 | 221 | results.push({ | |
| 135 | 222 | type: "tool_result", | |
| 136 | 223 | tool_use_id: block.id, | |
| 137 | 224 | content: output, | |
| 138 | 225 | }); | |
| 139 | 226 | } | |
| 140 | 227 | ||
| 141 | 228 | messages.push({ | |
| 142 | 229 | role: "user", | |
| 143 | 230 | content: results, | |
| 144 | 231 | }); | |
| 145 | 232 | } | |
| 146 | 233 | } | |
| 147 | 234 | ||
| 148 | 235 | async function main() { | |
| 149 | 236 | const rl = createInterface({ | |
| 150 | 237 | input: process.stdin, | |
| 151 | 238 | output: process.stdout, | |
| 152 | 239 | }); | |
| 153 | 240 | ||
| 154 | 241 | const history: Message[] = []; | |
| 155 | 242 | ||
| 156 | 243 | while (true) { | |
| 157 | 244 | let query = ""; | |
| 158 | 245 | try { | |
| 159 | - | query = await rl.question("\x1b[36ms01 >> \x1b[0m"); | |
| 246 | + | query = await rl.question("\x1b[36ms02 >> \x1b[0m"); | |
| 160 | 247 | } catch (error) { | |
| 161 | 248 | if ( | |
| 162 | 249 | error instanceof Error && | |
| 163 | 250 | (("code" in error && error.code === "ERR_USE_AFTER_CLOSE") || error.name === "AbortError") | |
| 164 | 251 | ) { | |
| 165 | 252 | break; | |
| 166 | 253 | } | |
| 167 | 254 | throw error; | |
| 168 | 255 | } | |
| 169 | 256 | if (!query.trim() || ["q", "exit"].includes(query.trim().toLowerCase())) { | |
| 170 | 257 | break; | |
| 171 | 258 | } | |
| 172 | 259 | ||
| 173 | 260 | history.push({ role: "user", content: query }); | |
| 174 | 261 | await agentLoop(history); | |
| 175 | 262 | ||
| 176 | 263 | const last = history[history.length - 1]?.content; | |
| 177 | 264 | if (Array.isArray(last)) { | |
| 178 | 265 | const text = assistantText(last); | |
| 179 | 266 | if (text) console.log(text); | |
| 180 | 267 | } | |
| 181 | 268 | console.log(); | |
| 182 | 269 | } | |
| 183 | 270 | ||
| 184 | 271 | rl.close(); | |
| 185 | 272 | } | |
| 186 | 273 | ||
| 187 | 274 | void main(); |