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.
Files changed (98) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/CONTRIBUTING.md +69 -0
  3. package/LICENSE +22 -0
  4. package/README.md +324 -2
  5. package/dist/src/agent.d.ts +110 -0
  6. package/dist/src/agent.js +1336 -0
  7. package/dist/src/agent.js.map +1 -0
  8. package/dist/src/approvals.d.ts +20 -0
  9. package/dist/src/approvals.js +100 -0
  10. package/dist/src/approvals.js.map +1 -0
  11. package/dist/src/client-entry.d.ts +12 -0
  12. package/dist/src/client-entry.js +7 -0
  13. package/dist/src/client-entry.js.map +1 -0
  14. package/dist/src/client.d.ts +109 -0
  15. package/dist/src/client.js +498 -0
  16. package/dist/src/client.js.map +1 -0
  17. package/dist/src/decisions.d.ts +54 -0
  18. package/dist/src/decisions.js +44 -0
  19. package/dist/src/decisions.js.map +1 -0
  20. package/dist/src/durable-chat-transport.d.ts +48 -0
  21. package/dist/src/durable-chat-transport.js +173 -0
  22. package/dist/src/durable-chat-transport.js.map +1 -0
  23. package/dist/src/history-types.d.ts +21 -0
  24. package/dist/src/history-types.js +6 -0
  25. package/dist/src/history-types.js.map +1 -0
  26. package/dist/src/history.d.ts +35 -0
  27. package/dist/src/history.js +163 -0
  28. package/dist/src/history.js.map +1 -0
  29. package/dist/src/http.d.ts +9 -0
  30. package/dist/src/http.js +67 -0
  31. package/dist/src/http.js.map +1 -0
  32. package/dist/src/index.d.ts +25 -0
  33. package/dist/src/index.js +14 -0
  34. package/dist/src/index.js.map +1 -0
  35. package/dist/src/logging.d.ts +4 -0
  36. package/dist/src/logging.js +8 -0
  37. package/dist/src/logging.js.map +1 -0
  38. package/dist/src/mcp.d.ts +41 -0
  39. package/dist/src/mcp.js +112 -0
  40. package/dist/src/mcp.js.map +1 -0
  41. package/dist/src/status.d.ts +29 -0
  42. package/dist/src/status.js +50 -0
  43. package/dist/src/status.js.map +1 -0
  44. package/dist/src/steps.d.ts +41 -0
  45. package/dist/src/steps.js +125 -0
  46. package/dist/src/steps.js.map +1 -0
  47. package/dist/src/stores/postgres.d.ts +53 -0
  48. package/dist/src/stores/postgres.js +140 -0
  49. package/dist/src/stores/postgres.js.map +1 -0
  50. package/dist/src/stores/sqlite.d.ts +1 -0
  51. package/dist/src/stores/sqlite.js +2 -0
  52. package/dist/src/stores/sqlite.js.map +1 -0
  53. package/dist/src/streaming/redis.d.ts +33 -0
  54. package/dist/src/streaming/redis.js +55 -0
  55. package/dist/src/streaming/redis.js.map +1 -0
  56. package/dist/src/streaming.d.ts +29 -0
  57. package/dist/src/streaming.js +64 -0
  58. package/dist/src/streaming.js.map +1 -0
  59. package/dist/src/telemetry.d.ts +10 -0
  60. package/dist/src/telemetry.js +49 -0
  61. package/dist/src/telemetry.js.map +1 -0
  62. package/dist/src/testing/index.d.ts +70 -0
  63. package/dist/src/testing/index.js +165 -0
  64. package/dist/src/testing/index.js.map +1 -0
  65. package/dist/src/tools.d.ts +96 -0
  66. package/dist/src/tools.js +69 -0
  67. package/dist/src/tools.js.map +1 -0
  68. package/dist/src/types.d.ts +321 -0
  69. package/dist/src/types.js +19 -0
  70. package/dist/src/types.js.map +1 -0
  71. package/dist/src/validation.d.ts +1 -0
  72. package/dist/src/validation.js +19 -0
  73. package/dist/src/validation.js.map +1 -0
  74. package/dist/src/worker-entry.d.ts +7 -0
  75. package/dist/src/worker-entry.js +6 -0
  76. package/dist/src/worker-entry.js.map +1 -0
  77. package/dist/src/worker.d.ts +24 -0
  78. package/dist/src/worker.js +107 -0
  79. package/dist/src/worker.js.map +1 -0
  80. package/docs/Hosted-DTS.md +115 -0
  81. package/docs/architecture.md +76 -0
  82. package/docs/decisions/0001-dual-surface-authoring.md +14 -0
  83. package/docs/decisions/0002-generator-turn-stepper.md +8 -0
  84. package/docs/decisions/0003-tools-deps-and-mcp.md +19 -0
  85. package/docs/decisions/0004-approvals-and-status.md +18 -0
  86. package/docs/decisions/0005-state-streaming-subagents-versioning.md +19 -0
  87. package/docs/decisions/0006-maf-entity-session-comparison-and-hybrid-model.md +360 -0
  88. package/docs/decisions/0007-workflow-world-dts-and-durable-functions-sketch.md +191 -0
  89. package/docs/decisions/README.md +17 -0
  90. package/docs/development.md +139 -0
  91. package/docs/getting-started.md +325 -0
  92. package/docs/limitations.md +130 -0
  93. package/docs/operations.md +178 -0
  94. package/docs/security-and-tenancy.md +41 -0
  95. package/docs/support-matrix.md +26 -0
  96. package/docs/user-guide.md +1120 -0
  97. package/package.json +121 -12
  98. package/index.js +0 -1
@@ -0,0 +1,325 @@
1
+ # Getting started with durable Vercel AI agents
2
+
3
+ This tutorial creates a durable support agent, runs it on the local Azure Durable
4
+ Task Scheduler Emulator, adds a tool approval, and carries conversation history
5
+ across turns. Model steps and tool activities are checkpointed by Durable Task.
6
+
7
+ > [!NOTE]
8
+ > **Public Preview:** `ai-sdk-azure-durable-task` `0.1.0` is pre-1.0
9
+ > Preview software for evaluation and feedback. APIs, behaviors, packaging,
10
+ > and support may change or be retired before General Availability.
11
+
12
+ ## Prerequisites
13
+
14
+ - Node.js **22.15 or later** and npm.
15
+ - Docker with a running container engine for the DTS Emulator.
16
+ - A terminal and a TypeScript editor.
17
+ - A built source checkout or access to a package registry containing a release.
18
+
19
+ The examples use a scripted AI model so you can learn the execution model without
20
+ provider credentials. Later, replace it with your chosen AI SDK provider model.
21
+ The in-memory harness in the [README quickstart](../README.md#getting-started)
22
+ is an alternative when Docker is unavailable; it does not persist after exit.
23
+
24
+ ## Step 1: Install packages
25
+
26
+ Create an empty project directory and run:
27
+
28
+ ```powershell
29
+ npm init -y
30
+ npm pkg set type=module
31
+ npm install ai-sdk-azure-durable-task ai zod @microsoft/durabletask-js @microsoft/durabletask-js-azuremanaged
32
+ npm install --save-dev typescript tsx @types/node
33
+ ```
34
+
35
+ For source-checkout development, use `npm ci` and `npm run build` instead.
36
+ Until a registry release is available, run the tutorial files from that built
37
+ checkout or install its locally packed tarball. No package publication is implied
38
+ by these commands.
39
+ See [local package installation](development.md#local-package-installation)
40
+ for building and installing the tarball before a registry release.
41
+
42
+ ## Step 2: Start the Azure Durable Task Scheduler Emulator
43
+
44
+ ```powershell
45
+ docker run --name dts-vercel-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
46
+ ```
47
+
48
+ The scheduler gRPC endpoint is `http://localhost:8080`; the DTS Dashboard is
49
+ **http://localhost:8082**. Dynamic task hubs allow this tutorial to use the hub
50
+ `vercel-ai` without provisioning it separately. If these ports are occupied,
51
+ change the host-side mappings and the client/worker endpoint together.
52
+
53
+ Wait for startup and inspect errors with:
54
+
55
+ ```powershell
56
+ docker logs dts-vercel-ai
57
+ ```
58
+
59
+ The emulator runs locally without Azure credentials. Do not expose its ports to
60
+ an untrusted network. The container keeps state while it exists; this command
61
+ does not configure persistence after container deletion.
62
+
63
+ ## Step 3: Create your first durable agent
64
+
65
+ Save the following complete program as **`hello.ts`**. It registers the agent
66
+ before starting the worker, schedules one run, and shuts down the connections
67
+ after completion.
68
+
69
+ ```ts
70
+ import {
71
+ DurableTaskAzureManagedClientBuilder,
72
+ DurableTaskAzureManagedWorkerBuilder,
73
+ } from "@microsoft/durabletask-js-azuremanaged";
74
+ import { DurableTaskAgent } from "ai-sdk-azure-durable-task";
75
+ import { scriptedModel, text } from "ai-sdk-azure-durable-task/testing";
76
+
77
+ const agent = new DurableTaskAgent({
78
+ name: "hello",
79
+ instructions: "Respond with a short greeting.",
80
+ model: scriptedModel(() => text("Hello from Durable Task!")),
81
+ });
82
+ const endpoint = "http://localhost:8080";
83
+ const taskhub = "vercel-ai";
84
+ const builder = new DurableTaskAzureManagedWorkerBuilder()
85
+ .endpoint(endpoint, taskhub, null);
86
+ agent.register(builder);
87
+ const worker = builder.useWorkItemFilters().build();
88
+ const sdk = new DurableTaskAzureManagedClientBuilder()
89
+ .endpoint(endpoint, taskhub, null).build();
90
+
91
+ try {
92
+ await worker.start();
93
+ const handle = await agent.client(sdk).start("Hello");
94
+ console.log("Instance:", handle.instanceId);
95
+ const result = await handle.waitForResult();
96
+ console.log(result.text);
97
+ console.log("Tokens:", result.totalUsage.totalTokens);
98
+ } finally {
99
+ await worker.stop();
100
+ await sdk.stop();
101
+ }
102
+ ```
103
+
104
+ Run it:
105
+
106
+ ```powershell
107
+ npx tsx hello.ts
108
+ ```
109
+
110
+ Expected text: `Hello from Durable Task!`. The scripted model reports synthetic
111
+ usage for demonstration; it is not provider billing data.
112
+
113
+ ### Attach durability to an existing ToolLoopAgent
114
+
115
+ Instead of constructing the agent above, retain the original settings and create
116
+ a durable wrapper. This complete alternative runs without Docker:
117
+
118
+ ```ts
119
+ import { ToolLoopAgent } from "ai";
120
+ import { attachDurability } from "ai-sdk-azure-durable-task";
121
+ import {
122
+ createInMemoryHarness, scriptedModel, text,
123
+ } from "ai-sdk-azure-durable-task/testing";
124
+
125
+ const settings = {
126
+ model: scriptedModel(() => text("Hello from the wrapped agent!")),
127
+ instructions: "Respond with a short greeting.",
128
+ };
129
+ const nativeAgent = new ToolLoopAgent(settings);
130
+ const agent = attachDurability(nativeAgent, { name: "wrapped", ...settings });
131
+ const harness = createInMemoryHarness();
132
+ agent.register(harness.worker);
133
+ await harness.worker.start();
134
+ try {
135
+ console.log((await agent.client(harness.client).run("Hello")).text);
136
+ } finally {
137
+ await harness.close();
138
+ }
139
+ ```
140
+
141
+ The wrapper copies the public tools, not hidden model/instruction settings.
142
+ Explicitly retain `prepareStep`, `stopWhen`, outputs, and hooks when present.
143
+ Native `generate()`/`stream()` calls on the original instance stay native.
144
+ See [authoring and migration](user-guide.md#authoring-durable-agents).
145
+
146
+ ## Step 4: Add durable tools and a human-in-the-loop approval gate
147
+
148
+ Save as **`approval.ts`** and run `npx tsx approval.ts`. This complete emulator
149
+ example requests a credit, exposes the full pending decision, and approves the
150
+ demonstration operation. No money moves: the tool returns a local demo receipt.
151
+
152
+ ```ts
153
+ import { z } from "zod";
154
+ import {
155
+ DurableTaskAzureManagedClientBuilder,
156
+ DurableTaskAzureManagedWorkerBuilder,
157
+ } from "@microsoft/durabletask-js-azuremanaged";
158
+ import {
159
+ DurableTaskAgent, durableTool, InMemoryDecisionStore,
160
+ } from "ai-sdk-azure-durable-task";
161
+ import {
162
+ scriptedModel, calls, text,
163
+ } from "ai-sdk-azure-durable-task/testing";
164
+
165
+ const decisionStore = new InMemoryDecisionStore();
166
+ const agent = new DurableTaskAgent({
167
+ name: "support",
168
+ decisionStore,
169
+ approvalTimeoutMs: 300_000,
170
+ model: scriptedModel(prompt =>
171
+ prompt.some(message => message.role === "tool")
172
+ ? text("Credit request processed.")
173
+ : calls({ name: "credit", id: "credit-1", input: { amount: 350 } })),
174
+ tools: {
175
+ credit: durableTool({
176
+ inputSchema: z.object({ amount: z.number().positive() }),
177
+ needsApproval: ({ amount }) => amount > 100,
178
+ execute: ({ amount }, options) => ({
179
+ amount, receiptId: `demo-${options.durable.idempotencyKey}`,
180
+ }),
181
+ }),
182
+ },
183
+ });
184
+ const builder = new DurableTaskAzureManagedWorkerBuilder()
185
+ .endpoint("http://localhost:8080", "vercel-ai", null);
186
+ agent.register(builder);
187
+ const worker = builder.useWorkItemFilters().build();
188
+ const sdk = new DurableTaskAzureManagedClientBuilder()
189
+ .endpoint("http://localhost:8080", "vercel-ai", null).build();
190
+
191
+ try {
192
+ await worker.start();
193
+ const api = agent.client(sdk);
194
+ const handle = await api.start("Credit 350");
195
+ console.log("Instance:", handle.instanceId);
196
+ const boundary = await handle.waitForApprovalOrCompletion();
197
+ if ("toolCallId" in boundary) {
198
+ const pending = await handle.pendingDecision();
199
+ if (!pending) throw new Error("Expected a pending decision");
200
+ console.log("Review:", pending.input);
201
+ await handle.approvePending({
202
+ approvalToken: pending.approvalToken,
203
+ approved: true,
204
+ reason: "Approved the tutorial's demo operation",
205
+ });
206
+ }
207
+ console.log((await handle.waitForResult()).text);
208
+ } finally {
209
+ await worker.stop();
210
+ await sdk.stop();
211
+ }
212
+ ```
213
+
214
+ For a real human review, send the **displayed** `approvalToken` back from the
215
+ reviewer's form after authentication, tenant ownership, and reviewer permission
216
+ checks. Never replace a stale submitted token with a newly fetched one.
217
+ `InMemoryDecisionStore` works here because client and worker share a process;
218
+ use `PostgresDecisionStore` or an application-provided persistent decision store for
219
+ restart recovery. Tokens identify gates; they are not authorization credentials.
220
+
221
+ Alternatively, set agent-level `toolApproval: { credit: "user-approval" }` to
222
+ require approval for every credit call. An undefined agent-level rule falls back
223
+ to the tool's `needsApproval`. Durable waits release the orchestration work item;
224
+ they do not require a request to remain open.
225
+
226
+ Forward `options.durable.idempotencyKey` to real mutation APIs. Checkpointing does
227
+ not prevent a side effect from repeating if a worker dies before its result commits.
228
+
229
+ ## Step 5: Run a multi-turn conversational session
230
+
231
+ Save as **`session.ts`** and run `npx tsx session.ts`. This complete example uses
232
+ the same emulator with a persistent local `FileHistoryStore` in `./chat-history`.
233
+ Each returned handle carries the turn ID that `waitForTurn()` observes.
234
+
235
+ ```ts
236
+ import {
237
+ DurableTaskAzureManagedClientBuilder,
238
+ DurableTaskAzureManagedWorkerBuilder,
239
+ } from "@microsoft/durabletask-js-azuremanaged";
240
+ import {
241
+ DurableTaskAgent, FileHistoryStore, Limits,
242
+ } from "ai-sdk-azure-durable-task";
243
+ import { scriptedModel, text } from "ai-sdk-azure-durable-task/testing";
244
+
245
+ const historyStore = new FileHistoryStore("./chat-history");
246
+ const agent = new DurableTaskAgent({
247
+ name: "conversation", historyStore,
248
+ limits: new Limits({ maxTurnsPerGeneration: 4 }),
249
+ model: scriptedModel(prompt =>
250
+ text(`I have received ${prompt.filter(m => m.role === "user").length} user turns.`)),
251
+ });
252
+ const builder = new DurableTaskAzureManagedWorkerBuilder()
253
+ .endpoint("http://localhost:8080", "vercel-ai", null);
254
+ agent.register(builder);
255
+ const worker = builder.useWorkItemFilters().build();
256
+ const sdk = new DurableTaskAzureManagedClientBuilder()
257
+ .endpoint("http://localhost:8080", "vercel-ai", null).build();
258
+
259
+ try {
260
+ await worker.start();
261
+ const api = agent.client(sdk);
262
+ const threadId = `tutorial-${crypto.randomUUID()}`;
263
+ const first = await api.runSession("My name is Alex.", { threadId });
264
+ console.log("Session:", first.instanceId);
265
+ await first.waitForTurn();
266
+ const second = await api.runSession("What did I just tell you?", { threadId });
267
+ await second.waitForTurn();
268
+ await second.finish();
269
+ const result = await second.waitForResult();
270
+ console.log(result.text); // I have received 2 user turns.
271
+ console.log("Messages:", result.messages.length); // 4
272
+ } finally {
273
+ await worker.stop();
274
+ await sdk.stop();
275
+ historyStore.close();
276
+ }
277
+ ```
278
+
279
+ The scripted model counts turns rather than reasoning about your name. A real
280
+ provider receives the accumulated history. `runSession` reuses the thread's
281
+ session and enqueues each new prompt; `handle.send()` is another way to enqueue.
282
+ Call `finish()` when done, then `waitForResult()` for session completion.
283
+
284
+ A `HistoryStore` persists messages and step metadata and enables automatic
285
+ claim-check offloading for large tool outputs. File and SQLite stores are local;
286
+ use PostgreSQL across separate web/worker hosts. Serialize work on a thread:
287
+ conflict detection is not compensation for already-executed external effects.
288
+ See [sessions and scaling](user-guide.md#conversation-state-sessions-and-scaling-limits).
289
+
290
+ ## Step 6: Inspect execution and token usage in the DTS Dashboard
291
+
292
+ Open **http://localhost:8082**, select the `vercel-ai` task hub, and locate the
293
+ instance ID printed by the program.
294
+
295
+ 1. Inspect orchestration status and execution history.
296
+ 2. Find model-step activities (names ending in `__model_step`) and tool activities.
297
+ Their completed results are the checkpoints used during replay.
298
+ 3. For the support agent, inspect approval status and the external decision event.
299
+ Pause before approving, or use a separate reviewer client, to observe a live gate.
300
+ 4. Inspect persisted activity/result payloads and custom status for step counts
301
+ and token totals. `result.totalUsage.totalTokens` is also printed by `hello.ts`.
302
+ When results are stored by reference, hydrate them with the client API.
303
+
304
+ The dashboard is the scheduler's execution viewer, not a model billing portal.
305
+ Scripted usage is synthetic. In production, enable model telemetry and use
306
+ provider usage records alongside the scheduler history.
307
+
308
+ ## Clean up and next steps
309
+
310
+ Stop only the tutorial container when finished:
311
+
312
+ ```powershell
313
+ docker stop dts-vercel-ai
314
+ docker rm dts-vercel-ai
315
+ ```
316
+
317
+ Deleting the container removes its unmounted local scheduler state. Retain
318
+ `chat-history` if you want to inspect snapshots; delete it only after the tutorial
319
+ runs no longer reference it.
320
+
321
+ - Continue with the [Developer Guide](user-guide.md).
322
+ - Run the [console examples](../examples/README.md).
323
+ - Build a [Next.js client and separate worker](user-guide.md#reliable-streaming-and-nextjs-usechat).
324
+ - Configure [hosted DTS](Hosted-DTS.md), [security and tenancy](security-and-tenancy.md),
325
+ and [operations](operations.md) before deployment.
@@ -0,0 +1,130 @@
1
+ # Limitations and guarantees
2
+
3
+ **Experimental, not production certification.** Current verification uses a
4
+ scripted AI SDK provider with the real local DTS emulator and real SDK executors.
5
+ Hosted Azure acceptance remains **unexecuted**: gated tests skip without the
6
+ endpoint and identity configuration. Actual commercial LLM providers and external
7
+ MCP servers also require separate checks. Bundled Postgres/Redis adapters have local live
8
+ contract/HTTP tests, not production-scale/HA certification.
9
+
10
+ **At-least-once activities.** Recorded completions replay without rerunning.
11
+ A crash after a side effect but before its completion commits may repeat it.
12
+ Idempotency keys help only when downstream systems enforce them atomically.
13
+ Timeout abort signals are cooperative; a timed-out mutation may still finish
14
+ if the downstream client ignores cancellation. Retry can overlap that old work.
15
+
16
+ **Pure replay code only.** Orchestrator-inline tools must be synchronous and
17
+ deterministic. Dependency guards do not sandbox fetch, Date.now or random calls.
18
+ With pointer history they cannot hydrate `options.messages`: use activity-inline
19
+ or durable tools when full pre-turn context is required. Async approval predicates,
20
+ prepareStep, step/final hooks and stop conditions run on workers against persisted
21
+ step DTOs, never in replay; their side effects are at least once. ToolLoopAgent's
22
+ private settings and prepareCall are not intercepted: retain and pass supported
23
+ configuration explicitly rather than assuming whole-agent monkey-patching.
24
+ Supported defaults can also come from an application-owned public settings
25
+ wrapper or a public getter. Current native SDK private fields remain ignored;
26
+ a future visibility-only change needs a compatibility update, since JavaScript
27
+ cannot distinguish TypeScript public/private fields.
28
+ Durable-safe native call settings are forwarded, including prepared step
29
+ overrides. Native maxRetries defaults to two provider retries; modelRetryPolicy
30
+ controls separate activity retries. Retained abortSignal and timeout are rejected.
31
+ Headers must not contain committed credentials; trace headers are opt-in.
32
+ Prepared context is lossless JSON, not a channel for live dependencies. Native
33
+ nullish prepared context follows the installed SDK's fallback behavior.
34
+
35
+ **JSON wire boundary.** Inputs, outputs, tool arguments, messages and provider
36
+ metadata must survive JSON serialization. Use text/base64/URL strings for media,
37
+ not live streams, class instances or raw Uint8Array message content. Client-side
38
+ native output parsing re-applies schema transforms; composable orchestration
39
+ results must remain serializable DTOs. Tool call IDs must fit 128 UTF-8 bytes.
40
+
41
+ **State lifecycle.** Memory is not cross-process storage. SQLite/file need a
42
+ shared durable filesystem for multiple processes on one host; use the bundled
43
+ Postgres adapter across hosts. Snapshots are immutable. Postgres exposes explicit
44
+ pinned retention/trim, not automatic reachability GC or encryption policies. A file head
45
+ lock left by process death fails closed and requires operator recovery. CAS
46
+ detects concurrent thread commits, not concurrent external effects. No hidden
47
+ thread history survives in a client's process-only cache.
48
+ HistoryStore implementations must retain both messages and encoded steps
49
+ (`put(key, messages, steps)` / `getSteps(key)`). Immutable snapshots and native
50
+ step retention still grow external storage; rollover bounds DTS history, not
51
+ database size. Legacy raw-array snapshots have empty step history.
52
+ `Limits.maxGenerationBytes` defaults to 512,000 bytes and automatically rolls
53
+ owned runs over at committed step boundaries (also honoring `stepsPerGeneration`).
54
+ It accounts for serialized activity results and the current inline state; it is
55
+ not a hard per-RPC size limit. Use a shared `HistoryStore` for large histories:
56
+ rollover alone cannot shrink inline state. With a store configured, tool
57
+ activities claim-check outputs larger than
58
+ `AgentConfig.toolOutputOffloadThresholdBytes` (default 32,768 serialized UTF-8
59
+ bytes). Only a small reference crosses the scheduler; the history-append activity
60
+ hydrates the full outcome for model messages, hooks and UI output. Tool-output
61
+ snapshots share the history store's retention policy. Large model outputs, tool
62
+ inputs, deferred results and inline/subagent outputs are not covered by
63
+ tool-activity claim checks.
64
+
65
+ **Streaming is two channels, not one archive.** Checkpoint status is capped at
66
+ 7,500 bytes and may drop old details. Gap events require refresh. Live chunks
67
+ are now projected only **after** DTS records the canonical model activity result.
68
+ The immutable encoded step holds its UI projection; a separate activity publishes
69
+ that exact projection under a content-addressed identity. Publication failure
70
+ retries publication, not the model, so partial speculative answers cannot mask a
71
+ different committed answer. A failed model attempt publishes no chunks.
72
+ Bundled brokers deduplicate redelivery of that committed projection, but do not
73
+ transactionally commit the snapshot, UI log and scheduler completion together.
74
+ Configure a model retry policy for projection retries too; exhausted publication
75
+ can fail the run, and a UI log can lag committed work. Already-written legacy UI
76
+ logs are not repaired. Recorded model results without a projection marker retain
77
+ their original task sequence during replay. Configure
78
+ auth and retention; the UI is not an authoritative effect ledger.
79
+ InMemoryStreamBroker is unbounded until cleared.
80
+ Without a subscriber the UI response emits final text, not live deltas.
81
+ Opening a stream selects the run's versioned subscriber. Live migrations across
82
+ versions must share one ordered cursor transport; separate unrelated brokers
83
+ cannot provide a continuous cross-version token archive.
84
+ The native model chunks are assembled/persisted per step before publication,
85
+ not guaranteed token-by-token during generation. Reconnect rewinds the complete
86
+ message; the browser transport requires fresh UI parser state and stable-ID
87
+ replacement, not appending to cached partial messages. The starter's cursor
88
+ header is a high-water snapshot at response creation, with replay origin in a
89
+ separate header; later high-water marks arrive in transient data chunks.
90
+ The generic `await handle.toUIMessageStreamResponse(...)` has the same headers;
91
+ a configured custom subscriber must implement `readPage` for authoritative
92
+ high-water and retention metadata. A cursor is not proof a browser rendered it.
93
+ Redis event trim retains dedup/sequence metadata; apps must reclaim whole
94
+ expired instance key groups separately.
95
+
96
+ **Versioning boundary.** Ship old version configs to drain them. Migration is
97
+ only at parked approval/deferred boundaries and does not imply authorization.
98
+ Custom owning generators must manage their own rollover; this library does not
99
+ magically resume a surrounding application graph after continue-as-new.
100
+ Same-name distinct child versions are coalesced, but one name+version cannot
101
+ refer to different config objects/contracts. Preflight rejects those conflicts
102
+ before mutating the worker. Third-party worker registration failures are not
103
+ transactionally rollbackable: fix the worker or create a fresh worker instead
104
+ of treating a failed external install as a usable registration. Child DI mappers
105
+ must be deterministic; bind tenant/authorization inputs explicitly.
106
+
107
+ **Concurrency and duplicate start.** Client preflight queries improve errors;
108
+ the backend's atomic duplicate-instance rejection is authoritative under races.
109
+ Never substitute a backend which silently overwrites existing instances.
110
+ Approval decision APIs validate the currently published pending call; application
111
+ endpoints must add identity and authorization. `approvePending` requires a token
112
+ and shared atomic receipt store; the starter adds authenticated tenant ownership,
113
+ reviewer permission, server-derived actor subject and key-bound request deduplication.
114
+ Tenant ownership is not a per-subject resource ACL. Its auth provider intentionally fails closed
115
+ until integrated. Receipt/event delivery is not a distributed transaction:
116
+ retry the same POST for recovery, or implement an application outbox sweep.
117
+ Bind UI decisions to `approvalToken`; legacy token-optional `approve` and
118
+ `approveToolCall` are deprecated, have no atomic receipt and must not back a
119
+ production decision route. Optional `actorSubject` is server-supplied audit
120
+ attribution, not authentication; old/CLI receipts can lack it. `runSession` queues submissions by
121
+ turnId even while busy. Completion status retains only the latest 32 turn IDs:
122
+ waitForTurn can time out if a consumer waits beyond this window. It is not a
123
+ permanent turn-result archive, and it does not make independent thread writers safe.
124
+ All approval gates in a tool batch share a timeout and upgrade listener. Each
125
+ decision updates status and the UI immediately, in arrival order; no tool
126
+ effects are scheduled until all gates resolve.
127
+
128
+ **Termination and purge.** Termination is not compensation or guaranteed
129
+ cancellation of an in-flight mutation. Purge does not delete shared stores or
130
+ external effects.
@@ -0,0 +1,178 @@
1
+ # Operating durable Vercel AI agents
2
+
3
+ The Node web process is a DTS client. The separately supervised worker performs
4
+ model/tool I/O; a route timeout/browser abort only ends a reader. Neither implies
5
+ run cancellation or rollback. Hosted Azure acceptance is a separate opt-in lane,
6
+ not established by local emulator success. See [verification](verification.md).
7
+
8
+ ## Locate a run before acting
9
+
10
+ Keep the application tenant, instanceId, deployment/version, generation and step
11
+ in structured logs. Start with `sdk.getOrchestrationState(instanceId, true)`:
12
+ inspect `runtimeStatus`, `failureDetails`, input/output version and bounded custom
13
+ status. The client handle `customStatus()` deliberately raises failures; query the
14
+ SDK state directly for a failed run. A preview is not the full ledger/input.
15
+
16
+ ```ts
17
+ const state = await sdk.getOrchestrationState(instanceId, true);
18
+ console.log(state?.runtimeStatus, state?.failureDetails);
19
+ const handle = client.reconnect(instanceId);
20
+ const decision = await handle.pendingDecision(); // shared DecisionStore, authorized UI only
21
+ ```
22
+
23
+ Do not log prompts, tool inputs, credentials, trace baggage or full decision
24
+ payloads by default. Correlate by IDs; retrieve sensitive details only through
25
+ authorized tooling. Status/Redis retention is not DTS history retention.
26
+
27
+ ## Four failure classes
28
+
29
+ | Observation | Interpretation | Action |
30
+ |---|---|---|
31
+ | Parked gate + token | Human decision outstanding | Authorize reviewer, retrieve full input, POST exact token |
32
+ | Tool error from `NonRetryableToolError` / rejected approval | Business rejection, usually model-visible | Explain outcome; do not retry an invalid operation |
33
+ | Activity attempts exhausted / run FAILED | Infrastructure/provider/tool failure | Inspect failure history, connectivity, timeout and external effect receipt |
34
+ | Reader timeout/disconnect/retention gap | Web delivery failure, not necessarily run failure | Reconnect/rebuild by stable message ID or load authoritative completion |
35
+
36
+ Use SDK/DTS monitoring to read orchestration/activity history and sequence IDs.
37
+ The deterministic test hub's `getHistoryEvents(id)` returns real protobuf events
38
+ for local diagnostics; it is not a hosted history-query facade. Model/tool
39
+ request bodies stay inside activity payloads or history-store snapshots.
40
+
41
+ ## Attempts and terminal failure
42
+
43
+ `experimental_telemetry` is forwarded to **both** native model activity paths,
44
+ including configured tracer/functionId/privacy settings. Adapter correlation
45
+ metadata adds instance ID, generation and step. Install your OpenTelemetry SDK,
46
+ context manager and exporter in worker bootstrap; the adapter does not silently
47
+ create an exporter or send telemetry elsewhere. Prefer `recordInputs:false` and
48
+ `recordOutputs:false` for sensitive workloads.
49
+
50
+ ```ts
51
+ const agent = defineDurableAgent({
52
+ name: "shipping", model,
53
+ experimental_telemetry: { isEnabled: true, functionId: "shipping",
54
+ recordInputs: false, recordOutputs: false },
55
+ onToolAttempt(event) {
56
+ logger.info("tool-attempt", {
57
+ instanceId: event.instanceId, toolName: event.toolName,
58
+ attempt: event.attempt, maxAttempts: event.maxAttempts,
59
+ classification: event.classification, generation: event.generation, step: event.step,
60
+ });
61
+ },
62
+ onRunFailed(event) {
63
+ logger.error("run-failed", { instanceId: event.instanceId, version: event.version });
64
+ },
65
+ });
66
+ ```
67
+
68
+ These are **worker activity observers**, at least once, not replay-time side
69
+ effects or a guaranteed audit outbox. Observer failures surface rather than
70
+ being ignored; make hooks bounded/reliable and idempotent. Worker tool attempts
71
+ report success, business rejection or infrastructure failure after cleanup.
72
+ For exact attempt numbering when `onToolAttempt` is enabled, the orchestration
73
+ records each retry attempt/input and durable timer explicitly, honoring attempt,
74
+ backoff, predicate and retry-timeout bounds. Successful parallel siblings are not
75
+ re-executed. Without that hook, the existing SDK retry path is unchanged.
76
+ Pure orchestrator-inline tools do not run a worker attempt hook; choose a worker
77
+ execution mode if attempt telemetry is required. `onRunFailed` reports an engine
78
+ failure, not an operator termination, worker process crash, or reader abort.
79
+
80
+ ## Trace propagation
81
+
82
+ An authenticated Node route calls `traceContextFromHeaders(request.headers)` and
83
+ passes `traceContext` to `client.start`. Supported version-00 W3C traceparent/
84
+ tracestate is validated; malformed data fails explicitly. This serializable
85
+ carrier crosses orchestration input, continue-as-new, child orchestration and
86
+ activity input. Activities restore a remote parent in the configured OTel context
87
+ manager. Model headers carry the context and telemetry metadata correlates the
88
+ run; native AI SDK instrumentation owns its spans. `options.durable.traceContext`
89
+ is available to tools for downstream propagation. Do not treat trace headers as
90
+ identity, forward arbitrary baggage, or claim scheduler-internal spans are traced.
91
+
92
+ ## Retry, restart, compensation
93
+
94
+ Retry a transient **activity** under its declared policy, not a whole request
95
+ blindly. A completed activity boundary replays without repeating its effect.
96
+ An activity that committed externally before its DTS completion was persisted
97
+ may execute again. Look up the external system's receipt for the stable
98
+ idempotency key before deciding to retry or start a new run. Use a new instance
99
+ ID for a new business request; reuse a recorded key only for the same request.
100
+
101
+ Compensation is an application workflow/tool, not a property of retries. If an
102
+ approved charge must be reversed, invoke an authorized idempotent refund with
103
+ its own receipt, never purge history to pretend the charge did not happen.
104
+
105
+ ```ts
106
+ await client.terminate(instanceId, "Operator stopped after upstream outage");
107
+ // Poll scheduler state until terminal; running remote mutations may still finish.
108
+ await client.purge(instanceId); // rejects an observed nonterminal run
109
+ ```
110
+
111
+ The facade maps to SDK `terminateOrchestration` (reason stored as output) and
112
+ `purgeOrchestration`. Termination is not guaranteed cooperative cancellation of
113
+ an already-running tool/provider, not compensation, and not a recursive child
114
+ termination guarantee. Purge removes scheduler metadata, **not** shared history,
115
+ decision receipts, Redis data or external effects. Export required audit evidence
116
+ and apply application retention policies before purging.
117
+
118
+ ## State retention and decision recovery
119
+
120
+ Postgres snapshots are immutable JSONB rows; heads use transactional CAS and
121
+ foreign keys. Scope every store with explicit namespace and tenant ID; restrict
122
+ database roles/networking. `trim({before, protectedKeys})` excludes head targets
123
+ and the caller's pinned in-flight/reference keys. Inventory *all* retained run/
124
+ version references before trimming. It is not safe to pass an empty protected
125
+ list while unheaded active runs still reference old snapshots. No automatic GC
126
+ guesses which scheduler generations are safe to delete.
127
+
128
+ Redis uses per-instance ordered Streams with an atomic sequence/XADD/dedup step,
129
+ exact MAXLEN and explicit trim. `readPage` reports gaps even when the log is
130
+ empty. Size retention to the reconnect window. Dedup hashes/sequences are retained
131
+ separately from event trim so activity redelivery cannot reset ordering; reclaim
132
+ whole instance key groups only after runs and browser reconnect windows expire,
133
+ under an application-owned retention job. Production Redis needs persistence/HA;
134
+ a process-local broker is a test fixture, not failover storage.
135
+
136
+ Postgres decision records are immutable first-writer-wins submissions plus a
137
+ delivery receipt. If recording succeeded and event delivery failed/crashed, retry
138
+ the same instance/token: the original decision is redelivered, never replaced.
139
+ An app requiring unattended recovery should sweep undelivered receipts and resend
140
+ their exact gate-scoped events using its durable outbox job. Tokens do not grant
141
+ reviewer permissions; all retries still pass authentication and tenant ownership.
142
+
143
+ ## Deployment, drain and rollback
144
+
145
+ `createWorker` from `/worker` supplies the reusable health/drain host; the starter
146
+ wires DTS credentials and named history/decision/stream probes. `/health` is
147
+ liveness, not dependency health. `/ready` checks every configured dependency and
148
+ DTS with one 1,500 ms deadline (`readinessTimeoutMs`, maximum 2,000 ms). Errors or
149
+ timeouts return only `dependency unavailable`/503. Underlying driver calls may
150
+ outlive that deadline; each remains single-flight until it settles. Configure
151
+ driver connection/query timeouts as well, and alert on sustained 503s.
152
+
153
+ The checkpoint-first UI projection is another worker activity. Monitor its
154
+ retries separately from model calls: it republishes the committed snapshot
155
+ without paying for a new model answer. Model retry policy also bounds projection
156
+ attempts. If its retry budget is exhausted, diagnose Redis before deciding to
157
+ start a new business run. A previously recorded model result lacking the new
158
+ projection marker replays its legacy task sequence; old UI logs are not rewritten.
159
+ Do not roll back a run with `__project_model` history to a binary unaware of that
160
+ activity/sequence. Keep compatible workers and snapshot retention while draining.
161
+
162
+ Register current and retained contracts before starting a worker. Same-name
163
+ versions share canonical dispatch, but incompatible contracts/migration function
164
+ definitions fail preflight. Do not delete retained versions while runs reference
165
+ them. Upgrades occur only at parked boundaries, with explicit migrations and a
166
+ fresh gate token; a previously approved v1 gate does not authorize v2.
167
+
168
+ Deploy a compatible replacement first, verify `/ready`, withdraw old readiness,
169
+ then SIGTERM/drain the old worker. The starter's SDK drain budget defaults to
170
+ 30 seconds; align platform termination grace with it. Outstanding work returns
171
+ to the scheduler when leases expire; do not assume instant failover.
172
+
173
+ Rollback to an image that understands **every active version**, not simply the
174
+ previous binary. Keep schemas/store namespaces/provider contracts compatible.
175
+ Test old-first/new-first registration, parked migration and a true worker
176
+ replacement with the exact candidate. If a new version already mutated state,
177
+ roll forward or provide an explicit reverse migration/compensation rather than
178
+ silently relabeling it v1.
@@ -0,0 +1,41 @@
1
+ # Security and tenancy
2
+
3
+ For vulnerabilities, follow the [private reporting guidance](../README.md#security).
4
+ Do not put exploit details, credentials or customer data in
5
+ GitHub issues. This document describes application obligations, not a security
6
+ certification or a replacement reporting channel.
7
+
8
+ ## Application boundaries
9
+
10
+ Authenticate every route, derive tenant and actor identity from trusted
11
+ server-side authentication, and authorize run ownership and reviewer permission
12
+ before accessing state or submitting a decision. Tenant membership alone is not
13
+ a per-subject resource ACL. The starter's auth provider intentionally fails closed
14
+ until the application supplies a real integration.
15
+
16
+ Bind human decisions to the currently published `approvalToken` and use shared
17
+ atomic decision receipts. A token is not identity or authorization. Do not expose
18
+ legacy token-optional approval APIs as production decision routes. Retrying a
19
+ decision must preserve its original instance/token and pass authorization again.
20
+
21
+ ## Storage, transport and operations
22
+
23
+ Use explicit namespaces and tenant scope for shared stores. Restrict database and
24
+ Redis roles/network access, use TLS and configure persistence and retention.
25
+ Keep immutable history snapshots referenced by active or retained runs.
26
+ Reclaim Redis instance metadata only after runs and reconnect windows expire.
27
+
28
+ Routes and workers need separate least-privilege scheduler and store credentials;
29
+ worker identity does not grant route access. Keep provider credentials on workers,
30
+ not browser bundles or serialized orchestration inputs. Only `/transport` is
31
+ browser-safe; client/worker/store entry points are Node-only.
32
+
33
+ Do not log prompts, full tool inputs, credentials or trace baggage by default.
34
+ Trace headers and `actorSubject` audit fields are not authentication.
35
+ Disable telemetry input/output recording for sensitive workloads and retrieve
36
+ payloads only through authorized tooling.
37
+
38
+ An at-least-once tool effect needs downstream atomic idempotency. Termination,
39
+ purge and approval denial are not rollback of already committed external effects.
40
+ See [operations](operations.md), [limitations](limitations.md) and
41
+ [hosted DTS](Hosted-DTS.md).