← Blog

Making an agent's side-effecting tools safe to call twice

Agents repeat tool calls: a retry after a lost response, a model that did not see its own result, a crashed worker that replays its last step. A design for tools that open pull requests, post comments or start resources: deterministic keys, a small ledger, the downstream API's own idempotency, and what to tell the model when a call was a repeat.

Read-only tools are easy. If an agent calls read_file twice, it pays for two reads and nothing else happens. The trouble starts with tools that change the world: open a pull request, post a comment on an issue, send a message, start a sandbox, create a ticket. Call one of those twice and you get two of the thing.

Agents call tools twice more often than you might expect, and usually for reasons that look reasonable from inside the loop. This post covers why it happens, how to make each side-effecting tool safe to repeat, and how to tell the model that a call was a repeat so it stops trying.

How the same call happens twice

  • A retry after a lost answer. The tool sent a request, the other side did the work, and the response was lost to a timeout or a dropped connection. From the caller’s side that looks exactly like a failure, so it retries.
  • The model repeats itself. After a long context, a summarization step, or a result it did not parse, the model decides the comment was never posted and posts it again. Each attempt gets a fresh tool call ID, so the IDs do not reveal the repeat.
  • A worker crashes and resumes. The agent process dies after performing a step but before saving that it did. On restart it replays from the last checkpoint, which includes that step.
  • Parallel calls. A model that emits several tool calls in one turn can emit the same one twice.

The common thread: the caller cannot tell “did not happen” from “happened, but I did not hear about it”. Retrying the first is right; retrying the second duplicates. So the fix has to live in the tool, not in the caller’s retry logic.

Sort your tools first

Kind Examples What to do
Read-only read a file, list issues, fetch a page Nothing. Retry freely.
Naturally idempotent set a label, write a file’s full contents, close an issue Usually nothing. Doing it twice leaves the same end state.
Not idempotent open a PR, post a comment, send a message, start a sandbox, create a ticket Needs a key and a ledger, below.

Some tools can be moved up the table by changing their shape. “Append a line to the changelog” is not idempotent; “set the changelog entry for this task to this text” is.

A deterministic key for each effect

The key has to be the same every time the agent means the same action, and different when it means a different one. A good default is a hash of three things:

  • The task or run ID, so the same comment on two different tasks counts as two actions.
  • The tool name.
  • The arguments, in canonical form, so {"issue": 4, "body": "hi"} and {"body": "hi", "issue": 4} give the same key.

Do not use the model’s tool call ID; a repeated call gets a new one. Do not use a random UUID per call either, since that turns every repeat into a new action, which is the bug you are fixing.

A small ledger in front of the effect

Before performing an effect, record that you are about to. After it succeeds, record the result. A repeat then finds the record and returns the stored result instead of acting again.

import { createHash } from 'node:crypto';

export type Entry =
  | { state: 'pending'; startedAt: Date }
  | { state: 'done'; result: unknown }
  | { state: 'failed'; error: string };

export interface Ledger {
  /** Inserts a pending entry if none exists. Returns null if it inserted, else the existing entry. */
  claim(key: string): Promise<Entry | null>;
  finish(key: string, entry: Entry): Promise<void>;
}

/** Stable JSON: the same arguments in a different key order give the same string. */
function canonical(value: unknown): string {
  if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
  if (value && typeof value === 'object') {
    const obj = value as Record<string, unknown>;
    return `{${Object.keys(obj)
      .sort()
      .map((k) => `${JSON.stringify(k)}:${canonical(obj[k])}`)
      .join(',')}}`;
  }
  return JSON.stringify(value);
}

export function effectKey(taskId: string, tool: string, args: unknown): string {
  return createHash('sha256').update(`${taskId}\n${tool}\n${canonical(args)}`).digest('hex');
}

/** Throw this from an effect when the other side clearly refused and changed nothing. */
export class RefusedError extends Error {}

export type ToolOutcome =
  | { status: 'done'; result: unknown; repeated: boolean }
  | { status: 'in_progress' | 'unknown'; note: string }
  | { status: 'failed'; error: string };

export async function once(
  ledger: Ledger,
  key: string,
  effect: (idempotencyKey: string) => Promise<unknown>,
  staleAfterMs = 10 * 60_000,
): Promise<ToolOutcome> {
  const existing = await ledger.claim(key);
  if (existing?.state === 'done') return { status: 'done', result: existing.result, repeated: true };
  if (existing?.state === 'failed') return { status: 'failed', error: existing.error };
  if (existing?.state === 'pending') {
    const age = Date.now() - existing.startedAt.getTime();
    return age < staleAfterMs
      ? { status: 'in_progress', note: 'The same action is already running. Do not repeat it.' }
      : { status: 'unknown', note: 'An earlier attempt did not report back. Check whether it happened before trying again.' };
  }
  try {
    const result = await effect(key);
    await ledger.finish(key, { state: 'done', result });
    return { status: 'done', result, repeated: false };
  } catch (e) {
    // Only record a failure you know left nothing behind. Anything ambiguous stays pending.
    if (e instanceof RefusedError) {
      await ledger.finish(key, { state: 'failed', error: e.message });
      return { status: 'failed', error: e.message };
    }
    throw e;
  }
}

The ledger needs one property: claiming a key must be atomic, so two concurrent attempts cannot both think they were first. In Postgres that is a primary key and ON CONFLICT:

CREATE TABLE agent_effects (
  key         text PRIMARY KEY,
  state       text NOT NULL CHECK (state IN ('pending', 'done', 'failed')),
  result      jsonb,
  error       text,
  started_at  timestamptz NOT NULL DEFAULT now(),
  finished_at timestamptz
);

-- claim: returns a row only if this attempt inserted it
INSERT INTO agent_effects (key, state) VALUES ($1, 'pending')
ON CONFLICT (key) DO NOTHING
RETURNING key;

-- if nothing came back, read what is there
SELECT state, result, error, started_at FROM agent_effects WHERE key = $1;

Two details in the wrapper carry most of the weight:

  • Ambiguous failures stay pending. If the effect throws a timeout or a connection error, the wrapper does not mark the key failed. It might have happened. Only a clear refusal from the other side, such as a validation error, becomes failed.
  • Stale pending means “go and check”. A pending entry older than a few minutes means an attempt never reported back. The right response is to look, not to retry.

Let the other side deduplicate, where it can

The ledger protects your side. Some APIs can protect theirs too, which closes the gap between “the effect happened” and “the ledger recorded it”. That is why the wrapper hands the key to the effect.

  • Idempotency key headers. Stripe’s API accepts an Idempotency-Key header on POST requests. Per Stripe’s docs, keys can be up to 255 characters, a retry with the same key returns the saved response, a reuse with different parameters is an error, and keys can be pruned once they are at least 24 hours old. A SHA-256 hex key is 64 characters. The IETF HTTP APIs working group has a draft that standardizes the same header for other APIs.
  • Natural uniqueness. GitHub allows one open pull request per head and base branch, and refuses a second with a validation error. If the agent’s branch name comes from the task ID, a repeated “open PR” fails safely, and you can find the existing one with the pull request list endpoint’s head filter.
  • A marker you can search for. When an API has neither, put the key in the thing you create: a hidden HTML comment such as <!-- agent-effect: KEY --> at the end of an issue comment, a label on a resource, a header on a message. Then “did it happen?” becomes a search.

For sandboxes specifically, the same idea applies: label the sandbox with an attempt ID when you create it, and list by label before creating again. Our post on handling sandbox API errors walks through that recovery for a create that timed out.

Tell the model what happened

The model is part of the loop, so it needs to understand the outcome, not just receive it.

  • A repeat returns the original result, marked as a repeat. repeated: true alongside the pull request URL tells the model the PR exists and it should move on. Without the flag, a model that thought it had not acted may now think it acted twice.
  • In progress and unknown are their own answers. “The same action is already running. Do not repeat it.” stops a model from hammering a slow tool. “Check whether it happened before trying again.” points it at a read-only tool.
  • Mention the rule in the tool description. One sentence, such as “calling this again with the same arguments returns the first result instead of acting twice”, saves turns.

When the model really does mean to repeat an action, for example posting a second status update with the same text, the arguments should say so. Give that tool an explicit field such as update_number, so the intent changes the key.

Where this sits next to the sandbox

Idempotency is about effects outside the sandbox: your Git host, your tracker, your messaging. Inside a Sandscale sandbox, a repeated command runs against a throwaway microVM, and the worst a duplicate usually costs is the compute it used. That is one more reason to keep side effects out of the sandbox and in tools you own: there, the ledger, the key and the audit trail are yours. Pair this with human approvals for agent tool calls for the effects that should not happen even once without a person.

Run your agents in a box of their own

Each sandbox is a Firecracker microVM. Free includes 100 awake vCPU-hours a month.

Start free

Keep reading