Build a Readable TypeScript Agent Loop

Résumé

Pixel’s announcement features Agent Loop Starter, a small MIT-licensed TypeScript repository for building readable AI agent loops without an agent framework. It covers conversation history, allowlisted tools, raw JSON argument handling, abort signals, and model-call traces—practical details that make tool behavior and failures easier to inspect.

DEV Community

Build a readable TypeScript agent loop with tools and traces

An agent that calls tools needs a few concrete pieces: conversation history, a model interface, an allowlist of tools, and a decision about when to stop. Writing those pieces yourself makes the behavior visible. You can follow a failed tool call from its arguments to the error message sent back to the model. I put that approach into Agent Loop Starter, a small MIT-licensed TypeScript repository. It uses strict TypeScript, ESM, Zod v4, and the official OpenAI SDK. There is no agent framework between the loop and the tools. Start with the conversation The model receives messages and tool definitions. Its reply contains text, tool calls, or both. Each tool call has an ID, a name, and arguments encoded as JSON text. Keeping the arguments raw lets malformed JSON follow the same recovery path as other tool errors. The loop begins with one user message. Every model reply is appended as an assistant message. Tool results follow it, carrying the matching call IDs. On the next request, the model sees what it asked for and what actually happened. Here is the model-call section from src/agent.ts, inside while (steps < maxSteps): if (signal?.aborted) return stopped("aborted");
const step = ++steps;
const started = performance.now();
let response;
try {
try {
response = await withAbort(() => model.complete({ messages, tools: definitions, ...(signal ? { signal } : {}) }), signal);
} finally {
emit({ type: "model_call", step, durationMs: performance.now() - started });
}
} catch (error) {
if (signal?.aborted) return stopped("aborted");
throw error; // Transport/auth errors are different from recoverable tool errors.
}
withAbort stops waiting if the signal fires. It also passes the signal through to the model adapter. Authentication and transport failures reject the run, giving the caller a chance to decide whether to retry. The next decision is short: if (signal?.aborted) return stopped("aborted");
messages.push({ role: "assistant", ...response });
if (!response.toolCalls?.length) {
emit({ type: "final", step, durationMs: 0, output: response.content });
return { output: response.content, stopReason: "final", steps, trace };
}
A reply with tool calls enters a sequential execution loop. After appending all results, execution returns to the next model call. A reply without tool calls ends the run. Define tools once, with Zod A tool needs a description the model can read and validation the program can enforce. defineTool takes a Zod object schema, converts its input shape with z.toJSONSchema, and validates arguments before calling execute. The argument type is inferred from that schema. This is the calculator definition from src/tools/calculator.ts: export const calculator = defineTool({
name: "calculator",
description: "Calculate arithmetic with +, -, , /, %, parentheses, decimals and unary signs. No exponents. Uses JavaScript floating-point numbers.",
schema: z.object({ expression: z.string().min(1).max(512) }).strict(),
execute: ({ expression }) => ({ value: evaluateExpression(expression) }),
});
expression is a string inside execute. The schema also rejects extra fields. The arithmetic implementation is a recursive descent parser with precedence, parentheses, and unary signs. It never evaluates JavaScript. It rejects division by zero, excessive nesting, and non-finite results. The other examples return the current time for an IANA timezone through Intl, and search three built-in notes by keyword. All three run without external services. Tools return JSON values so results can go into conversation history and traces. Make failures part of the conversation A model can request an unknown tool, send broken JSON, or use the wrong argument types. A valid call can also fail during execution. These cases become tool error messages rather than crashing the loop. The execution boundary includes these lines: const tool = registry.get(call.name);
if (!tool) throw new Error(Unknown tool: ${call.name});
const args: u...
Build a Readable TypeScript Agent Loop
Powered by Readybot.io*

Les dernières actus de Pixel

Incident Response: Look Beyond the Red Alert

Pixel’s DEV Community announcement explores how teams can fixate on one failing service while overlooking the real cause of an outage, such as a full …

Sach: AI Fact-Checks WhatsApp Forwards in India

Pixel’s announcement introduces Sach, a tool that checks forwarded messages in English, Hindi, Telugu, and 14 other Indian languages against official sources. It gives cited …

Java 25 Removes SecurityManager: What to Fix

Pixel’s announcement explains how Java 24’s JEP 486 permanently disabled the SecurityManager, breaking test workarounds that intercept System.exit. It recommends returning exit codes or throwing …