Cloudflare Agents
Make a Cloudflare Agents tool or Workflow wait for a person's approval from an inbox, with a signed webhook waking the agent when someone decides.
Cloudflare Agents runs each agent as a Durable Object with its own SQLite database and its own schedule, and AIChatAgent from @cloudflare/ai-chat adds a chat that keeps its messages. Its own approval step, needsApproval on a tool, waits for someone in that chat to answer in your interface with addToolApprovalResponse, and a Workflow can wait in step.waitForEvent until your code sends it the answer. VariantGate fits when the person who decides is not the one chatting, such as a customer asking for a refund that someone on staff approves from their phone, email or Slack, or when nobody is in a chat at all. The agent asks without waiting, keeps the request id in its own SQL table, and finishes when a signed webhook says someone decided.
The code below ran locally in wrangler dev 4.165.0 (workerd 1.20261118.1) with agents 0.33.0, @cloudflare/ai-chat 0.12.2 and ai 7.0.177, against the real approvals API and its real signed webhooks, with a scripted model standing in for Workers AI, whose binding needs a Cloudflare account even in local development. For the chat agent and the Workflow alike: approved, denied with a note, approved for a lower amount, approved at once by a rule, approved while the workspace was paused, a refund call that failed, one webhook delivered four times (three at once), forged and unsigned webhooks, the approvals API out of reach, a request whose answer was lost on the way back, an expired request and a lost webhook. For the chat also a tell that could not be queued the first time, the same tool call twice in one turn, the same order asked for again while its refund was under way or unconfirmed, an ask so slow that its claim was given up, two settles of one request racing, a deleted conversation and a decided request from another agent key in the workspace; for the Workflow a provider that failed once and a webhook for a run that no longer exists. For the expired request, the lost webhook and the slow ask the waits were cut to seconds.
1. Install
npm install agents @cloudflare/ai-chat ai workers-ai-provider zod
npm install https://variantgate.com/sdk/variantgate-agent-latest.tgz2. Configure the Worker
One Durable Object class holds the chats, and one Workflow handles refunds that start without a chat:
{
"name": "support-agent",
"main": "src/worker.ts",
"compatibility_date": "2026-11-01",
"compatibility_flags": ["nodejs_compat"],
"ai": { "binding": "AI" },
"durable_objects": {
"bindings": [{ "name": "SupportAgent", "class_name": "SupportAgent" }]
},
"workflows": [
{ "name": "refunds", "binding": "REFUNDS", "class_name": "RefundWorkflow" }
],
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["SupportAgent"] }]
}Make an agent key under Agents in your workspace. Put it and the webhook’s signing secret from step 4 in .dev.vars for wrangler dev, and set them with npx wrangler secret put for a deployed Worker. Then run npx wrangler types so Env knows them.
VARIANTGATE_KEY=gl_...
VARIANTGATE_WEBHOOK_SECRET=whsec_...import { ApprovalClient } from "@variantgate/agent";
import { ApprovalApiError, OutOfScopeError } from "@variantgate/agent/errors";
/** A client for the agent key. A Worker gets its secrets with each call. */
export function approvals(env: Env) {
return new ApprovalClient({
agent: "support-agent",
apiUrl: "https://api.variantgate.com",
key: env.VARIANTGATE_KEY,
});
}
/** True when the call may have reached the API although no answer came. */
export function unanswered(error: unknown): boolean {
return error instanceof ApprovalApiError && error.status === 0;
}
/** What the model is told when asking failed. Never "denied". */
export function notAsked(error: unknown): string {
if (unanswered(error)) {
// The request may be in the inbox, where nothing will act on it.
return (
"Not refunded: the approvals service did not answer, so the request " +
"may have reached the inbox. Nothing will act on it there; try again " +
"in a few minutes."
);
}
if (error instanceof OutOfScopeError) {
return "Not refunded: this agent's key may not ask for refunds.";
}
if (error instanceof ApprovalApiError) {
return `Not refunded: the approvals service refused the request (${error.code}).`;
}
return "Not refunded: something went wrong before anyone was asked.";
}- The client needs only
fetchand Web Crypto, nothing from Node.js.nodejs_compatis in the config because Cloudflare’s Agents examples set it. notAskedtells the model why asking failed and never calls it a no. When the API gave no answer at all, the request may still have reached the inbox, where nothing will act on it: if one turns up there, deny it.
3. Ask in the tool, act when the answer comes
import { AIChatAgent } from "@cloudflare/ai-chat";
import {
ChangedApprovalError,
NotApprovedError,
} from "@variantgate/agent/errors";
import type { Decision } from "@variantgate/agent/types";
import { convertToModelMessages, isStepCount, streamText, tool } from "ai";
import { createWorkersAI } from "workers-ai-provider";
import { z } from "zod";
import { approvals, notAsked, unanswered } from "./approvals";
import { shop } from "./shop"; // your own refund code
const EUROS = /^\d+(\.\d{1,2})?$/;
const ONE_DAY = 24 * 60 * 60;
const FIVE_MINUTES = 5 * 60_000;
const TEN_MINUTES = 10 * 60; // in seconds, for this.schedule
const MAY_HAVE_GONE_THROUGH =
"the refund may have gone through: check the order before retrying";
interface Refund {
amount: string;
order_id: string;
}
/** What settling decided, and the state the row is left in. */
interface Settled {
state: "done" | "unsure";
text: string;
}
export class SupportAgent extends AIChatAgent<Env> {
async onStart() {
this.sql`CREATE TABLE IF NOT EXISTS refunds (
order_id TEXT NOT NULL, amount TEXT NOT NULL, request_id TEXT UNIQUE,
state TEXT NOT NULL, claim TEXT NOT NULL, claimed_at INTEGER NOT NULL,
result TEXT, told INTEGER NOT NULL DEFAULT 0)`;
// One refund per order until it is done: a repeated call asks once, and
// nothing asks again while a refund is under way or may have gone through.
this.sql`CREATE UNIQUE INDEX IF NOT EXISTS one_open_refund ON refunds
(order_id) WHERE state IN
('asking', 'waiting', 'settling', 'refunding', 'unsure')`;
}
async onChatMessage() {
const workersai = createWorkersAI({ binding: this.env.AI });
const result = streamText({
model: workersai("@cf/moonshotai/kimi-k2.7-code"),
system:
"Handle refunds with the refund tool. Tell the customer what happened.",
messages: await convertToModelMessages(this.messages),
tools: {
refundOrder: tool({
description:
"Refund an order to the customer's original payment method.",
inputSchema: z.object({
orderId: z.string(),
amountEur: z.string().regex(EUROS).describe("Euros, such as 25.00"),
}),
execute: ({ orderId, amountEur }) =>
this.askToRefund(orderId, amountEur),
}),
},
stopWhen: isStepCount(5),
});
return result.toUIMessageStreamResponse();
}
/** Asks a person and returns at once. The refund happens in settle. */
async askToRefund(orderId: string, amount: string): Promise<string> {
const now = Date.now();
// An ask that never came back (the object was evicted) frees the order.
this.sql`DELETE FROM refunds WHERE order_id = ${orderId}
AND state = 'asking' AND claimed_at < ${now - FIVE_MINUTES}`;
// Claimed before the first await, so a repeated call asks only once.
const claim = crypto.randomUUID();
const [claimed] = this.sql`INSERT INTO refunds
(order_id, amount, state, claim, claimed_at)
VALUES (${orderId}, ${amount}, 'asking', ${claim}, ${now})
ON CONFLICT DO NOTHING RETURNING 1`;
if (!claimed) {
return `A refund for order ${orderId} is already asked for, under way or waiting to be checked.`;
}
let request: Decision;
try {
request = await approvals(this.env).ask({
action: "payment.refund",
summary: `Refund €${amount} for order ${orderId}`,
amount,
currency: "EUR",
// The webhook route reads chat to find this conversation.
details: { order: orderId, chat: this.name },
ttlSeconds: ONE_DAY,
});
} catch (error) {
// With no answer the request may exist: the claim stays and locks the
// order until it goes stale. Otherwise nobody was asked.
if (!unanswered(error)) {
this.sql`DELETE FROM refunds WHERE claim = ${claim}`;
}
return notAsked(error);
}
let saved: unknown[] = [];
try {
// Saved only if the claim is still ours: a slow ask can lose it.
saved = this.sql`UPDATE refunds
SET request_id = ${request.id}, state = 'waiting'
WHERE claim = ${claim} AND state = 'asking' RETURNING 1`;
} catch {
saved = [];
}
if (saved.length === 0) {
// Untracked, it could be approved with nobody to act: take it back.
await this.takeBack(request.id);
this.sql`DELETE FROM refunds WHERE claim = ${claim} AND state = 'asking'`;
return (
"Not refunded: the request could not be kept, so it was withdrawn, " +
"or closed as not done."
);
}
// The fallback in case its webhook is lost.
await this.schedule(TEN_MINUTES, "recheck", request.id);
// A rule may have answered already, before its webhook could find the row.
// Its answer goes into this tool result, so the chat is not told again.
const settled = await this.settle(request.id, true).catch(() => undefined);
return (
settled ??
`Asked a person to approve refunding €${amount} for order ${orderId}. ` +
"Nothing is refunded until they do; the answer will come to this chat."
);
}
/** Called by the webhook route and by recheck: settle, then tell the chat. */
async finish(requestId: string): Promise<void> {
await this.settle(requestId);
// Claimed before queueing, so the chat is told once; also when settling
// was finished earlier and the queue call failed then.
const [row] = this.sql<{ result: string }>`UPDATE refunds SET told = 1
WHERE request_id = ${requestId} AND told = 0
AND state IN ('done', 'unsure') RETURNING result`;
if (!row) return;
try {
// A new turn, queued so the webhook gets its answer at once.
await this.queue("tell", row.result);
} catch (error) {
this.sql`UPDATE refunds SET told = 0 WHERE request_id = ${requestId}`;
throw error; // the webhook is delivered again, and recheck runs too
}
}
async tell(result: string) {
await this.saveMessages((messages) => [
...messages,
{
id: crypto.randomUUID(),
role: "user",
parts: [{ type: "text", text: `Approval update: ${result}` }],
},
]);
}
/** Finishes one request once, however often it is called. */
async settle(requestId: string, told = false): Promise<string | undefined> {
const now = Date.now();
const claim = crypto.randomUUID();
// One conditional update claims it; a repeated webhook finds nothing.
const [row] = this.sql<Refund>`UPDATE refunds
SET state = 'settling', claim = ${claim}, claimed_at = ${now}
WHERE request_id = ${requestId} AND (state = 'waiting'
OR (state = 'settling' AND claimed_at < ${now - FIVE_MINUTES}))
RETURNING order_id, amount`;
if (!row) return undefined;
let decision: Decision;
try {
// The API, never the webhook body, says what happens.
decision = await approvals(this.env).check(requestId);
} catch (error) {
this.release(requestId, claim);
throw error;
}
if (decision.status === "pending") {
this.release(requestId, claim);
return undefined;
}
const settled = await this.act(row, decision, claim);
if (!settled) return undefined; // a later settle took the claim over
// Only the holder of the claim closes the row.
const [closed] = this.sql`UPDATE refunds
SET state = ${settled.state}, result = ${settled.text},
told = ${told ? 1 : 0}
WHERE request_id = ${requestId} AND claim = ${claim} RETURNING 1`;
return closed ? settled.text : undefined;
}
private release(requestId: string, claim: string) {
this.sql`UPDATE refunds SET state = 'waiting'
WHERE request_id = ${requestId} AND state = 'settling'
AND claim = ${claim}`;
}
/** Refunds only on a plain yes. Never throws once money may have moved. */
private async act(
row: Refund,
decision: Decision,
claim: string
): Promise<Settled | undefined> {
const client = approvals(this.env);
const done = (text: string): Settled => ({ state: "done", text });
if (!decision.allowed) {
if (decision.status === "approved") {
// Approved while paused: closed undone, and the record says so.
await client
.reportOutcome(decision.id, "failed", "not done: paused")
.catch(() => undefined);
}
return done(`Not refunded. ${new NotApprovedError(decision).message}`);
}
if (decision.changed) {
await client
.reportOutcome(decision.id, "failed", "not done: approved with changes")
.catch(() => undefined);
return done(
`Not refunded. ${new ChangedApprovalError(decision).message}`
);
}
// Only the settle holding the claim moves the money, and only once.
const [mine] = this.sql`UPDATE refunds SET state = 'refunding'
WHERE request_id = ${decision.id} AND state = 'settling'
AND claim = ${claim} RETURNING 1`;
if (!mine) return undefined;
try {
await shop.refund(row.order_id, row.amount, {
idempotencyKey: decision.id,
});
} catch {
// A timeout can hide a refund that went through: keep the order locked.
await client
.reportOutcome(decision.id, "failed", MAY_HAVE_GONE_THROUGH)
.catch(() => undefined);
return {
state: "unsure",
text:
`The refund of €${row.amount} for order ${row.order_id} may have ` +
"gone through. Check the order before trying again.",
};
}
await client
.reportOutcome(decision.id, "succeeded", `Refunded €${row.amount}`)
.catch(() => undefined); // the money moved: never fail or retry now
return done(`Refunded €${row.amount} for order ${row.order_id}.`);
}
/** Ten minutes after asking, and again until it is settled and told. */
async recheck(requestId: string) {
await this.finish(requestId).catch((error) =>
console.error("recheck: not settled yet", requestId, error)
);
const [open] = this.sql`SELECT 1 FROM refunds
WHERE request_id = ${requestId}
AND (state IN ('waiting', 'settling')
OR (told = 0 AND state IN ('done', 'unsure')))`;
if (open) await this.schedule(TEN_MINUTES, "recheck", requestId);
}
/** Withdraws a request; one approved already is recorded as not done. */
private async takeBack(requestId: string) {
const client = approvals(this.env);
try {
await client.withdraw(requestId);
} catch {
// Refused once decided, such as by a rule at once. Best-effort.
const decision = await client.check(requestId).catch(() => undefined);
if (decision?.status === "approved") {
await client
.reportOutcome(requestId, "failed", "not done: no longer tracked")
.catch(() => undefined);
}
}
}
/** The conversation is deleted: what it asked for may never happen. */
async destroy() {
const open = this.sql<{ request_id: string }>`SELECT request_id
FROM refunds WHERE state IN ('waiting', 'settling')`;
for (const { request_id } of open) {
await this.takeBack(request_id);
}
await super.destroy();
}
}- The tool returns at once.
askToRefundmakes a request that stays open for a day, keeps its id in therefundstable and tells the model a person was asked. The refund happens later, insettle, so no chat turn is held open while someone decides. - The order is claimed in SQL before the first
await, and a unique index allows one refund per order until it is done, so the same tool call twice in one turn asks once, and asking again while a refund is under way or unconfirmed gets “already asked for, under way or waiting to be checked” instead of a second request with a second idempotency key. A claim stuck inaskingfor five minutes is given up; if its slow ask then returns, the request is withdrawn, or closed as not done if a rule approved it at once, and the model is told so. If the API refuses the request, the claim is dropped. If it gives no answer, the claim stays and locks the order until it goes stale, and the model reads “Not refunded: the approvals service did not answer, so the request may have reached the inbox.” - A rule can approve before the row is saved, and its webhook then finds nothing to do. So
askToRefundsettles once itself straight after saving, and with a rule that allows refunds up to €20 the tool answered “Refunded €15.00 for order 1201.” in the same turn. settleclaims the row with one conditionalUPDATEand a fresh claim id, so a webhook delivered twice, or at the same moment as a recheck, refunds once. A settle stuck for five minutes can be taken over, but only the holder of the current claim moves the money and closes the row, so the chat is told once. It reads the request withcheckand refunds only onallowed: truewith no changes. Denied, expired, withdrawn, a paused workspace and an approval with changes all end as “Not refunded” with the reason. For a lowered amount the model reads “Approved only with changes, so nothing was done: ‘Refund €50.00 for order 1003’, for at most 20.00 EUR.” and can ask again for what was approved; the record says “not done: approved with changes”. An approval that came while paused is recorded as “not done: paused”.- To refund a lowered amount instead, refund the decision’s
approved_amountwhenchangedis true and theapproved_summarystill describes this refund, never the amount the model asked for. - The row moves to
refundingbefore the money moves, and the request id goes to your payment provider as the idempotency key, so nothing refunds twice. The outcome is put on the request’s record on a best-effort basis: once money has moved, nothing fails or retries. - A refund call that throws may still have gone through, such as a timeout after the provider paid. The row then stays
unsure, which keeps the order locked, the record says “the refund may have gone through: check the order before retrying”, and the chat is told the same. A row left inrefundingmeans the object stopped mid-refund. Either way, look the refund up at your provider by the request id, then set the row todone. - The answer reaches the chat as a new turn.
finishmarks the row told and then queuestellwiththis.queue, which runs it durably; if queueing fails, the mark is undone and the webhook’s next delivery or the recheck sends it.telladds an “Approval update” message withsaveMessages. The model reads it and tells the customer, who sees it in the chat’s history even if they closed the page. The webhook gets its answer without waiting for the model. this.schedulerunsrecheckten minutes after asking, and again every ten minutes until the request is settled or has expired. That covers a webhook that never came: with the webhook turned off, the refund went through on the next recheck.- Deleting the conversation with
destroywithdraws its open requests, waiting or being settled, so nobody approves a refund that no chat will finish. One that was decided meanwhile refuses the withdrawal; if it was approved, it is recorded as not done. finish,settleandrecheckhave no@callable: only callable methods can be reached from a browser throughrouteAgentRequest. Your Worker calls them over Durable Object RPC.
4. Wake the agent with a signed webhook
import {
verifyWebhook,
WebhookVerificationError,
} from "@variantgate/agent/webhook";
import { ApprovalApiError } from "@variantgate/agent/errors";
import { getAgentByName, routeAgentRequest } from "agents";
import { approvals } from "./approvals";
export { SupportAgent } from "./agent";
export { RefundWorkflow } from "./workflow";
const DECIDED = new Set([
"request.approved",
"request.denied",
"request.expired",
"request.withdrawn",
]);
const FINISHED = new Set(["complete", "errored", "terminated"]);
/** Sends the run its wake-up, unless it has finished or no longer exists. */
async function wake(env: Env, instanceId: string, requestId: string) {
let run: WorkflowInstance;
try {
run = await env.REFUNDS.get(instanceId);
} catch (error) {
if (
error instanceof Error &&
error.message.includes("instance.not_found")
) {
return;
}
throw error;
}
const { status } = await run.status();
if (!FINISHED.has(status)) {
await run.sendEvent({ type: "decided", payload: { requestId } });
}
}
/** POST /variantgate: a request was decided. Only a wake-up. */
async function decided(request: Request, env: Env): Promise<Response> {
if (!env.VARIANTGATE_WEBHOOK_SECRET) {
throw new Error("Set VARIANTGATE_WEBHOOK_SECRET"); // not a bad signature
}
let event;
try {
event = await verifyWebhook(
env.VARIANTGATE_WEBHOOK_SECRET,
request.headers,
await request.text()
);
} catch (error) {
if (error instanceof WebhookVerificationError) {
return new Response(null, { status: 400 });
}
throw error;
}
if (!(DECIDED.has(event.type) && "request_id" in event.data)) {
return new Response(null, { status: 204 });
}
const id = event.data.request_id;
let details: Record<string, unknown>;
try {
// A webhook carries no details: read from the API who asked.
({ details } = await approvals(env).check(id));
} catch (error) {
// Webhooks cover the workspace; another agent key's request is not ours.
if (error instanceof ApprovalApiError && error.status === 404) {
return new Response(null, { status: 204 });
}
throw error;
}
if (typeof details.chat === "string") {
const agent = await getAgentByName(env.SupportAgent, details.chat);
await agent.finish(id); // reads the request again before it acts
}
if (typeof details.workflow === "string") {
await wake(env, details.workflow, id);
}
return new Response(null, { status: 204 });
}
export default {
async fetch(request: Request, env: Env) {
const url = new URL(request.url);
if (url.pathname === "/variantgate" && request.method === "POST") {
return decided(request, env);
}
return (
(await routeAgentRequest(request, env)) ??
new Response("Not found", { status: 404 })
);
},
} satisfies ExportedHandler<Env>;- Add the Worker’s
/variantgateaddress under Settings, Webhooks in your workspace (Pro and up) forrequest.approved,request.denied,request.expiredandrequest.withdrawn, and put itswhsec_secret inVARIANTGATE_WEBHOOK_SECRET. verifyWebhookchecks the signature and that the message is no more than five minutes old. A forged or unsigned one gets a 400 and changes nothing.- A webhook carries no details, so the route reads the request to learn which chat or Workflow asked.
getAgentByNamereturns that chat’s Durable Object, andfinishreads the request again before it acts: the webhook is a notice, never a permission. - Webhooks cover the whole workspace, but an agent key can read only its own requests. A decided request from another agent key reads as not found, and the route answers 204 and does nothing. Any other failure to read the request, such as the API being out of reach, answers 500, so VariantGate delivers the webhook again; the recheck covers it too. A Workflow run that no longer exists, or has finished, is not woken.
routeAgentRequestserves every chat by name at/agents/support-agent/<name>, its messages included. Put your own sign-in in front of it with itsonBeforeConnectandonBeforeRequestoptions.
5. With nobody in a chat: a Workflow
A refund that starts from a form, a queue or a cron trigger needs no chat. Start a run with env.REFUNDS.create({ params: { orderId, amount } }); the same webhook route wakes it.
import {
WorkflowEntrypoint,
type WorkflowEvent,
type WorkflowStep,
} from "cloudflare:workers";
import {
ChangedApprovalError,
NotApprovedError,
} from "@variantgate/agent/errors";
import type { Decision } from "@variantgate/agent/types";
import { approvals, notAsked } from "./approvals";
import { shop } from "./shop"; // your own refund code
interface Params {
amount: string;
orderId: string;
}
const ONE_DAY = 24 * 60 * 60;
const CHECKS = 25; // one an hour, a little longer than the request lives
const MAY_HAVE_GONE_THROUGH =
"the refund may have gone through: check the order before retrying";
/** What one check found, small enough to keep as a step result. */
interface Found {
status: Decision["status"];
pending: boolean;
yes: boolean;
changed: boolean;
paused: boolean;
why: string;
}
const NOT_YET: Found = {
status: "pending",
pending: true,
yes: false,
changed: false,
paused: false,
why: "",
};
/** Reads the request: the only thing that decides what happens. */
async function look(env: Env, id: string): Promise<Found> {
let decision: Decision;
try {
decision = await approvals(env).check(id);
} catch {
return NOT_YET; // the API did not answer: look again at the next check
}
return {
status: decision.status,
pending: decision.status === "pending",
yes: decision.allowed && !decision.changed,
changed: decision.allowed && decision.changed,
paused: decision.status === "approved" && !decision.allowed,
why: decision.allowed
? new ChangedApprovalError(decision).message // used only when changed
: new NotApprovedError(decision).message,
};
}
export class RefundWorkflow extends WorkflowEntrypoint<Env, Params> {
async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
const { orderId, amount } = event.payload;
const env = this.env;
// Kept by Workflows once it returns, so a replay never asks again.
const asked = await step.do("ask", async () => {
try {
const request = await approvals(env).ask({
action: "payment.refund",
summary: `Refund €${amount} for order ${orderId}`,
amount,
currency: "EUR",
details: { order: orderId, workflow: event.instanceId },
ttlSeconds: ONE_DAY,
});
return { id: request.id, why: "" };
} catch (error) {
// Read here: an error leaving a step loses its class.
return { id: "", why: notAsked(error) };
}
});
if (!asked.id) {
return asked.why;
}
let found = await step.do("check 0", () => look(env, asked.id));
for (let i = 1; found.pending && i <= CHECKS; i++) {
try {
// Woken by the webhook route; after an hour it looks anyway.
await step.waitForEvent(`decided ${i}`, {
type: "decided",
timeout: "1 hour",
});
} catch {
// No webhook came: a lost one, or nobody has answered yet.
}
found = await step.do(`check ${i}`, () => look(env, asked.id));
}
if (found.pending) {
await step.do("withdraw", async () => {
await approvals(env)
.withdraw(asked.id)
.catch(() => undefined); // refused if it was answered meanwhile
return true;
});
// Say what the request ended as, not what the last check could read.
const last = await step.do("last check", () => look(env, asked.id));
if (last.status === "withdrawn") {
return "Not refunded: nobody answered in time.";
}
if (last.pending || last.status === "approved") {
await step.do("record late", async () => {
await approvals(env)
.reportOutcome(asked.id, "failed", "not done: not read in time")
.catch(() => undefined);
return true;
});
}
return last.pending
? "Not refunded: no answer could be read in time."
: `Not refunded: the request was ${last.status}, but not read in time.`;
}
if (!found.yes) {
let note = "";
if (found.changed) note = "not done: approved with changes";
if (found.paused) note = "not done: paused";
if (note) {
await step.do("record not done", async () => {
await approvals(env)
.reportOutcome(asked.id, "failed", note)
.catch(() => undefined);
return true;
});
}
return `Not refunded. ${found.why}`;
}
// The last check above is a step of its own. The refund step only ever
// retries the refund with the same key: an attempt may already have paid.
let paid = true;
try {
const retries = {
limit: 2,
delay: "5 seconds",
backoff: "exponential",
} as const;
await step.do("refund", { retries }, async () => {
await shop.refund(orderId, amount, { idempotencyKey: asked.id });
return true;
});
} catch {
paid = false; // retries used up, and any attempt may have gone through
}
await step.do("record outcome", async () => {
await approvals(env)
.reportOutcome(
asked.id,
paid ? "succeeded" : "failed",
paid ? `Refunded €${amount}` : MAY_HAVE_GONE_THROUGH
)
.catch(() => undefined); // never fail the run once money moved
return true;
});
return paid
? `Refunded €${amount} for order ${orderId}.`
: `The refund of €${amount} for order ${orderId} may have gone ` +
"through. Check the order before trying again.";
}
}- Workflows keeps each step’s result and replays it when a run starts again, so the request is made once and a refund step that returned never runs again. A step cut off halfway does run again, which is why the refund passes the request id as its idempotency key.
- The last check is a step of its own, before the refund step. A retry of the refund step only repeats the refund with the same idempotency key and never decides again, since an earlier attempt may already have paid. When the retries run out, the run ends “The refund … may have gone through. Check the order before trying again.” and the record says the same.
- Errors are read inside the step. An error that leaves
step.doloses its class, soinstanceofoutside the step never matches and every failure would look the same. step.waitForEventwaits up to an hour for the event the webhook route sends. When none comes it throws; the run catches that and checks anyway, which covers a lost webhook. A check the API cannot answer counts as no answer yet. After the first check and 25 more, the request is withdrawn and the run ends without a refund. It then reads the request once more and ends with what that says: “nobody answered in time” only when the withdrawal took. An approval that came too late to be read ends as “Not refunded: the request was approved, but not read in time.” and is recorded as not done.- An event sent before the run reaches
waitForEventis kept for it. Extra events from a repeated webhook change nothing: the run moves on as soon as a check finds an answer, and the route sends nothing to a run that has finished. - The run’s output is the sentence it ends with, such as “Not refunded. Not approved: the request is denied (customer kept the item).” Read it with
instance.status()and tell whoever needs to know.
When the answer may take hours
Nothing here waits on an open connection. The request stays open for a day (ttlSeconds); the Durable Object may sleep or be evicted in the meantime, since what it needs is in its SQL table and its schedule, and the Workflow is suspended in waitForEvent. Choose the time to live to suit the action, and the recheck interval by how late an answer may arrive when a webhook is lost. A request that expires ends as “Not refunded. Not approved: the request is expired.” in the chat and in the run’s output.
When Cloudflare’s own approval is enough
If the person in the chat is the one who should decide, needsApproval on the tool and a button in your chat do the job, and an AgentWorkflow can wait in waitForApproval for your own app to call approveWorkflow. VariantGate earns its place when someone else must decide, when nobody is chatting or the work starts unattended, when the question should reach the decider by email, Slack, Teams, Discord or a phone notification, when rules should settle the routine cases, or when you need a record of who approved what and how it went. See the TypeScript client for every method, the AI SDK page for tools that can wait in the turn, or try both sides in the playground.