Back to The Perch

Developer series, part 2

When a person steps in

Part 1 paused Daniel's $900 refund and resumed it after a manager approved $600. In production that manager might take all afternoon, and your service will probably restart before they answer. Here's how to make sure Daniel gets his refund exactly once.

Where the paused refund lives

A review_required refund won't run until a signed decision comes back, and what the SDK needs to resume it lives in a store you give the review runtime. The store is an interface, DurableHumanReviewContinuationStore, whose methods all have to be atomic and survive a crash. Build it on your own database, or use the one VeriProof hosts:

const reviews = await veriproof.reviews<RefundInput>({
  store: veriproof.hostedReviewStore(),
  revalidate: async ({ input }, reviewResponse) => {
    const order = await orders.get(input.orderId);
    try {
      const amount = approvedAmount(reviewResponse, input.amount);
      return !order.refunded && amount <= order.total;
    } catch {
      return false;
    }
  },
  signalApplication: (continuationId) => jobs.enqueue(continuationId),
});

The demo's live mode uses the hosted store. Callbacks still land on your server and get verified there, then VeriProof keeps the checkpoint and outcome, so any worker can resume without sharing a database with the receiver. Your key needs the review-continuations.write scope. Use your own store when checkpoints have to stay in your environment.

For tests there's InMemoryHumanReviewContinuationStore in @veriproof/sdk-core/testing, which the demo's offline rehearsal runs on. It forgets everything when the process stops, so keep it out of production.

Save before you reply

Here's part 1's review_required branch, filled out:

case 'review_required': {
  const checkpoint = result.review;
  await reviews.save(checkpoint);
  await pending.add({
    continuationId: checkpoint.continuation.outcomeBinding.continuationId,
    customerId: customer.id,
    checkpoint,
  });
  return reply("That's over my limit, so I've asked a manager.");
}

reviews.save() stores what the runtime needs to match a callback to this refund. Keep the whole checkpoint too, because resume() takes it as an argument and refuses to run if it doesn't match the saved copy.

The Teams card reaches the manager seconds after the agent says it has asked. Reply first and crash before saving, and the signed approval arrives with nothing to match. The SDK won't run the refund, which is the safe way to fail, but Daniel was told a manager is on it and nothing will come of it. Save first, and the worst case is a reply that never went out.

Take the callback, then step aside

VeriProof posts the decision to your callback URL, signed with its own ed25519 key. There's no shared secret: the SDK loads VeriProof's public keys from the endpoint you configure. Hand over the body exactly as it arrived:

createServer(async (request, response) => {
  const chunks: Buffer[] = [];
  for await (const chunk of request) chunks.push(chunk);
  const getAll = (name: string) =>
    [request.headers[name.toLowerCase()] ?? []].flat();
  try {
    const received = await reviews.receive(
      new Uint8Array(Buffer.concat(chunks)), { getAll });
    response.writeHead(received.status, { 'content-type': 'application/json' });
    response.end(JSON.stringify(
      received.connectionTest ?? received.receipt ?? {}));
  } catch (error) {
    const retry = error instanceof HumanReviewCallbackError
      && error.code === 'key_set_unavailable';
    response.writeHead(retry ? 503 : 400).end();
  }
}).listen(4601);

The signature covers {webhook-id}.{webhook-timestamp}.{body} byte for byte. Parse the JSON and serialize it again, and key order or spacing can shift, so verification fails, or worse, you trust a copy instead of what VeriProof signed. In Express, give this route express.raw() and keep express.json() off it. Cap the body at 64 KiB before buffering it. A 503 when the key set can't load tells VeriProof to try again later. (HumanReviewCallbackError comes from @veriproof/sdk-core/advanced.)

A first delivery gets 202 and a receipt. An exact repeat gets 200 with replayed: true, and a delivery that conflicts with a stored one gets 409. The portal's connection test lands here too, and the runtime answers it without storing or resuming anything.

Then the listener is done. signalApplication fires once the outcome is safely stored, and the demo's server.mjs uses it to schedule the resume with setImmediate and return the receipt right away. A receipt means "stored", and a refund shouldn't depend on how long one HTTP request stays open.

What happens after review

The refund workflow handles these review outcomes when it calls resume().

  • approved means yes, as asked. The refund runs with its original input, and resume() returns completed with $900.
  • response_submitted is what Daniel's manager sent. The demo's form has one required money field, approved_refund, and the resume mode Resume with response, so the answer reaches your function as reviewResponse. You get completed with $600.
  • rejected ends it. Your function never runs, and resume() returns blocked with reason code review_not_authorized.
  • cancelled and expired end it the same way. Expiry never approves anything. If Daniel still wants his refund, run the check again, and the new review needs its own decision.

Forms can also route an answer to a revision path your app owns; the callback reference covers that. If Daniel gives up first, call veriproof.cancelReview(checkpoint, { reason: 'end_user_cancelled' }) so the card doesn't sit in Teams.

Treat the manager's answer as form data. The demo's approvedAmount() reads approved_refund from reviewResponse.fieldValues, checks it's a USD amount above zero and no more than Daniel asked for, and throws otherwise. The form limits the field to $1 to $2,000, but it has no idea what Daniel asked for. Your code does.

Recheck, then tell Daniel

An approval describes the order as the manager saw it. Before your function runs, revalidate looks at the order as it is now, in case it was refunded some other way. Then VeriProof checks the decision against current policy and runs the check again, so a rule that changed while Daniel waited still applies. That check uses the facts saved in the checkpoint, so the live look at the order belongs in revalidate.

Return false to refuse, and you get blocked with review_revalidation_refused. Throw when you can't tell, say the orders database is down, and the approval isn't used up. You get review_required with review_revalidation_unavailable and can try again.

const result = await reviews.resume(entry.checkpoint, issueRefund);
switch (result.status) {
  case 'completed':
  case 'completed_with_warning':
  case 'transformed':
    await pending.remove(continuationId);
    return tell(entry, `I've refunded $${result.value.amount}.`);
  case 'blocked':
    await pending.remove(continuationId);
    return tell(entry, result.reasonCode === 'review_revalidation_refused'
      ? "Your order changed while it was with my manager, so I've held off."
      : "I couldn't get this refund approved, so I haven't issued it.");
  case 'review_required':
    if (result.reasonCode === 'review_lease_lost'
        || result.reasonCode === 'review_revalidation_unavailable') {
      return retryLater(continuationId, result);
    }
    return; // a manager's question, or nothing to act on yet
  default:
    return retryLater(continuationId, result);
}

issueRefund is part 1's refund function. A manager's refusals all look alike here, so that reply has to fit any of them. default catches a timeout or outage during the recheck. With execution: 'not_started', nothing was refunded and the decision is still waiting, but no new callback will wake you, so schedule the retry yourself.

Restarts and repeat callbacks

resume() takes a lease on the outcome and renews it while the refund runs, so a second worker can't pick up the same decision. Lose the lease before the refund starts and you get review_lease_lost, with the decision still waiting. Within one process, the demo also tracks which continuations it's resuming, so a repeat signal can't start a second resume.

Right before your function runs, the runtime writes a "started" marker to the store, the line between "never ran" and "might have run". If the process dies after it, the next resume() won't refund again. It returns failed with reconciliation_required and execution: 'completion_unknown'. Look in billing, then call reviews.reconcile(checkpoint, true) if the refund went through, or false so a later resume() can try again.

Billing gets its own protection. On resume, invocationId is tied to the protected action, so every attempt at Daniel's refund carries the same idempotency key.

A repeat callback gets the stored receipt and signals your app again, which the demo ignores once that conversation's entry is gone. On startup it resumes every entry still pending and calls reviews.flushAcknowledgments() to resend acknowledgments VeriProof hasn't accepted. That acknowledgment is how VeriProof learns the refund ran, and the portal shows Application resumed only after it arrives. Recover a long-paused continuation covers more restart cases.

Earlier and next in the series

New to the loop? Start with part 1, which wraps the refund in govern(). The runnable examples include a callback receiver for each SDK language.

Next, part 3 looks at the facts behind Daniel's review: which ones your rules can use, and how to send the right ones.

Put a person in the loop

Try the whole loop with Developer, free for 60 days, or see which decisions a sample agent sends to a person first.