Leanpub Header

Skip to main content

AI Agents in TypeScript

Minimum price

$19.00

$19.00

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

Buying multiple copies for your team? See below for a discount!

EPUB
About

About

About the Book

AI Agents in TypeScript

Building verifiable agent systems: the loop, the tool surface, determinism, and what a run costs.

Most agent tutorials stop when the demo works. This book starts there. An agent that answered correctly once is a coincidence; the engineering question is whether you can prove it will answer correctly again next Tuesday, on a different model, with a customer waiting. Every chapter builds one mechanism that makes that proof possible — and then breaks it on purpose to show the failure the mechanism exists to catch.

Twenty chapters, no framework, no abstractions you did not write yourself. Each chapter is a single file you can read in one sitting, a harness that runs it, and five exercises drawn from incidents that actually happen in production.

Who this is for

You write TypeScript and you have already shipped something that calls a model. You have noticed that the interesting problems are not prompt problems: they are state, contracts, replay, cost, tenancy, cancellation, deletion. You want the architecture that survives contact with real traffic, and you want it in code you can read rather than in a framework you have to trust.

The book assumes comfort with TypeScript and the terminal. It does not assume ML experience, and it does not assume you have built an agent before.

Why this book is different

Every listing runs. Not “illustrative code” — the listings are the files. A checker takes each of the 324 code listings in the manuscript, finds the source file it came from, and compares them byte for byte. The book cannot drift from the code without the build failing.

Recorded model turns, so the results are reproducible. The chapters ship their recordings. The whole suite runs offline in about fifteen seconds and produces the same output every time, on your machine, without a key and without a bill. When you want a live run, the API key is the only variable you have to set; the adapter does the rest.

The numbers in the prose were produced by the code in the chapter. When a chapter says a projection shrank a tool result by 92 percent, or that a retry refused a second refund, or that the ledger found two findings in a table, the harness computed it and the output is printed in the text.

Failures are first-class. Every mechanism is introduced by the failure it removes: a false green, an unexplained survivor, a residual copy after deletion, a cancelled run recorded as complete, a canary that never rolled back.

The companion repository

All the code is public, MIT-licensed, and organised to match the book, one directory per chapter:

https://github.com/edgarmilvus/ai-agents-typescript

git clone https://github.com/edgarmilvus/ai-agents-typescript.git
cd ai-agents-typescript
./run_offline.sh

The repository holds 103 demos and 39 harnesses across the twenty chapters, plus the shared lib/ adapter and the fixtures/ recordings they replay. There is no package graph to install: zero runtime dependencies, Node’s own TypeScript support, Node 24 or later.

  • run_offline.sh — every demo and every harness against recorded turns. No key, no network.
  • run_everything.sh — the single live pass, on a throwaway copy of the tree.

The README carries the full chapter map with a link to each directory, a Windows/PowerShell section, and the exact environment variables. If a listing in the book does not run, the repository has an issue form for it — the promise is that specific.

How each chapter is built

Every chapter follows the same structure, so you always know where you are:

  1. Theoretical foundations — the mechanism, the vocabulary, and the failure it removes, before any code.
  2. Basic code example — the smallest complete version, one file, read line by line.
  3. Common pitfalls — the ten mistakes that version invites, each tied to the exercise that catches it.
  4. Advanced application implementation — the same mechanism under real constraints: several files, a real adversary, a real budget.
  5. How to run it — the harness, its cases, and what a green run proves.
  6. Reading a transcript — what the recorded output actually shows, turn by turn.
  7. Five practical exercises on real cases — each one a genuine incident shape, not a toy variation.
  8. Solutions to the exercises — a full worked solution per exercise, with the reasoning, the code, and the trade-off it rejects. Every solution is accompanied by a five-part instructor’s analysis: what the exercise is really testing, why the obvious answer is wrong, what the correct design is, how it fails at scale, and how to grade a reader’s attempt.
  9. What this chapter established — the invariant the chapter leaves behind.

That is 100 exercises, 100 worked solutions and 100 instructor’s analyses across the book, all backed by runnable code.

Length

The manuscript is twenty chapters, 76 diagrams and figures, and more than a thousand fenced code and terminal blocks. Printed at a standard technical-book density it would run to well over 500 pages.

Table of contents

Chapter 1 — The Loop, the State, the Tool Surface The agent loop, a typed transcript, a tool registry, replay, and the three ways a tool call fails.

Chapter 2 — Contracts: Schemas, Descriptions and the Repair Loop Schema validation, tool descriptions that teach the model what to send, and the bounded repair loop when it sends the wrong thing.

Chapter 3 — The Protocol Boundary: Discovering, Scoping and Surviving MCP Tools An MCP client and server, tool discovery, scoping, and what survives when the server crashes mid-call.

Chapter 4 — Recordings: Making a Test Mean Something Recording and replaying model turns, divergence detection, and why a test that never diverges tests nothing.

Chapter 5 — Grading: What “Right” Means When the Model Varies Rubrics, graders, and the difference between a check and a judgement.

Chapter 6 — Statistics: How Often, and How Much of That Number Is Noise Sample sizes, confidence intervals, and the number you are allowed to quote.

Chapter 7 — The Judge Is a Model: Auditing Renders When the Grader Has a Variance Model-as-judge, its own noise, its cost, and the ledger that replaces a score.

Chapter 8 — Which Part Moved: Attributing a Failed Run to the Component That Caused It Attribution: prompt, tool, model, or data — bisecting a failure to the component that moved.

Chapter 9 — Who Tests the Tests: Mutation, Survivors and a Gate That Can Fail Mutation testing of the suite itself, survivors, and a gate that is allowed to say no.

Chapter 10 — The Traffic You Did Not Write: Shadow Runs, Drift and a Canary That Rolls Back Shadow traffic, drift detection, and a canary that actually reverses a rollout.

Chapter 11 — The Handoff: What Crosses the Seam When One Agent Calls Another Multi-agent handoff as a typed seam: what is passed, what is dropped, and what is re-derived.

Chapter 12 — The Tool Is an Attack Surface: Injections, Taint and the Policy at the Boundary Prompt injection, taint tracking, allowlists, and the policy that lives outside the tool.

Chapter 13 — The Human Boundary: Approvals, Durable Runs and Doing It Exactly Once Approvals, durable execution, resumption, and exactly-once side effects across a restart.

Chapter 14 — What the Agent Keeps: Memory, Retrieval and the Cost of Remembering Memory, retrieval, summarisation, and the bill that arrives when an agent remembers everything.

Chapter 15 — The Budget Is a Design Constraint: Routing, Caching and What the Loop Costs Token budgets, model routing, caching, and the cost model that belongs in the design, not the invoice.

Chapter 16 — The Loop That Does Not Close: Incidents, Fixtures and Continuous Evaluation The incident pipeline: ten incidents, what each one owes, and the ledger that tracks the debt.

Chapter 17 — One Agent, Many Customers: Tenancy and the Leak You Cannot See Tenancy, isolation, and the cross-tenant leak that passes every functional test.

Chapter 18 — The Customer Who Left: Deletion and the Data That Outlives It Deletion across caches, logs, recordings and embeddings — and the residual copy that survives it.

Chapter 19 — The Customer Who Hung Up: Streaming, Cancellation and the Cost of Silence Streaming, cancellation, partial writes, and the run that must not be recorded as complete.

Chapter 20 — The Model That Changed Underneath: Portability and the Contract at the Boundary Ports and adapters, conformance tests, and what a model swap is allowed to change.

What you take away

A loop you wrote and can debug. A transcript that is the state. Contracts at every boundary: tool, protocol, handoff, model. Tests that replay instead of hope. Numbers with intervals attached. A policy that lives outside the model. A budget that is a design parameter. And a ledger that tells you, after an incident, what now exists that did not exist before.

The last chapter is not about agents at all. It is about the loop that does not close: the system that keeps working after the chapter that built it has been closed.

Team Discounts

Team Discounts

Get a team discount on this book!

  • Up to 3 members

    Minimum price
    $24.00
    Suggested price
    $47.00

Bundle

Bundles that include this book

Author

About the Author

Edgar Milvus

A veteran software engineer with 20 years of experience, I have dedicated my career to the art of automation. My philosophy is simple: programming should eliminate repetitive chores to unlock human creativity. This journey began early on with the development of custom code-generation tools and has evolved into a deep mastery of LLMs and their APIs. Today, I specialize in architecting AI-driven solutions that handle everything from complex coding and security tasks to advanced knowledge retrieval, transforming the way we interact with technology

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub