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,115 @@
|
|
|
1
|
+
# Hosted Azure Durable Task Scheduler
|
|
2
|
+
|
|
3
|
+
Hosted Azure acceptance is an opt-in qualification lane, not a guarantee supplied
|
|
4
|
+
by offline or emulator tests. Validate hosted Azure, commercial model providers,
|
|
5
|
+
and high availability against your deployment requirements before rollout.
|
|
6
|
+
|
|
7
|
+
## Topology and credentials
|
|
8
|
+
|
|
9
|
+
Run Node web routes as DTS clients and model/tool execution in a separate,
|
|
10
|
+
long-lived Node worker. Root, client and worker imports require Node; they are
|
|
11
|
+
not Edge-compatible. Only `/transport` is a browser UI transport.
|
|
12
|
+
|
|
13
|
+
Use Azure-managed DTS client/worker builders with an HTTPS endpoint, the task
|
|
14
|
+
hub name and `DefaultAzureCredential`. Authenticate routes and workers separately;
|
|
15
|
+
a worker identity does not automatically authenticate the web client. Configure
|
|
16
|
+
least-privilege scheduler authorization, network access and TLS outside the
|
|
17
|
+
library. Do not commit credentials.
|
|
18
|
+
|
|
19
|
+
### Vercel OIDC federation to Microsoft Entra ID
|
|
20
|
+
|
|
21
|
+
Do not copy the worker's managed identity or store a long-lived Entra client secret
|
|
22
|
+
in Vercel. Configure an Entra application federated identity credential that trusts
|
|
23
|
+
the exact Vercel team/project/environment issuer and subject, and the Azure token
|
|
24
|
+
exchange audience. The deployment must obtain a fresh Vercel OIDC assertion for
|
|
25
|
+
each token exchange and use `ClientAssertionCredential` (or an explicitly
|
|
26
|
+
configured workload identity credential) with the Entra tenant/client IDs.
|
|
27
|
+
`DefaultAzureCredential` alone does not discover Vercel's assertion automatically.
|
|
28
|
+
|
|
29
|
+
Scope the trust to the intended production deployment; preview deployments need
|
|
30
|
+
their own explicitly authorized subject/trust. Grant that route principal only
|
|
31
|
+
the scheduler/task-hub permissions needed to start/read/raise events. Give the
|
|
32
|
+
worker its own principal and permissions. Validate issuer/subject/audience against
|
|
33
|
+
the current [Vercel OIDC documentation](https://vercel.com/docs/oidc) and
|
|
34
|
+
[Entra workload identity federation](https://learn.microsoft.com/entra/workload-id/workload-identity-federation)
|
|
35
|
+
before provisioning; no credential or trust is created by this package.
|
|
36
|
+
|
|
37
|
+
Use PostgreSQL for history and decisions and Redis for shared UI events across
|
|
38
|
+
hosts. File/SQLite and in-memory stores do not provide cross-host persistence.
|
|
39
|
+
Configure identical store namespaces and explicit tenant scope on clients and
|
|
40
|
+
workers. The application must authenticate and authorize every run and decision.
|
|
41
|
+
|
|
42
|
+
## Opt-in acceptance
|
|
43
|
+
|
|
44
|
+
Run the complete live gRPC suite against **real Azure Managed DTS**:
|
|
45
|
+
|
|
46
|
+
```powershell
|
|
47
|
+
az login
|
|
48
|
+
$env:DTS_ENDPOINT = "https://<scheduler>.<region>.durabletask.io"
|
|
49
|
+
$env:DTS_TASKHUB = "vercel-ai" # or an existing, authorized test hub
|
|
50
|
+
$env:DTS_CREDENTIAL = "azure-cli" # optional; default is DefaultAzureCredential
|
|
51
|
+
npm run test:dts
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Use the scheduler's actual `properties.endpoint`, not an endpoint synthesized
|
|
55
|
+
from its ARM name. The signed-in identity needs **Durable Task Data Contributor**
|
|
56
|
+
on the scheduler or test hub; subscription Owner alone is not data-plane access.
|
|
57
|
+
Verify the scheduler and existing hubs before creating anything. A scheduler
|
|
58
|
+
may have reached its task-hub quota; reuse an authorized hub with unique test
|
|
59
|
+
names and registry-derived worker filters instead of deleting another hub or
|
|
60
|
+
creating a new scheduler. No infrastructure or RBAC is provisioned by this
|
|
61
|
+
test runner.
|
|
62
|
+
|
|
63
|
+
`npm run test:dts` requires `DTS_ENDPOINT` (or the legacy `DTS_HOSTED_ENDPOINT`)
|
|
64
|
+
with HTTPS, and fails if authentication, authorization or the live scheduler
|
|
65
|
+
is unavailable. It never substitutes the emulator or in-memory harness.
|
|
66
|
+
`DTS_HOSTED_TASKHUB` overrides `DTS_TASKHUB`; the default hub is `vercel-ai`.
|
|
67
|
+
Both client and worker receive the same explicit credential and hub.
|
|
68
|
+
`DefaultAzureCredential` is the default; `DTS_CREDENTIAL=azure-cli` selects
|
|
69
|
+
`AzureCliCredential` for a locally signed-in developer. Azure client/tenant
|
|
70
|
+
environment variables are not prerequisites for Azure CLI credentials.
|
|
71
|
+
Service-principal/workload identities must supply their appropriate credential
|
|
72
|
+
configuration. Never print access tokens or commit credentials.
|
|
73
|
+
|
|
74
|
+
The command runs `tests/emulator.test.ts` against hosted DTS plus
|
|
75
|
+
`tests/hosted.test.ts`. Coverage includes:
|
|
76
|
+
|
|
77
|
+
- Single-turn `DurableTaskAgent` with explicit `ToolExecution.DURABLE` tools,
|
|
78
|
+
and `attachDurability` on a native `ToolLoopAgent`.
|
|
79
|
+
- Concurrent idempotent starts and multi-turn `runSession` with persistent
|
|
80
|
+
`threadId`, SQLite history and queued turns across `continueAsNew`.
|
|
81
|
+
- Parallel `toolApproval` gates, out-of-order `approve`, token correlation,
|
|
82
|
+
timers and worker replacement while approval is parked.
|
|
83
|
+
- `child.asTool()` composition, custom `yield* agent.runInOrchestration(ctx, ...)`,
|
|
84
|
+
retained child versions and canonical version migration.
|
|
85
|
+
- A 5 MB tool result offloaded before scheduler serialization to a compact
|
|
86
|
+
`__tool_output_ref__`, full result hydration and byte-budget generation rollover.
|
|
87
|
+
- Reopened SQLite history across workers and explicit termination.
|
|
88
|
+
|
|
89
|
+
The PostgreSQL hydration case additionally requires `DATABASE_URL`; without it,
|
|
90
|
+
only that case skips. SQLite and in-memory claim-check storage qualify a
|
|
91
|
+
single-machine test, **not** a cross-host production deployment. Configure shared
|
|
92
|
+
production stores separately.
|
|
93
|
+
|
|
94
|
+
Offline `npm test` skips the live suites unless a live endpoint is selected.
|
|
95
|
+
`npm run test:emulator` continues to use anonymous HTTP with `DTS_EMULATOR`
|
|
96
|
+
(default `127.0.0.1:18080`). Clear hosted endpoint variables when selecting the
|
|
97
|
+
emulator directly. All live tests use scripted AI models; passing does not qualify
|
|
98
|
+
a commercial provider or high availability.
|
|
99
|
+
|
|
100
|
+
For restricted validation evidence, opt in to `DTS_TEST_TRACE=1`. It emits
|
|
101
|
+
endpoint, task hub, root/child instance IDs and elapsed milliseconds, without
|
|
102
|
+
model payloads or credentials. Capture the verbose test output with timings:
|
|
103
|
+
|
|
104
|
+
```powershell
|
|
105
|
+
New-Item -ItemType Directory -Force .work | Out-Null
|
|
106
|
+
$env:DTS_TEST_TRACE = "1"
|
|
107
|
+
npm run test:dts 2>&1 | Tee-Object .work\hosted-dts.log
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`.work` is gitignored. Keep the exact endpoint/identity configuration, instance
|
|
111
|
+
IDs, test output and timings in this restricted record, not public CI logs.
|
|
112
|
+
|
|
113
|
+
See [operations](operations.md), [security and tenancy](security-and-tenancy.md),
|
|
114
|
+
[the support matrix](support-matrix.md) and [limitations](limitations.md)
|
|
115
|
+
before deployment.
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# Architecture and internals
|
|
2
|
+
|
|
3
|
+
```mermaid
|
|
4
|
+
flowchart LR
|
|
5
|
+
C[Typed client / handle] --> D[Durable Task Scheduler]
|
|
6
|
+
D --> G[async generator turn stepper]
|
|
7
|
+
G --> M[model_step activity: one native AI SDK turn]
|
|
8
|
+
G --> A[approval event / timer race]
|
|
9
|
+
A --> T[ordered whenAll tool activities or child orchestrations]
|
|
10
|
+
T --> G
|
|
11
|
+
M --> H[HistoryStore snapshots or inline JSON]
|
|
12
|
+
T --> H
|
|
13
|
+
M --> S[live UI chunk transport]
|
|
14
|
+
G --> B[bounded 7500-byte customStatus]
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`src/agent.ts` owns registration, model/tool activities and the deterministic
|
|
18
|
+
generator. AI SDK generateText/streamText run **only in activities**, with
|
|
19
|
+
stepCountIs(1), native tool schemas and no execute/needsApproval callbacks.
|
|
20
|
+
Complete response messages preserve provider-specific metadata. A distinct
|
|
21
|
+
pending-work descriptor excludes provider-completed and SDK error results.
|
|
22
|
+
Validated/transformed native inputs are not parsed again. `src/steps.ts` records
|
|
23
|
+
explicit StepResult getters as JSON DTOs with usage, dates and media. Worker
|
|
24
|
+
prepareStep/stopWhen/hooks see complete persisted native steps across generations.
|
|
25
|
+
Prepared experimental_context is lossless-JSON validated and retained both on
|
|
26
|
+
step DTOs and RunState. Every tool mode and approval sees the effective context.
|
|
27
|
+
An outer stop always finalizes output before returning or invoking final hooks;
|
|
28
|
+
structured-output failures retain the bounded correction path.
|
|
29
|
+
The generator receives unresolved client calls and gates every approval before scheduling
|
|
30
|
+
any effects, so an upgrade cannot abandon a half-dispatched batch.
|
|
31
|
+
|
|
32
|
+
Tools are created in index order and awaited via native whenAll. Results occupy
|
|
33
|
+
their original slots even if workers finish out of order. Chunking bounds
|
|
34
|
+
outstanding activity count. Pure inline helpers rerun on replay; durable tools
|
|
35
|
+
replay recorded TaskCompleted results. RetryPolicy retries only the failed task.
|
|
36
|
+
|
|
37
|
+
`src/approvals.ts` races approval, upgrade and timer Tasks. The winning event
|
|
38
|
+
cancels the losing timer. Losing event waiters are removed by identity from
|
|
39
|
+
the SDK `_pendingEvents` object or Map. Version/generation/step/invocation tokens
|
|
40
|
+
bind decisions to a gate rather than only a reusable toolCallId. The adapter fails if the pinned contract
|
|
41
|
+
changes; it never optional-chains into a silent no-op.
|
|
42
|
+
|
|
43
|
+
`src/history.ts` stores immutable, content-addressed message snapshots and CAS
|
|
44
|
+
thread heads. Snapshots include both messages and encoded steps. File publication
|
|
45
|
+
uses a completed sibling temp file plus hard link (snapshot) or locked rename
|
|
46
|
+
(head). Init, append and commit are separate activities. File/SQLite I/O
|
|
47
|
+
never runs during orchestration replay. Pointer inputs/results retain compact
|
|
48
|
+
references; the full transcript exists off the DTS wire. Inline mode needs no
|
|
49
|
+
external store but repeatedly sends growing arrays.
|
|
50
|
+
|
|
51
|
+
Limits roll complete owned agent/session workflows using continueAsNew(...,
|
|
52
|
+
true). An instance ID stays the same; its execution ID changes. Native child
|
|
53
|
+
IDs derive from the generation's execution ID and sequence, avoiding deeply
|
|
54
|
+
nested parent-name growth. Migration resumes a saved pending turn, preserving
|
|
55
|
+
completed work and requiring a new decision for changed effects.
|
|
56
|
+
The entire active version's configuration and store is selected at every worker
|
|
57
|
+
boundary; registration retains the union of old/new activity and child names.
|
|
58
|
+
Preflight traverses the complete retained graph and rejects name/version
|
|
59
|
+
conflicts before touching the worker. Canonical per-name dispatch tables route
|
|
60
|
+
activities/orchestrators by recorded version, coalescing old/new child objects
|
|
61
|
+
without renaming already-scheduled work. Child descriptors build the child's
|
|
62
|
+
own version-selected state and record explicitly bound/mapped dependency input.
|
|
63
|
+
Migration functions and target-version availability are canonical per worker
|
|
64
|
+
too. Old execution closures remain unchanged but consult that registry at the
|
|
65
|
+
upgrade gate; the continued generation dispatches to its target handler. All
|
|
66
|
+
retained declarations are preflighted for conflicting function identities,
|
|
67
|
+
avoiding first-registration-wins migration behavior.
|
|
68
|
+
Composition allocates a replay-safe invocation ID for unique effect keys.
|
|
69
|
+
Session turns are queued with independent IDs and bounded completion tracking;
|
|
70
|
+
terminal model turns count toward rollover without resetting global steps.
|
|
71
|
+
|
|
72
|
+
`src/testing/index.ts` uses SDK InMemoryOrchestrationBackend with actual
|
|
73
|
+
OrchestrationExecutor and ActivityExecutor instances, actual Registry lookup,
|
|
74
|
+
and protobuf HistoryEvent logs. It adds concurrent activity draining,
|
|
75
|
+
stepNext controls, execution counters and archived generations for measurement.
|
|
76
|
+
It is not a simplified agent loop pretending to be DTS.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# ADR 0001: dual-surface native authoring
|
|
2
|
+
Status: Accepted, 2026-10-19.
|
|
3
|
+
|
|
4
|
+
Provide a typed DurableAgent registration/client facade and composable async
|
|
5
|
+
generator primitives over the same stepper. Preserve native AI SDK tools,
|
|
6
|
+
schemas, middleware and providers. Reject unsupported opaque configuration
|
|
7
|
+
rather than guessing. This matches Python's two surfaces without pretending
|
|
8
|
+
JavaScript can replace Python's asyncio trampoline.
|
|
9
|
+
|
|
10
|
+
All construction/attachment/extraction paths enforce dependency-branded tool
|
|
11
|
+
compatibility with the worker factory. Child tools with required dependency
|
|
12
|
+
input require a serializable binding or deterministic mapping at construction.
|
|
13
|
+
Ordinary native call settings are retained; retry and cancellation remain
|
|
14
|
+
adapter-owned rather than silently accepting incompatible native controls.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# ADR 0002: deterministic Option A
|
|
2
|
+
Status: Accepted, 2026-10-19.
|
|
3
|
+
|
|
4
|
+
Yield real DTS Tasks from async function*; run one AI SDK turn in a named model
|
|
5
|
+
activity with schema-only, execute-less tools and stepCountIs(1). AI SDK 6 does
|
|
6
|
+
not use the research's older maxSteps option. Parallel tools use whenAll with
|
|
7
|
+
bounded chunks. Preserve response messages verbatim. No V8 microtask trampoline
|
|
8
|
+
or exception suspension. Test with the real pinned executor.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# ADR 0003: selectable tools, dependencies and MCP
|
|
2
|
+
Status: Accepted, 2026-10-19.
|
|
3
|
+
|
|
4
|
+
Native tools default to durable activities. Pure synchronous helpers opt into
|
|
5
|
+
zero-RPC inline replay with throwing dependency guards; activity-inline has one
|
|
6
|
+
attempt. Worker depsFactory never runs during replay. Use deterministic
|
|
7
|
+
idempotency keys and native RetryPolicy; timeouts are cooperative cancellation.
|
|
8
|
+
Pool MCP connections on workers and record discovery separately from calls.
|
|
9
|
+
Dispose pools explicitly at shutdown, not from the deterministic generator.
|
|
10
|
+
|
|
11
|
+
Native inputs have already been transformed; only raw approval overrides are
|
|
12
|
+
validated again, once on the worker. Dependency-branded tools retain factory
|
|
13
|
+
compatibility and required serializable inputs through public generics. Setup,
|
|
14
|
+
hydration and execute share timeout/error ownership and exactly-once resource
|
|
15
|
+
cleanup (explicit callback, asyncDispose or dispose). Effect keys include agent
|
|
16
|
+
and deterministic invocation scope plus monotonic global step and call identity.
|
|
17
|
+
MCP discovery is single-flight and retryable, namespace routing is exact and
|
|
18
|
+
collision-checked, and native converters retain image/content outputs.
|
|
19
|
+
Contradictory local/durable policies raise exported PolicyConflictError.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# ADR 0004: approvals and bounded status
|
|
2
|
+
Status: Accepted, 2026-10-19.
|
|
3
|
+
|
|
4
|
+
Scoped external events race durable timers. Cancel losing timers and prune
|
|
5
|
+
losing pending-event tasks using an explicit SDK 0.4 compatibility adapter.
|
|
6
|
+
Support boolean/predicate approval and deferred tools without execute.
|
|
7
|
+
Bound every customStatus to 7,500 UTF-8 bytes using field clamps, event eviction,
|
|
8
|
+
preview shrinking and an emergency floor. Clip by code point, never split a
|
|
9
|
+
surrogate pair. Expose pending-call identity even when argument previews shrink.
|
|
10
|
+
Status is a bounded window; clients must detect cursor gaps.
|
|
11
|
+
|
|
12
|
+
Evaluate boolean/async approval predicates on workers with native pre-turn
|
|
13
|
+
messages, persisting decisions for replay. Every event/payload is scoped by a
|
|
14
|
+
token bound to agent, invocation, version, generation, step and call ID. Reject
|
|
15
|
+
stale UI tokens and discard mismatched carryover events. Migration requires a
|
|
16
|
+
fresh gate even when an old deferred tool becomes executable. The waiter
|
|
17
|
+
adapter supports Map and record storage and removes only the exact task.
|
|
18
|
+
Retain at most 32 session completion IDs alongside the latest completed ID.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# ADR 0005: state plane, sessions, streaming and versioning
|
|
2
|
+
Status: Accepted, 2026-10-19.
|
|
3
|
+
|
|
4
|
+
Inline messages need no extra infrastructure. Optional immutable HistoryStore
|
|
5
|
+
references keep DTS payloads constant-sized while client/worker hydrate content.
|
|
6
|
+
Ship memory, file and node:sqlite stores with conflict detection. Roll generations
|
|
7
|
+
via continueAsNew(state, true) and preserve unread events. Subagent tools create
|
|
8
|
+
real child orchestrations. Live UI chunks are worker-published; checkpoint
|
|
9
|
+
cursors reconnect independently. Retain previous version handlers and allow
|
|
10
|
+
explicit pure migrations only at a parked upgrade gate.
|
|
11
|
+
|
|
12
|
+
Snapshots persist native encoded step DTOs alongside messages (`getSteps`),
|
|
13
|
+
including explicit serialization of SDK prototype getters. File snapshots and
|
|
14
|
+
heads publish atomically. Versioned references resolve the correct old store;
|
|
15
|
+
draining selects the entire old contract and registers the union of handlers.
|
|
16
|
+
Queue each runSession invocation with its own turnId, count terminal model
|
|
17
|
+
steps toward generation limits and never reset the global step at rollover.
|
|
18
|
+
Benchmark the independent storage/rollover controls as a complete 2x2 matrix
|
|
19
|
+
with full transcript equality and external storage measurements.
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
# ADR 0006: MAF entity sessions, orchestration turn steppers, and a hybrid model
|
|
2
|
+
|
|
3
|
+
**Status:** Accepted (`2026-10-20`)
|
|
4
|
+
|
|
5
|
+
**Recorded at:** `2026-10-20T23:32:16.840+03:00`
|
|
6
|
+
|
|
7
|
+
**Owner:** maintainers
|
|
8
|
+
|
|
9
|
+
**Scope:** `ai-sdk-azure-durable-task`; documentation and architectural direction, not a runtime migration.
|
|
10
|
+
|
|
11
|
+
## Context
|
|
12
|
+
|
|
13
|
+
Vercel AI SDK's `ToolLoopAgent` / `generateText` and Microsoft Agent Framework's
|
|
14
|
+
`ChatClientAgent` / `FunctionInvokingChatClient` are structurally twin agent loops:
|
|
15
|
+
send conversation and tool schemas to a model, receive text or tool calls, invoke
|
|
16
|
+
tools, append their results, and repeat until a stop condition. Their SDK APIs,
|
|
17
|
+
middleware, and message formats differ; the control-flow shape does not.
|
|
18
|
+
|
|
19
|
+
The durability boundary is a separate choice from the agent loop:
|
|
20
|
+
|
|
21
|
+
- **MAF durable agent:** `Microsoft.Agents.AI.DurableTask` puts a session in
|
|
22
|
+
`AgentEntity`, and executes an ordinary agent turn inside one entity operation.
|
|
23
|
+
- **This adapter:** a `TOrchestrator` drives a **Step-Level Orchestration Turn
|
|
24
|
+
Stepper**, as accepted in [ADR 0002](0002-generator-turn-stepper.md).
|
|
25
|
+
One model step runs in an activity with execute-less tool schemas and
|
|
26
|
+
`stepCountIs(1)`; durable tools run in their own activities or child orchestrations.
|
|
27
|
+
The orchestrator, not a process-local AI SDK loop, owns the next step.
|
|
28
|
+
|
|
29
|
+
See [model-step implementation](../../src/agent.ts#L175-L198) and
|
|
30
|
+
[stepper implementation](../../src/agent.ts#L641-L823). Explicit local tool
|
|
31
|
+
execution policies are opt-outs from the durable-tool boundary, not evidence of
|
|
32
|
+
per-tool durability.
|
|
33
|
+
|
|
34
|
+
**Correction to the initial hypothesis:** the installed
|
|
35
|
+
`@microsoft/durabletask-js@0.4.0` does have public entity APIs and executable entity
|
|
36
|
+
runtime support. The empirical findings below supersede the proposed claim that
|
|
37
|
+
entities exist only in protobuf definitions. We retain the stepper because of its
|
|
38
|
+
execution semantics, not because of a nonexistent SDK API gap.
|
|
39
|
+
|
|
40
|
+
## Empirical Verification of `@microsoft/durabletask-js@0.4.0` Entity Support
|
|
41
|
+
|
|
42
|
+
### Installed artifact and exact evidence
|
|
43
|
+
|
|
44
|
+
Inspection root: the installed `node_modules/@microsoft/durabletask-js` package
|
|
45
|
+
(v0.4.0).
|
|
46
|
+
Paths below are relative to that root; line numbers refer to the inspected files.
|
|
47
|
+
`package.json:2-6` identifies version `0.4.0`, runtime entry `dist/index.js`, and
|
|
48
|
+
types entry `dist/index.d.ts`.
|
|
49
|
+
|
|
50
|
+
| Question | Finding | Exact installed file evidence |
|
|
51
|
+
|---|---|---|
|
|
52
|
+
| Public entity identity and base class? | **Yes.** `EntityInstanceId`, `TaskEntity`, and `TaskEntityShim` are public exports, not merely generated messages. | `dist\index.d.ts:27-37`; runtime exports in `dist\index.js:70-85`; `TaskEntity<TState>` in `dist\entities\task-entity.d.ts:46-71`. |
|
|
53
|
+
| Client signal/read APIs? | **Yes.** `TaskHubGrpcClient.signalEntity(...)` and `getEntity<T>(...)` have public declarations and actual gRPC implementations. | `dist\client\client.d.ts:301-322`; `dist\client\client.js:740-797`. |
|
|
54
|
+
| Worker registration and execution? | **Yes.** `TaskHubGrpcWorker.addEntity`, `addNamedEntity`, and `processEntityBatchRequest` are public. The worker resolves the entity factory and executes a `TaskEntityShim`. | `dist\worker\task-hub-grpc-worker.d.ts:113-164`; runtime registration at `dist\worker\task-hub-grpc-worker.js:217-237`, batch entry at `:289-298`, and factory/shim execution at `:768-822`. |
|
|
55
|
+
| Where does request/response `callEntity` live? | **On `ctx.entities`**, not directly on the external client or worker. Its return value is a durable `Task<TResult>`. Absence of `TaskHubGrpcClient.callEntity` is not absence of entity calls. | `dist\task\context\orchestration-context.d.ts:48-56`; `dist\entities\orchestration-entity-feature.d.ts:53-71`; runtime feature getter in `dist\worker\runtime-orchestration-context.js:101-103` and `callEntity` / `signalEntity` implementations at `:663-746`. |
|
|
56
|
+
| Are protobuf entities present? | **Yes, alongside the high-level runtime.** They are the wire contracts, not the only implementation. | `dist\proto\orchestrator_service_pb.d.ts:1569` (`SendEntityMessageAction`), `:3100` (`EntityBatchRequest`), and `:3136` (`EntityBatchResult`). |
|
|
57
|
+
| Is entity state actually executed and serialized? | **Yes.** The shim hydrates state, executes each operation, serializes results/state, and commits or rolls back operation state/actions. | `dist\worker\entity-executor.js:270-345`. |
|
|
58
|
+
| Can an entity signal itself and start a turn orchestration? | **The SDK exposes both operations.** Backend behavior still needs integration qualification. | `dist\entities\task-entity-context.d.ts:26-57` (`signalEntity`, with scheduled-delivery options, and `scheduleNewOrchestration`). |
|
|
59
|
+
|
|
60
|
+
Fingerprints (SHA-256) of the installed artifact:
|
|
61
|
+
|
|
62
|
+
| File | SHA-256 |
|
|
63
|
+
|---|---|
|
|
64
|
+
| `package.json` | `6B85CCF80F3F8DF5ED5B7167FAAF7DBF986C714FF191EBB60B6F27B9E8B0C31E` |
|
|
65
|
+
| `dist\index.d.ts` | `E9915A9D023A2B402FD24B5FB9D539AC7C00ADE860396AC111833F692524060C` |
|
|
66
|
+
| `dist\worker\task-hub-grpc-worker.js` | `95795B8D566E3E3E90DFC9446341DDEABDF0C15423A57142484B80A7F534598A` |
|
|
67
|
+
|
|
68
|
+
### Executable verification
|
|
69
|
+
|
|
70
|
+
A backend-free probe imported the package's public exports, checked client/worker
|
|
71
|
+
methods, registered a subclass of `TaskEntity`, and passed two serialized entity
|
|
72
|
+
batches through the public `TaskHubGrpcWorker.processEntityBatchRequest` entry
|
|
73
|
+
point. The second batch hydrated the first batch's serialized state.
|
|
74
|
+
|
|
75
|
+
**Result: passed.** Entity state advanced `0 -> 2 -> 5`; the second operation
|
|
76
|
+
returned `5`; both batches reported success. Direct external-client `callEntity`
|
|
77
|
+
was `undefined`, as expected. No worker listener or gRPC channel was started.
|
|
78
|
+
|
|
79
|
+
Reproduce from the repository root in PowerShell:
|
|
80
|
+
|
|
81
|
+
```powershell
|
|
82
|
+
@'
|
|
83
|
+
const assert = require("node:assert/strict");
|
|
84
|
+
const sdk = require("@microsoft/durabletask-js");
|
|
85
|
+
const pb = require("@microsoft/durabletask-js/dist/proto/orchestrator_service_pb");
|
|
86
|
+
const { StringValue } = require("google-protobuf/google/protobuf/wrappers_pb");
|
|
87
|
+
assert.equal(require("@microsoft/durabletask-js/package.json").version, "0.4.0");
|
|
88
|
+
for (const name of ["TaskEntity", "EntityInstanceId", "TaskEntityShim"])
|
|
89
|
+
assert.equal(typeof sdk[name], "function");
|
|
90
|
+
for (const name of ["signalEntity", "getEntity"])
|
|
91
|
+
assert.equal(typeof sdk.TaskHubGrpcClient.prototype[name], "function");
|
|
92
|
+
for (const name of ["addEntity", "addNamedEntity", "processEntityBatchRequest"])
|
|
93
|
+
assert.equal(typeof sdk.TaskHubGrpcWorker.prototype[name], "function");
|
|
94
|
+
assert.equal(typeof sdk.TaskHubGrpcClient.prototype.callEntity, "undefined");
|
|
95
|
+
class Counter extends sdk.TaskEntity {
|
|
96
|
+
initializeState() { return 0; }
|
|
97
|
+
add(value) { this.state += value; return this.state; }
|
|
98
|
+
}
|
|
99
|
+
(async () => {
|
|
100
|
+
const worker = new sdk.TaskHubGrpcWorker({ logger: new sdk.NoOpLogger() });
|
|
101
|
+
worker.addNamedEntity("adr0006counter", () => new Counter());
|
|
102
|
+
const id = new sdk.EntityInstanceId("adr0006counter", "verification");
|
|
103
|
+
async function batch(value, previousState) {
|
|
104
|
+
const request = new pb.EntityBatchRequest();
|
|
105
|
+
request.setInstanceid(id.toString());
|
|
106
|
+
if (previousState) request.setEntitystate(previousState);
|
|
107
|
+
const operation = new pb.OperationRequest();
|
|
108
|
+
operation.setOperation("add");
|
|
109
|
+
operation.setRequestid(`probe-${value}`);
|
|
110
|
+
operation.setInput(new StringValue().setValue(JSON.stringify(value)));
|
|
111
|
+
request.setOperationsList([operation]);
|
|
112
|
+
const result = pb.EntityBatchResult.deserializeBinary(
|
|
113
|
+
await worker.processEntityBatchRequest(request.serializeBinary()));
|
|
114
|
+
assert.equal(result.hasFailuredetails(), false);
|
|
115
|
+
assert.equal(result.getResultsList().length, 1);
|
|
116
|
+
assert.equal(result.getResultsList()[0].hasSuccess(), true);
|
|
117
|
+
return result;
|
|
118
|
+
}
|
|
119
|
+
const first = await batch(2);
|
|
120
|
+
assert.equal(JSON.parse(first.getEntitystate().getValue()), 2);
|
|
121
|
+
const second = await batch(3, first.getEntitystate());
|
|
122
|
+
assert.equal(JSON.parse(second.getEntitystate().getValue()), 5);
|
|
123
|
+
assert.equal(
|
|
124
|
+
JSON.parse(second.getResultsList()[0].getSuccess().getResult().getValue()), 5);
|
|
125
|
+
console.log("PASS: public entity runtime, serialized batch states [2, 5]");
|
|
126
|
+
})().catch(error => { console.error(error); process.exitCode = 1; });
|
|
127
|
+
'@ | node -
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
**Evidence boundary:** this proves the installed SDK surface and local entity
|
|
131
|
+
execution, not successful entity RPCs against a live DTS task hub, scheduled TTL
|
|
132
|
+
delivery, distributed crash recovery, or production qualification of a hybrid.
|
|
133
|
+
It does not establish the contents of every registry artifact bearing this version.
|
|
134
|
+
|
|
135
|
+
## How MAF's two durability layers work
|
|
136
|
+
|
|
137
|
+
The comparison uses the local `agent-framework-durable-extension` checkout at
|
|
138
|
+
commit `63e87a43396e001e1cfa49f0df657de2f6e80b95`; the cited source files match
|
|
139
|
+
that commit. Secondary write-ups were used only as a navigation aid; the
|
|
140
|
+
implementation is authoritative.
|
|
141
|
+
|
|
142
|
+
### Agent layer: whole-turn entity cut
|
|
143
|
+
|
|
144
|
+
1. **Session identity and storage.** `AgentSessionId` maps an agent name to
|
|
145
|
+
`dafx-{agentName}` plus a session key / `EntityInstanceId`
|
|
146
|
+
([MAF session identity, lines 15-44][maf-session]).
|
|
147
|
+
`AgentEntity : TaskEntity<DurableAgentState>` holds `ConversationHistory`.
|
|
148
|
+
`Run` appends the request, invokes the wrapped agent, then appends the
|
|
149
|
+
response tagged with the request's `CorrelationId`
|
|
150
|
+
([AgentEntity, lines 13-107][maf-entity]).
|
|
151
|
+
2. **External turn invocation.** `DefaultDurableAgentClient.RunAgentAsync` calls
|
|
152
|
+
`SignalEntityAsync(..., nameof(AgentEntity.Run), request)` and returns a handle
|
|
153
|
+
([lines 14-29][maf-client]). `AgentRunHandle` polls
|
|
154
|
+
`GetEntityAsync<DurableAgentState>` for the matching response `CorrelationId`,
|
|
155
|
+
with exponential backoff starting at **50 ms** and capped at **3 seconds**
|
|
156
|
+
([lines 47-80][maf-handle]). Its comment says one second; the implementation's
|
|
157
|
+
three-second cap wins. An orchestrator caller instead uses
|
|
158
|
+
`DurableAIAgent` -> `ctx.Entities.CallEntityAsync<AgentResponse>`
|
|
159
|
+
([lines 129-143][maf-agent]), not wall-clock client polling.
|
|
160
|
+
3. **The real checkpoint boundary.** `AgentEntity.Run` awaits the wrapped
|
|
161
|
+
`AIAgent.RunStreamingAsync` and response aggregation **inside one entity
|
|
162
|
+
operation**. `EntityAgentWrapper` delegates into the registered agent's
|
|
163
|
+
chat-client pipeline ([lines 40-54, 74-127][maf-wrapper]). For the usual
|
|
164
|
+
`ChatClientAgent` / `FunctionInvokingChatClient` configuration, this includes
|
|
165
|
+
the entire model/tool loop. Those tool invocations are **not separate Durable
|
|
166
|
+
Task activities** merely because the outer session is durable.
|
|
167
|
+
4. **Consequences.** An inline slow tool or an inline HITL wait occupies the
|
|
168
|
+
session's serialized entity operation. A worker crash before the operation
|
|
169
|
+
commits can cause the **entire uncommitted turn to execute again**: earlier
|
|
170
|
+
model calls and external effects inside that turn have no per-tool Durable
|
|
171
|
+
Task checkpoint. This is operation re-execution, not deterministic replay of
|
|
172
|
+
recorded model results. Committed turns survive; external side effects still
|
|
173
|
+
require idempotency. A tool can request a new orchestration through
|
|
174
|
+
`DurableAgentContext.ScheduleNewOrchestration`, but scheduling is deferred to
|
|
175
|
+
the entity operation's state/actions commit; it does not checkpoint the
|
|
176
|
+
remainder of an inline turn ([lines 80-98][maf-context]).
|
|
177
|
+
5. **TTL.** The default is **14 days**, configurable or disabled with `null`
|
|
178
|
+
([options, lines 24-30][maf-options]). After successful turn execution,
|
|
179
|
+
`Run` updates `ExpirationTimeUtc` and schedules the first deletion check.
|
|
180
|
+
`ScheduleDeletionCheck` sends a delayed self-signal to
|
|
181
|
+
`CheckAndDeleteIfExpired`; subsequent turns extend expiration, and the
|
|
182
|
+
existing check either deletes state or reschedules itself
|
|
183
|
+
([AgentEntity, lines 121-221][maf-entity]). This is idle-expiration checking,
|
|
184
|
+
not a guarantee of deletion at the exact expiration instant.
|
|
185
|
+
|
|
186
|
+
### Workflow layer: durable supersteps are a different cut
|
|
187
|
+
|
|
188
|
+
MAF is **not entity-only**. `DurableWorkflowRunner` is an orchestration that
|
|
189
|
+
dispatches ready executors concurrently and routes their results in supersteps
|
|
190
|
+
([runner, lines 175-249][maf-runner]). `DurableExecutorDispatcher` selects:
|
|
191
|
+
|
|
192
|
+
| Executor | Durable boundary |
|
|
193
|
+
|---|---|
|
|
194
|
+
| Agentic executor | `context.GetAgent(...)` -> `DurableAIAgent.RunAsync` -> `ctx.Entities.CallEntityAsync`; the inner agent turn remains one entity operation. |
|
|
195
|
+
| Activity executor | `CallActivityAsync`, independently checkpointed. |
|
|
196
|
+
| Request port | `WaitForExternalEvent<string>`; an orchestrator wait, not an entity blocked on a human. No built-in timeout in this path; a timer race must be added for a deadline. |
|
|
197
|
+
| Sub-workflow | `CallSubOrchestratorAsync`, with independent orchestration history. |
|
|
198
|
+
|
|
199
|
+
See [dispatcher, lines 40-88, 103-124, 160-175, 193-206][maf-dispatcher] and
|
|
200
|
+
[DurableAIAgent, lines 129-143][maf-agent]. The source method for request ports
|
|
201
|
+
is named `WaitForExternalEvent<T>`, not `WaitForExternalEventAsync<T>`.
|
|
202
|
+
MAF already demonstrates that entity-backed conversational memory and
|
|
203
|
+
orchestration-level workflow durability are complementary.
|
|
204
|
+
|
|
205
|
+
## Architectural Comparison Table
|
|
206
|
+
|
|
207
|
+
| Dimension | MAF `AgentEntity` — Whole-Turn Entity Cut | `ai-sdk-azure-durable-task` `TOrchestrator` — Step-Level Activity Cut | Hybrid Entity-Session + Stepper-Turn Model — proposed |
|
|
208
|
+
|---|---|---|---|
|
|
209
|
+
| Crash recovery granularity | Committed entity state survives; an interrupted, uncommitted agent turn can rerun as a whole. | Recorded model/tool activity completions are replayed; uncommitted activities can rerun. No exactly-once external-effect guarantee. | Same step-level recovery for delegated turns; whole-operation recovery for deliberately inline single-shot turns. |
|
|
210
|
+
| Tool retry isolation | Inner chat-client retries are process-local; no independent Durable Task retry/checkpoint for each ordinary agent tool. | Durable tools have isolated retry policies, effect keys, and recorded results; explicit local execution modes opt out. | Tools requiring isolation use the stepper; inline mode must not silently accept side-effecting tools. |
|
|
211
|
+
| Long-running HITL approvals | Waiting inside `Run` blocks that entity. MAF workflow request ports avoid this by waiting in an orchestration. | `whenAny` races an approval/deferred event, upgrade event, and durable timer; no worker compute is held while parked. | Child turn orchestration owns approval waits; session entity commits admission and returns immediately, remaining available for control operations. |
|
|
212
|
+
| Multi-turn thread storage & TTL | Entity owns `ConversationHistory`; default 14-day sliding TTL uses delayed self-signals. | `runSession`, `continueAsNew(state, true)`, optional immutable `HistoryStore` snapshots and CAS thread heads; automatic TTL cleanup is not currently provided. | Entity owns thread head, request queue, receipts, and TTL; optional external history stores hold large immutable content. |
|
|
213
|
+
| Single-turn latency / RPC overhead | Fewer durability boundaries inside the turn; external signal/poll adds RPCs and up to the polling interval in observation delay. Not a measured latency claim. | Model/tool/commit activities incur more scheduler transitions; parallel tool batches can offset wall-clock cost. | Bounded pure chat can run inline; delegated turns pay admission, orchestration, and completion handoff overhead. Benchmark before choosing thresholds. |
|
|
214
|
+
| Concurrency / head-of-line blocking | Operations serialize per session entity; a long tool holds that session, not every entity in the hub. | A session intentionally serializes its turns, but durable waits release workers; independent sessions and bounded `whenAll` tool batches run concurrently. | One active conversational writer per session; short entity operations service admission/control while a child waits. Later turns still queue to preserve conversation order. |
|
|
215
|
+
| Sub-agent composition | An agent can delegate in-process or schedule workflow work; ordinary inner tool delegation is not automatically a separately checkpointed child. MAF workflows explicitly compose entity agents and sub-orchestrations. | Sub-agent tools create real child orchestrations with their own histories, retries, and summarization boundary. | Child steppers compose sub-agents; entity state tracks correlation and authoritative completion rather than awaiting a child under the entity lock. |
|
|
216
|
+
| SDK availability: .NET / Python / JS `0.4.0` | MAF extension implements entity agents in .NET and Python; it is not a JS extension package. | This adapter is TypeScript on JS `0.4.0` orchestration/activity APIs. **JS `0.4.0` also exposes high-level entities**, as verified above. | Native primitives exist in the inspected .NET, Python, and JS surfaces; this adapter's entity-session integration is **not implemented or backend-qualified**. Future work is integration/qualification, not waiting for public JS `TaskEntity` APIs. |
|
|
217
|
+
|
|
218
|
+
Python availability is supported by MAF's [worker entity registration][maf-py-worker]
|
|
219
|
+
(`_worker.py:145-146`) and [signal/read/call paths][maf-py-executors]
|
|
220
|
+
(`_executors.py:300,419,512-520`). This does not assert exact .NET/Python feature parity.
|
|
221
|
+
|
|
222
|
+
## Decision
|
|
223
|
+
|
|
224
|
+
### 1. Keep the Step-Level Orchestration Turn Stepper as the primary engine
|
|
225
|
+
|
|
226
|
+
Retain [ADR 0002](0002-generator-turn-stepper.md) and the current public adapter
|
|
227
|
+
contract. Vercel AI SDK applications need isolated durable tool retries, bounded
|
|
228
|
+
parallel `whenAll` batches, durable sub-agents, and zero-compute HITL `whenAny`
|
|
229
|
+
gates. Moving an unrestricted `generateText` / `ToolLoopAgent` execution into one
|
|
230
|
+
entity operation would weaken those guarantees.
|
|
231
|
+
|
|
232
|
+
**Do not use “JS `0.4.0` lacks a high-level `TaskEntity` worker/client runtime” as
|
|
233
|
+
a justification: that assertion is false for the installed package.** Entity
|
|
234
|
+
availability does not determine the correct checkpoint granularity.
|
|
235
|
+
|
|
236
|
+
### 2. Adopt MAF's strongest session patterns in today's architecture
|
|
237
|
+
|
|
238
|
+
Use the mechanisms already present rather than replacing the execution engine:
|
|
239
|
+
|
|
240
|
+
- `runSession` assigns each submission a unique `turnId`, queues it through the
|
|
241
|
+
session orchestration, and returns a correlation-bound handle. `send` and
|
|
242
|
+
`waitForTurn` address the submitted turn, not just “the latest response”
|
|
243
|
+
([client](../../src/client.ts#L153-L167),
|
|
244
|
+
[session admission](../../src/client.ts#L310-L341)).
|
|
245
|
+
- Keep session state and unread events across
|
|
246
|
+
`continueAsNew(state, true)`; do not reset global step identity at rollover
|
|
247
|
+
([engine](../../src/agent.ts#L671-L685)).
|
|
248
|
+
- Keep optional `HistoryStore` immutable snapshots and compare-and-swap
|
|
249
|
+
`threadId` heads. Snapshot contents include native step DTOs, not only text
|
|
250
|
+
messages ([store contract](../../src/history-types.ts#L7-L14),
|
|
251
|
+
[ADR 0005](0005-state-streaming-subagents-versioning.md)).
|
|
252
|
+
- Preserve correlation-bound completion receipts. Current custom status keeps a
|
|
253
|
+
**bounded 32-turn** completion window; it is not an unlimited deduplication or
|
|
254
|
+
receipt database. A timeout outside that window is not proof a turn never ran.
|
|
255
|
+
- Adopt optional idle TTL cleanup as a **future, opt-in policy**, not an existing
|
|
256
|
+
capability claim. A durable timer/control orchestration or store sweeper can
|
|
257
|
+
mark idle sessions for expiry. Deletion must distinguish orchestration history,
|
|
258
|
+
receipts, thread heads, and referenced snapshots, and must not purge active
|
|
259
|
+
turns or shared/reachable history.
|
|
260
|
+
|
|
261
|
+
### 3. Define Phase 2: Entity-Backed Session + Orchestration Turn
|
|
262
|
+
|
|
263
|
+
Introduce a future `AgentSessionEntity` with a `dafx-`-style, namespaced identity:
|
|
264
|
+
|
|
265
|
+
```text
|
|
266
|
+
client -- Submit(turnId, prompt, expectedHead) --> AgentSessionEntity
|
|
267
|
+
<-- accepted / existing receipt ---------|
|
|
268
|
+
| commit admission + start action
|
|
269
|
+
v
|
|
270
|
+
turn-stepper orchestration
|
|
271
|
+
model -> tools -> approval -> ...
|
|
272
|
+
|
|
|
273
|
+
Complete(turnId, epoch, newHistoryRef, outcome)
|
|
274
|
+
|
|
|
275
|
+
v
|
|
276
|
+
client <-- correlated receipt / thread head -- AgentSessionEntity
|
|
277
|
+
|
|
|
278
|
+
delayed TTL self-signal
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
- **State owner:** the entity owns the authoritative conversation head,
|
|
282
|
+
expiration, FIFO request/correlation queue, active turn identity/epoch, and
|
|
283
|
+
retained receipts. Large conversation/step snapshots may remain in
|
|
284
|
+
`HistoryStore`; do not create competing entity and child writers for the head.
|
|
285
|
+
- **Admission and execution:** enqueue a request, durably record its identity,
|
|
286
|
+
schedule the turn orchestration through the entity's scheduling action, and
|
|
287
|
+
**return from the entity operation**. A scheduled turn is a logical child of
|
|
288
|
+
the session; an entity starting an orchestration is not itself
|
|
289
|
+
`CallSubOrchestrator` parentage. The turn may use true sub-orchestrations below it.
|
|
290
|
+
- **Completion protocol:** the turn signals a short entity completion operation.
|
|
291
|
+
That operation validates `turnId`, epoch, expected history version, and active
|
|
292
|
+
child identity; publishes the new head/receipt once; and admits the next turn.
|
|
293
|
+
Duplicate submissions/completions return existing outcomes; stale completions
|
|
294
|
+
cannot overwrite newer state. Bound queue and receipt retention explicitly.
|
|
295
|
+
Admission/child-start and completion/head-publication require backend
|
|
296
|
+
crash/retry tests, not assumptions about cross-store atomicity.
|
|
297
|
+
- **No entity-held wait:** do not await child completion or human approval
|
|
298
|
+
inside the entity operation. The child parks with durable events/timers;
|
|
299
|
+
request/cancel/status operations can still reach the entity. Conversational
|
|
300
|
+
turns remain ordered even though entity control operations stay responsive.
|
|
301
|
+
- **Low-latency inline path:** allow only an explicitly selected, bounded,
|
|
302
|
+
pure single-shot chat turn with tool execution disabled and no approval wait.
|
|
303
|
+
It uses MAF's whole-turn cut deliberately. Any turn needing tools, fine-grained
|
|
304
|
+
retries, sub-agent durability, or HITL uses the stepper. Accept whole-turn
|
|
305
|
+
re-execution and at-least-once model billing for the inline path.
|
|
306
|
+
- **TTL:** use a delayed self-signal, extend expiration on activity, and recheck
|
|
307
|
+
current state when the timer fires. Do not delete sessions with active/queued
|
|
308
|
+
work. Use epochs/tombstones or equivalent fencing to reject late completions;
|
|
309
|
+
collect external history only under an explicit reference/retention policy.
|
|
310
|
+
- **Availability gate:** the proposed gate “when JS lands public `TaskEntity`
|
|
311
|
+
support” is already satisfied by the inspected `0.4.0` package. Phase 2 remains
|
|
312
|
+
deferred until native entity integration, live-backend support, and failure
|
|
313
|
+
semantics are qualified. A `VirtualEntityOrchestrator` can instead emulate a
|
|
314
|
+
serialized session owner using events, timers, and `continueAsNew`; it is a
|
|
315
|
+
**design alternative, not an exported class or implemented feature in this
|
|
316
|
+
adapter**. Its event, batching, locking, and atomicity semantics must not be
|
|
317
|
+
advertised as equivalent to native entities without tests.
|
|
318
|
+
|
|
319
|
+
## Consequences and validation boundary
|
|
320
|
+
|
|
321
|
+
The default path retains its existing step-level recovery, parallel tool
|
|
322
|
+
scheduling, and parked approval behavior. MAF supplies valuable session identity,
|
|
323
|
+
correlation, and TTL patterns without requiring a whole-turn execution cut.
|
|
324
|
+
The hybrid separates state ownership from execution ownership but adds handoff,
|
|
325
|
+
deduplication, retention, and recovery complexity.
|
|
326
|
+
|
|
327
|
+
This ADR changes **no `src/` files**, dependency pins, runtime defaults, or release
|
|
328
|
+
tags. Acceptance of the design is not implementation or production readiness.
|
|
329
|
+
Phase 2 requires tests for duplicate delivery, concurrent submissions, crashes
|
|
330
|
+
before/after admission and completion commits, child failure, TTL races, stale
|
|
331
|
+
callbacks, external-store conflicts, and HITL worker restarts, plus latency/RPC
|
|
332
|
+
benchmarks for inline versus delegated turns.
|
|
333
|
+
|
|
334
|
+
The local entity probe above is the empirical SDK check. Repository regression
|
|
335
|
+
validation completed with `npm test` (including its build pretest): **passed,
|
|
336
|
+
165 tests passed and 28 skipped; 15 test files passed and 3 skipped**.
|
|
337
|
+
Environment-dependent emulator, hosted, Postgres, Redis, and related integration
|
|
338
|
+
checks were skipped; those backends were not qualified by this run. A separate
|
|
339
|
+
local-link check **passed for all 15 local targets** in the ADR index and decision
|
|
340
|
+
documents, including source line anchors and reference-style links. The probe
|
|
341
|
+
embedded in this document was also executed successfully. Neither check
|
|
342
|
+
substitutes for a live-backend entity integration or crash-recovery test.
|
|
343
|
+
|
|
344
|
+
## Source references
|
|
345
|
+
|
|
346
|
+
MAF links pin the verified checkout commit. Installed JS file paths/line numbers
|
|
347
|
+
above are local artifact evidence because `node_modules` is not tracked here.
|
|
348
|
+
|
|
349
|
+
[maf-session]: https://github.com/microsoft/agent-framework-durable-extension/blob/63e87a43396e001e1cfa49f0df657de2f6e80b95/dotnet/src/Microsoft.Agents.AI.DurableTask/AgentSessionId.cs#L15-L44
|
|
350
|
+
[maf-entity]: https://github.com/microsoft/agent-framework-durable-extension/blob/63e87a43396e001e1cfa49f0df657de2f6e80b95/dotnet/src/Microsoft.Agents.AI.DurableTask/AgentEntity.cs#L13-L221
|
|
351
|
+
[maf-client]: https://github.com/microsoft/agent-framework-durable-extension/blob/63e87a43396e001e1cfa49f0df657de2f6e80b95/dotnet/src/Microsoft.Agents.AI.DurableTask/DefaultDurableAgentClient.cs#L14-L29
|
|
352
|
+
[maf-handle]: https://github.com/microsoft/agent-framework-durable-extension/blob/63e87a43396e001e1cfa49f0df657de2f6e80b95/dotnet/src/Microsoft.Agents.AI.DurableTask/AgentRunHandle.cs#L47-L80
|
|
353
|
+
[maf-agent]: https://github.com/microsoft/agent-framework-durable-extension/blob/63e87a43396e001e1cfa49f0df657de2f6e80b95/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAIAgent.cs#L129-L143
|
|
354
|
+
[maf-wrapper]: https://github.com/microsoft/agent-framework-durable-extension/blob/63e87a43396e001e1cfa49f0df657de2f6e80b95/dotnet/src/Microsoft.Agents.AI.DurableTask/EntityAgentWrapper.cs#L40-L127
|
|
355
|
+
[maf-context]: https://github.com/microsoft/agent-framework-durable-extension/blob/63e87a43396e001e1cfa49f0df657de2f6e80b95/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAgentContext.cs#L80-L98
|
|
356
|
+
[maf-options]: https://github.com/microsoft/agent-framework-durable-extension/blob/63e87a43396e001e1cfa49f0df657de2f6e80b95/dotnet/src/Microsoft.Agents.AI.DurableTask/DurableAgentsOptions.cs#L24-L30
|
|
357
|
+
[maf-runner]: https://github.com/microsoft/agent-framework-durable-extension/blob/63e87a43396e001e1cfa49f0df657de2f6e80b95/dotnet/src/Microsoft.Agents.AI.DurableTask/Workflows/DurableWorkflowRunner.cs#L175-L249
|
|
358
|
+
[maf-dispatcher]: https://github.com/microsoft/agent-framework-durable-extension/blob/63e87a43396e001e1cfa49f0df657de2f6e80b95/dotnet/src/Microsoft.Agents.AI.DurableTask/Workflows/DurableExecutorDispatcher.cs#L40-L206
|
|
359
|
+
[maf-py-worker]: https://github.com/microsoft/agent-framework-durable-extension/blob/63e87a43396e001e1cfa49f0df657de2f6e80b95/python/packages/durabletask/agent_framework_durabletask/_worker.py#L145-L146
|
|
360
|
+
[maf-py-executors]: https://github.com/microsoft/agent-framework-durable-extension/blob/63e87a43396e001e1cfa49f0df657de2f6e80b95/python/packages/durabletask/agent_framework_durabletask/_executors.py#L300-L520
|