Build a human-in-the-loop flow
Pause for a durable decision and resume from an authenticated app route.
Use a wait token when a run needs one external result: an approval, rejection, edit, or operator choice.
| Runlane owns | Your application owns |
|---|---|
| Token state, timeout, first-terminal-write-wins completion, and run resume | Review records, assignments, UI, authentication, authorization, and business audit |
The examples below include both the waiting task and the server-side completion call. Your application still owns the review UI and access policy.
Store the business record first
Create an application record with the document id, reviewer, display data, and business status. Save the Runlane token id on this record after the task creates it.
Do not use runlane.wait.listTokens() as an approval inbox. It filters by token status and creation time. Its summaries omit metadata and output.
Keep token metadata small. Store identifiers, not documents, prompts, or other sensitive bodies.
Share the output definition
Both the waiting task and the completion route import the same definition:
import { waitToken } from '@runlane/core'
import * as z from 'zod'
export const reviewDecision = waitToken({
id: 'review-decision',
output: z.object({ decision: z.enum(['approve', 'reject']) }),
})The id labels this contract in application code; it does not bind stored tokens to a kind.
Create the token once
Call context.wait.createToken() directly. Without an explicit key, Runlane returns the same token for that call on every attempt. The application calls in this example are pseudocode for your review service:
import { ErrorCode, RunlaneError, task } from '@runlane/core'
import * as z from 'zod'
import { reviewDecision } from '../reviews/review-decision.js'
const reviewSchema = z.object({ documentId: z.string() })
export const reviewDocument = task({
id: 'documents.review',
schema: z.object({ reviewId: z.string() }),
async run({ reviewId }, context) {
//////////////////////////////////
// MAKE YOUR API CALLS HERE
//////////////////////////////////
const review = reviewSchema.parse(await loadReview({ reviewId, signal: context.signal }))
const created = await context.wait.createToken({
meta: { documentId: review.documentId, reviewId },
timeout: '7d',
})
const tokenId = created.token.id
//////////////////////////////////
// MAKE YOUR API CALLS HERE
//////////////////////////////////
await saveTokenId({ reviewId, tokenId })
for (let day = 1; ; day += 1) {
const decision = await context.wait.forToken(tokenId, {
...reviewDecision,
reason: 'human_review_pending',
timeout: '1d',
})
if (decision.ok) {
await saveDecision({ decision: decision.output.decision, reviewId })
return
}
if (decision.error.code === ErrorCode.WaitTokenExpired) {
await saveReviewTimeout({ reviewId })
return
}
if (decision.error.code !== ErrorCode.WaitTimedOut) throw new RunlaneError(decision.error)
await context.step.run(`remind-${day}`, { output: z.null() }, async ({ token }) => {
await sendReviewReminder({ idempotencyKey: token, reviewId })
return null
})
}
},
})The task follows this path:
- Load the application review.
- Replay or create its Runlane token.
- Save the token id on the application record.
- Await one day for approval; a pending token parks the attempt.
- Apply a completed decision, save expiry, or send one reminder and wait again.
context.wait.forToken() parks while pending. A daily window timeout returns ok: false with wait_timed_out; it leaves the token pending. The seven-day token deadline returns wait_token_expired. A completed decision returns ok: true with parsed output.
On replay, earlier window timeouts stay timed out, even after approval. Earlier reminder steps reuse their saved results, so the loop sends each reminder once. The next window sees the completed token. Keep timed waits in the same call order per token. Use the reminder step token as the notification provider's idempotency key to cover a crash before the step is saved.
Keyless token creation is counted in call order, so keep those calls in the same order on every attempt.
Make saveTokenId() and saveDecision() idempotent. They sit outside the durable step and may run again.
Choose timeout and retention separately
createToken({ timeout }) controls how long the token may remain pending. Omit it when the decision has no deadline. forToken(..., { timeout }) controls only one wait window, such as the daily reminder interval above.
idempotencyKeyTTL controls how long the same key keeps returning a terminal token. If omitted, ownership remains until that token is pruned.
Useful starting ranges are:
| Decision | Typical timeout |
|---|---|
| Machine callback | 5m to 1h |
| Human review | 1d to 7d |
Use the actual business deadline rather than copying these values blindly.
Complete the token from an app route
Use POST or another state-changing method. Authenticate the reviewer, authorize access to this review, and check current business state. For cookie-authenticated routes, require a CSRF token or require the Origin header to exactly match an allowed application origin.
import { ActorType, type RunlaneRuntime } from '@runlane/core'
import { reviewDecision } from './review-decision.js'
interface PendingReview {
readonly id: string
readonly tokenId: string
}
interface Reviewer {
readonly id: string
}
export async function completeReview(
runlane: RunlaneRuntime,
review: PendingReview,
reviewer: Reviewer,
input: { readonly comment: string; readonly decision: 'approve' | 'reject'; readonly intentId: string },
) {
return runlane.wait.completeToken(reviewDecision, review.tokenId, input, {
actor: { id: reviewer.id, type: ActorType.Operator },
meta: { intentId: input.intentId, reviewId: review.id },
})
}Persist an idempotent decision intent before this call when the application needs a stronger audit or recovery path.
Completion validates input before saving. An invalid decision, such as approved instead of approve, rejects with wait_token_output_invalid and leaves a pending token open for a corrected call.
The waiting task also validates stored output. A schema mismatch returns ok: false with wait_token_output_invalid. The token is already resolved, so recovery needs a new token; waiting again on the same token returns the same error. The example throws on unexpected errors; applications can instead create and wait for a replacement token.
Completion is first-terminal-write-wins. A valid repeat returns already_resolved with the stored completed or timed-out token. Reconcile the application record from that returned token, not from the request body.
Runlane records the actor supplied by your server. It cannot prove that the actor was authenticated. That remains the app's responsibility.
Secure the review flow
- Treat the token id as an identifier, not a bearer credential.
- Authorize both reading and completing the review.
- Escape all document titles, comments, and model output.
- Use a restrictive content security policy.
- Send
Cache-Control: private, no-storeon review responses. - Never complete a token from a
GETrequest.
Operate and test it
Keep maintenance running. It makes timeouts terminal and resumes token-linked runs in bounded batches. The small resume attempt after completion is only a latency improvement.
Test these cases:
- retrying the task reuses the same token;
- an unauthorized reviewer cannot read or complete the review;
- a cross-site request fails its CSRF or exact-origin check;
- repeated and competing decisions use the stored winner;
- a timed-out token cannot later complete;
- the task restarts and replays token creation and earlier reminders;
- approval after two daily timeouts sends each reminder once across replays;
- untrusted content is escaped and never cached;
- maintenance resumes links left after eager completion.
Prune terminal tokens separately from terminal runs. A token is eligible only when it is terminal and no retained run links remain.