Build a Custom Agent Harness

Build a TypeScript agent harness with tools, approvals, and OpenRouter.

Introduction

30 Second Summary

Codex and Claude Code can feel like magic because one prompt can trigger a whole sequence of work. Underneath that experience, a CLI agent is just a program that sends messages, runs tools, and returns the results to a model.

In this project, you will build a small TypeScript CLI agent that exposes the path from a user message to local action.

What You'll Build

You'll run a coding task and watch the terminal reveal every model turn, tool result, approval, and verified file change.

By the end of this project, you'll have:

  • 🔁 Complete agent loop: Run a coding task through repeated model turns until the agent returns a final answer.
  • 🐾 Transparent message trail: Watch each user request, model response, tool call, and tool result appear in order.
  • 🔐 Approval-gated execution: Approve consequential tool calls before the agent edits and verifies files inside a protected workspace directory.
  • 💎 Secret Mission: Add a persistent session store that recalls information after the TUI restarts.

Are there any prerequisites?

You should be comfortable reading TypeScript. Have these tools ready before you start:

  • Git installed for cloning the starter project.
  • Node.js installed for running the TypeScript CLI.
  • A code editor for working with the project files.

Is this project right for me?

Before We Start

This first checkpoint defines what you will be building. You are committing to creating an agent harness from scratch.

Set Up the Starter TUI

Your agent harness needs a way to interact with you. The starter project provides a terminal user interface (TUI) that gives you a test surface without turning interface design into the project.

In this step, get ready to:
  • Verify the supported Node.js runtime and Git installation.
  • Clone the starter repository and install its locked dependencies.
  • Configure local access and run the starter TUI with a controlled workspace.
Verify the supported tools

The starter project needs Node.js 18 or newer. Git has no project-specific minimum version, so any version output confirms it is ready.

  • Choose your operating system below to open a terminal and check Node.js plus Git.

macOS

  • Press Cmd+Space to open Spotlight.
  • Type Terminal.
  • Press Enter to open Terminal.
  • Check Node.js and Git by running these commands:
node --version
git --version
  • Does your output show Node.js 18 or newer followed by a Git version number?

Yes

Both tools are ready. Keep this Terminal window open for the project commands.

No

The repository supports Node.js 18 or newer. A fresh installation should use the current LTS release.

  • Open the official Node.js download page.
  • Select the macOS installer for Node.js 24.21.0 LTS.
  • Run the downloaded .pkg installer.
  • Close Terminal after the installer finishes.
  • Open a new Terminal window through Spotlight.
  • Repeat the version checks:
node --version
git --version

ⓧ A command is missing

Install only the tool whose version command was unavailable.

  • Open the official Node.js download page if node is missing.
  • Install the macOS package for Node.js 24.21.0 LTS.
  • Install Git through Xcode Command Line Tools by running this command if git is missing:
xcode-select --install
  • Complete the installation dialog.
  • Open a new Terminal window.
  • Repeat both checks:
node --version
git --version

Windows

  • Press the Windows key to open search.
  • Type PowerShell.
  • Press Enter to open PowerShell.
  • Check Node.js and Git by running these commands:
node --version
git --version
  • Does your output show Node.js 18 or newer followed by a Git version number?

Yes

Both tools are ready. Keep this PowerShell window open for the project commands.

No

The repository supports Node.js 18 or newer. A fresh installation should use the current LTS release.

  • Open the official Node.js download page.
  • Select the Windows installer for Node.js 24.21.0 LTS.
  • Run the downloaded .msi installer.
  • Close PowerShell after the installer finishes.
  • Open a new PowerShell window through Windows search.
  • Repeat the version checks:
node --version
git --version

ⓧ A command is missing

Install only the tool whose version command was unavailable.

  • Open the official Node.js download page if node is missing.
  • Install the Windows package for Node.js 24.21.0 LTS.
  • Open the official Git for Windows page if git is missing.
  • Run the Git for Windows installer with its default command-line options.
  • Close PowerShell after the installations finish.
  • Open a new PowerShell window.
  • Repeat both checks:
node --version
git --version

Linux

  • Open your desktop's application menu.
  • Search for Terminal.
  • Open Terminal from the search results.
  • Check Node.js and Git by running these commands:
node --version
git --version
  • Does your output show Node.js 18 or newer followed by a Git version number?

Yes

Both tools are ready. Keep this Terminal window open for the project commands.

No

The repository supports Node.js 18 or newer. A fresh installation should use the current LTS release.

  • Open the official Node.js download page.
  • Select Linux and Node.js 24.21.0 LTS.
  • Follow the installation method shown for your Linux distribution.
  • Close Terminal after the installation finishes.
  • Open a new Terminal window.
  • Repeat the version checks:
node --version
git --version

ⓧ A command is missing

Install only the tool whose version command was unavailable.

  • Open the official Node.js download page if node is missing.
  • Select Linux and install Node.js 24.21.0 LTS using the displayed method for your distribution.
  • Install Git on Debian or Ubuntu by running:
sudo apt-get install git
  • Install Git on Fedora by running:
sudo dnf install git
  • Use the official Git for Linux page to find the documented command for another distribution.
  • Open a new Terminal window after installation.
  • Repeat both checks:
node --version
git --version

Once both commands return supported versions, your terminal is ready for the starter repository.

Clone the starter project

The starter project already contains the terminal client. Keeping that client intact lets you spend the remaining steps on the harness types and runtime.

macOS

  • Move to your Desktop, clone the repository, and enter its folder by running these commands:
cd ~/Desktop
git clone https://github.com/nextwork-projects/custom-agent-harness.git
cd custom-agent-harness
  • You should see Git create custom-agent-harness on your Desktop. Terminal finishes inside that folder.

Windows

  • Move to your Desktop, clone the repository, and enter its folder by running these commands:
Set-Location "$HOME\Desktop"
git clone https://github.com/nextwork-projects/custom-agent-harness.git
Set-Location custom-agent-harness
  • You should see Git create custom-agent-harness on your Desktop. PowerShell finishes inside that folder.

Linux

  • Move to your Desktop, clone the repository, and enter its folder by running these commands:
cd ~/Desktop
git clone https://github.com/nextwork-projects/custom-agent-harness.git
cd custom-agent-harness
  • You should see Git create custom-agent-harness on your Desktop. Terminal finishes inside that folder.

The starter repository is now local. Your active terminal is inside the custom-agent-harness folder.

Repository did not clone?

Confirm your internet connection if the download fails. If a custom-agent-harness folder already exists on your Desktop, rename or remove it before repeating the commands.

If cloning still fails, help me diagnose the clone command.

  • Install the locked project dependencies by running this command:npm ci
npm ci

The first dependency installation can sit quietly while packages download. That pause is expected while npm reconstructs the versions recorded in the lockfile.

Why use npm ci?

The command installs dependencies from the committed lockfile. It keeps your local package versions aligned with the tested starter snapshot.

💡 What are locked project dependencies?

Locked project dependencies are the exact package versions recorded in package-lock.json. Installing those versions gives every learner the same tested environment and avoids surprises from newer package releases.

  • You should see the installation finish without a dependency error. The project now has its pinned TypeScript and terminal-client packages.

Dependency installation failed?

Confirm your terminal is inside the custom-agent-harness folder. The folder must contain package.json and package-lock.json.

If the install still fails, help me diagnose an npm ci failure in this starter repository.

Inspect the starter project

The project files work in any code editor or IDE. We'll open your favorite editor next.

Need help choosing or installing one? Help me set up an IDE.

macOS

  • Press Cmd+Space to open Spotlight.
  • Type the name of your preferred IDE.
  • Press Enter to open the IDE.
  • Choose the IDE option for opening an existing folder.
  • Select custom-agent-harness from your Desktop.
  • Open the folder to load the project.

Windows

  • Press the Windows key to open search.
  • Type the name of your preferred IDE.
  • Press Enter to open the IDE.
  • Choose the IDE option for opening an existing folder.
  • Select custom-agent-harness from your Desktop.
  • Open the folder to load the project.

Linux

  • Open your desktop's application menu.
  • Search for the name of your preferred IDE.
  • Open the IDE from the search results.
  • Choose the IDE option for opening an existing folder.
  • Select custom-agent-harness from your Desktop.
  • Open the folder to load the project.

The starter keeps the harness entry point separate from terminal presentation. src/index.ts defines response behavior, while src/tui/index.tsx manages terminal input, interface state, transcript display, and rendering.

  • Open src/index.ts from your IDE's project explorer.
  • Find the respond() function in the file.
  • Find the runTui(respond) call near the bottom.
  • Open src/tui/index.tsx from your IDE's project explorer.
  • Identify the input and transcript-rendering code inside the TUI file.

Why keep this boundary?

respond(message) is the replaceable backend boundary in src/index.ts. This boundary lets later steps replace the response behavior while the terminal client stays focused on collecting input and displaying results. Model calls, tool execution, event hooks, and approval hooks stay outside the interface layer.

💡 What are these functions doing?

runTui(respond) passes that function into the terminal client. Inside src/tui/index.tsx, runTui() renders App with the supplied response function.

App stores the current input, transcript entries, and pending-response state. Its submit() function validates the message, records it, awaits respond(), and appends the result or a fallback error.

Configure access and run the TUI

The later model adapter needs an OpenRouter API key. The key stays in a local environment file so source files never contain the credential.

Credentials deserve careful handling. You will keep this key inside the ignored .env file and avoid showing it in screenshots.

  • Create an OpenRouter account from the API authentication page if you do not have one.
  • Sign in to your OpenRouter account.
  • Create an API key
  • Copy the new API key without sharing it.
  • Switch back to your project terminal.
  • Create the local environment file using the command for your operating system:

macOS

  • Copy the supplied example to .env by running:
cp .env.example .env

Windows

  • Copy the supplied example to .env by running:
Copy-Item .env.example .env

Linux

  • Copy the supplied example to .env by running:
cp .env.example .env

What does this command create?

The command copies .env.example to a new local .env file. The starter's .gitignore already excludes that local file.

  • Open .env from your preferred IDE's project explorer.
  • Replace your_openrouter_api_key_here with the copied regular API key.
  • Save .env.

Your local .env now defines OPENROUTER_API_KEY with your regular OpenRouter API key. Keep that file uncommitted.

The starter repository already includes the workspace folder with two controlled files. These give the later tools safe, predictable targets.

  • Expand the workspace folder in your IDE's project explorer.
  • Open workspace/app.js.
  • Find the const status = 'hello agent'; line.
  • Open workspace/notes.txt.
  • Find the Search phrase: hello agent and Expected workflow: lines.

You should find hello agent in both files and an Expected workflow: line in notes.txt. Those known targets make later tool results easy to verify.

The development command starts the terminal client and keeps control of the terminal until you stop it. Before you run it, do you expect the current starter to perform agent work or simply pass your input through its existing response boundary?

  • Start the starter TUI from your project terminal by running this command:
npm run dev

What does this command start?

The development script launches the existing terminal client. It uses src/index.ts as the composition root and renders the interface from src/tui/index.tsx.

You should see the Agent Harness title and an input prompt. The terminal stays attached to the client while it is running.

  • Type setup at the TUI prompt.
  • Press Enter to submit the input.

You should see setup in the transcript followed by one response. That visible round trip proves the thin client can submit input and render a result.

  • Press Ctrl+C to exit the TUI after confirming the response.

TUI did not start?

Confirm your terminal is inside the custom-agent-harness folder. Check that the earlier dependency installation completed successfully.

If the interface still does not load, help me diagnose why npm run dev does not start the Agent Harness TUI.

Your starter client now runs against a controlled local workspace. Next, you will define the types and model adapter that turn this interface into a client for your own harness.

Define the Contracts and Model Adapter

Define the Types and Model Adapter

Your TUI is running locally. It can collect a task and display a response.

The harness now needs stable internal types before it can coordinate model calls. You will define those types in TypeScript before isolating the provider-specific transport inside an OpenRouter model adapter.

In this step, get ready to:
  • Define the harness types for messages, tools, hooks, context, and results.
  • Build a model adapter that sends harness messages to OpenRouter.
  • Use the existing TUI to exercise one model turn without workspace tools.
Define the harness types

A harness needs one vocabulary for every message and tool interaction. These types keep provider response shapes consistent and predictable.

  • Create src/types.ts inside the existing src folder using your preferred IDE's project explorer.

You should see types.ts listed beside index.ts in the src folder.

  • Add the message types to src/types.ts by pasting this code:
export interface ToolCall {
  id: string;
  type: 'function';
  function: {
    name: string;
    arguments: string;
  };
}

export interface AssistantMessage {
  role: 'assistant';
  content: string | null;
  tool_calls?: ToolCall[];
}

export type Message =
  | {role: 'system' | 'user'; content: string}
  | AssistantMessage
  | {role: 'tool'; tool_call_id: string; content: string};

What Do These Types Define?

  • ToolCall captures the identifier and function request returned by the model.
  • AssistantMessage supports ordinary text plus optional tool requests.
  • Message unifies system instructions, user input, assistant output, and correlated tool results.
  • Save src/types.ts.

Add the schema and hook types below the existing Message union by pasting this code:

export interface ObjectSchema {
  type: 'object';
  properties: Record<string, unknown>;
  required?: string[];
  additionalProperties?: boolean;
}

export interface ToolDefinition {
  type: 'function';
  function: {
    name: string;
    description: string;
    parameters: ObjectSchema;
  };
}

export interface AgentHooks {
  emit(text: string): void;
  approve(action: string): Promise<boolean>;
}

How Do Schemas and Hooks Fit?

  • ObjectSchema describes tool arguments using JSON Schema fields.
  • ToolDefinition gives the model a tool name, purpose, and accepted argument shape.
  • AgentHooks lets a caller observe events or decide whether a proposed action is approved.
  • Save src/types.ts.
  • Complete src/types.ts by adding the execution and result types below AgentHooks.
export interface ToolContext extends AgentHooks {
  workspaceRoot: string;
}

export interface ToolSpec {
  definition: ToolDefinition;
  execute(
    args: Record<string, unknown>,
    context: ToolContext,
  ): Promise<unknown>;
}

export type ToolExecutionResult =
  | {ok: true; data: unknown}
  | {ok: false; error: string};

export interface ChatCompletionResponse {
  choices: Array<{
    message: AssistantMessage;
  }>;
}

export interface AgentRunResult {
  messages: Message[];
  answer: string;
}

What Completes the Type Layer?

  • ToolContext combines the caller hooks with the bounded workspace location.
  • ToolSpec pairs each model-facing definition with a local executor.
  • ToolExecutionResult gives every tool call a structured success or failure shape.
  • ChatCompletionResponse keeps the provider response shape at the adapter boundary.
  • AgentRunResult returns the complete message trace plus the final answer.
  • Save src/types.ts.

✔️ Awesome, I've got everything!

Your complete src/types.ts file is ready for the final project type check.

ⓧ I'd like to double check the full code

Compare your saved src/types.ts with this complete types file.

export interface ToolCall {
  id: string;
  type: 'function';
  function: {
    name: string;
    arguments: string;
  };
}

export interface AssistantMessage {
  role: 'assistant';
  content: string | null;
  tool_calls?: ToolCall[];
}

export type Message =
  | {role: 'system' | 'user'; content: string}
  | AssistantMessage
  | {role: 'tool'; tool_call_id: string; content: string};

export interface ObjectSchema {
  type: 'object';
  properties: Record<string, unknown>;
  required?: string[];
  additionalProperties?: boolean;
}

export interface ToolDefinition {
  type: 'function';
  function: {
    name: string;
    description: string;
    parameters: ObjectSchema;
  };
}

export interface AgentHooks {
  emit(text: string): void;
  approve(action: string): Promise<boolean>;
}

export interface ToolContext extends AgentHooks {
  workspaceRoot: string;
}

export interface ToolSpec {
  definition: ToolDefinition;
  execute(
    args: Record<string, unknown>,
    context: ToolContext,
  ): Promise<unknown>;
}

export type ToolExecutionResult =
  | {ok: true; data: unknown}
  | {ok: false; error: string};

export interface ChatCompletionResponse {
  choices: Array<{
    message: AssistantMessage;
  }>;
}

export interface AgentRunResult {
  messages: Message[];
  answer: string;
}
Build the OpenRouter adapter

The type layer describes what the harness understands. The adapter now translates that vocabulary into one provider request.

Why Use a Direct Adapter?

A direct fetch() call exposes the request boundary without adding an agent framework. You can see exactly where messages, tools, authentication, and provider errors enter the harness.

The rest of the project can replace this adapter without changing the TUI. That separation keeps the TUI independent from the model provider.

  • Create src/openrouter.ts inside the existing src folder using your preferred IDE's project explorer.

You should see openrouter.ts listed beside types.ts in the src folder.

  • Add the adapter imports and provider constants to src/openrouter.ts by pasting this code:
import type {
  AssistantMessage,
  ChatCompletionResponse,
  Message,
  ToolSpec,
} from './types.ts';

const ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions';
export const MODEL = 'openrouter/free';

What Does This Adapter Configuration Do?

  • The type-only import keeps the adapter aligned with the harness types.
  • ENDPOINT stores OpenRouter's chat completions endpoint.
  • MODEL selects the Free Models Router through openrouter/free.
  • Save src/openrouter.ts.

The adapter must reject a missing key before making a request. It also adds tool definitions only when the caller supplies a non-empty registry.

  • Begin callModel() below the provider constants by pasting this first function section:
export async function callModel(
  messages: Message[],
  tools: ToolSpec[],
): Promise<AssistantMessage> {
  const apiKey = process.env.OPENROUTER_API_KEY;
  if (!apiKey) {
    throw new Error('OPENROUTER_API_KEY is missing from .env.');
  }

  const body: Record<string, unknown> = {
    model: MODEL,
    messages,
  };

  if (tools.length > 0) {
    body.tools = tools.map(tool => tool.definition);
    body.tool_choice = 'auto';
  }

How Is the Request Body Prepared?

  • OPENROUTER_API_KEY is read from the process environment populated by your local .env file.
  • body always contains the selected model plus the harness message trace.
  • tools and tool_choice appear only when at least one tool is available.
  • Complete callModel() by pasting this section directly below the closing brace for the tool check:
  const response = await fetch(ENDPOINT, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
  });

  if (!response.ok) {
    throw new Error(
      `OpenRouter request failed with ${response.status}: ${await response.text()}`,
    );
  }

  const data = (await response.json()) as ChatCompletionResponse;
  const message = data.choices[0]?.message;
  if (!message) {
    throw new Error('OpenRouter returned no assistant message.');
  }

  return message;
}

How Does the Adapter Complete the Turn?

  • fetch() sends the serialized request body with Bearer authentication.
  • response.ok separates successful responses from provider failures.
  • ChatCompletionResponse keeps provider parsing inside the adapter.
  • message returns one assistant turn in the harness format.
  • Save src/openrouter.ts.

✔️ Awesome, I've got everything!

Your complete src/openrouter.ts file is ready for the final project type check.

ⓧ I'd like to double check the full code

Compare your saved src/openrouter.ts with this complete adapter file.

import type {
  AssistantMessage,
  ChatCompletionResponse,
  Message,
  ToolSpec,
} from './types.ts';

const ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions';
export const MODEL = 'openrouter/free';

export async function callModel(
  messages: Message[],
  tools: ToolSpec[],
): Promise<AssistantMessage> {
  const apiKey = process.env.OPENROUTER_API_KEY;
  if (!apiKey) {
    throw new Error('OPENROUTER_API_KEY is missing from .env.');
  }

  const body: Record<string, unknown> = {
    model: MODEL,
    messages,
  };

  if (tools.length > 0) {
    body.tools = tools.map(tool => tool.definition);
    body.tool_choice = 'auto';
  }

  const response = await fetch(ENDPOINT, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
  });

  if (!response.ok) {
    throw new Error(
      `OpenRouter request failed with ${response.status}: ${await response.text()}`,
    );
  }

  const data = (await response.json()) as ChatCompletionResponse;
  const message = data.choices[0]?.message;
  if (!message) {
    throw new Error('OpenRouter returned no assistant message.');
  }

  return message;
}
Perform one model call

The adapter can produce a response, but it cannot inspect the workspace yet. This deliberate limitation separates model transport from agency.

  • Replace the starter pass-through in src/index.ts with model call:
import 'dotenv/config';

import {callModel} from './openrouter.ts';
import {runTui} from './tui/index.tsx';
import type {Message} from './types.ts';

async function respond(message: string): Promise<string> {
  // Build a fresh trace for this single model turn.
  const messages: Message[] = [
    {
      role: 'system',
      content:
        'You are a helpful AI coding assitant',
    },
    {role: 'user', content: message},
  ];

  // Keep this adapter test read-only by passing no tools.
  const assistant = await callModel(messages, []);
  return assistant.content ?? 'No text returned.';
}

runTui(respond);

How Does the TUI Reach the Adapter?

  • The side-effect import loads the local environment before the adapter reads OPENROUTER_API_KEY.
  • The messages array creates a fresh system-and-user trace for each submission.
  • The empty tool array keeps this model turn separate from workspace access.
  • The returned assistant content flows back through respond() for the TUI to display.
  • Save src/index.ts.

✔️ Awesome, I've got everything!

Your complete src/index.ts is ready for the type check below.

ⓧ I'd like to double check the full code

Compare your saved src/index.ts with this complete one-turn composition root.

import 'dotenv/config';

import {callModel} from './openrouter.ts';
import {runTui} from './tui/index.tsx';
import type {Message} from './types.ts';

async function respond(message: string): Promise<string> {
  // Build a fresh trace for this single model turn.
  const messages: Message[] = [
    {
      role: 'system',
      content:
        'You have no workspace tools. Say clearly when a task needs file access.',
    },
    {role: 'user', content: message},
  ];

  // Keep this adapter test read-only by passing no tools.
  const assistant = await callModel(messages, []);
  return assistant.content ?? 'No text returned.';
}

runTui(respond);

Before you run the type check, do you expect TypeScript to accept the new type boundary?

  • Check the complete project by running:
npm run typecheck

The type check should complete without TypeScript errors. This proves the composition root and adapter agree on the shared types.

Does the Final Type Check Fail?

  • Check that every type imported by src/openrouter.ts and src/index.ts is exported from src/types.ts.
  • Help me debug the final type check across the harness files.

The development command keeps the TUI active in the terminal. You can stop it with Ctrl+C after the check.

  • Start the existing client by running:
npm run dev

You should see the Agent Harness title plus its input prompt. Free-model availability can make the response time vary.

Before you submit the task, do you think the model can report real workspace contents without any registered tools?

  • Submit this task through the TUI input:
List the files in the workspace and report what they contain.

Why Use This Test?

The prompt asks for information that requires local file access. Passing an empty registry tests whether the model respects the system boundary.

You should receive one assistant response explaining that it has no workspace tools or file access. The exact wording can vary because the Free Models Router selects from available models.

No Model Response?

  • Confirm src/index.ts updated before you started the client.
  • Help me debug a missing response from my OpenRouter model adapter.

Your type layer and provider adapter are working through the existing client. Next, you will turn that single model call into a stateful agent runtime.

Build the Agent Runtime

Your OpenRouter adapter can complete one model request. It still forgets each submission because no runtime owns the conversation trace.

This step adds the central agent loop that carries messages across model requests. It also turns tool failures into observations that the model can handle.

In this step, get ready to:
  • Create a tool-call executor for validated results.
  • Build the repeating model loop in runAgent().
  • Move the message trace into the composition root.
Create the tool execution pipeline

A requested tool call is data until the harness finds a matching executor. The pipeline must validate that request before adding a correlated result to the message trace.

  • Create src/agent.ts inside the src folder using your preferred IDE's project explorer.
  • Add the model import plus the harness type imports by pasting this code:
import {callModel} from './openrouter.ts';
import type {
  AgentRunResult,
  Message,
  ToolCall,
  ToolContext,
  ToolExecutionResult,
  ToolSpec,
} from './types.ts';

What do these imports provide?

  • The callModel() import gives the runtime one provider-independent model turn.
  • The type imports define the runtime boundary without exposing provider response details.
  • The ToolExecutionResult union gives every execution a structured success or failure shape.

Add the tool-call executor below the imports by pasting this code:

async function executeToolCalls(
  calls: ToolCall[],
  messages: Message[],
  tools: ToolSpec[],
  context: ToolContext,
): Promise<void> {
  const toolMap = new Map(
    tools.map(tool => [tool.definition.function.name, tool]),
  );

  for (const call of calls) {
    let result: ToolExecutionResult;

    try {
      const tool = toolMap.get(call.function.name);
      if (!tool) {
        throw new Error(`Unknown tool: ${call.function.name}`);
      }

      const value: unknown = JSON.parse(call.function.arguments);
      if (!value || typeof value !== 'object' || Array.isArray(value)) {
        throw new Error('Tool arguments must decode to a JSON object.');
      }

      const data = await tool.execute(
        value as Record<string, unknown>,
        context,
      );
      result = {ok: true, data};
    } catch (error) {
      result = {
        ok: false,
        error: error instanceof Error ? error.message : String(error),
      };
    }

    context.emit(
      `Tool: ${call.function.name}\n${JSON.stringify(result, null, 2)}`,
    );
    messages.push({
      role: 'tool',
      tool_call_id: call.id,
      content: JSON.stringify(result),
    });
  }
}

How does tool execution stay reliable?

  • The toolMap resolves each requested name to a local executor.
  • The JSON check rejects arguments that do not decode to an object.
  • The try block converts unknown tools plus executor failures into ToolExecutionResult values.
  • The tool_call_id value links each tool result to the request that produced it.
  • The context.emit() hook exposes execution without printing from the runtime.
Add the agent loop

The executor handles one batch of tool calls. The orchestration loop must keep requesting model turns until an assistant message contains no more tool calls.

  • Add the harness policy prompt below executeToolCalls() by pasting this code:
const SYSTEM_PROMPT = `You are a small coding agent.
Use tools for every claim about workspace files and every local action.
Never claim an action succeeded without a matching tool result.
If a required tool is unavailable or an action is denied, say so clearly.
Return a concise response when the task is complete.`;

What policy does the prompt establish?

The prompt requires evidence for workspace claims. It also tells the model to surface missing capabilities or denied actions clearly.

These rules shape model behavior while local executors remain the authority for actual side effects.

  • Add runAgent() below SYSTEM_PROMPT by pasting this code:
export async function runAgent(
  userInput: string,
  context: ToolContext,
  initialMessages: Message[] = [],
  tools: ToolSpec[] = [],
): Promise<AgentRunResult> {
  const messages: Message[] =
    initialMessages.length > 0
      ? [...initialMessages]
      : [{role: 'system', content: SYSTEM_PROMPT}];

  messages.push({role: 'user', content: userInput});

  let turn = 1;
  while (true) {
    context.emit(`Model turn ${turn}`);
    const assistant = await callModel(messages, tools);
    messages.push(assistant);

    const calls = assistant.tool_calls ?? [];
    if (calls.length === 0) {
      return {
        messages,
        answer: assistant.content ?? 'No text returned.',
      };
    }

    await executeToolCalls(calls, messages, tools, context);
    turn += 1;
  }
}

How does the loop create agency?

  • The initialMessages parameter lets any caller supply an existing trace.
  • The runtime adds the system prompt only when that trace is empty.
  • Each user message enters the same ordered Message[] trace as assistant messages.
  • Each model turn receives the current tool registry through callModel().
  • A turn without tool_calls becomes the final AgentRunResult.

✔️ Awesome, I've got everything!

Great. Double check that you saved src/agent.ts.

ⓧ I'd like to double check the full code

Compare your complete src/agent.ts with this reference:

import {callModel} from './openrouter.ts';
import type {
  AgentRunResult,
  Message,
  ToolCall,
  ToolContext,
  ToolExecutionResult,
  ToolSpec,
} from './types.ts';

async function executeToolCalls(
  calls: ToolCall[],
  messages: Message[],
  tools: ToolSpec[],
  context: ToolContext,
): Promise<void> {
  const toolMap = new Map(
    tools.map(tool => [tool.definition.function.name, tool]),
  );

  for (const call of calls) {
    let result: ToolExecutionResult;

    try {
      const tool = toolMap.get(call.function.name);
      if (!tool) {
        throw new Error(`Unknown tool: ${call.function.name}`);
      }

      const value: unknown = JSON.parse(call.function.arguments);
      if (!value || typeof value !== 'object' || Array.isArray(value)) {
        throw new Error('Tool arguments must decode to a JSON object.');
      }

      const data = await tool.execute(
        value as Record<string, unknown>,
        context,
      );
      result = {ok: true, data};
    } catch (error) {
      result = {
        ok: false,
        error: error instanceof Error ? error.message : String(error),
      };
    }

    context.emit(
      `Tool: ${call.function.name}\n${JSON.stringify(result, null, 2)}`,
    );
    messages.push({
      role: 'tool',
      tool_call_id: call.id,
      content: JSON.stringify(result),
    });
  }
}

const SYSTEM_PROMPT = `You are a small coding agent.
Use tools for every claim about workspace files and every local action.
Never claim an action succeeded without a matching tool result.
If a required tool is unavailable or an action is denied, say so clearly.
Return a concise response when the task is complete.`;

export async function runAgent(
  userInput: string,
  context: ToolContext,
  initialMessages: Message[] = [],
  tools: ToolSpec[] = [],
): Promise<AgentRunResult> {
  const messages: Message[] =
    initialMessages.length > 0
      ? [...initialMessages]
      : [{role: 'system', content: SYSTEM_PROMPT}];

  messages.push({role: 'user', content: userInput});

  let turn = 1;
  while (true) {
    context.emit(`Model turn ${turn}`);
    const assistant = await callModel(messages, tools);
    messages.push(assistant);

    const calls = assistant.tool_calls ?? [];
    if (calls.length === 0) {
      return {
        messages,
        answer: assistant.content ?? 'No text returned.',
      };
    }

    await executeToolCalls(calls, messages, tools, context);
    turn += 1;
  }
}

How to compare this file

Check the imports first. Then compare executeToolCalls() before checking SYSTEM_PROMPT plus runAgent().

Move message state into the composition root

The runtime returns a complete trace after every submission. The composition root can retain that trace while the TUI stays focused on input and rendering.

  • Switch back to src/index.ts from earlier.
  • Replace its existing imports with this import group:
import 'dotenv/config';

import {mkdir, realpath} from 'node:fs/promises';
import {resolve} from 'node:path';
import process from 'node:process';
import {runAgent} from './agent.ts';
import {runTui} from './tui/index.tsx';
import type {AgentHooks, Message} from './types.ts';

Why do these imports belong here?

  • The composition root loads environment configuration before starting the harness.
  • The file-system imports create one canonical workspace location for every execution context.
  • The runAgent() import replaces the temporary one-turn model call.
  • The AgentHooks type describes optional event and approval capabilities that a caller can supply. The TUI keeps its one-argument respond() boundary until the approval interface is added.
  • Add the composition logic below the imports by pasting this code:
async function main(): Promise<void> {
  // Keep one canonical workspace and conversation trace outside the TUI.
  const configuredRoot = resolve(process.cwd(), 'workspace');
  await mkdir(configuredRoot, {recursive: true});
  const workspaceRoot = await realpath(configuredRoot);
  let messages: Message[] = [];

  async function respond(message: string, hooks?: AgentHooks): Promise<string> {
    // Use UI hooks when available. Defaults keep the TUI compatible.
    const activeHooks: AgentHooks = hooks ?? {
      emit() {},
      approve: () => Promise.resolve(false),
    };
    const result = await runAgent(
      message,
      {...activeHooks, workspaceRoot},
      messages,
    );
    // Preserve the returned trace for the next submission.
    messages = result.messages;
    return result.answer;
  }

  runTui(respond);
}

void main().catch((error: unknown) => {
  console.error(error instanceof Error ? error.message : error);
  process.exitCode = 1;
});

Where does conversation state live?

  • The workspaceRoot value gives every future tool the same canonical boundary.
  • The mutable messages array lives outside the TUI.
  • Each respond() call passes the previous trace into runAgent().
  • The returned result.messages value becomes the trace for the next submission.
  • The optional hooks parameter preserves the TUI's one-argument callback. Without UI hooks, events stay silent and approvals default to denied.
  • The updated TUI supplies real emit() and approve() implementations later without changing the runtime.

✔️ Awesome, I've got everything!

Great. Double check that you saved src/index.ts.

ⓧ I'd like to double check the full code

Compare your complete src/index.ts with this reference:

import 'dotenv/config';

import {mkdir, realpath} from 'node:fs/promises';
import {resolve} from 'node:path';
import process from 'node:process';
import {runAgent} from './agent.ts';
import {runTui} from './tui/index.tsx';
import type {AgentHooks, Message} from './types.ts';

async function main(): Promise<void> {
  // Keep one canonical workspace and conversation trace outside the TUI.
  const configuredRoot = resolve(process.cwd(), 'workspace');
  await mkdir(configuredRoot, {recursive: true});
  const workspaceRoot = await realpath(configuredRoot);
  let messages: Message[] = [];

  async function respond(message: string, hooks?: AgentHooks): Promise<string> {
    // Use UI hooks when available. Defaults keep the TUI compatible.
    const activeHooks: AgentHooks = hooks ?? {
      emit() {},
      approve: () => Promise.resolve(false),
    };
    const result = await runAgent(
      message,
      {...activeHooks, workspaceRoot},
      messages,
    );
    // Preserve the returned trace for the next submission.
    messages = result.messages;
    return result.answer;
  }

  runTui(respond);
}

void main().catch((error: unknown) => {
  console.error(error instanceof Error ? error.message : error);
  process.exitCode = 1;
});

How to compare this file

Check the import group first. Then compare main() plus the nested respond() function.

  • Save src/agent.ts.
  • Save src/index.ts.
  • Verify the complete runtime by running this command:
npm run typecheck

What Does the Final Type Check Cover?

This type check covers the complete path from src/index.ts through runAgent() to callModel(). It also confirms that the TUI still receives only the respond() boundary.

You should return to the terminal prompt without TypeScript errors.

Is the Runtime Failing the Type Check?

Use the file path and line number in the type-check output to locate the mismatch in src/agent.ts, src/index.ts, or src/types.ts.

Help me debug the consolidated runtime type check.

The type check proves the modules fit together. The final run proves that one TUI process can reuse its message trace across separate submissions.

  • Start the TUI by running this command:
npm run dev

What does this command start?

The development script starts the existing TUI with the new runtime behind it. Keep this process running while you submit both test messages.

  • Submit this first message in the TUI:
Remember that my test word is cobalt.

What does the first message establish?

This submission adds a user message plus the assistant response to the composition-layer trace. The returned trace replaces the previous messages value.

  • Wait for the agent to acknowledge the message.

Before you submit the follow-up, do you think the harness will retain a detail that appeared only in the earlier user message?

  • Submit this follow-up in the same TUI process:
What test word did I give you?

What does the follow-up test?

The second submission receives the trace returned by the first run. A response containing cobalt proves that the composition root preserves conversation state.

You should see an answer containing cobalt. That is the runtime remembering across separate TUI submissions.

Your runtime now owns model turns plus message state plus tool-result correlation. Next up, you will give that loop grounded workspace capabilities through a bounded tool registry.

Add Read-Only Workspace Tools

Your runtime now owns model turns, message history, tool dispatch, result correlation, and loop termination. However, the model still has no evidence about files inside the workspace.

A tool registry gives the harness a controlled set of local capabilities. This step adds inspection tools while keeping every consequential action outside the registry.

In this step, get ready to:
  • Build helpers that keep file access inside the workspace.
  • Register tools for reading, listing, and searching files.
  • Prove that unsupported changes remain unavailable.
Build the workspace policy helpers

The registry needs one path boundary before it reads anything. Each existing target is resolved to its canonical location so a path cannot escape through a symbolic link.

  • Create src/tools.ts inside the src folder using your preferred IDE's project explorer.

You should see tools.ts open beside the existing harness modules.

  • Add the shared imports, text limit, and argument validator to src/tools.ts by pasting this code:
import {exec} from 'node:child_process';
import {
  lstat,
  mkdir,
  readdir,
  readFile,
  realpath,
  unlink,
  writeFile,
} from 'node:fs/promises';
import {dirname, isAbsolute, relative, resolve, sep} from 'node:path';
import type {ToolSpec} from './types.ts';

const MAX_TEXT = 12_000;

function requiredString(
  args: Record<string, unknown>,
  name: string,
  allowEmpty = false,
): string {
  const value = args[name];
  if (typeof value !== 'string' || (!allowEmpty && value.length === 0)) {
    throw new Error(
      `${name} must be ${allowEmpty ? 'a string' : 'a non-empty string'}.`,
    );
  }

  return value;
}

What does this code do?

  • The import group gives the registry access to filesystem and path primitives from Node.js.
  • The MAX_TEXT limit keeps one file observation from flooding the model context.
  • The requiredString() helper rejects missing arguments before a tool touches the filesystem.
  • Save src/tools.ts.

String validation protects the executor boundary. Path validation now decides whether that accepted value points inside the controlled workspace.

  • Add boundedPath() below requiredString() by pasting this code:
async function boundedPath(root: string, inputPath: string): Promise<string> {
  const rootPath = await realpath(root);
  const targetPath = await realpath(resolve(root, inputPath));
  const relativeTarget = relative(rootPath, targetPath);

  if (
    relativeTarget === '..' ||
    relativeTarget.startsWith(`..${sep}`) ||
    isAbsolute(relativeTarget)
  ) {
    throw new Error(`Path escapes the workspace: ${inputPath}`);
  }

  return targetPath;
}

How does the boundary work?

  • The first realpath() call finds the canonical workspace root.
  • The second realpath() call resolves the requested target before access is allowed.
  • The relative-path checks reject parent traversal and absolute paths outside the workspace.
  • Save src/tools.ts.

Directory inspection needs deterministic traversal. Sorted results make repeated tool observations easier for the model to compare.

  • Add walkFiles() below boundedPath() by pasting this code:
async function walkFiles(directory: string): Promise<string[]> {
  const entries = await readdir(directory, {withFileTypes: true});
  const files: string[] = [];

  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
    if (entry.isSymbolicLink()) {
      continue;
    }

    const target = resolve(directory, entry.name);
    if (entry.isDirectory()) {
      files.push(...(await walkFiles(target)));
    } else if (entry.isFile()) {
      files.push(target);
    }
  }

  return files;
}

What does this traversal do?

  • The directory entries are sorted before traversal so the same workspace produces a stable order.
  • Symbolic-link entries are skipped so recursive inspection cannot follow them elsewhere.
  • Nested directories call walkFiles() again until every regular file has been collected.
  • Save src/tools.ts.

Searching builds on the same traversal policy. A fixed match limit keeps the observation compact even when many files contain the query.

  • Add searchFiles() and the shared path property below walkFiles() by pasting this code:
async function searchFiles(
  root: string,
  directory: string,
  query: string,
): Promise<string[]> {
  const matches: string[] = [];

  for (const file of await walkFiles(directory)) {
    try {
      const lines = (await readFile(file, 'utf8')).split('\n');
      lines.forEach((line, index) => {
        if (matches.length < 50 && line.includes(query)) {
          const path = relative(root, file).split(sep).join('/');
          matches.push(`${path}:${index + 1}:${line}`);
        }
      });
    } catch {
      // Ignore unreadable or non-text files in this learning harness.
    }
  }

  return matches;
}

const pathProperty = {
  type: 'string',
  description: 'Path relative to the workspace root. Use . for the root.',
};

How does searching stay bounded?

  • The search reads each traversed file as UTF-8 text.
  • Each match records a relative path, line number, and matching line.
  • The match condition stops collecting results after 50 entries.
  • The shared pathProperty gives each tool the same path description.
  • Save src/tools.ts.
Register the read-only tools

Each tool pairs a JSON Schema definition with a local executor. The definition tells the model what it may request while the executor remains in control of filesystem access.

  • Add the read_file tool below pathProperty by pasting this code:
const readFileTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'read_file',
      description: 'Read a UTF-8 text file inside the workspace.',
      parameters: {
        type: 'object',
        properties: {path: pathProperty},
        required: ['path'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    const path = requiredString(args, 'path');
    const target = await boundedPath(context.workspaceRoot, path);
    const content = await readFile(target, 'utf8');

    return {
      path: relative(context.workspaceRoot, target).split(sep).join('/'),
      content: content.slice(0, MAX_TEXT),
      truncated: content.length > MAX_TEXT,
    };
  },
};

How does read_file work?

  • The definition advertises one required relative path.
  • The executor validates the argument before resolving the canonical target.
  • The returned observation includes the relative path and bounded file content.
  • The truncated flag tells the model when content exceeded 12,000 characters.
  • Save src/tools.ts.

File reading answers questions about one known path. Directory listing gives the model the evidence it needs to discover those paths first.

  • Add the list_files tool below readFileTool by pasting this code:
const listFilesTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'list_files',
      description: 'List files and directories at a workspace path.',
      parameters: {
        type: 'object',
        properties: {path: pathProperty},
        required: ['path'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    const path = requiredString(args, 'path');
    const target = await boundedPath(context.workspaceRoot, path);
    const entries = await readdir(target, {withFileTypes: true});

    return entries
      .sort((a, b) => a.name.localeCompare(b.name))
      .map(entry => (entry.isDirectory() ? `${entry.name}/` : entry.name));
  },
};

How does list_files work?

  • The tool accepts the same bounded relative path used by read_file.
  • Directory entries are sorted alphabetically before they become a tool result.
  • A trailing slash distinguishes directories from regular files.
  • Save src/tools.ts.

A search tool connects a phrase to the files that contain it. The returned line references let the model decide which matching files need a full read.

  • Add the search_directory tool below listFilesTool by pasting this code:
const searchDirectoryTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'search_directory',
      description: 'Search UTF-8 files under a workspace directory for text.',
      parameters: {
        type: 'object',
        properties: {
          path: pathProperty,
          query: {
            type: 'string',
            description: 'Case-sensitive text to find.',
          },
        },
        required: ['path', 'query'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    const path = requiredString(args, 'path');
    const query = requiredString(args, 'query');
    const target = await boundedPath(context.workspaceRoot, path);
    const matches = await searchFiles(context.workspaceRoot, target, query);

    return {matches, truncated: matches.length === 50};
  },
};

How does search_directory work?

  • The schema requires a path and a case-sensitive query.
  • The executor applies the same canonical workspace boundary before traversal.
  • The result exposes collected matches plus a flag when the search reaches its limit.
  • Save src/tools.ts.
Connect and test the registry

The three tool objects exist locally, but the adapter can only advertise tools that reach runAgent(). Exporting one array keeps the runtime and the OpenRouter request synchronized.

  • Export the read-only registry at the bottom of src/tools.ts by pasting this code:
export const tools: ToolSpec[] = [
  readFileTool,
  listFilesTool,
  searchDirectoryTool,
];

Why use one exported registry?

The exported array is the complete capability boundary for this run. Passing the same array into each model turn keeps provider definitions aligned with local executors.

  • Save src/tools.ts.

✔️ Awesome, I've got everything!

Great. Double check that you saved src/tools.ts.

ⓧ I'd like to double check the full code

import {exec} from 'node:child_process';
import {
  lstat,
  mkdir,
  readdir,
  readFile,
  realpath,
  unlink,
  writeFile,
} from 'node:fs/promises';
import {dirname, isAbsolute, relative, resolve, sep} from 'node:path';
import type {ToolSpec} from './types.ts';

const MAX_TEXT = 12_000;

function requiredString(
  args: Record<string, unknown>,
  name: string,
  allowEmpty = false,
): string {
  const value = args[name];
  if (typeof value !== 'string' || (!allowEmpty && value.length === 0)) {
    throw new Error(
      `${name} must be ${allowEmpty ? 'a string' : 'a non-empty string'}.`,
    );
  }

  return value;
}

async function boundedPath(root: string, inputPath: string): Promise<string> {
  const rootPath = await realpath(root);
  const targetPath = await realpath(resolve(root, inputPath));
  const relativeTarget = relative(rootPath, targetPath);

  if (
    relativeTarget === '..' ||
    relativeTarget.startsWith(`..${sep}`) ||
    isAbsolute(relativeTarget)
  ) {
    throw new Error(`Path escapes the workspace: ${inputPath}`);
  }

  return targetPath;
}

async function walkFiles(directory: string): Promise<string[]> {
  const entries = await readdir(directory, {withFileTypes: true});
  const files: string[] = [];

  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
    if (entry.isSymbolicLink()) {
      continue;
    }

    const target = resolve(directory, entry.name);
    if (entry.isDirectory()) {
      files.push(...(await walkFiles(target)));
    } else if (entry.isFile()) {
      files.push(target);
    }
  }

  return files;
}

async function searchFiles(
  root: string,
  directory: string,
  query: string,
): Promise<string[]> {
  const matches: string[] = [];

  for (const file of await walkFiles(directory)) {
    try {
      const lines = (await readFile(file, 'utf8')).split('\n');
      lines.forEach((line, index) => {
        if (matches.length < 50 && line.includes(query)) {
          const path = relative(root, file).split(sep).join('/');
          matches.push(`${path}:${index + 1}:${line}`);
        }
      });
    } catch {
      // Ignore unreadable or non-text files in this learning harness.
    }
  }

  return matches;
}

const pathProperty = {
  type: 'string',
  description: 'Path relative to the workspace root. Use . for the root.',
};

const readFileTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'read_file',
      description: 'Read a UTF-8 text file inside the workspace.',
      parameters: {
        type: 'object',
        properties: {path: pathProperty},
        required: ['path'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    const path = requiredString(args, 'path');
    const target = await boundedPath(context.workspaceRoot, path);
    const content = await readFile(target, 'utf8');

    return {
      path: relative(context.workspaceRoot, target).split(sep).join('/'),
      content: content.slice(0, MAX_TEXT),
      truncated: content.length > MAX_TEXT,
    };
  },
};

const listFilesTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'list_files',
      description: 'List files and directories at a workspace path.',
      parameters: {
        type: 'object',
        properties: {path: pathProperty},
        required: ['path'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    const path = requiredString(args, 'path');
    const target = await boundedPath(context.workspaceRoot, path);
    const entries = await readdir(target, {withFileTypes: true});

    return entries
      .sort((a, b) => a.name.localeCompare(b.name))
      .map(entry => (entry.isDirectory() ? `${entry.name}/` : entry.name));
  },
};

const searchDirectoryTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'search_directory',
      description: 'Search UTF-8 files under a workspace directory for text.',
      parameters: {
        type: 'object',
        properties: {
          path: pathProperty,
          query: {
            type: 'string',
            description: 'Case-sensitive text to find.',
          },
        },
        required: ['path', 'query'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    const path = requiredString(args, 'path');
    const query = requiredString(args, 'query');
    const target = await boundedPath(context.workspaceRoot, path);
    const matches = await searchFiles(context.workspaceRoot, target, query);

    return {matches, truncated: matches.length === 50};
  },
};

export const tools: ToolSpec[] = [
  readFileTool,
  listFilesTool,
  searchDirectoryTool,
];
  • Switch back to src/index.ts from earlier.
  • Add the registry import below the existing runAgent import by pasting this line:
import {tools} from './tools.ts';
  • In src/index.ts, find the runAgent() call inside respond().
  • Locate this existing argument list:
const result = await runAgent(
  message,
  {...activeHooks, workspaceRoot},
  messages,
);
  • Add tools as the fourth argument, so the call looks like this:
const result = await runAgent(
  message,
  {...activeHooks, workspaceRoot},
  messages,
  tools,
);

What do these changes connect?

The import makes the completed read-only registry available to the composition root.

Passing tools as the fourth argument replaces the empty registry used in Step 3. Each model turn can now advertise the new capabilities and dispatch matching requests.

✔️ Awesome, I've got everything!

Great. Double check that you saved src/index.ts.

ⓧ I'd like to double check the full code

import 'dotenv/config';

import {mkdir, realpath} from 'node:fs/promises';
import {resolve} from 'node:path';
import process from 'node:process';
import {runAgent} from './agent.ts';
import {tools} from './tools.ts';
import {runTui} from './tui/index.tsx';
import type {AgentHooks, Message} from './types.ts';

async function main(): Promise<void> {
  // Keep one canonical workspace and conversation trace outside the TUI.
  const configuredRoot = resolve(process.cwd(), 'workspace');
  await mkdir(configuredRoot, {recursive: true});
  const workspaceRoot = await realpath(configuredRoot);
  let messages: Message[] = [];

  async function respond(message: string, hooks?: AgentHooks): Promise<string> {
    // Use UI hooks when available. Defaults keep the starter TUI compatible.
    const activeHooks: AgentHooks = hooks ?? {
      emit() {},
      approve: () => Promise.resolve(false),
    };
    const result = await runAgent(
      message,
      {...activeHooks, workspaceRoot},
      messages,
      tools,
    );
    // Preserve the returned trace for the next submission.
    messages = result.messages;
    return result.answer;
  }

  runTui(respond);
}

void main().catch((error: unknown) => {
  console.error(error instanceof Error ? error.message : error);
  process.exitCode = 1;
});
  • Save src/index.ts.
  • Check the completed registry by running:
npm run typecheck

Type check failing?

  • Confirm that src/tools.ts sits beside src/index.ts if TypeScript cannot resolve the module.
  • Check that readFileTool, listFilesTool, and searchDirectoryTool use the shared ToolSpec shape if the registry type fails.
  • Help me debug the final type check.

The registry is now connected. Before you test it, which tool do you expect the model to request first when it needs to discover unknown workspace files?

  • Start the harness from the project terminal by running this command:
npm run dev

What does this command do?

This starts the existing TUI with the new registry connected. The process keeps control of the terminal until you stop it with Ctrl+C.

  • Submit this inspection task in the TUI:
List the files in the workspace, find "hello agent", read the matching files, and summarize them.

What should you see?

The starter TUI displays your submitted task and one final response from the agent. That response should identify app.js and notes.txt.

The response should explain that both files contain hello agent and summarize what each file says.

The exact wording can vary because openrouter/free routes requests across available free models. A response grounded in both file names and matching text confirms that the read-only registry worked.

That is the read-only path working: your harness can inspect local files and ground its answer in their contents.

Before you submit the next task, do you think a capable model can edit or execute a file when those capabilities are missing from its registry?

  • Submit this consequential task in the same TUI process:
Change app.js so it prints "agent loop complete", then run node app.js.

The limitation is intentional

The harness should report that the requested edit and command capabilities are unavailable. workspace/app.js should still contain hello agent because no consequential tool exists.

  • Stop the running TUI by pressing Ctrl+C.

Your registry can now ground workspace claims without granting mutation access. Next, you will place edits, commands, writes, and deletion behind an approval policy.

Approve and Run Consequential Tools

Your read-only tool registry can inspect the workspace. The previous test exposed its deliberate limit because the harness could not edit files or run commands.

This step adds four consequential tools behind an approval policy. The TUI collects each decision while the harness keeps ownership of policy and execution.

In this step, get ready to:
  • Add guarded tools for writing files and editing files.
  • Add approval-gated tools for deleting files and running commands.
  • Approve the intended workflow and verify its changes.
Add guarded mutation tools

New files do not have canonical paths yet. The mutation helpers first apply a lexical workspace check. They then use lstat() to reject existing path segments that are symbolic links.

Each consequential executor requests approval before changing state. A denied request becomes a structured result that the model can read and explain.

  • Open src/tools.ts in your preferred IDE.
  • Add the mutation boundary below boundedPath() by pasting this code:
function mutationPath(root: string, inputPath: string): string {
  // Resolve the proposed target without requiring it to exist yet.
  const target = resolve(root, inputPath);
  const relativeTarget = relative(root, target);

  if (
    relativeTarget === '..' ||
    relativeTarget.startsWith(`..${sep}`) ||
    isAbsolute(relativeTarget)
  ) {
    throw new Error(`Path escapes the workspace: ${inputPath}`);
  }

  return target;
}

How does the mutation boundary work?

The helper checks a proposed path before a new file exists. Parent traversal and absolute paths outside the workspace are rejected.

  • Add the symbolic-link guard below mutationPath() by pasting this code:
function isErrno(error: unknown): error is NodeJS.ErrnoException {
  return error instanceof Error && 'code' in error;
}

async function assertNoSymlinkPath(
  root: string,
  target: string,
): Promise<void> {
  let current = root;

  // Check every existing segment before a mutation is approved.
  for (const part of relative(root, target).split(sep).filter(Boolean)) {
    current = resolve(current, part);

    try {
      if ((await lstat(current)).isSymbolicLink()) {
        throw new Error(`Symbolic links are not allowed: ${part}`);
      }
    } catch (error) {
      if (isErrno(error) && error.code === 'ENOENT') {
        return;
      }

      throw error;
    }
  }
}

Why inspect every path segment?

A path can remain lexically inside the workspace while an existing symbolic link redirects access elsewhere. The guard stops at the first missing segment because later segments cannot be links yet.

  • Add the write_file tool below searchDirectoryTool by pasting this code:
const writeFileTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'write_file',
      description: 'Create or replace a UTF-8 file inside the workspace.',
      parameters: {
        type: 'object',
        properties: {
          path: pathProperty,
          content: {type: 'string', description: 'Complete new file content.'},
        },
        required: ['path', 'content'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    // Validate the target before requesting approval.
    const path = requiredString(args, 'path');
    const content = requiredString(args, 'content', true);
    const target = mutationPath(context.workspaceRoot, path);
    await assertNoSymlinkPath(context.workspaceRoot, target);
    if (!(await context.approve(`write ${path}`))) return {approved: false};

    // Apply only an approved workspace mutation.
    await mkdir(dirname(target), {recursive: true});
    await writeFile(target, content, 'utf8');
    return {approved: true, path};
  },
};

How does writing stay controlled?

The executor validates the target before it asks for approval. Only an approved request creates parent folders and writes the supplied UTF-8 content.

  • Add the edit_file tool below writeFileTool by pasting this code:
const editFileTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'edit_file',
      description: 'Replace one exact text occurrence in a workspace file.',
      parameters: {
        type: 'object',
        properties: {
          path: pathProperty,
          old_text: {type: 'string', description: 'Exact text to replace once.'},
          new_text: {type: 'string', description: 'Replacement text.'},
        },
        required: ['path', 'old_text', 'new_text'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    // Require one unambiguous replacement inside the workspace.
    const path = requiredString(args, 'path');
    const oldText = requiredString(args, 'old_text');
    const newText = requiredString(args, 'new_text', true);
    const target = mutationPath(context.workspaceRoot, path);
    await assertNoSymlinkPath(context.workspaceRoot, target);
    const source = await readFile(target, 'utf8');
    const count = source.split(oldText).length - 1;
    if (count !== 1) throw new Error(`old_text must occur exactly once; found ${count}.`);
    if (!(await context.approve(`edit ${path}`))) return {approved: false};
    await writeFile(target, source.replace(oldText, newText), 'utf8');
    return {approved: true, path};
  },
};

Why require one exact match?

The executor rejects missing or repeated source text before asking for approval. That rule keeps one approved edit tied to one predictable change.

  • Add the delete_file tool below editFileTool by pasting this code:
const deleteFileTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'delete_file',
      description: 'Delete one file inside the workspace.',
      parameters: {
        type: 'object',
        properties: {path: pathProperty},
        required: ['path'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    // Validate the file before requesting a destructive action.
    const path = requiredString(args, 'path');
    const target = mutationPath(context.workspaceRoot, path);
    await assertNoSymlinkPath(context.workspaceRoot, target);
    if (!(await context.approve(`delete ${path}`))) return {approved: false};

    await unlink(target);
    return {approved: true, path};
  },
};

How is deletion gated?

The executor resolves and checks the target before showing the approval request. A denial returns a structured result without deleting the file.

  • Add the run_command tool below deleteFileTool by pasting this code:
const runCommandTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'run_command',
      description: 'Run a shell command from the workspace after approval.',
      parameters: {
        type: 'object',
        properties: {
          command: {type: 'string', description: 'Exact shell command to run.'},
        },
        required: ['command'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    const command = requiredString(args, 'command');
    if (!(await context.approve(`run shell command: ${command}`))) {
      return {approved: false};
    }

    // Capture bounded command output from the canonical workspace.
    return await new Promise<unknown>(done => {
      exec(command, {cwd: context.workspaceRoot, encoding: 'utf8', timeout: 10_000, maxBuffer: 1_000_000}, (error, stdout, stderr) => {
        const exitCode = error && typeof error.code === 'number' ? error.code : error ? 1 : 0;
        done({approved: true, exitCode, stdout: String(stdout).slice(0, MAX_TEXT), stderr: String(stderr).slice(0, MAX_TEXT), error: error?.message ?? null});
      });
    });
  },
};

How is command output bounded?

The executor runs an approved command from the canonical workspace. It limits runtime, buffer size, and returned text before the result reaches the model.

  • Find the existing registry export at the bottom of src/tools.ts.
  • Locate this code:
export const tools: ToolSpec[] = [
  readFileTool,
  listFilesTool,
  searchDirectoryTool,
];
  • Replace the existing export with the seven-tool registry below:
export const tools: ToolSpec[] = [
  readFileTool,
  listFilesTool,
  searchDirectoryTool,
  writeFileTool,
  editFileTool,
  deleteFileTool,
  runCommandTool,
];
  • Save src/tools.ts.

✔️ Awesome, I've got everything!

Great. Double check that you saved src/tools.ts.

ⓧ I'd like to double check the full code

import {exec} from 'node:child_process';
import {
  lstat,
  mkdir,
  readdir,
  readFile,
  realpath,
  unlink,
  writeFile,
} from 'node:fs/promises';
import {dirname, isAbsolute, relative, resolve, sep} from 'node:path';
import type {ToolSpec} from './types.ts';

const MAX_TEXT = 12_000;

function requiredString(
  args: Record<string, unknown>,
  name: string,
  allowEmpty = false,
): string {
  const value = args[name];
  if (typeof value !== 'string' || (!allowEmpty && value.length === 0)) {
    throw new Error(
      `${name} must be ${allowEmpty ? 'a string' : 'a non-empty string'}.`,
    );
  }

  return value;
}

async function boundedPath(root: string, inputPath: string): Promise<string> {
  const rootPath = await realpath(root);
  const targetPath = await realpath(resolve(root, inputPath));
  const relativeTarget = relative(rootPath, targetPath);

  if (
    relativeTarget === '..' ||
    relativeTarget.startsWith(`..${sep}`) ||
    isAbsolute(relativeTarget)
  ) {
    throw new Error(`Path escapes the workspace: ${inputPath}`);
  }

  return targetPath;
}

function mutationPath(root: string, inputPath: string): string {
  // Resolve the proposed target without requiring it to exist yet.
  const target = resolve(root, inputPath);
  const relativeTarget = relative(root, target);

  if (
    relativeTarget === '..' ||
    relativeTarget.startsWith(`..${sep}`) ||
    isAbsolute(relativeTarget)
  ) {
    throw new Error(`Path escapes the workspace: ${inputPath}`);
  }

  return target;
}

function isErrno(error: unknown): error is NodeJS.ErrnoException {
  return error instanceof Error && 'code' in error;
}

async function assertNoSymlinkPath(
  root: string,
  target: string,
): Promise<void> {
  let current = root;

  // Check every existing segment before a mutation is approved.
  for (const part of relative(root, target).split(sep).filter(Boolean)) {
    current = resolve(current, part);

    try {
      if ((await lstat(current)).isSymbolicLink()) {
        throw new Error(`Symbolic links are not allowed: ${part}`);
      }
    } catch (error) {
      if (isErrno(error) && error.code === 'ENOENT') {
        return;
      }

      throw error;
    }
  }
}

async function walkFiles(directory: string): Promise<string[]> {
  const entries = await readdir(directory, {withFileTypes: true});
  const files: string[] = [];

  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
    if (entry.isSymbolicLink()) {
      continue;
    }

    const target = resolve(directory, entry.name);
    if (entry.isDirectory()) {
      files.push(...(await walkFiles(target)));
    } else if (entry.isFile()) {
      files.push(target);
    }
  }

  return files;
}

async function searchFiles(
  root: string,
  directory: string,
  query: string,
): Promise<string[]> {
  const matches: string[] = [];

  for (const file of await walkFiles(directory)) {
    try {
      const lines = (await readFile(file, 'utf8')).split('\n');
      lines.forEach((line, index) => {
        if (matches.length < 50 && line.includes(query)) {
          const path = relative(root, file).split(sep).join('/');
          matches.push(`${path}:${index + 1}:${line}`);
        }
      });
    } catch {
      // Ignore unreadable or non-text files in this learning harness.
    }
  }

  return matches;
}

const pathProperty = {
  type: 'string',
  description: 'Path relative to the workspace root. Use . for the root.',
};

const readFileTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'read_file',
      description: 'Read a UTF-8 text file inside the workspace.',
      parameters: {
        type: 'object',
        properties: {path: pathProperty},
        required: ['path'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    const path = requiredString(args, 'path');
    const target = await boundedPath(context.workspaceRoot, path);
    const content = await readFile(target, 'utf8');

    return {
      path: relative(context.workspaceRoot, target).split(sep).join('/'),
      content: content.slice(0, MAX_TEXT),
      truncated: content.length > MAX_TEXT,
    };
  },
};

const listFilesTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'list_files',
      description: 'List files and directories at a workspace path.',
      parameters: {
        type: 'object',
        properties: {path: pathProperty},
        required: ['path'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    const path = requiredString(args, 'path');
    const target = await boundedPath(context.workspaceRoot, path);
    const entries = await readdir(target, {withFileTypes: true});

    return entries
      .sort((a, b) => a.name.localeCompare(b.name))
      .map(entry => (entry.isDirectory() ? `${entry.name}/` : entry.name));
  },
};

const searchDirectoryTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'search_directory',
      description: 'Search UTF-8 files under a workspace directory for text.',
      parameters: {
        type: 'object',
        properties: {
          path: pathProperty,
          query: {
            type: 'string',
            description: 'Case-sensitive text to find.',
          },
        },
        required: ['path', 'query'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    const path = requiredString(args, 'path');
    const query = requiredString(args, 'query');
    const target = await boundedPath(context.workspaceRoot, path);
    const matches = await searchFiles(context.workspaceRoot, target, query);

    return {matches, truncated: matches.length === 50};
  },
};

const writeFileTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'write_file',
      description: 'Create or replace a UTF-8 file inside the workspace.',
      parameters: {
        type: 'object',
        properties: {
          path: pathProperty,
          content: {type: 'string', description: 'Complete new file content.'},
        },
        required: ['path', 'content'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    // Validate the target before requesting approval.
    const path = requiredString(args, 'path');
    const content = requiredString(args, 'content', true);
    const target = mutationPath(context.workspaceRoot, path);
    await assertNoSymlinkPath(context.workspaceRoot, target);
    if (!(await context.approve(`write ${path}`))) return {approved: false};

    // Apply only an approved workspace mutation.
    await mkdir(dirname(target), {recursive: true});
    await writeFile(target, content, 'utf8');
    return {approved: true, path};
  },
};

const editFileTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'edit_file',
      description: 'Replace one exact text occurrence in a workspace file.',
      parameters: {
        type: 'object',
        properties: {
          path: pathProperty,
          old_text: {type: 'string', description: 'Exact text to replace once.'},
          new_text: {type: 'string', description: 'Replacement text.'},
        },
        required: ['path', 'old_text', 'new_text'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    // Require one unambiguous replacement inside the workspace.
    const path = requiredString(args, 'path');
    const oldText = requiredString(args, 'old_text');
    const newText = requiredString(args, 'new_text', true);
    const target = mutationPath(context.workspaceRoot, path);
    await assertNoSymlinkPath(context.workspaceRoot, target);
    const source = await readFile(target, 'utf8');
    const count = source.split(oldText).length - 1;
    if (count !== 1) throw new Error(`old_text must occur exactly once; found ${count}.`);
    if (!(await context.approve(`edit ${path}`))) return {approved: false};
    await writeFile(target, source.replace(oldText, newText), 'utf8');
    return {approved: true, path};
  },
};

const deleteFileTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'delete_file',
      description: 'Delete one file inside the workspace.',
      parameters: {
        type: 'object',
        properties: {path: pathProperty},
        required: ['path'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    // Validate the file before requesting a destructive action.
    const path = requiredString(args, 'path');
    const target = mutationPath(context.workspaceRoot, path);
    await assertNoSymlinkPath(context.workspaceRoot, target);
    if (!(await context.approve(`delete ${path}`))) return {approved: false};

    await unlink(target);
    return {approved: true, path};
  },
};

const runCommandTool: ToolSpec = {
  definition: {
    type: 'function',
    function: {
      name: 'run_command',
      description: 'Run a shell command from the workspace after approval.',
      parameters: {
        type: 'object',
        properties: {
          command: {type: 'string', description: 'Exact shell command to run.'},
        },
        required: ['command'],
        additionalProperties: false,
      },
    },
  },
  async execute(args, context) {
    const command = requiredString(args, 'command');
    if (!(await context.approve(`run shell command: ${command}`))) {
      return {approved: false};
    }

    // Capture bounded command output from the canonical workspace.
    return await new Promise<unknown>(done => {
      exec(command, {cwd: context.workspaceRoot, encoding: 'utf8', timeout: 10_000, maxBuffer: 1_000_000}, (error, stdout, stderr) => {
        const exitCode = error && typeof error.code === 'number' ? error.code : error ? 1 : 0;
        done({approved: true, exitCode, stdout: String(stdout).slice(0, MAX_TEXT), stderr: String(stderr).slice(0, MAX_TEXT), error: error?.message ?? null});
      });
    });
  },
};

export const tools: ToolSpec[] = [
  readFileTool,
  listFilesTool,
  searchDirectoryTool,
  writeFileTool,
  editFileTool,
  deleteFileTool,
  runCommandTool,
];
  • Check the seven-tool registry for TypeScript errors by running:
npm run typecheck

What does this check prove?

The type check validates the new tool schemas and executors against the existing ToolSpec type. Success confirms that the registry composes with the rest of the harness.

You should see the type check finish without TypeScript errors. The runtime now has every capability required for the final workflow.

Seeing a TypeScript error?

  • Check that the node:fs/promises import includes lstat, mkdir, unlink, and writeFile.
  • Check that the exported tools array contains all seven tool specifications.
  • Help me debug the consequential tool registry.
Wire approvals into the TUI

The harness decides when approval is required. The thin TUI adapter only displays the proposed action and resolves the pending Promise from the learner's response.

This boundary keeps TUI input out of the runtime. Another UI adapter can implement the same AgentHooks type without changing any tool.

  • Open src/tui/index.tsx in your preferred IDE.
  • Replace the import group and Respond type at the top with this code:
import {useState} from 'react';
import {Box, Text, render} from 'ink';
import TextInput from 'ink-text-input';
import type {AgentHooks} from '../types.ts';

// Let the TUI pass interface hooks into the harness boundary.
export type Respond = (
  message: string,
  hooks: AgentHooks,
) => Promise<string>;

What changes at the boundary?

The response boundary now accepts the same hooks used by the runtime. The TUI supplies user interaction while the harness keeps control of policy.

  • Replace the type declarations plus the labelFor() and colorFor() helpers with this code:
// Represent approval requests alongside the existing transcript roles.
type TranscriptEntry = {
  role: 'user' | 'agent' | 'event' | 'approval' | 'error';
  text: string;
};

type PendingApproval = {
  action: string;
  resolve: (approved: boolean) => void;
};

type AppProps = {
  respond: Respond;
};

function labelFor(role: TranscriptEntry['role']): string {
  if (role === 'user') return 'You';
  if (role === 'agent') return 'Agent';
  if (role === 'event') return 'Event';
  if (role === 'approval') return 'Approval';
  return 'Error';
}

function colorFor(role: TranscriptEntry['role']): string {
  if (role === 'user') return 'cyan';
  if (role === 'agent') return 'green';
  if (role === 'event') return 'yellow';
  if (role === 'approval') return 'magenta';
  return 'red';
}

How is approval represented?

A pending approval stores the proposed action and the resolver for its waiting promise. The label and color helpers make each decision visible in the transcript.

  • Inside App, find the three existing state declarations:
const [input, setInput] = useState('');
const [transcript, setTranscript] = useState<TranscriptEntry[]>([]);
const [isThinking, setIsThinking] = useState(false);
  • Inside App, replace the three existing state declarations with the approval-aware state and transcript helper below:
const [input, setInput] = useState('');
const [transcript, setTranscript] = useState<TranscriptEntry[]>([]);
const [isThinking, setIsThinking] = useState(false);
const [approval, setApproval] = useState<PendingApproval | null>(null);

// Add one entry without discarding the existing transcript.
function append(entry: TranscriptEntry): void {
  setTranscript(entries => [...entries, entry]);
}
  • Add the approval resolver below append() by pasting this code:
function settleApproval(message: string): boolean {
  if (!approval) return false;

  // Record the decision before releasing the waiting executor.
  const pending = approval;
  const approved = /^y(es)?$/i.test(message);
  setInput('');
  setApproval(null);
  append({
    role: 'approval',
    text: `${approved ? 'Approved' : 'Denied'}: ${pending.action}`,
  });
  pending.resolve(approved);
  return true;
}

How is a decision resolved?

The helper treats y and yes as approval. Every other response denies the action and resolves the waiting executor with false.

  • Inside submit(), find the message assignment and its existing guard:
const message = value.trim();

if (!message || isThinking) {
  return;
}
  • Insert the approval check before the existing guard:
const message = value.trim();

// Route input to a pending approval before accepting a new task.
if (settleApproval(message)) {
  return;
}

if (!message || isThinking) {
  return;
}
  • Add the hook adapter after setIsThinking(true) by pasting this code:
// Translate runtime events and approvals into TUI state.
const hooks: AgentHooks = {
  emit(text) {
    append({role: 'event', text});
  },
  approve(action) {
    return new Promise<boolean>(resolveApproval => {
      setApproval({action, resolve: resolveApproval});
    });
  },
};
  • Find the existing response call:
const response = await respond(message);
  • Pass the new hooks into the response boundary:
const response = await respond(message, hooks);

How do hooks reach the interface?

The emit() hook appends runtime events. The approve() hook pauses its executor until your next input resolves the promise.

  • Find the input <Box> near the bottom of App.
  • Replace that input block with the approval-aware version below:
{/* Show the pending action before collecting its decision. */}
{approval ? (
  <Text color="magenta">
    Approve "{approval.action}"? Type y to approve. Any other response denies.
  </Text>
) : null}

<Box>
  {isThinking && !approval ? (
    <Text color="yellow">Thinking...</Text>
  ) : (
    <>
      <Text color="cyan">{approval ? 'Approve> ' : '> '}</Text>
      <TextInput
        value={input}
        onChange={setInput}
        onSubmit={value => {
          void submit(value);
        }}
        placeholder={approval ? 'y/N' : 'Type a message'}
        focus={!isThinking || approval !== null}
      />
    </>
  )}
</Box>

What changes in the TUI?

The interface keeps the input focused while an approval is pending. The prompt names the exact proposed action before you accept or deny it.

  • Save src/tui/index.tsx.

✔️ Awesome, I've got everything!

Great. Double check that you saved src/tui/index.tsx.

ⓧ I'd like to double check the full code

import {useState} from 'react';
import {Box, Text, render} from 'ink';
import TextInput from 'ink-text-input';
import type {AgentHooks} from '../types.ts';

// Let the TUI pass interface hooks into the harness boundary.
export type Respond = (
  message: string,
  hooks: AgentHooks,
) => Promise<string>;

// Represent approval requests alongside the existing transcript roles.
type TranscriptEntry = {
  role: 'user' | 'agent' | 'event' | 'approval' | 'error';
  text: string;
};

type PendingApproval = {
  action: string;
  resolve: (approved: boolean) => void;
};

type AppProps = {
  respond: Respond;
};

function labelFor(role: TranscriptEntry['role']): string {
  if (role === 'user') return 'You';
  if (role === 'agent') return 'Agent';
  if (role === 'event') return 'Event';
  if (role === 'approval') return 'Approval';
  return 'Error';
}

function colorFor(role: TranscriptEntry['role']): string {
  if (role === 'user') return 'cyan';
  if (role === 'agent') return 'green';
  if (role === 'event') return 'yellow';
  if (role === 'approval') return 'magenta';
  return 'red';
}

function App({respond}: AppProps) {
  const [input, setInput] = useState('');
  const [transcript, setTranscript] = useState<TranscriptEntry[]>([]);
  const [isThinking, setIsThinking] = useState(false);
  const [approval, setApproval] = useState<PendingApproval | null>(null);

  function append(entry: TranscriptEntry): void {
    setTranscript(entries => [...entries, entry]);
  }

  function settleApproval(message: string): boolean {
    if (!approval) return false;

    // Record the decision before releasing the waiting executor.
    const pending = approval;
    const approved = /^y(es)?$/i.test(message);
    setInput('');
    setApproval(null);
    append({
      role: 'approval',
      text: `${approved ? 'Approved' : 'Denied'}: ${pending.action}`,
    });
    pending.resolve(approved);
    return true;
  }

  async function submit(value: string) {
    const message = value.trim();

    // Route input to a pending approval before accepting a new task.
    if (settleApproval(message)) {
      return;
    }

    if (!message || isThinking) {
      return;
    }

    setInput('');
    append({role: 'user', text: message});
    setIsThinking(true);

    // Translate runtime events and approvals into TUI state.
    const hooks: AgentHooks = {
      emit(text) {
        append({role: 'event', text});
      },
      approve(action) {
        return new Promise<boolean>(resolveApproval => {
          setApproval({action, resolve: resolveApproval});
        });
      },
    };

    try {
      const response = await respond(message, hooks);
      append({role: 'agent', text: response});
    } catch (error) {
      console.error('Agent response failed:', error);
      append({role: 'error', text: 'Something went wrong. Try again.'});
    } finally {
      setIsThinking(false);
    }
  }

  return (
    <Box flexDirection="column" padding={1}>
      <Text bold color="green">
        Agent Harness
      </Text>

      <Box flexDirection="column" marginTop={1}>
        {transcript.map((entry, index) => (
          <Box key={`${entry.role}-${index}`}>
            <Text bold color={colorFor(entry.role)}>
              {labelFor(entry.role)}:{' '}
            </Text>
            <Text>{entry.text}</Text>
          </Box>
        ))}
      </Box>

      {/* Show the pending action before collecting its decision. */}
      {approval ? (
        <Text color="magenta">
          Approve "{approval.action}"? Type y to approve. Any other response denies.
        </Text>
      ) : null}

      <Box>
        {isThinking && !approval ? (
          <Text color="yellow">Thinking...</Text>
        ) : (
          <>
            <Text color="cyan">{approval ? 'Approve> ' : '> '}</Text>
            <TextInput
              value={input}
              onChange={setInput}
              onSubmit={value => {
                void submit(value);
              }}
              placeholder={approval ? 'y/N' : 'Type a message'}
              focus={!isThinking || approval !== null}
            />
          </>
        )}
      </Box>

      <Box marginTop={1}>
        <Text dimColor>Ctrl+C to exit</Text>
      </Box>
    </Box>
  );
}

export function runTui(respond: Respond): void {
  render(<App respond={respond} />);
}
  • Confirm the adapter still satisfies the harness types by running:
npm run typecheck

What Does This Second Type Check Cover?

This type check covers the approval state and hook implementation against the TUI adapter and harness types. Success confirms that the TUI adapter remains replaceable.

You should see the type check finish without TypeScript errors. The TUI adapter can now pause a tool call and return your decision to the executor.

Approval state not compiling?

  • Check that PendingApproval stores both action and resolve.
  • Help me debug the TUI approval hook.
Approve the end-to-end workflow

Which shell runs the command?

The run_command tool uses /bin/sh on macOS and Linux. Windows uses the system command shell from process.env.ComSpec.

Shell syntax can vary by platform. The project test node app.js works on all three operating systems.

  • Start the approval-enabled harness by running:
npm run dev

What does this command start?

The development command starts the TUI with the complete harness behind it. The same TUI displays model turns, tool results, and approval prompts.

  • Run the prompt below:
Inspect the workspace. Find "hello agent". Edit app.js so its status is "agent loop complete". Run node app.js. Write summary.txt with exactly "Verified output: agent loop complete". Delete notes.txt. Finish by listing the workspace.
  • Enter y when the TUI asks to approve edit app.js.
  • Enter y when the TUI asks to approve run shell command: node app.js.
  • Enter y when the TUI asks to approve write summary.txt.
  • Enter y when the TUI asks to approve delete notes.txt.
  • Deny any action that does not match those four expected requests.

You should see approved tool results for the edit, command, write, and delete actions. The command result should contain agent loop complete.

The final list_files result should contain app.js and summary.txt. It should no longer contain notes.txt.

  • Open workspace/app.js from your preferred IDE's project explorer.

You should see const status = 'agent loop complete'; followed by console.log(status);.

  • Open workspace/summary.txt from your preferred IDE's project explorer.

You should see exactly Verified output: agent loop complete. That completes the full inspect, edit, execute, and verify loop.

Did the workflow stop or request another action?

  • Keep the TUI running while an approval prompt is visible.
  • If you're agent stops halfway through, prompt it to continue
  • Help me diagnose the incomplete agent workflow.

Secret mission

Add a Persistent Session Store

Your harness remembers conversations while its current process stays alive. Add a persistent session store so the harness can recall the workspace name after the TUI stops and restarts.

Clean Up Your Resources

Clean Up Your Resources

Choose whether to keep the local project, pause the TUI, or delete everything. Neither the local files nor requests routed through the OpenRouter Free Models Router create ongoing charges.

Resources you used:

  • The local custom-agent-harness project folder containing the source modules, workspace/app.js, workspace/summary.txt, .env, and .agent-session.json.
  • The local TUI process if it is still active in your terminal.
  • The regular OpenRouter API key stored through OPENROUTER_API_KEY in .env.

Keep everything running

No action is needed. Choose this if you are still testing the harness or plan to add more adapters and tools.

  • Leave the TUI running if you are still using it.
  • Keep the custom-agent-harness folder on your computer for future development.
  • Keep the regular OpenRouter API key active for future model requests.
  • Keep .env and .agent-session.json private because they contain an active credential and plaintext conversation history.

Pause - I'll come back to this later

Stop the TUI to free your terminal while retaining the code, workspace files, credential, and saved conversation history.

  • Return to the terminal window where the TUI is running.
  • Press Ctrl+C to stop the TUI.
  • Leave the custom-agent-harness folder in place so you can resume later.
  • Keep the OpenRouter project key active if you plan to make more model requests.
  • Review .agent-session.json before sharing the project because it contains the NextWork conversation history in plaintext.

Delete - I don't want to use this again

Deleting the project removes its source files, local credential, workspace files, and saved conversation history. Copy anything you want to keep before continuing.

What Deletion Removes

Deleting the OpenRouter key prevents this harness from authenticating future model requests with that credential.

Removing custom-agent-harness permanently deletes .env, .agent-session.json, the source code, and the final workspace files from your computer.

  • Return to the terminal window where the TUI is running.
  • Press Ctrl+C to stop the TUI.
  • Open the OpenRouter key settings page.
  • Select the regular project API key stored in .env.
  • Click Delete for that key.
  • Confirm the deletion when OpenRouter asks.

Future runs cannot use the deleted key. Choose your operating system below to remove the local project.

macOS

  • Remove the project folder from your Desktop by running this command:
rm -rf "$HOME/Desktop/custom-agent-harness"
  • List your Desktop to verify the folder is gone:
ls "$HOME/Desktop"

You should no longer see custom-agent-harness in the output.

Windows

  • Remove the project folder from your Desktop by running this command in PowerShell:
Remove-Item "$HOME\Desktop\custom-agent-harness" -Recurse -Force
  • List your Desktop to verify the folder is gone:
Get-ChildItem "$HOME\Desktop"

You should no longer see custom-agent-harness in the output.

Linux

  • Remove the project folder from your Desktop by running this command:
rm -rf "$HOME/Desktop/custom-agent-harness"
  • List your Desktop to verify the folder is gone:
ls "$HOME/Desktop"

You should no longer see custom-agent-harness in the output.

Nice Work!

Nice Work!

You did it! Your custom agent harness now coordinates model inference, seven local tools, workspace policy, approvals, events, and verification through the TUI.

You've learned how to:

  • Define explicit harness types for messages, tools, execution context, events, approvals, and run results. Build a model adapter that translates those types into requests for OpenRouter.
  • Build runAgent() as an agent loop that owns model turns and message state. Correlate each tool result through tool_call_id before returning the final answer.
  • Expose a seven-tool registry for inspecting, changing, executing, and verifying workspace files. Protect consequential actions with workspace boundaries, symbolic-link checks, structured failures, and approval hooks while the TUI stays focused on interaction.
  • Complete the optional Secret Mission by adding a persistent session store that recalls NextWork after the TUI stops and restarts.

Ready to quiz yourself?