Skip to content

Latest commit

 

History

History
2446 lines (2171 loc) · 199 KB

CHANGELOG.md

File metadata and controls

2446 lines (2171 loc) · 199 KB

opencode .NET SDK Change Log

This document outlines the changes, updates, and important notes for the opencode SDK for .NET. Each released version links straight to its GitHub Release tag.

[Unreleased]

Nightly builds of master are on GitHub Packages as nightlies of the next version, {version}-nightly.{yyyyMMdd}.g{shortSha}.

2.1.1 - 2026-12-03

2.1.1 pins opencode 2.4.3. It is a patch release that moves the protocol pin from 2.4.1, so generated types change the way upstream changed them: a machine reports one Status (unpaired, offline, online with its OS, architecture and connection, or incompatible) in place of its separate online, paired, OS, architecture and connection fields, and the server.connected event's data names the live event stream. Both are listed as breaking under protocol changes. Experimental push notifications, spaces, feature flags and skill files are added, and a background-service service.json that cannot be read or decoded is refused instead of read as empty settings.

🔌 Protocol changes

  • The SDK pins opencode 2.4.3, where it pinned 2.4.1.
  • Breaking: MachineInfo.Online, Paired, Os, Arch and Connection move into a required Status, an IMachineStatus that is MachineStatusUnpaired, MachineStatusOffline, MachineStatusOnline (which carries the Os, the Arch and the Connection, an IMachineTransport) or MachineStatusIncompatible (with its IMachineRefusal reason), because opencode 2.4.3 reports one status per machine. MachineInfoConnection, MachineInfoConnectionKind and MachineInfoConnectionPath are removed. Before: if (machine.Online) Console.WriteLine(machine.Os);. After: if (machine.Status is MachineStatusOnline online) Console.WriteLine(online.Os);.
  • Breaking: EventServerConnected.Data changes from IReadOnlyDictionary<string, JsonElement> to EventServerConnectedData, whose Stream names the live event stream, which ExperimentalClient.SubscribeSpacesAsync addresses. Before: connected.Data["…"]. After: connected.Data.Stream.
  • ExperimentalClient manages push notifications to phones: GetPushSettingsAsync, RegisterPushDeviceAsync, UpdatePushDeviceAsync, RemovePushDeviceAsync, SetPushDeviceSessionAsync, RemovePushDeviceSessionAsync, SetPushSessionAsync, RemovePushSessionAsync and SetPushSettingsAsync, with ExperimentalPushUpdated on the event stream. ExperimentalPushDeviceRegisterRequest.CallbackUrl carries the relay's delivery token, so the record's printed form masks it.
  • ExperimentalClient reads and writes spaces, a shared key-value store: WriteSpaceValuesAsync, SyncSpacesAsync, SubscribeSpacesAsync, UnsubscribeSpacesAsync and ResetSpaceRevisionsAsync, with ExperimentalSpaceUpdated, ExperimentalSpaceDeleted and ExperimentalSpaceResync on the event stream.
  • ExperimentalClient.GetFeatureFlagsAsync returns the feature flags a location's clients may act on.
  • ExperimentalClient.GetSkillFileAsync reads one file of a skill.
  • AgentInfo.Instructions (AgentInfoInstructions) holds an agent's added instructions: text, or an AgentSelectionInstructions with the text sent while the agent is selected and the text sent once when the session switches away.
  • SessionClient.PromptAsync and ExperimentalClient.ActivateSessionSkillAsync can answer 502 SkillLoadError, and FileSystemClient.ReadFileAsync, ListEntriesAsync and FindEntriesAsync, ExperimentalClient.WriteFileAsync, CreatePtyAsync and RunShellCommandAsync can answer 503 ServiceUnavailableError where the location cannot serve them.
  • ConfigInfoExperimental exposes the CompactionJobs, McpSkills, CodemodeAgents and BrowserStreamTunnel flags, ModelCompatibility.SupportsSystemUpdates is new, and ModelType gains Embedding, Realtime and Transcription.
  • The experimental browser tunnel (experimental.browser.tunnel) is a WebSocket the SDK offers no door for; its single-use ticket comes from the browser plugin's tunnel.ticket RPC for a browser attached to a session.
  • Since opencode 2.4.2, sending a message, command, skill or shell command to an archived session unarchives it.

🐛 Fixes

  • A background-service config (service.json) that cannot be read or decoded is refused, as opencode's own CLI refuses it since 2.4.3. OpenCodeServiceConfiguration, OpenCodeServer.ResolveAsync and OpenCodeServer.EnsureAsync throw OpenCodeServerException naming the file, where the SDK used to read it as empty settings, so a configuration change can no longer replace such a file with empty settings. Only a missing file reads as empty. Discovery and stop no longer migrate the legacy config file; reading the config still does.

📚 Documentation

  • SessionInfo.Model says when opencode records a session's model: at creation, through SessionCreateRequest.Model or from a subagent's agent or parent, on a fork or import, and through SwitchModelAsync. A session created through the API without a model has none even when its agent configures one, and each assistant message records the model it ran on.
  • The README's API coverage counts five WebSocket connections: three with doors, the planned machine link, and the browser tunnel, which has none.
  • Query parameters keep opencode's descriptions: since opencode 2.4.3 they sit on the parameters themselves, which the generator now reads first.
  • HQ reads a session's agents, models and providers again when the server announces a change to them without a location, as opencode's app does from 2.4.3: a plugin that registers late announces its catalog that way. The getting-started guide says to refresh every loaded location on such an event.
  • The pagination guide says that sending a prompt, a command, a skill or a shell command to an archived session unarchives it, as opencode does from 2.4.2.
  • Sessions.GetTotalCostAsync's documentation names opencode's app and TUI as the clients whose total it matches. From opencode 2.4.3, opencode's ACP server also adds a child session's descendants.
  • The requests guide says that, from opencode 2.4.2, a shell tool call inside an automation's code action fails when its timeout runs out, while a fixed shell action runs without a timeout.

2.1.0 - 2026-11-24

2.1.0 pins opencode 2.4.1. It is a minor release that moves the protocol pin, so generated types change the way upstream changed them: a blob no longer reports its expiry, three experimental config flags are removed because automations and MCP events ship without one, video_generate also takes an options object, and a voice model requires an engine and a name. All four are listed as breaking under protocol changes. Background jobs can be cancelled, machines can be listed, added and removed, and the server no longer waits for plugins at startup. Sessions.GetTotalCostAsync totals a session's cost with its subagent sessions, and HQ is redesigned.

🔌 Protocol changes

  • The SDK pins opencode 2.4.1, where it pinned 2.3.2.
  • Breaking: BlobInfo.ExpiresAt is removed, because opencode 2.4.0 no longer reports a blob's expiry. opencode still deletes a blob seven days after writing it. Before: double expires = blob.ExpiresAt;. After: remove the read.
  • Breaking: ConfigInfoExperimental.Automations, McpEvents and Schedules are removed, because opencode 2.4.0 ships automations and MCP events without a feature flag. Automations are on by default and switch off with the new ConfigInfo.Automations. Before: new ConfigInfoExperimental { Automations = true }. After: nothing to set; to turn automations off, new ConfigInfo { Automations = false }.
  • Breaking: ConfigInfoExperimental.VideoGenerate changes from bool? to ConfigInfoExperimentalVideoGenerate?, which holds either a Boolean or a ConfigVideoGenerateOptions naming the video tool's default Model. Before: new ConfigInfoExperimental { VideoGenerate = true }. After: new ConfigInfoExperimental { VideoGenerate = ConfigInfoExperimentalVideoGenerate.FromBoolean(true) }.
  • Breaking: VoiceModel gains required Engine and Name, so code that constructs the record sets both.
  • ExperimentalClient.CreateVideoGenerationAsync and GetVideoGenerationAsync no longer answer 403 ForbiddenError: opencode 2.4.0 no longer checks a flag before generating video. A video generation is listed as a background job, JobVideo, with JobKind.Video.
  • ExperimentalClient.CancelJobAsync (experimental.job.cancel) cancels a background job, and ExperimentalJobUpdated, with ExperimentalJobUpdatedData, joins IEvent; EventType.ExperimentalJobUpdated filters the event subscription to experimental.job.updated.
  • ExperimentalClient.ListMachinesAsync, AddMachineAsync and RemoveMachineAsync (experimental.machine.list, .add, .remove) manage machines. AddMachineAsync returns a MachineInvite whose Join is a single-use join string carrying the join secret; the record's printed form masks it. ConfigInfoExperimental.Machines exposes the machines flag. The machine link, the WebSocket a machine connects through (experimental.machine.link), has no door yet; one is planned.
  • An automation can run a fixed shell command: AutomationShellActionInput creates one, and AutomationActionShell reads it back.
  • ModelInfo.Experimental.Speed (ModelSpeed) names a model's service tier, and ConfigInfoExperimental.ModelSpeeds exposes its flag. ConfigInfoExperimental.HomeMemory, OpencodeApi, ProjectOverlay, RecommendedApi and SqliteFts expose the other new feature flags.
  • Since opencode 2.4.0 the server no longer waits for plugins: listing models and providers, the default model, web search, and experimental generation and voice answer right after startup with what has loaded, so a list can be empty or partial, and they no longer answer 503 ServiceUnavailableError while plugins load. Plugins.WaitForPluginsAsync and LanguageModels.WaitForDefaultAsync are unchanged and still poll the plugin list as opencode's CLI does.

✨ Added

  • Sessions.GetTotalCostAsync returns a session's total cost as opencode's own clients show it: a session's cost plus the cost of every descendant subagent session, and a subagent session's own cost. An unknown session fails with the server's not-found error, where opencode's client shows 0.

🐛 Fixes

  • An OpenCodeApiException whose server message already ends in ., ! or ? no longer gets a second period, so the readable 500 opencode answers handler defects with reads "… Check server logs for details." instead of ending in "..".

📚 Documentation

  • HQ's redesigned board and session screens show named asks, edit previews, rendered Markdown and coloured diffs, with Changes and Terminal tabs and an SDK calls dock remembered across reloads. Permission asks offer Deny, Allow always and Allow once; questions can be submitted or dismissed, and a running turn can be stopped. Session titles follow later renames, and untitled rows stay clickable. A session's asks are listed again when its page opens and when one of its turns ends, so an ask a stopped turn dropped no longer stays on the board.
  • HQ can rename, archive and delete a session.
  • HQ can fork a session from a message, compact it, and switch its agent and model.
  • QuickStart picks a free model only when every price tier lists zero input and output rates, as the README example does.
  • The README is reorganized around a quick start and the runnable apps. A new versioning-and-support guide holds the target-framework rule, the version policy and the support policy. The contributing guide moves to the repository root, a support page is added, and usage questions go to the Q&A category of GitHub Discussions.
  • The README shows HQ's board. On NuGet.org the image comes from the commit the package was built from, like the README's links.
  • The getting-started guide says the server no longer waits for plugins and that a catalog can be empty or partial right after startup, and names the *.updated events a long-lived application can refresh on. The README's streaming example and QuickStart no longer treat a 503 as "the server is still starting".

2.0.1 - 2026-11-22

2.0.1 pins opencode 2.3.2. It is a patch that moves the protocol pin, so generated types change the way upstream changed them: schedules become automations, and two experimental config flags are removed. All three are listed as breaking under protocol changes, and existing schedules may not survive the server upgrade. Video generation and blob reads are added.

🔌 Protocol changes

  • The SDK pins opencode 2.3.2, where it pinned 2.3.0.
  • Breaking: schedules become automations, as opencode 2.3.1 replaced them. ExperimentalClient's CreateScheduleAsync, GetScheduleAsync, ListSchedulesAsync, PauseScheduleAsync, ResumeScheduleAsync and DeleteScheduleAsync become CreateAutomationAsync, GetAutomationAsync, ListAutomationsAsync, PauseAutomationAsync, ResumeAutomationAsync and DeleteAutomationAsync, and the Schedule* types, ExperimentalSchedule* requests and responses, and ScheduleNotFoundError are removed for Automation*, ExperimentalAutomation* and AutomationNotFoundError. An automation has a required Name, a Trigger (AutomationTriggerAt, AutomationTriggerEvery, AutomationTriggerCron, or AutomationTriggerEvent for a connected MCP server's push event), and an Action that sends a prompt or runs a Code Mode program; it has no If, Until or Ends. Before: new ExperimentalScheduleCreateRequest { SessionId = id, Prompt = "Check the build", When = ScheduleWhenInput.FromScheduleWhenInputEvery(new ScheduleWhenInputEvery { Every = "2 hours" }) }. After: new ExperimentalAutomationCreateRequest { SessionId = id, Name = "Check the build", Trigger = new AutomationTriggerEvery { Every = "2 hours" }, Action = new AutomationPromptActionInput { Prompt = "Check the build", To = AutomationTarget.FromAutomationTargetSession(new AutomationTargetSession { Session = id }) } }. The server enables them with experimental.automations; ConfigInfoExperimental.Schedules stays as its deprecated alias. Existing schedules may not survive the server upgrade: opencode's migration carries over only active or paused schedules that send a prompt, with no If or Until condition and no Ends.Times limit, as automations with the same ID suffix and an aut_ prefix, and deletes the rest, finished ones included.
  • Breaking: ConfigInfoExperimental.BackgroundCompaction is removed, because opencode 2.3.1 replaced the background_compaction flag with compaction.background, which defaults to on. Background summaries now start by default as a session nears automatic compaction, and a summary that is never used still costs tokens. Before: new ConfigInfoExperimental { BackgroundCompaction = false }. After: new ConfigInfoCompaction { Background = false } in the config's Compaction.
  • Breaking: ConfigInfoExperimental.ShellTimeoutBackground is removed, because opencode 2.3.1 removed the flag: a foreground shell command still running when its timeout expires always moves to the background. Code that set it removes the assignment.
  • ExperimentalClient.CreateVideoGenerationAsync (experimental.generate.video.create) submits a video job and returns its ID once the provider accepts it; GetVideoGenerationAsync (experimental.generate.video.get) reads it as GenerateVideoRunning, GenerateVideoCompleted with the video's blob, or GenerateVideoError with a GenerateVideoErrorReason, and answers VideoNotFoundError for an unknown ID. The server keeps jobs in memory and enables them with experimental.video_generate. ModelType.Video names a video model.
  • ExperimentalClient.GetBlobAsync (experimental.blob.get) streams a stored blob, such as a generated video, and answers BlobNotFoundError for an unknown ID; opencode deletes blobs 7 days after writing them.
  • JobKind.Codemode and JobCodeMode list a Code Mode program as a background job, and ExperimentalJobListRequest's kind filter accepts it.
  • ConfigInfoExperimental.Automations, VideoGenerate and FullCodemode expose the new feature flags; FullCodemode is off in every build unless set.

📚 Documentation

  • PersistentPtyRole's XML documentation says a controller attach without takeover fails while another attachment controls the terminal, and that input sent on an observer's connection makes that attachment the controller, where it said a connection that asked to control could be attached as an observer and an observer's input was ignored.
  • The getting-started guide says the calls that wait for plugins wait a bounded time, not for activation to finish, where it said the server exposes no activation barrier, which the next point contradicted.

2.0.0 - 2026-11-17

2.0.0 keeps the opencode 2.3.0 pin shipped in 1.1.0. It is a major for hand-written breaks: the shared event connection changes buffering, admission, retries, error reporting and subscription lifetime (#902, ADR-0041); standalone readiness has no default timeout, a discovered server's password can be null, mock default-model failures can throw synchronously, and loopback discovery follows the client's proxy decision. User files now read through PromptAttachment; the Protocol changes below cover that migration.

💥 Breaking changes

  • EventsClient.SubscribeAsync uses one shared background source per root client. Before: each enumeration owned a pull-driven connection. After: each is an independent subscription with 4,096 queued selected events allowed; the next refused selected offer discards that subscriber's backlog and throws OpenCodeEventSubscriberOverflowException. A sole subscriber's overflow stops the source.
  • The first server.connected changes meaning. Before: it began a new physical connection. After: it marks admission to the shared feed, possibly cached and sharing its Id with neighbours, not a new connection or liveness proof. Earlier business events are not replayed. A later marker still announces a possible gap.
  • Ordinary event-attempt failures no longer end the subscription after a minute. Before: a minute in which every attempt failed threw the last API, transport or failure-frame exception. After: retries continue forever and connection state's Error exposes the classified exception. Consumers that require a deadline own a cancellation token.
  • Event source faults are shared. Before: each stream owned its failures. After: an unexpected source/cleanup fault ends admitted subscriptions after their queued prefix with the same exception; state watchers receive Idle. Cancellation still wins over a preserved prefix on a later pull.
  • Event selection and payload ownership are shared. Before: Types went to the server and each enumeration decoded its own events. After: Types are copied and validated at the call and selected locally; physical attempts send no Types query. The whole bus is decoded once, so malformed unselected traffic reconnects every subscriber. Event and metadata instances are shared references, not deep-frozen graphs; consumers treat them as read-only. Queue bounds count events, not bytes, and subscriber count remains unbounded.
  • Event subscriptions no longer forward per-call Location. Before: it reached every connection attempt. After: it is accepted but ignored; every shared attempt sends only the client's ambient header snapshot. Other operations retain their existing override behavior.
  • Event reading and disposal no longer depend on the consumer's pulls. Before: holding an event paused reading and idle detection, and disposing an enumerator with a pending move threw NotSupportedException. After: idle detection keeps running while a consumer holds an event, and pending-move disposal is supported: an unsettled move ends false unless cancelled, and an already settled move keeps its result. Disposal drains unread data and later pulls end false, even after an earlier overflow, fault or root disposal, unless an entry token is cancelled.
  • OpenCodeServerOptions.ReadinessTimeout now defaults to Timeout.InfiniteTimeSpan: a standalone start waits for readiness until its cancellation token fires, as opencode's CLI does. Before: StartAsync() failed after 60 seconds without a readiness line. After: set ReadinessTimeout = TimeSpan.FromSeconds(60) to keep that failure, an OpenCodeServerException naming the bound; a cancellation token bounds the wait too, but ends the start with OperationCanceledException.
  • A background service registered without a password is used, as opencode's CLI uses it. OpenCodeServer.Password is string?: such a service is now discovered and reused, and its handle's Password is null. Before: string password = server.Password;. After: string? password = server.Password;.
  • LanguageModels.WaitForDefaultAsync calls a mocking client's GetDefaultAsync directly. Before: an override that threw synchronously produced a faulted task. After: that exception throws from the call itself; catch it around the invocation as well as the await. Real clients keep the plugin poll followed by one default-model read.
  • Background-service discovery (OpenCodeServer.DiscoverAsync and the probe EnsureAsync runs) takes the client's proxy decision for a loopback service, as opencode's CLI does. Before: the probe always bypassed a proxy for a loopback service, so it reported a service ready behind HTTP_PROXY, HTTPS_PROXY or ALL_PROXY without NO_PROXY, although the client it returned sent its requests through that proxy. After: on .NET 10 and later such a discovery goes through the proxy and does not find the service. To reach a loopback service directly, add its host (127.0.0.1 or localhost) to NO_PROXY, or to a system proxy's bypass list; the SDK has no proxy option of its own for discovery. .NET Framework is unchanged.

🔌 Protocol changes

  • Breaking: SessionMessageUser.Files and SessionInboxUserPayload.Files now contain PromptAttachment, with PromptAttachmentKind selecting the unchanged PromptFileAttachment, the new PromptMediaFileAttachment, or raw Unknown. Before: PromptFileAttachment file = user.Files![0];. After: PromptAttachment file = user.Files![0];, then read file.PromptFileAttachment.Data or file.PromptMediaFileAttachment.Uri according to file.Kind. This also changes the files in SessionInboxEnqueued.Data.Item (SessionInboxEnqueuedData.Item → SessionInboxItemUser.Payload → SessionInboxUserPayload). A media file appears only with the experimental experimental-media-uri capability on; without it every element's known arm is PromptFileAttachment. Code that sets Files wraps each attachment: Files = [PromptAttachment.FromPromptFileAttachment(file)]. The opencode pin is unchanged (2.3.0): the change comes from a restore patch that gives these reads the attachment union upstream already defines.

✨ Added

  • Experimental client-hosted MCP exposes application tools through ConnectClientMcp over a reconnecting WebSocket, including text/image results and the browser CreateClientMcpConnectTokenAsync door (OPENCODE001).
  • ClientMcpSchema.FromType exports object input schemas from source-generated metadata without a new dependency.
  • OpenCodeClientOptions.HttpHandler accepts a caller-owned HTTP transport for requests and event streams on every target, and for terminal upgrades on net10.0 and net11.0. The SDK never disposes it; net472 and netstandard2.0 terminal upgrades keep their own socket transport.
  • OpenCodeClientOptions.MediaReferences asks the message and inbox reads for media references, as opencode's own client does with withMediaRefs: when the session location's experimental.media_blob is on, a stored user file then reads as PromptMediaFileAttachment, and MediaReference.HashFromUri(file.Uri) gives the hash client.Experimental.GetMediaAsync fetches. OpenCodeRequestOptions.InlineMedia stops the SDK sending that capability on one call, for self-contained exports; a capability header the caller sets still goes out. All three are experimental (OPENCODE001).
  • OpenCodeClientOptions.Headers and OpenCodeRequestOptions.Headers set client-wide and per-call HTTP headers, copied at construction and call admission respectively, with per-call values winning; on the message and inbox reads, the capability header MediaReferences sends replaces both. They do not reach terminal upgrades or background-service info probes; SubscribeAsync refuses per-call Headers. A 401's missing-credential hint now depends on whether the request carried Authorization, including a caller's header, rather than whether Password was set.
  • OpenCodeServer.ResolveAsync selects an explicit endpoint, an owned standalone server or the shared service with the CLI's precedence, including the saved disabled flag. Connections expose resolve-time ServerVersion; explicit mismatches can invoke OnServerVersionMismatch. Managed ServiceOperations reconnect or restart with a best-effort persistent-terminal handoff using the resolve-time snapshot.
  • OpenCodeServerStopOptions.Pty accepts OpenCodeServerStopPtyMode.Handoff so that StopAsync attempts a best-effort persistent-terminal handoff after it reads the registration and before it signals the process. Follow it with EnsureAsync using the same registration selection to restart as the managed connection does; preservation depends on preparing and adopting the ticket before it expires. Null and Clear keep the default: terminals end with the service, as with the CLI's service restart.
  • Plugins.WaitForPluginsAsync runs the bounded, best-effort plugin poll that opencode's CLI runs before it lists agents, models and integrations; returning does not guarantee activation completed. LanguageModels.WaitForDefaultAsync now runs it.
  • OpenCodeServer.ShutdownPersistentPtyAsync discovers the background service and, when one is running, shuts down its persistent terminals, as opencode's CLI does before an uninstall; with no service it does nothing. It is experimental (OPENCODE002).
  • Virtual EventsClient.GetConnectionState() and WatchConnectionAsync(CancellationToken) expose EventConnectionState and EventConnectionStatus (Idle, Connecting, Connected, Reconnecting). Watches coalesce to the latest unread state and do not start or retain a source.
  • OpenCodeEventSubscriberOverflowException.Capacity reports the SDK's fixed 4,096 bound, including for instances constructed through its standard public constructors.
  • OpenCodeServer.FindIncumbentAsync reports whether the registered background service that answers at a given URL is ready, starting or stopping, or failed (OpenCodeServerIncumbent, OpenCodeServerState), as opencode's serve --service checks, before it binds, whether a compatible service already owns its address; it answers null when no compatible registered service answers there.
  • RpcDefinition declares a plugin's RPC definition once, with Method (RpcMethod<TInput, TOutput>) and Event (RpcEventDefinition<TData>) descriptors that carry your source-generated JSON metadata, so it works under native AOT and on every target. client.Rpc.CallAsync(method, input) calls a method with typed input and output, as opencode's own client binds a definition, and a failure the RPC registry or the plugin reports throws OpenCodeRpcException with its ErrorType, its message and ErrorData. It derives from OpenCodeApiException, which is no longer sealed, so an existing catch (OpenCodeApiException) still catches it.
  • client.Events.SubscribeAsync(rpcEvent) yields one RPC definition's events as RpcEventPayload<TData>, the shared EventRpc and its data read with your metadata, as opencode's own client subscribes to a definition's events. It selects nothing at the feed and keeps only its own events, so queued unrelated events count against its 4,096-event queue. It skips server.connected; read markers on a separate subscription to detect gaps. An event whose data does not match your type, or reads as null, throws OpenCodeTransportException.
  • OpenCodeServiceConfiguration adds typed administration of the background service's config, matching the CLI's service get, set, and unset surface. ReadAsync returns an OpenCodeServiceConfig without the password or remote route and migrates or repairs legacy config as the CLI's read does. GetOrCreatePasswordAsync returns a stored password or creates and stores one when it is absent or empty. Setters change the hostname, port, password, CORS origins, environment entries and disabled flag; UnsetAsync(OpenCodeServiceSetting) and UnsetEnvironmentVariableAsync remove settings, and DisableRemoteAsync turns remote access off. Sets and unsets stop the registered service first except SetDisabledAsync(false) and unsetting Disabled; nothing restarts it. OpenCodeServiceConfigOptions selects the channel and installed-version comparand. ReadAsync, GetOrCreatePasswordAsync, and the set and unset operations refuse a config or donor the CLI may read but the SDK's JSON reader rejects, rather than returning empty settings or erasing them.
  • OpenCodeServiceConfiguration.EnableRemoteAsync turns remote access on through the installed opencode service set remote true, using the CliCommand and Environment members of OpenCodeServiceConfigOptions. Only EnableRemoteAsync reads those two members. After CLI success, the SDK reads and returns the selected config's secret route through the shared migrating and repairing read. The SDK does not check that the command, channel and environment agree. Cancellation after CLI success can leave remote access enabled.

🔧 Changes

  • StopAsync and the EnsureAsync version-mismatch replacement treat a failed persistent-terminal handoff or clear as best-effort, whatever the exception type, as opencode's CLI does. Before: a failure other than an OpenCodeServerException ended StopAsync before it terminated the old service, and ended EnsureAsync at once. After: StopAsync terminates the old service; EnsureAsync keeps polling, and the last replacement failure becomes the inner exception of its timeout. The caller's cancellation still ends both.
  • The EnsureAsync replacement and the new StopAsync handoff mode treat every persistent-terminal ticket-request, shutdown fallback or sidecar-publish failure as best-effort, as opencode's CLI does. Before: a failure other than an OpenCodeException could end the replacement's handoff preparation before terminal shutdown or empty-ticket publication completed. After: a failed ticket request still takes the terminal-shutdown fallback and publishes the empty handoff ticket; a failed shutdown no longer skips publication, and a failed publish no longer ends the preparation. The caller's cancellation still ends it.
  • The packages' .NET dependency floors move from 10.0.13 to the 10.0.15 servicing release: on net472 and netstandard2.0, System.Text.Json, System.Threading.Channels, System.Collections.Immutable, Microsoft.Bcl.AsyncInterfaces, Microsoft.Bcl.Memory and Microsoft.Bcl.TimeProvider; in OpenCodeDotNet.Sdk.Extensions, on every target, Microsoft.Extensions.DependencyInjection.Abstractions and Microsoft.Extensions.Options.ConfigurationExtensions. No security advisory of the .NET 10.0.14 or 10.0.15 release lists these packages.

🐛 Fixes

  • OpenCodeServiceConfiguration.SetCorsOriginsAsync accepted fewer CORS origins than the CLI. It now accepts the same origins for the covered empty-label, long ASCII-name, !$&'()*+;=~, quotation mark, grave accent, and brace host-character classes.
  • client.Rpc.CallAsync runs until the plugin's method returns, as opencode's own client does: it no longer takes the client-wide NetworkTimeout (100 s by default). A per-call NetworkTimeout still bounds it, and the cancellation token is its deadline.
  • Legacy service-config and registration migration now write the decoded UTF-8 text opencode's CLI writes: one leading byte-order mark is dropped and invalid sequences become U+FFFD. A donor whose decoded text still begins with U+FEFF is not migrated. Before: donor bytes were copied unchanged.

📚 Documentation

  • The streaming guide says that a turn's end and client.Experimental.WaitForSessionAsync cover one session, not the background jobs its prompt started, and that a job ListJobsAsync lists is not necessarily still running. It recommends a Message with every permission Reject: at opencode v2.3.0, a Reject without one ends the turn as a shutdown, and a background subagent rejected that way stays listed as cancelled with its parent never told.
  • The terminals guide and PersistentPtySession's XML documentation correct the observer rule: input from an observer connection is accepted and makes that attachment the controller, rather than being dropped.
  • The terminals guide no longer promises gap-free, duplicate-free reconnects: a normal PTY cursor marks the replay boundary, not live consumption, so reconnecting can repeat live output and cannot recover output older than the retained buffer.
  • The terminals guide says silence and a PTY process's status do not prove an interactive command finished; use RunShellCommandAsync for a command result or supply your own terminal completion protocol.
  • The terminals guide documents the .NET Framework limit for closes 1012–1014: both terminal families still throw OpenCodeTransportException, but its inner WebSocketException replaces the close status and reason that .NET 10+ reports.
  • The streaming guide scopes a durable cursor to its aggregate and retained database, not one server lifetime: an embedded host with events.persist and a file-backed database can resume across restarts. The distributed CLI's persistence limit is unchanged.
  • The getting-started guide corrects GenerateTextAsync: it reads the existing session context without adding history messages and still updates session usage totals. Its options table includes experimental MediaReferences.
  • The connection and getting-started guides explain that a null Password omits SDK-generated Basic authentication, not caller Authorization: client-wide headers can authenticate the shared feed, per-call headers cannot, and authenticated terminal upgrades require Password. The requests guide names the automatic media capability's exception to per-call header precedence.
  • EventStreamIdleTimeout's XML documentation says the shared source keeps reading and the idle window keeps running while a consumer holds an event. The errors guide's exception diagram includes OpenCodeEventSubscriberOverflowException and distinguishes subscriber overflow from retried attempt failures.
  • The terminals guide and PersistentPtyConnectOptions.Takeover's and ConnectAsync's XML documentation say a controller attach without Takeover fails while another attachment controls the terminal: the server closes with 4404 and ConnectAsync throws OpenCodeTransportException, whose message names that case. The attach is not downgraded to an observer.
  • CreateClient's XML documentation on OpenCodeServer and OpenCodeServerConnection, and its refusal message, state the identity rule it enforces: Endpoint and Password must stay null and Username must stay opencode. Every other option the delegate sets, headers and the handler included, is carried into the client.

1.1.0 - 2026-11-14

1.1.0 pins opencode 2.3.0. It is a minor that moves the protocol pin, so two generated types change the way upstream changed them: CredentialUpdated.Data becomes CredentialUpdatedData, and SessionGenerateData gains required Tokens and Cost. Both are listed as breaking under protocol changes. Since opencode 2.2.7 fewer endpoints wait for plugins, and LanguageModels.WaitForDefaultAsync now waits the way opencode's CLI does.

🔌 Protocol changes

  • The SDK pins opencode 2.3.0, where it pinned 2.2.6.
  • Breaking: CredentialUpdated.Data changes from IReadOnlyDictionary<string, JsonElement> to CredentialUpdatedData, because opencode 2.2.7 declares the event's data as the required string members IntegrationId and CredentialId. A reader changes IReadOnlyDictionary<string, JsonElement> data = updated.Data; to CredentialUpdatedData data = updated.Data; and reads those members directly.
  • Breaking: SessionGenerateData gains required TokenUsageInfo Tokens and double Cost, so code that constructs the record sets both alongside Text; the generation's usage counts toward the session's totals.
  • GeneratePredicateQuestion.Criteria accepts a GeneratePredicateQuestionCriteria with optional True and False strings describing the two outcomes.
  • ConfigInfoExperimental.ConsoleWatches exposes the console-watch feature flag.
  • SessionUsageRecordedDataSource.Generate names usage recorded by session generation.
  • ProviderSettings.Tls and ConfigProviderSettings.Tls accept ProviderTls, with required Cert and Key strings and optional Passphrase, for a provider gateway's mutual TLS. The three values are masked in the record's printed form.
  • ToolFreeformFormat names Text, Regex and Lark; ModelCapabilities.Freeform and ConfigModelCapabilities.Freeform list the formats a model supports.
  • ConfigInfoExperimental.McpEvents exposes the MCP-event feature flag.
  • ConfigInfoExperimental.ShellTimeoutBackground exposes the shell-timeout-background feature flag.
  • SessionMessageAssistantTime.FirstToken records when the provider streamed the first output token, in epoch milliseconds, as double?.
  • ExperimentalMcpEvent, with ExperimentalMcpEventData, joins IEvent, and EventType.ExperimentalMcpEvent filters the event subscription to experimental.mcp.event.
  • SessionStepFirstToken, with SessionStepFirstTokenData and SessionStepFirstTokenDurable, joins IEvent, ISessionEventDurable, ISessionLogItem and ISessionScopedEvent; EventType.SessionStepFirstToken filters the event subscription to session.step.first-token.
  • AgentsClient.ListAgentsAsync (agent.list) no longer declares 503, because opencode 2.2.7 answers with the agents loaded so far instead of waiting for plugins. Since 2.2.7 the integration list (integration.list), usage limits (experimental.usage.limits), repository initialization (vcs.init), RPC calls (rpc.call) and the artifact routes (experimental.artifacts.*) do not wait for plugin activation either. Listing models and providers, the default model, web search, and experimental generation and voice still wait up to five seconds.
  • ConfigWarming.Interval defaults to auto at opencode 2.3.0: 90% of the model's cache.ttl, or 4 minutes when the model has none. The default was 4 minutes, and auto skipped models without a ttl. The property's summary says so.
  • A failed persistent-terminal rename (PersistentPtyClient.UpdateAsync with a Title) answers 404 or 503 on opencode 2.3.0. 501 with PtyFeatureUnsupportedError stays declared, but the pinned server no longer answers it.

🔧 Changes

  • LanguageModels.WaitForDefaultAsync now waits the way opencode's CLI does at 2.3.0: it polls the location's plugin list every 25 ms for up to five seconds, until non-empty, then reads the default model once. A failed plugin listing ends the wait without an error, and the read follows. A ServiceUnavailableError from that read now surfaces where it was retried up to twelve times. The call is unchanged: await client.LanguageModels.WaitForDefaultAsync();.
  • OpenCodeServer.StopAsync no longer asks the daemon to shut its persistent terminals down before it ends the process, and makes no request to the daemon at all, as the CLI's service stop does since opencode 2.3.0; ending the daemon still ends its terminals.
  • The status sentence of OpenCodeApiException.Message now includes the server's own message, chosen as opencode's own client chooses it, for example The opencode API returned status 503 ('ServiceUnavailableError'): opencode-pty request timed out.. Error, Status and RawBody are unchanged; code that matched the old message text exactly now sees the longer text whenever the server sends a non-empty message.

📚 Documentation

  • OpenCodeServer.StopAsync's summary says a pid reused after the stop first looked at the process is never signalled, where it said "a pid the operating system reused", and that a service that re-registered after the stop read the registration is never signalled, where it said "before the stop began", and the connection-modes guide says the same.
  • The errors guide names the 401 challenge as WWW-Authenticate: Basic realm="Secure Area", where it said WWW-Authenticate: Basic.

1.0.1 - 2026-11-11

1.0.1 pins opencode 2.2.6 and is built on the GA .NET 11 SDK. It is a patch that moves the protocol pin, so two generated types change the way upstream changed them: ConfigWarming.Interval is now a ConfigWarmingInterval?, and IMcpServerConfig gains Pool. Both are listed as breaking under protocol changes. Disposing a standalone server on Linux and macOS reports exit code 143, where it reported 130. The Important Notes explain the version rule this release follows, which differs from the one 1.0.0 stated.

🔌 Protocol changes

  • The SDK pins opencode 2.2.6, where it pinned 2.2.5.
  • Breaking: ConfigWarming.Interval changes from string? Interval to ConfigWarmingInterval? Interval, because opencode 2.2.6 declares it as "auto" or a duration. A reader changes string? interval = warming.Interval; to string? interval = warming.Interval?.Value;; assigning a non-null string still compiles through the implicit conversion, while a null string? now throws ArgumentNullException where it was a valid value, and ConfigWarmingInterval.Auto names "auto".
  • Breaking: IMcpServerConfig gains bool? Pool { get; }, so a type outside the SDK that implements the interface adds that member. McpLocalConfig.Pool and McpRemoteConfig.Pool set opencode's option to share one connection to a server across every directory that configures it identically.
  • client.Experimental.ListJobsAsync lists the server's active and unconsumed background jobs: JobShell, JobSubagent and JobImage behind IJobInfo. ExperimentalJobListRequest filters them by SessionId, Descendants, Kind and Status.
  • ProviderCache.Warming is a provider's or model's cache warming, which overrides the top-level ConfigWarming: a boolean, or ProviderCacheWarmingSettings with Interval and Duration.
  • client.FileSystem.ReadFileAsync reports FsReadResponse.ContentType as text/plain; charset=utf-8 for HTML, JavaScript and XML files, SVG included, where it reported the file's own type: opencode 2.2.6 serves every file as a download and those types as plain text. The bytes are unchanged; a caller that needs the type reads it from the path.
  • A PTY read throws OpenCodeTransportException naming close status 1012 ("location shut down") when the server shuts the PTY's location down, for example on a reload: opencode 2.2.6 closes the socket that way.
  • SessionClient.CompactAsync and SessionClient.AddSyntheticMessageAsync no longer declare a 404 LocationNotFoundError: opencode 2.2.6 stops resolving a location for these two calls, so a missing session is their only 404.
  • ConfigInfoExperimental gains AllFlags, PartRows and CodemodeVm, the policy actions gain WebsearchUse, and IntegrationAttempt.Paste says an automatic OAuth attempt also accepts the redirect URL pasted from the browser as its code.

🔧 Changes

  • Disposing a standalone server on Linux and macOS now reports Exited with code 143, where it was 130: the pinned opencode 2.2.6 exits with 143 on SIGTERM. SIGINT still exits with 130, and Windows still reports code 1.
  • The packages are built on the GA .NET 11 SDK (11.0.100), where 1.0.0 was built on the go-live release candidate as a one-time exception to the rule that a non-preview package is built only on a GA SDK (ADR-0002).

📚 Documentation

  • The domain glossary is GLOSSARY.md (previously CONTEXT.md), and the getting-started guide points there.
  • OpenCodeServer's and OpenCodeServer.StartAsync's summaries name the two servers outside the Windows job: a batch shim's real server and one whose job assignment Windows refuses, which end with a crashed owner only through the stdin lease.
  • The remark on every generated union and hoisted interface, IMcpServerConfig among them, no longer says that a minor version may move the pin: a release of any bump type may move it (ADR-0034), so the remark now says only that the members change when the SDK moves to a newer pin. Likewise, OpenCodeServerExit.Kind's and OpenCodeServerExitKind's summaries say members may be added in a later version, where they said a minor one: the SDK's own additions are a patch.

📋 Important Notes

  • The version rule differs from the one 1.0.0 stated. A version follows the bump type of the upstream opencode release it pins, where 1.0.0's notes said only a minor moves the pin. A patch such as this one can therefore move the pin and change generated protocol types the way upstream changed them; each such change is listed as breaking under protocol changes. A family marked [Experimental] may change in any release that moves the pin, where it was any minor. The SDK's own fixes and additions are a patch, and a break of the hand-written surface needs a major (ADR-0034). 1.0.0's notes also said 1.0.1 would have no API change; it moves the pin to opencode 2.2.6.

1.0.0 - 2026-11-06

1.0.0: the public surface is stable. From this release, a version's parts say where a change comes from; the Important Notes below explain them. Since 0.9.0-preview.15, LanguageModels.WaitForDefaultAsync waits out a location's plugin activation, and the SDK reads the messages, events and tool states that real use carries through generated readers: on .NET 10, a message of 2,400 parts deserializes about twice as fast and allocates about 40% less, and a captured coding turn's subscription allocates about half as much. The playground shows the SDK running in four apps.

✨ Added

  • client.LanguageModels.WaitForDefaultAsync returns the default model, asking again while the location's plugins activate. On a 503 ServiceUnavailableError it asks again on the schedule opencode's app uses for its boot-time catalog sync: up to twelve attempts, waiting one second after the first and doubling to at most five seconds. Every other failure surfaces at once. It refuses NoThrow at the call, as streams and cursor traversals do.

⚡ Performance

  • Messages deserialize faster and allocate less. On .NET 10, a message of 2,400 parts deserializes in about 8.5 ms instead of about 16.8 ms, a medium one about 47% faster, and a prompt's event frames about 54% faster. Reading that message also allocates 3,086,288 B instead of 5,098,776 B on .NET 10, and 3,086,288 B instead of 5,055,504 B on .NET 11. Messages, their content parts and tool states keep the same values and failure behavior; serialization is unchanged.
  • A prompt's event stream allocates less. Reading 1,024 delta frames and 16 text-ended frames allocates 704,732 B instead of 1,491,796 B on .NET 10, and 704,658 B instead of 1,491,724 B on .NET 11. Materializing the frames alone allocates 663,424 B instead of 1,450,368 B on both runtimes. Values, failure behavior and serialization are unchanged.
  • Real-turn event subscriptions allocate less. Reading a captured coding turn allocates 36,096 B instead of 75,280 B on .NET 10, and 36,024 B instead of 75,208 B on .NET 11. Values, failure behavior and serialization are unchanged.
  • On net472 and netstandard2.0, a response body under 64 MiB, up from 16 MiB, reuses a pooled buffer rather than allocating one per call. A 36 MB body on net472 goes from about 138 MB to about 102 MB per call. As a trade-off, the pool keeps more for the life of the process: at most about 250 MiB, up from about 60 MiB.
  • On net472, .NET 10 and .NET 11, a JSON request body is serialized into a pooled buffer, cleared on return, rather than a new array per call. A prompt with 2 MiB of text goes from about 2.1 MB to about 4 KB on .NET 10; on net472, from about 8.4 MB to about 7 KB, or from about 34 MB to about 25 MB with newlines. As trade-offs, a send holds a larger array than its body while it runs, because the writer reserves about three times the text and the pool rounds up, and on net472 the SDK's pool can now also keep arrays after large requests, within its existing limit.
  • A terminal write allocates less. A keystroke on a PTY or a persistent PTY allocates about 792 B instead of about 1,048 B on .NET 10, and about 1,733 B instead of about 1,910 B on net472.

📚 Documentation

  • The in-repo Sandbox is gone; the playground apps replace it.
  • The guides link to the playground apps that show their features running.
  • HQ's session page opens a terminal in the session's folder, removed from the server when the page ends.
  • HQ's pages no longer prerender, so a click right after a page loads is no longer dropped.
  • HQ shows a sent prompt at once, with "Working..." under it, so a first prompt no longer leaves the page blank while the server loads the session's folder; a prompt the server refuses goes back into the prompt box.
  • HQ answers text and choice questions in place, styles both screens, and shows its real SDK calls in a hideable source panel.
  • Every complete C# snippet in the README and guides is now compiled against the SDK in CI.
  • Correct consumer signatures, streaming examples and terminology, provider setup, experimental opt-ins, installation guidance, and contribution routing. The README has a Playground section and a Versions and support section that states what a version's parts mean.
  • The package descriptions state what each package provides, PersistentPtyResizedFrame's summary says that only ResizeAsync changes the viewport later writes carry, and the security policy names the latest release as the supported line.
  • The Known Issues name a .NET Framework cost: reading a JSON string over 1 MiB that contains an escape, such as a newline, allocates one extra array of its length each time.
  • EnsureAsync warns about a service boot's resume. A service it starts resumes every suspended session on the shared data, including one another process is still running, so both drive it. The connection modes guide says when that matters.
  • A runnable QuickStart sample lives in playground/.
  • HQ shows live sessions, streamed conversations, prompts, permission answers, changed files and new sessions in a chosen directory in Blazor Server with an Aspire AppHost.
  • Worker shows a hosted event-bus subscription and an owned server's failure exit in a Generic Host.
  • AotCli inspects a repository's branch, changed files, top-level entries and config sources as a Native AOT console tool.

📋 Important Notes

  • From 1.0.0, a version's parts say where a change comes from. A patch (1.0.x) carries fixes and additive changes of the SDK's own. A minor (1.x.0) moves the pinned opencode release and may change the generated protocol models the way upstream changed them; its section here lists each such change. Only a major (2.0.0) breaks the hand-written surface. A family upstream marks experimental carries [Experimental] and may change in any minor.
  • 1.0.0 is built on the go-live .NET 11 release-candidate SDK, a one-time exception to the GA-SDK rule; 1.0.1 rebuilds it on the GA SDK with no API change.

0.9.0-preview.15 - 2026-11-01

The SDK speaks opencode 2.2.x and allocates much less. The pinned server moves from 2.1.4 to 2.2.5. That moves the session log to ExperimentalClient, changes several generated protocol models (listed below), and adds experimental schedules, artifacts, image and decision generation, usage limits and file watching, a types filter on the event stream, and renaming of persistent terminals. Open enums become generated extensible enums. On .NET 10, a prompt's event stream allocates about a third less per frame, a one-shot call up to about a quarter less, and a 16 KiB terminal paste about 1 KB instead of about 17 KB; the Performance section has the figures and the two trade-offs.

💥 Breaking changes

  • The upstream pin moves to opencode v2.2.5. Most entries below follow a change upstream made between v2.1.4 and v2.2.5. The open-enum, IMcp, savedPermissionId, OnStart and Optional<T> entries are the SDK's own.
  • The session log moves to ExperimentalClient.ReadSessionLogAsync. Upstream serves it as experimental.session.log, so SessionClient.ReadLogAsync is gone and SessionLogRequest is ExperimentalSessionLogRequest, with the same After and Follow. Migrate client.Sessions.GetSessionClient(id).ReadLogAsync(new SessionLogRequest { … }) to client.Experimental.ReadSessionLogAsync(id, new ExperimentalSessionLogRequest { … }). The session-log types now carry OPENCODE001, the experimental client's diagnostic, and OPENCODE003 is retired: a suppression of OPENCODE003 becomes one of OPENCODE001.
  • ExperimentalClient.SetVoiceSessionInstructionsAsync is removed, with ExperimentalVoiceInstructionsRequest and ExperimentalVoiceInstructionsResponse: upstream removed the operation.
  • EventsClient.SubscribeAsync takes an optional EventSubscribeRequest first. Its Types limits the stream to the listed event types. A call that passed requestOptions by position names it instead: SubscribeAsync(requestOptions: options).
  • Model variants have their own settings type. ModelVariant.Settings is ModelVariantSettings? and ConfigModelVariants.Settings is ConfigModelVariantSettings?, as upstream separates a variant's settings from a model's.
  • VoiceModel.Integration, VoiceModel.Workspace and ExperimentalVoiceSessionData.Session are removed, with VoiceSessionReference: upstream no longer declares them.
  • ConfigInfoCompaction.Buffer is ConfigInfoCompactionBuffer?, not long?. Upstream now accepts a share of the context window such as "20%" besides a token count, so the value is a carrier: Kind says which arm it holds, Text the percentage and WholeNumber the token count. Migrate config.Compaction.Buffer to buffer.WholeNumber after checking buffer.Kind == ConfigInfoCompactionBufferKind.WholeNumber, and set it with ConfigInfoCompactionBuffer.FromWholeNumber(...) or FromText("20%").
  • PersistentPtyInfo.UserTitle is required. It is the title a user gave the terminal, or null when none was given; upstream always sends the key, so a terminal from a server that omits it no longer deserializes, and an initializer that builds a PersistentPtyInfo must set it.
  • PersistentPtyUpdateRequest.Size is optional (PtySize?), no longer required. Code reading it must handle null before accessing its dimensions.
  • Open enums are generated extensible enums, not string. A string enum beside a free string, such as a reasoning field's known names, now binds a generated extensible enum that carries any other value too. ModelCompatibility.ReasoningField and ProviderCompatibility.ReasoningField are ModelReasoningField?, TuiCommandExecuteData.Command is TuiCommandName, ConfigWebSearchInfo.Provider is WebSearchProviderChoice, and SessionInstructionsUpdatedData.Delta's values are SessionInstructionChange. Migrate a comparison with ModelReasoningField.ReasoningContent (or the type's Values strings), and read the text with ToString(); nothing on the wire changes.
  • IMcp is now IMcpServerConfig, and UnknownMcp is now UnknownMcpServerConfig. The union represents one MCP server's configuration, the value type of ConfigInfoMcp.Servers and of ExperimentalMcpAddRequest.Config. Migrate by renaming type references; IMcpTimeout keeps its name, and nothing on the wire changes.
  • PermissionsClient.UpdateSavedAsync takes savedPermissionId. Its route value was a bare id; it now matches RemoveSavedAsync. Only calls that name the argument (id: …) need to change; nothing on the wire changes.
  • OpenCodeServerEnsureOptions.OnStart now takes an OpenCodeServerEnsureStartContext. Action<OpenCodeServerEnsureReason, string?> becomes Action<OpenCodeServerEnsureStartContext>. Migrate (reason, previous) => … to start => … start.Reason … start.PreviousVersion.
  • Optional<T>.Value is annotated [MaybeNull]. Reading an Optional<string> (non-nullable T) may produce a new nullable warning. Migrate a receiving string local to string? and check for null before dereferencing it.

⚡ Performance

Figures are approximate, from short benchmark runs on .NET 10 unless stated.

  • The event stream and the session log read on bytes. The reader no longer builds a UTF-16 string per frame, and it is faster. Its own cost falls from about 5 KB to under 10 B per large frame, and from about 25 KB to about 400 B per enumeration. A prompt's event stream allocates about 1,430 B per frame instead of about 2,210 B, and the largest session-log items about 5,900 B instead of about 11,300 B.
  • A one-shot call allocates up to about a quarter less. About 2,000 B instead of about 2,600 B on a call that doesn't suspend (HttpClient alone takes about 940 B), and about 3,400 B instead of about 3,900 B on one that does. Part of that comes from pooled state-machine boxes on .NET, a saving that shrinks as concurrency grows.
  • A JsonElement dictionary shares one document. A large message allocates about 5.1 MB instead of about 5.5 MB. The trade-off: a value you keep holds the whole dictionary's JSON alive, and Clone() doesn't detach it; JsonElement.Parse(value.GetRawText()) does.
  • On net472 and netstandard2.0, a known union tag allocates no marker string. A large message allocates about 5.2 MB instead of about 5.4 MB on net472.
  • A terminal connection reuses a pooled 16 KiB receive buffer. It rents it from the shared array pool for as long as the connection reads, so a connection after the first usually allocates about 16 KB less.
  • Terminal input reuses a pooled buffer for the message it sends. A 16 KiB paste allocates about 1 KB instead of about 17 KB; a pool miss still allocates one. The buffer is cleared when it goes back to the pool, because input can carry typed secrets, and that isn't a process-memory guarantee: the socket keeps its own buffer. A persistent paste on net472 takes about 3.7 µs instead of about 2.0 µs; how much of that is the clearing wasn't measured.
  • A PtySession frame keeps the UTF-8 it was received as. PtyOutputFrame.Text decodes on its first read, with the same replacement decoding, and every read returns the same string. A queued frame of mostly ASCII output now holds about half what it did; box-drawing and CJK output holds about 1.5 times more, since those characters take 3 bytes in UTF-8 and 2 in UTF-16. The trade-off: the decode moves to the consumer's first read, so draining a queued burst takes longer.

🔧 Changes

  • Rename persistent terminals through PersistentPtyClient.UpdateAsync. Set Title to a non-empty string, or null to clear the user's title; a terminal service that predates renaming answers 501 with PtyFeatureUnsupportedError.
  • Deleting a session now removes its persistent terminals.
  • The operations the refresh adds. ExperimentalClient gains WatchFileAsync, UnwatchFileAsync, GenerateDecisionsAsync, GenerateImagesAsync, GetMediaAsync, GetUsageLimitsAsync, and the schedule operations CreateScheduleAsync, GetScheduleAsync, ListSchedulesAsync, PauseScheduleAsync, ResumeScheduleAsync and DeleteScheduleAsync; PluginsClient gains GetGuiAsync. event.subscribe takes a types filter of EventType values, and model.list takes a types filter. Upstream's legacy text generation endpoint is left out, as both of upstream's own clients leave it out. New members follow upstream too, among them SessionInfoTime.Busy, a Cache setting on models and providers, ConfigInfo.Timezone and VcsDiffRequest.Untracked, and a local plugin's PluginSourceLocal.Path is now the path it was configured with. ExperimentalClient also gains the artifacts operations ListArtifactsAsync, GetArtifactAsync, CreateArtifactAsync, UpdateArtifactAsync, DeleteArtifactAsync, ListArtifactProvidersAsync and GetArtifactFileAsync; they need experimental.artifacts in the location's config. The event stream gains ArtifactUpdated and PersistentPtyUpdated, the error family gains ArtifactNotFoundError and PtyFeatureUnsupportedError, ConfigInfoExperimental gains Artifacts, and policy actions gain integration.connect, mcp.use, skill.use and plugin.use. A schedule's condition is a shell check or a Code Mode script: ScheduleInfo.If and Until are IScheduleCondition?, and ScheduleConditionInput is built with FromScheduleConditionInputRun or FromScheduleConditionInputCode. Other new members include ConfigInfoExperimental.Schedules, MediaBlob and ImageGenerate, PromptInputFileAttachment.Source, ModelCompatibility.MediaInput, ModelInfo.Type, ServerInfo.Hostname, FileDiffInfo.More, McpServer.Title and PluginFeatures.Gui.
  • Clearer IntelliSense documentation. EnumerateSessionsAsync and EnumerateMessagesAsync link their page methods and carry those methods' summaries; server.connected renders as code in SubscribeAsync's remarks.
  • Known stream tags can now arrive as the unknown arm. On event.subscribe and the session log, a frame whose normal decoding fails arrives as UnknownEvent or UnknownSessionLogItem when the existing carrier can preserve it; its neighbours continue on the same connection or request. Invalid JSON and carrier refusals keep their original failures.
  • The streaming guide's "a server upgrade cannot break your event loop" promise is now scoped tolerance, including the payloads that still fail and when a regenerated frame becomes typed.
  • Match stream boundaries on Type. A loop that detects a reconnect with is EventServerConnected or a replay boundary with is EventLogSynced should match Type against "server.connected" or "log.synced" instead: a drifted marker can now arrive as the unknown arm. The same holds for a turn's end ("session.execution.succeeded", "session.execution.failed", "session.execution.interrupted"); the streaming guide's EndsTurn and SessionOf helpers also read the session of an unknown arm from its payload.
  • The event stream's connect-bound failure names its case. Before any response it says "The opencode server did not answer the event stream request within 2 seconds."; when headers arrived but no first event followed it says "The opencode server answered the event stream request but sent no event within 2 seconds." Both replace "The opencode event stream did not connect within 2 seconds."
  • IntelliSense explains the event stream and session members. EventsClient.SubscribeAsync's XML now states the reconnect and termination contract; the session list's archive filter and the two idle timestamps now state their meaning or unit.
  • The guides explain file-system entry path formats and timestamp units, including provider-specific voice expiry and the persistent-PTY handoff's expiry in milliseconds since the Unix epoch.
  • Repeated JSON literals in a JsonElement dictionary no longer compare equal by default. Repeated true, false and null values no longer compare equal under JsonElement's default equality; compare JSON values with JsonElement.DeepEquals, as System.Text.Json recommends.

🐛 Fixes

  • Response envelope logging keeps the page cursor and resolved location. ToString() now includes Cursor and Location when the response has them, so a logged page such as SessionListResponse keeps its continuation token.
  • On Windows, an event stream to a refused loopback port reports the refusal. A .NET connect to a closed loopback port is refused there only after about two seconds, so every attempt ran into the stream's two-second connect bound, and the subscription gave up with "did not connect within 2 seconds", which reads like a slow server. On .NET 5 and later the SDK's own transport now connects loopback targets without SYN retransmission, as upstream's runtime does, and the give-up says "The opencode server could not be reached." with the refusal inside; on .NET Framework the connect keeps its retransmissions and reports through the "did not answer" text.
  • A NUL in a launcher command, environment entry or working directory is refused before the command is resolved. OpenCodeServer.StartAsync refuses a NUL in an OpenCodeServerOptions.Command or OpenCodeServerOptions.Environment entry, or in OpenCodeServerOptions.WorkingDirectory, with ArgumentException before it looks the command up. A bare command name no longer reports first that it was not found on PATH, a working directory is no longer cut short at the NUL, and the exception's ParamName is options, the public parameter, instead of an internal name.
  • A standalone start's failure message keeps at most 8,192 characters of stderr. The stderr tail in an OpenCodeServerException from OpenCodeServer.StartAsync was bounded only to its last 40 lines, so one very long line went into the message whole. The tail now also keeps at most the last 8,192 characters of text, so its size is bounded, as the background-service start's already is.
  • The background-service door refuses a NUL in a command entry. OpenCodeServer.EnsureAsync refused a NUL in an OpenCodeServerEnsureOptions.Environment entry but not in a Command entry, so a command entry with a NUL could reach the contender's spawn and be cut short there. It now refuses it with ArgumentException for options before the registration is read or anything is spawned, as it does for the environment.
  • On Windows, a background service's environment now resolves a key that differs only in case as upstream does. The first spelling in ordinal order wins, whichever side set it. Before, a saved or caller entry always replaced the host's value, so a saved xdg_state_home moved the registration away from clients looking under the host's root. A caller's PATH still replaces the host's Path.
  • A saved XDG_STATE_HOME no longer moves a background service. EnsureAsync used to pass the channel's saved value to the service it spawned, which moved the registration away from every client looking for it. A value saved under that exact spelling is now ignored, as the CLI ignores it; a caller's own Environment entry still applies.
  • A persistent PTY's bad Cwd is now refused. A given Cwd whose path doesn't exist or isn't a directory used to start the terminal in the home directory. The server now answers 400 with an InvalidRequestError whose Kind is invalid_cwd, and no terminal starts. The SDK's code didn't change.

📚 Documentation

  • What an unread terminal costs. The terminals guide now says that a queued frame of either terminal family keeps about 1 byte per byte of output, that an unread session through a verbose build grows by about 15 MB a minute, and that the queue is unbounded as upstream's is.
  • The guides cover more. Connection modes gain exit kinds, the Windows shim's linger, fixed endpoints, cancelled starts and what a server shares or a private launch inherits. New sections cover handing events off from a slow handler, what a shell exit does to a normal PTY read, choosing a model, scoping session lists, and replaying sessions with fork, revert and export.
  • The requests guide and README are corrected. The requests guide fixes four claims: what an unmatched permission rule evaluates to, a worktree's Directory, the collision refusal text, and PersistentPtyHandoff.ExpiresAt. The README now says bodies of 1-16 MiB are pooled on net472 and netstandard2.0.

0.9.0-preview.14 - 2026-10-23

The SDK speaks opencode 2.1.x. The pinned server moves from 2.0.32 to 2.1.4. 0.9.0-preview.13 against a 2.1.x server fails reading compaction messages and loses bus events around them, so a wait for the end of a turn can hang; upgrade the SDK. The upgrade changes several generated protocol models (listed below), adds a heap-snapshot door, saved-permission updates, experimental voice models and instructions, and archived sessions, and makes persistent PTYs work on Windows hosts. The SDK's own transport now drops a connection idle for three seconds, which fixes reuse of a closed socket on .NET Framework, and on macOS a server ended with a whole-tree Process.Kill is now reaped instead of staying a zombie.

💥 Breaking changes

  • Protocol model changes. Recent is removed from compaction messages and event data. ProviderState, State, ResultState and ProviderResultState become Native across assistant messages, parts and turn events. SessionProviderContext and SessionProviderContextProvenance are deleted, along with ProviderContext on completed compaction messages and compaction-ended data; CredentialKey.Configuration is removed. ExperimentalSessionImportRequest.Messages now takes IReadOnlyList<JsonElement>; ToolFileContent.Name and SessionMessageLocationSwitched.Previous lose Optional<>.

✨ Added

  • New protocol doors and members. DebugClient.WriteHeapSnapshotAsync, PermissionsClient.UpdateSavedAsync, and experimental ListVoiceModelsAsync and SetVoiceSessionInstructionsAsync join the surface, and experimental voice session responses gain Session, a VoiceSessionReference. Sessions gain Archived filters and updates and archived/unarchived events; models and provider compatibility gain StreamUsage, structured errors gain RetryAfterMs, and experimental config gains Todo, BackgroundCompaction and LocationIdleTimeout.
  • Persistent PTYs work on Windows hosts. opencode 2.1.x ships the opencode-pty daemon for win32 too, so create no longer answers the daemon-absent 503 there.

🔧 Changes

  • The Windows default background-service port is now 28894. It replaces 45278 for released CLI channels.
  • The SDK's own transport drops a connection that sat idle for three seconds, as upstream's client does. On .NET Framework, an idle connection used to be kept for 100 seconds, long after the server closed it, so a request could pick up a socket the server had already closed. Modern .NET already retired it after four seconds, following the server's Keep-Alive hint, and now does so after three. The netstandard2.0 asset on a modern .NET runtime keeps the four seconds.

🐛 Fixes

  • A server ended with Process.Kill(entireProcessTree: true) is reaped on macOS. That kill stops the server before it kills it, and the launcher took the stop for the exit: the server stayed a zombie of the calling process, a Process wait on its pid never ended, and the launcher reported an unknown exit while the server was only stopped. The launcher now reports the server's real exit and reaps it.

0.9.0-preview.13 - 2026-10-18

The SDK speaks opencode 2.0.32. The pinned server moves from 2.0.29 to 2.0.32. The upgrade brings an experimental voice session, typed reasoning and temperature capabilities on models, and a background service whose saved env wins after startup. On Linux and macOS, StopAsync now returns only once the stopped daemon has been reaped. IntelliSense reaches the members that implement a documented interface. The guides gain a recipe for answering permission asks and question forms, plus the notes that isolating and cleaning up a background service needs.

✨ Added

  • The SDK speaks opencode 2.0.32. ExperimentalClient.CreateVoiceSessionAsync opens an experimental voice session over WebRTC or WebSocket. ConfigModelCapabilities.Reasoning tells a model that does not reason (ConfigModelReasoningUnsupported) from one that does (ConfigModelReasoningSupported, with its toggle, efforts and ConfigModelReasoningBudget); ConfigModelCapabilities.Temperature and ModelCapabilities.Temperature say whether a model takes a temperature, and ConfigModel.ReleaseDate carries its release date.

🔧 Changes

  • A spawned background service's saved env wins after startup. OpenCodeServerEnsureOptions.Environment entries still win over the channel's service-config env at spawn, but a 2.0.32 service re-applies its saved env when it starts, so a key set in both takes the saved value for everything the service reads after startup.

🐛 Fixes

  • Stopping a background service waits for its child process to be reaped. On Linux and macOS, OpenCodeServer.StopAsync no longer returns while the daemon it stopped is still an unreaped zombie of the calling process.
  • IntelliSense reaches implementing members and restores declared halves. Properties that implement a documented interface member (durable envelopes' Seq and Version, the MCP timeouts and Codemode, inbox and compaction Created times) show that member's documentation, and 26 summaries that preview.12 dropped as partly implementation-only return with the part upstream declares. SDK types and runtime behavior are unchanged.

📚 Documentation

  • Isolating a background service needs separate state and config roots. The connection-modes guide now says to give XDG_STATE_HOME and XDG_CONFIG_HOME different directories: the registration and the CLI's service configuration are both named service.json, so one folder for both makes them the same file, and EnsureAsync then fails now and then on Windows with EPERM.
  • A stopped service's files unlock a moment after StopAsync on Windows. The connection-modes guide now says that the daemon's opencode.db-shm and -wal stay locked for a few tens of milliseconds after the call returns, so deleting an isolated data directory right away can fail.
  • The streaming guide answers permission asks and question forms. One recipe covers explicit tool-action rules, one-time approval or rejection, and field-keyed text answers with nullable union-member handling; the requests guide links to it from session permissions.

0.9.0-preview.12 - 2026-10-17

Streams and automatic traversals take per-call options, and the public surface sheds its last loose names before 1.0. SubscribeAsync, ReadLogAsync (formerly GetLogAsync), EnumerateMessagesAsync and EnumerateSessionsAsync accept OpenCodeRequestOptions, so a per-call Location reaches every connection attempt and page request, and EventStreamIdleTimeout sets the event bus's idle window. Query parameters take the types the server reads (bool?, int?, long?), generated enums work in switch and patterns through their Values constants, assistant content has one union type, PTY sizes share PtySize, and OpenCodeRoutes is internal. Cancellation reports your own token at every public async door, disposing the root client interrupts calls and streams with ObjectDisposedException, readiness timeouts keep an outcome recorded before them, IntelliSense states only what the API declares, and on .NET Framework and netstandard2.0 response bodies up to 16 MiB are pooled.

💥 Breaking changes

  • Streams and automatic cursor traversals take per-call options before cancellation. These four virtual method signatures change; recompile consumers and update overrides. Name a token as cancellationToken: token when omitting the new options argument. Calls that omit options keep their behavior. Streams and traversals refuse NoThrow; the event bus also refuses a per-call NetworkTimeout, including Timeout.InfiniteTimeSpan.

    Door Was Now
    EventsClient.SubscribeAsync (CancellationToken cancellationToken = default) (OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default)
    SessionClient.ReadLogAsync (SessionLogRequest? request = null, CancellationToken cancellationToken = default) (SessionLogRequest? request = null, OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default)
    SessionClient.EnumerateMessagesAsync (SessionMessageListRequest? request = null, CancellationToken cancellationToken = default) (SessionMessageListRequest? request = null, OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default)
    SessionsClient.EnumerateSessionsAsync (SessionListRequest? request = null, CancellationToken cancellationToken = default) (SessionListRequest? request = null, OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default)
  • Invalid per-call options name requestOptions in exceptions. An undefined ErrorBehavior on a one-shot call now reports ArgumentOutOfRangeException.ParamName as "requestOptions" rather than "options", and the new stream and traversal refusals name "requestOptions" too.

  • IOpenCodeStreamFailureCause exposes Tag. Every cause in OpenCodeStreamFailureException.Causes exposes its wire tag without a cast, including an unknown cause. Custom test implementations must supply the property. IStreamFailureCause inherits it rather than redeclaring it; concrete causes and their wire representation are unchanged.

  • Instruction-entry DTO names retain Put. ExperimentalSessionInstructionsEntryRequest is now ExperimentalSessionInstructionsEntryPutRequest, and ExperimentalSessionInstructionsEntryResponse is now ExperimentalSessionInstructionsEntryPutResponse. ExperimentalClient.SetSessionInstructionsEntryAsync keeps its method name.

  • The instruction-entry list method names its subject in the plural. ExperimentalClient.ListSessionInstructionsEntryAsync is now ListSessionInstructionsEntriesAsync, and ExperimentalSessionInstructionsEntryListResponse.SessionInstructionsEntry is now SessionInstructionsEntries.

  • The session log uses stream-reading terminology. SessionClient.GetLogAsync is now ReadLogAsync; its request and stream item types and its behavior are unchanged.

  • OpenCodeRoutes is no longer public. Call the typed clients to build and send request paths instead of using route constants or builders directly. Request paths on the wire are unchanged.

  • Assistant content has one union type. Message content and content-updated events use ISessionMessageAssistantContent; the encoded duplicate and its unknown carrier are removed. Existing text, reasoning, and tool records implement the surviving interface. The wire is unchanged.

    Surface Was Now
    SessionMessageContentUpdatedData.Content item ISessionMessageAssistantContentEncoded ISessionMessageAssistantContent
    Unknown assistant-content record UnknownSessionMessageAssistantContentEncoded UnknownSessionMessageAssistantContent
  • PTY requests share PtySize. Replace the three old size names with PtySize. Its Cols and Rows members remain required long values. The persistent requests remain experimental. The pty.update body now writes cols before rows, which the server does not observe.

    Property Was Now
    PtyUpdateRequest.Size PtyUpdateSize? PtySize?
    PersistentPtyCreateRequest.Size PersistentPtyCreateInputSize? PtySize?
    PersistentPtyUpdateRequest.Size PersistentPtyUpdateInputSize PtySize
  • Boolean query parameters use bool?. QueryBoolean is removed. Pass true or false, not QueryBoolean.True or QueryBoolean.False; leave the member null to omit it. The query text remains lowercase true or false.

    Property Was Now
    SessionLogRequest.Follow QueryBoolean? bool?
    SessionInterruptRequest.Resume QueryBoolean? bool?
    ProjectListRequest.Archived QueryBoolean? bool?
    ExperimentalSessionExportRequest.Sanitize QueryBoolean? bool?
  • Numeric query parameters are numbers. The API description declares them as strings, but the server reads each one as a number and upstream's own client takes a number, so the request records now do too. Pass Limit = 50, not Limit = "50". The value still goes out as query text, and the server still enforces its range.

    Property Was Now
    ListRequest.Limit (SessionListRequest, SessionMessageListRequest) string? int?
    FsFindRequest.Limit string? int?
    VcsBranchListRequest.Limit string? int?
    ShellOutputRequest.Limit string? int?
    ShellOutputRequest.Cursor string? long?
    PersistentPtyReadRequest.Lines string? int?
    SessionLogRequest.After string? long?
    SessionDiffRequest.Context string? int?
    VcsDiffRequest.Context string? int?
    ExperimentalSessionStatsRequest.From, .To (milliseconds since the Unix epoch) string? long?
  • OpenCodeApiException and OpenCodeServerException are sealed. They can no longer be used as base classes; their constructors and error data are unchanged.

  • SessionParentFilter is a record with value equality. Filters for the same parent compare equal and have the same hash code, so SessionListRequest records built with equal filters compare equal too. ToString() identifies RootOnly or Of and includes the parent id for Of.

✨ Added

  • Per-call Location applies to streams and automatic cursor traversals. Pass OpenCodeRequestOptions to override the ambient directory on every stream connection attempt or every page request. The server still ignores the header on routes that resolve a session's location or need no location; it does not filter the global event bus. A per-call NetworkTimeout bounds only opening the session log, and bounds each page request separately on a traversal, not the whole walk.

  • OpenCodeClientOptions.EventStreamIdleTimeout sets the event bus's idle window, as upstream's own client allows. A connection that receives nothing for that long is replaced; the default stays 45 seconds. Keep it above the server's 15-second keepalive. Any window above zero and at most int.MaxValue milliseconds is accepted, but not Timeout.InfiniteTimeSpan: a bus that never times out would hang on a half-open connection. The 2-second connect bound and the 1-second delay before a new attempt stay fixed.

  • Enum values work in switch and in patterns. Every generated enum carries its pinned wire spellings as const string members of a nested Values class, and a Value property that returns a value's spelling. Match one against the other in a case label or a property pattern; a value a newer server sends matches none of them:

    switch (mode.Value) { case VcsMode.Values.Committed: /* … */ break; }
    if (rule is { Effect.Value: PermissionEffect.Values.Allow }) { /* … */ }

    Nothing else changes: the static properties, ==, IsKnown and the wire format stay as they were.

🔧 Changes

  • On .NET Framework and netstandard2.0, response bodies between 1 and 16 MiB are pooled instead of allocated on every call. The SDK then typically keeps one buffer per size class it has used, at most about 60 MiB after large responses; bodies above 16 MiB still allocate.

🐛 Fixes

  • IntelliSense documents declared units, defaults and family roles. Documentation inferred only from server implementation is removed; SDK types and runtime behavior are unchanged.
  • Generated XML summaries use grammatical prose. Articles and brand spellings are corrected, digits stay attached to their words, and members named Value read "Gets the value."
  • A background-service start failure no longer carries part of the PTY handoff ticket. The contender's stderr tail redacts the ticket even where the 8 KiB cut or the end of the pipe splits it, so no fragment of it reaches OpenCodeServerException messages.
  • Caller cancellation preserves your token across public async doors: HTTP, SSE, cursor traversal, both terminal families, and OpenCodeServer.StartAsync, DiscoverAsync, EnsureAsync, and StopAsync. OperationCanceledException.CancellationToken is the token you supplied at either entry point, including the same token at both enumeration entry points; two distinct cancellable tokens are observed without an identity guarantee.
  • A caller token already canceled at the launch boundary prevents the server process from starting.
  • Readiness timeouts preserve recorded outcomes: a readiness line, root exit, or stdout end recorded before timeout arbitration is reported instead of a timeout. Cancellation arriving only during teardown does not replace the selected failure.
  • POSIX pipe-creation failures throw OpenCodeServerException naming the command, with the underlying IOException retained.
  • Malformed PTY-handoff sidecar and ticket documents are refused, including trailing garbage or a second JSON value; trailing whitespace remains valid.
  • Endpoints with a query, fragment, or user info no longer escape best-effort service shutdown and handoff paths, so endpoint refusal does not prevent termination or replacement.
  • Disposing the root client interrupts HTTP calls and SSE streams with ObjectDisposedException, rather than misreporting a transport timeout. Caller cancellation already observed takes precedence; terminal sessions keep their separate ownership and disposal rules.
  • SSE releases its live response on cancellation or client disposal on every target, even while your code holds an event. A suspended enumeration reports the exception on its next pull.
  • A stream positioned past its end uploads zero bytes, with a zero Content-Length when it can seek, without rewinding or disposing the caller's stream.
  • Malformed PTY cursor control documents are refused, including truncation after the cursor value, trailing garbage, or a second JSON value. Trailing whitespace remains valid.
  • AddOpenCode keeps existing client registrations. Calling it again does not add another OpenCodeClient or sub-client registration. A consumer's earlier registration of the root client or any sub-client wins; missing sub-clients are resolved from the registered root client.

0.9.0-preview.11 - 2026-10-15

The event bus reconnects the way upstream's own client does, and the calls that answer only when their work ends now wait for it. EventsClient.SubscribeAsync replaces a dropped, failed or silent connection one second later, starts every connection with EventServerConnected, and gives up after one minute in which every attempt failed, so a wrong address or password surfaces after a minute rather than at once. NetworkTimeout sets how long a call may go without network progress, and WaitForSessionAsync, RunShellCommandAsync, RunCommandAsync and GenerateTextAsync wait with no window. The other breaking changes: generated string enums are extensible value types, the upstream-experimental surface is [Experimental] and needs an opt-in, and OAuth, shellId and savedPermissionId are spelled as they should be. Events that belong to a session implement ISessionScopedEvent, the generated XML documentation says what each record is, the guides carry the fixes from the preview.10 evaluation, and on Windows the background service's sidecar publishes even while another process reads it.

💥 Breaking changes

  • EventsClient.SubscribeAsync reconnects, as upstream's client does.

    • A connection that drops, fails, or receives nothing for 45 seconds is replaced one second later. Every failure counts: an HTTP error status, a malformed frame, a failure frame and the server ending the stream included.
    • Each connection has 2 seconds to answer and deliver its first event, so a server consistently slower than that fails every attempt.
    • Each connection starts with EventServerConnected, and the SDK fails one that does not. A second one means the events in between were missed.
    • The stream no longer ends on its own. Your token, disposing the client, or one minute in which every attempt failed ends it; the minute throws the last failure.
    • What changes for you: a wrong address or a refused password surfaces after one minute, not at once, and code that expected the stream to end when the server went away now sees a new EventServerConnected instead. OpenCodeClientOptions.NetworkTimeout no longer reaches the bus.
  • The upstream-experimental surface is marked [Experimental]. Every member that calls an operation upstream serves under /api/experimental/, and every type only those operations use, now reports a diagnostic when you use it. It is a compile error until you opt in with #pragma warning disable or <NoWarn> for its id:

    • OPENCODE001: client.Experimental (ExperimentalClient);
    • OPENCODE002: the persistent-PTY family (client.PersistentPtys, its handle, connect door, session, options and frames);
    • OPENCODE003: the Session family's experimental operations, today SessionClient.GetLogAsync.

    Nothing on the wire changes. See Experimental APIs. Waiting for a turn on the event bus, as the getting-started guide shows, needs no opt-in.

  • Every generated name spells OAuth as the brand does. Names built from operation ids and wire members said Oauth, beside the schema-derived CredentialOAuth and McpOAuthConfig. They are now BeginOAuthConnectionAsync, CancelOAuthConnectionAsync, CompleteOAuthConnectionAsync, GetOAuthStatusAsync, the IntegrationOAuth* request and response types with their OAuthConnect and OAuthStatus members, McpRemoteConfigOAuth (with its Kind), the OpenCodeRoutes builders and templates, and the OAuth value of ConnectionCredentialInfoMethod. Rename the uses; nothing on the wire changes.

  • The shell and saved-permission ids have descriptive parameter names.

    • ShellsClient.GetShellClient, and the OpenCodeRoutes.Shells builders, take shellId.
    • PermissionsClient.RemoveSavedAsync and OpenCodeRoutes.Permissions.RemoveSaved take savedPermissionId.
    • Before, both were a bare id. Only a call that named the argument (id: …) changes.
  • Generated string enums are extensible value types (ADR-0035).

    • Every enum the API defines, such as VcsMode, PermissionEffect, SessionInboxDelivery and AgentInfoMode, is now a readonly struct, not a C# enum.

    • Previously a server newer than the SDK broke reading whenever it sent a value the SDK did not know, on a response or on an event stream frame. That value now reads as it was sent, and it is written back unchanged.

    • The pinned values are static properties with the same names, so VcsMode.Committed still compiles.

    • IsKnown reports whether this SDK's pin defines a value. new VcsMode("…"), the implicit conversion from string, and FromString create a value from any spelling.

    • Equality is ordinal.

    • ToString() now returns the wire spelling (running), not the C# member name (Running). Logs and string comparisons built on it change.

    • A default value has no spelling. A request body or query refuses it.

    • What breaks: enum values used as constant patterns, and code that relied on enum behaviour (numeric casts, Enum.GetValues, [Flags]). Compare with == instead:

      // Before
      switch (mode) { case VcsMode.Committed: /* … */ break; }
      if (rule is { Effect: PermissionEffect.Allow }) { /* … */ }
      
      // After
      if (mode == VcsMode.Committed) { /* … */ }
      if (rule.Effect == PermissionEffect.Allow) { /* … */ }

✨ Added

  • ISessionScopedEvent routes an event by its session. Every event whose payload names the session it happened in (58 at the pin: the session.* events, permission.asked/replied, persistent-pty.added/removed and tui.session.select) implements it, so e is ISessionScopedEvent { SessionId: var id } replaces a switch over every type. The member is implemented explicitly, so the events gain no public member and serialize as before. The form events are not session-scoped: a form's session id can be "global".

  • NetworkTimeout sets how long a call may go without network progress. OpenCodeClientOptions.NetworkTimeout sets it for the client and OpenCodeRequestOptions.NetworkTimeout for one call; the default stays 100 seconds. WaitForSessionAsync, RunShellCommandAsync, RunCommandAsync and both GenerateTextAsync methods (on SessionClient and ExperimentalClient) answer only when their work ends, so they now wait with no window and the call's cancellation token is their deadline; before, each failed after 100 seconds without headers, and a shell command kept running on the server. A client-wide value does not reach them; a per-call value does. OpenCodeServer.CreateClient carries the client value over. See Requests.

🔧 Changes

  • Generated XML documentation says what each record is. The pinned API describes almost none of its schemas, so summaries now come from the wire: an event record names its event type, its payload names the event it belongs to, an operation's body, response and query records name the operation with its method and route, and an error record names its tag. The types builders found hardest carry hand-written summaries from upstream's behaviour: assistant messages and their finish, error and retry; text deltas and their end; the prompt and create requests; the execution events; and a PTY's command and arguments, including which shell starts when the command is absent.
  • The package README links open the docs of the release they came with. On NuGet.org, the links to the guides point at the commit the package was built from, not at master.
  • The hosting internals join the flat OpenCode.Sdk.Internal namespace. The public API is unchanged, byte for byte; only internal type names differ, as a stack trace or reflection shows them.

🐛 Fixes

  • An event stream no longer ends on an enum value the SDK does not know. Before, a frame with such a value, such as a new reason on session.execution.interrupted, failed to materialize and ended the subscription with OpenCodeTransportException. The frame now reads as its typed event, with the value kept (IsKnown is false). One-shot responses read the same way. See the Breaking entry on extensible enums.
  • On Windows, publishing the background service's sidecar no longer fails while another process reads it. The sidecar was replaced with a rename that Windows refuses with access denied while a reader holds the file open. It is now replaced with a POSIX-semantics rename, which succeeds even then, and falls back to the previous rename where the file system does not support it.

📚 Documentation

  • The streaming guide streams an answer as it arrives. The recipe follows upstream's own client:
    • wait for EventServerConnected before you prompt;
    • prompt with your own msg_ id, and match it to SessionInboxDelivered's InboxId;
    • append SessionTextDelta text, and replace it with SessionTextEnded's final Text;
    • stop on the session's execution event.
  • The requests guide names the session-create location. SessionCreateRequest.Location is a body LocationPublicRef, not the LocationSelector that headers and queries use. The guide also shows that a collection expression cannot fill an Optional collection member (CS9174).
  • The terminals guide documents the two normal-PTY gaps. It says which shell a PTY gets without a Command: the configured shell, then $SHELL, then a per-OS fallback. It also shows how to resize a normal PTY, through PtyClient.UpdateAsync with Size.
  • The connection guide keeps a launched server around a host, and fixes the 401.
    • A launched server stays in await using around the host's RunAsync. The container does not dispose a handle you register.
    • A passwordless 401 carries the typed UnauthorizedError, not an empty body.
  • The guides wait for a turn on the execution events, not on SessionIdle. The pinned server never publishes session.idle or session.status, so a loop that waited for SessionIdle never ended. A turn ends with exactly one of SessionExecutionSucceeded, SessionExecutionFailed or SessionExecutionInterrupted.

📋 Important Notes

  • This release is built on the .NET 11 release-candidate SDK. A preview package may build on a go-live release candidate (ADR-0002); the first non-preview package waits for the GA SDK. The net11.0 asset needs the .NET 11 runtime, and a net10.0 app keeps using the net10.0 asset.

0.9.0-preview.10 - 2026-10-14

The packages target netstandard2.0, net472, net10.0, and net11.0: net8.0 and net9.0 leave ahead of their end of support, and net11.0 joins on its go-live release candidate. A project on .NET 8 or 9 still installs the packages through the netstandard2.0 asset, now with a build warning. The pin moves to upstream release tag v2.0.29, which adds provider compatibility defaults, request-body encoding and top-level config policies. OpenCodeServer.Exited reports how a started server ended, and on Windows a server's exit is observed on the operating system's own wait thread, so a busy host no longer reports a crashed start as a closed stdout. The breaking changes come first: besides the target frameworks, OpenCodeServerOptions refuses an out-of-range timeout when it is set, IOpenCodeClientOptions is removed, OpenCodeStreamFailureException.Cause is now Causes, and PersistentPtyReplayBounds takes camelCase constructor parameters.

💥 Breaking changes

  • The packages target netstandard2.0, net472, net10.0, and net11.0. net8.0 and net9.0 leave ahead of their end of support on 2026-11-10, and net11.0 joins on its go-live release candidate. 0.9.0-preview.9 is the last version with net8.0 and net9.0 assets. A net8.0 or net9.0 project still installs the packages through the netstandard2.0 asset, now with a build warning, because that runtime is not one the packages are tested on; set <SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings> to silence it, or move the project to net10.0 or later. A project that treats warnings as errors fails its build on it until it does one or the other.
  • OpenCodeServerOptions refuses an out-of-range timeout when it is set. ReadinessTimeout takes a value above zero and at most int.MaxValue milliseconds, or Timeout.InfiniteTimeSpan to wait until the start's cancellation token fires; GracefulShutdownTimeout takes zero to int.MaxValue milliseconds. A value outside that range throws ArgumentOutOfRangeException from the setter. A zero or negative readiness timeout and a negative grace were refused by OpenCodeServer.StartAsync before; a value past the ceiling was accepted and failed only after the server had been spawned.
  • IOpenCodeClientOptions is removed. No public API accepted it, and every option added later would have broken its implementers, because net472 and netstandard2.0 have no default interface members. Configure clients through OpenCodeClientOptions, which a client still snapshots at construction. Code that declared a variable or parameter as IOpenCodeClientOptions uses OpenCodeClientOptions instead.
  • OpenCodeStreamFailureException.Cause is now Causes. It is a list of causes, so the name is now plural. The constructor parameter is now causes as well. Read failure.Causes where you read failure.Cause, and pass causes: where you named the argument.
  • PersistentPtyReplayBounds takes camelCase constructor parameters. They are requestedOffset, availableOffset, endOffset and truncated, like the other frame types' constructors. The properties keep their names, and positional construction, with and deconstruction are unchanged. Only a call that named an argument (RequestedOffset: 0) changes.

✨ Added

  • OpenCodeServer.Exited reports how a started server ended. The task completes with an OpenCodeServerExit. It holds an exit code (on Windows the full 32-bit code), a terminating signal by name and number, or Unknown when the exit status could not be read, for example because something else reaped the server. It completes whether the server ended on its own or disposal ended it, once its output has ended or one second after the exit, as upstream's exited does. It never faults. On a handle from DiscoverAsync or EnsureAsync it throws InvalidOperationException, because that handle owns no process.
  • The accepted snapshot moved to upstream release tag v2.0.29 (042d0832f5f3a73eaa039a58a7d565776f6d4290), published as @opencode/cli@2.0.29; install it with npm install -g @opencode/cli@2.0.29. It adds and changes no operation, so all 142 remain callable.
  • Provider compatibility defaults. ProviderInfo.Compatibility and ConfigProvider.Compatibility carry a ProviderCompatibility, the defaults a provider's models inherit: ReasoningField, RequireReasoning, MaxTokensField, RequireFinishReason, RequireAssistantAfterTool, SupportsPromptCacheKey, and CacheFormat.
  • Prompt-cache marker format. ModelCompatibility.CacheFormat and ProviderCompatibility.CacheFormat name the marker syntax the endpoint accepts, as the new ModelCacheFormat enum (Anthropic, Alibaba).
  • Request-body encoding. ProviderSettings.Encoding, ConfigProviderSettings.Encoding, ModelSettings.Encoding, and ConfigModelSettings.Encoding name the compression upstream applies to the provider request body, as the new ProviderEncoding enum (Zstd, Gzip, None).
  • Top-level config policies. ConfigInfo.Policies carries the ordered policies that control access to providers, tools, and integrations, as the new ConfigInfoPolicies (Action, Resource, Effect) with the new ConfigInfoPoliciesAction (ProviderUse, ToolUse, IntegrationUse) and ConfigInfoPoliciesEffect (Allow, Deny) enums. Upstream deprecates experimental.policies: a 2.0.29 server reports those policies here, and ConfigInfoExperimental.Policies stays null.

🔧 Changes

  • The packages depend on the .NET 10.0.13 servicing builds of their dependencies. OpenCodeDotNet.Sdk requires System.Text.Json, Microsoft.Bcl.AsyncInterfaces, Microsoft.Bcl.Memory, Microsoft.Bcl.TimeProvider, System.Collections.Immutable, and System.Threading.Channels 10.0.13 on netstandard2.0 and net472, up from 10.0.11; its net10.0 and net11.0 assets declare no dependency. OpenCodeDotNet.Sdk.Extensions requires Microsoft.Extensions.DependencyInjection.Abstractions and Microsoft.Extensions.Options.ConfigurationExtensions 10.0.13 on every target, up from 10.0.10. No security advisory covers the versions they replace. A project that references one of these packages directly at a lower version must raise it, or restore reports a package downgrade (NU1605, an error by default).
  • A server that does not report readiness in time fails with the timeout as the inner exception. The OpenCodeServerException that OpenCodeServer.StartAsync throws then carries the readiness bound's OperationCanceledException as its InnerException, which was null.
  • A settings encoding member is read as the typed Encoding. On ProviderSettings, ConfigProviderSettings, ModelSettings, and ConfigModelSettings it is no longer in AdditionalProperties, where 0.9.0-preview.9 kept it as an undeclared member.
  • The source is laid out in feature folders, and the shared internal namespaces are flattened into OpenCode.Sdk.Internal. The public API is unchanged, byte for byte. Only the names of internal types differ, as a stack trace or reflection shows them.

🐛 Fixes

  • On a busy Windows host, a server's exit is no longer reported late. The launcher learned of a Windows server's exit through a callback queued to the .NET thread pool, so under load it could arrive seconds after the server had exited. A server that exited before readiness then failed its start as one that closed its stdout, without its exit code; OpenCodeServer.Exited completed late; and ending a server that had already exited could still end the descendants it left running. The exit is now observed on the operating system's own wait thread, as libuv observes it, so each of these reads the exit as soon as the kernel reports it.
  • OpenCodeServer.EnsureAsync started through a .cmd or .bat shim on Windows opens no console window. With a batch shim such as npm's opencode.cmd as the command, the background service took a new console of its own, with a visible terminal window that took the focus and stayed open for the service's life, and its startup output went to that window instead of to the SDK. The shim now starts with a console that has no window, which the service inherits, so its window stays hidden and its startup output reaches the SDK again. A service started from an .exe still starts detached, with no console.
  • On Unix under Mono, a failed chmod of an owner-only file fails its write. The netstandard2.0 and net472 assets set mode 0600 on the files discovery and EnsureAsync write through a chmod child process after the create. That process now receives a quoted path, and a nonzero exit removes the file and fails the create, as the modern targets' atomic owner-only create does. Behaviour change: such a file was kept at the process umask before.

📋 Important Notes

  • This release is built on the .NET 11 release-candidate SDK. A preview package may build on a go-live release candidate (ADR-0002); the first non-preview package waits for the GA SDK. The net11.0 asset needs the .NET 11 runtime, and a net10.0 app keeps using the net10.0 asset.
  • From 1.0.0, a minor version may move the protocol pin and change the generated surface the way upstream changed it, each change listed under protocol changes; only a major version breaks the hand-written design (ADR-0034).

0.9.0-preview.9 - 2026-10-13

The pin moves to upstream release tag v2.0.27, and all 142 operations it exposes are callable — 140 as generated HTTP calls, and the two terminal WebSocket connections through hand-written transports. Upstream 2.0.27 moves to Effect 4.0.1, which renames the stream failure frame, and project.list takes an archived filter, which makes its route helper a method; the two breaking changes come first. A project records when it was archived, an idle message carries the error of a failed turn, fs.list answers a missing directory with a typed FileNotFoundError, and the background-service config reader validates remoteAccepted as the CLI does. Discovery reads a refused connection as no service even when its bound expires at the same moment. net8.0 and net9.0 still leave in an upcoming preview; see the important notes.

💥 Breaking changes

  • A mid-stream failure is recognized under upstream 2.0.27's frame name. Upstream 2.0.27 moves to Effect 4.0.1, which renames the reserved failure frame from effect/httpapi/stream/failure to effect/http-api/stream/failure. Against a 2.0.27 server a failure on EventsClient or the session log surfaces as OpenCodeStreamFailureException with its typed causes; against an older server it surfaces as OpenCodeTransportException naming the undeclared frame. On 0.9.0-preview.8 it was the other way round.
  • OpenCodeRoutes.Projects.ListProjects is now a method. project.list takes an optional archived query, so the route helper is ListProjects(ProjectListRequest? request = null) and the template constant is ListProjectsTemplate. ProjectsClient.ListProjectsAsync gains a leading optional ProjectListRequest? request parameter: a call that passes requestOptions positionally moves it one place, and the change needs a recompile.

✨ Added

  • The accepted snapshot moved to upstream release tag v2.0.27 (1f4d07a4a519185955ae8ab2ea3607805509e386), published as @opencode/cli@2.0.27; install it with npm install -g @opencode/cli@2.0.27.
  • Archived projects. Upstream 2.0.27 archives a project whose known directories are all gone and unarchives it when it is resolved again. ProjectTime.Archived carries when it was archived, and project.list leaves archived projects out unless ProjectListRequest.Archived is QueryBoolean.True.
  • SessionMessageIdle.Error carries the SessionStructuredError of a turn that went idle with a failed outcome.

🔧 Changes

  • The netstandard2.0 and net472 assets depend on Microsoft.Bcl.TimeProvider. The request progress window and the standalone launcher's output drain now run on TimeProvider, which net8.0 and later carry inbox. Behaviour does not change: both still run on the system clock.
  • The background-service config reader validates remoteAccepted as upstream 2.0.27 decodes it. The CLI records an accepted remote access as the literal true; a document whose remoteAccepted is anything else is no config at all, so its env overlay and the legacy migration it gates do not apply, as in the CLI.
  • A 2.0.27 server that stops or fails while a terminal is connected closes it with 1001 or 1011, which reads as an abnormal close. When the server stops, or a handler fails, before it queues its own close on a pty.connect or persistent-terminal connection, it now closes with 1001 or 1011, which PtySession and PersistentPtySession report as an abnormal close (OpenCodeTransportException), as upstream's own terminal clients do. A 2.0.26 server sent a close frame with no status there, which read as a normal end.
  • FileSystemClient.ListEntriesAsync reports a missing directory as the typed FileNotFoundError, which upstream 2.0.27 now answers, and declares on fs.list's 404 beside LocationNotFoundError; an older server answered an undeclared server error.

🐛 Fixes

  • OpenCodeServer.DiscoverAsync and EnsureAsync read a refused connection as no service even when the probe's two-second bound expires at the same moment. On a loaded machine the bound could expire after the runtime had already seen the daemon's port refuse the connect, and the probe then reported a timeout for a daemon that was gone. A refused connection now decides whatever the bound says; any other failure still counts as a timeout exactly when the bound expired. Behaviour change: fewer spurious timeouts under load, so Ensure less often counts a dead daemon toward the three timeouts that end a registered service, and starts a contender after the spawn delay instead.

📋 Important Notes

  • net8.0 and net9.0 leave the packages, and net11.0 joins, in an upcoming preview, ahead of their end of support on 2026-11-10; this release still ships them. The packages will then target netstandard2.0;net472;net10.0;net11.0. An app on .NET 8 or 9 still installs through the netstandard2.0 asset, but that asset is a compatibility asset, not a supported runtime: support and testing cover the targeted runtimes only, and .NET 5–7 are not supported. Plan the move to .NET 10.
  • Upstream's committed OpenAPI document matches its own generator at v2.0.27. The stale copy that 0.9.0-preview.8 noted is current again, so a diff against it no longer shows operations or errors this SDK has and that document lacks.

0.9.0-preview.8 - 2026-10-09

The pin moves to upstream release tag v2.0.26, and all 142 operations it exposes are callable — 140 as generated HTTP calls, and the two terminal WebSocket connections through hand-written transports. An integration can connect through an external credential source, and a 2.0.26 server's external credentials now decode; the experimental policy action permission is renamed tool.use, the one breaking change, which comes first. On Windows a standalone server now runs as upstream's launcher runs it: created suspended in a kill-on-close job, so it ends with its owner however the owner ends; given its three standard handles and nothing else; read through overlapped pipes; and ended at once with taskkill /T /F. net8.0 and net9.0 still leave in an upcoming preview; see the important notes.

💥 Breaking changes

  • ConfigInfoExperimentalPoliciesAction.Permission is now ToolUse. Upstream 2.0.26 renames the experimental policy action permission to tool.use and adds integration.use, which gates MCP servers and skills, so the enum's members are ProviderUse, ToolUse, and IntegrationUse. A 2.0.26 server drops a permission policy entry when it loads its config; against an older server whose config still has one, reading the config fails to decode.

✨ Added

  • The accepted snapshot moved to upstream release tag v2.0.26 (9b4ec5714d481559990db0a816d5dec19541a814), published as @opencode/cli@2.0.26; install it with npm install -g @opencode/cli@2.0.26.
  • An integration can be connected through an external credential source. IntegrationClient.ConnectWithExternalCredentialsAsync(request) (integration.connect.external) runs an external authentication method, named by MethodId with an optional form Answer and Label, and stores a reference to its credential source. The integration lists such a method as IntegrationExternalMethod, and the stored credential reads as CredentialExternal (MethodId, Metadata). The route helper is OpenCodeRoutes.Integrations.ConnectWithExternalCredentials. Behaviour change: on 0.9.0-preview.7 a 2.0.26 server's external method surfaced as UnknownIntegrationMethod, and its external credential value as UnknownCredentialValue.
  • ConnectionCredentialInfoMethod.External names a credential stored through an external method. Before, a server that returned one failed the decode of its connection.
  • ModelCompatibility.SupportsThinkingBlockBinding and SupportsEffortUpdates carry the two compatibility flags upstream 2.0.26 adds.

🔧 Changes

  • On Windows a standalone server is placed in a job that ends it with its owner, however the owner ends. StartAsync creates the server suspended, places it in a process-wide job that ends it when the host process exits, and only then lets it run, as upstream's launcher places its server in a job. Behaviour change: a server that ignores the end-of-stream of its stdin no longer outlives an owner that crashed or was killed before disposing it. Descendants the server starts detached stay outside the job and keep running; the other children of a server built on Bun or Node end with it, because its runtime places them in a job of its own under the launcher's. The job also ends a server that crashes on an unhandled exception at once, without a Windows Error Reporting dialog, as upstream's job does, and any window the server opens starts hidden. A server the kernel refuses to place in the job with ERROR_ACCESS_DENIED, as under a host job that cannot nest, runs outside it, as upstream's does, and then ends with a crashed owner only through its stdin lease. Any other refusal, a job that cannot be created, and a server that cannot be resumed fail the start with OpenCodeServerException and leave nothing running.
  • With the default npm install, pass the path of opencode.exe in Command for that guarantee. The bare opencode resolves to npm's opencode.cmd shim, which runs through cmd.exe: the job then holds cmd.exe, and the real server, cmd.exe's child, ends with a crashed owner only through its stdin lease, as upstream's own launcher of a .cmd file arranges it.
  • Disposing a standalone server on Windows ends the server and its whole process tree at once with taskkill /T /F, as upstream does, instead of closing its stdin and waiting. Behaviour changes:
    • The server no longer runs its own graceful shutdown on disposal: it exits with code 1, where the stdin end-of-stream used to end it with code 0. Stdin now closes last, as on Linux and macOS, so an Output collector no longer receives the lines a server writes when its stdin ends.
    • Every live descendant of the server is ended at every close, detached ones included; the descendants used to survive a normal close.
    • Disposal takes the taskkill run, about 300 ms, where a server that left on its stdin's end-of-stream used to take about 10 ms.
    • GracefulShutdownTimeout now starts with that first kill and bounds it: when the server is still running at its end, the same kill runs once more, and TerminateProcess ends the server with code 1 when a kill fails. A disposal takes at most the grace plus 26 seconds, the output drain and the release of the output readers included.
    • On net8.0 and later the forced end is taskkill, exit code 1, where it was the runtime's tree kill, exit code -1.
    • A server that already exited is not tree-killed, and a failed start ends the server the same way, with the configured grace, so a canceled or timed-out StartAsync can take up to the grace plus 26 seconds to throw.
    • On net8.0 and later the descendants of a server that exits before readiness are no longer ended: the runtime's tree kill used to end them, but taskkill reaches no descendant of an exited root, so it does not run.
  • On Windows the server no longer inherits the host's own inheritable handles. It receives its three standard handles and nothing else, so a parent process that captures the host's output sees it end when the host exits, even while a server it started still runs. Behaviour change: the server also no longer receives the handles the host inherited from its own ancestors.
  • On Windows the server's output is read without a dedicated thread, on every target. Its stdout and stderr are overlapped pipes whose reads complete on the I/O completion port, on .NET Framework too; the two reader threads each server used to hold are gone.
  • StartAsync on Windows fails at once when the server closes its stdout before readiness and keeps running, as on Linux and macOS, where it used to wait for the readiness timeout. A readiness line that arrives together with the exit now always starts the server, where the exit could win before. A server that exits before readiness while a process it started holds its stdout fails the start after a drain of at most one second instead of two.
  • A negative Windows exit code is reported with its hexadecimal form. A server that crashes before readiness is reported as exited with code -1073741819 (0xC0000005), where the message used to give only the decimal value.
  • A whitespace-only WorkingDirectory counts as none on Windows too. The server then starts in the host's directory, as on Linux and macOS, where the blank value used to be passed to the process start as the server's directory.
  • OPENCODE_PRINT_LOGS=1 in the host's environment hands the server the host's own stderr on Windows too, as upstream's launcher does; no stderr is then collected or quoted in a startup failure. Diagnostics-mode behaviour, as upstream's: the server then also shares the host's console, so a Ctrl+C in that console reaches the server, even when the host handles it.
  • A NUL in a command entry or an environment entry is refused with ArgumentException on Windows too, before anything is spawned, and a spawn that fails in a WorkingDirectory names the directory.
  • StopAsync and the Ensure replacement act on the service registered when they stop it. Like upstream's client, they read the registration again before preparing or clearing the terminal handoff, and end the service that file names then. Behaviour change: a service that registered while StopAsync was asking the old one to shut its terminals down is the one stopped, where it used to be left running.
  • The service config's remote key is read as upstream reads it. Remote access is set only through the CLI (opencode service set remote true, or opencode pair --remote); the SDK reads the key and never writes it. While the service's tunnel is attached, its remote URL is listed in ServerInfo.Urls. Behaviour change: a remote that is neither an object holding a string route nor the legacy boolean makes the whole document no config, as upstream decides, so its env overlay no longer applies, and a document with a legacy boolean still reads but is no longer migrated to a named channel's file; 0.9.0-preview.7 ignored remote in both cases.
  • A PTY connect refused with HTTP 401 or 403 names the credential or the origin. Upstream 2.0.26 checks the request's origin on every connect, before it looks the PTY up. Behaviour change: the OpenCodeTransportException message now ends "the request's credential or origin was rejected", as the persistent PTY's message already did, and a refused origin is reported as such even for a PTY that does not exist.
  • FileSystem.ReadFileAsync with a path that leaves the location answers the declared 404 with a typed FileNotFoundError. Upstream 2.0.26 refuses such a path, and one it cannot decode, as a missing file. Behaviour change: the status is 404, not an undeclared 5xx, and Error is a FileNotFoundError.
  • A server bound to every interface lists its loopback URL first in ServerInfo.Urls. Upstream 2.0.26 puts http://127.0.0.1:{port} (or http://[::1]:{port}) before the interface addresses of a server bound to 0.0.0.0 or ::.

🐛 Fixes

  • OpenCodeServer.EnsureAsync starts the background service on Windows the way upstream's client does: detached, with no console, and hidden. The service it started had a windowless console of its own instead, and no hidden show state for a window it might open. It now starts with no console at all, still in a process group of its own, and with any window it opens starting hidden. Behaviour change: the background service an Ensure call starts on Windows no longer has a console.
  • The background service's contender on Windows exposes its stderr pipe to processes the host starts only while it is being created. The pipe's write end was inheritable from its creation, so a Process.Start on another thread of the host could inherit it and hold the contender's stderr open after the contender ended. It is now inheritable only while the contender is being created, under the lock every SDK spawn takes.

📋 Important Notes

  • net8.0 and net9.0 leave the packages, and net11.0 joins, in an upcoming preview, ahead of their end of support on 2026-11-10; this release still ships them. The packages will then target netstandard2.0;net472;net10.0;net11.0. An app on .NET 8 or 9 still installs through the netstandard2.0 asset, but that asset is a compatibility asset, not a supported runtime: support and testing cover the targeted runtimes only, and .NET 5–7 are not supported. Plan the move to .NET 10.
  • Upstream's committed OpenAPI document is still stale at v2.0.26 (anomalyco/opencode#53105). It lacks LocationNotFoundError, and with it the 404 that location-scoped operations declare for a missing location, and it lacks integration.connect.external. This SDK's snapshot comes from upstream's own pinned generator, so a diff against that committed file shows them here; they are real and the server answers them.

0.9.0-preview.7 - 2026-10-06

The pin moves to upstream release tag v2.0.23, and all 141 operations it exposes are callable — 139 as generated HTTP calls, and the two terminal WebSocket connections through hand-written transports. A repository can now be initialized, a location whose directory does not exist answers a typed 404, and the server says whether it can run persistent terminals. 2.0.23 tags every error, so WorktreeError changes shape and an error body marked only by name no longer decodes, and EnsureAsync no longer replaces a service whose health protocol is incompatible; the breaking changes come first. On Linux and macOS a standalone server now runs in a session of its own and is ended as upstream's launcher ends it, a SIGTERM to its process group before the SIGKILL; Windows keeps its earlier path. The background-service doors follow the 2.0.23 client, the generated ToString() masks every configured header and environment map, the open provider options, and unrecognized union values that can carry a secret, and both packages declare IsAotCompatible on net8.0 and net9.0 too. net8.0 and net9.0 still leave in an upcoming preview; see the important notes.

💥 Breaking changes

  • WorktreeError is a tagged error. Upstream 2.0.23 declares it with _tag beside its name and data, so Tag reads _tag and a new required Name carries name. A body without _tag, from a server older than 2.0.23, no longer decodes to a typed error: Error is null and RawBody keeps the body.
  • _tag is the only error marker. Every error the 2.0.23 contract declares is tagged, so a name is no longer read as an error's marker:
    • Any error body whose only marker is name, not just a worktree failure, no longer decodes to UnknownOpenCodeError: Error is null and RawBody keeps the body.
    • The public UnknownOpenCodeError(tag, payload) constructor throws ArgumentException for a payload whose only marker is name; the payload must carry the tag under _tag.
  • OpenCodeServer.EnsureAsync throws OpenCodeServerException on a service whose health protocol is incompatible, where it used to replace it. A registered daemon that answers /api/info with an authenticated 404 is left running and the call throws, unless the call's version requirement is unmet, which still replaces it. Stop it explicitly with StopAsync to replace it.
  • OpenCodeServer.StartAsync refuses POSIX systems other than Linux and macOS, FreeBSD among them, with OpenCodeServerException before anything is spawned; they used to start through Process. On Linux and macOS a NUL in a command entry or an environment entry is now refused with ArgumentException, because the C string it is passed as would end there.

✨ Added

  • The accepted snapshot moved to upstream release tag v2.0.23 (0fd7e2829449b052abf0078666669302923d77af), published as @opencode/cli@2.0.23; install it with npm install -g @opencode/cli@2.0.23.
  • A repository can be initialized in a project that has none. client.Vcs.InitializeRepositoryAsync(request) (vcs.init) takes an optional Provider (git by default); a provider without initialization answers 501 VcsInitNotSupportedError. The route helper is OpenCodeRoutes.Vcs.InitializeRepository.
  • A missing directory is a typed 404. Every location- and session-scoped route, and experimental.generate.text, session.diff, and session.permission.list by name, now declare LocationNotFoundError (Location, Message) for a location whose directory does not exist; before 2.0.23 the server failed such a request instead of answering it. A PTY connect refused with HTTP 404 carries no error body, so its OpenCodeTransportException now names both causes: the PTY session or the requested location does not exist.
  • ServerInfo.Capabilities.PersistentPty says whether the server can run the persistent-terminal daemon: false on Windows, where opencode-pty ships no binaries. A server older than 2.0.23 leaves Capabilities null.

🔧 Changes

  • On Linux and macOS a standalone server runs in a session of its own, so a Ctrl+C or a hangup sent to the host's terminal no longer reaches it. Behaviour change: the server used to stay in the host's process group, so a Ctrl+C the host itself handled still ended the server. It now ends through DisposeAsync, or, when the host dies without disposing, on the end-of-stream of its stdin lease.
  • Disposing a standalone server on Linux and macOS sends SIGTERM to the server's process group, and SIGKILL to whatever is left of the group after GracefulShutdownTimeout, as upstream's own launcher does. Behaviour changes:
    • The pinned server answers the SIGTERM by exiting with code 130, where the stdin end-of-stream used to end it with code 0. Stdin now closes last.
    • Children the server started in its own process group end with it. Descendants that moved into a session of their own (the persistent-terminal daemon, PTY shells) are left to the server, as upstream leaves them; the forced tree kill used to end them too.
    • A server that already exited on its own with a non-zero code has the survivors of its group ended, and so does one whose exit status nobody could read (the host ignores SIGCHLD on Linux, or runs as pid 1); one that exited with code 0 or on a signal leaves them alone, as before.
  • A failed StartAsync on Linux and macOS ends the server the same way, with the configured grace, so a canceled or timed-out start can take up to that grace plus 16 seconds to throw: at most 10 for the server's exit after SIGKILL, 1 for draining its output, and 5 for releasing the output readers. Behaviour change: it used to kill the server at once.
  • StartAsync on Linux and macOS sees the server's own exit without waiting for its output, and fails at once when the server closes its stdout before readiness. A server that exits before readiness while a process it started still holds its stdout now fails the start within about a second instead of at the readiness timeout. Behaviour change in the message: a server ended by a signal before readiness reads "terminated on signal N", where it read "exited with code 128+N".
  • OpenCodeServerOptions.WorkingDirectory works on Linux with a C library older than glibc 2.29 (RHEL 8, Debian 10, Ubuntu 18.04): the server starts there through /usr/bin/env -C, which keeps it the same process, and a directory that does not exist fails the start as an exit with code 125 whose stderr names it. A blank WorkingDirectory counts as none.
  • A standalone server's relative command path on Linux and macOS is resolved against the caller's current directory, never against WorkingDirectory. Behaviour change: Process tried it against the application's own directory first, so a relative path that named a file there started that file even when the current directory held another.
  • OPENCODE_PRINT_LOGS=1 in the host's environment hands the server the host's own stderr on Linux and macOS, as upstream's launcher does; no stderr is then collected or quoted in a startup failure.
  • EnsureAsync reports the first contender failure without recruiting replacements. While a failed contender's error stands, no further contender starts; the call throws it once no contender is live, and at the 120-second bound it throws that failure rather than the timeout. A recovery or replacement that ends the registered service clears it and releases the contenders it made moot. Behaviour change: a call that a recruited replacement contender used to rescue now throws the first contender's failure.
  • Persistent-terminal handoff and the sidecar clear are best-effort. Preparing the handoff for a replacement never fails it: a failed or unusable ticket shuts the daemon's terminals down and publishes no ticket, and a sidecar that cannot be written leaves the replacement without one. StopAsync and the Ensure replacement end the service even when the sidecar cannot be removed. Behaviour change: StopAsync used to throw OpenCodeServerException when it could not remove the sidecar.
  • StopAsync escalates to the hard kill by the signalled process alone. When the process survives the request to stop, the hard kill follows it even if its registration disappeared or another service registered meanwhile, as upstream's client does; a successor's registration is still never removed. Behaviour change: the stop used to end without the hard kill when the registration changed between the two signals.
  • Both packages declare IsAotCompatible on every modern target (net8.0 and later), not only net10.0, so trimming and native AOT analysis cover the net8.0 and net9.0 assets too.

🔒 Security

  • An unrecognized union value no longer prints a secret. When a union's known shapes carry a masked member at any depth, its unknown arm — what a newer server's value decodes to — prints its preserved payload as [REDACTED] and keeps its marker: UnknownCredentialValue, UnknownMcp, UnknownConfigEntry, and the unknown arm of McpRemoteConfigOauth, ConfigInfoFormatter, ConfigInfoLsp, and ConfigLspEntry. Payload itself and serialization are unchanged.
  • Every user-configured header and environment map is masked in ToString(), now including ConfigProvider.Headers, ConfigModel.Headers, ConfigModelVariants.Headers, ConfigAgentRequest.Headers, ConfigFormatterEntry.Environment, ConfigLspServer.Env, and SessionEnvironmentRequest.Variables.
  • The open provider options are masked in ToString(). ProviderSettings, ConfigProviderSettings, ModelSettings, and ConfigModelSettings keep upstream's provider options, apiKey among them, in AdditionalProperties. A record printed that dictionary's type name, so no key was printed; it now prints [REDACTED] while the dictionary holds any member and empty while it holds none, so the value stays out if printing ever changes. The dictionary and serialization are unchanged.

🐛 Fixes

  • Disposing a standalone server on Linux and macOS no longer waits about 13 seconds when a process the server started keeps its output open. The shutdown waits also waited for the server's redirected output to end, so a server that exited at once still ran out the 3-second grace and the 10-second forced-exit wait. Disposal now waits for the server's own exit and then for its process group; only an OpenCodeServerOutput collector waits for the output, for at most one second.
  • A standalone server on Linux and macOS starts with every signal at its default disposition and an empty signal mask, as upstream's launcher starts it. It used to inherit a signal its host ignores (the .NET runtime ignores SIGPIPE, and a host started under nohup ignores SIGINT and SIGHUP).
  • Servers and background-service contenders started at the same time on macOS no longer receive each other's pipe ends. macOS marks a new pipe close-on-exec only after creating it, so a spawn on another thread in between could inherit a server's stdin lease and keep it open after the host died. The SDK's spawns now take one lock around pipe creation and spawn, and on macOS the child receives no descriptor beyond its own three.
  • OpenCodeServer.DisposeAsync no longer throws when the forced tree kill is incomplete. The runtime raises AggregateException when a process of the tree refuses the kill. That exception escaped disposal and skipped the rest of it: the bounded output drain, the release of the output readers (on Windows, a reader blocked on a pipe that a descendant still held was never cancelled), and the completion of the OpenCodeServerOutput collector. A failed StartAsync whose tree kill was incomplete threw that AggregateException instead of OpenCodeServerException or OperationCanceledException. Disposal and a failed start now continue past an incomplete kill and release everything.
  • A standalone server's stdout and stderr pipe handles are closed at disposal on Windows. Process never closes a redirected stream that was read synchronously, so the handles waited for the finalizer; each output reader now closes its pipe as it ends, after a failed start too.
  • The net472 and netstandard2.0 Windows tree kill no longer leaves taskkill running. A taskkill still running at its 10-second bound is now ended instead of left running.

📋 Important Notes

  • On Windows a standalone server is still started and ended through Process. The session placement and the SIGTERM-then-SIGKILL ladder above apply to Linux and macOS only. On Windows, disposal closes the server's stdin, waits up to GracefulShutdownTimeout, and only then kills the server's process tree; a server that exits inside the grace leaves its descendants running.
  • net8.0 and net9.0 leave the packages, and net11.0 joins, in an upcoming preview, ahead of their end of support on 2026-11-10; this release still ships them. The packages will then target netstandard2.0;net472;net10.0;net11.0. An app on .NET 8 or 9 still installs through the netstandard2.0 asset, but that asset is a compatibility asset, not a supported runtime: support and testing cover the targeted runtimes only, and .NET 5–7 are not supported. Plan the move to .NET 10.
  • Upstream's committed OpenAPI document is still stale at v2.0.23 (anomalyco/opencode#53105). It lacks LocationNotFoundError, and with it the 404 that 95 operations declare or widen for a missing location. This SDK's snapshot comes from upstream's own pinned generator, so a diff against that committed file shows them here; they are real and the server answers them.

0.9.0-preview.6 - 2026-10-04

The pin moves to upstream release tag v2.0.22, and all 140 operations it exposes are callable — 138 as generated HTTP calls, and the two terminal WebSocket connections through hand-written transports. Stored credentials can now be listed and created, a session can be created as a linked child of another, a cancelled form can tell the asker why, and a connection reports when it needs signing in again. The refresh changes three shapes, so the breaking changes come first. Discovery, Ensure, and Stop now read the CLI's service files exactly as the CLI does. net8.0 and net9.0 leave the packages in an upcoming preview; see the important notes.

💥 Breaking changes

  • CancelFormAsync takes an optional SessionFormCancelRequest before requestOptions. A call that passed requestOptions positionally names it now (requestOptions: options). The method is virtual, so overrides and mock setups move to the new signature, and an assembly compiled against 0.9.0-preview.5 must be rebuilt. The route helper OpenCodeRoutes.Sessions.CancelForm gained the same optional request.
  • ProviderSettings.ChunkTimeout and ConfigProviderSettings.ChunkTimeout are number-or-false unions, not double?. Upstream accepts a number of milliseconds or false (no timeout), so a provider configured with false now decodes. Read Kind, then Number or Boolean; a value neither arm claims is kept as Unknown. ChunkTimeout = 30000 becomes ChunkTimeout = ProviderSettingsChunkTimeout.FromNumber(30000) (ConfigProviderSettingsChunkTimeout on the config side), and FromBoolean(false) turns the timeout off; upstream refuses true.
  • ConfigModel.Capabilities is a ConfigModelCapabilities, not the catalog's ModelCapabilities. It is the shape upstream's config accepts, and every member is optional: Tools is bool?, and Input and Output may be null. ModelInfo.Capabilities is unchanged.
  • IConnectionInfo has a Status member. A type outside the SDK that implements the interface, such as a test fake, adds ConnectionStatus? Status; code that only reads connections is unaffected.

✨ Added

  • The accepted snapshot moved to upstream release tag v2.0.22 (527f0b931d1f9b3ebd34e106c51b31ce5db5b075), published as @opencode/cli@2.0.22; install it with npm install -g @opencode/cli@2.0.22.
  • Stored credentials can be listed and created. client.Credentials.ListCredentialsAsync() (credential.list) returns every CredentialEntry (Id, IntegrationId, Label, Active, Value), and CreateCredentialAsync(request) (credential.create) stores one and returns it; an Id that already exists answers with the declared 409. They join activate, update, and remove. Value is a CredentialKey or a CredentialOAuth. Upstream returns secrets in clear text, so the API key (CredentialKey.Key) and the OAuth tokens (CredentialOAuth.Access, Refresh) are masked in ToString().
  • SessionCreateRequest.ParentId creates a linked child session at its parent's location; a missing parent answers with the declared 404 SessionNotFoundError.
  • A cancelled form can tell the asker why. CancelFormAsync(formId, new SessionFormCancelRequest { Message = "..." }) sends it, and FormStateCancelled.Message carries it back.
  • HeaderTimeout on ProviderSettings and ConfigProviderSettings bounds the wait for a provider's response headers, as the same number-of-milliseconds-or-false union.
  • A connection reports when it needs attention. IConnectionInfo.Status is a ConnectionStatus with the Status, a Message, and, when set, the Url to sign in again at.
  • SessionStructuredError.Response carries the failed provider response's Body.

🐛 Fixes

  • OpenCodeServer.DiscoverAsync, EnsureAsync, and StopAsync decode the CLI's service files exactly as the CLI does. A whole-valued number such as 8080.0 is an integer for the service config's port and for the pid in the registration and the info probe. Before, such a config was ignored, so EnsureAsync lost its env overlay, and such a registration was not found. A service config whose disabled member is not a boolean is no config at all, so its env overlay and the legacy config copy do not apply, as in the CLI. disabled: true itself does not stop EnsureAsync: only CLI commands read it, never the CLI's service operations.

📋 Important Notes

  • net8.0 and net9.0 leave the packages, and net11.0 joins, in an upcoming preview, ahead of their end of support on 2026-11-10. The packages will then target netstandard2.0;net472;net10.0;net11.0. An app on .NET 8 or 9 still installs through the netstandard2.0 asset, but that asset is a compatibility asset, not a supported runtime: support and testing cover the targeted runtimes only, and .NET 5–7 are not supported. Plan the move to .NET 10.
  • Upstream's committed OpenAPI document is stale at v2.0.22 (anomalyco/opencode#53105). This SDK's snapshot comes from upstream's own pinned generator, so a diff against that committed file shows four more operations here; they are real and the server serves them.

0.9.0-preview.5 - 2026-09-29

The packages are now OpenCodeDotNet.Sdk and OpenCodeDotNet.Sdk.Extensions, and the repository lives in the opencode-dotnet organization. The API is unchanged: only the PackageReference changes. The release also fixes thread-pool starvation from standalone servers on Windows.

💥 Breaking changes

  • The packages are now OpenCodeDotNet.Sdk and OpenCodeDotNet.Sdk.Extensions. Change the PackageReference from OpenCodeAI.Sdk and OpenCodeAI.Sdk.Extensions; the earlier ids receive no further versions. Assemblies and namespaces are still OpenCode.Sdk, so no source changes.
  • The repository moved to opencode-dotnet/opencode-sdk-dotnet. GitHub redirects the old links. The nightly feed moved with it to https://nuget.pkg.github.com/opencode-dotnet/index.json; the earlier feed keeps its existing OpenCodeAI.* nightlies and receives no new ones.

🐛 Fixes

  • A standalone server no longer holds two thread-pool threads on Windows. Process creates the redirected stdout and stderr pipes synchronous there before .NET 11, and its event readers blocked a pool thread on each for the server's whole life; with a few servers in one process the pool starved, and unrelated async work stalled for seconds. The launcher now reads both streams on dedicated threads on Windows, and disposal ends them: it waits for end-of-stream inside the drain bound and cancels a read still blocked, so no reader outlives the server handle. That also keeps the last lines of an exited child from missing the OpenCodeServerOutput snapshot under load. Linux and macOS are unchanged.

0.9.0-preview.4 - 2026-09-27

Every operation upstream exposes is now callable: 100% coverage of the protocol surface. At upstream release tag v2.0.18, all 138 operations in the pinned document are usable — 136 generated and the two terminal WebSocket transports — and none is declined. 0.9.0-preview.3 generated 130 and declined 4. config.get, experimental.migration.v1.status, fs.read, and experimental.fs.write are now generated, and the refresh to v2.0.18 adds pairing.

✨ Added

  • The accepted snapshot moved to upstream release tag v2.0.18 (cd9a14a6b688d4021bee381dfd39d2cef9c0f862), published as @opencode/cli@2.0.18; install it with npm install -g @opencode/cli@2.0.18. It adds two operations and moves none, so all 138 are usable: 136 generated and the two WebSocket transports.
  • Pairing. client.Server.CreatePairingCodeAsync() (server.pair) issues a short-lived, single-use code; client.Server.RedeemPairingCodeAsync(code) (server.connect) exchanges it, with no other credential, for a session token the server accepts anywhere the password is, so another client connects with Password = token without ever holding the server password. The token is masked in PairingSession.ToString(), and so is the code in PairingCode.ToString().
  • ShellInfo.Signal names the signal that ended a killed command.
  • The configuration can be read back. client.Config.GetConfigAsync() (config.get) returns the configuration documents and discovery sources for the location, from lowest to highest priority: a ConfigDocument carries its ConfigInfo, a ConfigDirectory the directory it came from. Experimental.UpdateConfigAsync writes the global file and the server reloads it asynchronously, publishing config.updated once the loaded configuration changes, so read after that event.
  • client.Experimental.GetMigrationV1StatusAsync() (experimental.migration.v1.status) returns the V1 session-history migration status: ExperimentalMigrationV1StatusIdle (Required or Completed), …Running with its progress, or …Error.
  • Files can be written. client.Experimental.WriteFileAsync(new ExperimentalFsWriteRequest { Path = … }, stream) (experimental.fs.write) sends the stream as the raw body and returns the resolved absolute path as File.Path. The SDK reads the stream once from its current position to its end and never disposes or rewinds it; a slow upload stays alive while it keeps moving. Upstream does not confine the target to the location, so a relative Path resolves against it and an absolute one does not.
  • Files can be read. client.FileSystem.ReadFileAsync(new FsReadRequest { Path = … }) (fs.read) returns the file's bytes as Content (ReadOnlyMemory<byte>) and the MIME type the server declared as ContentType. Path is relative to the location and may be nested; the SDK escapes each segment as upstream's own client does and refuses . and .. segments. A missing file is the declared 404 FileNotFoundError; a path that leaves the location is refused by the server.
  • Unions of objects without a discriminator are typed. A structural union carrier whose object members share the JSON object token now selects a member the way upstream's decoder does: the first member in declaration order whose required keys are present and whose literal-constrained properties hold admitted values, then that member's full parse. A value no member claims is kept as the carrier's raw Unknown. The configuration's reference entries (ConfigReferenceEntry), language-server entries (ConfigLspEntry), and the migration status use it.
  • Operation members name their OpenAPI operation. Each generated operation method, each Enumerate*Async companion, and each hand-written PTY and persistent-PTY door carries an XML <remarks> with its operation id, HTTP method, and route, for example Operation session.permission.create: POST /api/session/{sessionID}/permission.

🔧 Changes

  • A 401 now carries the typed UnauthorizedError. From 2.0.18 the server answers a missing or refused credential with the error body its document declares, where it used to send an empty one, so Error is UnauthorizedError instead of null. Nothing changed in the SDK; the errors guide now says so.

🐛 Fixes

  • A logged response no longer prints the raw error body. Every response envelope's ToString() printed RawBody, so logging a failed response wrote whatever the server echoed into its error body, request data included. The printed form now keeps Status, IsError, and the typed Error; RawBody itself is unchanged and still carries the body.
  • OpenCodeServer.EnsureAsync no longer holds a thread-pool thread per contender on Windows. The contender's standard error was an anonymous pipe, which Windows reads synchronously, so every contender Ensure started kept one pool thread blocked for as long as its standard error stayed open — for the elected service, its whole life — and ten concurrent callers stalled the pool for seconds. The pipe's read end is now overlapped, as in .NET 11's Process and libuv.

📚 Documentation

  • The README is a front page. It opens with the status and a capability table that maps each area of the API to its client.* entry point and guide page. The quick start opens with a table for choosing a connection mode, and the known issues keep only what a consumer meets. Every link is absolute, so the page also works on NuGet.org.
  • The connection guide shows how to pair another client (CreatePairingCodeAsync, then RedeemPairingCodeAsync, then Password = token), and it lists the launcher's Output option.
  • A CLI-started server's session log is the marker alone, followed as well as replayed. The streaming guide and the README's known issues said live Follow = True delivery was unaffected by persistence; it is not. The server's live tail re-reads the same persisted store as a replay, so against a server the distributed opencode CLI started, GetLogAsync delivers one EventLogSynced and no durable event either way. Both now say so and point live session activity to client.Events.SubscribeAsync, filtered by session id. Observed on @opencode/cli@2.0.15.
  • A refused worktree removal can be partial. The errors guide said a 400 WorktreeError removed nothing. With ForceRequired false, git can already have deleted the worktree's files and its git metadata while the directory and the inventory row remain, and a retry then answers Worktree directory unavailable with ForceRequired null. The guide names the cause observed on Windows at the pin — the server keeps the worktree's location alive, and that location's local MCP servers run inside the worktree — and shows how to prevent it (Debug.EvictLocationAsync before the removal) and how to recover (evict, delete the directory, RefreshWorktreesAsync).
  • An empty VCS summary is explained. Getting started says that Vcs.GetVcsAsync for a directory the server has not served before can answer with a null Provider and null branch values until that location's plugins settle, that the caller waits for a non-null Provider, and that a null Branch.Current with a provider set is a detached HEAD.
  • Getting started shows a prompt answered in a console app: PromptAsync, then Experimental.WaitForSessionAsync under a caller-owned deadline, then EnumerateMessagesAsync.
  • Getting started has a .NET Framework section. A net472 project needs <LangVersion>10.0</LangVersion> — the SDK's public surface needs C# 9 and the console template's implicit usings C# 10 — and no extra package.
  • The requests guide explains the members the schema does not: session permission rules (an update replaces the whole ruleset; create, list, and reply; how upstream evaluates), a worktree's Directory as the parent and Name as the child, and a shell Timeout in milliseconds with 0 or unset meaning none.
  • The README no longer states a test count by hand; the test badges carry it. A tools test now fails when the README's guide table and the pages under docs/guide differ.

0.9.0-preview.3 - 2026-09-24

The launcher is complete: OpenCodeServer.EnsureAsync joins discovery and stop, so the three connection modes upstream's CLI offers are all in the SDK. The SDK follows upstream release tag v2.0.15 instead of v2.0.11, which makes two wire members required — the breaking changes come first — and adds session metadata updates. Generated models stop printing secrets, and the background-service door reads registrations the way upstream does in every case the fixes below list.

💥 Breaking changes

  • The accepted snapshot moved to upstream release tag v2.0.15 (6f3639d82ed0760091792189b78f8eeb44f699b1), which published as @opencode/cli@2.0.15; install it with npm install -g @opencode/cli@2.0.15. No operation was added, removed, or moved since v2.0.11. The Restore patch for upstream's lost SSE payload schemas (anomalyco/opencode#44911) is still required at this tag and applies unchanged.
  • ConnectionCredentialInfo.Method is required. A stored connection credential now says how it was obtained, ConnectionCredentialInfoMethod.Key or ConnectionCredentialInfoMethod.Oauth; a credential from a server that omits it no longer deserializes.
  • ProjectTime.Active is required. It is the project's most recent activity, in the same unit as Created and Updated, and upstream now orders the project list by it; a project from a server that omits it no longer deserializes.

✨ Added

  • Session metadata updates. SessionUpdateRequest.Metadata replaces a session's metadata as a whole — keys the update leaves out are removed, not kept — and the server logs the replacement as the durable SessionMetadataUpdated event (session.metadata.updated), which the event stream and the session log deliver.

  • OpenCodeServer.EnsureAsync, the managed-service election beside discovery and stop. It reuses a ready compatible daemon, replaces a version-mismatched one according to OpenCodeServerEnsureOptions.VersionPolicy (Ignore, Replace, Error), and otherwise spawns detached contenders until one registers or the 120-second wall-clock bound expires. The persistent-terminal handoff sidecar travels with replacement, and OnStart fires at most once before a new service process is spawned.

🔒 Security

  • Generated models no longer print secrets. A model's ToString() — string interpolation, logging templates, the debugger — printed every member, so logging an McpOAuthConfig, or the McpRemoteConfig holding it, wrote its ClientSecret. Members upstream's own recorder redacts (client_secret, password, api_key, token, …) now print [REDACTED], as do IntegrationConnectKeyRequest.Key and the user-configured header and environment maps; an absent secret prints empty, and every other member prints as before. Equality and JSON are unchanged.

🐛 Fixes

  • Discovery reaches a background service bound to every interface. A daemon started with hostname: 0.0.0.0 (or ::) registers that address, which .NET refuses as a connect target, so DiscoverAsync returned null and StopAsync could not ask it to shut its terminals down while the CLI worked. The connect target is now the same family's loopback, as Bun's is; the registered URL still identifies the daemon.
  • A registration file that is not valid UTF-8 reads as absent. DiscoverAsync and StopAsync threw InvalidOperationException for a registration holding an invalid UTF-8 string, outside their documented failures; such a file is now no registration, like any other undecodable one. A byte-order mark at the start of a registration or service-config file is skipped, as the CLI skips it.
  • A whitespace password is sent as written. OpenCodeClientOptions.Password refused an empty or whitespace value at client construction, and a background-service registration carrying a whitespace password read as passwordless, so discovery skipped a daemon the CLI reached. The CLI's server runs with any configured password, whitespace included; only a null password now means "no credential", as in the pinned client.
  • Reading a registration no longer blocks its removal on Windows. A service that exits removes its registration while clients may be reading it; the SDK now opens the file with delete sharing, as libuv does, so the removal never fails on the SDK's account.
  • OpenCodeServer.StopAsync treats a zombie as stopped on Linux. A service process that had exited but was not yet reaped by its parent kept its start time readable, so the stop read it as still running, sent the kill rung, and failed with "still running after the kill rung", leaving the registration behind. The identity read now checks the process state and treats a zombie as gone, the way macOS already did.
  • Structural union values print themselves. ToString() on FormValue, FormWhenValue, McpRemoteConfigOauth, and ProviderSettingsTimeout threw InvalidOperationException ("The structural value does not contain the requested arm."): a record's compiler-synthesized PrintMembers read every arm, and an inactive arm throws by design. Each union now prints its kind and its active arm only — ProviderSettingsTimeout { Kind = Number, Number = 30000 }, FormValue { Kind = TextList, TextList = [a, b] } — with numbers in the invariant culture and an Unknown arm as its raw JSON. String interpolation, logging templates, and the debugger were the paths that hit this; equality and JSON were never affected.

0.9.0-preview.2 - 2026-09-21

Three things changed since 0.9.0-preview.1. The SDK follows upstream release tag v2.0.11 instead of v2.0.8, which reshapes the provider and model catalog entries. Public names no longer carry the HTTP method, so a wave of methods and types is renamed; the breaking changes come first, each with what to change. And OpenCodeServer gained StopAsync, the stop door beside discovery.

💥 Breaking changes

  • The accepted snapshot moved to upstream release tag v2.0.11 (9eb6902aaf3c35ce985b67c605a775992249066b), which published as @opencode/cli@2.0.11; install it with npm install -g @opencode/cli@2.0.11. No operation was added, removed, or moved since v2.0.8; the change is in the provider and model catalog entries. The Restore patch for upstream's lost SSE payload schemas (anomalyco/opencode#44911) is still required at this tag and applies unchanged.
  • Provider and model settings are typed open objects. ProviderInfo.Settings is a ProviderSettings (Timeout, ChunkTimeout, Compaction, Transport) and ModelInfo.Settings and ModelVariant.Settings are a ModelSettings (Compaction) instead of IReadOnlyDictionary<string, JsonElement>; ProviderRequestOptions.Settings is the same ProviderSettings. Every other member the server puts in settings — baseURL, apiKey, region, and whatever a provider adds — is in AdditionalProperties, an IReadOnlyDictionary<string, JsonElement> keyed by wire name that is empty, never null, when the body carried none; read it the way upstream does, by checking the ValueKind you expect. Compaction and Transport are removed from ModelInfo and ProviderInfo themselves: upstream moved them under settings. Timeout is a ProviderSettingsTimeout structural union (Number, Boolean for the wire's false, Unknown).
  • The compaction union changed its arms and marker. IProviderCompaction now dispatches on type with ProviderCompactionSummary (summary) and ProviderCompactionNative (native); ProviderCompactionLocal, ProviderCompactionProvider, its Threshold, and the mode marker are gone with upstream's schema.
  • The HTTP method is no longer part of any name. An operation's verb is its closing identifier segment when that segment is one of create, get, list, remove, rename, timeout, or update; a GET without one is a read and names Get<Subject>Async; every other operation is named by a reviewed, reason-bearing curation row, and the generator refuses to fall back to Post…, Put…, Patch…, or Delete…. Three consequences reach your code:
    • Every Post…/Put…/Patch…/Delete… method is renamed. On SessionClient: PostPromptAsync → PromptAsync, PostGenerateAsync → GenerateTextAsync, PostCommandAsync → RunCommandAsync, PostShellAsync → RunShellCommandAsync, PostCompactAsync → CompactAsync, PostForkAsync → ForkAsync, PostMoveAsync → MoveAsync, PostInterruptAsync → InterruptAsync, PostBackgroundAsync → MoveToolsToBackgroundAsync, PostViewAsync → MarkViewedAsync, PostSyntheticAsync → AddSyntheticMessageAsync, PostSwitchAgentAsync → SwitchAgentAsync, PostSwitchModelAsync → SwitchModelAsync, PutEnvironmentAsync → SetEnvironmentAsync, PostFormReplyAsync → ReplyToFormAsync, DeleteFormCancelAsync → CancelFormAsync, PostPermissionReplyAsync → ReplyToPermissionAsync, DeleteInboxCancelAsync → CancelInboxAsync, PostRevertStageAsync → StageRevertAsync, PostRevertCommitAsync → CommitRevertAsync, DeleteRevertClearAsync → ClearRevertAsync. On IntegrationClient: PostConnectKeyAsync → ConnectWithKeyAsync, PostOauthConnectAsync → BeginOauthConnectionAsync, PostOauthCompleteAsync → CompleteOauthConnectionAsync, DeleteOauthCancelAsync → CancelOauthConnectionAsync, PostCommandConnectAsync → BeginCommandConnectionAsync, DeleteCommandCancelAsync → CancelCommandConnectionAsync. On ExperimentalClient: PostSessionImportAsync → ImportSessionAsync, PostSessionSkillAsync → ActivateSessionSkillAsync, PostSessionWaitAsync → WaitForSessionAsync, PutSessionInstructionsEntryAsync → SetSessionInstructionsEntryAsync. On PtyClient: PutUpdateAsync → UpdateAsync.
    • A handle names itself, not its family. A handle client's own read, update, and remove drop the family word: SessionClient.GetSessionAsync / UpdateSessionAsync / RemoveSessionAsync → GetAsync / UpdateAsync / RemoveAsync; likewise ShellClient.GetShellAsync / RemoveShellAsync, IntegrationClient.GetIntegrationAsync, PtyClient.GetPtyAsync / RemovePtyAsync, and PersistentPtyClient.GetPersistentPtyAsync / UpdatePersistentPtyAsync / RemovePersistentPtyAsync. Collection clients are unchanged (Sessions.ListSessionsAsync, Sessions.CreateSessionAsync).
    • Request, response, and payload types drop the verb the same way. Every …PostRequest, …PutRequest, …PatchRequest, …DeleteRequest and the matching …Response / …Data type loses the method word: SessionPromptPostRequest → SessionPromptRequest, SessionPromptPostResponse → SessionPromptResponse, SessionUpdatePatchRequest → SessionUpdateRequest, PtyUpdatePutResponse → PtyUpdateResponse, LocationReloadPostResponse → LocationReloadResponse, PluginCheckPostRequest → PluginCheckRequest, SessionGeneratePostData → SessionGenerateData, and so on for all 104 such types; grammar verbs keep their word (SessionListResponse, SessionRemoveResponse). Two names needed more than the rule: the body session.interrupt answers with was upstream's SessionInterruptResponse and is now SessionInterruptOutcome, so that the operation's own response record can carry SessionInterruptResponse (response.Interrupt.Interrupted reads as before); and the three update responses whose payload was mislabelled Update now name their subject — PtyUpdateResponse.Pty, PersistentPtyUpdateResponse.PersistentPty, ProjectUpdateResponse.Project. The route builders in OpenCodeRoutes follow their methods (Sessions.PostPrompt(id) → Sessions.Prompt(id), Sessions.GetSession(id) → Sessions.Get(id), …Template constants alike).
  • McpProtocol.Value20260728 is McpProtocol.Revision20260728. The wire value 2026-07-28 is unchanged; a reviewed enum member-name row names the member.

✨ Added

  • OpenCodeServer.StopAsync stops the registered background service — opencode's service stop for your code, shaped by OpenCodeServerStopOptions (Channel, RegistrationFilePath, InstalledVersion). It resolves the registration the way discovery does, asks a ready daemon to shut its persistent terminals down, clears the handoff sidecar, ends the registered process with the CLI's own ladder (SIGTERM, about five seconds, then SIGKILL; hard kills on Windows), and removes the registration once the process is gone. The registration is re-read before every signal and the process is identified by pid and start time, so a service that re-registered under the file or a pid the operating system reused is never signalled. A missing registration completes successfully; a process still running after the hard kill throws OpenCodeServerException and leaves the registration in place. Disposing a discovered handle still stops nothing.

🔧 Changes

  • Discovery answers a stale registration at once on Windows. OpenCodeServer.DiscoverAsync probes the registered loopback address without SYN retransmission, so a registration whose daemon is gone returns null in milliseconds instead of waiting out the two-second bound, and a refused port is classified as "no service" rather than a timeout on every operating system and target framework — the classification the Ensure door will rely on. The probe also never routes a loopback request through a proxy: HTTP_PROXY without NO_PROXY no longer hides a running service. Nothing changes for the SDK's other calls.

0.9.0-preview.1 - 2026-09-18

Two things changed since 0.8.0-preview.2. The SDK now follows upstream release tag v2.0.8 instead of v2.0.2: upstream renamed, moved, or removed many operations in between, and the SDK keeps no compatibility layer, so the breaking changes come first, each with what to change. And OpenCodeServer gained background-service discovery, opencode's third connection mode.

💥 Breaking changes

  • The accepted snapshot moved to upstream release tag v2.0.8 (7673ed6bd6547ee0dcb81aab55f1392fb751d652), which published as @opencode/cli@2.0.8; install it with npm install -g @opencode/cli@2.0.8. Operation identities lost their v2. prefix upstream (session.diff, event.subscribe); routes did not change for that reason. 130 of the document's 136 operations are generated and two more are hand-written WebSocket transports. The Restore patch that repairs upstream's lost SSE payload schemas (anomalyco/opencode#44911) is still required at this tag and applies unchanged.
  • Health became server info. OpenCodeClient.GetHealthAsync, ServerClient.GetServerAsync, HealthResponse, Health, and ServerResponse are removed with upstream's /api/health and /api/server. Call client.Server.GetInfoAsync() (GET /api/info) and read ServerInfoResponse.ServerInfo: Version, Pid, Urls, and Paths.Tmp, the server's temporary directory. There is no Healthy member; an info call that answers is the health signal, and it throws like any other call when the server does not. Background-service discovery probes the same door, and a registered daemon of an older 2.x release, which still serves /api/status, is reported as present but incompatible.
  • Location targeting is directory-only. LocationSelector.Workspace and SessionListRequest.Workspace are removed: upstream dropped the location[workspace] query and the x-opencode-workspace header. The Location a location-scoped response carries is now LocationPublicRef with Directory alone, and location.get answers LocationPublicInfo; LocationInfo and LocationInfoProject are removed. The client.Workspaces family (WorkspacesClient) is removed with upstream's workspace routes.
  • Operations upstream marked experimental moved to client.Experimental, as flat methods that take their ids explicitly:
    • SessionClient.GetExportAsync → Experimental.GetSessionExportAsync (payload member SessionExport), SessionsClient.PostImportAsync → Experimental.PostSessionImportAsync, SessionsClient.GetStatsAsync → Experimental.GetSessionStatsAsync.
    • SessionClient.PostSkillAsync / PostWaitAsync → Experimental.PostSessionSkillAsync / PostSessionWaitAsync, and the three …InstructionsEntryAsync methods → Experimental.ListSessionInstructionsEntryAsync, PutSessionInstructionsEntryAsync, and RemoveSessionInstructionsEntryAsync.
    • The McpServerClient handle and McpServersClient.GetMcpServerClient are removed; adding, connecting, disconnecting, and removing a server are Experimental.AddMcpServerAsync, ConnectMcpServerAsync, DisconnectMcpServerAsync, and RemoveMcpServerAsync. McpServersClient keeps the list and the resource catalog.
    • client.Generation.GenerateTextAsync → Experimental.GenerateTextAsync; GenerationClient is removed.
  • Configuration preferences are gone upstream. ConfigClient.GetPreferencesAsync, PatchUpdatePreferencesAsync, and the ConfigPreferences* and ConfigWebSearchInfo models are removed with /api/config/preferences. Write through Experimental.UpdateConfigAsync, whose Shell is required and nullable: a string sets the shell, null clears it, and there is no "leave it unchanged" form any more. There is no configuration read at this pin: upstream folded it into config.get, which this SDK does not generate yet (coverage). ConfigClient keeps GetShellsAsync.
  • Session operations that changed shape. RenameSessionAsync and PutPermissionRulesAsync → SessionClient.UpdateSessionAsync (Title, Permissions). PostInboxQueueAsync and PostInboxSteerAsync → UpdateInboxAsync with the delivery to switch to. GetFormStateAsync is removed; the state is GetFormAsync(…).Form.State on the new FormDetail. PostFormCancelAsync → DeleteFormCancelAsync and PostRevertClearAsync → DeleteRevertClearAsync (upstream changed the method). The fork boundary union (ISessionForkRequestBoundary, SessionForkRequestBoundaryBefore, …Through) is removed; set SessionForkPostRequest.Before. SessionInterruptPostRequest.Continue → Resume. MessageListRequest, MessageListResponse, and MessageListRequestType → SessionMessageListRequest, SessionMessageListResponse, and SessionMessageListRequestType.
  • Events. session.permissions.updated is now session.permissions: SessionPermissionsUpdated and its Data and Durable companions → SessionPermissions, SessionPermissionsData, and SessionPermissionsDurable. catalog.updated (CatalogUpdated) is removed; provider.updated and model.updated arrive as ProviderUpdated and ModelUpdated.
  • Worktrees name their project. Every worktree request requires ProjectId, and the requests no longer take a Location; WorktreeCreateRequest.Strategy is removed.
  • Smaller renames and removals. VcsClient.GetBranchesAsync → ListBranchesAsync (VcsBranchListRequest / VcsBranchListResponse). FormsClient.ListRequestsAsync → ListFormsAsync, and its payload Requests → Forms. ProjectsClient.GetCurrentAsync is removed; the current project arrives on client.Location.GetLocationAsync(). ShellClient.TimeoutShellAsync is removed. ShellCreateRequest.Timeout is optional (long → long?). SkillInfo.Location and Slash → Path. An unknown integration now throws the declared 404 instead of returning null.
  • PluginsClient.AwaitPluginActivationAsync is removed and has no replacement: the pin exposes no HTTP activation barrier. When your code needs a particular plugin, provider, or model, wait for that identity under your own cancellation deadline; an empty list does not prove absence.

✨ New features

  • Background-service discovery. OpenCodeServer.DiscoverAsync opens opencode's third connection mode: it finds the background service the opencode CLI registers for every client on the machine, through the CLI's own rules — the registration file resolved by service channel under the XDG state root (or named directly), the CLI's one-time copy of an older hashed registration filename, a strict decode of the registration, and an authenticated /api/info probe under a two-second bound whose pid must match. A ready daemon comes back as a non-owning OpenCodeServer: the new OwnsProcess member is false, DisposeAsync is a no-op, and CreateClient() binds a client to the daemon exactly as it does to a started server. Everything unusable — no registration, an undecodable or passwordless one, a daemon still starting or failed, a probe timeout, a version other than the expected one — is a null answer, never a half-usable handle. OpenCodeServerDiscoverOptions carries Channel, RegistrationFilePath, ExpectedVersion, and InstalledVersion, validated at the call. This is the one SDK door that reads the environment, and it reads exactly XDG_STATE_HOME, XDG_CONFIG_HOME, OPENCODE_CONFIG_DIR, and the user profile (USERPROFILE first on Windows, HOME elsewhere) — never a credential. The behaviour is the pinned CLI's, source-watched at the accepted commit (ADR-0025); live tests prove it against the pin's own serve --service daemon on every target-framework leg, from an isolated process whose environment the test owns. Ensuring and stopping the service follow as their own slices.
  • Turn diffs. SessionClient.GetDiffAsync binds session.diff: the structured per-file diffs of the files one turn changed, where a turn runs from the first prompt after the session was last idle to its next idle marker. SessionDiffRequest carries the optional From and To user-message anchors and the Context line count, and SessionDiffResponse.Diffs is the same FileDiffInfo list the VCS diff returns. A live test proves the declared 200, 400, and 404 arms against the pinned server.
  • The idle turn marker is a typed message. SessionMessageIdle joins the message union with its Outcome (Succeeded, Failed, or Interrupted). The server writes one at the end of every turn; on 0.8.0-preview.2 those entries surfaced as UnknownSessionMessageInfo.
  • Reloading every loaded location. client.ReloadLocationsAsync() binds location.reload: the server shuts down and rebuilds every loaded location, cancels pending permissions and forms, lets running sessions continue with fresh services at their next step boundary, and answers once every replacement build settles. The new location.shutdown event (LocationShutdown) arrives on the event stream for each location it tears down, so a consumer can revalidate its reads. The declared ServiceUnavailableError is its one typed failure.
  • Smaller additions. SessionStepStartedData.Started carries the step's request dispatch time, before the provider answers, and every Form*Field has an optional Hidden that skips the interactive prompt when a default exists.

🔧 Changes

  • The version line is 0.9.0. Discovery is the M4 milestone's background-service boundary; nightlies are 0.9.0-nightly.*.
  • OpenCodeServerException now covers every local-server door. Discovery throws it for one cause only — an XDG variable unset with no user home to fall back to — beside the launcher's start, readiness, and stop failures. The class summary and the errors guide say so.
  • OpenCodeServer is the home of every local-server handle (ADR-0024): its summary no longer promises that it never attaches to another server, because a discovered handle is exactly that, with its ownership visible through OwnsProcess.
  • The published opencode build is tested now, not only the pinned source. The live-test fixture takes a new optional OPENCODE_SDK_TESTS_SERVER_COMMAND (|-separated, e.g. opencode|serve): it replaces the command the fixture starts and changes nothing else, so the whole suite can be pointed at any build of the same server — the executable is resolved from PATH by the SDK's own launcher. The new Consumer leg workflow — on demand and weekly, Linux and Windows — uses it to run that suite against npm install -g @opencode/cli at the version spec/SNAPSHOT.md pins, after asserting the version the installed command reports.

0.8.0-preview.2 - 2026-09-12

The second preview, built against upstream release tag v2.0.2. The breaking changes come first, each with what to change; nothing else needs action to upgrade from 0.8.0-preview.1.

💥 Breaking changes

  • A request property the API document declares both optional and nullable is now Optional<T?> instead of T? — 39 properties across 21 operations, one of them the shared ToolFileContent.Name. The wrapper is what tells "leave this alone" apart from "send an explicit null": an unassigned member is absent and is not written at all, = null and Optional<T?>.Null both write JSON null, and a value assigns through an implicit conversion, so Title = "Fix the build" keeps compiling unchanged. Reading one back goes through IsSet and Value, and = default returns a member to absent. Response-only schemas are untouched; ToolFileContent is the one schema shared both ways, so its Name carries the wrapper on the read side too and is read through .Value. The new Requests guide page covers it.
  • The accepted snapshot moved to upstream release tag v2.0.2 (ea5ae2329569e4fbf063be451480b58e29de6816), which published as @opencode/cli@2.0.2. Install that release (npm install -g @opencode/cli@2.0.2); the @opencode-ai/cli scope that the previous README named is frozen at an August build that predates the worktree route shape and the whole persistent-PTY family this SDK generates.
  • v2.session.messageUpdate is gone because upstream removed the message content mutation API (anomalyco/opencode#48043). SessionClient.PatchMessageUpdateAsync, SessionMessageUpdatePatchRequest, SessionMessageUpdatePatchResponse, and the route constants are removed, and with them the ISessionMessageAssistant union and its UnknownSessionMessageAssistant carrier, which only that request body referenced. Assistant content records keep ISessionMessageAssistantContent.
  • session.message.content.updated left the live event union. SessionMessageContentUpdated no longer implements IEvent; it remains a durable session-log item.

✨ New features

  • A preference can be cleared, not just overwritten. PatchUpdatePreferencesAsync sends an explicit JSON null for Shell or Websearch when you assign Optional<T?>.Null (or plain null), which is how upstream deletes the key from the preferences document; omitting the member leaves the stored value alone.

  • The config family is on the client. The v2.0.2 snapshot added four operations and all four are generated and covered: OpenCodeClient.Config carries GetPreferencesAsync, GetShellsAsync, and PatchUpdatePreferencesAsync (global preferences read, the host shell catalog, and the preferences patch), and SessionClient.PutPermissionRulesAsync replaces a session's permission ruleset. ConfigPreferences.Websearch and ConfigUpdatePreferencesPatchRequest.Websearch are structural unions over false and a ConfigWebSearchInfo provider. Coverage is 138 of 143 pinned operations, up from 135 of 140 in 0.8.0-preview.1.

  • Sessions carry their permission ruleset, and changing it raises an event. SessionCreateRequest, SessionInfo, and SessionCreatedData gained Permissions, and the new durable event session.permissions.updated materializes as SessionPermissionsUpdated on IEvent, ISessionEventDurable, and ISessionLogItem, carrying the session id and the new ruleset.

  • One door submits a command line on both terminal families. PtySession.SubmitAsync(string) and PersistentPtySession.SubmitAsync(string) send the line plus the carriage return a terminal's Enter key sends, through the same serialized send path as the matching WriteAsync — a UTF-8 text message for a normal PTY, the framed input message carrying the viewport for a persistent one. The argument is exactly one line: a \r or an \n inside it is refused with ArgumentException, an empty line is a bare Enter, and nothing is trimmed. WriteAsync is unchanged and stays the raw door — partial input, control sequences, and bytes a terminal emulator produced.

  • A union interface now carries what all its members share. A marked union whose members all declare a property in the same shape promises that property on its interface, so a generic consumer reads it without a switch over concrete types. The landmark case is the session log: ISessionEventDurable gained Id, Created, Metadata, Location, and Durable, and the 43 per-event envelope records now implement one new IDurableEnvelope carrying AggregateID, Seq, and Version — so item.Durable?.Seq replaces a partial type switch. IEvent, IFormField, IMcp, IReferenceSource, ISessionMessageInfo, ISessionMessageCompaction, ISessionInboxInfo, ISessionInboxItem, ISessionForkBoundary, IIntegrationAttemptStatus, and IIntegrationCommandAttemptStatus gained members the same way, with IMcpTimeout, ISessionMessageCompactionTime, IIntegrationAttemptStatusTime, and IIntegrationCommandAttemptStatusTime as further carriers. Members are declared nullable because a union's Unknown* carrier preserves a raw payload and materializes none of them; the concrete records keep their existing non-nullable properties, the wire shape is unchanged, and no type was removed. Implementing one of these interfaces outside the SDK now requires the new members.

  • Session listing enumerates too. SessionsClient.EnumerateSessionsAsync joins SessionClient.EnumerateMessagesAsync as an automatic cursor walk. A list query now binds the shared ListRequest spine whenever it includes limit, order, and cursor — extra filters no longer disqualify it — so SessionListRequest derives from ListRequest and gains the companion. Every filter of the first request rides each continuation unchanged; only the first-page-only order is dropped and the opaque cursor replaced.

  • Every automatic walk can be read as pages. Enumerate*Async now returns CursorSequence<TPage, TItem>, whose Pages property yields each generated response envelope — Status, Cursor, RawBody and all — instead of only the items. There is no new page type and no page-size knob: a page is the response the server returned for one request. The item door and the page door are independent walks of the same recipe, so enumerating both sends both sets of requests.

🐛 Fixes

  • The docs no longer claim an anonymous opencode server exists, and a 401 now says so. The guide and the shipped XML on OpenCodeClientOptions.Password told readers that null was the right value "for a server started without authentication". No such server can be started: the opencode CLI always runs its server with a password — the one set through OPENCODE_PASSWORD, or one it generates and prints as server password <pw> — and it rejects an uncredentialed request above the API layer, with an empty body and no typed error to read. Every statement of that claim is corrected, and when a call answers 401 while the client was built with Password left null, the OpenCodeApiException message now adds one sentence naming the missing credential and where to get one. The sentence appears for 401 only, and only when no password was configured; a rejected password keeps the plain message, and the NoThrow envelope is unchanged. No public member changed.
  • OpenCodeServer.StartAsync() now works on Windows with an npm-installed CLI. npm writes shim files (opencode, opencode.cmd, opencode.ps1) and keeps the real binary inside node_modules, while Process.Start appends only .exe and ignores PATHEXT — so the shipped default Command failed on every npm-installed Windows machine with a bare "Failed to start the server command 'opencode'" and no stderr. The launcher now resolves Command[0] the way a shell does before spawning anything, so the .cmd shim is found and started. Nothing changes on Linux or macOS, where npm's bin entry is a link to the binary and the default already worked.

🔧 Changes

  • Command[0] is resolved before the process is created. A path (rooted, or carrying a directory separator) is used as written; a bare name is searched through the PATH directories in order, skipping empty entries and resolving relative ones against the current directory. On Windows a bare name with no extension is tried with each PATHEXT extension in PATHEXT order (falling back to .COM;.EXE;.BAT;.CMD), and a name that already carries an extension is tried as written; on Unix the name itself is searched. A bare name that matches nothing now fails with an OpenCodeServerException that names the command, the number of directories searched, and the extensions tried, instead of the bare spawn error it used to surface.

  • A resolved Windows .cmd/.bat shim is launched through the system cmd.exe (/d /s /c, every token quoted) rather than through CreateProcess's implicit batch handling. Two consequences: ProcessId then reports the cmd.exe host rather than the server process — ask the server for health.Health.Pid when you need that one, and note that disposal's whole-tree kill still covers everything underneath — and a leading argument of yours containing &, |, <, >, ^, %, !, ", CR, or LF is refused with OpenCodeServerException before anything starts, because cmd.exe re-parses the line (the fail-closed answer to BatBadBut / CVE-2024-24576). The SDK's own --stdio --port 0 are unaffected, and non-batch targets are launched exactly as before.

  • The terminals guide no longer contradicts itself about Enter. Its normal-PTY example wrote "echo hello\r" while its persistent-PTY example wrote "echo hello\n". Both now run their command through SubmitAsync, and the terminator rule is stated once: Enter is \r, \n is a line feed that the Windows console host does not accept as a submit, and the SDK never rewrites what WriteAsync is given.

  • Snapshot additions. MessageListRequest.Type filters a message list by message type (MessageListRequestType) and rides every continuation unchanged; ModelInfo.Websocket and ProviderInfo.Websocket are new optional flags; compaction ended and failed data, and the compaction message records, carry optional Cost and Tokens.

  • SessionClient.EnumerateMessagesAsync returns CursorSequence<MessageListResponse, ISessionMessageInfo> instead of IAsyncEnumerable<ISessionMessageInfo>. await foreach over it is unchanged, and code that stored the result in a variable typed IAsyncEnumerable<T> still compiles, because CursorSequence<TPage, TItem> implements IAsyncEnumerable<TItem>. Code that declared the variable with var and then assigned an IAsyncEnumerable<T> to the same variable is the one shape that needs its type written out.

  • SessionListRequest no longer declares Limit, Order, and Cursor itself; it inherits all three from ListRequest. Reading and initializing them is unchanged.

📚 Documentation

  • Durable replay now says which servers can actually do it. The streaming guide and the README's known issues state that the distributed opencode CLI starts its server without event persistence and exposes no switch for it, so a replay from a CLI-started server answers with the log.synced marker alone — a contract-valid success with no history in it. Observed on @opencode/cli@2.0.2. A new live test on the ordinary pinned CLI profile asserts the marker-only answer and is the reversal trigger: when it fails, upstream began persisting by default and those statements change with it.
  • "Choosing a model" is a new section in the getting-started guide. One compiled recipe — await plugin activation, read the provider and model catalogs, then place new ModelRef { ProviderId = model.ProviderId, Id = model.Id } on session creation — plus the three rules that surround it: health is process liveness and not catalog readiness, a session reference carries ModelInfo.Id and never ModelInfo.ModelId, and neither create nor prompt validates the reference. The same recipe runs in the in-repo sandbox's --standalone leg.
  • Session export documents what Sanitize does. A sanitized export replaces message text with [redacted:text:<id>]-shaped placeholders while ids, types, order, and count survive, so it is for sharing a conversation's shape and never for comparing transcripts.
  • A refused worktree removal has a paragraph in the errors guide. A 400 WorktreeError removed nothing — the directory and its inventory row both remain — and ForceRequired false means git ran and failed for a reason Force cannot fix, such as the Windows permission denial observed on the then-pinned @opencode/cli@0.0.0-beta-19242 while another process held the directory.

0.8.0-preview.1 - 2026-09-09

The first published release. Everything below describes the surface as it ships; there is no migration to perform, because no earlier version was ever published.

✨ New features

  • OpenCodeAI.Sdk — the typed client. 135 of the 140 operations in the pinned OpenAPI snapshot are callable across 28 client families: sessions, PTYs, persistent PTYs, shells, events, MCP servers, integrations, projects, worktrees, workspaces, providers, language models, agents, skills, commands, forms, permissions, credentials, plugins, RPC, references, VCS, websearch, file system, generation, server, debug, and experimental. Every operation carries a generated request type and a generated response envelope; bound handles (SessionClient, PtyClient, PersistentPtyClient) partially apply a resource id over the shared pipeline.
  • Unions dispatch by tag, and tolerate what they do not know. A discriminated union decodes by the literal tag the document declares. The live event stream additionally carries one prefix-tagged arm, so every rpc.* event dispatches to EventRpc — tried after the literal tags and before the carrier. Anything matching neither lands in that union's Unknown* variant with its tag and raw payload, so a server newer than the pinned snapshot widens an enumeration rather than breaking it.
  • A standalone server launcher. OpenCodeServer.StartAsync() starts, monitors, and stops a private opencode2 serve child — generated lease credential, stdin-EOF ownership, bounded tree termination — and CreateClient() hands back a client already bound to it. An optional OpenCodeServerOutput collector, supplied through OpenCodeServerOptions.Output, retains a bounded tail of the child's stdout and stderr for pull snapshots that report truncation, and it stays readable after a failed start; ProcessId stays readable after disposal for the same diagnostic use. Real-process lifecycle acceptance runs on Windows, Linux, and macOS.
  • Server-sent event streaming. EventsClient.SubscribeAsync follows the global bus and SessionClient.GetLogAsync follows one session's log, both as IAsyncEnumerable<T> of typed frames over the same transport, decoration, and status walls as one-shot calls. A body cut mid-event is reported rather than dispatched, and the contract's mid-stream failure channel surfaces as a typed exception instead of being discarded.
  • PTY and persistent-PTY terminal sessions. PtySession and PersistentPtySession are hand-written WebSocket doors over a shared, family-neutral socket core: read frames, write input, dispose to close. The persistent family adds attach/handoff/snapshot semantics, byte-typed output and checkpoints, and the framed input protocol with viewport tracking.
  • Terminal connection lifetime a caller can drive. A connection-owned receiver assembles frames into an internal queue independently of the caller's enumeration, so canceling a read ends only that wait: the same healthy connection can be read again, or written to, afterwards. Both connect options gained an init-only SendTimeout (default 30 seconds) bounding each input or resize send end to end, including the wait for the send gate. Connection termination delivers the frames it already holds before reporting its outcome, while disposal abandons unread frames and joins the connection's own work. A persistent PTY keeps its locally requested viewport coherent with the input it labels, rather than letting an inbound resize report overwrite it. See the terminals guide.
  • Dependency injection through OpenCodeAI.Sdk.Extensions. AddOpenCode(Action<…>) or AddOpenCode(IConfiguration) registers one singleton client owning its transport for the container's lifetime, plus every sub-client resolved from that same instance — inject SessionsClient or EventsClient directly.
  • A typed error model. Calls throw typed exceptions by default; OpenCodeRequestOptions.NoThrow returns the failure as data on the same envelope (IsError, Error) for the cases where a non-2xx is a normal answer. Transport failures map to their own exception family.
  • Cursor-based asynchronous pagination. The two cursor-carrying list envelopes — session list and message list — expose the wire cursor directly, and SessionClient.EnumerateMessagesAsync follows it to exhaustion as an IAsyncEnumerable<T>.
  • Source-generated JSON. System.Text.Json source generation throughout, with no reflection fallback anywhere in the serialization path. Both packages declare IsAotCompatible on net10.0; the one reflective seam, AddOpenCode(IConfiguration), is annotated [RequiresDynamicCode] / [RequiresUnreferencedCode] so a trimmed or AOT build is warned rather than surprised.

🛠️ General

  • Target frameworks: netstandard2.0, net472, net8.0, net9.0, net10.0 — for both packages. The suite runs on net472 on Windows, real-process launcher tests included, and on net8.0/net9.0/net10.0 on all three OSes. netstandard2.0 is a consumption target rather than a test target — it has no runtime to execute on, and the net472 leg is what exercises its compile surface.
  • Protocol identity: built against an accepted OpenAPI snapshot of upstream's v2 branch, not a live branch. The exact commit, its digest, and the receipt-governed refresh procedure live in spec/SNAPSHOT.md.
  • Generated output is committed and reviewed as source, locked by a public-API baseline and verified by regeneration, so a protocol refresh arrives as a readable diff.
  • Test suite: 5,138 tests green on Windows — the fullest leg, and the only one that adds the net472 assemblies. Linux and macOS run the same suite on the three modern targets.

📋 Important Notes

  • Unofficial. This project is not affiliated with or endorsed by the opencode team.
  • Three operations are declined by decision, not by omission. v2.config.get and v2.experimental.migration.v1.status hit an undiscriminated object-union wall; v2.fs.read is a framework wildcard route with no OpenAPI path template to bind. Admitting any of them would mean inventing a contract upstream does not declare. See API Coverage.
  • Two operations are transport-owned, not missing. v2.pty.connect and v2.persistentPty.connect are WebSocket upgrades, so they are served by the hand-written PtySession / PersistentPtySession doors rather than by generated code — fully usable, just not generated.
  • Pre-1.0 API. The public surface is locked by a reviewed baseline, but it may still move before 1.0.0. Breaking changes will be called out here with impact and migration path.