Loop gate
POST /api/loop-gateDecides whether an agent loop should run another iteration.
Details
Returns decision (continue, stop or escalate), reason, confidence (0 to 1), the checks behind it and nextStep (iterate, change_approach, narrow_scope, verify_result, hand_off). Send the goal, lastOutput and iteration, and optionally maxIterations, a budget { spentUsd, maxUsd }, history (up to 20 of { iteration, summary }) and constraints. The budget and iteration checks run in code before anything else: when either trips the answer is stop, no model is consulted and goalMet and model are null, at the same price. Repeating and stuck outputs are found lexically. Otherwise a typed judgment model (the /v1/judge backends) answers; model names which served. Model-backed, not deterministic, except the budget and iteration checks.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
goal | string | yes | What the loop is trying to accomplish. Up to 600 characters. Up to 600 characters. |
lastOutput | string | object | yes | What the iteration that just finished produced, or a digest of it. Up to 3000 characters. Up to 3000 characters. |
iteration | integer (1-) | yes | The number of iterations completed so far (the one that produced lastOutput). At least 1. The example sends 4. |
maxIterations | integer (1-) | no | Optional. At iteration >= maxIterations the answer is stop, decided in code. At least 1. The example sends 6. |
budget | object | no | Optional { spentUsd, maxUsd }. At spentUsd >= maxUsd the answer is stop, decided in code. |
history | array of object | no | Optional, up to 20 earlier iterations as { iteration, summary }, oldest first; each summary up to 400 characters. Pass the same kind of text you pass as lastOutput so repeats compare like with like. The model reads the newest 5; all are compared lexically. |
constraints | array of string | no | Optional, up to 8 rules the output must respect, each up to 160 characters. With constraints the model also answers constraintBreached; a breach escalates. |
Example request
curl -i -X POST https://agent402.tools/api/loop-gate \
-H "Content-Type: application/json" \
-d '{"goal":"Find three peer-reviewed studies on sleep and memory consolidation published since 2020, with DOIs.","lastOutput":"Found two studies with DOIs (Nature Neuroscience 2021, Sleep 2023). A third search of PubMed returned review articles only.","iteration":4,"maxIterations":6,"budget":{"spentUsd":0.52,"maxUsd":0.5},"history":[{"iteration":2,"summary":"One study found (Nature Neuroscience 2021)."},{"iteration":3,"summary":"Second study found (Sleep 2023); PubMed search for a third in progress."}]}'Watch a call get paid
POST /api/loop-gate$0.001 USDCPAYMENT-SIGNATUREon 14 chains200 OKAgent402-ReceiptEd25519Example response
{
"decision": "stop",
"reason": "Budget exhausted: spent 0.52 USD of 0.5 USD. No model was consulted.",
"confidence": 1,
"checks": {
"goalMet": null,
"budgetExceeded": true,
"iterationsExhausted": false,
"repeating": false,
"stuck": false,
"constraintBreached": false
},
"model": null,
"aiGenerated": true
}| Field | Type | Always present | In the example |
|---|---|---|---|
decision | string | yes | stop |
reason | string | yes | Budget exhausted: spent 0.52 USD of 0.5 USD. No model was consulted. |
confidence | number | yes | 1 |
checks | object | yes | 6 fields: goalMet, budgetExceeded, iterationsExhausted, repeating and 2 more |
model | null | no | null |
aiGenerated | boolean | yes | true |
From an MCP client
catalog.call {
"slug": "loop-gate",
"params": {
"goal": "Find three peer-reviewed studies on sleep and memory consolidation published since 2020, with DOIs.",
"lastOutput": "Found two studies with DOIs (Nature Neuroscience 2021, Sleep 2023). A third search of PubMed returned review articles only.",
"iteration": 4,
"maxIterations": 6,
"budget": {
"spentUsd": 0.52,
"maxUsd": 0.5
},
"history": [
{
"iteration": 2,
"summary": "One study found (Nature Neuroscience 2021)."
},
{
"iteration": 3,
"summary": "Second study found (Sleep 2023); PubMed search for a third in progress."
}
]
}
}Hosted connector (https://agent402.tools/mcp): paid in the call. Stdio package (npx -y agent402-mcp@0.20.0): pays from a wallet or AGENT402_CREDITS_KEY.
Errors and behavior
- Pay $0.001 per call over x402 or MPP. Wallet-only, model-backed: no proof-of-work tier; the same input can give a different result. A prepaid card-credits key (
Authorization: Bearer a402_...) also pays it. - Required:
goal,lastOutputanditeration; a rejected input answers 4xx witherror,tool,expected,requiredandexample. - On this route, a call ending in any status of 400 or above is not charged over x402, MPP or a credits key. A Tempo push credential pays before the call; a failure is a refund owed.
- A bodyless
GETorHEADreturns the same 402 quote. - An
Idempotency-Keyreplays the first 200 uncharged (an answer larger than 1 MB is not replayed).
Paid call (JavaScript agent)
import { wrapFetchWithPayment } from "@x402/fetch";
import { x402Client } from "@x402/core/client";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
const client = new x402Client();
client.setSpendControls?.({ maxAmountPerPayment: "$0.001" }); // refuse any quote above this tool's price
registerExactEvmScheme(client, { signer: privateKeyToAccount(process.env.AGENT_KEY) });
const payFetch = wrapFetchWithPayment(fetch, client);
const res = await payFetch("https://agent402.tools/api/loop-gate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
"goal": "Find three peer-reviewed studies on sleep and memory consolidation published since 2020, with DOIs.",
"lastOutput": "Found two studies with DOIs (Nature Neuroscience 2021, Sleep 2023). A third search of PubMed returned review articles only.",
"iteration": 4,
"maxIterations": 6,
"budget": {
"spentUsd": 0.52,
"maxUsd": 0.5
},
"history": [
{
"iteration": 2,
"summary": "One study found (Nature Neuroscience 2021)."
},
{
"iteration": 3,
"summary": "Second study found (Sleep 2023); PubMed search for a third in progress."
}
]
}),
});Get a wallet or run npx -y agent402-mcp@0.20.0 wallet new.
The quote (Python)
import base64, json, urllib.error, urllib.request
req = urllib.request.Request("https://agent402.tools/api/loop-gate", method="POST", data="{\"goal\":\"Find three peer-reviewed studies on sleep and memory consolidation published since 2020, with DOIs.\",\"lastOutput\":\"Found two studies with DOIs (Nature Neuroscience 2021, Sleep 2023). A third search of PubMed returned review articles only.\",\"iteration\":4,\"maxIterations\":6,\"budget\":{\"spentUsd\":0.52,\"maxUsd\":0.5},\"history\":[{\"iteration\":2,\"summary\":\"One study found (Nature Neuroscience 2021).\"},{\"iteration\":3,\"summary\":\"Second study found (Sleep 2023); PubMed search for a third in progress.\"}]}".encode(), headers={"Content-Type": "application/json"})
try:
urllib.request.urlopen(req)
except urllib.error.HTTPError as e:
quote = json.loads(base64.b64decode(e.headers["PAYMENT-REQUIRED"]))
print(e.code, [(a["network"], a["amount"]) for a in quote["accepts"]]) # the price, per chain, in base units