Prerequisites and scope

An application may encounter the same AI tool call again when a response is replayed or processed by two handlers. Repeating the operation blindly can create duplicate work. This Node.js example keeps a response-scoped ledger keyed by call identifier. It accepts one application-owned tool, lookup_product, with one string SKU argument. Use a current Node.js runtime; the fixture was executed with Node.js 26.13.0 and needs no packages.

The call object is an application adapter contract, not a claim about any provider response format. Parse and translate provider data before dispatching it. Create one ledger for the response-processing session and share it among the handlers that need replay protection. Creating a new ledger for every callback would lose the shared history.

Why the promise is recorded first

The dispatcher validates the tool name and argument shape, snapshots the SKU, creates a promise and stores it before the lookup callback runs. The callback is deferred through Promise.resolve().then(). Two immediate dispatches with the same identifier therefore receive the same promise and cause one lookup execution. The assertion checks promise identity as well as the execution counter.

A repeated identifier with a different SKU raises a conflicting-replay error. This avoids pretending that a previous result answers a different request. Comparing the validated SKU is sufficient for this one-field contract. A tool with several arguments needs a comparison covering every meaningful field, with deliberate handling of defaults and ordering. Arbitrary JSON.stringify comparisons are not a substitute for that contract.

Failure retention and capacity

The ledger retains rejected promises. Replaying a failed call returns the same failure and does not silently start another execution. An orchestrator that wants a new attempt must choose and document a separate retry policy. The test uses an offline failure fixture and confirms the callback ran only once across two rejected dispatches.

The capacity limit bounds distinct identifiers. Existing identifiers can still be replayed after the ledger is full, but a new identifier is rejected. The sample does not evict old entries, since eviction would allow an earlier identifier to execute again. Discard the whole ledger when its response session ends rather than growing it for the lifetime of a server.

Troubleshooting and practical limits

The checks also reject an unexpected argument and an unrecognized tool. Arguments are expected to originate from JSON, so this validator is not a general sandbox for hostile JavaScript objects with getters or proxies. The lookup fixture freezes its flat result to avoid callers changing a shared result object.

This is in-process replay suppression. It does not provide durable exactly-once execution across restarts, worker processes or network failures. A real operation with side effects needs persistence and an appropriate idempotency contract at the operation boundary. The executed fixture performs only an in-memory read-style lookup; no AI service or external tool was contacted.

Complete example

Save as replay.cjs.

const assert = require('node:assert/strict');
function replayLedger(lookup, maxCalls = 32) {
  const entries = new Map();
  return function dispatch(call) {
    if (!call || typeof call.id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(call.id)
        || call.name !== 'lookup_product') throw new TypeError('invalid call');
    const args = call.arguments;
    if (!args || typeof args !== 'object' || Array.isArray(args)
        || Object.keys(args).length !== 1 || !Object.hasOwn(args, 'sku')
        || typeof args.sku !== 'string' || !/^[A-Z0-9-]{1,32}$/.test(args.sku))
      throw new TypeError('invalid arguments');
    const sku = args.sku; // Snapshot before any asynchronous work.
    const existing = entries.get(call.id);
    if (existing) {
      if (existing.sku !== sku) throw new Error('conflicting replay');
      return existing.promise;
    }
    if (entries.size >= maxCalls) throw new Error('ledger full');
    const promise = Promise.resolve().then(() => lookup(sku));
    entries.set(call.id, {sku, promise});
    return promise;
  };
}
async function main() {
  let runs = 0;
  const dispatch = replayLedger(async sku => {
    runs++;
    return Object.freeze({sku, available: true});
  }, 2);
  const call = {id:'call_1', name:'lookup_product', arguments:{sku:'BOOK-1'}};
  const first = dispatch(call);
  const replay = dispatch(call);
  assert.equal(first, replay);
  const results = await Promise.all([first, replay]);
  assert.equal(runs, 1);
  assert.equal(results[0], results[1]);
  assert.throws(() => dispatch({...call, arguments:{sku:'BOOK-2'}}), /conflicting/);
  await dispatch({...call, id:'call_2'});
  assert.throws(() => dispatch({...call, id:'call_3'}), /ledger full/);
  assert.throws(() => dispatch({...call, arguments:{sku:'BOOK-1', extra:1}}), TypeError);
  assert.throws(() => dispatch({...call, name:'delete_product'}), TypeError);
  let failures = 0;
  const failing = replayLedger(async () => { failures++; throw new Error('offline'); });
  await assert.rejects(failing(call), /offline/);
  await assert.rejects(failing(call), /offline/);
  assert.equal(failures, 1);
  console.log('duplicate executions=1; conflicts, capacity and retained failures checked');
}
main().catch(error => { console.error(error); process.exitCode = 1; });

Run and expected output

node replay.cjs
duplicate executions=1; conflicts, capacity and retained failures checked

Primary references

Continue with node.js tutorials and AI tutorials.