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,191 @@
1
+ # Engineering design sketch: a Durable Task World for Workflow SDK
2
+
3
+ **ADR 0007 · Proposed for discussion · 27 October 2026**
4
+
5
+ **For:** the Vercel Workflow / AI SDK team
6
+
7
+ **Proposed package:** `@microsoft/workflow-world-durabletask`, standalone and proposed to be maintained alongside the Durable Task SDKs. Naming and maintenance commitments remain subject to agreement.
8
+
9
+ ## 1. Overview
10
+
11
+ We propose implementing Vercel's **World interface**, not replacing its workflow engine. One package would expose two drivers: Azure Durable Task Scheduler (DTS) for managed scheduling and persistence, and Durable Functions for applications already hosted in Azure Functions.
12
+
13
+ This would bring Azure-backed execution to three entry points:
14
+
15
+ - **Workflow SDK v5:** retain `"use workflow"` / `"use step"`, the compiler, and Workflow's event replay.
16
+ - **AI SDK:** support `WorkflowAgent` from `@ai-sdk/workflow` and World-backed `HarnessAgent` integrations, with resumable chat streaming.
17
+ - **`durable-harness`:** support its World-backed Pi, Claude Code, Codex, and OpenCode sessions. A World changes persistence and delivery, not sandbox execution or model access; existing sandbox, credential, and isolation requirements still apply. These are compatibility targets, not tested support claims. ([AI SDK][ai]; [harness hosting][harness])
18
+
19
+ The community **`fantasticfour-azure`** World, packaged as `@fantasticfour/world-azure`, already offers Cosmos DB + Service Bus with Change Feed streaming.[azure-world] This proposal complements that investment: DTS unifies entity-state persistence, orchestration scheduling, durable timers, and work-item delivery behind one managed Azure resource. It avoids requiring customers to assemble Cosmos DB, Service Bus, or SQL for the base adapter. DTS still needs application compute; it is not an HTTP push queue or a general-purpose database.[dts]
20
+
21
+ For an existing Durable Functions application, the second driver would reuse its Functions host, task hub, and entity-capable storage provider: **zero additional infrastructure for the base World**, not infrastructure-free execution. Choosing DTS as that provider is optional; an existing Azure Storage-backed app need not provision DTS.
22
+
23
+ ```text
24
+ Workflow SDK / WorkflowAgent / HarnessAgent / durable-harness
25
+ |
26
+ World: Storage + Queue + Streamer
27
+ |
28
+ @microsoft/workflow-world-durabletask
29
+ / \
30
+ DTS SDK driver Durable Functions driver
31
+ Node bridge/worker Existing Functions host
32
+ \ /
33
+ Run / hook-index / stream entities + dispatch orchestrations
34
+ |
35
+ Optional live-stream adapter
36
+ ```
37
+
38
+ **Boundary:** Workflow or the harness owns application replay. Durable Task orchestrations coordinate adapter commands, deliveries, and timers; activities execute the compiled application handler. We do not run the Workflow VM or model/tool loop inside a state-entity operation or a deterministic Durable Task orchestrator.
39
+
40
+ ## 2. Contract baseline and capability declarations
41
+
42
+ The inspected upstream snapshot is `vercel/workflow` commit `af8c6d3295ebc9aa7c0168cd0ca5007f62e6b9ba`, whose `@workflow/world` package is **5.0.5**. Package major v5 is **not protocol spec 5**. Declare `specVersion: mintedSpecVersion()` inside `createWorld()`; at this snapshot it returns **8**, or **6** with `WORKFLOW_SEALED_LOG=0`. Persist each run's version and keep World/runtime dependencies in the same release channel. ([World contract][world]; [version source][spec]; [implementation guide][guide])
43
+
44
+ | Surface | Proposed implementation / declaration rule |
45
+ |---|---|
46
+ | `Storage` | `events`, `runs`, `steps`, `hooks`; `Wait` views are returned by events. There is **no `Storage.waits` namespace**. |
47
+ | Snapshots / attributes | Optional `experimental_snapshots.save/load/delete`; attributes on `WorkflowRun.attributes`, via `attr_set` and the optional `runs.experimentalSetAttributes` compatibility surface. No top-level `snapshots` or `attributes` storage namespace. |
48
+ | `capabilities.inBandFence` | Set only after atomic counter/fence conformance passes. |
49
+ | `capabilities.hookRetention` | Shape is **`{ active: true }`**, not a boolean; enable only with retention-aware lookup, conflict, and cleanup. |
50
+ | `capabilities.hookForceClaim` | Enable only after the ordered cross-run takeover protocol below is crash-qualified. |
51
+ | `capabilities.maxConcurrency` | Enable only with distributed, per-topic consumption limits, including limit 1; host-wide worker concurrency is insufficient. The inspected `createQueueHandler` signature itself takes no concurrency-options argument. |
52
+ | `capabilities.dynamicWorkflowCode` | Persist code on both `run_created` and resilient `run_started`, return it on creation and `runs.get({ resolveData: 'all' })`; otherwise leave unsupported. |
53
+ | Optional methods | Presence advertises `events.createBatch` and `runs.waitForTerminalStatus`; neither has a separate capability flag. |
54
+
55
+ Unimplemented capabilities stay absent. Current consumers may also need `invoke` / `capabilities.invoke`: qualify a single active runner per run across workers, processing inputs while awaiting step work, before claiming the request/response harness path. Queue serialization alone is not that guarantee. ([Capabilities][world]; [Queue contract][queue])
56
+
57
+ ## 3. Storage: entity-backed event log and projections
58
+
59
+ ### Per-run commit boundary
60
+
61
+ **`RunStateEntity`, logical key `wf-run:{runId}`**, owns the event log, counters, command receipts, and materialized `WorkflowRun`, `Step`, `Hook`, and `Wait` views. DTS uses `TaskEntity`; Functions uses a Durable Entity. The installed **`@microsoft/durabletask-js@0.4.0` publicly exports `TaskEntity`**, with worker registration and executable entity-batch support. This is verified SDK support, not proof of a backend-qualified World.[entities]
62
+
63
+ Each short entity operation validates the transition, allocates dense slots, appends events, updates projections, and records the result in one state commit. Application I/O happens elsewhere. An `events.create` promise resolves **after committed processing**, never merely after `signalEntity` accepts a message.
64
+
65
+ For DTS 0.4.0, request/response entity calls are on **`ctx.entities.callEntity` inside an orchestration**, not on the external client. Initially, a command orchestration calls the entity and returns its committed result; transport retries reuse a command ID and payload digest. Functions uses the analogous `context.df.callEntity` path. A signal-plus-receipt gateway may optimize this later without changing acknowledgment semantics.
66
+
67
+ **Required invariants** ([event contracts][events]; [implementation guide][guide]):
68
+
69
+ - Allocate at commit and format IDs with `slotToEventId`; `requireEventSlot` must recover dense, 1-based positions. No UUID event IDs or speculative slot reservations. Commit-time allocation needs no `noop` hole repair.
70
+ - Honor `eventCount` using **bump-and-report**, not routine stale-write rejection: commit at the next slot and return skipped events with valid cursor/pagination semantics.
71
+ - Keep `seq` and `seqInBand`; creation initializes both to 1. With `inBand: true`, atomically compare `expectedSeqInBand` before any mutation. A mismatch writes nothing and throws **`InBandSupersededError`** with both counters; a missing count is a 400. Out-of-band writes advance only `seq`. Return a consistent `events.list` snapshot.
72
+ - **`PreconditionFailedError` is a distinct, optional stale-snapshot rejection**, not the in-band fence error. Our commit-time allocator should not need it. If introduced, reject only on proven discrepancy with a supplied `eventCount`; never infer an empty log from an absent count.
73
+ - Implement `createBatch` as an ordered, **atomic-per-attempt** entity operation with index-aligned per-event results. This does **not** mean all-or-nothing success: valid items may commit together while conflicting items report individual errors. Reject unsupported shapes and over-budget batches before mutation. Exclude `run_created`, `run_started`, `run_cancelled`, `hook_created`, `hook_disposed`, and `attr_set`; permit the special `step_created` + `step_started` pair only with input on the creation event. Do not blindly retry non-convergent events or ambiguous ownership claims.
74
+
75
+ ### Event-to-view mapping
76
+
77
+ | Event | Materialized behavior |
78
+ |---|---|
79
+ | `run_created` / `run_started` | Create `WorkflowRun` as `pending`, then `running`; resilient start can atomically synthesize creation when the original write was lost. |
80
+ | `step_created` / `step_started` | Create a pending `Step`, then start/increment its attempt. Lazy start carrying creation data atomically synthesizes creation and returns `stepCreated: true` only to the winning creator. Reject starts on terminal runs. |
81
+ | `step_completed` / `step_failed` / `step_retrying` | Commit result, terminal error, or pending retry state and `retryAfter`. Preserve legitimate finishing writes from already-started work after run termination. |
82
+ | `hook_created` / `hook_received` / `hook_disposed` | Register ownership, append a validated resume payload, or dispose/release ownership. A conflict creates World-authored `hook_conflict`, which the consumer surfaces as `HookConflictError`. |
83
+ | `wait_created` / `wait_completed` | Materialize `Wait` as `waiting` with `resumeAt`, then `completed`; the timer/delivery responsibility is described below. |
84
+ | `run_completed` / `run_failed` / `run_cancelled` | Commit `completed`, `failed`, or `cancelled`, plus required outcome/timestamps; initiate retention-aware hook cleanup and terminal notifications. |
85
+ | `attr_set` | Merge attribute changes into the run, preserving reserved-key rules. |
86
+
87
+ Reads preserve binary serialized data and the upstream `resolveData` contract, including treating `'skip-step-inputs'` as `'all'` for everything except the optional omission of step inputs. Implement cursor-based `events.get/list/listByCorrelationId`, `runs.get/list`, `steps.get/list`, and `hooks.get/getByToken/list` over the projections. ([Run][runs], [Step][steps], [Hook][hooks], and [Wait][waits] schemas)
88
+
89
+ ### Global hook tokens without an external SQL database
90
+
91
+ **`HookIndexEntity`**, keyed by `wf-hook-token:{tokenHash}` (or bucketed `wf-hook:{hashBucket}`), serializes claims across runs within the World's tenant/project/environment namespace. Store the original identity to detect hash collisions. Maintain a hook-ID locator too: `hooks.get(hookId)` has no `runId` argument.
92
+
93
+ This is **not** an automatic transaction across entities. A durable per-token coordinator owns reservation generations, idempotent commands, and recovery:
94
+
95
+ 1. Reserve the token; commit the claimant's hook/event before making a normal claim available to lookups. A competing claim waits for recovery or commits `hook_conflict` with `conflictingRunId`.
96
+ 2. On forced takeover, first commit the victim's `hook_disposed{forceClaimedBy}` **atomically with its run-local receive fence**. Only then change the index owner and its `claimedFrom`, and commit the claimant's `hook_created{force, forceClaimedFrom}`. Validate the reservation generation so an intervening takeover cannot resurrect an obsolete claim.
97
+ 3. Keep transitional ownership recoverable, not visible as two live owners. A resume resolved to the old owner is refused with **`HookForceClaimedError`**, after completing any pending index repointing, so the caller can follow the token. Preserve the victim wake-routing data in the log. Refuse takeover of an active victim whose stamped version cannot interpret involuntary disposal.
98
+ 4. On terminal runs, hooks cannot resume. Retained hooks remain readable and reserve their tokens until `tokenRetentionUntil`; an active run retains ownership beyond that deadline. Explicit `hook_disposed` releases immediately. Cleanup timers use generation checks, and retained owner runs remain readable.
99
+
100
+ Qualification must cover crashes between every phase, creation racing cancellation, and resume racing takeover. Leave `hookForceClaim` absent until these guarantees hold. If declaring `hookResumeDedup`, also atomically deduplicate `(runId, resumeId)`, validate the payload digest, and round-trip `resumeId` on reads. ([Takeover contract][world]; [event fields][events])
101
+
102
+ ### Terminal waits, listings, and size boundaries
103
+
104
+ `runs.waitForTerminalStatus(id, { timeoutMs, resolveData, signal })` first reads, registers a waiter, then rereads to close the subscribe race. A terminal entity commit records a notification outbox entry; worker delivery wakes waiting bridges, which reread authoritative state and answer immediately on observing `completed` / `failed` / `cancelled`. Cross-worker notification delivery is adapter work, not a built-in DTS change feed. Bounded rereads repair lost notifications. At the timeout budget return the latest run, even if nonterminal; timeout is not an error, and missing runs fail as `get` does.[world]
105
+
106
+ Sharded directory entities, populated through durable outboxes, support required cross-run `runs.list` / `hooks.list` operations. Recheck candidate records and honor filters, ordering, and pagination; directory queries are eventually consistent, not cross-entity transactional snapshots. Optional `analytics` is a separate metadata-only query surface, initially omitted rather than pretending DTS is SQL.
107
+
108
+ Entity state is finite. The first implementation must publish conservative run/event/payload/stream limits and reject before exceeding backend budgets. Large histories and payloads may need paged immutable storage or optional Blob spill; that changes the base infrastructure profile. Optional VM snapshots use atomic bytes-plus-`SnapshotMetadata` envelopes and idempotent deletion, or remain absent with correct full replay.
109
+
110
+ ## 4. Queue and durable timers: two execution topologies
111
+
112
+ `world.queue(queueName, message, opts)` durably admits an adapter dispatch record and schedules its orchestration/activity. It preserves `deploymentId`, `idempotencyKey`, `delaySeconds`, namespace, binary transport, trace context, and a stable `messageId` across redeliveries. `getDeploymentId()` returns the configured build identity; routing retains that build for existing runs. Authentication and deployment routing are explicit adapter responsibilities.[queue]
113
+
114
+ | | Topology A — push to HTTP flow route | Topology B — co-located execution |
115
+ |---|---|---|
116
+ | Hosting | Next.js on Vercel, Azure App Service, or Container Apps; separate DTS worker / Functions bridge | Self-hosted Node worker container or Azure Functions host |
117
+ | Delivery | Dispatch activity POSTs to the compiled **`WORKFLOW_FLOW_ROUTE`**, `/.well-known/workflow/v1/flow`, or the prefix's `registerRoute` target served by `createQueueHandler` | Dispatch activity invokes the registered Fetch handler **in-process**, using `registerHandler(prefix, handler)` and the same `createQueueHandler` request/response contract |
118
+ | Cost / constraint | Preserves existing web deployment shape; adds a network hop and needs a reachable, authenticated route | Zero extra HTTP delivery hop; requires importing/bundling the appropriate compiled Workflow or harness handler in each worker |
119
+
120
+ Both use **at-least-once delivery**. A rejected handler retries the same message with incremented attempt; ordinary `{ timeoutSeconds }` results schedule another delivery. Persist backoff/deadlines with native timers, not a sleeping activity. A distributed dispatcher/lease protocol enforces per-topic `maxConcurrency`, with fencing against expired owners; worker-local semaphores alone do not qualify. Application side effects still need idempotency.
121
+
122
+ **`sleep` ownership:** Workflow records `wait_created` and queues a delayed continuation. The adapter's `TimerOrchestration` honors `delaySeconds` with DTS `ctx.createTimer` or Functions `context.df.createTimer`, then dispatches the handler. Workflow replay completes elapsed waits by writing `wait_completed`. Do not independently append a second completion from the timer worker. Preserve continuation attempt/idempotency keys so an early delivery can re-arm rather than lose the wake; cancel stale dispatches logically when runs terminate.[timers]
123
+
124
+ Non-Workflow consumers such as `durable-harness` need their **own queue namespace and registered handler/route**; not every message belongs at the default Workflow flow route. Neither topology makes DTS itself an HTTP queue service.
125
+
126
+ ## 5. Streamer: durability first, optional low-latency fan-out
127
+
128
+ Implement `streams.write`, optional `writeMulti` and `createWriteSession`, `close`, `get`, **`list`**, `getChunks`, and `getInfo`. A write session exposes `write(chunkSeq, chunks)` and `close()`; its `writerId` and sequence describe one in-memory writer lifetime, not a global replay identity. ([Streamer contract][world]; [chunk response types][chunks])
129
+
130
+ | | Tier 1 — zero-extra-service mode | Tier 2 — high-throughput live mode |
131
+ |---|---|---|
132
+ | Durable storage | Per-stream entity, logical key `wf-stream:{runId}:{name}`; ordered chunk groups with receipt-based retry deduplication | Pluggable durable Redis Streams adapter, or durable chunk/Blob storage paired with Azure Web PubSub fan-out |
133
+ | Writes | Proposed **`streamFlushIntervalMs: 50`** batches high-frequency token traffic; enforce a byte/count flush ceiling and await durable acknowledgment | Lower/zero flush interval and persistent connections; publish only after durable append |
134
+ | Readers | `getChunks` paginates persisted chunks; `getInfo` returns `tailIndex` / `done`; `get` exposes a live `ReadableStream` backed by local wakeups and cross-process long polling | Durable cursors provide reconnect/backfill; live Redis/Web PubSub delivery accelerates fan-out, never becomes the sole copy |
135
+ | Trade-off | No extra service, but roughly 50 ms batching plus entity/RPC latency, finite entity capacity, and serialization overhead | Additional service and operations; target **sub-10 ms live fan-out**, to be measured, not promised as end-to-end CTT |
136
+
137
+ Redis Streams can use a compatible managed service such as Azure Managed Redis or an existing Azure Cache for Redis deployment. Blob alone is not a sub-10 ms pub/sub transport.
138
+
139
+ Persist thousands of chunks per turn without one entity operation per token. `close` must flush and durably finish all prior accepted writes. Preserve zero-based chunk indices, negative `get` start indices, pagination, and `done` independently of `hasMore`; release/dispose transports without accidentally closing the logical stream.
140
+
141
+ AI SDK may store raw `ModelCallStreamPart` and transform it into `UIMessageChunk`; these cursor spaces are not interchangeable. `WorkflowChatTransport` reconnects must respect that transform boundary.[ai] Benchmark **chunk trip time (CTT)** from the call to write a chunk through reader receipt, including buffering and persistence, alongside fan-out-only latency, p50/p75/p99, reconnect correctness, and sustained backpressure. Tier 1 and Tier 2 must report separate results.
142
+
143
+ ## 6. One package, two drivers; complementary native integration
144
+
145
+ The proposed internal driver seam supplies entity commands/reads, orchestration admission/results, timers, delivery, and namespace/deployment identity. Shared code owns World event semantics, projections, hook coordination, serialization, and stream adapters.
146
+
147
+ | Driver | Implementation and hosting |
148
+ |---|---|
149
+ | **`mode: "dts"`** | `@microsoft/durabletask-js` + `@microsoft/durabletask-js-azuremanaged`; production TLS and `DefaultAzureCredential` with task-hub RBAC. Local development uses **`mcr.microsoft.com/dts/dts-emulator`**. Host the bridge/worker separately from a Vercel function, or co-locate it on Azure compute. |
150
+ | **`mode: "durable-functions"`** | `durable-functions` **v3** Node SDK, using **`df.app.entity`**, **`df.app.orchestration`**, **`df.app.activity`**, and **`df.getClient(context)`** with its required durable-client input binding. This SDK version uses the Functions Node programming model v4; the version numbers are different. Register package-owned functions and compiled application handlers at host startup; reuse the app's configured provider.[functions] |
151
+
152
+ The base package would not require Redis, Blob, Cosmos DB, Service Bus, or SQL as separately provisioned services. Optional adapters and the chosen Functions provider can add or reuse those dependencies. Qualify backend entity support and limits per driver/provider, not just against local SDK types.
153
+
154
+ | Choose | When |
155
+ |---|---|
156
+ | **`@microsoft/workflow-world-durabletask` — World adapter** | Authoring with Workflow SDK `"use workflow"` / `"use step"`, AI SDK `WorkflowAgent` / `HarnessAgent`, or `durable-harness`; retain that engine and ecosystem. |
157
+ | **`ai-sdk-azure-durable-task` — direct AI SDK integration** | A DTS-native application wants `ToolLoopAgent` / `generateText` / `streamText`-style model work as activities or a turn sub-orchestration inside a larger `async function*` DTS orchestration, including C#/Python polyglot composition. Existing Durable Functions apps have the same native-composition use case, but Functions/provider/polyglot interoperability needs its own qualification; this proposal does not claim the existing package is a drop-in Functions v3 driver. |
158
+
159
+ The direct integration retains orchestration-owned, step-level model/tool checkpoints rather than moving the whole loop into an entity operation. The World adapter leaves those application durability boundaries to Workflow/the harness. Neither path implies exactly-once external side effects.
160
+
161
+ ## 7. Five questions for the technical sync
162
+
163
+ 1. **v5 write contract:** Are the proposed `createBatch` per-event outcomes, commit-time bump-and-report, and optional `inBandFence` declarations aligned with your intended third-party baseline? Which batch size caps and conformance suites should gate first release?
164
+ 2. **Timers and hosting:** Can we standardize on World-delayed queue delivery with Workflow owning `wait_completed`, as the inspected runtime does? Which of HTTP topology A or in-process topology B should the first cookbook demonstrate, including harness namespace registration?
165
+ 3. **Streams:** What chunk byte limits, retention windows, close/reconnect guarantees, and CTT workload should we target for `HarnessAgent` and `WorkflowChatTransport`? Is a 50 ms, bounded entity-backed base mode useful alongside an optional high-throughput adapter?
166
+ 4. **Queries and harness readiness:** What cross-run `analytics` filters/consistency are required without SQL, beyond canonical storage listings? Should the first milestone include request/response `invoke` and its single-runner contract before advertising all harness integrations?
167
+ 5. **Packaging:** Do you prefer `@microsoft/workflow-world-dts` or **`@microsoft/workflow-world-durabletask`** for one package covering DTS and Durable Functions? We favor the latter, with driver-specific configuration, Microsoft maintenance, and a jointly reviewed cookbook.
168
+
169
+ **Suggested next step:** agree on the baseline, then build a conformance-first spike: atomic append/batch/fence tests; cross-run hook crash races; both delivery topologies and timer recovery; terminal long-poll races; bounded streaming/reconnect and CTT. Run the same suite against the DTS emulator, hosted DTS, and a Functions provider. No production-readiness or performance claim precedes that evidence.
170
+
171
+ ### References
172
+
173
+ Source-checked on 27 October 2026. All adapter behavior above is proposed; upstream contracts and the installed SDK entity surface are the verified inputs.
174
+
175
+ [world]: https://github.com/vercel/workflow/blob/af8c6d3295ebc9aa7c0168cd0ca5007f62e6b9ba/packages/world/src/interfaces.ts
176
+ [spec]: https://github.com/vercel/workflow/blob/af8c6d3295ebc9aa7c0168cd0ca5007f62e6b9ba/packages/world/src/spec-version.ts
177
+ [events]: https://github.com/vercel/workflow/blob/af8c6d3295ebc9aa7c0168cd0ca5007f62e6b9ba/packages/world/src/events.ts
178
+ [queue]: https://github.com/vercel/workflow/blob/af8c6d3295ebc9aa7c0168cd0ca5007f62e6b9ba/packages/world/src/queue.ts
179
+ [guide]: https://workflow-sdk.dev/worlds/building-a-world.md
180
+ [runs]: https://github.com/vercel/workflow/blob/af8c6d3295ebc9aa7c0168cd0ca5007f62e6b9ba/packages/world/src/runs.ts
181
+ [steps]: https://github.com/vercel/workflow/blob/af8c6d3295ebc9aa7c0168cd0ca5007f62e6b9ba/packages/world/src/steps.ts
182
+ [hooks]: https://github.com/vercel/workflow/blob/af8c6d3295ebc9aa7c0168cd0ca5007f62e6b9ba/packages/world/src/hooks.ts
183
+ [waits]: https://github.com/vercel/workflow/blob/af8c6d3295ebc9aa7c0168cd0ca5007f62e6b9ba/packages/world/src/waits.ts
184
+ [chunks]: https://github.com/vercel/workflow/blob/af8c6d3295ebc9aa7c0168cd0ca5007f62e6b9ba/packages/world/src/shared.ts
185
+ [timers]: https://github.com/vercel/workflow/blob/af8c6d3295ebc9aa7c0168cd0ca5007f62e6b9ba/packages/core/src/runtime/wait-continuation.ts
186
+ [azure-world]: https://github.com/vercel/workflow/blob/af8c6d3295ebc9aa7c0168cd0ca5007f62e6b9ba/worlds-manifest.json
187
+ [dts]: https://learn.microsoft.com/en-us/azure/durable-task/scheduler/durable-task-scheduler
188
+ [entities]: https://github.com/microsoft/durabletask-js/tree/main/packages/durabletask-js/src/entities
189
+ [functions]: https://github.com/Azure/azure-functions-durable-js/blob/v3.x/src/app.ts
190
+ [ai]: https://ai-sdk.dev/docs/agents/workflow-agent
191
+ [harness]: https://vercel.com/docs/agent-harnesses/self-hosting
@@ -0,0 +1,17 @@
1
+ # Architecture decisions
2
+
3
+ 1. [Dual native surfaces](0001-dual-surface-authoring.md)
4
+ 2. [Deterministic generator turn stepper](0002-generator-turn-stepper.md)
5
+ 3. [Tool durability, deps and MCP](0003-tools-deps-and-mcp.md)
6
+ 4. [Approvals and bounded status](0004-approvals-and-status.md)
7
+ 5. [State, streaming, sessions, subagents and versions](0005-state-streaming-subagents-versioning.md)
8
+ 6. [MAF entity sessions, turn steppers and the hybrid model](0006-maf-entity-session-comparison-and-hybrid-model.md)
9
+
10
+ Decisions 0001–0006 are accepted. They adapt the verified Vercel research and
11
+ Python sibling architecture to the actual pinned TypeScript SDK contracts. See
12
+ the root engineering design for compatibility corrections and the support matrix
13
+ for implementation boundaries.
14
+
15
+ ## Proposed integration sketches
16
+
17
+ 7. [A Durable Task World for Workflow SDK: DTS and Durable Functions](0007-workflow-world-dts-and-durable-functions-sketch.md) — proposed for discussion with the Vercel Workflow / AI SDK team; not an implemented or accepted runtime change.
@@ -0,0 +1,139 @@
1
+ # Development
2
+
3
+ ## Local package installation
4
+
5
+ Until a registry release is available, clone
6
+ [vercel-labs/ai-sdk-azure-durable-task](https://github.com/vercel-labs/ai-sdk-azure-durable-task)
7
+ and build the package:
8
+
9
+ ```powershell
10
+ npm ci
11
+ npm run build
12
+ npm pack
13
+ ```
14
+
15
+ In a separate application, install the resulting local tarball with its peers:
16
+
17
+ ```powershell
18
+ npm install C:\path\to\ai-sdk-azure-durable-task-0.1.0.tgz ai zod
19
+ ```
20
+
21
+ Use the qualified tarball rather than repacking when validating exact bytes.
22
+ `npm run qualify:artifact -- --ai-version=6.0.303` (or `7.0.172`) retains
23
+ the tarball, `SHA256SUMS`, and `qualification.json` in the printed `.work/`
24
+ artifact directory. None of these commands publishes to npm.
25
+
26
+ ## Validation
27
+
28
+ ```powershell
29
+ npm ci
30
+ npm run typecheck
31
+ npm test
32
+ npm run test:emulator
33
+ npm run test:dts # opt-in: requires an authenticated HTTPS DTS_ENDPOINT
34
+ npm run build
35
+ npm run examples
36
+ npm run examples:emulator
37
+ npm run benchmark
38
+ ```
39
+
40
+ No extra tools are installed during validation. `npm ci` installs the locked
41
+ dependency versions from the default public npm registry; no registry
42
+ configuration is required.
43
+ The portable lockfile retains exact versions and integrity hashes without
44
+ registry-specific tarball URLs. When regenerating it, use
45
+ `npm install --package-lock-only --ignore-scripts --omit-lockfile-registry-resolved=true`
46
+ to keep it independent of the maintainer's configured registry.
47
+ After dependency updates, run `npm install` and commit the resulting
48
+ `package-lock.json`; `npm run check:package` validates the lockfile license
49
+ metadata, exact dependency pins, absence of app/driver dependencies, import boundaries and the operational-document
50
+ tarball allowlist.
51
+ The root manifest pins patched transitive dependencies through npm `overrides`.
52
+ After changing those overrides, run `npm audit` and check the lockfile versions,
53
+ including the development-only PostCSS dependency required by Vitest/Vite.
54
+ No PostCSS is installed by the published SDK. If npm retains stale entries,
55
+ regenerate the lockfile without
56
+ an existing `node_modules` directory and verify a clean `npm ci`
57
+ before running the builds and tests.
58
+ CI runs `npm ci` for the locked SDK 6 qualification. The SDK 7 legs back up
59
+ the root manifest and move the lockfile aside before installing the alternate
60
+ version into a fresh dependency tree and auditing its generated lockfile.
61
+ The manifest and original lockfile are restored immediately after
62
+ installation (also on failure), leaving SDK 7 in `node_modules` without changing
63
+ the tracked package inputs used by `npm run check:package`.
64
+ SDK 7 qualification selects `@ai-sdk/react@4.0.176` to match `ai@7.0.172` instead of
65
+ the locked SDK 6 React binding (`3.0.306` / `ai@6.0.303`).
66
+ `tests/mcp-optional-peer.test.ts` asserts one version of each SDK 7 provider
67
+ package. PostgreSQL/Redis/MCP clients are caller-owned structural interfaces,
68
+ not SDK dependencies. Factory-backed MCP pools never import an adapter.
69
+ `npm run qualify:artifact -- --ai-version=6.0.303` and
70
+ `npm run qualify:artifact -- --ai-version=7.0.172` install the actual tarball
71
+ in standalone `.work/` consumers and compile/run all exports without drivers.
72
+ See [CONTRIBUTING.md](../CONTRIBUTING.md) for the complete CI and emulator commands.
73
+ Negative compile-time assertions in
74
+ `tests/consumer-types.ts` ensure output/dependency/tool types cannot decay to any.
75
+ Real-executor tests cover native tools, local guards, fan-out/retry isolation,
76
+ history snapshots, approval timer/waiter cleanup, deferred results, streaming,
77
+ MCP pooling, idempotent start and session event carryover. Examples add graph,
78
+ version drain/migration and actual process restart coverage.
79
+
80
+ `npm run build` emits ESM JavaScript, declarations and source maps. Runtime and
81
+ testing exports resolve from `dist/src`. No public registry publish is performed.
82
+ VS Code profiles use Node plus tsx so breakpoints map directly into TypeScript.
83
+
84
+ SDK private internals are confined to the explicit compatibility surface in
85
+ approvals and the testing harness. When updating durabletask-js, review those
86
+ contracts and rerun the timeout cleanup test plus all emulator examples.
87
+ Treat missing hosted/provider evidence as an open verification boundary, not as
88
+ proof supplied by a large unit-test count.
89
+
90
+ `npm test` skips the live suites unless `DTS_EMULATOR`, `DTS_ENDPOINT` or
91
+ `DTS_HOSTED_ENDPOINT` selects their backend.
92
+ CI waits up to 60 seconds for an Azure-managed `getOrchestrationState` gRPC
93
+ readiness probe before running emulator tests and examples. A TCP connection alone
94
+ is insufficient: Docker can accept connections before the emulator's Kestrel
95
+ server is ready. The probe queries a nonexistent instance and closes its client
96
+ after readiness or timeout.
97
+ `npm run test:emulator` explicitly selects it and defaults DTS_EMULATOR to
98
+ 127.0.0.1:18080, DTS_TASKHUB default vercel-ai; an unavailable requested backend fails
99
+ instead of skipping or using the in-memory harness. Override with
100
+ `$env:DTS_EMULATOR = "host:port"` and `$env:DTS_TASKHUB = "hub"` in PowerShell. The suite uses Azure-managed
101
+ gRPC builders and covers concurrent starts, approval/timer cleanup, SQLite
102
+ session rollover, old-version drain, replacement gates and same-name retained
103
+ child versions on a replacement worker. Additional regressions compare
104
+ native output messages, prepared context across policies/rollover, ordinary call
105
+ settings and terminal outer-stop validation. Compiler negatives cover attachment
106
+ dependency compatibility and required child-input binding.
107
+ Canonical-extension regressions additionally cover old/latest registration in
108
+ both orders, exact retained contracts, fresh upgrade gates, migration conflicts
109
+ within/across registrations, recovery after rejected registration and isolation
110
+ between workers. The two compatible-order upgrade cases also run over live gRPC.
111
+
112
+ Storage and streaming contracts run memory/file/SQLite unconditionally. Set
113
+ `DATABASE_URL` / `REDIS_URL` to include Postgres/Redis; otherwise those tests
114
+ skip clearly, without failing offline CI. Install `pg` and `redis` locally
115
+ with `npm install --no-save --package-lock=false pg redis --ignore-scripts`
116
+ before opting into those driver-backed tests; they are loaded only in test
117
+ helpers, not SDK source. The worker replacement test uses SDK exports directly
118
+ and requires only `DTS_EMULATOR`. `npm run test:dts` selects the entire live suite
119
+ against a real HTTPS `DTS_ENDPOINT` (legacy `DTS_HOSTED_ENDPOINT` also works).
120
+ Both client and worker use `DefaultAzureCredential`, or `AzureCliCredential`
121
+ when `DTS_CREDENTIAL=azure-cli`. Azure CLI authentication does not require
122
+ `AZURE_CLIENT_ID` / `AZURE_TENANT_ID`. Postgres hosted hydration also requires
123
+ `DATABASE_URL`. This explicit lane fails, rather than skipping or substituting
124
+ the emulator, when the selected scheduler or credentials are unavailable.
125
+ `npm run test:emulator` clears inherited hosted endpoints so it stays local.
126
+ See [Hosted-DTS.md](Hosted-DTS.md) for hub/RBAC requirements, coverage and
127
+ restricted instance-ID/timing evidence. Never commit connection credentials.
128
+
129
+ After a package build, `npm run check:package` exercises runtime imports,
130
+ strict built-only declaration consumers and `npm pack --dry-run`.
131
+ Sample apps are not part of this SDK repository. Example 09 is a route factory,
132
+ tested separately instead of run as a worker script. See
133
+ [the hosting guide](user-guide.md#reliable-streaming-and-nextjs-usechat) for mandatory auth integration and reader reset
134
+ semantics, and [operations](operations.md) for trace/attempt/failure controls.
135
+
136
+ The benchmark runs 60 combinations: 5 counts x 3 scenarios x inline/SQLite x
137
+ rollover off/on. It asserts complete transcript hashes, pointer-only wire shape,
138
+ large-run byte improvements and bounded generations, while reporting external
139
+ SQLite storage separately. Regenerate its JSON and Markdown together.