The first time Claude Code, Codex, or Goose reads your repository, edits three files, and runs tests, it can seem mysterious. Under the polish is a simple loop: send the conversation to a model, run the tool it requests, return the result, and repeat. That loop and its surrounding code form an *agent harness*. Build a working coding agent from scratch, one runnable step at a time. Finish with a single Go file under 400 lines, using only the standard library. ## What You'll Build You'll build `harness`, a terminal coding agent. It handles requests like "write a FizzBuzz script and run it" by listing and reading files, creating files, and running shell commands. It asks permission before writing or running commands, and its file tools block paths outside the starting folder. It runs free on your machine via [Ollama][ollama] and works unchanged with any hosted OpenAI Chat Completions-compatible service. ## What You'll Learn * How a harness talks to a model over plain HTTP (Hypertext Transfer Protocol) and JSON (JavaScript Object Notation). * Why the model forgets everything between calls, and how the harness remembers it. * How tool calling works: the model asks, the harness runs the tool, the harness reports back. * How the agent loop turns one request into many model calls. * Which guardrails make an agent safe enough to run on your own machine. * How to test an agent without a model, and how to ship it as a single binary for macOS, Linux, and Windows. **Time estimate:** about 90 minutes, plus a model download of a few gigabytes. **Difficulty:** beginner to intermediate. You should be comfortable using a terminal and have coding experience; Go isn't required. ## Why Go You can build a harness in any language; Sebastian Raschka's [Mini Coding Agent][mini-coding-agent] offers a clean Python example. This tutorial uses Go for four reasons: * **One file runs anywhere.** `go build` creates a standalone executable, and one command cross-compiles it for another operating system. * **The standard library covers the job.** HTTP, JSON, files, and child processes are built in, so you need no packages or AI software development kit (SDK). * **It starts fast and stays small.** On an Apple Silicon Mac, the finished harness starts in about 10 ms and uses about 10 MB of memory, leaving model latency as the only wait. * **It reads like pseudocode.** Go's simple syntax and explicit error handling make every line easy to follow, even for beginners. ## How an Agent Harness Works Anthropic's [Building Effective Agents][building-effective-agents] describes agents built on large language models (LLMs) as "typically just LLMs using tools based on environmental feedback in a loop." Your harness owns everything but the model. ```mermaid flowchart TB U[You type a request] --> H[Harness appends it to the history] H --> M[Model reads the history and the tool list] M --> D{Did the model ask for a tool?} D -->|Yes| T[Harness runs the tool] T --> R[Harness appends the tool result to the history] R --> M D -->|No| A[Harness prints the answer] A --> U ``` A few terms you'll meet along the way: * **Model.** An LLM that reads text and predicts more text. It cannot touch your files on its own. * **History.** The list of messages so far. The harness sends the whole list on every call, because the model keeps no memory between calls. * **Tool.** A function the harness exposes, described by a name, a sentence, and a list of arguments. The model sees the description; the harness runs the code. * **Tool call.** The model's request to run a tool with specific arguments. For a deeper tour of what production harnesses add on top of this loop, read [What Are Coding Agents?][coding-agents]. ## Prerequisites **Required:** * A Mac, Linux, or Windows computer with about 8 GB of free memory and 8 GB of free disk space for a local model. * [Go][go-install] 1.22 or newer. * [Ollama][ollama-download], which runs open models locally and serves them over an OpenAI-compatible application programming interface (API). * A terminal, and an editor with Go support, such as VS Code with the Go extension, which adds missing imports when you paste code. **Not required:** * A graphics card. Small models run on a laptop's processor, just more slowly. * An API key or an account with an AI company. * Python, Node.js, or any AI framework. If your computer can't run a local model, you can point the harness at a hosted model instead. Step 6 shows how. ## Setup ### Install Go Download the installer for your system from the [Go download page][go-install] and run it, then open a new terminal and check the version: ```bash go version ``` **You should see:** a line such as `go version go1.27.4 darwin/arm64`. Any version from 1.22 up works. ### Install Ollama and pull a model On macOS or Linux, install Ollama with its script. On Windows, use the PowerShell command on the [Ollama download page][ollama-download]. ```bash curl -fsSL https://ollama.com/install.sh | sh ``` The script installs `ollama`; alternatively, download the installer from the same page. Download a tool-calling model. This tutorial uses [Gemma 4 E2B][gemma4], Google's smallest Gemma 4 model, designed for laptops and phones: ```bash ollama pull gemma4:e2b ``` **You should see:** a progress bar, then `success`. **Checkpoint:** confirm Ollama answers on its OpenAI-compatible endpoint: ```bash curl http://localhost:11434/v1/models ``` The JSON response lists `gemma4:e2b`. If the connection is refused, run `ollama serve` in another terminal and retry. ### Create the project ```bash mkdir harness && cd harness && go mod init harness ``` **You should see:** `go: creating new go.mod: module harness`. Build a single `main.go` using these steps. Finished copies of Steps 1 to 5 are in the [companion code repository][harness-repo] (`steps/01-hello` to `steps/05-guardrails`). The Step 6 tests are in `steps/05-guardrails/main_test.go`, and `steps/06-extensions` holds the extensions from Next Steps. ## Step 1: Send One Message Create `main.go` to send one message and print the reply. ```go // harness talks to a model through an OpenAI-compatible Chat Completions API. package main import ( "bytes" "encoding/json" "fmt" "net/http" "os" "strings" ) // Message is one entry in the conversation, in the OpenAI-compatible format. type Message struct { Role string `json:"role"` Content string `json:"content"` } type chatRequest struct { Model string `json:"model"` Messages []Message `json:"messages"` } type chatResponse struct { Choices []struct { Message Message `json:"message"` } `json:"choices"` } func main() { prompt := strings.Join(os.Args[1:], " ") if prompt == "" { prompt = "What is the capital of France?" } reply, err := chat([]Message{{Role: "user", Content: prompt}}) if err != nil { fmt.Fprintln(os.Stderr, "error:", err) os.Exit(1) } fmt.Println(reply.Content) } // chat sends the whole conversation to the model and returns its next message. func chat(messages []Message) (Message, error) { body, err := json.Marshal(chatRequest{ Model: env("HARNESS_MODEL", "gemma4:e2b"), Messages: messages, }) if err != nil { return Message{}, err } url := env("HARNESS_BASE_URL", "http://localhost:11434/v1") + "/chat/completions" req, err := http.NewRequest("POST", url, bytes.NewReader(body)) if err != nil { return Message{}, err } req.Header.Set("Content-Type", "application/json") if key := os.Getenv("HARNESS_API_KEY"); key != "" { req.Header.Set("Authorization", "Bearer "+key) } resp, err := http.DefaultClient.Do(req) if err != nil { return Message{}, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return Message{}, fmt.Errorf("model server returned %s", resp.Status) } var out chatResponse if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { return Message{}, err } if len(out.Choices) == 0 { return Message{}, fmt.Errorf("model returned no choices") } return out.Choices[0].Message, nil } // env reads an environment variable, falling back to a default. func env(name, fallback string) string { if v := os.Getenv(name); v != "" { return v } return fallback } ``` Run it: ```bash go run . "What is the capital of France?" ``` **You should see:** `The capital of France is **Paris**.` The asterisks mark Markdown bold, which the model outputs, but your terminal displays them as raw text. Responses may vary between runs because models aren't deterministic. **What happened:** `chat` JSON-encoded messages, posted them to `/chat/completions`, and decoded the first response choice. Each message has a `role` (`user` or `assistant`) and `content`. Three environment variables let you change models and servers without editing code. **Checkpoint:** Run it twice with different prompts. Every call works; no packages installed. ## Step 2: Keep the Conversation Tell the Step 1 program your name, then ask it to recall it. It can't: each run sends one message and exits. The model only knows the request; the harness must manage memory. Add `"bufio"` to the imports, then replace `main` with a loop that stores history in a slice (a growable list) and appends new entries. ```go func main() { var history []Message input := bufio.NewScanner(os.Stdin) fmt.Println("Chat with the model. Type /quit to exit.") for { fmt.Print("\nyou> ") if !input.Scan() { return } line := strings.TrimSpace(input.Text()) if line == "" { continue } if line == "/quit" { return } history = append(history, Message{Role: "user", Content: line}) reply, err := chat(history) if err != nil { fmt.Fprintln(os.Stderr, "error:", err) history = history[:len(history)-1] continue } history = append(history, reply) fmt.Println("model>", reply.Content) } } ``` Run it and have a short conversation: ```bash go run . ``` At each `you>` prompt, type only the text after `you>` and press Enter. The harness prints everything else. This transcript shows two messages, `My name is Inigo Montoya.` and `What is my name?`: ```text you> My name is Inigo Montoya. model> It's a pleasure to meet you, Inigo Montoya. you> What is my name? model> Your name is Inigo Montoya. ``` **What happened:** Each turn sends the full conversation history with your new message, then appends the reply. The model "remembers" your name because the harness resends the first exchange. If a call fails, the harness drops your last message, so retrying won't duplicate it. **Checkpoint:** Type `/quit`, restart, and ask your name. The model has forgotten because the program exited, clearing its in-memory history. ## Step 3: Give the Model a Tool A tool lets the model act on your machine. Here, you add `read_file` and an agent loop to run it. ### Teach messages about tool calls When the model requests a tool, its reply contains `tool_calls` instead of text. Return the result in a `tool` message with the matching call ID. Replace the `Message` type and add types for calls and tool definitions. ```go // Message is one entry in the conversation, in the OpenAI-compatible format. type Message struct { Role string `json:"role"` Content string `json:"content"` ToolCalls []ToolCall `json:"tool_calls,omitempty"` ToolCallID string `json:"tool_call_id,omitempty"` } // ToolCall is the model asking the harness to run a tool. type ToolCall struct { ID string `json:"id"` Type string `json:"type"` Function FunctionCall `json:"function"` } type FunctionCall struct { Name string `json:"name"` Arguments string `json:"arguments"` // a JSON object, encoded as a string } // ToolDef describes a tool to the model: its name, purpose, and arguments. type ToolDef struct { Type string `json:"type"` Function FunctionDef `json:"function"` } type FunctionDef struct { Name string `json:"name"` Description string `json:"description"` Parameters map[string]any `json:"parameters"` } ``` Add a `Tools` field to `chatRequest`: ```go type chatRequest struct { Model string `json:"model"` Messages []Message `json:"messages"` Tools []ToolDef `json:"tools,omitempty"` } ``` ### Describe the tool The model sees only the name, description, and JSON Schema (argument names and types). It never sees your Go code. Document them for a new teammate. Add this below the types: ```go var tools = []ToolDef{{ Type: "function", Function: FunctionDef{ Name: "read_file", Description: "Read a text file and return its contents.", Parameters: map[string]any{ "type": "object", "properties": map[string]any{ "path": map[string]any{"type": "string", "description": "Path to the file."}, }, "required": []string{"path"}, }, }, }} ``` In `chat`, send the tools along with the messages: ```go body, err := json.Marshal(chatRequest{ Model: env("HARNESS_MODEL", "gemma4:e2b"), Messages: messages, Tools: tools, }) ``` ### Write the agent loop Every coding agent runs a function that calls the model, executes any requested tools, appends their results, and repeats until the model responds in plain text. ```go // runTurn is the agent loop: call the model, run any tools it asks for, // send the results back, and repeat until the model answers in plain text. func runTurn(history []Message) ([]Message, error) { for { reply, err := chat(history) if err != nil { return history, err } history = append(history, reply) if len(reply.ToolCalls) == 0 { fmt.Println("agent>", reply.Content) return history, nil } for _, call := range reply.ToolCalls { fmt.Printf(" [tool] %s %s\n", call.Function.Name, call.Function.Arguments) history = append(history, Message{ Role: "tool", ToolCallID: call.ID, Content: runTool(call), }) } } } ``` ### Run the tool `runTool` decodes the arguments and reads the file. Errors go back to the model as text, so when it sees `no such file or directory`, it can try another path. ```go // runTool executes one tool call. Errors go back to the model as text, // so it can read them and try something else. func runTool(call ToolCall) string { if call.Function.Name != "read_file" { return "error: unknown tool " + call.Function.Name } var args struct { Path string `json:"path"` } if err := json.Unmarshal([]byte(call.Function.Arguments), &args); err != nil { return "error: bad arguments: " + err.Error() } data, err := os.ReadFile(args.Path) if err != nil { return "error: " + err.Error() } return string(data) } ``` Finally, replace `main` to pass each message to the agent loop: ```go func main() { var history []Message input := bufio.NewScanner(os.Stdin) fmt.Println("Agent ready. Type /quit to exit.") for { fmt.Print("\nyou> ") if !input.Scan() { return } line := strings.TrimSpace(input.Text()) if line == "" { continue } if line == "/quit" { return } history = append(history, Message{Role: "user", Content: line}) var err error history, err = runTurn(history) if err != nil { fmt.Fprintln(os.Stderr, "error:", err) } } } ``` The loop keeps your message if a call fails, since `runTurn` may have added related tool results. Run it from your project folder: ```bash go run . ``` At the `you>` prompt, ask the model to read a file it has never seen. Type `Read go.mod and tell me the module name.` The harness prints the `[tool]` line, then the model's answer: ```text you> Read go.mod and tell me the module name. [tool] read_file {"path":"go.mod"} agent> The module name is `harness`. ``` Say "read" outright. Small models often answer from what they already know instead of reaching for a tool. Asked "What module name is declared in go.mod?", `gemma4:e2b` usually explains what the `module` directive is, with no `[tool]` line, and never opens the file. Larger models pick up the hint more often. **What happened:** one request produced two model calls. The first returned a tool call instead of an answer. Your harness read `go.mod`, appended its contents as a `tool` message, and called the model again. The second call had the facts it needed, so it answered. **Checkpoint:** ask it to read a file that doesn't exist: `Read notes.txt and summarize it.` The `[tool]` line still appears, and the model reports that the file is missing instead of the program crashing. ## Step 4: Build a Toolbox One tool proves the loop. A coding agent needs four: list a folder, read a file, write a file, and run a command. Adding them one `if` at a time gets messy. Instead, give each tool a struct (a named group of fields) that pairs what the model sees with what the harness does. Add `"os/exec"`, `"runtime"`, and `"sort"` to the imports. Delete the `tools` variable, and add the `Tool` type and the toolbox: ```go // Tool pairs what the model sees (name, description, parameters) // with what the harness does (Run). type Tool struct { Name string Description string Params map[string]string // argument name -> description Run func(args map[string]string) (string, error) } var toolbox = []Tool{ { Name: "list_files", Description: "List the files and folders in a directory.", Params: map[string]string{"path": "Directory to list. Use . for the current directory."}, Run: func(args map[string]string) (string, error) { entries, err := os.ReadDir(args["path"]) if err != nil { return "", err } var b strings.Builder for _, e := range entries { name := e.Name() if e.IsDir() { name += "/" } b.WriteString(name + "\n") } return b.String(), nil }, }, { Name: "read_file", Description: "Read a text file and return its contents.", Params: map[string]string{"path": "Path to the file."}, Run: func(args map[string]string) (string, error) { data, err := os.ReadFile(args["path"]) return string(data), err }, }, { Name: "write_file", Description: "Create or overwrite a text file with the given content.", Params: map[string]string{"path": "Path to the file.", "content": "The full new contents of the file."}, Run: func(args map[string]string) (string, error) { err := os.WriteFile(args["path"], []byte(args["content"]), 0o644) if err != nil { return "", err } return fmt.Sprintf("wrote %d bytes to %s", len(args["content"]), args["path"]), nil }, }, { Name: "run_command", Description: "Run a shell command and return its combined output.", Params: map[string]string{"command": "The command line to run."}, Run: func(args map[string]string) (string, error) { shell, flag := "sh", "-c" if runtime.GOOS == "windows" { shell, flag = "cmd", "/C" } out, err := exec.Command(shell, flag, args["command"]).CombinedOutput() if err != nil { return string(out) + "\n" + err.Error(), nil } return string(out), nil }, }, } ``` `run_command` returns a failing command's output as a normal result, because the model needs a failed test's output to fix the test. Next, generate the JSON Schema from the toolbox so a new tool is one struct literal, with no hand-written schema: ```go // toolDefs converts the toolbox into the JSON schema the model expects. func toolDefs() []ToolDef { var defs []ToolDef for _, t := range toolbox { props := map[string]any{} var required []string for name, desc := range t.Params { props[name] = map[string]any{"type": "string", "description": desc} required = append(required, name) } sort.Strings(required) defs = append(defs, ToolDef{ Type: "function", Function: FunctionDef{ Name: t.Name, Description: t.Description, Parameters: map[string]any{"type": "object", "properties": props, "required": required}, }, }) } return defs } ``` Go randomizes map order, so `sort.Strings` keeps the request byte-for-byte identical between calls, which lets servers that cache prompt prefixes reuse their work. Replace `runTool` with a lookup by name: ```go // runTool finds the tool by name, decodes its arguments, and runs it. // Errors go back to the model as text, so it can read them and adjust. func runTool(call ToolCall) string { for _, t := range toolbox { if t.Name != call.Function.Name { continue } var args map[string]string if err := json.Unmarshal([]byte(call.Function.Arguments), &args); err != nil { return "error: bad arguments: " + err.Error() } out, err := t.Run(args) if err != nil { return "error: " + err.Error() } return out } return "error: unknown tool " + call.Function.Name } ``` In `chat`, change `Tools: tools,` to `Tools: toolDefs(),`. **Warning:** This version runs any command the model chooses with your permissions, without asking. Run it only in an empty scratch folder, and press Ctrl+C if anything unexpected happens. Step 5 fixes this. Create a `playground` folder in your project and run the agent there. `go run ..` builds the parent folder's code while keeping your working directory in `playground`: ```bash mkdir playground && cd playground && go run .. ``` At the `you>` prompt, type this request as one line: ```text Create a file called hello.txt containing the text "You keep using that word. I do not think it means what you think it means.", then run the command ls -la and tell me how big hello.txt is. ``` The harness and the model handle the rest: ```text you> Create a file called hello.txt containing the text "You keep using that word. I do not think it means what you think it means.", then run the command ls -la and tell me how big hello.txt is. [tool] write_file {"content":"You keep using that word. I do not think it means what you think it means.","path":"hello.txt"} [tool] run_command {"command":"ls -la"} agent> The file `hello.txt` has been created with the text "You keep using that word. I do not think it means what you think it means.". The `ls -la` command confirmed its presence. Based on the execution, the file size is 74 bytes. ``` On Windows, ask for `dir` instead of `ls -la`. **What happened:** The model chained two tools in one turn and used the second's output to answer. No planning code was needed; Step 3's loop handles any number of calls. **Checkpoint:** `hello.txt` exists in `playground` and contains `You keep using that word. I do not think it means what you think it means.` ## Step 5: Add Guardrails Step 4 works and could delete your home folder if asked. Production harnesses limit the loop. Add six: * **Workspace fence.** File tools only touch the folder you started in. * **Approval.** Any tool that writes or executes asks first. * **Timeout.** Shell commands stop after 60 seconds, so `npm start` can't hang the agent forever. * **Output limit.** A 50,000-line log can't flood the model's context window, the fixed amount of text the model can read in one call. * **Step budget.** A confused model can't loop forever. * **System prompt.** The model knows where it is and how to behave. ### Add limits and shared state Update the imports to this full list: ```go import ( "bufio" "bytes" "context" "encoding/json" "errors" "fmt" "net/http" "os" "os/exec" "path/filepath" "runtime" "sort" "strings" "time" ) ``` Add the limits and three package-level variables below the imports. The scanner moves out of `main` because approval prompts need to read from it too: ```go const ( maxSteps = 25 // tool rounds allowed per user message maxOutputBytes = 10_000 // longest tool result sent back to the model commandTimeout = 60 * time.Second // longest a shell command may run ) var ( input = bufio.NewScanner(os.Stdin) httpClient = &http.Client{Timeout: 5 * time.Minute} workspace string // the folder the agent may touch, set in main ) ``` In `chat`, change `http.DefaultClient.Do(req)` to `httpClient.Do(req)`, so a stalled server can't freeze the agent. ### Fence the workspace `safePath` resolves every path against the workspace and rejects anything that climbs out of it. `filepath.IsLocal` reports whether the relative path stays inside, so `..` and `a/../../b.txt` fail while `a/../b.txt` passes: ```go // safePath resolves a path against the workspace and refuses anything outside it. func safePath(p string) (string, error) { full := p if !filepath.IsAbs(p) { full = filepath.Join(workspace, p) } rel, err := filepath.Rel(workspace, full) if err != nil || !filepath.IsLocal(rel) { return "", fmt.Errorf("%s is outside the workspace %s", p, workspace) } return filepath.Join(workspace, rel), nil } ``` The next section routes every file tool through it. ### Ask before risky tools Add a `Risky` field to `Tool`: ```go // Tool pairs what the model sees (name, description, parameters) // with what the harness does (Run). Risky tools need the user's approval. type Tool struct { Name string Description string Params map[string]string // argument name -> description Risky bool Run func(args map[string]string) (string, error) } ``` Replace the entire `toolbox` variable with this version. All file tools use `safePath`, and the two risky tools are marked `Risky: true`. `write_file` creates missing folders, while `run_command` runs in the workspace with a deadline. Each description tells the model about the workspace before it attempts to leave. ```go var toolbox = []Tool{ { Name: "list_files", Description: "List the files and folders in a directory inside the workspace.", Params: map[string]string{"path": "Directory to list, relative to the workspace. Use . for the workspace root."}, Run: func(args map[string]string) (string, error) { dir, err := safePath(args["path"]) if err != nil { return "", err } entries, err := os.ReadDir(dir) if err != nil { return "", err } var b strings.Builder for _, e := range entries { name := e.Name() if e.IsDir() { name += "/" } b.WriteString(name + "\n") } return b.String(), nil }, }, { Name: "read_file", Description: "Read a text file inside the workspace and return its contents.", Params: map[string]string{"path": "Path to the file, relative to the workspace."}, Run: func(args map[string]string) (string, error) { path, err := safePath(args["path"]) if err != nil { return "", err } data, err := os.ReadFile(path) return string(data), err }, }, { Name: "write_file", Description: "Create or overwrite a text file inside the workspace.", Params: map[string]string{"path": "Path to the file, relative to the workspace.", "content": "The full new contents of the file."}, Risky: true, Run: func(args map[string]string) (string, error) { path, err := safePath(args["path"]) if err != nil { return "", err } if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return "", err } if err := os.WriteFile(path, []byte(args["content"]), 0o644); err != nil { return "", err } return fmt.Sprintf("wrote %d bytes to %s", len(args["content"]), args["path"]), nil }, }, { Name: "run_command", Description: "Run a shell command in the workspace and return its combined output.", Params: map[string]string{"command": "The command line to run."}, Risky: true, Run: func(args map[string]string) (string, error) { shell, flag := "sh", "-c" if runtime.GOOS == "windows" { shell, flag = "cmd", "/C" } ctx, cancel := context.WithTimeout(context.Background(), commandTimeout) defer cancel() cmd := exec.CommandContext(ctx, shell, flag, args["command"]) cmd.Dir = workspace out, err := cmd.CombinedOutput() if errors.Is(ctx.Err(), context.DeadlineExceeded) { return string(out) + "\nerror: command timed out after " + commandTimeout.String(), nil } if err != nil { return string(out) + "\n" + err.Error(), nil } return string(out), nil }, }, } ``` Add the approval prompt: ```go // approve asks the user before a risky tool runs. func approve(call ToolCall) bool { fmt.Printf(" allow %s? [y/N] ", call.Function.Name) if !input.Scan() { return false } answer := strings.ToLower(strings.TrimSpace(input.Text())) return answer == "y" || answer == "yes" } ``` Replace `runTool` so it asks before running a risky tool. The denial message tells the model what to do next; without that sentence, small models tend to retry the same command: ```go // runTool finds the tool by name, decodes its arguments, asks for approval // when the tool is risky, and runs it. Errors go back to the model as text. func runTool(call ToolCall) string { for _, t := range toolbox { if t.Name != call.Function.Name { continue } var args map[string]string if err := json.Unmarshal([]byte(call.Function.Arguments), &args); err != nil { return "error: bad arguments: " + err.Error() } if t.Risky && !approve(call) { return "error: the user denied this action. Do not retry it; ask the user what to do instead." } out, err := t.Run(args) if err != nil { return "error: " + err.Error() } return out } return "error: unknown tool " + call.Function.Name } ``` ### Budget the loop Add the output limit: ```go // truncate keeps tool output from flooding the model's context window. func truncate(s string) string { if len(s) <= maxOutputBytes { return s } return s[:maxOutputBytes] + fmt.Sprintf("\n[truncated %d bytes]", len(s)-maxOutputBytes) } ``` Then change `runTurn` from an endless `for` to a counted one, and truncate each tool result before it enters the history: ```go // runTurn is the agent loop: call the model, run any tools it asks for, // send the results back, and repeat until the model answers in plain text // or the step budget runs out. func runTurn(history []Message) ([]Message, error) { for step := 0; step < maxSteps; step++ { reply, err := chat(history) if err != nil { return history, err } history = append(history, reply) if len(reply.ToolCalls) == 0 { fmt.Println("agent>", reply.Content) return history, nil } for _, call := range reply.ToolCalls { fmt.Printf(" [tool] %s %s\n", call.Function.Name, call.Function.Arguments) history = append(history, Message{ Role: "tool", ToolCallID: call.ID, Content: truncate(runTool(call)), }) } } return history, fmt.Errorf("stopped after %d tool rounds; ask again to continue", maxSteps) } ``` **Checkpoint:** from `playground`, run `go vet ..`. It prints nothing if all edits landed. If there's an error, compare the named function with the [finished step][step-5]. ### Brief the model A system prompt is a message with the role `system` at the start of the history. The model treats it as standing instructions: ```go func systemPrompt() string { return fmt.Sprintf(`You are a coding agent running on %s. Your workspace is %s. Every path is relative to it. Use the tools to look at files and run commands instead of guessing. When a tool returns an error, read it and try a different approach. Keep answers short and say which files you changed.`, runtime.GOOS, workspace) } ``` Replace `main` so it sets the workspace, seeds the history with the system prompt, and adds a `/reset` command that clears everything after it: ```go func main() { var err error workspace, err = os.Getwd() if err != nil { fmt.Fprintln(os.Stderr, "error:", err) os.Exit(1) } history := []Message{{Role: "system", Content: systemPrompt()}} fmt.Printf("Agent ready in %s. Type /reset to start over, /quit to exit.\n", workspace) for { fmt.Print("\nyou> ") if !input.Scan() { return } line := strings.TrimSpace(input.Text()) switch line { case "": continue case "/quit": return case "/reset": history = history[:1] fmt.Println("History cleared.") continue } history = append(history, Message{Role: "user", Content: line}) history, err = runTurn(history) if err != nil { fmt.Fprintln(os.Stderr, "error:", err) } } } ``` Run it from `playground` and give it a real task: ```bash go run .. ``` At the `you>` prompt, type this request as one line. If you don't have Python, ask for a shell script instead. ```text Write a Python script called fizz.py that prints FizzBuzz from 1 to 15, then run it with python3 to check it works. ``` Type `y` at each `allow` prompt. When the agent answers, type `Read the file ../go.mod` to test the workspace fence: ```text you> Write a Python script called fizz.py that prints FizzBuzz from 1 to 15, then run it with python3 to check it works. [tool] write_file {"content":"for i in range(1, 16):\n ...","path":"fizz.py"} allow write_file? [y/N] y [tool] run_command {"command":"python3 fizz.py"} allow run_command? [y/N] y agent> The Python script `fizz.py` has been created and executed successfully. ... you> Read the file ../go.mod [tool] read_file {"path":"../go.mod"} [tool] list_files {"path":"."} agent> I cannot read the file `../go.mod` because it appears to be outside the current workspace directory. ... ``` After an error, the model used `list_files` before replying. It may phrase its answer differently, such as saying it can't find the file, but `safePath` refused the read, and the reply never quotes `go.mod`. Finally, answer `n` at an approval prompt and watch the model pause for instructions. **What happened:** The model chose each action; the harness chose which ran. Approval is the sole safeguard for `run_command`: approved commands can access any file your account can, so review each before typing `y`. **Checkpoint:** `fizz.py` exists in `playground`, the agent could not read `../go.mod`, a denied command did not run, and `/reset` prints `History cleared.` ## Step 6: Test It and Ship It ### Test the loop without a model Tests using real models are slow and inconsistent. Fake the server with Go's `httptest` package, which runs a real HTTP server so `chat` works unchanged. Create `main_test.go` next to `main.go`: ```go package main import ( "encoding/json" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" ) func TestSafePathKeepsAgentInsideWorkspace(t *testing.T) { workspace = t.TempDir() for _, p := range []string{"notes.txt", "src/main.go", ".", "a/../b.txt"} { if _, err := safePath(p); err != nil { t.Errorf("safePath(%q) refused a path inside the workspace: %v", p, err) } } outside := filepath.Join(filepath.Dir(workspace), "secrets.txt") for _, p := range []string{"..", "../secrets.txt", "a/../../b.txt", outside} { if _, err := safePath(p); err == nil { t.Errorf("safePath(%q) allowed a path outside the workspace", p) } } } // TestAgentLoopRunsToolThenAnswers fakes a model server that asks for // read_file once, then answers with what the tool returned. func TestAgentLoopRunsToolThenAnswers(t *testing.T) { workspace = t.TempDir() if err := os.WriteFile(filepath.Join(workspace, "go.mod"), []byte("module demo\n"), 0o644); err != nil { t.Fatal(err) } calls := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req chatRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { t.Errorf("bad request body: %v", err) http.Error(w, err.Error(), http.StatusBadRequest) return } calls++ var reply Message last := req.Messages[len(req.Messages)-1] if last.Role == "tool" { reply = Message{Role: "assistant", Content: "The file says: " + last.Content} } else { reply = Message{Role: "assistant", ToolCalls: []ToolCall{{ ID: "call_1", Type: "function", Function: FunctionCall{Name: "read_file", Arguments: `{"path":"go.mod"}`}, }}} } json.NewEncoder(w).Encode(map[string]any{"choices": []map[string]any{{"message": reply}}}) })) defer server.Close() t.Setenv("HARNESS_BASE_URL", server.URL) history, err := runTurn([]Message{{Role: "user", Content: "What is in go.mod?"}}) if err != nil { t.Fatal(err) } if calls != 2 { t.Errorf("expected 2 model calls (tool request, then answer), got %d", calls) } final := history[len(history)-1] if !strings.Contains(final.Content, "module demo") { t.Errorf("final answer did not include the tool result: %q", final.Content) } } ``` Run the tests from the project folder, not `playground`: ```bash cd .. && go test ./... ``` **You should see:** `ok harness 0.012s` or a similar time. The tests pass with Ollama stopped. The [finished step][step-5] adds two more tests in `more_test.go`, for `truncate` and for unknown tool names. ### Build one binary per platform ```bash go build -ldflags="-s -w" -o harness . GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o harness.exe . GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -o harness-linux-arm64 . ``` On Windows, build the first binary with `-o harness.exe`. To cross-compile in PowerShell, set `$env:GOOS = "linux"; $env:GOARCH = "arm64"` before `go build`. Afterward, run `Remove-Item Env:GOOS, Env:GOARCH` to target Windows again. `-ldflags="-s -w"` strips debug symbols. Each binary is about 6 to 7 MB and runs on any computer with the same operating system and processor, without Go, Python, or package installation. ### Point it at a hosted model Run the binary you just built from `playground`, with no `go run`: ```bash cd playground && ../harness ``` **Checkpoint:** The agent answers from the local model, and `harness.exe` and `harness-linux-arm64` sit next to `harness` in the project folder. **Optional: use a hosted model.** If your computer struggles with a local model, this binary also works with any OpenAI-compatible Chat Completions endpoint. Hosted models require an account and charge per request, so check pricing first. For [Ollama's cloud API][ollama-openai], create an Ollama account key and run: ```bash export HARNESS_BASE_URL=https://ollama.com/v1 export HARNESS_API_KEY=your-ollama-api-key export HARNESS_MODEL=gemma4:31b ../harness ``` To go back to your local model, run `unset HARNESS_BASE_URL HARNESS_API_KEY HARNESS_MODEL` or open a new terminal. In PowerShell, set each variable with `$env:HARNESS_BASE_URL = "https://ollama.com/v1"` and so on, then run `..\harness.exe`. ## Verification Run through this list to confirm the harness is complete: * `go test ./...` passes with Ollama stopped. * Asking the agent to read a file in the workspace produces a `[tool] read_file` line and a correct answer. * A request to write a file or run a command shows an `allow ...? [y/N]` prompt, and answering `n` stops it. * Asking for `../go.mod` fails, and the agent never shows the file's contents. * `/reset` clears the conversation, and the agent no longer remembers earlier turns. If every item checks out, you have a working agent harness. ## Troubleshooting ### Problem: connection refused **Symptoms:** `error: Post "http://localhost:11434/v1/chat/completions": dial tcp ... connection refused`. **Solution:** start Ollama with `ollama serve`, or open the Ollama app, then run the harness again. **If that doesn't work:** check `curl http://localhost:11434/v1/models`. If that also fails, something else may be using port 11434, or `HARNESS_BASE_URL` points to the wrong address. ### Problem: model server returned 404 Not Found **Symptoms:** the harness prints `error: model server returned 404 Not Found` on the first message. **Solution:** The model may be missing or misspelled. Run `ollama list`, then `ollama pull gemma4:e2b` or set `HARNESS_MODEL` to a listed model. For hosted endpoints, check the provider's model list and set `HARNESS_MODEL` to an exact name. ### Problem: the model prints JSON instead of calling a tool **Symptoms:** the agent replies with text such as `{"name": "write_file", "parameters": ...}` and no `[tool]` line appears. **Solution:** The model output a tool call as text instead of using the tool-calling format, a common issue with small or older models. In tutorial tests, `llama3.2:3b` handled one tool but garbled four, while `qwen2.5-coder:7b` rendered its first call as text. Choose a model whose Ollama page lists the "tools" capability and that handles multiple tools well, such as `gemma4:e2b` or `gemma4:e4b`. ### Problem: the build fails after an edit **Symptoms:** `go run` stops with `undefined: tools`, `"time" imported and not used`, or `declared and not used`. **Solution:** An edit was only partially applied. Complete the current step, then rerun. If it still fails, download that step's `main.go` from the [companion code repository][harness-repo] and compare it with yours using `diff`. ### Problem: stopped after 25 tool rounds **Symptoms:** The harness prints `error: stopped after 25 tool rounds; ask again to continue`. **Solution:** The model kept calling tools without answering. Type `continue` to give it 25 more rounds. If `[tool]` lines repeat the same call, type `/reset` and ask for a smaller task. ### Problem: the agent is slow **Symptoms:** each reply takes many seconds or minutes. **Solution:** Speed depends on the model, not the harness. Close resource-heavy apps, try a smaller model that reliably calls tools, or use a hosted model (Step 6). Step 5's five-minute HTTP timeout prevents requests from hanging indefinitely. ### Problem: model server returned 401 Unauthorized **Symptoms:** a hosted endpoint rejects every request. **Solution:** Set `HARNESS_API_KEY` in the harness's terminal session and ensure `HARNESS_BASE_URL` ends in `/v1` without a trailing slash. ### Problem: shell commands fail on Windows **Symptoms:** commands such as `ls` or `cat` return "is not recognized as an internal or external command." **Solution:** On Windows, commands run through `cmd /C`; use `dir` and `type`, or specify in the system prompt that the shell is `cmd.exe`. ## Next Steps **To learn more:** * [What Are Coding Agents?][coding-agents] explains the six components production harnesses add: repository context, prompt caching, structured tools, context reduction, memory, and subagents. * [Building Effective Agents][building-effective-agents] from Anthropic covers when to use an agent at all, and how to design tools a model can use well. * [Mini Coding Agent][mini-coding-agent] by Sebastian Raschka implements the same ideas in one Python file, including session memory and subagents. **To extend this project:** * **Stream replies.** Add `"stream": true` to the request and print tokens as they arrive, so long answers don't look frozen. * **Edit instead of overwrite.** Add an `edit_file` tool that replaces one exact snippet. Rewriting a whole file wastes tokens and invites the model to drop lines. * **Save sessions.** Write the history to a JSON file on `/quit` and load it on start, so the agent remembers yesterday's work. * **Compact the history.** When the history grows past a size limit, ask the model to summarize older turns and replace them with the summary. * **Close the symlink gap.** `safePath` checks path text, so a symbolic link inside the workspace can still point outside it. Resolve links with `filepath.EvalSymlinks` before checking. To check your work, or to skip ahead, [`steps/06-extensions`][step-6] in the companion repository implements all five, with a test for each. Run `diff steps/05-guardrails/main.go steps/06-extensions/main.go` to see what each one adds. The harness you built is small enough to read in one sitting, and every coding agent you use runs the same loop within much more code. Next time one surprises you, good or bad, you'll know which part of the loop to examine. ## References * [Companion code repository][harness-repo], the finished program for each step, with tests. * [Building Effective Agents][building-effective-agents], Anthropic's guide to agent patterns and tool design. * [Mini Coding Agent][mini-coding-agent], a minimal Python coding agent harness by Sebastian Raschka. * [Ollama OpenAI compatibility][ollama-openai], the endpoints, request fields, and tool support used in this tutorial. * [Gemma 4 on Ollama][gemma4], model sizes, capabilities, and the edge models used here. * [Download and install Go][go-install], official installation steps for each operating system. * [Download Ollama][ollama-download], install commands for macOS, Linux, and Windows. [ollama]: https://ollama.com [ollama-download]: https://ollama.com/download [ollama-openai]: https://docs.ollama.com/api/openai-compatibility [gemma4]: https://ollama.com/library/gemma4 [go-install]: https://go.dev/doc/install [building-effective-agents]: https://www.anthropic.com/engineering/building-effective-agents [mini-coding-agent]: https://github.com/rasbt/mini-coding-agent [harness-repo]: https://github.com/jeffabailey/learn/tree/main/ai-agents/harness [step-5]: https://github.com/jeffabailey/learn/tree/main/ai-agents/harness/steps/05-guardrails [step-6]: https://github.com/jeffabailey/learn/tree/main/ai-agents/harness/steps/06-extensions [coding-agents]: https://jeffbailey.us/blog/2026/04/04/what-are-coding-agents/