Skip to content

A first program

This page builds a program in which a model reads a text file and summarizes it in one sentence:

bun main.ts notes.txt <model-id>

Install the kit and the model packages first.

The program has one class of each kind a harness needs:

File Kind What it does
TextFile.ts Capability Reads lines of the file
schemas.ts, types.ts The zod schemas and the types
ReadLinesTool.ts Tool Lets the model read lines
SummaryHarness.ts Harness The model with the tool
SummaryStep.ts Flow step Runs the harness
SummaryWorkflow.ts Workflow Runs the flow step and gives the summary
main.ts Starts the program
tsconfig.json The TypeScript settings

A capability is the kind of class that reaches outside the program. This one reads a file.

  • permission is the word a run must be given before a tool gets this capability.
  • scope: "run" means it belongs to one run.
  • @RunValue("path") gives it the path of the workflow’s input. So it reads the one file the run is about, and the model cannot name another file.

TextFile.ts

import { Capability, CapabilityBase, RunValue } from "@kerpetensh/harness-kit";
@Capability({
name: "text-file",
description: "Reads lines of the text file the run is about.",
permission: "files:read",
scope: "run",
})
export class TextFile extends CapabilityBase {
@RunValue("path")
private readonly path!: string;
public async lines(from: number, count: number): Promise<string[]> {
const text = await Bun.file(this.path).text();
return text.split("\n").slice(from - 1, from - 1 + count);
}
}

Two zod schemas: what the tool takes and what the harness answers.

schemas.ts

import { z } from "zod";
export const readLinesInput = z.strictObject({
from: z.int().min(1),
count: z.int().min(1).max(200),
});
export const summaryOutput = z.strictObject({ summary: z.string() });

SummaryInput is the input of the workflow. The model adapter and the logger come in with it, so the program decides both in one place.

types.ts

import type { HarnessLogger, LlmAdapter } from "@kerpetensh/harness-kit";
import type { z } from "zod";
import type { readLinesInput, summaryOutput } from "./schemas";
export type ReadLinesInput = z.infer<typeof readLinesInput>;
export type Summary = z.infer<typeof summaryOutput>;
export interface SummaryInput {
readonly path: string;
readonly llm: LlmAdapter;
readonly log: HarnessLogger;
}

A tool is something the model can call.

  • It takes the capability with @Use.
  • The kit checks the input against the schema before execute runs, so execute gets parsed data.
  • A ToolError is an answer to the model and does not fail the program. The model reads the message and can go on.

ReadLinesTool.ts

import { Tool, ToolError, Use } from "@kerpetensh/harness-kit";
import { readLinesInput } from "./schemas";
import { TextFile } from "./TextFile";
import type { ReadLinesInput } from "./types";
@Tool({
name: "read_lines",
description: "Returns up to 200 lines of the file, starting at line `from`. The first line is 1.",
input: readLinesInput,
})
export class ReadLinesTool {
@Use(TextFile)
private readonly file!: TextFile;
public async execute(input: ReadLinesInput): Promise<string> {
const lines = await this.file.lines(input.from, input.count);
if (lines.length === 0) throw new ToolError(`the file has no line ${input.from}`);
return lines.join("\n");
}
}

A harness is a model with tools on one request.

  • It lists its tools and every permission those tools use.
  • Its two type arguments are the request, here the path, and the answer.
  • With the kit’s model adapters, instructions is the system text and context is the first user message.
  • After the model has stopped calling tools, the harness sends finalizeRequest and reads the answer by the output schema. On some providers the model’s last text is already the answer and no request is sent; see The final answer.

SummaryHarness.ts

import { Harness, HarnessBase } from "@kerpetensh/harness-kit";
import { ReadLinesTool } from "./ReadLinesTool";
import { summaryOutput } from "./schemas";
import type { Summary } from "./types";
@Harness({ name: "summary", tools: [ReadLinesTool], permissions: ["files:read"] })
export class SummaryHarness extends HarnessBase<string, Summary> {
protected readonly output = summaryOutput;
protected readonly finalizeRequest = "Give the summary now.";
protected instructions(): string {
return "Read the file with read_lines, then summarize it in one sentence.";
}
protected context(path: string): string {
return `The file is ${path}.`;
}
}

A flow step is one step of a workflow. It takes the harness with @Inject, runs it and returns the fields it adds to the state.

  • The limits are absolute times. The model may call tools until stepDeadline, and its final answer must be there by finalizeDeadline.
  • run.value is undefined when the model gave no final answer.

SummaryStep.ts

import { Inject } from "@asenajs/ioc";
import { FlowStep, FlowStepBase } from "@kerpetensh/harness-kit";
import { SummaryHarness } from "./SummaryHarness";
import type { SummaryInput } from "./types";
@FlowStep({ name: "summarize", description: "Has the model read the file and summarize it." })
export class SummaryStep extends FlowStepBase {
@Inject(SummaryHarness)
private readonly harness!: SummaryHarness;
public async execute(state: SummaryInput) {
const deadline = Date.now() + 60_000;
const run = await this.harness.run(state.path, {
llm: state.llm,
limits: { maxToolCalls: 10, stepDeadline: deadline, finalizeDeadline: deadline + 30_000 },
now: Date.now,
log: state.log,
});
if (run.value === undefined) throw new Error(`the model gave no summary: ${run.error ?? run.partialReason}`);
return { summary: run.value.summary };
}
}

A workflow runs its flow steps in order over one state and builds the result from the final state.

  • Its three type arguments are the input, the final state and the result.
  • After<typeof SummaryStep> is the state after that step ran: what the step took plus what it added.

SummaryWorkflow.ts

import { type After, Workflow, WorkflowBase } from "@kerpetensh/harness-kit";
import { SummaryStep } from "./SummaryStep";
import type { SummaryInput } from "./types";
@Workflow({ name: "summary", description: "Summarizes a text file.", steps: [SummaryStep] })
export class SummaryWorkflow extends WorkflowBase<SummaryInput, After<typeof SummaryStep>, string> {
protected finish(state: After<typeof SummaryStep>): string {
return state.summary;
}
}

The program lists its components, starts the container and runs the workflow. AiSdkAdapter.fromSettings builds the model adapter from a provider, a model id and an API key.

main.ts

import { HarnessApplication } from "@kerpetensh/harness-kit";
import { AiSdkAdapter } from "@kerpetensh/harness-kit/ai-sdk";
import { ReadLinesTool } from "./ReadLinesTool";
import { SummaryHarness } from "./SummaryHarness";
import { SummaryStep } from "./SummaryStep";
import { SummaryWorkflow } from "./SummaryWorkflow";
import { TextFile } from "./TextFile";
const [path, model] = process.argv.slice(2);
if (path === undefined || model === undefined) throw new Error("usage: bun main.ts <file> <model-id>");
const llm = AiSdkAdapter.fromSettings({
provider: "openrouter",
model,
apiKey: process.env.OPENROUTER_API_KEY ?? "",
zdr: false,
});
const quiet = () => {};
const log = { debug: quiet, info: quiet, warn: (message: string) => console.error(message) };
const app = await HarnessApplication.create({
components: [TextFile, ReadLinesTool, SummaryHarness, SummaryStep, SummaryWorkflow],
});
await app.start();
try {
const workflow = await app.resolve(SummaryWorkflow);
console.log(await workflow.run({ path, llm, log }));
} finally {
await app.stop();
}

Run it from the directory that holds tsconfig.json:

OPENROUTER_API_KEY=<key> bun main.ts notes.txt <model-id>

It prints the one-sentence summary. With an empty key, fromSettings throws the API key is empty before anything starts.

The example uses OpenRouter. Any provider of Models works the same way, also a model server on your machine: provider: "openai" with its baseUrl, such as http://localhost:11434/v1 for Ollama.

  1. HarnessApplication.create built the container from the five classes. Every class a list names must be among the components: the tool the harness lists, the capability the tool takes, the flow step the workflow lists.
  2. app.start() checked the wiring. The harness lists files:read, the permission of the capability its tool uses. Without it the start stops with a WiringError.
  3. workflow.run opened a run. No permission group was named, so the run’s grant gives every permission. The input became the values of the run, and that is where @RunValue("path") reads the path from.
  4. The flow step ran the harness. On the first tool call the run built TextFile, once, and the tool’s @Use field read that instance.
  5. The model stopped calling tools, the harness asked for the final answer, and the flow step put the summary into the state.
You want to Read
Make the workflow a command with flags and an exit code Workflows, commands and the CLI
Give a run less than every permission Runs and permissions
Read what a harness run reports when it hits a limit Tools, harnesses and contexts
Test the program without a model Testing