Agent loops fail in a few boring, expensive ways. The model calls the same tool with the same arguments again and again. Two calls ping-pong (search, read, search, read). The model repeats itself while nothing new comes back. A provider ends a final, text-only step with a finish reason the loop does not recognise as "done", so some frameworks re-send the same request until the step limit. Or the run quietly burns through a token, time or cost budget.
agent-loopguard is a small, framework-agnostic guard. You feed it one step at a time; it tells you whether to continue or stop, and why, as a typed, serialisable verdict. Zero runtime dependencies, ESM and CommonJS, Node 18 or newer.
npm install @osama.ansar/agent-loopguardimport { createGuard, explain } from '@osama.ansar/agent-loopguard';
const guard = createGuard();
for (let i = 0; ; i++) {
const step = await runOneModelStep(); // your code: call the model, run its tools
const verdict = guard.check({
text: step.text,
finishReason: step.finishReason,
toolCalls: step.toolCalls.map((c) => ({ name: c.name, args: c.args, result: c.result })),
usage: step.usage, // { inputTokens, outputTokens, totalTokens, costUsd } - whatever you have
});
if (verdict.stop) {
console.log(explain(verdict));
break;
}
}A stopped run looks like this (from npm run example:loop, a simulated agent that never changes its mind):
Stop [REPEATED_TOOL_CALL] Tool "search" was called 3 times in a row with identical arguments: search({"query":"agent loop detection"}).
Hint: The model keeps issuing the same call. Check that the tool result gives it something to act on, and that the prompt says what to do when a tool fails.
Every detector can be tuned or switched off with false. All defaults are listed here; none of them are tuned against real traffic, so treat them as sensible starting points.
| Detector (option) | Stops when | Defaults |
|---|---|---|
maxSteps |
the number of steps recorded reaches the limit | 50 |
tools.<name>.maxCalls |
a tool is called more often than its cap allows (the call after the Nth) | no caps unless you set them |
repeatedToolCall |
the same tool is called with canonically-equal arguments N times in a row | threshold: 3, requireIdenticalResults: false, ignoreErrors: false; per tool: repeatThreshold, polling |
repeatedToolCall.window |
the same call occurs N times among the newest K calls, even with other calls in between (off unless you set it) | no window unless you set window: { size, maxRepeats } |
oscillation |
the tail of the tool-call sequence is a cycle of 2..maxPeriod calls repeated repeats times |
maxPeriod: 3, repeats: 3, includeResults: false |
noProgress |
N consecutive steps have the same normalised text and no new tool outcome | threshold: 3 |
finishReason |
the finish reason is terminal, or is an unfamiliar one under the otherPolicy |
terminal: ['stop', 'length', 'content-filter', 'error'], otherPolicy: 'stop-if-text-only' |
budget |
a cumulative token, cost or duration total reaches its limit (and warns before that, if you set warnAt) |
no limits unless you set them |
Plus per-tool policies (tools), a custom hook for your own rules and custom signature functions for what counts as "the same" (all below). Around the detectors sit: preflight, which asks whether a call would trip a rule before you run it; early warnings, one step before a rule stops the run; feedback, a short message for every fault that is safe to send to the model; report() and onDecision; createToolRunner, which runs your tool executors through preflight and check; and toJSON / fromJSON, which carry a run into another process.
import { createGuard, explain, runAgentLoop } from '@osama.ansar/agent-loopguard';
const result = await runAgentLoop({
guard: createGuard({ maxSteps: 25, budget: { maxCostUsd: { limit: 0.5, warnAt: 0.8 } } }),
signal: controller.signal, // optional AbortSignal
step: async (i) => {
const response = await callModelAndRunTools(i); // your code
return {
text: response.text,
finishReason: response.finishReason,
toolCalls: response.toolCalls, // [{ name, args, result?, error? }]
usage: { inputTokens: response.inputTokens, outputTokens: response.outputTokens, costUsd: response.costUsd },
};
},
onVerdict: (verdict) => {
if (!verdict.stop && verdict.warnings) console.warn(verdict.warnings.map((w) => w.detail));
},
});
if (!result.completed) console.log(explain(result.verdict));runAgentLoop calls step(0), step(1), ... until the agent is done or the guard says stop. A step is "done" when it sets done: true, or, if done is not set, when it has no tool calls. It returns { steps, verdict, completed, aborted }.
import { generateText, stepCountIs } from 'ai';
import { createGuard, explain, toStopWhen } from '@osama.ansar/agent-loopguard';
const { text } = await generateText({
model,
tools,
prompt,
stopWhen: [
toStopWhen(() => createGuard(), { onStop: (verdict) => console.log(explain(verdict)) }),
stepCountIs(20), // keep your own cap too if you like
],
});toStopWhen is idempotent: on every call it builds a fresh guard from your factory and replays the whole steps array, so the answer depends only on the steps it is given (not on how many times the SDK calls it) and nothing leaks between runs. You can pass GuardOptions instead of a factory.
What was verified. The adapter is type-checked against the real StopCondition type and exercised end to end in generateText with the AI SDK's own MockLanguageModelV4 (offline, no provider involved), using [email protected]: a repeating tool call is stopped after the third step, a healthy multi-step run is not stopped, token budgets are enforced from the usage the SDK reports, and tool results and errors are mapped onto the call that produced them. That test needs Node 22 or newer because ai does; it is skipped on older Node. Not verified: real providers, and AI SDK major versions other than 7. The adapter reads the field names toolCalls[].input, toolResults[].output, usage and performance.stepTimeMs, and also accepts the older args and result names; those older shapes are only tested against hand-written fakes, so treat that support as "structurally compatible; verified against the documented shape".
import { createGuard, explain, withGuard } from '@osama.ansar/agent-loopguard';
const steps = withGuard(agentSteps(), createGuard()); // any (async) iterable of steps
for await (const step of steps) render(step);
if (steps.verdict?.stop) console.log(explain(steps.verdict));The step that triggers the stop is still yielded (it already happened); iteration ends right after and the source iterator is closed.
import { createGuard } from '@osama.ansar/agent-loopguard';
const guard = createGuard({
custom: (history, step) => {
const deletes = history.flatMap((s) => s.toolCalls ?? []).filter((c) => c.name === 'delete_file').length;
return deletes > 5
? { stop: true, code: 'TOO_MANY_DELETES', detail: `${deletes} delete_file calls in one run.`, evidence: { deletes } }
: undefined;
},
});A custom detector receives the full history (the current step last) and runs after the built-in ones. Return undefined or { stop: false } to continue. Its verdicts have reason: 'custom'. If it throws, the error propagates out of guard.check. A custom detector can also return feedback: '...' (text for the model); without it, a custom verdict has no feedback.
import { createGuard } from '@osama.ansar/agent-loopguard';
const guard = createGuard({
tools: {
search: { maxCalls: 8 }, // at most 8 searches in a run
job_status: { polling: { maxIdenticalResults: 6 } }, // same args are fine while the result changes
deploy: { repeatThreshold: 2 }, // two identical deploys in a row is already too many
think: { ignore: true }, // bookkeeping: never counts as a loop or as progress
rm: { maxCalls: 0 }, // forbidden outright
},
});| Policy field | Meaning |
|---|---|
maxCalls |
An integer >= 0: the most calls to this tool in one run. maxCalls: 3 allows three; the fourth stops the run with reason tool-limit, code TOOL_CALL_CAP (and preflight refuses it before it runs). 0 forbids the tool. |
repeatThreshold |
An integer >= 2 replacing the global repeatedToolCall.threshold for this tool. |
polling |
true (or { maxIdenticalResults?: number }): identical arguments are legitimate while the results keep changing. The repeated-call rule applies to this tool only when the result is identical too, after maxIdenticalResults identical outcomes in a row (default: the tool's repeatThreshold, else the global threshold, so raise it for jobs that stay "pending" for a while). Calls without a result compare equal. |
warnAt |
With early warnings: the number of calls (1 to maxCalls) at which the warning about the cap starts, or false for none. Needs maxCalls. See Early warnings. |
ignore |
true leaves the tool out of repeat, oscillation and no-progress detection and out of maxCalls. Takes precedence over the other fields. |
Tool names that are not listed follow the global options; names that are never called do no harm. An option the policy does not know (maxcalls, a typo) throws a TypeError from createGuard, so a misspelt cap cannot quietly do nothing. repeatThreshold and polling have no effect when repeatedToolCall is false; maxCalls and ignore still work.
import { createGuard } from '@osama.ansar/agent-loopguard';
const guard = createGuard({
repeatedToolCall: { window: { size: 10, maxRepeats: 3 } }, // the same call 3 times among the last 10
});
// search(x), read(a), search(x), read(b), search(x) -> stops on the third search(x)The default repeatedToolCall rule only sees a call repeated back to back, so an agent that goes search(x), read(a), search(x), read(b), search(x) is never stopped by it, and oscillation only finds fixed cycles of at most maxPeriod calls. window counts how often each call (tool plus canonically-equal arguments) occurs among the newest size tool calls and stops when one reaches maxRepeats. It is off unless you set it.
- Values.
sizeis an integer from 2 to 1000 (MAX_WINDOW_SIZE; anything else throws aTypeErrorfromcreateGuard),maxRepeatsan integer from 2 tosize.{ size: 10, maxRepeats: 3 }is a reasonable place to start, not a tuned value: a repeat that issizeor more calls away from the others is not seen, and a smallmaxRepeatsflags agents that legitimately re-read the same file. Count the calls of a normal step in your agent (parallel calls count one by one) before choosingsize. - Counting. The calls are the same ones the consecutive rule reads: flattened across steps and parallel calls, ignored tools left out, failed calls left out with
ignoreErrors. Consecutive repeats count towards the window too, somaxRepeatsbelowthresholdmakes the window the stricter rule. When both stop at once the consecutive rule is the one reported. - Per-tool policies.
ignoretakes a tool out of the window. Apollingtool (orrequireIdenticalResults) is counted by call and result, so only identical results repeat. A tool'srepeatThreshold, or a polling tool'smaxIdenticalResults, replacesmaxRepeatsfor that tool, exactly as it replacesthresholdfor the consecutive rule; a number abovesizecan never be reached.maxCallsis independent. - The stop.
reason: 'repeated-tool-call-window',code: 'REPEATED_TOOL_CALL_WINDOW', evidence{ tool, argsPreview, count, threshold, windowSize, windowCalls, identicalResults }. It is a new reason rather than a new shape underrepeated-tool-call, so code that narrows on'repeated-tool-call'keeps its types. It hasfeedbacklike every other fault. - Preflight. A call that would be the
maxRepeats-th occurrence in the window is refused before it runs (the window slides as parallel calls are added). As for the consecutive rule, result-aware cases cannot be judged before the result exists, sopreflightnever refuses on them. - Cost. Memory is bounded by
size(one 28-character hash per call) and each call costs O(1). A snapshot grows by about 31 bytes per slot: measured with 3,000 distinct calls, a snapshot withsize: 1000was 30,690 bytes larger than one withsize: 10.
import { createGuard } from '@osama.ansar/agent-loopguard';
const guard = createGuard({ warnings: true });
const verdict = guard.check(step);
if (!verdict.stop) {
for (const warning of verdict.warnings ?? []) {
messages.push({ role: 'user', content: warning.feedback }); // "...once more will stop this task..."
}
}A warning is a non-blocking note on a verdict ({ stop: false, warnings: [...] }, or next to a stop) raised one step before a rule would stop the run, so the model can change course while it still has room. Budgets have always had them (budget.warnAt); warnings: true adds them for the loop rules:
code |
Raised when | Default level | Option |
|---|---|---|---|
REPEATED_TOOL_CALL_WARNING |
the run of identical calls is one short of the limit that applies to the tool | threshold - 1 |
repeatedToolCall.warnAt |
REPEATED_TOOL_CALL_WINDOW_WARNING |
a call the step added is one short of maxRepeats in the window |
maxRepeats - 1 |
repeatedToolCall.window.warnAt |
OSCILLATION_WARNING |
the cycle at the end of the sequence has been seen one time short of repeats |
repeats - 1 |
oscillation.warnAt |
NO_PROGRESS_WARNING |
the stalled streak is one short of threshold |
threshold - 1 |
noProgress.warnAt |
TOOL_CALL_CAP_WARNING |
a capped tool has been called maxCalls - 1 or maxCalls times (the next call over the cap stops) |
maxCalls - 1, at least 1 |
tools.<name>.warnAt |
- Default: off. With default-on, 3 of the 682 assertions of 0.2.0 fail (they expect
preflightto return exactly{ allow: true }on the call before a repeat is refused), and every verdict of code written against 0.2.0 could gain awarningsfield it never saw. Sowarnings: trueis opt-in.warnings: falseis a kill switch for every warning, budget warnings included. A rule with its ownwarnAtnumber warns even withoutwarnings: true;warnAt: falseturns one rule off underwarnings: true. - Levels.
warnAtis the count at which a rule starts warning: an integer from 2 (from 1 for caps) up to one below its limit (up tomaxCallsfor caps). A rule that has no step before its stop (threshold: 2) never warns, and awarnAtthat cannot be reached throws aTypeErrorfromcreateGuard. The warning is raised on every step from that level until the rule stops, not just once. - When. A warning is raised on a step that adds to what it warns about: a counted call to that tool, a call that continues the cycle, one more stalled step. A text-only step after a warning carries none, and ignored tools never raise one.
- Shape.
{ code, detail, feedback, evidence }.evidencehas the shape of the matching stop's, with the counts still below the limit.detailis for developers and shows an argument preview;feedbackfollows the same privacy rule as stop feedback (fixed words, counts and a safe tool name, never arguments, results or text).feedbackForWarning(warning)returns the model-facing text for any warning, budget warnings included (those have nofeedbackfield, to keep their 0.2.0 shape). - Preflight.
guard.preflight(call)returns the warnings the call would carry ({ allow: true, warnings }), in the same order ascheck, exceptNO_PROGRESS_WARNING, which needs a finished step. - Snapshots. Warnings are derived from state that is already in the snapshot, and
warnAtnever changes a stop, so it is not part of the options fingerprint: a run may be restored with different warning settings.
import { createGuard } from '@osama.ansar/agent-loopguard';
const guard = createGuard({
// Compare calls by the fields that matter, not by the whole payload.
signature: (tool, args) => JSON.stringify({ q: (args as { q: string }).q }), // ignore `ts`, `requestId`, `pageToken`
resultSignature: (result) => (result as { status: string }).status, // "pending" is "pending"
errorSignature: (error) => (error as { code?: string }).code ?? 'unknown',
});By default two calls are the same when their canonical forms are equal, so a call that carries a timestamp, a request id or a page token is never the same call twice. These functions let you pick the fields that decide it, and they also spare the guard from walking a huge payload.
signature(toolName, args)describes the arguments of a call; the tool name is always part of the comparison on top of it.resultSignature(result)anderrorSignature(error)describe a result or an error; they matter wherever results are compared:requireIdenticalResults,pollingtools, the window with those, and the no-progress rule. Each is optional and independent.- What is done with the string. It is hashed like a canonical form, so any length is fine. The call's preview in evidence, labels and snapshots is the first 80 characters of your string, and the arguments themselves are not read at all, so nothing else about them reaches the guard's state.
- When your function fails. If it throws, or returns anything that is not a string,
checkandpreflightdo not throw: that one value falls back to the default canonical form, and the failure is counted insummary().signatures({ failures, lastFailure }, present only when a function is set;lastFailureis the message, cut at 200 characters, andreset()clears the count). A call that fell back does not match a call that did not. The alternative, treating a failure as a distinct signature, would silently switch detection off for every call a buggy function fails on; the fallback keeps detection working at its 0.2.0 strength. Passing something that is not a function throws aTypeErrorfromcreateGuard; what a function returns can only be checked when it runs, which is why a bad return is counted rather than thrown. - Snapshots. Functions cannot be saved, and a snapshot cannot tell whether you pass the same one on restore, exactly as with
customdetectors andfeedback. What it does record is which of the three are set, as asignaturesentry in the options fingerprint (present only when at least one is set, so snapshots without them are as they were): restoring without a function the snapshot was taken with, with one it was not, or with a different set, throws aTypeErrornamingsignatures. A snapshot taken before you added a function (including any from 0.2.0) is refused when you turn one on, because the hashes in it were made with the default form. Pass the same functions when you restore. - Not covered. Your functions run synchronously inside
check/preflight, on every call; keep them cheap and deterministic. A function with side effects, or one whose answer changes over time, will make verdicts differ between a run and its replay (toStopWhenreplays all steps on every call).
import { createGuard, createToolRunner } from '@osama.ansar/agent-loopguard';
const guard = createGuard({ warnings: true, tools: { search: { maxCalls: 8 } } });
const runner = createToolRunner(guard);
// One model turn: run its tool calls (in parallel if you like), then close the step.
const outcomes = await Promise.all(
modelToolCalls.map((c) => runner.run(c.name, c.args, () => tools[c.name](c.args))),
);
outcomes.forEach((outcome, i) => {
const id = modelToolCalls[i].id;
if (!outcome.ran) toolMessages.push({ id, content: 'denied' in outcome ? outcome.denied.feedback : 'cancelled' });
else toolMessages.push({ id, content: outcome.ok ? String(outcome.result) : `Error: ${String(outcome.error)}` });
});
const verdict = runner.endStep({ text, finishReason, usage });
if (verdict.stop) break;createToolRunner(guard, options?) is the glue most loops write by hand: guard.preflight before a call, run it, remember the call with its result or error, guard.check for the finished step. It returns { run, endStep, inFlight }:
run(name, args, executor)asksguard.preflightfirst. If the call is allowed it runsexecutor()(sync or async) and resolves to{ ran: true, ok: true, result }or{ ran: true, ok: false, error }. If it is refused the executor does not run andrunresolves to{ ran: false, denied }, wheredeniedis thepreflightrefusal with the model-safefeedbackto send back in place of the tool's result.- Errors come back, they are not thrown. The original error object is in the outcome, because a failed tool call is ordinary data in an agent loop and usually becomes the tool result the model sees. Pass
{ rethrow: true }to haverunreject with the original error instead; the call is recorded as failed either way (a thrownnullorundefinedis recorded as a failure too, and returned as thrown). An executor that throws synchronously is handled the same way. The other library'srun()rethrows by default; this one does not. - Refused calls are not recorded. They never reach
check, so the repeat rule cannot fire on a refusal itself (see Check a call before it runs); the step still counts towardsmaxSteps. - Parallel calls. Calls are judged together, in the order
runwas called, together with the calls already started in this step: with a repeat threshold of three, starting three identical calls at once runs two and refuses the third. Calls are recorded in the order they started, not the order they finished, so the step is the same however the tools' timings fall. endStep(meta?)builds the step from the calls run since the lastendStepplusmeta(text,finishReason,usage,durationMs,timestamp), callsguard.check, empties the buffer and returns the verdict. AtoolCallsinmetais ignored. If a call is still running it throws anErrorand changes nothing: await therunpromises first (runner.inFlightsays how many are pending). A tool that never settles therefore blocksendStep; give your tools their own timeouts.- Abort. With
{ signal }(anything withaborted, anAbortSignalincluded),runstarts nothing once it is aborted and resolves to{ ran: false, aborted: true }, without asking the guard and without recording. Calls already running are not cancelled; they finish and are recorded. Cancelling a tool is up to the executor. - What it does not do. It does not call the model, retry, time out or cancel your tools, and one runner belongs to one guard and one loop: it keeps one step buffer, so run two agents with two runners.
npm run example:runner runs a complete offline loop with parallel calls, a failing tool, a refused call and its feedback.
import { createGuard } from '@osama.ansar/agent-loopguard';
const guard = createGuard({ tools: { search: { maxCalls: 5 } } });
const executed = [];
for (const call of modelToolCalls) { // [{ name, args }]
const pre = guard.preflight(call);
if (!pre.allow) {
toolMessages.push({ toolCallId: call.id, content: pre.feedback }); // tell the model; do not run the tool
continue;
}
executed.push({ name: call.name, args: call.args, result: await runTool(call) });
}
// After the step, record what really happened, exactly as before.
const verdict = guard.check({ text, toolCalls: executed, finishReason, usage });guard.preflight(call) answers "if I run this call now, would it immediately trip a rule?". It records nothing and changes nothing, so you can ask as often as you like. It returns { allow: true, warnings? } or { allow: false, reason, code, detail, evidence, feedback }, using the same reason and code as a verdict. Pass an array to ask about parallel calls in one turn (guard.preflight([a, b])); an array is judged as one step, whereas asking about calls one at a time cannot see the calls of the same turn, which are not recorded yet.
What it can and cannot judge, because a call that has not run yet has no result, text, finish reason or usage:
| Rule | In preflight? |
|---|---|
budget |
Yes, when a limit is already reached (the totals so far; the wall clock for a duration limit). Budget warnings come back on an allowed call. |
maxSteps |
Yes, when the limit is already reached. |
tools.<name>.maxCalls |
Yes: the call after the Nth is refused. |
repeatedToolCall |
Yes, for the default rule: the call that would be the Nth identical one in a row. No for result-aware rules (requireIdenticalResults, polling tools): they cannot be judged before the result is known, so preflight never refuses on them (it may be right to run the call: the result might be new). check still stops them once the identical outcomes are in. |
repeatedToolCall.window |
Yes, by call: the call that would be the maxRepeats-th in the window. Not for result-aware cases, as above. |
oscillation |
Yes: the call that would complete the cycle. |
noProgress, finishReason, custom |
No. They need the finished step (or your code), so only check runs them. |
A tool with ignore: true skips the call-pattern rules in preflight too, but budget and maxSteps still apply to it. When several rules would refuse, the first in this order wins: budget, max steps, tool limit, repeated call, oscillation. preflight says nothing about a guard whose last verdict was already a stop; acting on that is up to you.
A refused call never ran, so leave it out of the step you pass to check. The step still counts towards maxSteps, and if the model keeps asking for the refused call, maxSteps ends the run (and noProgress, if its text repeats too). Recording a refused call as if it had run would make the repeat rule fire on the refusal itself.
const verdict = guard.check(step);
if (verdict.stop && verdict.feedback) {
messages.push({ role: 'user', content: verdict.feedback }); // let the model change course or wrap up
}Every stop verdict that is a fault (isFault(verdict)) has a feedback string: a few plain sentences, different for each code, the same every time, written to be pasted into the model's next turn or a tool result. For example, for REPEATED_TOOL_CALL:
You have called
search3 times in a row with the same arguments. Repeating it is unlikely to give you anything new. Try a different tool or different arguments, or answer with what you have.
Those words are the whole message: it is built from fixed text, counts and limits, and the tool name. It never repeats arguments, results, model text or provider strings, because those can hold secrets or personal data and this text is meant to be sent to a model (and ends up in logs and transcripts). explain() and verdict.detail are the developer's view and do show an argument preview. A tool name is only used if it looks like an ordinary identifier (letters, digits, _ . : / -, up to 64 characters); the model chooses names, so anything else is replaced by "that tool". A normal stop finish has no feedback, and neither does a custom verdict unless the detector supplies one.
import { createGuard, feedbackFor } from '@osama.ansar/agent-loopguard';
const guard = createGuard({
// Return a string to replace the text, or undefined to keep the default.
feedback: (verdict, { phase }) =>
verdict.code === 'MAX_STEPS' ? 'Out of steps. Summarise what you found.' : undefined,
});
// feedbackFor(verdict) returns the default text for any verdict (or undefined when there is none).phase is 'check' for a verdict from check and 'preflight' for a refused call, whose default wording differs ("That call was not run: ..."). feedback is called only for faults; if it throws, the error propagates out of check / preflight. Keeping your own text free of secrets is up to you.
import { createGuard } from '@osama.ansar/agent-loopguard';
const guard = createGuard({
warnings: true,
onDecision: ({ phase, verdict }) => metrics.count(`guard.${phase}`, { stop: 'stop' in verdict ? verdict.stop : !verdict.allow }),
});
// ...after some steps:
messages.push({ role: 'user', content: guard.report() });guard.report() renders a short status block for the model's context. It is deterministic (the same facts give the same text) and built only from counts, fixed wording and tool names that look like identifiers, so it never contains arguments, results, errors or model text:
Loop guard status
Steps: 5
Tool calls: 8 (1 failed): read 4, search 3, write 1
Warnings:
- You have called `read` 2 times in a row with the same arguments. Calling it that way once more will stop this task. Try a different tool or different arguments, or answer with what you have.
A third read with the same arguments would stop the run, and the report would then end with Last stop: repeated-tool-call (REPEATED_TOOL_CALL).
- Contents. Steps; calls with the number that failed and calls per tool (most called first, ties by name; the first 8 are listed, the rest summed as
other tools); the warnings carried by the most recent verdict, worded for the model (feedbackForWarning); and the most recent stop's reason and code (a custom code only if it looks like an identifier, elseCUSTOM). Lines for warnings and for a stop appear only when there is one. - Bounded. Calls are counted by name for at most 32 distinct names that match
/^[A-Za-z0-9_.:/-]{1,64}$/, as for model-facing text; every other call (an odd name, or a 33rd name) is summed inotherToolCalls. The tally is part of the snapshot, so a restored guard keeps counting. A snapshot from 0.2.0 has none, so for a run resumed from one the per-tool counts start at zero (stepsandtoolCallsstill carry over). - Last verdict. The warnings and the last stop come from verdicts this guard object has returned, like
summary().lastVerdict: after a restore the report shows neither until the nextcheck.reset()clears them. - JSON.
guard.report({ format: 'json' })returns the same facts as a plainGuardReportobject (steps,toolCalls,failedToolCalls,callsByTool,otherToolCalls,warnings: [{ code, message }],lastStop). Only the literal'json'asks for the object; anything else gives the text.
onDecision({ phase, verdict }) is called after every check (phase: 'check', verdict is the Verdict) and every preflight (phase: 'preflight', verdict is the Preflight answer), for logging and metrics. It cannot influence the guard:
- It receives a copy (
structuredClone; if the evidence of a custom stop cannot be copied it gets the event itself), so changing it changes neither the verdict the caller holds norsummary().lastVerdict. - What it throws is swallowed, and so is the rejection of a promise it returns.
- Calling
check,preflightorreseton the same guard from inside it throws anError("cannot be called from inside onDecision"), and the guard's state is untouched. The Error is thrown at the call site in your hook; if the hook does not catch it, it is swallowed like any other. Reading the guard (summary,report,toJSON,snapshot,history) and using another guard are fine. The guard has finished the decision before it calls the hook, so what you read is consistent. - It is not called for a
checkthat throws (a custom detector's error). It is not stored in a snapshot or checked when restoring.
import { createGuard } from '@osama.ansar/agent-loopguard';
const options = { maxSteps: 40, tools: { search: { maxCalls: 8 } } };
// In the first process: JSON.stringify(guard) is guard.toJSON().
await store.set(`run:${runId}`, JSON.stringify(guard));
// Later, in another process: pass the same options.
const guard = createGuard.fromJSON(JSON.parse(await store.get(`run:${runId}`)), options);The restored guard goes on exactly where the original stopped: given the same steps it returns the same verdicts and the same summaries (this is checked by a differential test that cuts random runs at random points, through structuredClone and through a JSON round trip). restoreGuard is the same function as createGuard.fromJSON.
- What a snapshot holds. Version number, step and call counters, calls per tool (for
report(); see above), running totals, the wall-clock time used so far (only when there is a duration budget), tool names, hashes of recent calls and outcomes, and a few previews of at most 80 characters of recent arguments and text, kept so that evidence and messages read the same after a restore. What it does not hold: raw arguments, results, errors, model text, the step history, the options, the last verdict. Hashes are not cryptographic; a short, guessable value could be recovered by hashing candidates, so treat a snapshot as run data, not as public.guard.snapshot({ redact: true })replaces the previews with[redacted]: stop decisions stay the same, but evidence for calls made before the snapshot says[redacted]. - Size. Bounded by the options, not by the length of the run: the oscillation detector keeps
maxPeriodcalls, the no-progress detector the newest 1024 distinct outcomes (about 31 bytes each), the repeat detector one run, pluswindow.sizecall hashes (about 31 bytes each) when you set a window. Measured with default options: 831 bytes for a fresh guard, and 33,153 bytes after 1,500 steps and 33,154 after 6,000 steps that each had a new 2 KB argument, a 3 KB result and 500 characters of text (it stops growing once 1024 outcomes are remembered); raisingoscillation.maxPeriodto 50 made it 39,356 bytes. Tool names over 256 characters are cut in the snapshot. - Options are not stored; they are fingerprinted. Functions cannot be saved, so you pass the options again. The snapshot records one fingerprint per group of options (
maxSteps,repeatedToolCall,oscillation,noProgress,finishReason,budget,tools, the number ofcustomdetectors, and whichsignaturefunctions are set), and restoring under different options throws aTypeErrorthat names the groups, instead of silently behaving differently. Not fingerprinted:now,feedback,onDecision, the warning settings (warnings, everywarnAt) and what your custom detectors do. To give a run that hit its limit more room, pass{ allowLimitChanges: true }as the third argument: thenmaxStepsandbudgetmay differ (and only those). - History. The raw steps are not in a snapshot, so a restored guard starts with an empty
history, and custom detectors see only the steps recorded since the restore.summary().stepsand the detectors keep counting across the restore.summary().lastVerdictisnulluntil the firstcheck. - Wall-clock budgets. The time used so far is stored as a duration, so the time between saving and restoring is not counted.
- Bad snapshots. An unknown version, a wrong shape, an impossible number or a hostile object (throwing getter, revoked proxy,
__proto__keys) throws aTypeErrorfromfromJSON, never a crash later fromcheck. Unknown extra keys are ignored.
- No semantic loop detection. It compares tool names, arguments, results and text after normalisation. A model that rewords its text and varies one argument slightly each time is not detected, and no embedding or LLM is involved.
- No cost table. It never estimates tokens or prices. Token and cost limits only work on the numbers you pass in
usage; if you supply nocostUsd, amaxCostUsdlimit can never fire. - No LLM calls and no network. The guard is plain, synchronous code. The tool runner is the only async part, and all it awaits is your executors.
- It does not run your agent.
runAgentLoopis a ten-line convenience, not a framework, andcreateToolRunnerruns your tool executors around the guard, not the model or the loop. - It does not cancel in-flight work. A verdict is advice; stopping is up to the caller (
runAgentLoopandtoStopWhendo it for you at step boundaries). - Defaults are not benchmarked. Thresholds such as "3 in a row" are conventions, not measured optima. Check them against your own traces.
- History is kept in memory for the life of the guard (
reset()clears it). It is cheap for a normal run but is not designed for unbounded sessions. The detectors themselves keep bounded state; onlyguard.history(the raw steps) grows. preflightis not a full check. It cannot see results, text, finish reasons or usage, so it never replacescheck; see the table above for exactly what it judges. It does not cancel or wrap your tool calls either: it only answers, and you decide (createToolRunneris the wrapper, if you want one).- A snapshot is not a transcript. It cannot rebuild
history, and it does not store your options (only their fingerprints).
Steps are reduced to comparable facts once, when check is called. Anything unusable (a non-string finish reason, NaN token counts, a throwing getter) is ignored rather than thrown on.
Canonical form. Arguments and results are turned into a deterministic string so equal values compare equal: object keys are sorted; properties whose value is undefined are omitted (like JSON); array order is kept; NaN, Infinity and bigint (10n) stay distinct from strings and numbers that print alike; -0 equals 0; Dates are written as ISO strings; Maps and Sets are sorted by their entries; objects with toJSON (URL, ...) are written by calling it; a reference back to an ancestor is written [Circular:<depth>]; nesting deeper than 64 levels and inputs of more than 200,000 values are cut off with a marker (so two huge values that agree on everything before the cut compare equal). If reading a value throws (hostile getters, revoked proxies), it gets a unique placeholder and is never equal to anything. Equality is decided on a fixed-length hash of the canonical form (two independent 53-bit hashes, 28 hex characters; for forms longer than 256 characters the length is folded in first), so detector state and snapshots hold hashes, not raw values. The hash is non-cryptographic and meant for equality checks, not security.
Call sequence. "A call" is one entry of toolCalls. repeatedToolCall and oscillation read the flattened sequence of calls across steps, in order (calls of a tool with ignore: true are removed from it first, so they neither extend nor break a run). Parallel calls in one step count one by one; steps with no tool calls neither extend nor break a run. A call's signature is its tool name plus the canonical arguments. Its outcome signature adds the canonical result or error (or, if neither was supplied, is just the call).
Early warnings. Computed after the detectors have seen a step, from the same state they stop on: the run, the window counts, the cycle counters, the streak and the tool counts. A rule that stops in the step does not also warn.
maxSteps. Stops when limit steps have been recorded. With maxSteps: 3 the third check stops.
tools.<name>.maxCalls. Counts every call to the tool in the run (across steps, whatever the arguments or results) and stops on the first call beyond the cap: with maxCalls: 3 the fourth call stops, with maxCalls: 0 the first does. With parallel calls in one step, the first call over the cap is the one reported. Ignored tools are never counted. It keeps stopping on every later step that calls the tool, like the other rules.
repeatedToolCall. Stops when the run of identical signatures at the end of the sequence reaches threshold (exactly N stops, N-1 does not). With requireIdenticalResults, identical means identical outcome signature, so polling a job whose status keeps changing is not a repeat. With ignoreErrors, calls with a non-null error are removed from the sequence before counting. A run that reaches the threshold in the middle of a step still counts if a later call in the same step ends it. A tool's repeatThreshold replaces the threshold for runs of that tool; a polling tool compares outcomes like requireIdenticalResults does, with its own threshold; the evidence reports the threshold and identicalResults that applied.
repeatedToolCall.window. Keeps the keys (call hashes) of the newest size counted calls in a ring buffer with a count per key. Each counted call is added, the oldest one drops out once the window is full, and the rule stops when the added call's key reaches its threshold (maxRepeats, or the tool's own number, see above). A run that reaches the threshold in the middle of a step still counts if a later call in the same step slides it out.
oscillation. For each period p from 2 to maxPeriod, looks at the end of the call-signature sequence: it stops when the last p calls repeat for repeats full cycles in a row (a b a b a b is period 2, three cycles). A cycle made of one distinct call (a a a a a a) is not an oscillation; that is repeatedToolCall's case. Results are not considered, unless you set includeResults: true: then the sequence is the outcome signatures (call plus result or error; a call without a result compares by the call alone), so a cycle counts only if the same results come back each time, and an agent that goes search, read, search, read while every result is new is not flagged. preflight cannot judge that before the results exist, so with includeResults it never refuses on a cycle (check still stops it). The option is part of the snapshot fingerprint only when it is on.
noProgress. A step is stalled when none of its tool outcomes is new in this run (a step without tool calls is always stalled). It stops after threshold consecutive stalled steps that all have the same normalised text (lower-cased, whitespace collapsed; an empty string counts as text, so tool-only steps are judged on outcomes alone). A new outcome, or different text, restarts the count. Because outcomes include the result, the same call returning a new result is progress. Calls of ignore tools are not outcomes, so a step that only calls them is stalled. The detector remembers the newest 1024 distinct outcomes; in a run with more than that, an outcome older than the window counts as new again (this bounds memory and snapshot size).
finishReason. Finish reasons are normalised (trimmed, lower-cased, _ becomes -). Then: a reason in terminal stops, even if tool calls are present; tool-calls continues; a missing reason says nothing; anything else (other, unknown, any unfamiliar string) follows otherPolicy: 'stop' stops, 'continue' continues, 'stop-if-text-only' (default) stops when the step has non-blank text and no tool calls.
Why the default exists: some frameworks only treat stop as "finished". If a provider ends a final, text-only answer with an unfamiliar reason, those frameworks see "not finished" and re-send the same request until the step limit, paying for the same answer again and again. A text-only step that is not a clean stop is the signature of that, so the guard ends the run there. A normal stop also produces a stop verdict (the run is over); use isFault(verdict) to tell that apart from a problem.
budget. Totals are summed from the steps: input, output and total tokens (total falls back to input plus output when a step gives none), costUsd, and durationMs. Numbers that are not finite and non-negative are ignored. A limit is spent when reached (value >= limit): the guard runs after a step has happened, so waiting for "exceeded" would always overshoot by a step. maxDurationMs compares against the larger of the summed durationMs values and the wall-clock time since the guard was created or reset (read from the injectable now(), so tests can control it). With warnAt (a ratio between 0 and 1, per limit or shared), a step that is at or past that fraction but below the limit returns { stop: false, warnings: [...] }; the warning repeats on every step while it applies.
Priority. All detectors see every step (so their state stays consistent), and the first stop wins in this order: finish reason, budget, max steps, tool limit, repeated tool call (the consecutive rule, then the window), oscillation, no progress, custom. The tool limit sits after the step and budget limits (all explicit caps) and before the pattern detectors, because a cap you set is a harder rule than a heuristic. preflight uses the same order for the rules it can judge. Detectors overlap: a perfectly repeating a b a b a with identical results and empty text is reported by noProgress a step before oscillation would fire.
interface GuardOptions {
maxSteps?: number | false; // default 50
repeatedToolCall?: {
threshold?: number; requireIdenticalResults?: boolean; ignoreErrors?: boolean; warnAt?: number | false;
window?: { size: number; maxRepeats: number; warnAt?: number | false } | false; // size 2..1000, maxRepeats 2..size; default off
} | false;
oscillation?: { maxPeriod?: number; repeats?: number; includeResults?: boolean; warnAt?: number | false } | false;
noProgress?: { threshold?: number; warnAt?: number | false } | false;
finishReason?: { terminal?: readonly string[]; otherPolicy?: 'stop' | 'continue' | 'stop-if-text-only' } | false;
budget?: {
maxTotalTokens?: BudgetLimit; maxInputTokens?: BudgetLimit; maxOutputTokens?: BudgetLimit;
maxCostUsd?: BudgetLimit; maxDurationMs?: BudgetLimit;
warnAt?: number; // default warning ratio
} | false; // BudgetLimit = number | { limit: number; warnAt?: number }
warnings?: boolean; // early warnings for the loop rules; default off, false silences all
tools?: Record<string, ToolPolicy>; // per-tool rules, below
custom?: CustomDetector | readonly CustomDetector[];
feedback?: (verdict: StopVerdict, info: { phase: 'check' | 'preflight' }) => string | undefined;
now?: () => number; // default Date.now
signature?: (toolName: string, args: unknown) => string; // what makes two calls the same
resultSignature?: (result: unknown) => string;
errorSignature?: (error: unknown) => string;
onDecision?: (event: { phase: 'check'; verdict: Verdict } | { phase: 'preflight'; verdict: Preflight }) => void;
}
interface ToolPolicy {
polling?: boolean | { maxIdenticalResults?: number }; // integer >= 2
maxCalls?: number; // integer >= 0
warnAt?: number | false; // 1..maxCalls; needs maxCalls
repeatThreshold?: number; // integer >= 2
ignore?: boolean;
}
interface Guard {
check(step: GuardStep): Verdict;
preflight(call: PreflightCall | readonly PreflightCall[]): Preflight; // would this call trip a rule? changes nothing
reset(): void; // forget the run, keep the options
summary(): GuardSummary; // counts, totals, per-detector state; JSON-serialisable
report(options?: { format?: 'text' }): string; // short model-safe status block
report(options: { format: 'json' }): GuardReport;
toJSON(): GuardSnapshot; // save the run; JSON.stringify(guard) uses it
snapshot(options?: { redact?: boolean }): GuardSnapshot;
readonly history: readonly GuardStep[]; // frozen shallow copy (empty after a restore)
}
// Rebuild a guard from a snapshot. `snapshot` may be the result of JSON.parse; `restoreGuard` is the same function.
createGuard.fromJSON(snapshot: unknown, options?: GuardOptions, restore?: { allowLimitChanges?: boolean }): Guard;Invalid options (a threshold below 2, a non-positive limit, a warnAt outside 0 to 1, a misspelt tool policy, ...) throw a TypeError from createGuard. check and preflight do not throw on odd step or call data.
summary() contains nothing time-dependent: durations are the summed durationMs values, never wall-clock readings.
interface GuardStep {
toolCalls?: { name: string; args?: unknown; result?: unknown; error?: unknown }[];
text?: string;
finishReason?: string; // 'stop' | 'length' | 'tool-calls' | 'content-filter' | 'error' | 'other' | 'unknown' | any string
usage?: { inputTokens?: number; outputTokens?: number; totalTokens?: number; costUsd?: number };
durationMs?: number;
timestamp?: number; // recorded in history; not used by any detector
}type Verdict =
| { stop: false; warnings?: GuardWarning[] }
| { stop: true; reason: StopReason; code: string; detail: string; evidence: /* depends on reason */; feedback?: string; warnings?: GuardWarning[] };
type StopReason = 'max-steps' | 'tool-limit' | 'repeated-tool-call' | 'repeated-tool-call-window' | 'oscillation' | 'no-progress' | 'finish-reason' | 'budget' | 'custom';verdict.reason narrows verdict.evidence in TypeScript. Verdicts are plain JSON.
reason |
code |
evidence |
|---|---|---|
max-steps |
MAX_STEPS |
{ steps, limit } |
tool-limit |
TOOL_CALL_CAP |
{ tool, calls, limit } |
repeated-tool-call |
REPEATED_TOOL_CALL |
{ tool, argsPreview, count, threshold, stepIndexes, identicalResults } |
repeated-tool-call-window |
REPEATED_TOOL_CALL_WINDOW |
{ tool, argsPreview, count, threshold, windowSize, windowCalls, identicalResults } |
oscillation |
OSCILLATION |
{ period, repeats, threshold, cycle, tools } |
no-progress |
NO_PROGRESS |
{ steps, threshold, textPreview } |
finish-reason |
FINISH_TERMINAL, FINISH_OTHER, FINISH_OTHER_TEXT_ONLY |
{ finishReason, normalized, policy, hasText, toolCallCount } |
budget |
BUDGET_TOTAL_TOKENS, BUDGET_INPUT_TOKENS, BUDGET_OUTPUT_TOKENS, BUDGET_COST_USD, BUDGET_DURATION_MS |
{ metric, value, limit } |
custom |
your code (default CUSTOM) |
whatever you return |
A budget warning is { code: 'BUDGET_WARNING', metric, value, limit, ratio, detail }; the loop warnings (see Early warnings) are { code, detail, feedback, evidence }. GuardWarning is the union of them, discriminated by code; metric, value, limit and ratio are typed undefined on the loop warnings so that code reading them compiles as before. feedback is present on every fault verdict from a built-in detector (see Tell the model what went wrong).
explain(verdict): string: readable text for logs, including a short hint and any warnings.isFault(verdict): verdict is StopVerdict: true for a stop that is not just the model finishing normally withstop.feedbackForWarning(warning): string: the model-facing text of any warning (thefeedbackof a loop warning, fixed wording for a budget warning).feedbackFor(verdict, phase?: 'check' | 'preflight'): string | undefined: the default model-facing text for a verdict (whatverdict.feedbackholds unless you override it).undefinedfor a normalstopfinish and for a custom verdict that brings no text.canonicalize(value): stringandstableHash(value): string: the comparison primitives, exported because they are useful on their own.restoreGuard(snapshot, options?, { allowLimitChanges? }?): Guard: the same function ascreateGuard.fromJSON.
type Preflight =
| { allow: true; warnings?: GuardWarning[] }
| { allow: false; reason: 'max-steps' | 'budget' | 'tool-limit' | 'repeated-tool-call' | 'repeated-tool-call-window' | 'oscillation';
code: string; detail: string; evidence: /* as for the same reason in a verdict */; feedback: string };reason narrows evidence as it does for a verdict. detail is for developers and may quote an argument preview; feedback is for the model and never does. The evidence of a refused repeat or cycle is what check would report for the same call (the counts include the call that was refused). See Check a call before it runs for what is judged.
interface GuardSnapshot {
version: 1;
steps: number; toolCalls: number; failedToolCalls: number;
totals: GuardTotals;
wallClockMs: number | null; // only with a duration budget
options: { maxSteps: string; repeatedToolCall: string; oscillation: string; noProgress: string;
finishReason: string; budget: string; tools: string; custom: string }; // fingerprints
detectors: { repeatedToolCall; oscillation; noProgress; finishReason; toolLimits }; // each null when that detector is off
}Plain JSON-safe data. The shape of each detector's state is exported as a type (RepeatedToolCallSnapshot, OscillationSnapshot, NoProgressSnapshot) but is an implementation detail: treat a snapshot as opaque and only pass it to createGuard.fromJSON. See Save and resume a run.
createToolRunner(guard: Guard, options?: { rethrow?: boolean; signal?: { aborted: boolean } }): {
run<T>(name: string, args: unknown, executor: () => T | PromiseLike<T>): Promise<ToolRunOutcome<T>>;
endStep(meta?: Omit<GuardStep, 'toolCalls'>): Verdict;
readonly inFlight: number;
};
type ToolRunOutcome<T> =
| { ran: true; ok: true; result: T }
| { ran: true; ok: false; error: unknown }
| { ran: false; denied: PreflightDeny } // not run, not recorded; denied.feedback is for the model
| { ran: false; aborted: true };See Run your tools through the guard.
toStopWhen(guardFactory | options, { onStop }?): returns({ steps }) => boolean, usable as an AI SDKstopWhencondition. Idempotent (see above). Only the verdict for the latest step counts. Because it replays steps in a fresh guard, a wall-clockmaxDurationMsis meaningless there; step durations (performance.stepTimeMs) are used instead.toGuardStep(aiSdkStep): GuardStep: the mappingtoStopWhenuses (tool results andtool-errorcontent parts are matched to calls bytoolCallId).runAgentLoop({ step, guard?, signal?, onVerdict? }): Promise<{ steps, verdict, completed, aborted }>.completedis true when the agent ended the run itself (a final step with no fault, or a normalstop), false when the guard cut it short, the finish reason was something likelengthorerror, or the signal aborted. The signal is checked before every step; an in-flight step is not cancelled.withGuard(source, guard): AsyncIterable<step> & { verdict }: wraps a sync or async iterable.
agent-loop-guard (by Nextbridge) is a similar, independent library, and a good one to look at. Everything below about it comes from its published README (version 0.2.0 at the time of writing); I have read that README and have not run the library, and it may have changed since.
What it describes. A LoopGuard with beforeCall() / afterCall() / afterError() around each tool call and a run() that wraps the three (it re-throws the executor's error with the decision attached). Limits: a total call ceiling (maxCalls, default 50), per-tool ceilings, a wall-clock limit. Detection: consecutive repeats, repeats inside a sliding window (up to 10,000 calls), the same call returning the same result or error N times in a row, and cycles of call and result pairs (up to 1,000 long). Allowed decisions carry warnings (on by default) one step before a limit. Blocked decisions carry a suggestedAction ("stop" or "change_approach") and a sentence for the model. It also describes summary() with per-tool and per-decision-code counts, a report() text, toJSON() / fromJSON(), custom signature / resultSignature / errorSignature functions, a maxSignatureLength after which signatures are SHA-256 hashed, and an onDecision hook that rejects re-entrant calls. It is ESM-only, and its README says arguments containing functions, symbols, Maps, Sets or accessors throw a TypeError.
How 0.3.0 lines up. This package now has a counterpart for most of that, shaped for a loop that records one finished step at a time rather than one call at a time:
| In the other library's README | Here |
|---|---|
beforeCall() before a call |
guard.preflight(call) (read-only; also takes the parallel calls of a turn) |
afterCall() / afterError() |
guard.check(step) with result / error on each call |
run() |
createToolRunner(guard).run(...) + endStep(); errors are returned unless rethrow: true; parallel calls in one step are judged together |
windowSize, maxRepeatsInWindow |
repeatedToolCall.window: { size, maxRepeats } (size up to 1,000) |
| early warnings | warnings: true (off by default here) and per-rule warnAt |
report() |
guard.report() / guard.report({ format: 'json' }) |
onDecision |
onDecision (gets a copy; re-entrant check / preflight / reset throws an Error) |
signature, resultSignature, errorSignature |
the same three options (the tool name is always part of the key; a function that fails falls back to the default and is counted) |
| cycles of call and result pairs | oscillation: { includeResults: true } (cycles of 2 to maxPeriod calls; off by default) |
toJSON() / fromJSON() |
guard.toJSON() / createGuard.fromJSON() |
| same call and result N in a row | repeatedToolCall: { requireIdenticalResults: true }, and polling per tool |
What this one has that its README does not describe. A finish-reason policy (for example, ending a run when a text-only step finishes with an unfamiliar reason); token, input, output and cost budgets driven by the usage numbers you report (its README describes call-count and wall-clock budgets); a no-progress rule on repeated text; per-tool polling and ignore policies and a per-tool repeat threshold; a custom-detector hook; a stopWhen adapter for the Vercel AI SDK that is tested against the real SDK; CommonJS as well as ESM builds; and canonicalisation that never throws on odd values (functions, Maps, cycles, hostile getters). Saved state is bounded by the options, not by the run (it remembers only the newest 1,024 distinct outcomes), holds hashes plus a few short previews, can be written with the previews redacted, and carries a fingerprint of the options so that restoring under different ones throws; its README says its own snapshot grows with the number of distinct calls.
What the other one has that this one does not. A total call ceiling across all tools (here there are per-tool caps and a step limit, but no cap on all tool calls together). The suggestedAction field on a blocked decision. Windows and cycles with much higher limits (10,000 and 1,000; here the window stops at 1,000, and oscillation.maxPeriod is not capped but is meant to stay small). Hashing of oversized signatures with SHA-256 and a maxSignatureLength option (here equality uses a non-cryptographic 28-character hash of the canonical form, and a custom signature is how you keep a large payload from being walked at all). A summary() that breaks calls down by decision code and counts blocked calls. Warnings on by default, and a warning when few calls remain in a call budget (budgetWarnAt). error.loopGuardDecision on a re-thrown error.
Where they differ in shape. The other library's two calls are the whole API and it decides per call; here the unit is the step, preflight is a question about a call that has not run (it cannot judge rules that need the result), and check sees the whole step including text, finish reason and usage. This package does not detect semantic loops (a reworded text or a slightly varied argument; see above), and the other README does not describe that either.
Both have zero runtime dependencies. Pick whichever fits how your loop is written; nothing stops you from using the other one's ideas.
npm ci
npm run typecheck
npm run lint
npm test # npm run test:coverage for coverage
npm run build
npm run example:loop
npm run example:preflight # preflight, feedback, per-tool policies and save/resume, offline
npm run example:warnings # windowed repeats and early warnings, offline
npm run example:runner # the tool runner with parallel calls, offline
npm run example:ai-sdk # Node >= 22 (needs the `ai` dev dependency)The package supports Node 18 and newer. The development toolchain (vitest, tsup) and the AI SDK integration test need a newer Node; CI runs Node 20, 22 and 24.
Publishing is done from a GitHub Release by .github/workflows/publish.yml, which publishes with npm provenance. It needs a repository secret named NPM_TOKEN (an npm automation token for an account allowed to publish @osama.ansar/agent-loopguard). Bump the version in package.json and CHANGELOG.md, tag, and create a Release.
MIT