ai-sdk-azure-durable-task 0.0.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +90 -0
- package/CONTRIBUTING.md +69 -0
- package/LICENSE +22 -0
- package/README.md +324 -2
- package/dist/src/agent.d.ts +110 -0
- package/dist/src/agent.js +1336 -0
- package/dist/src/agent.js.map +1 -0
- package/dist/src/approvals.d.ts +20 -0
- package/dist/src/approvals.js +100 -0
- package/dist/src/approvals.js.map +1 -0
- package/dist/src/client-entry.d.ts +12 -0
- package/dist/src/client-entry.js +7 -0
- package/dist/src/client-entry.js.map +1 -0
- package/dist/src/client.d.ts +109 -0
- package/dist/src/client.js +498 -0
- package/dist/src/client.js.map +1 -0
- package/dist/src/decisions.d.ts +54 -0
- package/dist/src/decisions.js +44 -0
- package/dist/src/decisions.js.map +1 -0
- package/dist/src/durable-chat-transport.d.ts +48 -0
- package/dist/src/durable-chat-transport.js +173 -0
- package/dist/src/durable-chat-transport.js.map +1 -0
- package/dist/src/history-types.d.ts +21 -0
- package/dist/src/history-types.js +6 -0
- package/dist/src/history-types.js.map +1 -0
- package/dist/src/history.d.ts +35 -0
- package/dist/src/history.js +163 -0
- package/dist/src/history.js.map +1 -0
- package/dist/src/http.d.ts +9 -0
- package/dist/src/http.js +67 -0
- package/dist/src/http.js.map +1 -0
- package/dist/src/index.d.ts +25 -0
- package/dist/src/index.js +14 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/logging.d.ts +4 -0
- package/dist/src/logging.js +8 -0
- package/dist/src/logging.js.map +1 -0
- package/dist/src/mcp.d.ts +41 -0
- package/dist/src/mcp.js +112 -0
- package/dist/src/mcp.js.map +1 -0
- package/dist/src/status.d.ts +29 -0
- package/dist/src/status.js +50 -0
- package/dist/src/status.js.map +1 -0
- package/dist/src/steps.d.ts +41 -0
- package/dist/src/steps.js +125 -0
- package/dist/src/steps.js.map +1 -0
- package/dist/src/stores/postgres.d.ts +53 -0
- package/dist/src/stores/postgres.js +140 -0
- package/dist/src/stores/postgres.js.map +1 -0
- package/dist/src/stores/sqlite.d.ts +1 -0
- package/dist/src/stores/sqlite.js +2 -0
- package/dist/src/stores/sqlite.js.map +1 -0
- package/dist/src/streaming/redis.d.ts +33 -0
- package/dist/src/streaming/redis.js +55 -0
- package/dist/src/streaming/redis.js.map +1 -0
- package/dist/src/streaming.d.ts +29 -0
- package/dist/src/streaming.js +64 -0
- package/dist/src/streaming.js.map +1 -0
- package/dist/src/telemetry.d.ts +10 -0
- package/dist/src/telemetry.js +49 -0
- package/dist/src/telemetry.js.map +1 -0
- package/dist/src/testing/index.d.ts +70 -0
- package/dist/src/testing/index.js +165 -0
- package/dist/src/testing/index.js.map +1 -0
- package/dist/src/tools.d.ts +96 -0
- package/dist/src/tools.js +69 -0
- package/dist/src/tools.js.map +1 -0
- package/dist/src/types.d.ts +321 -0
- package/dist/src/types.js +19 -0
- package/dist/src/types.js.map +1 -0
- package/dist/src/validation.d.ts +1 -0
- package/dist/src/validation.js +19 -0
- package/dist/src/validation.js.map +1 -0
- package/dist/src/worker-entry.d.ts +7 -0
- package/dist/src/worker-entry.js +6 -0
- package/dist/src/worker-entry.js.map +1 -0
- package/dist/src/worker.d.ts +24 -0
- package/dist/src/worker.js +107 -0
- package/dist/src/worker.js.map +1 -0
- package/docs/Hosted-DTS.md +115 -0
- package/docs/architecture.md +76 -0
- package/docs/decisions/0001-dual-surface-authoring.md +14 -0
- package/docs/decisions/0002-generator-turn-stepper.md +8 -0
- package/docs/decisions/0003-tools-deps-and-mcp.md +19 -0
- package/docs/decisions/0004-approvals-and-status.md +18 -0
- package/docs/decisions/0005-state-streaming-subagents-versioning.md +19 -0
- package/docs/decisions/0006-maf-entity-session-comparison-and-hybrid-model.md +360 -0
- package/docs/decisions/0007-workflow-world-dts-and-durable-functions-sketch.md +191 -0
- package/docs/decisions/README.md +17 -0
- package/docs/development.md +139 -0
- package/docs/getting-started.md +325 -0
- package/docs/limitations.md +130 -0
- package/docs/operations.md +178 -0
- package/docs/security-and-tenancy.md +41 -0
- package/docs/support-matrix.md +26 -0
- package/docs/user-guide.md +1120 -0
- package/package.json +121 -12
- package/index.js +0 -1
|
@@ -0,0 +1,1120 @@
|
|
|
1
|
+
# Developer guide: using the Durable Task extension for the Vercel AI SDK
|
|
2
|
+
|
|
3
|
+
This guide explains the public APIs of `ai-sdk-azure-durable-task`.
|
|
4
|
+
Start with the [Getting Started Guide](getting-started.md) for installation and
|
|
5
|
+
emulator wiring. Examples below either run with the in-memory harness or export
|
|
6
|
+
factories/handlers whose application dependencies are explicit parameters.
|
|
7
|
+
Use `npx tsx <file>.ts` for standalone Node.js examples.
|
|
8
|
+
|
|
9
|
+
> [!NOTE]
|
|
10
|
+
> **Public Preview:** `ai-sdk-azure-durable-task` `0.1.0` is pre-1.0
|
|
11
|
+
> Preview software for evaluation and feedback. APIs, behaviors, packaging,
|
|
12
|
+
> and support may change or be retired before General Availability.
|
|
13
|
+
|
|
14
|
+
## Authoring durable agents
|
|
15
|
+
|
|
16
|
+
Use `DurableTaskAgent` for an agent defined directly from native AI SDK settings.
|
|
17
|
+
`defineDurableTaskAgent` additionally infers dependency types from `depsFactory`
|
|
18
|
+
and binds them to your tools. `attachDurability` wraps an existing
|
|
19
|
+
`ToolLoopAgent` without rewriting its tools; retain its execution settings
|
|
20
|
+
explicitly because the native instance exposes tools, not its private settings.
|
|
21
|
+
The original instance remains a native agent.
|
|
22
|
+
|
|
23
|
+
This complete example uses structured output, a prepared step, an outer stop
|
|
24
|
+
condition, and worker callbacks:
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { Output, stepCountIs } from "ai";
|
|
28
|
+
import { z } from "zod";
|
|
29
|
+
import { DurableTaskAgent } from "ai-sdk-azure-durable-task";
|
|
30
|
+
import {
|
|
31
|
+
createInMemoryHarness, scriptedModel, text,
|
|
32
|
+
} from "ai-sdk-azure-durable-task/testing";
|
|
33
|
+
|
|
34
|
+
const agent = new DurableTaskAgent({
|
|
35
|
+
name: "summary",
|
|
36
|
+
model: scriptedModel(() => text('{"summary":"Durable execution preserves progress."}')),
|
|
37
|
+
output: Output.object({ schema: z.object({ summary: z.string() }) }),
|
|
38
|
+
stopWhen: stepCountIs(3),
|
|
39
|
+
prepareStep: ({ totalStepNumber }) => ({
|
|
40
|
+
instructions: `Produce a JSON summary. Durable step: ${totalStepNumber}.`,
|
|
41
|
+
temperature: 0,
|
|
42
|
+
}),
|
|
43
|
+
onStepEnd: step => console.log("Step tokens:", step.usage.totalTokens),
|
|
44
|
+
onEnd: event => console.log("Total tokens:", event.totalUsage.totalTokens),
|
|
45
|
+
});
|
|
46
|
+
const harness = createInMemoryHarness();
|
|
47
|
+
agent.register(harness.worker);
|
|
48
|
+
await harness.worker.start();
|
|
49
|
+
try {
|
|
50
|
+
const result = await agent.client(harness.client).run("Summarize durability");
|
|
51
|
+
console.log(result.output.summary);
|
|
52
|
+
} finally {
|
|
53
|
+
await harness.close();
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`prepareStep` receives turn-local `stepNumber`/`steps` and global
|
|
58
|
+
`totalStepNumber`, initial messages, accumulated response messages, and effective
|
|
59
|
+
context. Prepared model, messages, tools, instructions, and call settings are
|
|
60
|
+
applied on the worker. Instruction/runtime-context changes survive rollover.
|
|
61
|
+
`onStepEnd`/`onEnd` are aliases of `onStepFinish`/`onFinish`; hooks execute on the
|
|
62
|
+
worker, not in replay. Hooks are not an exactly-once side-effect mechanism.
|
|
63
|
+
|
|
64
|
+
| Concern | Guidance |
|
|
65
|
+
| --- | --- |
|
|
66
|
+
| AI SDK versions | Declared peer range: `>=6.0.303 <8.0.0`; SDK 6 and 7 |
|
|
67
|
+
| Instructions | `instructions` or `system` |
|
|
68
|
+
| Context / telemetry | `runtimeContext` / `experimental_context`; `telemetry` / `experimental_telemetry` |
|
|
69
|
+
| Structured output | Native `Output.object({ schema })`; inferred `result.output` |
|
|
70
|
+
| Stop conditions | Native `stopWhen` over persisted steps; `Limits` bounds the durable run |
|
|
71
|
+
| Provider retries | Native `maxRetries` defaults to 2; separate from activity retries |
|
|
72
|
+
| Unsupported native settings | Do not silently copy `prepareCall`, `callOptionsSchema`, native `abortSignal`/`timeout`, repair/download callbacks |
|
|
73
|
+
|
|
74
|
+
Native string/tool results, provider metadata, sources, finish reasons, and
|
|
75
|
+
custom `toModelOutput` formats are preserved. Legacy `DurableAgent` and
|
|
76
|
+
`defineDurableAgent` are deprecated, identity-preserving aliases; use the canonical
|
|
77
|
+
`DurableTaskAgent` and `defineDurableTaskAgent` names. This extension uses the
|
|
78
|
+
Durable Task engine, not Workflow DevKit's `WorkflowAgent`.
|
|
79
|
+
See [migration details](#migration-from-native-agents).
|
|
80
|
+
|
|
81
|
+
## Tool durability and execution policies
|
|
82
|
+
|
|
83
|
+
Native `ai.tool()` definitions run as durable activities by default. Use
|
|
84
|
+
`durableTool` to access `options.durable` and worker dependencies, and `ToolPolicy`
|
|
85
|
+
to select retries, timeouts, or local execution.
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import { z } from "zod";
|
|
89
|
+
import {
|
|
90
|
+
durableTool, ToolPolicy, ToolExecution, LocalToolMode, RetryPolicy,
|
|
91
|
+
} from "ai-sdk-azure-durable-task";
|
|
92
|
+
|
|
93
|
+
export const tools = {
|
|
94
|
+
reserve: durableTool({
|
|
95
|
+
inputSchema: z.object({ itemId: z.string() }),
|
|
96
|
+
policy: new ToolPolicy({
|
|
97
|
+
execution: ToolExecution.DURABLE,
|
|
98
|
+
retryPolicy: new RetryPolicy({ maxNumberOfAttempts: 3, firstRetryIntervalInMilliseconds: 1000 }),
|
|
99
|
+
timeoutMs: 10_000,
|
|
100
|
+
}),
|
|
101
|
+
execute: ({ itemId }, options) => ({
|
|
102
|
+
itemId, idempotencyKey: options.durable.idempotencyKey,
|
|
103
|
+
}),
|
|
104
|
+
}),
|
|
105
|
+
normalize: durableTool({
|
|
106
|
+
inputSchema: z.object({ value: z.string() }),
|
|
107
|
+
policy: new ToolPolicy({
|
|
108
|
+
execution: ToolExecution.LOCAL,
|
|
109
|
+
localMode: LocalToolMode.ORCHESTRATOR_INLINE,
|
|
110
|
+
}),
|
|
111
|
+
execute: ({ value }) => value.trim().toLowerCase(),
|
|
112
|
+
}),
|
|
113
|
+
preview: durableTool({
|
|
114
|
+
inputSchema: z.object({ value: z.string() }),
|
|
115
|
+
policy: new ToolPolicy({
|
|
116
|
+
execution: ToolExecution.LOCAL,
|
|
117
|
+
localMode: LocalToolMode.ACTIVITY_INLINE,
|
|
118
|
+
}),
|
|
119
|
+
execute: async ({ value }) => `Preview: ${value}`,
|
|
120
|
+
}),
|
|
121
|
+
};
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
| Execution policy | Behavior |
|
|
125
|
+
| --- | --- |
|
|
126
|
+
| `DURABLE` | Separate activity checkpoint; configured retries/timeouts |
|
|
127
|
+
| `LOCAL` + `ORCHESTRATOR_INLINE` | Pure synchronous replay code; no RPC, I/O, randomness, wall clock, or live deps |
|
|
128
|
+
| `LOCAL` + `ACTIVITY_INLINE` | Runs inside a worker activity with one attempt and no automatic retry |
|
|
129
|
+
|
|
130
|
+
LOCAL policies cannot specify durable retries/timeouts. `maxConcurrency` on the
|
|
131
|
+
agent bounds ordered batches of parallel tools. `toolPolicies` overrides policies
|
|
132
|
+
by tool name; `modelRetryPolicy` separately controls model activity retries.
|
|
133
|
+
Set native `maxRetries: 0` if the activity policy alone should retry the provider.
|
|
134
|
+
Timeout cancellation is cooperative; an external operation may still complete.
|
|
135
|
+
|
|
136
|
+
For mutations, atomically bind `options.durable.idempotencyKey` to the downstream
|
|
137
|
+
operation. The key is stable across attempts and rollover, not an exactly-once
|
|
138
|
+
guarantee. A run-start `idempotencyKey` deduplicates scheduling and is distinct from
|
|
139
|
+
the per-tool effect key.
|
|
140
|
+
|
|
141
|
+
| Tool failure | Result |
|
|
142
|
+
| --- | --- |
|
|
143
|
+
| Ordinary exception | After retries, a model-visible `tool-error` allows recovery |
|
|
144
|
+
| `NonRetryableToolError` | Model-visible business rejection without activity retry |
|
|
145
|
+
| `FatalToolError` | Fails the run rather than continuing the model loop |
|
|
146
|
+
| `failRunOnToolError: true` | Fails the run on tool errors |
|
|
147
|
+
|
|
148
|
+
For example, classify expected business rejections separately from a fatal
|
|
149
|
+
configuration failure:
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
import {
|
|
153
|
+
NonRetryableToolError, FatalToolError,
|
|
154
|
+
} from "ai-sdk-azure-durable-task";
|
|
155
|
+
|
|
156
|
+
export function validateReservation(available: boolean, configured: boolean) {
|
|
157
|
+
if (!configured) throw new FatalToolError("Reservation service is not configured");
|
|
158
|
+
if (!available) throw new NonRetryableToolError("Item is no longer available");
|
|
159
|
+
return { accepted: true };
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## Dependency injection and context
|
|
164
|
+
|
|
165
|
+
Only JSON-serializable `depsInput` crosses the scheduler boundary. Construct
|
|
166
|
+
live database/service clients in `depsFactory` on each worker activity attempt.
|
|
167
|
+
Use `depsCleanup` or `Symbol.asyncDispose`/`Symbol.dispose` to release them on
|
|
168
|
+
success, error, or timeout. Do not dispose a shared pooled client accidentally.
|
|
169
|
+
|
|
170
|
+
This factory keeps dependency input and tool dependencies fully inferred:
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
import type { LanguageModel } from "ai";
|
|
174
|
+
import { z } from "zod";
|
|
175
|
+
import { defineDurableTaskAgent } from "ai-sdk-azure-durable-task/worker";
|
|
176
|
+
|
|
177
|
+
interface CreditApi {
|
|
178
|
+
issue(amount: number, idempotencyKey: string): Promise<{ receiptId: string }>;
|
|
179
|
+
close(): Promise<void>;
|
|
180
|
+
}
|
|
181
|
+
export function buildSupportAgent(
|
|
182
|
+
model: LanguageModel,
|
|
183
|
+
connect: (tenantId: string) => Promise<CreditApi>,
|
|
184
|
+
) {
|
|
185
|
+
return defineDurableTaskAgent({
|
|
186
|
+
name: "support_di", model,
|
|
187
|
+
depsFactory: async (input: { tenantId: string }) => ({
|
|
188
|
+
creditApi: await connect(input.tenantId),
|
|
189
|
+
}),
|
|
190
|
+
depsCleanup: deps => deps.creditApi.close(),
|
|
191
|
+
tools: bind => ({
|
|
192
|
+
credit: bind({
|
|
193
|
+
inputSchema: z.object({ amount: z.number().positive() }),
|
|
194
|
+
execute: ({ amount }, { deps, durable }) =>
|
|
195
|
+
deps.creditApi.issue(amount, durable.idempotencyKey),
|
|
196
|
+
}),
|
|
197
|
+
}),
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
The resulting client requires `{ depsInput: { tenantId } }` at
|
|
203
|
+
`start`, `run`, and `runSession`. Authenticate the tenant before constructing that
|
|
204
|
+
input; model-generated tool arguments are not authority for tenant selection.
|
|
205
|
+
|
|
206
|
+
Use `runtimeContext` for serializable execution context and `toolsContext` for
|
|
207
|
+
per-tool scoped context. Agent `contextSchema` parses runtime context; a tool's
|
|
208
|
+
`contextSchema` parses its context before approval/execution, including inline
|
|
209
|
+
tools. Runtime context is separate from live `deps`.
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
import type { LanguageModel } from "ai";
|
|
213
|
+
import { z } from "zod";
|
|
214
|
+
import { DurableTaskAgent, durableTool } from "ai-sdk-azure-durable-task";
|
|
215
|
+
|
|
216
|
+
export function contextualAgent(model: LanguageModel) {
|
|
217
|
+
return new DurableTaskAgent({
|
|
218
|
+
name: "contextual", model,
|
|
219
|
+
runtimeContext: { locale: "en-US" },
|
|
220
|
+
contextSchema: z.object({ locale: z.string() }),
|
|
221
|
+
toolsContext: { lookup: { region: "west" } },
|
|
222
|
+
tools: {
|
|
223
|
+
lookup: durableTool({
|
|
224
|
+
inputSchema: z.object({ query: z.string() }),
|
|
225
|
+
contextSchema: z.object({ region: z.string() }),
|
|
226
|
+
execute: ({ query }, options) => ({
|
|
227
|
+
query, context: options.context, runtimeContext: options.runtimeContext,
|
|
228
|
+
}),
|
|
229
|
+
}),
|
|
230
|
+
},
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Functions, class instances, cycles, nested `undefined`, and non-finite numbers
|
|
236
|
+
cannot be losslessly serialized. Do not cast away a
|
|
237
|
+
`ToolRequiresDepsNotProvidedByDepsFactory` error: fix the factory or use the
|
|
238
|
+
bound-tools callback.
|
|
239
|
+
|
|
240
|
+
## Conversation state, sessions, and scaling limits
|
|
241
|
+
|
|
242
|
+
`run(prompt)` completes a single run; `start(prompt)` returns a handle.
|
|
243
|
+
Without a store, history is inline and a separate call must explicitly pass
|
|
244
|
+
`messages: previousResult.messages`. A `HistoryStore` persists snapshots and
|
|
245
|
+
thread heads; a `threadId` associates successive runs with conversation history.
|
|
246
|
+
|
|
247
|
+
`runSession` maintains a durable, multi-turn orchestration. Each call on the same
|
|
248
|
+
thread enqueues a turn; `waitForTurn` waits for that handle's turn, and `finish`
|
|
249
|
+
closes the session. See the
|
|
250
|
+
[complete session program](getting-started.md#step-5-run-a-multi-turn-conversational-session).
|
|
251
|
+
|
|
252
|
+
| Store | Import / intended use |
|
|
253
|
+
| --- | --- |
|
|
254
|
+
| `InMemoryHistoryStore` | Root; isolated, same-process tests |
|
|
255
|
+
| `FileHistoryStore(directory)` | Root; persistent local snapshots |
|
|
256
|
+
| `SqliteHistoryStore(filename)` | `/stores/sqlite`; local SQLite snapshots |
|
|
257
|
+
| `PostgresHistoryStore({ pool, namespace, tenantId })` | `/stores/postgres`; caller-owned structural pool; shared, tenant-scoped snapshots |
|
|
258
|
+
|
|
259
|
+
`SqliteHistoryStore` implements `HistoryStore`, not `DecisionStore`; the package
|
|
260
|
+
does not ship a SQLite decision adapter. Use `InMemoryDecisionStore` for a
|
|
261
|
+
same-process demo or `PostgresDecisionStore` for persistent decisions. PostgreSQL
|
|
262
|
+
provides separate history/decision classes.
|
|
263
|
+
Initialize shared stores before serving traffic. The caller creates, configures
|
|
264
|
+
and closes PostgreSQL pools and Redis clients after worker shutdown; adapter
|
|
265
|
+
`close()` never ends caller-owned connections. File/SQLite stores are not cross-host adapters.
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
import type { LanguageModel } from "ai";
|
|
269
|
+
import {
|
|
270
|
+
DurableTaskAgent, InMemoryHistoryStore, Limits,
|
|
271
|
+
} from "ai-sdk-azure-durable-task";
|
|
272
|
+
|
|
273
|
+
export function boundedConversation(model: LanguageModel) {
|
|
274
|
+
return new DurableTaskAgent({
|
|
275
|
+
name: "bounded_chat", model,
|
|
276
|
+
historyStore: new InMemoryHistoryStore(),
|
|
277
|
+
toolOutputOffloadThresholdBytes: 32_768,
|
|
278
|
+
limits: new Limits({
|
|
279
|
+
maxSteps: 100,
|
|
280
|
+
stepsPerGeneration: 10,
|
|
281
|
+
maxTurnsPerGeneration: 4,
|
|
282
|
+
maxGenerationBytes: 512_000,
|
|
283
|
+
}),
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Owned runs automatically `continueAsNew` at configured generation boundaries,
|
|
289
|
+
carrying history pointers, unread events, and global step/cursor counters.
|
|
290
|
+
Defaults are `maxSteps: 100`, `maxTurnsPerGeneration: 20`,
|
|
291
|
+
`maxGenerationBytes: 512_000`; `stepsPerGeneration` is opt-in.
|
|
292
|
+
`maxSteps` returns completed history by default; `throwOnMaxSteps: true` makes
|
|
293
|
+
the business budget a hard failure.
|
|
294
|
+
|
|
295
|
+
With a history store, tool outputs exceeding `toolOutputOffloadThresholdBytes`
|
|
296
|
+
(default 32,768 serialized UTF-8 bytes) are claim-checked and hydrated for the
|
|
297
|
+
model/UI. Rollover bounds scheduler generations, not the provider context window.
|
|
298
|
+
Keep referenced snapshots until no live run needs them.
|
|
299
|
+
|
|
300
|
+
Serialize independent runs for a thread. CAS detects conflicting heads but cannot
|
|
301
|
+
undo effects from a losing run. Session dependency input is fixed at creation;
|
|
302
|
+
status retains only the latest 32 completed turn IDs. Archive older results in
|
|
303
|
+
application storage rather than waiting on evicted turn IDs.
|
|
304
|
+
|
|
305
|
+
## Human-in-the-loop approvals and browser tools
|
|
306
|
+
|
|
307
|
+
Set tool `needsApproval` to a boolean/predicate, or configure agent-level
|
|
308
|
+
`toolApproval` with per-tool statuses/predicates or a generic predicate. Undefined
|
|
309
|
+
agent rules fall back to the tool's rule. `approvalTimeoutMs` bounds parked gates;
|
|
310
|
+
timeouts return an error tool result without executing the protected operation.
|
|
311
|
+
|
|
312
|
+
Use `waitForApprovalOrCompletion` to detect a gate, `pendingDecision` to retrieve
|
|
313
|
+
full typed input, and token-required `approvePending` to submit the reviewed gate.
|
|
314
|
+
This complete offline example handles multiple gates, one decision at a time:
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
import { tool } from "ai";
|
|
318
|
+
import { z } from "zod";
|
|
319
|
+
import {
|
|
320
|
+
DurableTaskAgent, InMemoryDecisionStore,
|
|
321
|
+
} from "ai-sdk-azure-durable-task";
|
|
322
|
+
import {
|
|
323
|
+
createInMemoryHarness, scriptedModel, calls, text,
|
|
324
|
+
} from "ai-sdk-azure-durable-task/testing";
|
|
325
|
+
|
|
326
|
+
const agent = new DurableTaskAgent({
|
|
327
|
+
name: "approvals", decisionStore: new InMemoryDecisionStore(),
|
|
328
|
+
approvalTimeoutMs: 60_000,
|
|
329
|
+
toolApproval: { publish: "user-approval" },
|
|
330
|
+
model: scriptedModel(prompt => prompt.some(m => m.role === "tool")
|
|
331
|
+
? text("Both publications completed.")
|
|
332
|
+
: calls(
|
|
333
|
+
{ name: "publish", id: "publish-1", input: { title: "First" } },
|
|
334
|
+
{ name: "publish", id: "publish-2", input: { title: "Second" } },
|
|
335
|
+
)),
|
|
336
|
+
tools: {
|
|
337
|
+
publish: tool({
|
|
338
|
+
inputSchema: z.object({ title: z.string() }),
|
|
339
|
+
execute: ({ title }) => `Demo publication: ${title}`,
|
|
340
|
+
}),
|
|
341
|
+
},
|
|
342
|
+
});
|
|
343
|
+
const harness = createInMemoryHarness();
|
|
344
|
+
agent.register(harness.worker);
|
|
345
|
+
await harness.worker.start();
|
|
346
|
+
try {
|
|
347
|
+
const handle = await agent.client(harness.client).start("Publish two drafts");
|
|
348
|
+
const submitted = new Set<string>();
|
|
349
|
+
while ("toolCallId" in await handle.waitForApprovalOrCompletion()) {
|
|
350
|
+
const pending = await handle.pendingDecision();
|
|
351
|
+
if (!pending) throw new Error("Missing decision");
|
|
352
|
+
if (submitted.has(pending.approvalToken)) {
|
|
353
|
+
await new Promise(resolve => setTimeout(resolve, 10));
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
console.log("Review:", pending.input);
|
|
357
|
+
await handle.approvePending({
|
|
358
|
+
approvalToken: pending.approvalToken, approved: true, reason: "Demo only",
|
|
359
|
+
});
|
|
360
|
+
submitted.add(pending.approvalToken);
|
|
361
|
+
}
|
|
362
|
+
console.log((await handle.waitForResult()).text);
|
|
363
|
+
} finally {
|
|
364
|
+
await harness.close();
|
|
365
|
+
}
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
This automatically approves **demo** actions, not production operations. In an
|
|
369
|
+
application, review full input in an authorized UI and submit the displayed token.
|
|
370
|
+
Parallel gates can resolve out of order; status/UI updates as each decision arrives.
|
|
371
|
+
Use `InMemoryDecisionStore` only in the same process. Use `PostgresDecisionStore`
|
|
372
|
+
for persistent decisions across hosts; never treat `argsPreview` as the
|
|
373
|
+
authoritative input.
|
|
374
|
+
|
|
375
|
+
An execute-less tool is a **deferred tool**: the worker parks until a browser or
|
|
376
|
+
external client returns its result. Define its native `inputSchema` without
|
|
377
|
+
`execute`; use `handle.resolveDeferredCall(toolCallId, result, { approvalToken })`.
|
|
378
|
+
|
|
379
|
+
```ts
|
|
380
|
+
import type { LanguageModel } from "ai";
|
|
381
|
+
import { tool } from "ai";
|
|
382
|
+
import { z } from "zod";
|
|
383
|
+
import {
|
|
384
|
+
DurableTaskAgent, InMemoryDecisionStore,
|
|
385
|
+
} from "ai-sdk-azure-durable-task";
|
|
386
|
+
|
|
387
|
+
export function browserLocationAgent(model: LanguageModel) {
|
|
388
|
+
return new DurableTaskAgent({
|
|
389
|
+
name: "browser_location", model,
|
|
390
|
+
decisionStore: new InMemoryDecisionStore(),
|
|
391
|
+
tools: {
|
|
392
|
+
location: tool({
|
|
393
|
+
description: "Request the user's location from the browser",
|
|
394
|
+
inputSchema: z.object({ reason: z.string() }),
|
|
395
|
+
}),
|
|
396
|
+
},
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
Register this factory's agent on the worker; the browser must obtain consent
|
|
402
|
+
before returning location data. Replace its in-memory decision store with shared
|
|
403
|
+
persistent decisions in a split-host deployment.
|
|
404
|
+
|
|
405
|
+
The browser transport also sends completed client tool results to the decision
|
|
406
|
+
route. A shared decision store plus `approvePending` with a result is the
|
|
407
|
+
receipt-backed application path. Deferred results are untrusted external input;
|
|
408
|
+
validate and authorize them at the route.
|
|
409
|
+
|
|
410
|
+
Legacy `approve`/`approveToolCall` accept optional tokens and are deprecated.
|
|
411
|
+
Do not use them for new application decision routes. Stale tokens, already-recorded
|
|
412
|
+
decisions, and missing gates have distinct typed errors. Atomic receipts cover
|
|
413
|
+
the decision store; DTS event delivery is at least once, not a cross-service
|
|
414
|
+
transaction. Use an application outbox for unattended delivery recovery.
|
|
415
|
+
See [decision safety details](#decisions-events-and-upgrades).
|
|
416
|
+
|
|
417
|
+
## Multi-agent and custom orchestrations
|
|
418
|
+
|
|
419
|
+
`child.asTool()` turns a durable agent into a native tool backed by a child
|
|
420
|
+
orchestration. Parent handles expose and route child approvals, and stream child
|
|
421
|
+
completion. Bind required child dependency input with
|
|
422
|
+
`child.asTool({ depsInput: ... })`; input mapper functions must be synchronous
|
|
423
|
+
and deterministic, with no live worker dependency access.
|
|
424
|
+
|
|
425
|
+
Inside custom async-generator orchestrators, use `yield*` for durable work:
|
|
426
|
+
|
|
427
|
+
```ts
|
|
428
|
+
import type { LanguageModel } from "ai";
|
|
429
|
+
import type { OrchestrationContext } from "@microsoft/durabletask-js";
|
|
430
|
+
import {
|
|
431
|
+
DurableTaskAgent, durableGenerateText,
|
|
432
|
+
} from "ai-sdk-azure-durable-task";
|
|
433
|
+
|
|
434
|
+
export function createResearchWorkflow(model: LanguageModel) {
|
|
435
|
+
const researcher = new DurableTaskAgent({ name: "researcher", model });
|
|
436
|
+
const writer = new DurableTaskAgent({
|
|
437
|
+
name: "report_writer", model, tools: { research: researcher.asTool() },
|
|
438
|
+
});
|
|
439
|
+
async function* report(ctx: OrchestrationContext, topic: string) {
|
|
440
|
+
const facts = yield* researcher.runInOrchestration(ctx, topic);
|
|
441
|
+
const draft = yield* durableGenerateText(ctx, {
|
|
442
|
+
agent: writer, prompt: `Write a report using: ${facts.text}`, temperature: 0,
|
|
443
|
+
});
|
|
444
|
+
return draft.text;
|
|
445
|
+
}
|
|
446
|
+
return { researcher, writer, report };
|
|
447
|
+
}
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
Register the agents and `addNamedOrchestrator("report", report)` before worker
|
|
451
|
+
startup. For fan-out/fan-in, schedule child orchestrations and use
|
|
452
|
+
`ctx.whenAll(tasks)`; see [example 04](../examples/04_multi_agent_graph.ts).
|
|
453
|
+
Branch on persisted results, and use external-event waits for human decisions.
|
|
454
|
+
Custom orchestrator owners must design their rollover boundary; an embedded agent
|
|
455
|
+
does not transparently `continueAsNew` an arbitrary surrounding workflow.
|
|
456
|
+
|
|
457
|
+
For MCP tools, supply a factory returning a structural `MCPClientLike`:
|
|
458
|
+
`tools(): Promise<ToolSet>` and `close(): Promise<void>`. The SDK does not import
|
|
459
|
+
or depend on `@ai-sdk/mcp`; the application can install a matching client
|
|
460
|
+
(1.x for SDK 6 or 2.x for SDK 7) or provide another implementation.
|
|
461
|
+
Configure worker connection pools and namespaced policies:
|
|
462
|
+
|
|
463
|
+
```ts
|
|
464
|
+
import type { LanguageModel } from "ai";
|
|
465
|
+
import {
|
|
466
|
+
DurableTaskAgent, MCPClientPool, ToolPolicy,
|
|
467
|
+
type MCPClientLike,
|
|
468
|
+
} from "ai-sdk-azure-durable-task";
|
|
469
|
+
|
|
470
|
+
export function mcpAgent(model: LanguageModel, createClient: () => Promise<MCPClientLike>) {
|
|
471
|
+
const pool = new MCPClientPool(createClient);
|
|
472
|
+
const agent = new DurableTaskAgent({
|
|
473
|
+
name: "mcp_assistant", model,
|
|
474
|
+
mcp: { catalog: pool },
|
|
475
|
+
mcpToolPolicies: { catalog__lookup: new ToolPolicy({ timeoutMs: 10_000 }) },
|
|
476
|
+
});
|
|
477
|
+
return { agent, close: () => pool.close() };
|
|
478
|
+
}
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
Pools share discovery, cache tool schemas, and disconnect when idle. Close them
|
|
482
|
+
explicitly after stopping the worker; do not close during active calls. Tool
|
|
483
|
+
names are routed exactly and collisions are rejected. Tool discovery/model calls
|
|
484
|
+
and MCP execution happen on workers, never in deterministic replay.
|
|
485
|
+
|
|
486
|
+
## Reliable streaming and Next.js useChat
|
|
487
|
+
|
|
488
|
+
Use the split topology: **Node.js routes import `/client`; a separate long-lived
|
|
489
|
+
worker imports `/worker`; browsers import `/transport`**. The SDK repository
|
|
490
|
+
does not include application workspaces; use the factories below and
|
|
491
|
+
[route example](../examples/09_nextjs_route_client.ts) in your own web application.
|
|
492
|
+
|
|
493
|
+
Configure matching `StreamPublisher` and `StreamSubscriber` implementations.
|
|
494
|
+
`InMemoryStreamBroker` is both in one process; `RedisStreamBroker` is the shared
|
|
495
|
+
adapter for separate hosts. A publisher selects worker `streamText`; without a
|
|
496
|
+
subscriber, the response helper falls back to completed text.
|
|
497
|
+
|
|
498
|
+
This factory creates worker-side lifecycle and route-side client configuration.
|
|
499
|
+
Its store/broker arguments can be PostgreSQL and Redis adapters:
|
|
500
|
+
|
|
501
|
+
```ts
|
|
502
|
+
import type { LanguageModel } from "ai";
|
|
503
|
+
import type { DTSClient, HistoryStore, DecisionStore, StreamBroker } from "ai-sdk-azure-durable-task";
|
|
504
|
+
import { DurableTaskAgent, createWorker } from "ai-sdk-azure-durable-task/worker";
|
|
505
|
+
import { createDurableClient } from "ai-sdk-azure-durable-task/client";
|
|
506
|
+
|
|
507
|
+
export function splitAgent(
|
|
508
|
+
model: LanguageModel, sdk: DTSClient, historyStore: HistoryStore,
|
|
509
|
+
decisionStore: DecisionStore, broker: StreamBroker,
|
|
510
|
+
) {
|
|
511
|
+
const agent = new DurableTaskAgent({
|
|
512
|
+
name: "chat", model, historyStore, decisionStore,
|
|
513
|
+
streamPublisher: broker, streamSubscriber: broker,
|
|
514
|
+
});
|
|
515
|
+
const service = createWorker({
|
|
516
|
+
endpoint: "http://localhost:8080", taskhub: "vercel-ai", credential: null,
|
|
517
|
+
register: worker => { agent.register(worker); },
|
|
518
|
+
});
|
|
519
|
+
const client = createDurableClient(sdk, {
|
|
520
|
+
name: "chat", historyStore, decisionStore, streamSubscriber: broker,
|
|
521
|
+
});
|
|
522
|
+
return { service, client };
|
|
523
|
+
}
|
|
524
|
+
```
|
|
525
|
+
|
|
526
|
+
The factory illustrates matching contracts; deploy the two sides as separate
|
|
527
|
+
modules/processes so the route never imports the model or worker graph.
|
|
528
|
+
Use the same name/version, output parser, namespaces, tenant scope, and stores.
|
|
529
|
+
In an authorized Node route, `await handle.toUIMessageStreamResponse({ cursor })`
|
|
530
|
+
returns native AI SDK SSE. A reader abort/timeout does not terminate the workflow.
|
|
531
|
+
|
|
532
|
+
Install `pg` and `redis` in your application for these example clients, not as
|
|
533
|
+
SDK dependencies. Adapters accept pure TypeScript `PgPoolLike`/`PgClientLike`
|
|
534
|
+
and `RedisClientLike` interfaces, without driver declarations or dynamic imports.
|
|
535
|
+
Construct clients using application-supplied connection settings and the same
|
|
536
|
+
namespace/tenant on both hosts:
|
|
537
|
+
|
|
538
|
+
```ts
|
|
539
|
+
import pg from "pg";
|
|
540
|
+
import { createClient } from "redis";
|
|
541
|
+
import {
|
|
542
|
+
PostgresHistoryStore, PostgresDecisionStore,
|
|
543
|
+
} from "ai-sdk-azure-durable-task/stores/postgres";
|
|
544
|
+
import { RedisStreamBroker } from "ai-sdk-azure-durable-task/streaming/redis";
|
|
545
|
+
|
|
546
|
+
export async function sharedState(databaseUrl: string, redisUrl: string, tenantId: string) {
|
|
547
|
+
const scope = { namespace: "support-app", tenantId };
|
|
548
|
+
const pool = new pg.Pool({ connectionString: databaseUrl });
|
|
549
|
+
pool.on("error", error => console.error("Postgres connection error", error.message));
|
|
550
|
+
const client = createClient({ url: redisUrl });
|
|
551
|
+
client.on("error", error => console.error("Redis connection error", error.message));
|
|
552
|
+
const history = new PostgresHistoryStore({ ...scope, pool });
|
|
553
|
+
const decisions = new PostgresDecisionStore({ ...scope, pool });
|
|
554
|
+
const broker = new RedisStreamBroker({ ...scope, client, maxLength: 10_000 });
|
|
555
|
+
try {
|
|
556
|
+
await client.connect();
|
|
557
|
+
await Promise.all([history.initialize(), decisions.initialize(), broker.probe()]);
|
|
558
|
+
return {
|
|
559
|
+
history, decisions, broker,
|
|
560
|
+
close: () => Promise.all([pool.end(), client.quit()]),
|
|
561
|
+
};
|
|
562
|
+
} catch (error) {
|
|
563
|
+
await pool.end();
|
|
564
|
+
if (client.isOpen) client.destroy();
|
|
565
|
+
throw error;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
```
|
|
569
|
+
|
|
570
|
+
Authenticate the tenant before invoking the factory. Load connection settings from
|
|
571
|
+
your application's secret management, not committed source. Configure TLS, store
|
|
572
|
+
retention, schema permissions, and tenant isolation for your deployment.
|
|
573
|
+
|
|
574
|
+
Install the AI SDK React binding matching your SDK major in the web app. This
|
|
575
|
+
browser-only hook wires `useChat` and persists the entire cursor state:
|
|
576
|
+
|
|
577
|
+
```ts
|
|
578
|
+
import { useChat } from "@ai-sdk/react";
|
|
579
|
+
import { useMemo } from "react";
|
|
580
|
+
import type { UIMessage } from "ai";
|
|
581
|
+
import {
|
|
582
|
+
DurableChatTransport, type DurableUiCursor,
|
|
583
|
+
} from "ai-sdk-azure-durable-task/transport";
|
|
584
|
+
|
|
585
|
+
export function useDurableChat(chatId: string, cachedMessages: UIMessage[]) {
|
|
586
|
+
const transport = useMemo(() => new DurableChatTransport({
|
|
587
|
+
api: "/api/runs",
|
|
588
|
+
storage: {
|
|
589
|
+
get: id => {
|
|
590
|
+
const value = sessionStorage.getItem(`durable:${id}`);
|
|
591
|
+
return value ? JSON.parse(value) as DurableUiCursor : undefined;
|
|
592
|
+
},
|
|
593
|
+
set: (id, state) => sessionStorage.setItem(`durable:${id}`, JSON.stringify(state)),
|
|
594
|
+
},
|
|
595
|
+
}), []);
|
|
596
|
+
return useChat({ id: chatId, transport, messages: cachedMessages, resume: true });
|
|
597
|
+
}
|
|
598
|
+
```
|
|
599
|
+
|
|
600
|
+
Scope storage keys/chat IDs to the authenticated subject and tenant; clear them
|
|
601
|
+
on sign-out. Persist the **message list as well as cursor state** in the app.
|
|
602
|
+
Keep the partial assistant with its stable ID when resuming. If no message cache
|
|
603
|
+
exists, reset the cursor to zero and rebuild from retained events.
|
|
604
|
+
|
|
605
|
+
The transport submits the newest user message/attachments, binds `chatId` to a
|
|
606
|
+
durable thread, and sends approval/browser-tool results to the same run.
|
|
607
|
+
It reconnects from the consumed cursor after refresh or an approval boundary,
|
|
608
|
+
without scheduling a replacement run. A retention gap is explicit (HTTP 410);
|
|
609
|
+
fetch authoritative status/result rather than pretending missing chunks exist.
|
|
610
|
+
|
|
611
|
+
Streaming is **committed-step streaming**, not pre-commit per-token latency.
|
|
612
|
+
Chunks publish only after the model checkpoint commits. Stable assistant
|
|
613
|
+
start/finish spans steps; a parked approval does not finish that assistant.
|
|
614
|
+
Projection retries redeliver the same immutable output instead of rerunning a
|
|
615
|
+
successful model call. Broker retention is separate from durable execution history.
|
|
616
|
+
See [stream/cursor details](#streaming-and-mcp).
|
|
617
|
+
|
|
618
|
+
## In-flight versioning and migrations
|
|
619
|
+
|
|
620
|
+
`version` identifies a registered execution contract. `previousVersions` retains
|
|
621
|
+
complete old configurations so in-flight runs can drain on their recorded
|
|
622
|
+
version. Keep old models, tools, limits, dependency factories, and stores available.
|
|
623
|
+
This factory registers an explicit migration and retains version 1:
|
|
624
|
+
|
|
625
|
+
```ts
|
|
626
|
+
import type { LanguageModel } from "ai";
|
|
627
|
+
import { tool } from "ai";
|
|
628
|
+
import { z } from "zod";
|
|
629
|
+
import { DurableTaskAgent, InMemoryDecisionStore } from "ai-sdk-azure-durable-task";
|
|
630
|
+
|
|
631
|
+
export function versionedAgent(model: LanguageModel) {
|
|
632
|
+
const decisionStore = new InMemoryDecisionStore();
|
|
633
|
+
const config = (version: string) => ({
|
|
634
|
+
name: "versioned", version, model, decisionStore,
|
|
635
|
+
tools: {
|
|
636
|
+
payout: tool({
|
|
637
|
+
inputSchema: z.object({ amount: z.number().positive() }),
|
|
638
|
+
needsApproval: true,
|
|
639
|
+
execute: ({ amount }) => `Demo ${version}: ${amount}`,
|
|
640
|
+
}),
|
|
641
|
+
},
|
|
642
|
+
});
|
|
643
|
+
return new DurableTaskAgent({
|
|
644
|
+
...config("v2"),
|
|
645
|
+
previousVersions: { v1: config("v1") },
|
|
646
|
+
migrations: {
|
|
647
|
+
"v1->v2": ({ state, payload }) => {
|
|
648
|
+
const { amount } = z.object({ amount: z.number().positive() }).parse(payload);
|
|
649
|
+
const pending = state.pendingTurn?.calls.find(call => call.toolName === "payout");
|
|
650
|
+
if (!pending) throw new Error("Upgrade requires a parked payout");
|
|
651
|
+
pending.input = { amount };
|
|
652
|
+
return state;
|
|
653
|
+
},
|
|
654
|
+
},
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
Start an old run with `{ version: "v1" }`, wait for its parked gate, then call
|
|
660
|
+
`await handle.upgrade("v2", { amount: 275 })`. Poll `customStatus` until the new
|
|
661
|
+
version/generation is visible, display the new pending decision, and obtain
|
|
662
|
+
**fresh approval**. A previous token never authorizes migrated arguments.
|
|
663
|
+
|
|
664
|
+
Migrations receive serializable state/payload and must be deterministic.
|
|
665
|
+
Conflicting registrations for the same name/version fail preflight; retained
|
|
666
|
+
child versions coalesce under stable dispatchers. Route clients need matching
|
|
667
|
+
old output parsers/stores in their own `previousVersions` configuration.
|
|
668
|
+
See [example 07](../examples/07_versioning_and_migration.ts) and
|
|
669
|
+
[version drain guidance](operations.md).
|
|
670
|
+
|
|
671
|
+
## Unit and integration testing
|
|
672
|
+
|
|
673
|
+
Import test fixtures only from `/testing`. `createInMemoryHarness` executes real
|
|
674
|
+
Durable Task replay/activity logic without network infrastructure; it is not a
|
|
675
|
+
production persistence backend. `scriptedModel` supplies deterministic provider
|
|
676
|
+
responses and synthetic usage.
|
|
677
|
+
|
|
678
|
+
```ts
|
|
679
|
+
import assert from "node:assert/strict";
|
|
680
|
+
import { DurableTaskAgent } from "ai-sdk-azure-durable-task";
|
|
681
|
+
import {
|
|
682
|
+
createInMemoryHarness, scriptedModel, text,
|
|
683
|
+
} from "ai-sdk-azure-durable-task/testing";
|
|
684
|
+
|
|
685
|
+
const agent = new DurableTaskAgent({
|
|
686
|
+
name: "test_hello", model: scriptedModel(() => text("Hello")),
|
|
687
|
+
});
|
|
688
|
+
const harness = createInMemoryHarness();
|
|
689
|
+
agent.register(harness.worker);
|
|
690
|
+
await harness.worker.start();
|
|
691
|
+
try {
|
|
692
|
+
const result = await agent.client(harness.client).run("Greet me");
|
|
693
|
+
assert.equal(result.text, "Hello");
|
|
694
|
+
assert.equal(result.totalUsage.totalTokens, 20);
|
|
695
|
+
assert(harness.worker.executedActivities.some(a => a.name.endsWith("__model_step")));
|
|
696
|
+
} finally {
|
|
697
|
+
await harness.close();
|
|
698
|
+
}
|
|
699
|
+
```
|
|
700
|
+
|
|
701
|
+
`MockLanguageModelV3` supports SDK 6 fixtures; `MockLanguageModelV4` supports SDK 7.
|
|
702
|
+
Use `scriptedModel(script, "v4")` with SDK 7 when selecting the model protocol
|
|
703
|
+
explicitly. Both mocks are exported from `/testing`; do not mix their protocol
|
|
704
|
+
versions unintentionally. Streaming fixtures use native simulated AI SDK streams.
|
|
705
|
+
|
|
706
|
+
From the repository:
|
|
707
|
+
|
|
708
|
+
```powershell
|
|
709
|
+
npm run build
|
|
710
|
+
npm run typecheck
|
|
711
|
+
npm test
|
|
712
|
+
npm run check:package
|
|
713
|
+
npm run test:emulator
|
|
714
|
+
```
|
|
715
|
+
|
|
716
|
+
Hosted tests need configured Azure identity/endpoint and explicitly skip without
|
|
717
|
+
them. Emulator/offline success is not commercial-provider or hosted acceptance.
|
|
718
|
+
See [development](development.md), [hosted DTS](Hosted-DTS.md), and
|
|
719
|
+
[support matrix](support-matrix.md).
|
|
720
|
+
|
|
721
|
+
## Detailed contracts and migration reference
|
|
722
|
+
|
|
723
|
+
The sections below document the compatibility and safety boundaries behind the
|
|
724
|
+
examples. Use them when migrating existing agents or implementing custom adapters.
|
|
725
|
+
|
|
726
|
+
## Start with the bound-tools factory: no explicit generics
|
|
727
|
+
|
|
728
|
+
Author the worker contract first. `defineDurableTaskAgent` infers the dependency
|
|
729
|
+
input, live dependency object, tool inputs/outputs and final output. Do not start
|
|
730
|
+
with a four-parameter generic list or cast a dependency mismatch away.
|
|
731
|
+
|
|
732
|
+
```ts
|
|
733
|
+
import { defineDurableTaskAgent } from "ai-sdk-azure-durable-task/worker";
|
|
734
|
+
import type { LanguageModel } from "ai";
|
|
735
|
+
import { z } from "zod";
|
|
736
|
+
|
|
737
|
+
interface CreditApi {
|
|
738
|
+
issue(amount: number, idempotencyKey: string): Promise<{ receiptId: string }>;
|
|
739
|
+
close(): Promise<void>;
|
|
740
|
+
}
|
|
741
|
+
export function buildSupportAgent(
|
|
742
|
+
model: LanguageModel,
|
|
743
|
+
connect: (tenantId: string) => Promise<CreditApi>,
|
|
744
|
+
) {
|
|
745
|
+
return defineDurableTaskAgent({
|
|
746
|
+
name: "support", model,
|
|
747
|
+
depsFactory: async (input: { tenantId: string }) => ({
|
|
748
|
+
creditApi: await connect(input.tenantId),
|
|
749
|
+
}),
|
|
750
|
+
depsCleanup: deps => deps.creditApi.close(),
|
|
751
|
+
tools: bind => ({
|
|
752
|
+
credit: bind({
|
|
753
|
+
inputSchema: z.object({ amount: z.number().positive() }),
|
|
754
|
+
needsApproval: ({ amount }) => amount > 100,
|
|
755
|
+
execute: ({ amount }, { deps, durable }) =>
|
|
756
|
+
deps.creditApi.issue(amount, durable.idempotencyKey),
|
|
757
|
+
}),
|
|
758
|
+
}),
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
```
|
|
762
|
+
|
|
763
|
+
Only JSON `depsInput` crosses the wire. `CreditApi` is constructed per worker
|
|
764
|
+
attempt, never serialized or accessed from replay. The downstream service must
|
|
765
|
+
atomically honor the supplied idempotency key. The result of `buildSupportAgent`
|
|
766
|
+
requires `{depsInput:{tenantId:string}}` at `start`/`run`/`runSession`, and exposes
|
|
767
|
+
exact `credit` tool-call input types. Add native `Output.object({schema})` to infer
|
|
768
|
+
structured `result.output` too. Register before starting the long-lived worker:
|
|
769
|
+
|
|
770
|
+
```ts
|
|
771
|
+
const agent = buildSupportAgent(model, connectCreditApi);
|
|
772
|
+
agent.register(worker);
|
|
773
|
+
await worker.start(); // on the worker host, not inside an HTTP request
|
|
774
|
+
const handle = await agent.client(sdk).start("Credit 350", {
|
|
775
|
+
depsInput: { tenantId: authenticatedSession.tenantId },
|
|
776
|
+
});
|
|
777
|
+
```
|
|
778
|
+
|
|
779
|
+
`model`, `worker`, `sdk`, `connectCreditApi` and `authenticatedSession` in the
|
|
780
|
+
second fragment are application integrations. For complete runnable wiring see
|
|
781
|
+
[the split Next.js/worker guide](#reliable-streaming-and-nextjs-usechat); for isolated engine work
|
|
782
|
+
import `createInMemoryHarness` from `/testing`. Node routes import `/client`,
|
|
783
|
+
not model/tool registration code. This is not an Edge-compatible package.
|
|
784
|
+
|
|
785
|
+
## Migration from native agents
|
|
786
|
+
|
|
787
|
+
`attachDurability(native, settings)` and `extractToolLoopAgentSettings` copy the
|
|
788
|
+
public `native.tools` property. They do **not** intercept the source agent's
|
|
789
|
+
`.generate()`/`.stream()` or inspect private settings. Current SDK 6/7
|
|
790
|
+
`ToolLoopAgent` declarations keep `settings` private, so keep the original config
|
|
791
|
+
in an application-owned variable and pass it explicitly.
|
|
792
|
+
|
|
793
|
+
An application-owned `{ tools, settings }` wrapper or a public `settings` getter
|
|
794
|
+
can supply supported defaults instead:
|
|
795
|
+
|
|
796
|
+
```ts
|
|
797
|
+
const durable = attachDurability(
|
|
798
|
+
{ tools: nativeAgent.tools, settings: retained },
|
|
799
|
+
{ name: "support", temperature: 0 },
|
|
800
|
+
);
|
|
801
|
+
```
|
|
802
|
+
|
|
803
|
+
Public defaults include `model`, `instructions`/`system`, `output`, `stopWhen`,
|
|
804
|
+
`prepareStep`, `toolApproval`, `onStepFinish`/`onStepEnd`, `onFinish`/`onEnd`,
|
|
805
|
+
`experimental_telemetry`/`telemetry`, `experimental_context`/`runtimeContext`,
|
|
806
|
+
`toolsContext`, `contextSchema`, tool selection/provider options and ordinary
|
|
807
|
+
call settings. Explicit options override defaults (including instruction,
|
|
808
|
+
context and telemetry aliases); source tools remain authoritative. Worker-only
|
|
809
|
+
policies, factories, stores and durable names still belong in the explicit options.
|
|
810
|
+
Unsupported public settings fail rather than being silently dropped.
|
|
811
|
+
|
|
812
|
+
**Public API boundary:** TypeScript-private SDK `settings` currently compiles to
|
|
813
|
+
an ordinary JavaScript field. Simply testing `"settings" in nativeAgent` would
|
|
814
|
+
read private internals today. The adapter therefore ignores that native field
|
|
815
|
+
but accepts a public getter, including one added by a future SDK. If the SDK only
|
|
816
|
+
changes the field's TypeScript visibility without adding a getter, runtime
|
|
817
|
+
detection cannot distinguish it from the old private field; that change needs an
|
|
818
|
+
explicit compatibility update. No claim of automatic support for that case is made.
|
|
819
|
+
|
|
820
|
+
| Native setting | Migration action |
|
|
821
|
+
|---|---|
|
|
822
|
+
| `tools` | Extracted from the public source; dependency compatibility is still checked |
|
|
823
|
+
| `model`, `instructions`/`system`, `output` | Explicit options or supported public settings defaults |
|
|
824
|
+
| `toolChoice`, `activeTools`, `providerOptions` | Explicitly retain |
|
|
825
|
+
| `prepareStep`, `stopWhen`, `onStepFinish`, `onFinish` | Explicitly retain; run on worker with persisted steps/context |
|
|
826
|
+
| temperature, maxOutputTokens, topP/topK, presence/frequency penalties, stopSequences, seed, headers | Explicitly retain; per-run `callSettings` / per-step overrides supported |
|
|
827
|
+
| `experimental_context` | Explicitly retain lossless JSON; effective prepared context survives rollover |
|
|
828
|
+
| `experimental_telemetry` | Explicitly retain; forwarded inside model activity, not run in replay |
|
|
829
|
+
| `prepareCall`, `callOptionsSchema` | Unsupported; validate/prepare serializable input at the application boundary; native preparation can dynamically replace model/tools with non-serializable values |
|
|
830
|
+
| `maxRetries` | Defaults to 2 native provider retries; `modelRetryPolicy` separately retries DTS model activities |
|
|
831
|
+
| `abortSignal`, native `timeout` | Rejected; live signals cannot cross durable processes, and run-wide wall clocks incorrectly include approval waits and retry timers. Use reader abort, `client.terminate(instanceId, reason)`, tool `timeoutMs`, `approvalTimeoutMs` and DTS retry policies |
|
|
832
|
+
| `experimental_repairToolCall`, `experimental_download` | Rejected; no silent partial native migration |
|
|
833
|
+
|
|
834
|
+
**Default budget changes:** native SDK v6 `ToolLoopAgent` defaults to
|
|
835
|
+
`stepCountIs(20)`; this adapter defaults to **`Limits({maxSteps:100})`**. If the
|
|
836
|
+
old budget matters, explicitly retain the stop condition and/or set
|
|
837
|
+
`new Limits({maxSteps:20})`. Rollover limits bound generations, not the business
|
|
838
|
+
budget and not the growing model transcript.
|
|
839
|
+
|
|
840
|
+
```ts
|
|
841
|
+
const retained = {
|
|
842
|
+
name: "support", model, instructions, output, toolChoice,
|
|
843
|
+
activeTools, providerOptions, prepareStep, stopWhen, onStepFinish, onFinish,
|
|
844
|
+
experimental_telemetry,
|
|
845
|
+
limits: new Limits({ maxSteps: 20 }),
|
|
846
|
+
};
|
|
847
|
+
validateAgentConfig(retained);
|
|
848
|
+
const durable = attachDurability(nativeAgent, retained);
|
|
849
|
+
```
|
|
850
|
+
|
|
851
|
+
`validateAgentConfig` also catches unsupported properties introduced by JavaScript
|
|
852
|
+
or object spreads, with an actionable replacement. TypeScript's excess-property
|
|
853
|
+
checks alone do not catch every spread. Native-only callbacks are not silently
|
|
854
|
+
ignored. Do not spread a whole opaque/native settings object into an adapter and
|
|
855
|
+
assume equivalent request-time behavior.
|
|
856
|
+
|
|
857
|
+
## Register and call
|
|
858
|
+
|
|
859
|
+
`defineDurableAgent`, `new DurableAgent({ name, model, tools, output, ... })` and
|
|
860
|
+
`attachDurability(config)` share the same implementation. Call `.register` before
|
|
861
|
+
starting either an SDK TaskHubGrpcWorker or Azure-managed worker builder, then
|
|
862
|
+
`.client(dtsClient)`. `run` waits for a result; `start` returns a handle;
|
|
863
|
+
`reconnect` only addresses existing work. Calls use ordinary promises outside
|
|
864
|
+
the orchestrator.
|
|
865
|
+
|
|
866
|
+
Current native ToolLoopAgent exposes tools but keeps model/instructions private.
|
|
867
|
+
`attachDurability(nativeAgent, { name, model, system, ... })` therefore requires
|
|
868
|
+
explicit execution configuration. It does not inspect private `.settings` or
|
|
869
|
+
silently copy callbacks from private fields. Retain the full original settings and pass instructions,
|
|
870
|
+
toolChoice, activeTools, providerOptions, prepareStep, stopWhen, onStepFinish and
|
|
871
|
+
onFinish explicitly. Native loop hooks execute on the worker; persisted steps
|
|
872
|
+
keep outer stop conditions and aggregate usage correct across rollover.
|
|
873
|
+
Supported call settings are temperature, maxOutputTokens, topP, topK,
|
|
874
|
+
presencePenalty, frequencyPenalty, stopSequences, seed and headers. Zero values
|
|
875
|
+
are retained. prepareStep can override these for its step (including headers).
|
|
876
|
+
`durableGenerateText(ctx, { agent, prompt, temperature: 0, maxOutputTokens: 100 })`
|
|
877
|
+
supports call-local overrides; client/composable run options accept callSettings.
|
|
878
|
+
Native maxRetries is supported (default 2); modelRetryPolicy independently retries
|
|
879
|
+
model activities. AbortSignal and timeout are rejected on agent config: use explicit
|
|
880
|
+
reader/worker/tool cancellation instead.
|
|
881
|
+
See [operations](operations.md) for telemetry, trace propagation, exact worker
|
|
882
|
+
attempt observers, terminal failure and terminate/purge controls.
|
|
883
|
+
|
|
884
|
+
prepareStep's effective experimental_context is carried to approval predicates,
|
|
885
|
+
every tool policy, current/prior step DTOs, stopWhen, hooks and the next step,
|
|
886
|
+
including rollover. Context must be lossless JSON; class instances, functions,
|
|
887
|
+
cycles, undefined nested values and non-finite numbers fail before the model call.
|
|
888
|
+
An outer stop finalizes native text/structured output even when the SDK already
|
|
889
|
+
resolved the tools; invalid structured output still follows bounded correction.
|
|
890
|
+
|
|
891
|
+
## Tool policy and worker dependencies
|
|
892
|
+
|
|
893
|
+
Unmodified `ai.tool()` definitions run as durable worker activities. Wrap with
|
|
894
|
+
`durableTool({ inputSchema, execute, policy })` for typed
|
|
895
|
+
`DurableToolOptions<TDeps>`; `options.deps` comes from
|
|
896
|
+
`depsFactory(depsInput, activityCtx)`. Only serializable depsInput crosses DTS.
|
|
897
|
+
Construct live clients on the worker; `depsCleanup` or async/sync disposal closes
|
|
898
|
+
per-activity dependencies on success, error and timeout. Do not return a shared
|
|
899
|
+
pooled client from the factory unless its cleanup deliberately releases a lease.
|
|
900
|
+
Use `defineDurableAgent({ depsFactory, tools: bind => ({ name: bind(...) }), ... })`
|
|
901
|
+
to infer tool deps directly from the factory. Required factory input makes
|
|
902
|
+
depsInput mandatory on typed client/composable calls. Typed result.toolCalls
|
|
903
|
+
retains exact native tool names and input shapes; asTool retains child output.
|
|
904
|
+
Both attachment and settings extraction enforce the same dependency factory
|
|
905
|
+
compatibility; they cannot silently erase a source tool's dependency contract.
|
|
906
|
+
By default native strings produce text results and undefined/null produce JSON
|
|
907
|
+
null. Custom toModelOutput text/json/content/denial formats remain authoritative.
|
|
908
|
+
|
|
909
|
+
### Why is my tool `never` / incompatible?
|
|
910
|
+
|
|
911
|
+
Older diagnostics reduced a dependency mismatch to `never`. The mapped type now
|
|
912
|
+
names it `ToolRequiresDepsNotProvidedByDepsFactory<Required>` with the property
|
|
913
|
+
`tool_requires_deps_not_provided_by_depsFactory`. It means the declared tool needs
|
|
914
|
+
live dependencies absent from the inferred factory output, **not** that its Zod
|
|
915
|
+
schema failed. Fix the factory or use `tools: bind => ({...})` so both are inferred
|
|
916
|
+
together. Do not use `as any`, erase the tool set to a generic `ToolSet`, or delete
|
|
917
|
+
the dependency brand to make it compile. Source attachment/extraction and child
|
|
918
|
+
`asTool({depsInput})` enforce the same contract.
|
|
919
|
+
|
|
920
|
+
`ToolPolicy({ retryPolicy: new RetryPolicy(...), timeoutMs })` controls isolated
|
|
921
|
+
activity retries and cooperative cancellation. Unexpected infrastructure errors
|
|
922
|
+
propagate to DTS. Throw NonRetryableToolError for a model-visible business error.
|
|
923
|
+
LOCAL + ORCHESTRATOR_INLINE is pure synchronous replay code: no I/O, randomness,
|
|
924
|
+
wall clock or live dependency access. The DepsProxy throws on live access.
|
|
925
|
+
LOCAL + ACTIVITY_INLINE uses one worker attempt, never automatic retry.
|
|
926
|
+
`maxConcurrency` chunks ordered parallel tasks.
|
|
927
|
+
|
|
928
|
+
Each mutation receives
|
|
929
|
+
`sha256(instanceId + ":" + agentName + ":" + invocationId + ":" + step + ":" + toolCallId)`.
|
|
930
|
+
Owned runs use scope `root`; composable entries allocate replay-safe ctx.newGuid().
|
|
931
|
+
Global step counts do not reset at generation rollover.
|
|
932
|
+
Persist it atomically with the external side effect. Task retries, process death
|
|
933
|
+
and network ambiguity make at-least-once execution unavoidable.
|
|
934
|
+
|
|
935
|
+
## Decisions, events and upgrades
|
|
936
|
+
|
|
937
|
+
For application UI decisions, configure a shared `decisionStore` on worker and
|
|
938
|
+
client (for example `PostgresDecisionStore` from `/stores/postgres`). Retrieve
|
|
939
|
+
`handle.pendingDecision()` for **full typed input**, gate token and version/step;
|
|
940
|
+
`pendingApproval().argsPreview` remains a bounded diagnostic preview, not an
|
|
941
|
+
authoritative amount/action to approve.
|
|
942
|
+
|
|
943
|
+
```ts
|
|
944
|
+
// Inside an authenticated route, after tenant ownership and reviewer permission checks:
|
|
945
|
+
const pending = await client.reconnect(instanceId).pendingDecision();
|
|
946
|
+
if (!pending) throw new NoPendingApprovalError();
|
|
947
|
+
await client.approvePending(instanceId, {
|
|
948
|
+
approvalToken: pending.approvalToken, // required, never reconstructed from a tool ID
|
|
949
|
+
approved: true,
|
|
950
|
+
reason: "Reviewed the full request",
|
|
951
|
+
actorSubject: authenticatedSession.subject, // trusted server session, never request JSON
|
|
952
|
+
});
|
|
953
|
+
```
|
|
954
|
+
|
|
955
|
+
In a real decision POST, use the token displayed in the reviewer's submitted
|
|
956
|
+
form, **not** a freshly fetched token that could authorize a different gate.
|
|
957
|
+
The fetch above illustrates the initial authorized view. The starter POST
|
|
958
|
+
accepts the submitted token and never substitutes the current one.
|
|
959
|
+
It adds `actorSubject` from the authenticated server session; strict request
|
|
960
|
+
validation rejects browser-supplied actor fields. First-writer receipts preserve
|
|
961
|
+
the original actor through double-clicks and interrupted-delivery recovery.
|
|
962
|
+
The field is optional for legacy/CLI callers, not a substitute for authorization.
|
|
963
|
+
Tenant scoping does not by itself grant per-subject resource privacy.
|
|
964
|
+
|
|
965
|
+
| UI event | Behavior |
|
|
966
|
+
|---|---|
|
|
967
|
+
| Refresh while parked | Fetch authoritative full pending input + token; no model/tool re-execution from refresh |
|
|
968
|
+
| Double-click / network retry | Atomic first decision wins; `DecisionAlreadyRecordedError` includes the original receipt |
|
|
969
|
+
| Stale tab after upgrade | `ApprovalGateChangedError` (409 in starter); refresh and review the new input/token |
|
|
970
|
+
| Gate already resolved/timed out | `NoPendingApprovalError`; refresh completion/status, do not auto-authorize a later gate |
|
|
971
|
+
| Process crash after record, before event send | Repeat the same POST/token; recover delivery of the **original** decision |
|
|
972
|
+
|
|
973
|
+
The receipt/event send is at least once, not a transaction spanning Postgres and
|
|
974
|
+
DTS. An application outbox job is needed for unattended delivery recovery. Tokens
|
|
975
|
+
bind events to gates; the scheduler validates the gate when consuming them.
|
|
976
|
+
A concurrent gate change after the route's status read may make an event stale;
|
|
977
|
+
that event cannot authorize the replacement gate. It is not a synchronous
|
|
978
|
+
compare-and-swap of scheduler state. Add server-session auth, tenant ownership,
|
|
979
|
+
reviewer permission, CSRF and audit controls; tokens are not credentials.
|
|
980
|
+
`InMemoryDecisionStore` is for a shared-process harness only.
|
|
981
|
+
|
|
982
|
+
Native needsApproval can be a boolean or async predicate. Predicates execute on
|
|
983
|
+
the worker with native pre-assistant-turn messages and record their decision.
|
|
984
|
+
Execute-less tools become deferred calls. Authenticate/authorize decisions in
|
|
985
|
+
your HTTP/application boundary; DTS events themselves are not human identity.
|
|
986
|
+
`waitForApprovalOrCompletion` returns either PendingApproval or a final result.
|
|
987
|
+
`approve` and `approveToolCall` are **deprecated** legacy APIs: their optional
|
|
988
|
+
token/no-receipt behavior is retained only for compatibility. Use token-required
|
|
989
|
+
`approvePending` for application decision routes. Deferred integrations use
|
|
990
|
+
`resolveDeferredCall(id, result, { approvalToken })` / `resolveDeferredTool(...)`.
|
|
991
|
+
UI decisions must supply the published token:
|
|
992
|
+
it binds version, generation, step and invocation as well as call ID. Raw
|
|
993
|
+
overrideArgs are parsed once; SDK-transformed inputs are never parsed again.
|
|
994
|
+
Timeouts return an error tool result without
|
|
995
|
+
executing the protected operation.
|
|
996
|
+
|
|
997
|
+
`previousVersions` maps labels to complete historical worker configurations.
|
|
998
|
+
Old limits, concurrency, approval/model retry policy, MCP and stores remain
|
|
999
|
+
version-selected. Registration retains the union of activity/child names, even
|
|
1000
|
+
when the newest definition is deferred. `migrations["v1->v2"]`
|
|
1001
|
+
receives serializable state plus an upgrade payload at a parked gate. Change
|
|
1002
|
+
`state.pendingTurn` if the pending tool's arguments must evolve. `upgrade("v2")`
|
|
1003
|
+
rolls into a new generation; the migrated effect requires **fresh approval**.
|
|
1004
|
+
Upgrade is not automatic authorization of a different amount or action.
|
|
1005
|
+
Distinct same-name child agents with different version labels coalesce behind
|
|
1006
|
+
one stable worker dispatcher. A different contract under the same name+version
|
|
1007
|
+
fails before registration touches the worker; reusing that worker after a
|
|
1008
|
+
preflight failure does not silently return a partially registered parent.
|
|
1009
|
+
Register compatible old/latest agents before starting the worker in either
|
|
1010
|
+
order. Their migration declarations are merged per worker, so a retained v1
|
|
1011
|
+
engine can discover a transition declared by the latest registration while
|
|
1012
|
+
still using v1's exact tools, model, limits and store. The new generation then
|
|
1013
|
+
dispatches by its recorded v2 version. Reuse the same migration function object
|
|
1014
|
+
for duplicate transition declarations; different functions under the same
|
|
1015
|
+
`from->to` key throw PolicyConflictError before worker mutation. Migration
|
|
1016
|
+
capabilities registered on one worker do not affect another worker.
|
|
1017
|
+
|
|
1018
|
+
## History, threads and sessions
|
|
1019
|
+
|
|
1020
|
+
Default history is inline. Separate calls explicitly pass previous
|
|
1021
|
+
`result.messages`; no hidden process-only conversation cache exists. A
|
|
1022
|
+
HistoryStore enables persistent `threadId` heads and reference-only orchestration
|
|
1023
|
+
payloads. The client hydrates `result.messages`; worker activities alone hydrate
|
|
1024
|
+
model inputs. Missing data and conflicting immutable writes fail explicitly.
|
|
1025
|
+
Serialize turns for a thread: compare-and-swap detects concurrent head writes
|
|
1026
|
+
but does not undo effects that already occurred in a losing run.
|
|
1027
|
+
|
|
1028
|
+
`runSession(firstPrompt)` creates a long-lived workflow; handle `send(prompt)`
|
|
1029
|
+
queues durable turns and `finish()` closes the session. Limits bound steps per
|
|
1030
|
+
turn, steps per generation and turns per generation. Continue-as-new retains
|
|
1031
|
+
unread events and global step/cursor counters, counting terminal model steps too.
|
|
1032
|
+
Calling runSession again for the same session always enqueues a unique turnId,
|
|
1033
|
+
even while busy. Optional caller turnId supports bounded duplicate suppression.
|
|
1034
|
+
Each returned handle carries its ID and waitForTurn observes completion; only
|
|
1035
|
+
the latest 32 completed IDs remain in status. Use a separate application archive
|
|
1036
|
+
for older per-turn results. Session dependency input is fixed at creation.
|
|
1037
|
+
|
|
1038
|
+
HistoryStore snapshots contain both messages and native encoded step DTOs:
|
|
1039
|
+
implement `put(key, messages, steps)` and `getSteps(key)` for custom stores.
|
|
1040
|
+
File snapshots/head changes publish atomically. Native provider signatures,
|
|
1041
|
+
custom tool toModelOutput and multimodal content survive round trips.
|
|
1042
|
+
|
|
1043
|
+
Production cross-host state uses `PostgresHistoryStore` with explicit namespace
|
|
1044
|
+
and tenant ID. It implements immutable snapshots, CAS heads and
|
|
1045
|
+
`trim({before,protectedKeys})`; inventory/pin every live run reference before
|
|
1046
|
+
trimming. Memory/file/SQLite are still local fixtures. SQLite loads only when
|
|
1047
|
+
constructed, not when root/client modules are imported. See the
|
|
1048
|
+
[operations retention runbook](operations.md) and shared contract tests.
|
|
1049
|
+
|
|
1050
|
+
## Composition and multi-agent workflows
|
|
1051
|
+
|
|
1052
|
+
Inside `async function*`, use `yield* agent.runInOrchestration(ctx, prompt)` or
|
|
1053
|
+
`yield* durableGenerateText(ctx, { agent, prompt })` with registered agents.
|
|
1054
|
+
The optional durableGenerateText historyStore must be the registered agent's
|
|
1055
|
+
version-selected worker store; conflicting stores/models fail explicitly.
|
|
1056
|
+
The orchestration result retains `history` as an inline array or reference;
|
|
1057
|
+
it deliberately does not hydrate external storage inside replay.
|
|
1058
|
+
Use `.asTool({ description, toModelOutput })` for a real child orchestration.
|
|
1059
|
+
If a child factory requires DI, bind it with
|
|
1060
|
+
`child.asTool({ depsInput: { tenantId: "tenant" } })` or
|
|
1061
|
+
`child.asTool({ depsInput: (args, parent) => ({ tenantId: args.prompt }) })`.
|
|
1062
|
+
Options are then required at compile time. Mappers run during replay and must
|
|
1063
|
+
be synchronous/pure; parent has deterministic durable metadata, effective
|
|
1064
|
+
experimental_context and serializable depsInput (not live deps). The resolved
|
|
1065
|
+
child input is persisted in its own state and survives worker replacement.
|
|
1066
|
+
`asTool({ version: "v1", ... })` can select a retained child contract explicitly.
|
|
1067
|
+
Ordinary `ctx.callActivity` nodes compose into graph-like workflows (example 04).
|
|
1068
|
+
Whole-owner rollover is not transparent to a custom graph: a composable agent
|
|
1069
|
+
fails explicitly at stepsPerGeneration; its owner must design that boundary.
|
|
1070
|
+
|
|
1071
|
+
## Streaming and MCP
|
|
1072
|
+
|
|
1073
|
+
`streamPublisher` switches the worker model activity to streamText. Provide a
|
|
1074
|
+
matching `streamSubscriber` for handle.toUIMessageStreamResponse; without one,
|
|
1075
|
+
the response adapts the final text. InMemoryStreamBroker is a development-only
|
|
1076
|
+
transport, kept alive after completion until explicitly cleared. Live cursor and
|
|
1077
|
+
checkpoint cursor are independent. `handle.stream({ cursor })` yields bounded
|
|
1078
|
+
committed checkpoints and explicit gap events, never a full token archive.
|
|
1079
|
+
|
|
1080
|
+
`RedisStreamBroker` from `/streaming/redis` supplies a cross-process ordered log
|
|
1081
|
+
with deduplication, trim and explicit retention gaps. One stable assistant
|
|
1082
|
+
`start`/`finish` spans model steps; **no finish is published while approval is
|
|
1083
|
+
parked**. Worker tool outcomes emit native `tool-output-available` /
|
|
1084
|
+
`tool-output-error`; gate updates emit `data-durable-approval-pending` and
|
|
1085
|
+
`data-durable-approval-resolved`. Model chunks are saved with the encoded step,
|
|
1086
|
+
then published by a separate `__project_model` activity **after** DTS commits
|
|
1087
|
+
the model result. Its content-addressed projection ID scopes redelivery. A
|
|
1088
|
+
publisher failure retries the same immutable projection, never regenerates a
|
|
1089
|
+
different model answer. Failed, uncommitted model attempts publish nothing.
|
|
1090
|
+
`data-durable-model-committed` identifies the projection and step. This is per-step
|
|
1091
|
+
UI buffering, **not per-token latency** during an active model call.
|
|
1092
|
+
|
|
1093
|
+
`await handle.toUIMessageStreamResponse({cursor,signal,pollIntervalMs,readerTimeoutSeconds})`
|
|
1094
|
+
defaults to 250 ms polling and a 60-second reader budget (configurable also in
|
|
1095
|
+
`streamOptions`). A timeout or abort does not cancel the orchestration.
|
|
1096
|
+
`x-durable-instance-id` identifies the run. The generic helper and starter route
|
|
1097
|
+
preflight the broker asynchronously and report its actual high-water snapshot
|
|
1098
|
+
as `x-durable-cursor`, with a separate `x-durable-replay-cursor` requested origin.
|
|
1099
|
+
Custom subscribers must implement `readPage` for this response helper; missing
|
|
1100
|
+
metadata fails explicitly rather than advertising a fabricated cursor.
|
|
1101
|
+
Transient `data-durable-cursor` chunks
|
|
1102
|
+
expose later high-water marks after headers are sent. Pass `?cursor=` through the
|
|
1103
|
+
route on refresh.
|
|
1104
|
+
|
|
1105
|
+
Reconnection reads from the **last consumed cursor**, without replaying prior
|
|
1106
|
+
parts. Native `useChat` keeps the current assistant; direct `readUIMessageStream`
|
|
1107
|
+
callers must pass that assistant as `message` when resuming. A fresh browser with
|
|
1108
|
+
no cached message must rebuild from cursor zero. An HTTP 410 /
|
|
1109
|
+
`StreamRetentionGapError` means retained
|
|
1110
|
+
chunks cannot reconstruct the message; fetch authoritative status/completion.
|
|
1111
|
+
See the [useChat integration guide](#reliable-streaming-and-nextjs-usechat).
|
|
1112
|
+
|
|
1113
|
+
`mcp: { serverName: new MCPClientPool(clientFactory) }` records list_tools
|
|
1114
|
+
schemas before model calls and schedules namespaced serverName__tool calls as
|
|
1115
|
+
activities. Pools retain worker connections, cache tools, idle-disconnect and
|
|
1116
|
+
must be closed explicitly after worker stop. Initial discovery is single-flight;
|
|
1117
|
+
failed discovery can retry. Exact tool routing rejects duplicate/colliding names
|
|
1118
|
+
instead of using prefix matching. `mcpToolPolicies["serverName__tool"]` controls
|
|
1119
|
+
retry and timeout/AbortSignal; MCP native toModelOutput preserves image/content
|
|
1120
|
+
blocks. LOCAL policies cannot request durable retries/timeouts.
|