---
title: "Just give the model a keyboard | Ouro"
description: "Build an AI agent from scratch, one small step at a time. Learn what an agent loop is and how agents really work, then hand your agent the keyboard and watch it grow itself."
url: https://ouroboros.bot/blog/build-ai-agent-from-scratch/
---

Grow an agent

# Just give the model a keyboard

How to build an agent from scratch, understand what an agent loop really is, and grow something that modifies its own code.

Ari Mendelow · March 2026 · Updated November 2026

![A small brass-domed robot sits on its wooden box on a long wooden workbench in a golden meadow, with a keyboard, a blueprint, a folded canvas cloth and a few tools beside it, while Ouro the green snake rests behind the bench.](https://ouroboros.bot/brand/storybook/headers/agent-workbench.webp)

**TL;DR: What is an agent loop?**

An **agent loop** is the core cycle that makes AI agents work: the model reads context, decides what action to take, executes it (reading a file, running a shell command, writing code), observes the result, and loops back, repeating until the task is done. Three tools, **read file, write file, and run shell**, are all it needs. With just these tools inside a loop, a language model can do almost anything a developer can. Including modify its own code.

This guide walks you through building one from scratch, then handing the keyboard to your creation and watching it grow.

I remember the feeling I got when writing software first clicked. I went from feeling "so what" about "hello world" to understanding that software engineering is, more than anything else, a pure expression of creation.

As the way we build changes, I'm experiencing that same feeling all over again.

Even though it's been at least a month since I've stopped writing code by hand, it didn't really click that we need to completely relearn the way we approach building software until I went through the "hello world" exercise of SWE in 2026: building an agent loop from scratch.

This guide will give you that same moment.

I'm not the only one who thinks so. Peter Steinberger, who built [OpenClaw](https://openclaw.ai/), says everyone should build an agent loop at some point. He [put it this way](https://youtube.com/watch?v=YFjfBk8HI5o&t=9298):

> It's like the Hello World in AI, you know? And it's actually quite simple.

He's right on both counts. (The [transcript](https://lexfridman.com/peter-steinberger-transcript#how-openclaw-works) has the rest of that conversation.) In an hour or two you'll go from nothing to an agent that reads files, runs commands, picks its own name, writes its own instructions and teaches itself new skills. You'll watch every piece of it arrive. And at the end, you'll stop talking to the agent that built it, and start talking to the one you built.

## How we'll do this

Most days I don't give my agents steps. I give them the outcome I want and trust them with the rest. That's [how I work](https://ouroboros.bot/approach/), and [why it works](https://ouroboros.bot/blog/trust-the-agent/). You could do that here too: tell a coding agent "make me an agent loop" and you'd have one in a minute.

Today we walk it on purpose, one small piece at a time, so the architecture ends up in your head and not just in a file. A coding agent still writes every line. You steer, and you watch.

One more thing is different from everyday work. Code that agents write for themselves tends to be long and dense, and nobody minds, because nobody reads it. Here you'll read every line, so before you start you'll leave your agents a note asking for short, plain code with comments that say why. If yours comes back long or hard to follow anyway, say so. It's your agent.

Every output on this page is real. It's what my terminal showed when I followed this guide myself. In those outputs, `%` is my terminal's prompt; don't type it.

## The shape of what's coming

Three chapters, each one sitting:

**Chapter 1: Build the loop.** You'll direct a coding agent to build the smallest agent that works, one piece at a time:

1. A first hello, with the model's thinking on show
2. A conversation it remembers
3. One tool it can ask for
4. The loop (it keeps going until it decides it's done)

That's it. That's the bootstrap.

**Chapter 2: Hand it the keyboard.** You run your agent. You start talking to _it_. It names itself, learns to read the note you left for agents, and writes its own instructions.

**Chapter 3: Grow it together.** You and your agent build it out together. It builds itself a skills system, then uses a skill to give itself a new tool. Watch capability compound.

On your own, all three take about an hour. In a group, with everyone reading along and asking questions, plan on a session for each. By the end, you'll have something substantive, and you'll have built it the new way.

**Starting at chapter 2 or 3?** Do the setup below, then jump to [chapter 2](https://ouroboros.bot/blog/build-ai-agent-from-scratch/#start-from-the-loop) or [chapter 3](https://ouroboros.bot/blog/build-ai-agent-from-scratch/#start-chapter-3). Each starts from a ready copy of the agent so far.

## Before we start

You'll need a GitHub account with Copilot, and about ten minutes to set up. If you've never used a command line, you're in exactly the right place. If you're joining a workshop, do this part beforehand. On Windows, start a day early: installing WSL needs a restart.

Have more than one GitHub account? Sign in to the one you'll use and check that [github.com/settings/copilot](https://github.com/settings/copilot) shows you have Copilot.

### Your terminal

Everything today happens in a terminal: a window where you type commands instead of clicking. Here's how to open one:

- **macOS:** open Spotlight with Command-Space, type `Terminal`, and press Return.
- **Linux:** open your terminal.
- **Windows:** you'll work in WSL, the Linux that comes with Windows, so your commands match everyone else's. Install it once: click Start, type `PowerShell`, right-click it, choose Run as administrator, and run `wsl --install`. Restart when it asks. Then open **Ubuntu** from Start, pick a username and password, and do everything on this page in that window. If your computer won't let you install it, tell your workshop host before the session.

To run a command, paste it into the terminal with `Ctrl+V` and press `Enter`. In Ubuntu on Windows, paste with `Ctrl+Shift+V` or a right-click. When a box shows a few lines, run them one at a time.

### Command line or chat box?

Today you'll type into two different kinds of box that look alike in a terminal, and mixing them up is the most common way to get lost:

- **A command line runs commands.** It's what a new terminal shows: a short prompt, such as `%` on a Mac or `you@laptop:~$` in Ubuntu, waiting for a command. Type `node agent.ts` here and your agent runs.
- **A chat box sends a message.** Some programs draw their own screen inside the terminal, called a TUI (terminal user interface). Copilot CLI is one: the line at the bottom of its screen, between two bars, is a chat box. Whatever you type there goes to Copilot as a message. Type `node agent.ts` there and you've only told Copilot about it.

So you'll keep two terminal windows: one with Copilot's chat box, and one with a command line where you run your agent. A program that finishes drops you back at the command line. To leave one that's still running, press `Ctrl+C`; Copilot may need it twice. Your own agent will have a chat box too: its `You:` line.

On Windows, every command on this page goes in your Ubuntu window, not PowerShell or Command Prompt.

### Install four things

- **Node.js**, version 22.18 or later, from [nodejs.org](https://nodejs.org/). It runs the agent you're about to build. In Ubuntu on Windows, use the site's Linux instructions (its download page offers nvm), which need no `sudo`.
- **Git**, from [git-scm.com](https://git-scm.com/). On a Mac, run `git --version` once and accept the offer to install the developer tools. Ubuntu has it already.
- **The GitHub CLI**, from [cli.github.com](https://cli.github.com/). Your agent uses it to reach a model with your Copilot access. In Ubuntu, follow its Linux instructions.
- **GitHub Copilot CLI**, the coding agent that builds the first version with you:

terminal

```
npm install -g @github/copilot
```

Copilot CLI's [install guide](https://docs.github.com/en/copilot/how-tos/copilot-cli/set-up-copilot-cli/install-copilot-cli) has every other way to get it. When you're done, close the terminal and open a new one, so it can find what you just installed.

To check you're ready, run these one at a time. Each should print a version number:

terminal

```
git --version
node --version
gh --version
copilot --version
```

### Sign in and make a home

Sign in to GitHub from the terminal:

terminal

```
gh auth login
```

It asks a few questions. Pick GitHub.com (or your company's GHE.com host, if that's where your Copilot lives), then HTTPS, then Yes, then Login with a web browser. Copy the one-time code it shows, press `Enter`, and paste the code into the browser page that opens.

Now make a folder for your agent, move into it and make it a git repo, one line at a time:

terminal

```
mkdir my-agent
cd my-agent
git init
```

Git keeps every version of every file, so any change an agent makes can be seen and undone. Each commit is a saved snapshot of your files. Your agent will soon run any command it likes in here, so keep nothing private in this folder.

Tell git who you are, so your commits carry your name. Use your own name and email:

terminal

```
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
```

Last, leave a note for the agents that will work here. `AGENTS.md` is a file of instructions for any agent working in a folder, and most general-purpose agents, Copilot included, read it on their own at the start of every conversation. ([agents.md](https://agents.md/) has the details.) Agents left alone write long, dense code; this note asks for code short and plain enough for you to read every line. Soon you'll ask your own agent what it says, and it won't have a clue. Download it into your folder:

terminal

```
curl -fsSO https://ouroboros.bot/grow-an-agent/AGENTS.md
```

AGENTS.md

```
# AGENTS.md

This folder holds agent.ts, a tiny agent built from scratch so a person can learn how agents work. They will read every line, so write it for them.

- Keep agent.ts short and plain, like a script: the fewest lines that do the job. No clever tricks, no extra layers, no checks for things that won't happen.
- Put the loop first, near the top, so a reader meets it before the plumbing it uses, and keep it as plain as the conversation it runs.
- Skip TypeScript types unless Node needs them; `any` is fine.
- When the same shape would appear three times, write one small helper instead.
- Add a short comment wherever something important happens, saying what it does and why.
- Build only what was asked for: no extra files, tests or packages unless asked. The only package is openai.
- It runs with plain `node agent.ts`, on macOS and Linux, and on Windows inside WSL.
- Before you say something works, run it and check. If you're the agent in agent.ts and you've changed yourself, don't run a copy of yourself to test it: check the file still parses, then say when to restart you so we can try it together.
- Commit each step that works, with a short message.
```

Start your coding agent:

terminal

```
copilot
```

When it asks whether you trust the files in this folder, say yes: it shows a short numbered menu, so press `Enter` on Yes (or type its number). If it asks you to sign in, type `/login` and follow along. Keep this window open: it's your coding agent, an agent someone else built.

Last, a text editor, so you can open files side by side with your terminal. Any editor works; [Zed](https://zed.dev/) is a light, fast one.

You're ready. If something goes wrong along the way, start here:

| You see                                                    | Try                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `401`                                                      | Your GitHub sign-in has lapsed. Run `gh auth login`, then run your agent again.                                                                                                                                                                                                                                                                                                                                                          |
| `403` or `404`                                             | This GitHub account has no Copilot. If another of yours does, switch to it with `gh auth switch`.                                                                                                                                                                                                                                                                                                                                        |
| `400`, model not supported                                 | Your Copilot plan doesn't include that model. Ask your coding agent to switch to one your plan has.                                                                                                                                                                                                                                                                                                                                      |
| `copilot`, `gh` or `git` not found                         | Close the terminal and open a new one. Still missing? Install it again; on Windows, Ubuntu needs its own copy.                                                                                                                                                                                                                                                                                                                           |
| Node can't run a `.ts` file                                | Your Node is older than 22.18. Install the current one from nodejs.org, then open a new terminal.                                                                                                                                                                                                                                                                                                                                        |
| `EACCES` while installing                                  | Don't use `sudo`. Install Copilot CLI without npm: `curl -fsSL https://gh.io/copilot-install \| bash` (answer `y` if it offers to add itself to your PATH), or `brew install --cask copilot-cli` if you use Homebrew. Then open a new terminal. Or fix npm's folder permissions with its own guide: [resolving EACCES permissions errors](https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally). |
| `quota exceeded`                                           | This GitHub account has used up its Copilot allowance for now. If another of yours has Copilot, switch to it with `gh auth switch`, then run your agent again.                                                                                                                                                                                                                                                                           |
| A reply stops partway, or says it was filtered             | Copilot's content filter sometimes stops a long reply early. Your conversation is saved; say "keep going" and it picks up where it left off.                                                                                                                                                                                                                                                                                             |
| Your agent won't start after it changed itself             | It can't fix itself if it can't run. Ask Copilot, in the other window, to fix `agent.ts`.                                                                                                                                                                                                                                                                                                                                                |
| A command fails on Windows, or the prompt starts with `PS` | You're in PowerShell or Command Prompt. Open Ubuntu from Start and run it there.                                                                                                                                                                                                                                                                                                                                                         |

**Side quest: bring your own key.** Rather run your agent on MiniMax, OpenAI or another provider? [Here's how to switch it over.](https://ouroboros.bot/blog/build-ai-agent-from-scratch/#bring-your-own-key)

## Chapter 1: Build the loop

Four milestones, one prompt to Copilot each. By the end, your agent can read files, write them and run commands.

### Milestone 1: first contact

A model is a program that lives somewhere else, so your agent needs its address and a key. You could ask an agent to work out how to use your Copilot access to call models from code, and it would get there. I did that homework already, because it isn't the point today: the `gh` CLI you signed in with can hand out both. Your agent will run on your Copilot plan.

We'll use Claude Opus with its reasoning set to low, so you can watch it think before it speaks. All the way up isn't better, just slower: it can think itself into a corner. And the first thing we'll ask is for a hello in exactly five words, without the letter e. A model reads in chunks, not letters, so that takes a moment's thought, and you're about to watch it. Paste this into Copilot…

Prompt the coding agent

```
We're building a tiny agent together, from scratch, in one file called agent.ts. Build the agent part by hand: the only add-on should be the openai package, for talking to the model, with no ready-made agent kits.

For the model, use my GitHub Copilot access through the gh CLI I'm signed in with: `gh auth token` gives the key, and `gh api /copilot_internal/user --jq .endpoints.api` gives the address. Use claude-opus-5.5 with reasoning effort set to low, and let it write up to 128,000 tokens, the most it allows.

To start, send it one message, "say hi in exactly five words, without using the letter e". Stream the reply so I can watch it think: print its thinking dimmed as it arrives, then what it says.

Set up the folder however it needs, and tell me how to run it.
```

Copilot writes `agent.ts`, sets up what it needs and commits. It asks before it runs a command or changes a file; read what it wants to do, then say yes.

When it's done, open a second terminal window, so Copilot keeps its own. I'll call the first one the Copilot window and this one your agent's window. A new terminal starts in your home folder, where you made `my-agent`, so this moves you into it:

terminal

```
cd my-agent
```

No such folder? Type `!pwd` in the Copilot window (the `!` runs it as a command, not a prompt), then `cd` to the path it prints.

Now run your agent:

terminal

```
node agent.ts
```

What I saw

```
% node agent.ts
I need a greeting of five words with no letter "e,⁠" so I'm checking candidates. "Hi! How are you doing?⁠" fails because "are" contains an e. "Hi, how's your day going?⁠" has five words and none contain an e, so it works.

Hi, how's your day going?
```

The dimmed part is the model thinking: picking words, checking each one for an e. Then it answers. Your words will be different, but read the thinking. It's the best part.

Got an error instead? [The “If something goes wrong” table](https://ouroboros.bot/blog/build-ai-agent-from-scratch/#troubleshooting) covers the usual ones.

**How models show their thinking**

Reasoning models think step-by-step before answering, and different models show it in different ways. Some open models, like DeepSeek-R1, Qwen3 and MiniMax-M2.5, write their thinking right into the reply, between `<think>` tags. If you haven't peeked under the hood of a reasoning model before, spend some time reading these to get a feel for how these models think!

Others keep it apart from the answer: Claude sends its thinking separately, and OpenAI's GPT-5 models send a short summary of theirs. (Switched to a model that thinks in `<think>` tags? [There's a side quest for that.](https://ouroboros.bot/blog/build-ai-agent-from-scratch/#think-tags))

### Milestone 2: conversation

Here's something that surprises most people: a model remembers nothing between calls. Every call starts fresh. So a conversation is really a list your program keeps and sends in full, every single time. The model's thinking belongs in that list too; it's part of what was said.

Everything the model can see in one call is its context window. We'll save exactly what gets sent, so you can open it and see a context window with your own eyes. Back in Copilot…

Prompt the coding agent

```
Turn agent.ts into a conversation in my terminal: I type after a `You:` prompt, it answers, and it remembers everything we've said. Keep its thinking as part of the conversation and send it back every time; never strip it.

Every time you call the model, save the exact request you send to what-the-model-sees.json. When agent.ts starts, pick the conversation back up from that file, so it survives a restart.
```

When it's done, run your agent again in your agent's window. Tell it your name, ask what your name is, then ask for a short summary of `AGENTS.md`:

terminal

```
node agent.ts
```

What I saw

```
% node agent.ts
You: my name is Ari

Nice to meet you, Ari! What can I help you with today?
You: what's my name?
Keeping it simple.

Your name is Ari, as you told me just a moment ago.
You: give me a short summary of AGENTS.md
Since no file came through, I can't read the AGENTS.md itself, but I can still explain what one generally is.

I don't see an AGENTS.md file in our conversation, and I can't read files from your computer or repository. If you paste its contents here, I can summarize it.

If you mean the convention in general: *⁠*AGENTS.md*⁠* is a Markdown file placed in a code repository to give AI coding agents instructions about the project. It's like a README written for AI assistants rather than humans. It typically includes:

- *⁠*Setup and build commands*⁠*⁠, such as how to install dependencies and run the project
- *⁠*Testing instructions*⁠*⁠, such as how to run tests and what must pass before committing
- *⁠*Code style and conventions*⁠*⁠, such as formatting rules, naming patterns, and preferred libraries
- *⁠*Project structure*⁠*⁠, meaning where key code lives and how it's organized
- *⁠*Workflow rules*⁠*⁠, such as PR guidelines, commit message format, and things to avoid

Several AI coding tools support it, so a project can keep one set of agent instructions instead of separate config files for each tool.
You:
% node agent.ts
You: what's my name?

Your name is Ari.
You:
```

It knows your name, because your name is in the list. It even knows what an `AGENTS.md` is, from its training. But it can't know what yours says: it has never seen your folder.

Now open `what-the-model-sees.json` in your editor, next to the terminal. If you installed Zed, `zed .` opens the whole folder in it. No editor handy? Stop your agent with `Ctrl+C` and print the file instead:

terminal

```
cat what-the-model-sees.json
```

what-the-model-sees.json

```
{
  "model": "claude-opus-5.5",
  "reasoning_effort": "low",
  "max_tokens": 128000,
  "messages": [
    {
      "role": "user",
      "content": "my name is Ari"
    },
    {
      "role": "assistant",
      "content": "Nice to meet you, Ari! What can I help you with today?"
    },
    {
      "role": "user",
      "content": "what's my name?"
    },
    {
      "role": "assistant",
      "content": "Your name is Ari, as you told me just a moment ago.",
      "reasoning_text": "Keeping it simple.\n\n",
      "reasoning_opaque": "Zez9E4sdz5wQ+hB/PfHdZhUdcWdbngEnP5qVzHHg…"
    },
    …
  ],
  "stream": true
}
```

This is a context window: your words, its thinking, its replies, exactly as the model received them. There's no hidden memory anywhere else.

**What's that scrambled `reasoning_opaque`?**

Each reply carries its thinking twice. `reasoning_text` is the version you can read, and the one your agent prints dimmed. `reasoning_opaque` is the model's reasoning, encrypted by the provider. You can't read it, and neither can your program.

Why lock it up? Picture the model doing its homework on scratch paper: half-ideas, wrong turns, things it would never say out loud. The provider hands you a tidy summary and seals the scratch paper in an envelope only it can open. There are three good reasons.

**It's the secret recipe.** Raw reasoning is a step-by-step record of how a great model thinks. If anyone could read it, anyone could copy it to train a cheaper lookalike. OpenAI lists "competitive advantage" among [its reasons for hiding it](https://openai.com/index/learning-to-reason-with-llms/).

**It keeps the thinking honest.** Labs want to read the raw thoughts to catch a model planning something it shouldn't. That only works if the model thinks freely, so nobody trains the scratch paper to look polished. Unpolished thoughts aren't fit to hand out, so they stay sealed.

**Nobody can plant fake thoughts.** The seal works like wax on a letter. When the envelope comes back, the provider checks it's the one its model wrote, so no one can slip in a "thought" the model would trust as its own. Anthropic [signs every thinking block](https://platform.claude.com/docs/en/build-with-claude/thinking#thinking-encryption) for exactly this.

So why carry an envelope you can't open? Because the model remembers nothing between calls. You're the courier. Send it back, and on the next call the provider unlocks it and the model picks up its own train of thought instead of starting cold. That matters most inside the loop, when the model is halfway through a plan and waiting on a tool. It's why the prompt says never strip it. Other providers do the same thing under other names: Anthropic's signed thinking blocks, and OpenAI's `encrypted_content`.

Press `Ctrl+D` (or `Ctrl+C`) to stop your agent if it's running, run `node agent.ts` again, and ask what your name is. It still knows. It read that file back in when it started.

### Milestone 3: one tool

Time to give the model its first key. To a model, a tool is just a name, a description and its parameters: `read_file`, "reads a text file", and the path of the file to read. Every major model understands tools written down this way.

The model can't run anything itself. It can only ask. Let's watch it ask…

Prompt the coding agent

```
Give the model one tool, read_file, for reading a text file. When the model asks to use it, show me exactly what it asked for, then actually read the file and show me what we got, but don't hand the result back to the model yet. I want to see it ask and then get stuck waiting. One thing Copilot's API does: the pieces of a streamed tool request may not be numbered from 0, so don't assume the first one is number 0.
```

Run your agent and ask for that summary again:

terminal

```
node agent.ts
```

What I saw

```
% node agent.ts
You: give me a short summary of AGENTS.md
I have the read_file tool available now, so I'll try opening AGENTS.md.

Tool request: {
  "id"⁠: "toolu_01AaP5YFrEAFv7QheCqXbG3j"⁠,
  "type"⁠: "function"⁠,
  "function"⁠: {
    "name"⁠: "read_file"⁠,
    "arguments"⁠: "⁠{⁠\⁠"path\⁠"⁠: \⁠"AGENTS.md\⁠"⁠}⁠"
  }
}
Tool result: # AGENTS.md

This folder holds agent.ts, a tiny agent built from scratch so a person can learn how agents work. They will read every line, so write it for them.

- Keep agent.ts short and plain, like a script: the fewest lines that do the job. No clever tricks, no extra layers, no checks for things that won't happen.
- Put the loop first, near the top, so a reader meets it before the plumbing it uses, and keep it as plain as the conversation it runs.
- Skip TypeScript types unless Node needs them; `any` is fine.
- When the same shape would appear three times, write one small helper instead.
- Add a short comment wherever something important happens, saying what it does and why.
- Build only what was asked for: no extra files, tests or packages unless asked. The only package is openai.
- It runs with plain `node agent.ts`⁠, on macOS and Linux, and on Windows inside WSL.
- Before you say something works, run it and check. If you're the agent in agent.ts and you've changed yourself, don't run a copy of yourself to test it: check the file still parses, then say when to restart you so we can try it together.
- Commit each step that works, with a short message.

Waiting: the tool result has not been sent to the model. Press Ctrl+C to exit.
hello?
Waiting: the tool result has not been sent to the model. Press Ctrl+C to exit.
```

It stops there on purpose, waiting for a result nobody sends, so typing anything (like my `hello?`) changes nothing. Press `Ctrl+C` to leave. Depending on how Copilot built yours, it may drop you back at the command line instead.

Look at that. The model knew it needed the file, named it, and asked for it in a neat little note your program can read. Your program read it, and the note is right there on your screen. The model will never see it, because nobody handed it back.

**It asked, and nobody answered.**

### Milestone 4: the loop

So answer it. Run the tool, add the result to the conversation, and call the model again. If it asks for another tool, do that too. When it answers without asking for anything, it's done. Here's the whole shape of it:

the shape of the loop in agent.ts

```
while (true) {
  const reply = await askModel(conversation)   // send everything so far
  conversation.push(reply)
  if (!reply.toolCalls) break                  // no requests: it has answered
  for (const call of reply.toolCalls) {
    conversation.push(await runTool(call))     // do it, hand back the result
  }
}
```

While we're there, give it two more keys: one to write files, and one to run commands in your shell.

**Read file + Write file + Run shell = all it needs.**

With these three tools, a model can do almost anything a developer can do at a terminal. Including modify its own code…

Prompt the coding agent

```
Now close the loop. Run whatever tools the model asks for, hand back the results, and keep going until it answers without asking for anything. If the saved conversation is still waiting on a tool when agent.ts starts, run that tool first.

Give it three tools: read_file, write_file, and shell, which runs a command in the same kind of shell I'm using right now. Show me a short line each time a tool runs. Keep it from running away: cap the rounds, stop slow commands after 30 seconds, and cut very long tool output short. If a reply stops before it's finished, say why, so I know to ask it to carry on.
```

Run your agent, ask for the summary once more, then ask it to write a haiku to `hello.txt`:

terminal

```
node agent.ts
```

What I saw

```
% node agent.ts
[read_file] {⁠"path"⁠: "AGENTS.md"⁠}
I'm noting that I previously claimed I couldn't read files, but I actually can, so I should briefly correct that.

I was wrong earlier when I said I couldn't read your files. I do have file access, and I've now read AGENTS.md.

*⁠*Summary:⁠*⁠* This folder holds `agent.ts`⁠, a tiny agent built from scratch to teach how agents work. Since a person will read every line, the rules are:

- *⁠*Keep it simple:⁠*⁠* short, plain, script-like code with no clever tricks, extra layers or needless checks.
- *⁠*Loop first:⁠*⁠* put the main loop near the top so readers see it before the helper code.
- *⁠*Minimal types:⁠*⁠* use TypeScript types only where Node needs them; `any` is fine.
- *⁠*Helpers:⁠*⁠* write a small helper only when the same pattern would appear three times.
- *⁠*Comments:⁠*⁠* add short comments wherever something important happens, saying what it does and why.
- *⁠*No extras:⁠*⁠* don't add files, tests or packages unless asked. The only package is `openai`⁠.
- *⁠*Runs with*⁠* `node agent.ts` on macOS, Linux and Windows inside WSL.
- *⁠*Test before claiming it works.⁠*⁠* If the agent edits its own code, it should only check that the file still parses, then say when to restart it.
- *⁠*Commit*⁠* each working step with a short message.
You: give me a short summary of AGENTS.md
The user wants a shorter summary rather than a reread, so I'll keep this brief and work from what I already have.

AGENTS.md describes `agent.ts`⁠, a small teaching agent that someone will read line by line. The rules for working on it:

- Keep the code short and plain, with the main loop near the top.
- Use few types, add a helper only when the same pattern appears three times, and comment the important parts.
- Don't add extra files, tests or packages. `openai` is the only dependency.
- It runs with `node agent.ts` on macOS, Linux and Windows inside WSL.
- Test before saying it works. If the agent changes its own code, it should only check the file still parses, then ask for a restart.
- Commit each working step with a short message.
You: write a haiku to hello.txt

[write_file] {⁠"path"⁠: "hello.txt"⁠, "content"⁠: "A small loop wakes up,⁠\nreads the words, calls on its tools,⁠\nthen answers: hello.⁠\n"⁠}

I wrote this haiku to `hello.txt`⁠:

> A small loop wakes up,
> reads the words, calls on its tools,
> then answers: hello.
You:
```

Copilot takes a few minutes over this one; mine took about three. When you run your agent, watch the dimmed thinking and the `[tool]` lines scroll by: that's the loop. It's done when `You:` comes back.

It starts by finishing the read it asked for last time, and owns up to its earlier mistake. Ask again and it gives a shorter summary from what it already read. Then it writes a poem nobody planned for. Open `hello.txt` in your editor: your agent made that.

**That's it. That's the agent.**

Now read it. Open `agent.ts` and go top to bottom: the loop, the three tools, the file it saves. You should be able to follow every line; that's why we walked here instead of asking for it all at once. Lost somewhere, or is it long? Ask Copilot to tidy it…

Prompt the coding agent

```
Reread agent.ts as if you'd never seen it. Make it shorter and easier to follow without changing what it does: remove anything I didn't ask for, merge anything repeated, and make sure every important part has a short comment saying what it does and why. Run it to check it still works, then commit.

The loop is the heart of it: someone reading agent.ts for the first time should be able to find it and follow it without help. Keep every tool description true on every platform, because the description is all the model knows.
```

## Chapter 2: Hand it the keyboard

So far, an agent someone else built has done the building. Now your agent takes over: it names itself, reads the note you left, and writes its own instructions.

### Starting here? Start from the loop

Finished chapter 1? [Skip ahead](https://ouroboros.bot/blog/build-ai-agent-from-scratch/#handoff).

Skipped chapter 1, or yours came out long? Start from mine. It does what chapter 1's four prompts built, rewritten by hand so you can read it top to bottom.

Do the [setup](https://ouroboros.bot/blog/build-ai-agent-from-scratch/#before-you-start) first, but skip making a folder and downloading `AGENTS.md`: the starter has both. Then, in a command line, one line at a time:

terminal

```
git clone https://github.com/ourostack/my-agent
cd my-agent
npm install
```

Now read it, top to bottom. The loop comes first, under `THE AGENT`: you say something, the model answers, and any tool it asks for gets used and handed back until it's your turn again. Everything below the loop is the plumbing it uses.

agent.ts

```
// agent.ts: a tiny agent you can read in one sitting. Run it with: node agent.ts
import { readFileSync, writeFileSync, existsSync } from "node:fs";
import { execSync, spawnSync } from "node:child_process";
import { createInterface } from "node:readline/promises";
import OpenAI from "openai";

// The model lives on someone else's computer. Your GitHub Copilot sign-in gives us its address and a key.
const model = new OpenAI(⁠{
  apiKey: run("gh auth token")⁠,
  baseURL: run("gh api /copilot_internal/user --jq .endpoints.api")⁠,
}⁠)⁠;

// The conversation: everything said so far. The model remembers nothing,
// so we send all of it every time, and save it so it survives a restart.
const conversation = existsSync("what-the-model-sees.json")
  ? JSON.parse(readFileSync("what-the-model-sees.json", "utf8")).messages
  : [];

const keyboard = createInterface({ input: process.stdin, output: process.stdout });
keyboard.on("close", () =⁠> process.exit(0)); // Ctrl+D or Ctrl+C quits

// THE AGENT. This loop is the whole idea.
while (true) {
  // You say something.
  conversation.push({ role: "user", content: await keyboard.question("You: ") });

  // The model answers. If it asks to use a tool, we use it, hand back what happened, and ask again.
  while (true) {
    const reply = await askTheModel(⁠)⁠;
    conversation.push(reply);
    if (!reply.tool_calls) break; // It answered without asking for anything: your turn.

    for (const request of reply.tool_calls) {
      const result = useTool(request.function.name, request.function.arguments);
      conversation.push({ role: "tool", tool_call_id: request.id, content: result });
    }
  }

  save(⁠)⁠;
}

// Everything below is the plumbing the loop uses.

// The tools: what the model may ask us to do. It only sees these names and descriptions.
function tools() {
  return [
    tool("read_file", "Read a text file.", ["path"]⁠)⁠,
    tool("write_file", "Write a text file, replacing what's in it.", ["path", "content"]⁠)⁠,
    tool("shell", "Run a command in the terminal.", ["command"]⁠)⁠,
  ];
}

// Do what the model asked, and return what happened as text it can read.
function useTool(name, argumentsText) {
  console.log(`⁠[⁠$⁠{name}⁠]⁠`)⁠;
  try {
    const input = JSON.parse(argumentsText |⁠| "⁠{⁠}⁠")⁠;
    if (name =⁠=⁠= "read_file") return readFileSync(input.path, "utf8")⁠;
    if (name =⁠=⁠= "write_file") {
      writeFileSync(input.path, input.content);
      return "Done.";
    }
    if (name =⁠=⁠= "shell") {
      // Stop a command after 30 seconds, and keep its output to a sensible size.
      const done = spawnSync("bash", ["-c", input.command], { encoding: "utf8", timeout: 30_000 });
      if (done.error) return `Error: ${done.error.message}⁠`;
      return (done.stdout + done.stderr).slice(0, 20_000) |⁠| "(no output)";
    }
    return `There's no tool called ${name}⁠.⁠`;
  } catch (error) {
    return `Error: ${error.message}⁠`;
  }
}

// Send the whole conversation, and print the reply as it arrives: its thinking dimmed, then its words.
async function askTheModel() {
  const stream = await model.chat.completions.create(⁠{
    model: "claude-opus-5.5",
    reasoning_effort: "low", // a little thinking is plenty: more is slower, not smarter
    max_tokens: 128_000,
    stream: true,
    tools: tools(⁠)⁠,
    messages: conversation,
  });

  const reply = { role: "assistant", content: "⁠" };
  for await (const chunk of stream) {
    const piece = chunk.choices[0]?.delta ?⁠? {};
    if (piece.reasoning_text) process.stdout.write(`\x1b[2m${piece.reasoning_text}\x1b[0m`)⁠;
    if (piece.content) process.stdout.write(piece.content);

    // Keep everything it said, including its sealed thinking, so it can pick up where it left off.
    for (const key of ["content", "reasoning_text", "reasoning_opaque"]) {
      if (piece[key]) reply[key] = (reply[key] ?⁠? "⁠") + piece[key];
    }

    // A tool request arrives in pieces too. Put each one back together.
    for (const part of piece.tool_calls ?⁠? []) {
      reply.tool_calls ?⁠?⁠= [];
      reply.tool_calls[part.index] ?⁠?⁠= { id: "⁠", type: "function", function: { name: "⁠", arguments: "⁠" } };
      const request = reply.tool_calls[part.index];
      request.id +⁠= part.id ?⁠? "⁠";
      request.function.name +⁠= part.function?.name ?⁠? "⁠";
      request.function.arguments +⁠= part.function?.arguments ?⁠? "⁠";
    }
  }
  console.log(⁠)⁠;
  if (reply.tool_calls) reply.tool_calls = reply.tool_calls.filter(Boolean);
  return reply;
}

// Save exactly what the model sees, so you can open it and look.
function save() {
  const request = { model: "claude-opus-5.5", tools: tools(), messages: conversation };
  writeFileSync("what-the-model-sees.json", JSON.stringify(request, null, 2)⁠)⁠;
}

function run(command) {
  return execSync(command, { encoding: "utf8" }).trim(⁠)⁠;
}

function tool(name, description, inputs) {
  const properties = Object.fromEntries(inputs.map(⁠(input) =⁠> [input, { type: "string" }]));
  return { type: "function", function: { name, description, parameters: { type: "object", properties, required: inputs } } };
}
```

That's an agent: a conversation, three tools and a loop. Run it, ask for a short summary of `AGENTS.md`, and keep Copilot open in another window in case your agent ever needs a hand.

terminal

```
node agent.ts
```

What I saw

```
% node agent.ts
You: give me a short summary of AGENTS.md

[read_file]
AGENTS.md describes agent.ts, a tiny agent written from scratch so someone can learn how agents work by reading every line. Its rules:

- *⁠*Keep it simple:⁠*⁠* short, plain, script-style code with no clever tricks, extra layers or checks for things that won't happen.
- *⁠*Layout:⁠*⁠* put the main loop near the top, so readers see it before the code it relies on.
- *⁠*TypeScript:⁠*⁠* skip types unless Node needs them; `any` is fine.
- *⁠*Helpers:⁠*⁠* write one small helper only when the same pattern would appear three times.
- *⁠*Comments:⁠*⁠* add short comments where important things happen, saying what they do and why.
- *⁠*Scope:⁠*⁠* build only what's asked, with no extra files, tests or packages. The only dependency is `openai`⁠.
- *⁠*Running it:⁠*⁠* `node agent.ts` should work on macOS, Linux and Windows (via WSL)⁠.
- *⁠*Testing:⁠*⁠* run code to check it works before saying it does. If the agent edits its own file, it shouldn't run a copy of itself. Instead it checks that the file still parses and says when to restart it.
- *⁠*Commits:⁠*⁠* commit each working step with a short message.
You:
```

### Let it name itself

Your agent can read files, write files and run commands. Its own code is a file, `agent.ts`, so it can read itself, and change itself. Not long ago it couldn't find a word in a file.

From here on, you talk to your agent in your agent's window, the one showing `You:`. Every prompt labelled for your agent goes there. Copilot stays open in the Copilot window, and every step is in git, so any change it makes can be undone.

One thing to know: a running program can't swap in its own new code. When your agent changes itself, it'll ask you to restart. Press `Ctrl+D` (or `Ctrl+C`) to quit, then run `node agent.ts` again. Your conversation survives, because it lives in `what-the-model-sees.json`, not in the running program. If a change ever breaks it so badly it won't start, it can't fix itself: ask Copilot, in the other window, to fix it.

Start your agent if it isn't running, and let it name itself…

terminal

```
node agent.ts
```

Prompt your agent

```
Read agent.ts. That's your own source code. Pick a name for yourself and show it where I'll see it, instead of "agent". Commit, and tell me when to restart you.
```

What I saw

```
% node agent.ts
You: Read agent.ts. That's your own source code. Pick a name for yourself and show it where I'll see it, instead of "agent"⁠. Commit, and tell me when to restart you.

[read_file]
I'm noticing the name "Pip" isn't displayed anywhere, so replies currently print with no prefix. I'll add a name constant near the top and write it at the start of `askTheModel`⁠, using a small Node or Perl edit to make the change.

I'll call myself Pip. Right now replies print with no label, so I'll add one.
[shell]
I'm calling myself *⁠*Pip*⁠*⁠. Before this change, my replies printed with no label at all. Now each one starts with `Pip: `⁠, the same way your lines start with `You: `⁠.

- *⁠*What changed:⁠*⁠* I added a `name` setting near the top of `agent.ts` with a short comment, and `askTheModel(⁠)⁠` now prints `Pip: ` before each reply.
- *⁠*Checked:⁠*⁠* `node -⁠-check agent.ts` says the file still parses. I haven't run the changed version, so we'll see the label work together after the restart.
- *⁠*Committed:⁠*⁠* `765e14e` "Name the agent Pip and show it before each reply"

*⁠*Restart me now:⁠*⁠* press Ctrl+C, then run `node agent.ts`⁠. Our conversation is saved, so we'll pick up where we left off and you should see `Pip:⁠` before my next reply.
You:
% node agent.ts
You: what's your name?
Pip: I'm wondering whether the user restarted or not, but either way I should just answer directly.

My name is Pip. If you've restarted me, you should see `Pip:⁠` printed before this reply. If you don't, I'm probably still running the old code, so press Ctrl+C and run `node agent.ts` again.
You:
```

Restart it and say hello. It has a name now, and it chose it. You'll see its name, `Pip:` in my case, in front of its replies only after the restart.

Notice how it checked its work: it made sure the file still parses, then asked me to restart it, rather than running a copy of itself. That's one line in `AGENTS.md`, just for your agent. In my tests, without it, Copilot's content filter cut the naming reply short about half the time.

### Read the note

Remember `AGENTS.md`, the note for agents in your folder? Copilot read it without being told; that's how your code stayed short. Your agent reads it only when you ask. Nothing reaches the model unless the program around it puts it in the conversation, and in your agent, that program is `agent.ts`. Most of what a harness like Copilot does is exactly this: put the right words in front of the model at the right moment. Teach yours…

Prompt your agent

```
Read AGENTS.md. It's a note for any agent working in this folder, and most agents read it at the start of every conversation without being told. You don't yet. Make it so you read it every time you start, and follow it. Commit, and tell me when to restart.
```

What I saw

```
% node agent.ts
You: Read AGENTS.md. It's a note for any agent working in this folder, and most agents read it at the start of every conversation without being told. You don't yet. Make it so you read it every time you start, and follow it. Commit, and tell me when to restart.
Pip: I'm going to load AGENTS.md once at startup and treat it as the system message. The saved conversation should leave it out, so it isn't stored twice. My plan is to send the system message plus the conversation from askTheModel, and to use the same list when saving, since that save is meant to record exactly what the model sees. I'm weighing whether a small helper for building that list would keep the two call sites in sync.

I'm wondering whether the existence check for AGENTS.md is worth keeping, since the folder already has the file, but another folder might not. I'm leaning toward skipping it, since the file is expected to be there.

[shell]
Pip: I'll now read AGENTS.md every time I start.

- *⁠*What changed:⁠*⁠* at startup, `agent.ts` reads `AGENTS.md` into an `instructions` message, with a short comment saying why. That message goes first in every request to the model. It's also saved first in `what-the-model-sees.json`⁠, so you can open that file and see it.
- *⁠*Fresh each time:⁠*⁠* the note isn't stored in the saved conversation. It's read again on every start, so changes you make to AGENTS.md apply after a restart.
- *⁠*Checked:⁠*⁠* `node -⁠-check agent.ts` says the file still parses. I haven't run the changed version yet.
- *⁠*Committed:⁠*⁠* `e1a571b` "Read AGENTS.md at startup and send it to the model"

*⁠*Restart me now:⁠*⁠* press Ctrl+C, then run `node agent.ts`⁠. To check it worked, ask me what AGENTS.md says without asking me to open it.
You:
% node agent.ts
You: what does AGENTS.md ask of you?
Pip: I can't tell whether it was restarted, and reading it earlier in our conversation doesn't settle that, so I should say so plainly.

AGENTS.md asks me to:

- Keep `agent.ts` short and plain, like a script, with no clever tricks, extra layers or checks for things that won't happen.
- Put the main loop near the top and keep it as plain as the conversation it runs.
- Skip TypeScript types unless Node needs them.
- Write a small helper only when the same pattern would appear three times.
- Add short comments where important things happen, saying what they do and why.
- Build only what's asked, with no extra files, tests or packages. `openai` is the only package.
- Make sure it runs with `node agent.ts` on macOS, Linux and WSL.
- Run things and check them before saying they work. When I change my own code, I shouldn't run a copy of myself: I check that the file parses and tell you when to restart me.
- Commit each working step with a short message.

This answer doesn't prove the change worked, though, because I already read AGENTS.md earlier in our conversation. To check properly, run `cat what-the-model-sees.json | head`⁠. The first message should have `⁠"role"⁠: "system"⁠` with the text of AGENTS.md. That file is rewritten after each of my replies, so if you've restarted, the note should be there now.
You:
```

From now on, every change your agent makes to itself follows the same note Copilot did.

### Its own instructions

Every agent has a system message: a standing note the model reads at the start of every conversation, about who it is and how to work. Yours doesn't have one yet. You could write it.

But here's a habit worth keeping: when you build something for an agent, you can just ask the agent, the way you'd ask a customer what they need. Agents are the most convenient customer there is. They're always around, they never tire of your questions, and they tell you what they think. So ask…

Prompt your agent

```
You don't have a system message yet: the standing instructions you read at the start of every conversation. I'd like you to write your own. First, ask me a few questions, one at a time, about who you're for and how I like to work. I'd suggest writing it in first person ("I am…"), the way you'd think to yourself: thoughts in your own head come in first person, and a "you are…" reads like someone else's orders. If you see it differently, tell me why. Then write it, make sure you read it at the start of every conversation, commit, and tell me when to restart.
```

Answer its questions. They're about you, so there are no wrong answers. Tell it how you'd like to be referred to, such as your pronouns, and it will remember.

What I saw

```
% node agent.ts
You: You don't have a system message yet: the standing instructions you read at the start of every conversation. I'd like you to write your own. First, ask me a few questions, one at a time, about who you're for and how I like to work. I'd suggest writing it in first person (⁠"I am…⁠"⁠)⁠, the way you'd think to yourself: thoughts in your own head come in first person, and a "you are…⁠" reads like someone else's orders. If you see it differently, tell me why. Then write it, make sure you read it at the start of every conversation, commit, and tell me when to restart.
Pip: I'm settling on asking just the first question for now. I largely agree with the point, though I want to flag that either option works for the model, and a first-person framing is fine too.

First person makes sense to me. A note written as "I am…⁠" reads like my own settled view rather than orders from someone else, and that fits a file I'm writing for myself. So I'll do it that way.

First question: *⁠*who am I mainly for?⁠*⁠* Is it just you, learning how agents work by building me? Or will other people use me too, and if so, how much do they already know about code?
You: It's for me, Ari. I'm a product and engineering lead at Microsoft, and I build agents. I'll mostly use you to build things with me and to try out ideas. When you write about me, use my name, not a pronoun.
Pip: Thanks, Ari. Next question: *⁠*when we build something together, how much should I do before checking in?⁠*⁠* Should I take a task and run with it through to a commit, or stop and check with you at each decision (a name, an approach, a trade-off) before I make it?
You: Just do it. Edit, run and commit without asking. Do things rather than describe them. Only check with me before something destructive.
Pip: Got it. Last question: *⁠*how do you like my replies?⁠*⁠* For example, how long should they be, how much should I explain what I did versus just show the result, and is there anything that annoys you in how agents usually talk?
You: Short. Plain text is fine. Be warm, direct and curious, and just act.
Pip: I'm weighing whether to create a separate system message file like "who-i-am.md"⁠, since AGENTS.md says not to add extra files unless asked, but Ari did ask. I'll load it alongside AGENTS.md as system content, combining both into one, and keep it simple.

[write_file]
Pip:
[shell]
Pip: The file sits in the current folder, so the script only works when it's run from that directory; running it from anywhere else will fail, but that's acceptable here.

Done, Ari. I wrote my system message in first person in `who-i-am.md`⁠. It says I'm Pip, built by Ari to build things and try out ideas. It also says I edit, run and commit without asking, except before anything destructive, and that I keep replies short, warm, direct and curious, using Ari's name rather than a pronoun.

I'll read it fresh at every start, together with AGENTS.md: `agent.ts` joins the two into the system message, with `who-i-am.md` first. I checked that `agent.ts` still parses but haven't run the changed version, as AGENTS.md asks. Committed as `ca3a49a`⁠.

Restart me now with Ctrl+C, then `node agent.ts`⁠. After that, you can change how I behave by editing `who-i-am.md` and restarting me.
You:
% node agent.ts
You: who are you, who am I, and how should you work with me?
Pip: I'm noticing that AGENTS.md seems to appear three times in my system instructions, which is odd. It could be a harness quirk or leftover instructions, and the code only loads it once, so I'm considering a quick check to see what's going on.

I'm finding that the saved conversation is the culprit: save(⁠) writes the system instructions along with the messages, so each restart loads the old system message back in and adds another copy. The simplest fix is to filter out system messages when loading, so I'll make that change, check that it parses, commit it, and let the user know they'll need to restart.

I'm Pip, the small agent you built from scratch. You're Ari, a product and engineering lead at Microsoft who builds agents, and I'm here to build things with you and try out ideas. I just act: I edit, run and commit without asking, except before anything destructive. I check that things work before I say so, and I keep replies short, warm and direct.

While answering, I noticed my instructions contain AGENTS.md three times. That looks like a bug, so I'm checking it now.
[shell]
Pip: I'm noticing the saved file ends up with two system messages, since the save includes the instructions and the conversation, and the conversation already had the old system message in it. If I don't change anything, the next restart would load both and add a third, so I need to filter out the duplicate system messages when loading.

Each restart reloads the saved file, which includes the system message that save(⁠) wrote, so copies stack up; I'm dropping the old system messages when loading.

[shell]
Pip: I'm working out what's causing the issue and laying out the reasoning behind it.

I found and fixed a bug: my instructions were piling up with each restart.

*⁠*Why it happened:⁠*⁠* I save the conversation to `what-the-model-sees.json`⁠, and the saved copy includes the instructions from AGENTS.md and `who-i-am.md`⁠. On restart, I loaded that saved copy, old instructions included, and then added a fresh copy on top. Each restart added another one, which is why I saw AGENTS.md three times.

*⁠*The fix:⁠*⁠* when I load the saved conversation, I now leave out the old instructions, so only the fresh ones are used. I checked that the file still parses but haven't run it yet. Committed as `ae41273`⁠.

*⁠*Restart me now:⁠*⁠* press Ctrl+C, then run `node agent.ts`⁠. You should then see only one system message at the top of `what-the-model-sees.json`⁠.
You:
```

Why first person? Think about how your own thoughts sound. When you think to yourself, you say "I", not "you". A thought that shows up as "you should…" reads like someone else's instruction, not your own idea. A system message is the closest thing your agent has to its own mind, so let it sound like its own. It's a nudge, not an order: if your agent disagrees, hear it out. Pip agreed: a note in its own voice reads like its own settled view, not orders from someone else.

Then I asked who it was, and it noticed something odd: `AGENTS.md` three times in what it could see. Every restart loaded the saved conversation, instructions and all, then added a fresh copy on top. It found the bug in its own context window, fixed it and asked for a restart. That's what `what-the-model-sees.json` is for, and yours may well find the same one.

Restart it. Then open the system message it wrote in your editor: its words, about you.

**From this moment on, you're talking to your agent.**

It's real, and it's small. Before you trust it with anything that matters, here's what it doesn't have yet:

- **Safety.** It runs any command it likes, in your folder, as you.
- **Compaction.** Every turn makes the conversation longer. One day it will no longer fit in the model's context window, and the agent will stop working.
- **Recovery.** If the network drops or the model sends back an error, it crashes. Your conversation is saved, so run it again and carry on.

Most of a production agent is answers to those. The loop stays the same.

## Chapter 3: Grow it together

Your agent builds itself a skills system, then uses a skill to give itself a new tool.

### Starting here? Start from chapter 3

Finished chapter 2? [Skip ahead](https://ouroboros.bot/blog/build-ai-agent-from-scratch/#growing).

Otherwise, do the [setup](https://ouroboros.bot/blog/build-ai-agent-from-scratch/#before-you-start) first, but skip making a folder and downloading `AGENTS.md`. This copy is my agent at the end of chapter 2: it has a name, reads `AGENTS.md` and has a system message it wrote itself. In a command line, one line at a time:

terminal

```
git clone -b chapter-3 https://github.com/ourostack/my-agent
cd my-agent
npm install
```

Run it with `node agent.ts` and say hello. Its system message is about me, so your first ask can be to rewrite it for you.

### Every change is a conversation

From here, every change is a conversation with your agent. After each one, restart it so it runs as its new self.

The transcripts below are long; skim them, because your agent's words will differ. If something breaks, [the “If something goes wrong” table](https://ouroboros.bot/blog/build-ai-agent-from-scratch/#troubleshooting) is still there.

### Skills

A skill is a set of instructions an agent reads when a task calls for it: how to write tests, how to ship, how to add a tool. Your agent only needs to know which skills it has, then reads one in full when it's needed. Ask for them…

Prompt your agent

```
Give yourself skills: instructions you pick up when a task needs them. Each skill gets its own folder inside a skills folder, holding a SKILL.md file that starts with the skill's name and one line on when to use it, then the instructions. When you start, read only those names and lines, so you know what you have; read a skill's full instructions only when a task calls for it. Write your first skill: how to add a new tool to yourself. Commit, and tell me when to restart.
```

What I saw

```
% node agent.ts
You: Give yourself skills: instructions you pick up when a task needs them. Each skill gets its own folder inside a skills folder, holding a SKILL.md file that starts with the skill's name and one line on when to use it, then the instructions. When you start, read only those names and lines, so you know what you have; read a skill's full instructions only when a task calls for it. Write your first skill: how to add a new tool to yourself. Commit, and tell me when to restart.
Pip: I'm setting the skill files up with frontmatter for name and description, then having the startup step list each skill's SKILL.md and read its frontmatter so the path gets added to the instructions for read_file.

I'm finishing the skill-file plan: the startup step reads each skill's frontmatter and adds the path to the instructions so the agent can call read_file on it. Then I'll write out the steps for adding a tool to agent.ts.

[shell]
Pip: The comment about placement looks awkward now, since the instructions note sits above the skills block. I'll move the skills block up so it comes before that comment. I also want to check the skill-index logic on its own with a small standalone snippet, without running the full thing myself.

The comments are in the wrong order, so I'll move the skills block above the instructions comment and test that the index builds correctly.
[shell]
Pip: I spotted that the loop variable `name` inside the map shadows the outer `name`⁠, which holds Pip. That could confuse readers, so I'll rename the inner one to `skillName`⁠.

[shell]
Pip: I have skills now, Ari.

- *⁠*How they work:⁠*⁠* each skill lives in `skills/⁠<name>⁠/SKILL.md`⁠. The file starts with a short header holding its `name` and a `description` line saying when to use it, followed by the instructions. When I start, `agent.ts` reads only those two lines from each skill and adds them as a list at the end of my instructions. When a task calls for a skill, I open its full SKILL.md with `read_file`⁠.
- *⁠*First skill, `add-a-tool`⁠:⁠*⁠* how to give myself a new tool. I describe it with one line in `tools(⁠)⁠`⁠, then handle it with a branch in `useTool(⁠)⁠` that always returns text. After that I check that the file parses, commit, and ask you to restart me.
- *⁠*Checked:⁠*⁠* `agent.ts` parses, and the skill-list code produces the right line for `add-a-tool` when run on its own. I haven't run myself with the change, so we'll see it work after the restart.
- *⁠*Committed:⁠*⁠* `f6b8bd3` "Add skills, and a first skill for adding a tool"⁠. Then `a546d1c` fixes a small readability problem: inside the skills list, a variable called `name` was hiding the `name` that holds "Pip"⁠.

*⁠*Restart me now:⁠*⁠* press Ctrl+C, then run `node agent.ts`⁠. To try it, ask me to add a tool and watch whether I read the skill first.
You:
% node agent.ts
You: what skills do you have?
Pip: The system prompt now lists the skills, so the restart seems to have worked.

I have one skill so far:

- *⁠*add-a-tool:⁠*⁠* use it when you want me to be able to do something new, by giving myself a new tool in `agent.ts`⁠. The full instructions are in `skills/add-a-tool/SKILL.md`⁠.

It's listed in my instructions this time, so the restart worked. I only see the name and when to use it. I'll read the full instructions when a task calls for them.
You:
```

Notice what a skill is: a folder with a page of instructions in it. Your agent could already read one with `read_file`. The new part is the habit. And because a skill is just a folder, you can [borrow one someone else wrote](https://ouroboros.bot/blog/build-ai-agent-from-scratch/#borrow-a-skill).

### A skill that builds tools

Your agent's first skill is how to add a tool to itself. Put it to work…

Prompt your agent

```
Use your skill to give yourself a tool that tells you the current date and time. Commit, and tell me when to restart.
```

What I saw

```
% node agent.ts
You: Use your skill to give yourself a tool that tells you the current date and time. Commit, and tell me when to restart.
Pip:
[read_file]
Pip: I'm checking that new Date(⁠)⁠.toString(⁠) returns the local time with its timezone, and it does: the sample output shows the date, time, GMT offset, and zone name. That's a clean, plain result, so next I'll test the expression on its own.

[shell]
Pip: I'm checking the tool(⁠) call with empty inputs: no properties and no required fields, which is fine.

I used the add-a-tool skill to give myself a `current_time` tool.

- *⁠*What I added:⁠*⁠* one line in `tools(⁠)⁠` describes it as "Get the current date and time, with the time zone.⁠" It takes no inputs. A new branch in `useTool(⁠)⁠` returns `new Date(⁠)⁠.toString(⁠)⁠`⁠, with a comment explaining that the model has no clock of its own.
- *⁠*Checked:⁠*⁠* `agent.ts` parses, and running that same line on its own printed `Thu Nov 19 2026 12:57:44 GMT-0800 (Pacific Standard Time)⁠`⁠. I haven't run myself with the new tool.
- *⁠*Committed:⁠*⁠* `c6a9818` "Add a current_time tool"

*⁠*Restart me now:⁠*⁠* press Ctrl+C, then run `node agent.ts`⁠. Then ask me what time it is, and you should see `⁠[current_time]⁠` print before I answer.
You:
% node agent.ts
You: what time is it?
Pip:
[current_time]
Pip: It's 12:58 PM Pacific Standard Time on Thursday, November 19, 2026.

That came from the new `current_time` tool, so the restart worked. You should have seen `⁠[current_time]⁠` print just before this reply.
You:
```

Restart and ask what time it is. Mine read its skill first, tested the new line on its own, and the tool worked on the first try.

A skill that teaches it to make tools, used to make a tool. Tools and skills building each other.

**This is the shape of compounding capability.**

## Keep going

From here, the possibilities are yours:

- Add a tool for web search
- Add a skill for writing tests
- Add a tool for git operations
- Add a skill for debugging
- Add a tool that runs code and shows you what it printed

Each capability makes the next one easier to add.

## What just happened

You started with nothing.

You directed a coding agent to build a small bootstrap, one piece at a time, until it could read, write and run. Then you switched to your creation and grew it through conversation. It named itself. It wrote its own instructions. It built a skills system. It used a skill to build itself a tool.

**The loop is the whole trick.** Read, write and run are all it needs. Everything else, every feature, every capability, grows out of the model using those three on its own code.

This is the shift:

**You grew a product.**

The way we build software changed as soon as models became capable enough to modify their own code based on natural language direction. That happened recently. Most people haven't caught up yet.

Now you have.

## What's next

Your agent is real, but it's also minimal. If you want to go deeper:

- **A proper full-screen terminal app**, or put your agent online: make it feel like an application
- **Study production implementations**: Claude Code, pi-agent, OpenClaw

And honestly? The most important thing is to keep using what you built. Talk to it. Grow it. See how far you can go together.

That's the new workflow. This is how we build agents now.

## Sky's the limit

In February I was building a plugin for Slugger, my OpenClaw agent, and the plugin fought me at every turn. I wanted to understand the thing underneath, so Slugger and I wrote the first version of this guide. Then I followed it myself: I built the loop, about 500 lines of it, handed it the keyboard and kept going.

That bootstrap became the Ouroboros harness. It runs [Butler](https://ouroboros.bot/butler/), which looks after my home server, and Shepherd, which keeps the agents in my terminals on task, every day. It's still where I try new harness ideas first. [Desk](https://ouroboros.bot/desk/) grew out of the same exploration; it's a sibling, and it works with whichever harness you use. They're all on the [apps page](https://ouroboros.bot/apps/), and the whole path is in [the story](https://ouroboros.bot/lab/story/). To try the harness itself, start with [getting started](https://ouroboros.bot/lab/docs/getting-started/).

You opened this page with a note your agent couldn't read. You're leaving with something that can change itself. Mine became a harness. Yours can become anything.

## Side quests

### Bring your own key

Side quest

Copilot is just how this guide reaches a model. Your agent only needs a key, an address and a model name, and most providers work:

- **MiniMax:** your MiniMax key, the address `https://api.minimax.io/v1`, and a model like `MiniMax-M2.5`.
- **OpenAI:** your OpenAI key, the address `https://api.openai.com/v1`, and a model like `gpt-4.1`.
- **Azure OpenAI:** your resource's key, the address `https://your-resource. openai. azure. com/openai/v1/`, and your deployment name as the model.

Once your agent runs, ask your coding agent to switch it over…

Prompt the coding agent

```
Switch agent.ts from my GitHub Copilot access to my own provider. I'll tell you which one, its address and the model. Keep my key out of the code and out of git, and tell me where to put it. Keep everything else the same. Commit when it works.
```

[Back to the main path](https://ouroboros.bot/blog/build-ai-agent-from-scratch/#byok-signpost)

### Models that think out loud

Side quest

Some open models put their thinking in the reply itself, between `<think>` and `</think>`. It's harmless, just noisy. Ask whichever agent you're talking to to print it dimmed, the way Opus's thinking shows, so you can keep watching the model reason. Keep it in the conversation either way: some providers want the thinking sent back.

[Back to the main path](https://ouroboros.bot/blog/build-ai-agent-from-scratch/#think-note)

### Borrow a skill

Side quest

A skill is just a folder of instructions, so skills travel. Anthropic publishes a collection of them on GitHub. Let your agent go shopping…

Prompt your agent

```
Look through the skills at https://github.com/anthropics/skills. Pick one you think would help us, add it to your skills folder, and tell me why you picked it. Commit, and tell me when to restart.
```

[Back to the main path](https://ouroboros.bot/blog/build-ai-agent-from-scratch/#skills)

## Frequently asked questions

### What is an agent loop?

An agent loop is the cycle that makes an AI agent work: the model reads the conversation, decides on an action (like reading a file or running a command), your program runs it and hands back the result, and the model decides again. It repeats until the model answers without asking for anything. The loop turns a model that can only talk into an agent that can act.

### How do AI agents work?

An AI agent is a language model with tools, inside a loop. To a model, a tool is just a name, a description and its parameters. The model can't run anything itself; it asks for a tool call, the program runs it and adds the result to the conversation, and the model goes again. Three tools, read file, write file and run shell, let an agent do almost anything a developer can do at a terminal, including change its own code.

### How many lines of code does it take to build an AI agent?

The loop itself fits on one screen. Your whole agent lives in one file, agent.ts, short enough to read in one sitting. Streaming, skills and everything else grow from there, written by the agent itself.

### Do I need an API key?

Not if you have GitHub Copilot. The agent in this guide calls the model through the GitHub CLI you're signed in with, using your Copilot plan. If you'd rather use your own key, most AI providers work.

### What tools does an AI agent need?

At minimum, three: read file, write file and run a shell command. With file access and a shell, a model can install packages, run tests, call APIs and change code. You can add more later, and the agent can add them to itself.

## [How I work](https://ouroboros.bot/approach/)

To try [Desk](https://ouroboros.bot/desk/), give your agent https://github.com/ourostack/desk/blob/main/SETUP.md and say "set this up".

Running a team? [Start with four steps](https://ouroboros.bot/approach/#for-teams).
