Universal.Operative.Sdk.Discrete
4.0.0
dotnet add package Universal.Operative.Sdk.Discrete --version 4.0.0
NuGet\Install-Package Universal.Operative.Sdk.Discrete -Version 4.0.0
<PackageReference Include="Universal.Operative.Sdk.Discrete" Version="4.0.0" />
<PackageVersion Include="Universal.Operative.Sdk.Discrete" Version="4.0.0" />
<PackageReference Include="Universal.Operative.Sdk.Discrete" />
paket add Universal.Operative.Sdk.Discrete --version 4.0.0
#r "nuget: Universal.Operative.Sdk.Discrete, 4.0.0"
#:package Universal.Operative.Sdk.Discrete@4.0.0
#addin nuget:?package=Universal.Operative.Sdk.Discrete&version=4.0.0
#tool nuget:?package=Universal.Operative.Sdk.Discrete&version=4.0.0
Universal.Operative.Sdk.Discrete
Provider-neutral conversations, model streams, tools, transforms, turn coordination, and durable conversation chronologies.
Install
dotnet add package Universal.Operative.Sdk.Discrete
Use a provider package such as Universal.Operative.Sdk.Discrete.OpenAI or Universal.Operative.Sdk.Discrete.Anthropic to supply an IModel.
SDK interfaces accept optional cancellation tokens, defaulting to default (equivalent to CancellationToken.None). Forward the caller's token when cancellation should propagate.
For settled output, consume TurnCompletedEvent.FinalMessage: an independent response snapshot after committed turn transformations. Its API documentation defines the message-identity requirements for replacement transformers.
Run a turn
using Universal.Operative.Sdk;
using Universal.Operative.Sdk.Discrete;
IEngine engine = EngineBuilder.FromDefaults(model).AddBaselineToolSet().Build();
Conversation conversation = new Conversation
{
Messages =
{
new Message
{
Role = MessageRoles.User,
Content =
{
new TextBlock("Inspect this repository.")
},
},
},
};
ConversationManager manager = await ConversationManager.CreateAsync(conversation);
await foreach (EngineEvent engineEvent in engine.ExecuteAsync(new ExecutionContext(new TurnContext()), manager, CancellationToken.None))
{
if (engineEvent is AssistantMessageEvent response)
{
Console.WriteLine(response.Message);
}
}
Engine streams model output, dispatches tools, applies transforms, and records turn and model-call audit facts through the conversation manager.
Submit messages through an operative
For a settled response without handling an event stream, use Message? reply = await operative.CompleteAsync(message, cancellationToken). This helper consumes and disposes the submission internally, returns the last TurnCompletedEvent.FinalMessage (possibly null), and propagates failures. An overload accepts an explicit ITurnContext. If a turn is already running, it injects the message and observes the submission stream using the same joining behavior as SubmitAsync; cancellation of that joined observation does not stop another caller's turn. Use SubmitAsync directly when you need streaming events.
IOperative.SubmitAsync and ResumeAsync return an owned SubmitResult. StartedTurn means a turn is reserved; the engine executes when its events are enumerated. Consume the events or dispose the result before leaving the reservation unstarted. Disposal before execution releases the reservation without running the model, rolls back pending owner input under CommitMessageMode.OnSuccess, and applies the configured admission policy to acknowledged injected input. Admitted injections are retained independently of a later unanswered owner input. Immediate-mode input remains committed. Started event streams are single-consumption.
await using SubmitResult submission = await operative.SubmitAsync(message, cancellationToken);
await foreach (OperativeEvent operativeEvent in submission.Events.WithCancellation(cancellationToken))
{
Console.WriteLine(operativeEvent.Type);
}
Disposing an active event enumerator stops its owned turn and performs cleanup. Dispose that enumerator before disposing its result; disposing the result while it is actively enumerating throws and can be retried after the enumerator is disposed. Disposing a joined result only unsubscribes that observer and never cancels another caller's turn. Supplying cancellation before the first event releases the unstarted reservation.
Configure operative policies through OperativeBuilder or the constructor's Operative.Options object rather than positional policy parameters. Engines, models, transformers, and repositories supplied by a host remain host-owned. Builder factories retain ownership of dependencies they create and inject. Use AddBaselineToolSet; the former AddBaselineTools alias is removed.
SessionInfo is an extensible metadata class with named properties. Replace its former positional constructor with an object initializer; Session.ToInfo() remains the listing shortcut. Session retains immutable replacement semantics. Truncating a session preserves its conversation identity and metadata while taking a detached snapshot of the retained messages.
Both discrete and realtime IModel interfaces now implement IDisposable. A consumer that creates a model owns its lifetime, even when a factory returns it through the interface. Engines, operative builders, and factory-created engines borrow injected models; dispose the model only after every operation using it has completed. Implement resource-free custom models with a no-op Dispose method.
AgentTool returns the subagent's settled TurnCompletedEvent.FinalMessage. Its default recursion exclusion applies to flat tools, static packs, and dynamic catalogs. An operative releases its reserved turn if startup fails; canceled or disposed joined observers unsubscribe without stopping the shared turn. Enqueue transformations run against a candidate queue: rejection does not accept the new message or attach an observer. Draining policy applies before every admission, including late handoff and disposal cleanup. If a policy refuses input or admits nothing while requeuing messages, execution fails explicitly instead of starting empty follow-up turns. Refused input stays in the operative's in-memory queue for a later retry; it is not part of durable conversation history until admitted. Reusing or disposing another unstarted reservation does not bypass the policy. The default DrainAllMessageQueueDrainingStrategy admits all acknowledged injections. If ordinary execution fails, cleanup attempts to retain queued input under the configured admission policy without rerunning failed transformations.
Interrupted tool rounds
The engine closes committed tool calls that have no recorded result before resuming a conversation and when a turn exits, including cancellation, early enumeration disposal, dispatch failure, and truncated responses. Results observed by the engine are preserved. Missing results receive an error block with Extensions["executionOutcome"] = "unknown"; the text explains that side effects may have occurred and external state should be checked before retrying. Recovery does not execute tools. It commits a toolHistoryRecovered revision, placing results after the calling assistant message and before subsequent user input.
An unknown outcome is not evidence that execution failed or did not start. Hosts own reconciliation and any retry or idempotency policy. Recovery cannot guarantee durability when storage fails or the process terminates; the next engine turn repairs persisted unanswered calls. Direct IModel consumers manage their own history and tool lifecycle.
Persist and resume
The host owns the repository and its lifetime. ConversationManager owns one mutable materialization and moves one named head.
FileSystemConversationRepositoryOptions repositoryOptions = new FileSystemConversationRepositoryOptions
{
Directory = conversationDirectory,
ChronologyId = conversationId,
};
await using FileSystemConversationRepository repository = await FileSystemConversationRepository.OpenOrCreateAsync(repositoryOptions);
ConversationManager manager = await ConversationManager.OpenOrCreateAsync(repository, () => new Conversation { Id = conversationId });
IOperative operative = OperativeBuilder.Create(engine, manager).WithChronologyCompactor(new SizeLimitedChronologyCompactor(new SizeLimitedChronologyCompactorOptions { MaximumBytes = 256L * 1024 * 1024, })).Build();
Use FileSystemConversationRepository.CreateAsync when the chronology must be new, OpenAsync when it must exist, and OpenOrCreateAsync for either state. A filesystem repository permits one open writer.
After a chronology append fails, dispose and reopen the repository before writing again. Reopening repairs an incomplete trailing record and supplies a missing final line delimiter before another append. The original append failure remains available as the inner exception on rejected writes.
chronology.jsonl contains ordered audit facts. Immutable content-addressed objects store conversation snapshots and messages. Unchanged messages are shared across revisions.
Branch and restore
Every revision records its ordered parents and exact conversation snapshot. A named head may be reset or forked without changing earlier revisions.
ConversationManager alternative = await manager.ForkAsync(earlierRevisionId, headName: "alternative");
await alternative.ResetAsync(otherRevisionId);
Conversation restored = alternative.Current;
Use ReadChronologyAsync to inspect revisions, named heads, turn outcomes, model invocations, and host-defined CustomChronologyEvent values.
Summarize model context while retaining the transcript
CompactionTransformer preserves the conversation ID, all system messages, conversation extensions, and retained tail messages. It copies the extensions dictionary before stamping its reserved compaction metadata; the input dictionary is unchanged. The result establishes a history boundary. The engine commits it as a transformed revision with transformer, stage, iteration, and historyBoundary metadata, and emits TransformerAppliedEvent after committing.
Use ConversationManager with FileSystemConversationRepository to persist that revision and retain earlier full snapshots. Read earlier revisions for the full transcript and render compaction separately using the revision metadata or the transformer event. No separate persistence callback is required. Calling the transformer directly returns replacement state; the caller must persist it.
Context summarization does not delete earlier revisions. Chronology compactors and payload retention are separate, explicitly lossy operations: leave them disabled when full historical payloads must remain available. A session store that saves only the latest conversation does not archive pre-compaction snapshots.
Host multiple sessions
Session is the durable host-level unit around one discrete Conversation. It is independent of authentication, tenancy, UI selection, and transport. ISessionStore is the persistence boundary: implement it over a database or remote service, or start with the included InMemorySessionStore and FileSystemSessionStore.
ISessionStore store = new FileSystemSessionStore(new FileSystemSessionStoreOptions { Directory = sessionDirectory, });
SessionManager sessions = new SessionManager(store, () => new Conversation { System = [new TextBlock("You are a helpful operative.")], });
Session session = await sessions.CreateAsync();
IOperative operative = operativeFactory.Create(session.Conversation);
// Run turns, then persist the mutated conversation with optimistic concurrency.
session = await sessions.SaveAsync(session with { Conversation = operative.Conversation });
Store-issued Session.Version values are opaque optimistic-concurrency tokens. Reads are detached, creates reject duplicate identifiers, stale saves fail with SessionConflictException, and deletes may be conditional. A store instance defines its own isolation boundary; the host decides whether that means one user, tenant, application, connection, or a deliberately shared consciousness.
SessionManager supplies storage-neutral create, rename, fork, truncate, and title inference operations. It intentionally does not track an active session or perform authorization. Those are adapter responsibilities.
Bound storage
IChronologyCompactor defines lossy chronology compaction for repositories that implement ICompactableConversationRepository.
SizeLimitedChronologyCompactorretains the largest recent reachable revision window within a byte limit.RevisionWindowChronologyCompactorretains a configured number of recent reachable revisions.CheckpointChronologyCompactorretains only revisions referenced by named heads.FileSystemConversationRepository.ApplyRetentionAsyncdeletes old payloads while retaining the audit graph.
Compactors preserve every named head. A result reports when the requested byte target cannot be met by the required heads alone.
Main abstractions
Conversationis mutable state supplied to a model.ConversationManagermaterializes revisions and moves one named head.SessionandSessionManagermodel host-level conversation lifecycle.ISessionStorepersists sessions independently of transport and identity.IConversationRepositorystores immutable revisions and chronology events.Chronologyis the audit read model.IModelmaps a provider to provider-neutral stream events.Engineruns one turn.Operativecoordinates concurrent submissions.ITransformerderives replacement conversation or turn-context state.
Invocation and dispatch observation
ModelInvocationStartedEvent identifies the invocation, iteration, committed input revision, offered tools, and actual conversation after input transformations. Observe live conversation references without modifying them. ModelInvocationCompletedEvent is the correlated terminal event for success, failure, or cancellation; it includes the committed output revision when available, the primary exception, and any secondary cleanup or chronology failures. A failure event is followed by the original exception on the next enumeration step.
Invocation lifetime includes synchronous stream opening, enumerator construction, reading Current, enumeration, stream disposal, response reduction, and output commit. Each started invocation makes one terminal chronology write attempt using an uncanceled cleanup token. If a primary operation and cleanup both fail, cleanup does not replace the primary exception. Chronology write failure itself propagates when there is no earlier failure. Durable storage failures cannot guarantee a recorded terminal event.
Disposing enumeration early records abandoned observation, or cancellation when requested, where chronology is available. A disposed subscriber cannot receive later live events. Model output is only complete after reduction, output commit, and stream disposal; receiving provider stop data alone does not establish SDK completion.
Tool events correlate original provider identifiers and iteration even if hooks rewrite requests. ToolCallDispatchingEvent holds the prepared-call snapshot before lookup, veto, or execution. ToolDispatchCompletedEvent holds shared-dispatcher facts; ToolCallCompletedEvent.Dispatch and ToolCallErrorEvent.Dispatch retain those facts. A successful result supplied by a hook does not imply a tool ran. Custom dispatch overrides that do not report shared-dispatcher facts retain an unknown path.
Set EngineBuilder.ToolDispatchCompleted for a terminal callback shared by ordinary engine dispatch and native adapter bridges using the supplied dispatcher. Use the event stream for engine invocation and turn events. These mechanisms do not configure logging, storage, or a tracing backend.
Batch cancellation and early disposal cancel queued dispatches without waiting indefinitely for uncooperative foreground work. The worker coordinator owns its gate and cancellation source until workers and the event reader finish. Late worker failures without an event reader go to the optional Engine.Options.ToolWorkerFailed callback and emit a payload-free warning through the optional consumer-owned ILogger. Hosts still own background jobs and any drain policy before releasing tool resources.
EngineBuilder.WithLogger supplies the engine, shared dispatcher, and model invocation with the same consumer-owned logger. Direct model callers can set ModelInvocation.Logger; the default IModel.CompleteAsync also passes it to stream reduction. Logging explains recovered failures and content omissions, while ordinary terminal failures remain results or exceptions for the host to record. Debug logging includes routine empty-history cleanup; substantive omissions and failures use information or warning levels. No provider is configured and no log is emitted when the logger is unset.
Turn usage counters are null if any model call omitted the corresponding counter. ContextTokens is the input count of the final call, or null when that call omitted it. Inspect per-call usage for partial billing evidence rather than treating missing counters as zero.
Generative AI telemetry
The shared Universal.Operative.Sdk package describes the pinned OpenTelemetry GenAI convention revision and host registration. Discrete engines emit invoke_agent internal spans for turns; configure a stable, non-sensitive name with EngineBuilder.WithAgentName or Engine.Options.AgentName. Engine turns and direct calls to built-in provider adapters emit model-operation spans without duplicating instrumentation for the same invocation. Custom models expose optional IModel.Info metadata and can use ModelTelemetry.StreamAsync to instrument direct streams; engines and the default IModel.CompleteAsync instrument custom models automatically. Unknown providers are identified as unknown rather than inferred from a CLR type.
Inference spans use the adapter's operation, provider, configured model, returned model and response identifier, normalized finish reason, and available token counts. The Codex app-server and Claude Agent SDK adapters emit invoke_agent client spans because their streams represent whole agent invocations. IModel.GetTotalUsage supplies totals including additive cache or reasoning tokens while preserving the original provider usage. Missing counts remain absent rather than becoming zero. Turn spans aggregate known model totals and omit a counter when any invocation omitted it.
Metrics include gen_ai.client.inference.duration, gen_ai.client.inference.time_to_first_chunk, gen_ai.invoke_agent.duration, and gen_ai.client.invoke_agent.duration histograms in seconds, plus gen_ai.client.inference.usage.input_tokens and gen_ai.client.inference.usage.output_tokens counters in tokens. The first-chunk metric measures receipt of the first canonical stream event when the adapter establishes that the provider request is streaming; gen_ai.request.stream records that wire mode when known. Token counters count inference operations only; agent totals appear on agent spans to avoid double counting. Metrics work independently of trace sampling. Full inference duration includes stream consumption and disposal; a caller that pauses enumeration extends the measured operation. Ending observation early stops the activity and preserves an abandoned or canceled outcome. Standard activity context is restored between yielded events so unrelated consumer work does not become a child of the inference.
License
Free for noncommercial use under the Universal.Operative Noncommercial License. Commercial use requires a separate license from Andrew Ong.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. net11.0 is compatible. |
-
net10.0
- Universal.Operative.Sdk (>= 7.0.0)
- Universal.VersionControl (>= 1.0.0)
-
net11.0
- Universal.Operative.Sdk (>= 7.0.0)
- Universal.VersionControl (>= 1.0.0)
NuGet packages (23)
Showing the top 5 NuGet packages that depend on Universal.Operative.Sdk.Discrete:
| Package | Downloads |
|---|---|
|
Universal.Operative.Sdk.Discrete.Microsoft.Foundry
Microsoft Foundry OpenAI, Anthropic, and MAI model adapters for Universal.Operative.Sdk.Discrete. |
|
|
Universal.Operative.Sdk.Discrete.OpenAI
OpenAI Chat Completions and Responses API adapters for Universal.Operative.Sdk.Discrete. |
|
|
Universal.Operative.Sdk.Discrete.Anthropic
Anthropic Messages API adapter for Universal.Operative.Sdk.Discrete. |
|
|
Universal.Operative.Sdk.Discrete.Anthropic.ClaudeAgentSdk
Claude Agent SDK model adapter for Universal.Operative.Sdk.Discrete. |
|
|
Universal.Operative.Sdk.Scheduling
Durably schedule a prompt to fire into a Universal.Operative.Sdk IOperative at a future time, either once or on a recurring cron schedule — registrations survive the creating process; delivery requires an available or independently activated trigger target. ScheduleCreate/List/Cancel tools (backed by a shared ScheduleService, reusable from an HTTP-facing admin surface too) register on creation and attempt compensating store cleanup on failure or cancellation, reporting partial failure. IDurableScheduleBackend implementations: WindowsTaskSchedulerBackend/SystemdTimerBackend/CrontabBackend register with the OS's own scheduler; HttpDurableScheduleBackend registers against a remote HTTP dispatcher instead, for hosts (e.g. a sandboxed PaaS container) with no local OS scheduler reachable at all. Every backend is fully configured at construction — RegisterAsync just needs the schedule. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 4.0.0 | 397 | 11/18/2026 |
| 3.4.1 | 225 | 11/16/2026 |
| 3.4.0 | 578 | 11/16/2026 |
| 3.3.0 | 752 | 11/11/2026 |
| 3.2.0 | 131 | 11/10/2026 |
| 3.1.2 | 379 | 11/10/2026 |
| 3.1.1 | 482 | 10/2/2026 |
| 3.1.0 | 555 | 9/17/2026 |
| 3.0.0 | 488 | 9/7/2026 |
| 2.4.1 | 140 | 9/5/2026 |
| 2.3.0 | 127 | 9/5/2026 |
| 2.2.1 | 213 | 9/4/2026 |
| 2.2.0 | 129 | 9/4/2026 |
| 2.1.0 | 252 | 9/3/2026 |
| 2.0.1 | 321 | 9/2/2026 |
| 2.0.0 | 461 | 9/1/2026 |
| 1.2.0 | 382 | 8/26/2026 |
| 1.1.0 | 208 | 8/24/2026 |
| 1.0.0 | 335 | 8/12/2026 |
Targets .NET 10 and .NET 11; removes .NET 8 support. Provider-neutral IModel is IDisposable; consumers own models and injected dependencies. Interface cancellation tokens are optional; configure optional standard logging through Logger or WithLogger. SubmitResult owns lazy reservations; consume or await-dispose it. Operative policies use Options; SessionInfo uses named properties.