---
title: Azure Durable Task
description: Add durable execution, approvals, and resumable streaming to AI SDK agents with ai-sdk-azure-durable-task.
url: "https://ai-sdk.dev/docs/agents/azure-durable-task"
docs_index: /llms.txt
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

[`ai-sdk-azure-durable-task`](https://github.com/vercel-labs/ai-sdk-azure-durable-task)
adds durable execution to AI SDK agents using Azure Durable Task Scheduler. Wrap
an existing [`ToolLoopAgent`](/docs/agents/building-agents), or construct a
`DurableTaskAgent` directly. A worker checkpoints model steps and tool activities
so completed work can be reused after a restart.

See [Durability](/docs/agents/durability) for the execution model and a comparison
with [WorkflowAgent](/docs/agents/workflow-agent). For a complete application,
follow the [Next.js cookbook](/cookbook/guides/durable-agent-dts).

This extension is in public preview. Durable activities execute at least once,
not exactly once. Make external mutations idempotent.

## Installation

Use Node.js 22.15 or later. The extension supports AI SDK 6 and 7
(`ai >=6.0.303 <8.0.0`).

```bash
npm install ai-sdk-azure-durable-task ai @microsoft/durabletask-js @microsoft/durabletask-js-azuremanaged
```

Install your chosen model provider separately. Examples using Zod also require
`zod`. PostgreSQL and Redis adapters accept application-owned clients rather
than installing database drivers.

## Quick Start

This in-memory harness uses a scripted model, so it needs **no Docker, Azure
account, or API key**. Save it as `hello.mts` and run `npx tsx hello.mts`.

```ts title="hello.mts"
import { ToolLoopAgent } from 'ai';
import { attachDurability } from 'ai-sdk-azure-durable-task';
import * as testing from 'ai-sdk-azure-durable-task/testing';
const settings = { model: testing.scriptedModel(() => testing.text('Hello!')) };
const nativeAgent = new ToolLoopAgent(settings);
const agent = attachDurability(nativeAgent, { name: 'hello', ...settings });
const harness = testing.createInMemoryHarness();
agent.register(harness.worker);
await harness.worker.start();
try {
  const result = await agent.client(harness.client).run('Hello');
  console.log(result.text);
} finally {
  await harness.close();
}
```

The harness exercises orchestration and activity execution in one process. It
does not preserve state after that process exits; use the emulator or managed
scheduler to test recovery across processes.

## Two Authoring Styles

### Wrap an existing ToolLoopAgent

Use `attachDurability(agent, options)` to reuse an agent's tools and supported
settings:

```ts
const agent = attachDurability(nativeAgent, {
  name: 'support',
  ...settings,
});
```

With an AI SDK 7+ release exposing a public `ToolLoopAgent.settings` getter, the
wrapper can inherit supported `model`, `instructions`, and lifecycle hooks:

```ts
const agent = attachDurability(nativeAgent, { name: 'support' });
```

The [settings-getter proposal](https://github.com/vercel/ai/pull/25757) is still
open; do not assume every SDK 7 release includes it. For earlier versions,
including SDK 6 without that getter, keep `...settings` as in the Quick Start.
Explicit options override inherited values. Durable stores and streaming still
need their own configuration.

The wrapper returns a new durable agent. Calling `nativeAgent.generate()` or
`nativeAgent.stream()` still executes the original, non-durable loop.

### Construct a DurableTaskAgent

Use the extension directly when you do not need to wrap an existing agent:

```ts
import { DurableTaskAgent } from 'ai-sdk-azure-durable-task';

const agent = new DurableTaskAgent({
  name: 'support',
  ...settings,
});
```

Both styles use `agent.register(worker)` and `agent.client(sdkClient)`. Use
`client.run(prompt)` to await a result, `client.start(prompt)` to get a run
handle, or `client.runSession(prompt, { threadId })` for a multi-turn session.
Native options and result shapes are not all interchangeable; check the
[support matrix](https://github.com/vercel-labs/ai-sdk-azure-durable-task/blob/main/docs/support-matrix.md)
before migrating.

## Tool Durability and Policies

Native AI SDK tools execute as durable activities by default. `durableTool`
adds a `ToolPolicy` and execution metadata to the familiar tool definition:

```ts
import { z } from 'zod';
import {
  durableTool,
  RetryPolicy,
  ToolExecution,
  ToolPolicy,
} from 'ai-sdk-azure-durable-task';

const receipt = durableTool({
  description: 'Create a demo receipt. No money moves.',
  inputSchema: z.object({ amount: z.number().positive() }),
  policy: new ToolPolicy({
    execution: ToolExecution.DURABLE,
    retryPolicy: new RetryPolicy({
      maxNumberOfAttempts: 3,
      firstRetryIntervalInMilliseconds: 1000,
      backoffCoefficient: 2,
    }),
    timeoutMs: 30_000,
  }),
  execute: async ({ amount }, options) => ({
    amount,
    receiptId: `demo-${options.durable.idempotencyKey}`,
  }),
});
```

Add it to `tools: { receipt }` when constructing the durable agent.

| Execution policy        | Behavior                                                         | Suitable work                                          |
| ----------------------- | ---------------------------------------------------------------- | ------------------------------------------------------ |
| `ToolExecution.DURABLE` | Checkpointed activity with optional retries and timeout          | Network I/O, database access, and external mutations   |
| `ToolExecution.LOCAL`   | By default, inline in orchestration code and rerun during replay | Small, deterministic, side-effect-free transformations |

`LOCAL` tools cannot configure durable retries or timeouts. Do not put network
requests, wall-clock reads, random values, or other non-deterministic operations
in orchestrator-inline tools. A timeout does not roll back an external mutation.

`options.durable.idempotencyKey` is deterministic for the logical tool call and
stable across its retries. Pass it to a downstream service that atomically
deduplicates mutations and returns the original result. It is not the request
key used to deduplicate turn submission.

### Parallel tool calls

The agent fans out durable tool calls from the same model step and joins their
results before continuing. For custom orchestrations, use the Durable Task
fan-out/fan-in primitive:

```ts
import {
  whenAll,
  type OrchestrationContext,
  type Task,
} from '@microsoft/durabletask-js';

async function* parallelLookups(
  ctx: OrchestrationContext,
): AsyncGenerator<Task<unknown>, unknown, unknown> {
  const tasks = [
    ctx.callActivity('lookup', 'first'),
    ctx.callActivity('lookup', 'second'),
  ];
  return yield whenAll(tasks);
}
```

Register the `lookup` activity and `parallelLookups` orchestrator before starting
the worker. In the JavaScript SDK this is the imported `whenAll(tasks)`, not
`ctx.whenAll(tasks)`. Do not replace durable tasks with `Promise.all` over
uncheckpointed I/O in orchestration code.

## Human-in-the-Loop Tool Approvals

Configure agent-level `toolApproval` rules or a tool's `needsApproval` boolean
or predicate. For example, extend the receipt agent above:

```ts
import {
  DurableTaskAgent,
  InMemoryDecisionStore,
} from 'ai-sdk-azure-durable-task';

const agent = new DurableTaskAgent({
  name: 'reviewed_receipts',
  ...settings,
  tools: { receipt },
  toolApproval: { receipt: 'user-approval' },
  decisionStore: new InMemoryDecisionStore(),
  approvalTimeoutMs: 7 * 24 * 60 * 60 * 1000,
});
```

An undefined agent rule falls back to the tool's `needsApproval` rule. The
runtime persists the gate and waits for a durable external event; it does not
keep an HTTP request open. An approval timeout returns an error tool result
without executing the protected tool.

After starting the run, detect a gate and retrieve the full decision:

```ts
const handle = await client.start('Create a demo receipt for 150');
const outcome = await handle.waitForApprovalOrCompletion();
if ('toolCallId' in outcome) {
  const decision = await handle.pendingDecision();
  // Display decision.input to an authorized reviewer.
}
```

After authenticating the reviewer and validating ownership and the exact
displayed operation, submit their choice with
`handle.approvePending({ approvalToken, approved, reason })`. Set `approved` to
`false` to deny. Repeat this flow for subsequent gates.

`approveToolCall(toolCallId, approved, options)` is a deprecated handle API
without atomic decision receipts. The legacy denial helper is `handle.deny`,
not `denyToolCall`. Both deliver external events, but new application routes
should use token-required `approvePending` with a shared decision store.

`InMemoryDecisionStore` is only for same-process examples. Use
`PostgresDecisionStore` for worker/client separation and decisions that survive
restarts. An approval token is not authorization. The
[cookbook](/cookbook/guides/durable-agent-dts#accept-an-approval) shows the
decision route; add application authentication and reviewer checks before
deployment.

## Worker and Client Separation

Run orchestration, model calls, and tools in a separate, long-lived Node.js
worker. Node.js web routes use `/client` only. Do not start workers in request
handlers or rely on post-response background promises. Neither the worker nor
the route-side client is Edge-compatible.

### Local DTS Emulator

Start the scheduler and dashboard locally:

```bash
docker run --name dts-ai -d -e DTS_USE_DYNAMIC_TASK_HUBS=true \
  -p 127.0.0.1:8080:8080 -p 127.0.0.1:8082:8082 \
  mcr.microsoft.com/dts/dts-emulator:latest
```

The scheduler is at `http://localhost:8080`; the dashboard is at
`http://localhost:8082`. Register the agent from either authoring style:

```ts title="worker.mts"
import { createWorker } from 'ai-sdk-azure-durable-task/worker';
import { agent } from './agent';

const service = createWorker({
  endpoint: 'http://localhost:8080',
  taskhub: 'vercel-ai',
  credential: null,
  register: worker => {
    agent.register(worker);
  },
});
await service.start();
```

Export `agent` from your agent module. Stop the service with `service.stop()` on
shutdown, then close application-owned database and Redis connections.

In a different Node.js process, create a client without importing that agent:

```ts title="client.mts"
import { DurableTaskAzureManagedClientBuilder } from '@microsoft/durabletask-js-azuremanaged';
import { createDurableClient } from 'ai-sdk-azure-durable-task/client';

const sdk = new DurableTaskAzureManagedClientBuilder()
  .endpoint('http://localhost:8080', 'vercel-ai', null)
  .build();
const client = createDurableClient(sdk, { name: 'support' });
try {
  console.log((await client.run('Hello')).text);
} finally {
  await sdk.stop();
}
```

Use the same agent name and version on both sides. Share history, decision
storage, namespaces, tenant scope, and stream configuration when enabling those
features; in-memory stores cannot bridge the two processes.

### Azure Managed Durable Task Scheduler

Install `@azure/identity`, provision a task hub, and assign the identity the
required scheduler permissions. Set the provisioned endpoint and hub name on
both hosts. Replace `null` with `new DefaultAzureCredential()` from
`@azure/identity` in both `createWorker({ credential })` and
`DurableTaskAzureManagedClientBuilder.endpoint(endpoint, taskhub, credential)`.
The emulator's unauthenticated `null` credential is for local use only.

## State, Limits, and Streaming

### Conversation history and claim-check offloading

Use `PostgresHistoryStore({ pool, namespace, tenantId })` for shared history
across worker and web hosts. The application supplies a `pg.Pool`-compatible
pool. Use `SqliteHistoryStore(filename)` for local history; it uses Node.js
`node:sqlite` and is not a cross-host store or a decision store.

With a history store, tool results larger than
`toolOutputOffloadThresholdBytes` (default **32,768 bytes**, approximately
32 KB) are offloaded into immutable history snapshots. Scheduler payloads carry
claim-check references rather than the full result; the model still receives
the hydrated output. This does not shrink the model's context window.

### Generation rollover

`Limits` bounds execution and controls `continueAsNew` rollover:

```ts
import { DurableTaskAgent, Limits } from 'ai-sdk-azure-durable-task';

const agent = new DurableTaskAgent({
  name: 'bounded_support',
  ...settings,
  historyStore,
  toolOutputOffloadThresholdBytes: 32_768,
  limits: new Limits({
    maxSteps: 100,
    maxGenerationBytes: 512_000,
    maxTurnsPerGeneration: 20,
  }),
});
```

The default generation thresholds are **512,000 bytes** (512 KB) and **20
turns**. Rollover carries conversation pointers, unread events, and global
counters into a new scheduler generation; it does not reset the business
step budget. `stepsPerGeneration` is opt-in. `maxSteps` returns completed history
by default; use `throwOnMaxSteps: true` for a hard failure. Custom surrounding
orchestrations must manage their own rollover.

### Resumable useChat streaming

Configure a `RedisStreamBroker({ client, namespace, tenantId })` as the worker's
`streamPublisher` and the client's `streamSubscriber`. Supply an already-connected
Redis client, and retain events for the intended reconnection window.

In the browser, pass `DurableChatTransport` from `/transport` to
[`useChat`](/docs/ai-sdk-ui/chatbot) with `resume: true`. Persist the conversation
ID, messages with stable IDs, and the complete transport cursor together.
Refreshing or disconnecting the reader does not cancel the durable run.

Streaming is **committed-step streaming**: the worker publishes model output
after its checkpoint commits, not token-by-token before commit. Resuming reads
retained events rather than repeating committed model calls. Handle expired
cursors by recovering authoritative state instead of assuming unlimited replay.

The [Next.js cookbook](/cookbook/guides/durable-agent-dts) includes shared
PostgreSQL and Redis initialization, worker lifecycle, Node.js routes, approval
UI, browser persistence, and an interruption/recovery exercise.

## Subpath Exports

These are eight entry points of one package, not separate installations.

| Import                                      | Purpose                                                               | Runtime                            |
| ------------------------------------------- | --------------------------------------------------------------------- | ---------------------------------- |
| `ai-sdk-azure-durable-task`                 | Agents, tools, policies, limits, and orchestration helpers            | Node.js                            |
| `ai-sdk-azure-durable-task/client`          | `createDurableClient`, run handles, and decisions without worker code | Node.js routes and console clients |
| `ai-sdk-azure-durable-task/worker`          | `createWorker`, registration, and lifecycle                           | Long-lived Node.js services        |
| `ai-sdk-azure-durable-task/transport`       | `DurableChatTransport` for `useChat`                                  | Browser                            |
| `ai-sdk-azure-durable-task/stores/postgres` | `PostgresHistoryStore` and `PostgresDecisionStore`                    | Node.js; caller-owned pool         |
| `ai-sdk-azure-durable-task/stores/sqlite`   | `SqliteHistoryStore`                                                  | Node.js with `node:sqlite`         |
| `ai-sdk-azure-durable-task/streaming/redis` | `RedisStreamBroker`                                                   | Node.js; caller-owned client       |
| `ai-sdk-azure-durable-task/testing`         | In-memory harness and scripted models                                 | Node.js tests                      |

Only `/transport` belongs in the browser bundle.

## Next Steps

- [Build a durable Next.js agent](/cookbook/guides/durable-agent-dts)
- [Understand durability and recovery](/docs/agents/durability)
- [Extension developer guide](https://github.com/vercel-labs/ai-sdk-azure-durable-task/blob/main/docs/user-guide.md)
- [Deployment and operations](https://github.com/vercel-labs/ai-sdk-azure-durable-task/blob/main/docs/operations.md)

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)