Strands Agents

Answer a Strands Agents interrupt with a person's decision from an inbox: a hook asks before a tool runs, in Python or TypeScript.

Strands Agents can stop a run before a tool runs. A hook on BeforeToolCallEvent calls event.interrupt(), the run ends with stop_reason "interrupt" and the interrupt in result.interrupts, and you call the agent again with an interruptResponse for it. On that second pass interrupt() returns the answer, and Strands runs the waiting call without asking the model again. Who answers is up to you. This page makes each interrupt a request in your VariantGate inbox, so a person can answer from a phone, an email link, Slack or Teams, a rule can answer the routine ones, and every answer is kept on the record.

The code ran against strands-agents 1.65.0 on Python 3.12 and @strands-agents/sdk 1.26.0, with a scripted model standing in for Bedrock: approved, denied with a note, approved at a lower amount, unanswered until it was withdrawn, a refund that failed, two refunds in one turn, and the approvals API out of reach. The long-wait version ran with the start and the resume in separate processes, each webhook handled twice at once and replayed, a rule that approved at once, and a resumed run that asked for another refund.

How it fits together

  1. A hook looks at every tool call. Calls that change nothing, such as looking up an order, run as usual.
  2. Any other call raises an interrupt that carries what a person should read: an action name, a summary, the amount.
  3. Your code turns each interrupt into a request and waits for the answer.
  4. It resumes the agent with each decision as the interrupt’s response.
  5. The hook lets the call run only on an approval of exactly what was asked. Otherwise it cancels the call, and the model reads why.

1. Install the client

pip install https://variantgate.com/sdk/variantgate-latest.tar.gz

It has no dependencies beyond the standard library and works on Python 3.9 or newer. Make an agent key under Agents in your workspace and put it in VARIANTGATE_KEY. The client reads it from there.

2. Stop each tool call that changes something

Install Strands too: pip install strands-agents. Without a model= the agent uses Amazon Bedrock; any provider works, since the hook never touches the model.

import asyncio
import contextlib
import json
import time

from strands import Agent, tool
from strands.hooks import (
    AfterToolCallEvent,
    BeforeToolCallEvent,
    HookOrder,
    HookProvider,
    HookRegistry,
)
from strands.interrupt import Interrupt
from variantgate import (
    ApprovalApiError,
    ApprovalClient,
    ChangedApprovalError,
    NotApprovedError,
    VariantGateError,
    is_allowed,
    is_changed,
)

import shop  # your own refund code

approvals = ApprovalClient("support-agent")  # reads VARIANTGATE_KEY
READ_ONLY = {"look_up_order"}  # tools that change nothing run without asking


@tool
def look_up_order(order_id: str) -> str:
    """Look up an order: what was bought, what it cost, how it was delivered."""
    return shop.order(order_id)


@tool
def refund_order(order_id: str, amount_eur: str) -> str:
    """Refund an order to the customer's original payment method.

    Args:
        order_id: The order to refund, such as "1182".
        amount_eur: The amount in euros, such as "49.00".
    """
    refund_id = shop.refund(order_id, amount_eur)
    return f"Refunded €{amount_eur} for order {order_id} as {refund_id}."


def describe(call: dict) -> dict:
    """What a person reads for one tool call. Rules match on the action and the amount."""
    args = call["input"]
    if call["name"] == "refund_order":
        return {
            "action": "payment.refund",
            "summary": f"Refund €{args['amount_eur']} for order {args['order_id']}",
            "amount": args["amount_eur"],
            "currency": "EUR",
            "details": {"order": args["order_id"]},
        }
    preview = json.dumps(args)[:2000]
    return {"action": f"tool.{call['name']}", "summary": f"Run {call['name']}", "details": {"input": preview}}


class AskFirst(HookProvider):
    """Stops each tool call that changes something until a person's decision comes back."""

    def __init__(self) -> None:
        self.ran: set[str] = set()  # tool calls a yes has let through
        self.asked: dict[str, str] = {}  # tool call id -> request id, for the record

    def register_hooks(self, registry: HookRegistry, **kwargs) -> None:
        # After every other hook, so a person approves the call exactly as it will run.
        registry.add_callback(BeforeToolCallEvent, self.before, order=HookOrder.SDK_LAST + 1)
        registry.add_callback(AfterToolCallEvent, self.after)

    async def before(self, event: BeforeToolCallEvent) -> None:
        call = event.tool_use
        if event.cancel_tool or call["name"] in READ_ONLY:
            return
        if call["toolUseId"] in self.ran:  # a retry: one yes is one run
            event.cancel_tool = "Not run again: it already ran once under this approval."
            return
        decision = event.interrupt("variantgate", reason=describe(call))  # stops the run until answered
        if not is_allowed(decision):  # denied, expired, withdrawn or paused
            event.cancel_tool = f"Not done. {NotApprovedError(decision)}"
            if decision.get("status") == "approved":  # approved, but paused
                await record(decision["id"], "failed", "not done: paused")
            return
        if is_changed(decision):  # a person lowered the amount or reworded it
            event.cancel_tool = f"Not done. {ChangedApprovalError(decision)}"
            await record(decision["id"], "failed", "not done: approved with changes")
            return
        self.ran.add(call["toolUseId"])  # let through: from now on, it has run
        self.asked[call["toolUseId"]] = decision["id"]

    async def after(self, event: AfterToolCallEvent) -> None:
        request_id = self.asked.pop(event.tool_use["toolUseId"], None)
        if request_id is None:
            return
        name = event.tool_use["name"]
        if event.exception or event.result["status"] == "error":
            await record(request_id, "failed", f"{name} failed: check before trying again")
        else:
            await record(request_id, "succeeded", f"{name} ran")


async def record(request_id: str, outcome: str, note: str) -> None:
    """Put how it went on the request's record. Best effort: never fails the run."""
    with contextlib.suppress(VariantGateError):
        await asyncio.to_thread(approvals.report_outcome, request_id, outcome, note)

agent = Agent(
    tools=[look_up_order, refund_order],
    hooks=[AskFirst()],
    system_prompt="You help customers with their orders.",
)


def answer(interrupts: list[Interrupt]) -> list[dict]:
    """Ask about every stopped call at once, wait up to 15 minutes in all, pass each answer back."""
    deadline, asked = time.monotonic() + 900, []
    try:
        for interrupt in interrupts:
            asked.append(approvals.ask(**interrupt.reason))
        # One deadline for all: a request still open when it passes is withdrawn.
        decisions = [approvals.wait(request, max(0, deadline - time.monotonic())) for request in asked]
    except BaseException:  # nobody will act on these now: take them back
        take_back(asked)
        raise
    return [
        {"interruptResponse": {"interruptId": interrupt.id, "response": decision}}
        for interrupt, decision in zip(interrupts, decisions, strict=True)
    ]


def take_back(asked: list[dict]) -> None:
    """Withdraw requests nobody will act on. One approved already is recorded as not done."""
    for request in asked:
        with contextlib.suppress(VariantGateError):
            try:
                approvals.withdraw(request["id"])
            except ApprovalApiError as error:
                if error.status != 409:  # 409: decided already
                    raise
                if approvals.check(request["id"])["status"] == "approved":
                    approvals.report_outcome(request["id"], "failed", "not done: the run stopped first")


def run(text: str) -> str:
    result = agent(text)
    while result.stop_reason == "interrupt":  # a resumed run can stop again
        result = agent(answer(result.interrupts))
    return str(result)


if __name__ == "__main__":
    print(run("Order 1182 arrived broken. Please refund the €49."))
  • describe is where you write what a person reads. Give each tool a clear action name and state the amount, so a rule such as “always allow payment.refund up to €20” approves the small ones without anyone waiting. A tool it does not know is still asked about, under tool. and its name.
  • A denied, expired or withdrawn request, or any request while the workspace or this agent is paused, cancels the call. The model gets “Not done. Not approved: the request is denied (Order was already replaced).” as the tool’s result, so it can tell the customer instead of trying again. A request approved while the workspace is paused also gets “not done: paused” on its record, so nobody reads the approval as done.
  • If a person lowers the amount or rewords the request, the call is cancelled, the record says nothing was done, and the model reads what was approved, such as “for at most 20.00 EUR”, and can ask again for that.
  • The hook is added at HookOrder.SDK_LAST + 1. A hook on BeforeToolCallEvent may rewrite tool_use or swap the tool, so this one runs after all of them and a person approves the call as it will run. A call another hook already cancelled is not asked about.
  • A hook on AfterToolCallEvent can set retry. Strands then fires BeforeToolCallEvent again, and interrupt() would hand back the same yes. ran stops that: one approval, one run. Only a call that was let through goes into it, so a retry of a call cancelled for changes reads the changed approval again.
  • After an approved call, after puts succeeded or failed on the request’s record, with a fixed note rather than the tool’s output. A failure to record never fails the run. When a tool raises, Strands gives the model the error text as the result, so keep secrets out of your exceptions. If the model then tries again, that is a new request, and a person decides again.

3. Ask, wait, resume

run calls the agent, and while the result says "interrupt", answer asks about every stopped call at once, so a person sees two refunds from one turn side by side. It waits up to 15 minutes in all, then resumes. The while matters: the resumed run can stop again when the model calls another tool.

  • A request still open after 15 minutes is withdrawn, so nobody approves it after the agent stopped listening, and the call is cancelled with “the request is withdrawn”.
  • If the approvals API cannot be reached or refuses, nobody has said no, so the model is not told that anyone did: ApprovalApiError leaves run, nothing runs, and take_back withdraws the requests already made in that round. One that was approved in the meantime is recorded as “not done: the run stopped first”. The agent is then still waiting on its interrupts, and Strands refuses a plain prompt to it with a TypeError, so begin the conversation again with a new agent. If the connection drops after the API stored a request, that request may still sit in the inbox with nobody waiting on it: deny it there.
  • agent(...) blocks while a person decides. In an async app, use await agent.invoke_async(...) and call answer through asyncio.to_thread.
  • If your own hooks raise interrupts too, answer those in the same loop; Strands collects the interrupts of every hook before it stops.

In TypeScript

npm install @strands-agents/sdk zod
npm install https://variantgate.com/sdk/variantgate-agent-latest.tgz

The TypeScript SDK has the same interrupts. The hook is registered from a Plugin with agent.addHook, cancels through event.cancel, and the agent resumes with agent.invoke(responses). Call await run("…") from your app.

import {
  AfterToolCallEvent,
  Agent,
  BeforeToolCallEvent,
  HookOrder,
  type Interrupt,
  type InterruptResponseContentData,
  type JSONValue,
  type LocalAgent,
  type Plugin,
  type ToolUseData,
  tool,
} from "@strands-agents/sdk";
import { ApprovalClient } from "@variantgate/agent";
import {
  ApprovalApiError,
  ChangedApprovalError,
  NotApprovedError,
} from "@variantgate/agent/errors";
import type { ApprovalRequest, Decision, Outcome } from "@variantgate/agent/types";
import { z } from "zod";
import { shop } from "./shop"; // your own refund code

const approvals = new ApprovalClient({
  agent: "support-agent",
  apiUrl: "https://api.variantgate.com",
  key: process.env.VARIANTGATE_KEY ?? "",
});
const READ_ONLY = new Set(["look_up_order"]); // tools that change nothing
const FIFTEEN_MINUTES = 15 * 60_000;

const lookUpOrder = tool({
  name: "look_up_order",
  description: "Look up an order: what was bought, what it cost, how it was delivered.",
  inputSchema: z.object({ orderId: z.string() }),
  callback: ({ orderId }) => shop.order(orderId),
});

const refundOrder = tool({
  name: "refund_order",
  description: "Refund an order to the customer's original payment method.",
  inputSchema: z.object({
    orderId: z.string().describe("The order, such as 1182"),
    amountEur: z.string().describe("Euros, such as 49.00"),
  }),
  callback: async ({ orderId, amountEur }) => {
    const refundId = await shop.refund(orderId, amountEur);
    return `Refunded €${amountEur} for order ${orderId} as ${refundId}.`;
  },
});

/** What a person reads for one tool call. Rules match on the action and the amount. */
function describe(call: ToolUseData): ApprovalRequest {
  const input = call.input as Record<string, string>;
  if (call.name === "refund_order") {
    return {
      action: "payment.refund",
      summary: `Refund €${input.amountEur} for order ${input.orderId}`,
      amount: input.amountEur,
      currency: "EUR",
      details: { order: input.orderId },
    };
  }
  const preview = JSON.stringify(input).slice(0, 2000);
  return { action: `tool.${call.name}`, summary: `Run ${call.name}`, details: { input: preview } };
}

/** Stops each tool call that changes something until a person's decision comes back. */
class AskFirst implements Plugin {
  readonly name = "variantgate-ask-first";
  private readonly ran = new Set<string>(); // tool calls a yes has let through
  private readonly approved = new Map<string, string>(); // tool call id -> request id

  initAgent(agent: LocalAgent): void {
    // After every other hook, so a person approves the call exactly as it will run.
    agent.addHook(BeforeToolCallEvent, (event) => this.before(event), {
      order: HookOrder.SDK_LAST + 1,
    });
    agent.addHook(AfterToolCallEvent, (event) => this.after(event));
  }

  private async before(event: BeforeToolCallEvent): Promise<void> {
    const call = event.toolUse;
    if (event.cancel || READ_ONLY.has(call.name)) {
      return;
    }
    if (this.ran.has(call.toolUseId)) {
      event.cancel = "Not run again: it already ran once under this approval.";
      return;
    }
    // Stops the run until answered; on resume, returns the answer.
    const decision = event.interrupt<Decision>({
      name: "variantgate",
      reason: describe(call) as unknown as JSONValue,
    });
    if (decision.allowed !== true) {
      // denied, expired, withdrawn or paused
      event.cancel = `Not done. ${new NotApprovedError(decision).message}`;
      if (decision.status === "approved") {
        // approved, but paused
        await record(decision.id, "failed", "not done: paused");
      }
      return;
    }
    if (decision.changed !== false) {
      // a person lowered the amount or reworded it
      event.cancel = `Not done. ${new ChangedApprovalError(decision).message}`;
      await record(decision.id, "failed", "not done: approved with changes");
      return;
    }
    this.ran.add(call.toolUseId); // let through: from now on, it has run
    this.approved.set(call.toolUseId, decision.id);
  }

  private async after(event: AfterToolCallEvent): Promise<void> {
    const requestId = this.approved.get(event.toolUse.toolUseId);
    if (!requestId) {
      return;
    }
    this.approved.delete(event.toolUse.toolUseId);
    const failed = event.error !== undefined || event.result.status === "error";
    const note = failed
      ? `${event.toolUse.name} failed: check before trying again`
      : `${event.toolUse.name} ran`;
    await record(requestId, failed ? "failed" : "succeeded", note);
  }
}

/** Put how it went on the request's record. Best effort: never fails the run. */
async function record(requestId: string, outcome: Outcome, note: string): Promise<void> {
  await approvals.reportOutcome(requestId, outcome, note).catch(() => undefined);
}

export const agent = new Agent({
  tools: [lookUpOrder, refundOrder],
  plugins: [new AskFirst()],
  systemPrompt: "You help customers with their orders.",
});

/** Ask about every stopped call at once, wait for a person, and pass each answer back. */
async function answer(interrupts: Interrupt[]): Promise<InterruptResponseContentData[]> {
  const asked: Decision[] = [];
  try {
    for (const interrupt of interrupts) {
      asked.push(await approvals.ask(interrupt.reason as unknown as ApprovalRequest));
    }
    const decisions = await Promise.all(
      asked.map((request) =>
        approvals.waitForDecision(request, { timeoutMs: FIFTEEN_MINUTES })
      )
    );
    return interrupts.map((interrupt, i) => ({
      interruptResponse: {
        interruptId: interrupt.id,
        response: decisions[i] as unknown as JSONValue,
      },
    }));
  } catch (error) {
    // Nobody will act on these now: take them back.
    await Promise.all(asked.map(takeBack));
    throw error;
  }
}

/** Withdraw a request nobody will act on. One approved already is recorded as not done. */
async function takeBack(request: Decision): Promise<void> {
  try {
    await approvals.withdraw(request.id);
  } catch (error) {
    // 409: decided already. Anything else: nothing more can be done.
    if (!(error instanceof ApprovalApiError && error.status === 409)) {
      return;
    }
    const latest = await approvals.check(request.id).catch(() => undefined);
    if (latest?.status === "approved") {
      await record(request.id, "failed", "not done: the run stopped first");
    }
  }
}

export async function run(text: string): Promise<string> {
  let result = await agent.invoke(text);
  while (result.stopReason === "interrupt") {
    // A resumed run can stop again.
    result = await agent.invoke(await answer(result.interrupts ?? []));
  }
  return result.toString();
}

As in Python, the hook records an approval it could not act on, changed or paused, before it returns, and after records the calls that ran. The waits run in parallel. An unreachable API throws out of run as in Python, with nothing refunded.

When the answer may take hours

Holding a process open for hours is fragile. Instead, let the run end on its interrupts. A session manager saves the conversation and the interrupt state, including the call that is waiting, so a new Agent with the same session id picks up where it stopped, in any process. start runs the agent, park saves the run with the calls it stopped on, and ask_about asks about them without waiting and saves the request ids. When a signed webhook says a request was decided, resume reads every request of the run and answers the interrupts. With the code above saved as support.py:

import contextlib
import json
import logging
import os
import sqlite3
import uuid
from collections.abc import Iterator

from strands import Agent
from strands.agent import AgentResult
from strands.session import FileSessionManager
from variantgate import VariantGateError, verify_webhook

import chat  # your own: sends the agent's answer to the customer
from support import AskFirst, approvals, look_up_order, refund_order, take_back

log = logging.getLogger(__name__)
CLAIM = """UPDATE runs SET claimed = 1
    WHERE id = (SELECT run_id FROM asked WHERE request_id = ?) AND claimed = 0
    RETURNING id, conversation, calls"""
CLAIM_UNASKED = "UPDATE runs SET claimed = 1 WHERE id = ? AND claimed = 0 AND asked = 0 RETURNING calls"
DECIDED = {"request.approved", "request.denied", "request.expired", "request.withdrawn"}
UNASKED = "SELECT id FROM runs WHERE claimed = 0 AND asked = 0"
UNCLAIMED = """SELECT MIN(request_id) FROM asked JOIN runs ON runs.id = asked.run_id
    WHERE claimed = 0 GROUP BY run_id"""


@contextlib.contextmanager
def database() -> Iterator[sqlite3.Connection]:
    """Your database: a connection per call, committed on the way out."""
    with contextlib.closing(sqlite3.connect("runs.db")) as db, db:
        yield db


with database() as db:
    db.execute("""CREATE TABLE IF NOT EXISTS runs
        (id TEXT PRIMARY KEY, conversation TEXT, calls TEXT, asked INT, claimed INT)""")
    db.execute("CREATE TABLE IF NOT EXISTS asked (request_id TEXT PRIMARY KEY, run_id TEXT)")


def agent_for(conversation: str) -> Agent:
    """The conversation's agent, restored from its session with any calls it stopped on."""
    return Agent(
        tools=[look_up_order, refund_order],
        hooks=[AskFirst()],
        session_manager=FileSessionManager(session_id=conversation, storage_dir="sessions"),
        system_prompt="You help customers with their orders.",
    )


def start(conversation: str, text: str) -> None:
    """Raises only before the run is saved, when nothing that needs a yes has run."""
    park(conversation, agent_for(conversation)(text))


def park(conversation: str, result: AgentResult, replaces: str | None = None) -> None:
    """Save the run with the calls it stopped on, then ask about them; or send the answer."""
    interrupts = result.interrupts if result.stop_reason == "interrupt" else []
    run_id = str(uuid.uuid4())
    calls = [[interrupt.id, interrupt.reason, None] for interrupt in interrupts]
    with database() as db:  # one transaction: the new run in, the one it continues out
        if calls:
            db.execute("INSERT INTO runs VALUES (?, ?, ?, 0, 0)", (run_id, conversation, json.dumps(calls)))
        db.execute("DELETE FROM asked WHERE run_id = ?", (replaces,))
        db.execute("DELETE FROM runs WHERE id = ?", (replaces,))
    if not calls:
        chat.send(conversation, str(result))
        return
    try:
        ask_about(run_id)
    except Exception as error:  # the run is saved: never fail into a second one; the sweep goes on
        log.warning("park: run %s stopped: %s", run_id, type(error).__name__)


def ask_about(run_id: str) -> None:
    """Ask about each call of a saved run, without waiting. If that fails, the sweep asks again."""
    with database() as db:
        row = db.execute(CLAIM_UNASKED, (run_id,)).fetchone()
    if row is None:
        return  # asked already, or someone else is asking
    calls, asked = json.loads(row[0]), []
    try:
        for _, reason, _ in calls:
            asked.append(approvals.ask(**reason, ttl_seconds=24 * 3600))
        for call, request in zip(calls, asked, strict=True):
            call[2] = request["id"]
        with database() as db:
            db.execute("UPDATE runs SET calls = ?, asked = 1, claimed = 0 WHERE id = ?", (json.dumps(calls), run_id))
            db.executemany("INSERT INTO asked VALUES (?, ?)", [(request["id"], run_id) for request in asked])
    except BaseException:  # nobody could act on these: take them back, and ask again later
        take_back(asked)
        release(run_id)
        raise
    resume(asked[0]["id"])  # a rule may have answered before the row was saved


def resume(request_id: str) -> None:
    """Call on every signed webhook, and from the sweep. Goes on once, when all are decided."""
    with database() as db:
        row = db.execute(CLAIM, (request_id,)).fetchone()  # take the run in one step
    if row is None:
        return  # not ours, finished, or another delivery has it
    run_id, conversation, calls = row[0], row[1], json.loads(row[2])
    try:
        decisions = [approvals.check(request) for _, _, request in calls]  # the webhook says when; this says what
    except VariantGateError:
        release(run_id)
        raise
    if any(decision["status"] == "pending" for decision in decisions):
        release(run_id)
        return  # the webhook for the last decision goes on
    answers = [
        {"interruptResponse": {"interruptId": interrupt_id, "response": decision}}
        for (interrupt_id, _, _), decision in zip(calls, decisions, strict=True)
    ]
    result = agent_for(conversation)(answers)  # AskFirst lets a call run only on an unchanged yes
    park(conversation, result, replaces=run_id)  # it may stop for a person again


def release(run_id: str) -> None:
    with database() as db:
        db.execute("UPDATE runs SET claimed = 0 WHERE id = ?", (run_id,))


def sweep() -> None:
    """Every few minutes: runs nobody could ask about yet, and runs whose webhook was missed."""
    with database() as db:
        steps = [(ask_about, run_id) for (run_id,) in db.execute(UNASKED)]
        steps += [(resume, request_id) for (request_id,) in db.execute(UNCLAIMED)]
    for step, key in steps:
        try:
            step(key)
        except Exception as error:  # one run's failure must not hold up the others
            log.warning("sweep: %s(%s) failed: %s", step.__name__, key, type(error).__name__)


def on_webhook(headers: dict, body: bytes) -> None:
    """From your handler for signed webhooks, with the raw body. Answer 400 when it raises
    WebhookVerificationError, and 500 for any other error, so the webhook comes again."""
    event = verify_webhook(os.environ["VARIANTGATE_WEBHOOK_SECRET"], headers, body)
    request_id = event["data"].get("request_id")
    if event["type"] in DECIDED and request_id:  # a webhook.test, say, needs nothing
        resume(request_id)
  • The webhook says when, never what. resume reads each decision with check, and the same hook acts only on an unchanged yes, so a pause after the decision still stops the refund. on_webhook refuses a body whose signature does not match (answer 400) and passes on any other error (answer 500, and the webhook comes again later). Other events, such as the test you can send from the webhook settings, get a 2xx and nothing else.
  • Webhooks can arrive twice, and a run with two calls gets one per call. resume claims the run in a single UPDATE … RETURNING before it reads or acts, so only one delivery goes on. While any request of the run is pending, it gives the claim back and the webhook for the last decision continues.
  • A rule can approve before the row is saved, and its webhook would find nothing, so ask_about calls resume once itself. A delivery can also arrive while another holds the claim: run sweep every few minutes. It also asks about runs nobody could ask about yet, logs a run that fails, by its id, and goes on with the others.
  • If the resumed run stops for another approval, park saves the new run in the same transaction that removes the old one, before asking anyone. If asking fails, for example because the API cannot be reached, or the request ids cannot be saved, the requests already made are taken back the same way and the run waits for the sweep to ask again, so the conversation is never left stuck.
  • If anything fails between the claim and saving the result, such as the model on the resumed run, the row stays claimed: a tool may already have run, so look at its requests on the record before you set claimed back to 0. chat.send comes after the row is gone, so a reply that fails is never retried into a second refund.
  • Once park has saved the run, start no longer raises: an error after that, even a model error after a rule-approved refund, is logged by id and left to the sweep or to you, and start returns None. If start raises, it did so before the run was saved, when nothing that needs a yes had run, so a job queue may retry it. Do not retry anything else here: a new run could ask, and refund, again.
  • ttl_seconds keeps each request open for a day instead of 15 minutes. The session files hold the conversation and the decisions: keep them on your server, or use S3SessionManager.
  • In TypeScript, SessionManager with FileStorage saves the same interrupt state. We checked that a new agent with the same sessionId resumed a stopped call in another process; the rest of this version we ran in Python only.

When to add VariantGate

Strands ships its own HumanInTheLoop intervention in both SDKs. With ask="stdio" it asks at the terminal, and an ask function can ask anywhere, with a text prompt and a yes or no. If you run the agent yourself, that is enough. VariantGate earns its place when the agent runs with nobody watching, when someone else must decide, when rules should settle the routine calls by action and amount, or when you need a record of who approved what. The framework comparison goes through that choice, and the playground lets you try the whole loop without signing up.