A small TypeScript agent harness with loop guards and an eval that scores a model with confidence intervals, plus a token cost ledger and four measured ways to cut cost.
A replay of real output from npm test (187 of 187 pass) and npm run mutants (18 guards removed one at a time, all 18 caught), captured 2026-10-24. Full quality mp4.
Running agents on small local models fails in quiet ways. A server answers 200 with half the prompt cut. A model drops a tool call. A big tool result is trimmed and the model invents the missing part. This repo is a clean room harness that turns each of those failures into code you can test. It adds an eval runner that says how often a model really gets a task right, with an interval. The runner keeps broken trials out of the score.
The only runtime dependency is zod, next to the Node standard library. There is no framework and no build step: Node 22.18 or newer runs the TypeScript files directly (type stripping), and TypeScript is used for npm run typecheck only.
| # | Lesson | Where it lives | Tests that pin it |
|---|---|---|---|
| 1 | A server can answer 200 after silently cutting the prompt. Compare the prompt token count it reports with what was sent, and report a mismatch. Never swallow it. | src/loop.ts (truncation check) |
tests/loop.test.ts "truncation: ..." (four tests: suspected, fail mode, honest count raises nothing, unreported count is not accused); table and simulation tests with truncated prompt report |
| 2 | Sampling temperature is an explicit per model setting. Unset sends nothing, 0 sends 0. The eval measures the difference. | src/model.ts, eval/engine.ts |
tests/loop.test.ts "temperature is explicit"; tests/ollama_client.test.ts "request: stream false, num_ctx always sent, temperature only when set, 0 is sent as 0" |
| 3 | A tool result over a byte cap becomes head, a visible marker, tail. The full text stays retrievable through read_result. A stub is never the only copy. |
src/context.ts |
tests/context.test.ts "byte cap: ..." and "read_result: ..."; tests/loop.test.ts "byte cap end to end"; the stub invariant in tests/simulation.test.ts |
| 4 | Offer fewer tools. The list per turn is narrowable, and a tool that was not offered is refused like an unknown one. | src/tools.ts (rank), src/loop.ts (toolsPerTurn) |
tests/loop.test.ts "narrowing: ..." and "a registered tool that is not offered this turn is rejected"; tests/tools.test.ts "registry rank" |
| 5 | An empty reply with finish_reason: length is not nudged with a longer prompt. Retry once with narrower tools, same messages. |
src/loop.ts |
tests/loop.test.ts "empty reply with finish_reason length: ..." (three tests) |
| 6 | Loop guards: a hard step limit, a repeated identical tool call guard, a total time budget (plus a per call timeout and retries only on transport errors, timeouts and 5xx, with exponential backoff and jitter). | src/loop.ts, src/retry.ts |
tests/loop.test.ts "step limit", "repeat guard", "timeout", "time budget", "retry", "backoff" (the step limit, repeat guard, timeout, time budget and retry each have a negative test and a positive control; backoff has growth and ordering tests); tests/table.test.ts |
| 7 | Structured output is validated against a schema. On failure it is re-asked once with the exact validation error. After that the run fails closed with a reason and returns no data. | src/structured.ts |
tests/structured.test.ts (eight tests); the structured simulation in tests/simulation.test.ts |
Every transition of the run (running, tool_pending, done, failed(reason)) is written to an event log. The tests assert on that log.
npm install
npm run typecheck
npm test # unit, table, simulation tests
npm run mutants # remove one guard at a time, the suite must go red
npm run eval:scripted # deterministic faults, no model needed
npm run eval:ollama -- qwen3.5:4b # a real local model: needs Ollama running and `ollama pull qwen3.5:4b` done first
npm run cost-report -- --ledger bench/results --month 2026-11 --task-depth 2 # the monthly cost report from the committed ledgers
npm run bench:table # the tables below, printed from the saved result files
GEMINI_API_KEY=... npm run bench:caching # rerun a benchmark (GROQ_API_KEY for bench:trimming and bench:routing)
GEMINI_API_KEY=... npm run bench:batching -- --model gemini-3.1-flash-lite --tag mine
Eval flags: --trials 10, --configs temp0-tools5,temp0-tools24, --budget-min 8 (stop cleanly) and --resume. Each run writes a dated JSON report under eval/reports/.
The last full local run (Node 24.18, 2026-11-28) gave these counts. The GIF above is the earlier 2026-10-24 capture.
npm test: 286 tests, all passing. That includes 66 generated table tests (11 fault types by 3 positions by 2 step limits), 20 seeded loop simulations of 50 scripted steps with random faults and 20 seeded structured output simulations of 50 requests.npm run mutants: 62 mutants, 62 caught, 0 survived, 0 stale anchors. A mutant is one broken guard in a temp copy. Eighteen are loop guards, such as the step limit, repeat guard, timeouts, byte cap, truncation and schema checks. Forty four are in the cost work: pricing, report filters, the two provider clients, the router, prompt layout, the summary cut, the scoring rule and batching. An anchor that no longer matches the source exactly once fails the run. So does a red baseline.npm run eval:scripted: 160 trials with seeded faults. It checks the scoring pipeline (PASS, FAIL and ERROR all occur, errors stay out of the denominator). Its rates say nothing about any model.
A case is a prompt, the tools a correct run must call, and a check on the final answer. The runner runs N trials per case per configuration (default 10) and reports pass counts with 95 percent Wilson score intervals. A rate is never printed without its interval and counts.
- PASS and FAIL are scored. A wrong answer, a skipped required tool call, a loop on one call and a step limit are FAIL.
- ERROR is a trial that measured nothing about the model. The server failed, a call timed out, a 4xx came back, or the reply was empty. ERROR is counted apart and is never a zero. The denominator is PASS plus FAIL.
- Four configurations cross temperature with the tool list. Temperature is unset (which sends no value) or 0. The tool list is 5 tools or 24, and the extra tools are named decoys that do nothing.
- Four cases:
arithmetic,lookup,two-stepandcut-result.two-stepmeans look something up, then calculate. Incut-resultthe answer sits in the tail of a 12 KB tool result that the harness cut to head and tail. The first three are the tool-choice cases. A correct number without the tool call is a FAIL, because dropped tool calls are what the eval is for.
Ollama 0.40.9, qwen3.5:4b (Q4_K_M), N=10 and N=30 per cell, 0 errors. With temperature unset, 14 of 180 tool-choice trials failed because a required tool call was never made, and with temperature 0 that happened in 0 of 180. Fewer tools did not reproduce on this model. Temperature 0 scored 0 of 30 on cut-result in both tool lists, so it is not better for everything. The tables, the per case numbers and what they do not show are in docs/ollama-results.md.
MeteredClient wraps any model client and writes one ledger line per call: agent, task, model, and the prompt, cached and output tokens the provider reported. Cost is worked out when a report is built, from pricing/prices.json (list prices, each with its source link and the date it was read, 2026-11-27). npm run cost-report prints cost per agent and per task for a month, and a Hermes Agent scheduled job runs it every month (docs/hermes-cron.md). Dollars are list price times tokens, not an invoice.
Four techniques were measured against a baseline on a fixed task set, with the same model and temperature 0, on 2026-11-27. The full tables, the raw files and the method are in docs/cost-and-token-savings.md.
| Technique | Baseline | After | Cost change | Answers |
|---|---|---|---|---|
| Provider caching: header moved behind the stable block | request header in front of a 7,700 token handbook | same words, header in the user message | 31.4%, 27.2%, 41.7% and 8.7% lower on four models, 0.0% on a fifth | same answer in 8 of 8 pairs on the one run that kept answers |
| Trim a 30 ticket log to a token budget | full log, 12 questions | oldest messages dropped | 51.3% lower | 5 of 12 against 12 of 12 |
| Rolling summary of the older log | full log | summary plus newest 12 messages | 44.1% lower | 10 of 12 against 12 of 12 |
| Cheap model first, escalate on doubt | strong tier for all 32 tasks | cascade | 96.2% lower | 29 of 32 against 32 of 32, no task escalated |
| Classifier, then the same cascade | same | complex prompts straight to the strong tier | 30.7% lower | 32 of 32 against 32 of 32 |
| Batch 12 questions into one request | one request per question, handbook each time | one request, handbook once, numbered answers | 88.7% lower | 12 of 12 against 12 of 12 |
Limits in plain words:
- The sets are small: 8 question pairs per caching model, one log of 30 tickets with 12 questions, 32 routing tasks, 12 batching questions. The intervals are wide and are in the docs.
- One machine, one day, free accounts. A rerun can land elsewhere, most of all where a provider's cache decides.
- Provider caching is best effort. One of the five models reported no cached tokens under either layout.
- The classifier's cue words were written after reading these generated tasks, and the escalation rule never fired because the cheap model never doubted itself.
- Two caching runs carry no accuracy figure, and the docs say why.
- Batching puts every answer in one reply, so a cut reply loses all of them: tests cover that, the real run did not hit it. Four earlier attempts ran out of free quota (partial).
hermes/ runs Hermes Agent 2026.9.24 as a small team of agents. Slack and ClickUp ran in real free workspaces, on one machine, with a 9B local model. WhatsApp ran against a local stand-in, because a real account needs a phone number. Hermes' code ran unmodified. Raw runs: docs/test-runs/.
- Gateways: the Slack gateway answered a message, a cron job posted the cost summary, and three agents handed work on.
- Agents: the hand-off, a Sheets skill, a ClickUp skill, an MCP server.
- Memory: a fact told in one session, used in a fresh process. Over 5 repeats on a 9B model the reminder named the owner from Hermes' memory 5 times and used the remembered format 2 times. The control named her 0 times.
- Hardening: a non-root container, a mode 600 env file, a read only root, a restart after a crash.
- respond.io: a Telegram bot on a trial workspace, and a customer message arrived in its inbox. No workflow or AI Agent built there.
- A small, focused harness for tool calling, loop guards, context budgeting, structured output and evals. Streaming, parallel tool calls, persistence and multi agent orchestration are the next steps.
- The token count is an estimate (
ceil(chars / 4)). It is only used to notice a gross mismatch with what the server reports, and to decide when to trim. A mismatch means less than 60 percent of the estimate, with at least 100 estimated tokens. A real tokenizer will differ, and a server that reports no count is not accused. - The Ollama numbers come from one machine, one model, one quantization, one day, four small cases and N of 10 and 30.
--ollama <model>repeats the run on another model or size. - Truncation is detected and the default is to warn.
onTruncation: "fail"fails the run closed. Scripted tests force a truncation. - Passing a case is a string check on the final answer plus the tool trace.
- Tested on Node 24.18 locally and on the latest Node 22 in CI (v22.23.3 on the last run; type stripping needs 22.18 or newer). The first Linux CI run found a bug Windows had hidden: the call timeout timer was unref'd, so a hung model call could end the process with no error. It is fixed and a test runs the hang in its own process.
- The loop and the eval target local models through Ollama. Two more clients, for Gemini and for the chat completions format Groq and OpenRouter speak, read real usage numbers for the cost work. They are checked against recorded response shapes, not by tool loops. P2P networking and hosted agent orchestration sit outside the harness.
src/model.ts ModelClient, OllamaClient (HTTP, explicit options, AbortSignal timeout), ScriptedModel with faults
src/loop.ts the agent loop, run state machine, event log, guards
src/retry.ts retry with exponential backoff and jitter, transport errors, timeouts and 5xx only
src/context.ts token estimate, byte cap stub, read_result, trimming that keeps tool call pairs
src/structured.ts schema checked output, one re-ask, fail closed
src/tools.ts calculator (no eval), lookup, decoys, registry with ranking and narrowing
src/gemini.ts GeminiClient: reads cachedContentTokenCount and counts thinking tokens as output
src/openai_compat.ts chat completions client for Groq and OpenRouter, reads cached_tokens
hermes/ Hermes skills, tools, stand-ins, an MCP server, the container
src/cost/ price table loader, usage ledger, monthly report CLI, Hermes session import
src/techniques/ prompt layout, history trimming and summary, model router, batching
pricing/prices.json list prices with a source link for each model and the date they were read
bench/ fixed task sets, benchmark runners, result files, the table printer
skills/cost-report/ the Agent Skill that the scheduled Hermes job runs
eval/ cases, runner, Wilson intervals, dated JSON reports
tests/ node:test suites, table and seeded simulation tests, mutants.mjs
MIT, see LICENSE.
