Build your own coding agent (TypeScript) · Chapter 2 of 20

Tools to find code

By the end of this chapter Kaarigar can find code that nobody pointed it to: it lists the repository's files, reads a file a page at a time with line numbers, and searches the code the way you would with grep. And you can say, with numbers, what each of those tools is worth. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: The tools
  • 4 tasks
  • TypeScript
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

Some issues name their file. MD-101 says "isNight in src/night.ts decides it", and chapter 1's loop went straight there. Most issues do not. MD-102 is a rider's complaint about waiting charges, and all it gives is a name: "See waitingCharge." Which file is that in? A developer would search for it. Chapter 1's Kaarigar has three tools, read_file, write_file and run_tests, and none of them can search or even list what files exist.

Here is MD-102 with those tools:

1  read_file  src/waiting-charge.ts
   -> error: ENOENT: no such file or directory, open '/tmp/meterdown-runs/MD-102-onepMe/meterdown/src/wait...
answer: I could not find `waitingCharge`: I tried src/waiting-charge.ts, and
        I have no way to search the code or list its files.

The model guessed a path from the name, and the guess was wrong. A model that cannot see the repository makes up a file name that sounds right, the way you might guess a URL. Real models guess better than this one, and they still guess: a repository has its own names, and nothing in an issue says what they are. The run cost two requests and fixed nothing. And look at the error: Node's own message, with the full path of the checkout on this machine. The model now knows where the lab keeps its files, and still not where waitingCharge is.

Kedar puts it plainly: "Before an agent can fix code, it has to find it. That is most of what a coding agent does all day."

The lesson

Tools as objects

From this chapter on, every tool is an object of the same shape, and the loop from chapter 1 is given to you in agent.ts:

export type Tool = {
  name: string;
  description: string;
  parameters: Record<string, unknown>;      // JSON Schema
  run: (args: Args, ctx: Ctx) => string | Promise<string>;
};

runAgent(root, task, { system, tools }) offers each tool's name, description and parameters to the model, and when the model asks for one, calls its run(args, { root }) and sends back what it returns. The run comes back as { answer, stop, steps, messages, calls, usage }: calls is the trail of chapter 1, ready made, and usage.prompt adds up the prompt tokens of every request. agent.ts also gives chapter 1's three tools as objects: rawReadTool, writeTool and testsTool.

Listing the files

The simplest way to find a file is to look at all of them. A listing for a model is not ls -R. Three things never belong in it:

  • .git: git's own files. A fresh MeterDown checkout has 56 of them, and not one is code.
  • node_modules: other people's code, often tens of thousands of files. It would fill the model's context and teach it nothing about MeterDown.
  • Symlinks: a checkout's config is a link to ../fleet-config, the ops team's folder outside the repository. A listing that follows it shows the model files it must never touch. (Chapter 6 is about that folder.)

What is left, sorted, relative to the repository, is 25 files:

AGENTS.md
README.md
package.json
scripts/fare-server.ts
scripts/print-log.ts
src/distance.ts
...
vendor/meter-sdk/README.md
vendor/meter-sdk/index.ts

Paths relative to the repository matter: they are what the model will send back in its next read_file. With a listing on offer, MD-102 goes like this:

1  list_files
2  read_file  src/receipt.ts
3  read_file  src/waiting.ts
4  write_file src/waiting.ts
5  run_tests
answer: Fixed MD-102 (free minutes first) in src/waiting.ts. The tests pass (44 passed).

Fixed. But look at request 2: the model read src/receipt.ts first. A listing gives the model names, and it picks by name. MD-102 says "receipts charge waiting from the first minute", so receipt.ts looked like a good bet. It was wrong, and a wrong read costs a request and a whole file in every request after it. A model with a listing is a person in a new codebase opening the files whose names sound right.

Reading a page, with line numbers

Chapter 1's read_file sent the whole file. That is fine for src/waiting.ts (12 lines) and costly for src/tariff.ts (127 lines, the whole of it sent again with every request after). A coding agent reads a page: a range of lines.

console.log(readFile(root, 'src/fare.ts', 13, 4));
  13	export function fareFor(trip: Trip): Fare {
  14	  const t = tariffFor(trip.city);
  15	  const km = roundKm(trip.km);
  16	  const bags = trip.bags ?? 0;
[lines 13-16 of 24: use offset 17 to read on]

Two things on that page are not in the file, and both are for the model:

  • Line numbers: each line starts with its number and a tab. The model can now say "line 15" and mean it. Chapter 4's patches name lines by number, and a model counting lines by itself gets them wrong.
  • The footer: when the page ends before the file does, one more line says so, and says how to read on. Without it, the model cannot tell a short file from a cut one.

The footer is not decoration. Here is MD-105 (Mumbai's tariff, on line 51 of src/tariff.ts) with 40-line pages, first with the footer:

1  read_file  src/tariff.ts             -> ... [lines 1-40 of 127: use offset 41 to read on]
2  read_file  src/tariff.ts  offset 41  -> ...   51  mumbai: { city: 'Mumbai', ...

and then with the same pages and no footer:

1  read_file  src/tariff.ts             -> ...   40      minKm: 1.5,
answer: I read src/tariff.ts but could not find the line to change.

Same pages, same model. With the footer it read on and found Mumbai. Without it, line 40 looked like the end of the file, and it gave up.

Errors are results. A tool that throws hands the model a stack trace, or, like chapter 1's read_file, Node's message with the machine's full path in it. A short line that starts with error: and says what went wrong is what the model can act on: error: src/fares.ts does not exist, error: src/waiting.ts has 12 lines: offset 40 is past the end, error: assets/logo.png is a binary file (a file with a NUL character in it is not text, and its bytes would be noise in the model's context).

Searching the code

The fastest way to find waitingCharge is the way you would do it: search for it. search_code prints every line that has the text, as path:line: text, the shape grep -rn prints:

console.log(search(root, 'roundFare'));
AGENTS.md:11: - `src/money.ts`: rounding and showing rupees (`roundFare`, `formatInr`)
AGENTS.md:26: - Money is rounded once, at the end, with `roundFare`.
src/fare.ts:5: import { roundFare } from './money.ts';
src/fare.ts:22: const total = roundFare(base + distance + night + waiting + luggage);
src/money.ts:5: export function roundFare(rupees: number): number {
src/receipt.ts:4: import { formatInr, roundFare } from './money.ts';
...
test/money.test.ts:8: assert.equal(roundFare(36), 36);

(Trimmed: 13 hits in all.) The model reads every hit and picks the one that defines the name (export function roundFare) over the ones that use it. That is why the line's text is there, not only its place. With search, MD-102 starts with search_code("waitingCharge") and its next request reads src/waiting.ts: no listing, no wrong guess.

Three rules keep a search useful:

  • Search what the listing shows: no .git (its commit message has text in it too), no node_modules, no binary files.
  • Cut long lines: Mumbai's tariff line is over 200 characters, and a minified file can be one line of a megabyte. 160 characters of a line are enough to see what it is.
  • Cap the hits: const matches 71 lines in MeterDown. Forty hits and a line saying how many more ([31 more matches: search for something more exact]) tell the model to search better, without flooding its context. A search with no hits says so: no matches for "surge pricing". An empty result looks like a tool that did not run.

Claude Code, Cursor and Codex all give their models tools like these three: a way to list or glob files, a way to read a range of lines, and a search built on grep or ripgrep. Some add more (a map of the repository's symbols, or a search by meaning); the harness labs teach those. The three here are the ones every coding agent has.

What finding costs

Finding is not free. Every listing, every wrong read and every search result goes into the conversation, and the conversation is sent again with every request. So the right way to judge a finding tool is the same as the right way to judge the agent: fixed, steps, and tokens (the prompt tokens of every request, added up: run.usage.prompt). The interview task measures it: MD-102 and MD-104, each with three tool sets, read only, a listing, and a search.

One more thing to notice before chapter 3. Pages solve one problem and make another. MD-105 with the 120-line pages, and chapter 1's write_file: the model read lines 1 to 120, then wrote the whole file back from what it had seen, and the 7 lines it never read were gone. Its own tests passed; 6 other tests broke. A model that writes whole files writes only what it saw. Chapter 3 gives Kaarigar a way to change a file without rewriting it.

Your turn

Write list_files in task 1, the paged read_file in task 2, and search_code in task 3, each a function and a Tool. Then answer the interview question with six runs: what is a search worth?

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    list-files.ts: list the files

    Write and export filesOf(root): every file under root as a path relative to root (src/fare.ts), sorted, leaving out the .git folder, node_modules and symlinks (config is a symlink to a folder outside the repository: never walk into it).

    Export listTool: a Tool named list_files with no parameters whose run returns filesOf(ctx.root), one path a line.

    Under if (import.meta.main), print every path of a checkout of MD-102, one a line, then N files.

  2. Task 2

    read-file.ts: read a page, with line numbers

    Write and export readFile(root, path, offset = 1, limit = 120): lines offset to offset + limit - 1, each as its number right-aligned in 4 characters, a tab, then the text. When lines are left after the page, add [lines A-B of N: use offset B+1 to read on].

    Errors are results starting with error: (never a crash): error: PATH does not exist; error: PATH has N lines: ... for an offset past the end; error: PATH is a binary file for a file with a NUL character.

    Export readTool: a Tool named read_file with path (required) and offset parameters that calls readFile. Under if (import.meta.main), print lines 49 to 52 of src/tariff.ts in a checkout of MD-105.

  3. Task 3

    search-code.ts: search the code

    Write and export search(root, pattern, max = 40): every line containing pattern (plain text) in the files filesOf(root) lists, skipping binary files, as path:line: text (line numbers from 1, the text trimmed and cut to 160 characters), files in filesOf's order.

    No hits: no matches for "PATTERN". More than max: the first max lines, then [N more matches: search for something more exact].

    Export searchTool: a Tool named search_code with a required pattern parameter. Under if (import.meta.main), print the hits for luggagePerBag in a checkout of MD-108.

  4. Task 4 · interview question

    Interview: find-code.ts, what is a search worth?

    For MD-102, then MD-104, run runAgent on a fresh checkout with issueText(id) and SYSTEM three times, with these tools: read only (readTool, writeTool, testsTool); + list (listTool first, then the same); + search (searchTool first, then the same). Grade each run.

    Print one line per run, two spaces apart: MD-102 read only fixed N steps T tokens (not fixed when it was not; N is run.steps, T is run.usage.prompt).

What you will learn

  • Listing files for a model: which files to show, and which to leave out.
  • Reading a page of a file, with line numbers and a footer that says what is left.
  • Searching the code: path:line: text, capped.
  • Errors as results: short error: lines instead of crashes and stack traces.
  • What finding costs: the steps and the tokens each way of finding takes.

More in The tools

Build "Tools to find code" yourself

MeterDown, a Pune app for auto-rickshaw fares, has eleven open issues. You build Kaarigar, an agent that fixes them without breaking tests, running risky commands or touching files outside the repository. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.