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.
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.
- The SDK pins opencode
2.4.3, where it pinned2.4.1. - Breaking:
MachineInfo.Online,Paired,Os,ArchandConnectionmove into a requiredStatus, anIMachineStatusthat isMachineStatusUnpaired,MachineStatusOffline,MachineStatusOnline(which carries theOs, theArchand theConnection, anIMachineTransport) orMachineStatusIncompatible(with itsIMachineRefusalreason), because opencode 2.4.3 reports one status per machine.MachineInfoConnection,MachineInfoConnectionKindandMachineInfoConnectionPathare removed. Before:if (machine.Online) Console.WriteLine(machine.Os);. After:if (machine.Status is MachineStatusOnline online) Console.WriteLine(online.Os);. - Breaking:
EventServerConnected.Datachanges fromIReadOnlyDictionary<string, JsonElement>toEventServerConnectedData, whoseStreamnames the live event stream, whichExperimentalClient.SubscribeSpacesAsyncaddresses. Before:connected.Data["…"]. After:connected.Data.Stream. ExperimentalClientmanages push notifications to phones:GetPushSettingsAsync,RegisterPushDeviceAsync,UpdatePushDeviceAsync,RemovePushDeviceAsync,SetPushDeviceSessionAsync,RemovePushDeviceSessionAsync,SetPushSessionAsync,RemovePushSessionAsyncandSetPushSettingsAsync, withExperimentalPushUpdatedon the event stream.ExperimentalPushDeviceRegisterRequest.CallbackUrlcarries the relay's delivery token, so the record's printed form masks it.ExperimentalClientreads and writes spaces, a shared key-value store:WriteSpaceValuesAsync,SyncSpacesAsync,SubscribeSpacesAsync,UnsubscribeSpacesAsyncandResetSpaceRevisionsAsync, withExperimentalSpaceUpdated,ExperimentalSpaceDeletedandExperimentalSpaceResyncon the event stream.ExperimentalClient.GetFeatureFlagsAsyncreturns the feature flags a location's clients may act on.ExperimentalClient.GetSkillFileAsyncreads one file of a skill.AgentInfo.Instructions(AgentInfoInstructions) holds an agent's added instructions: text, or anAgentSelectionInstructionswith the text sent while the agent is selected and the text sent once when the session switches away.SessionClient.PromptAsyncandExperimentalClient.ActivateSessionSkillAsynccan answer502SkillLoadError, andFileSystemClient.ReadFileAsync,ListEntriesAsyncandFindEntriesAsync,ExperimentalClient.WriteFileAsync,CreatePtyAsyncandRunShellCommandAsynccan answer503ServiceUnavailableErrorwhere the location cannot serve them.ConfigInfoExperimentalexposes theCompactionJobs,McpSkills,CodemodeAgentsandBrowserStreamTunnelflags,ModelCompatibility.SupportsSystemUpdatesis new, andModelTypegainsEmbedding,RealtimeandTranscription.- 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'stunnel.ticketRPC 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.
- 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.ResolveAsyncandOpenCodeServer.EnsureAsyncthrowOpenCodeServerExceptionnaming 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.
SessionInfo.Modelsays when opencode records a session's model: at creation, throughSessionCreateRequest.Modelor from a subagent's agent or parent, on a fork or import, and throughSwitchModelAsync. 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.
- The SDK pins opencode
2.4.1, where it pinned2.3.2. - Breaking:
BlobInfo.ExpiresAtis 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,McpEventsandSchedulesare 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 newConfigInfo.Automations. Before:new ConfigInfoExperimental { Automations = true }. After: nothing to set; to turn automations off,new ConfigInfo { Automations = false }. - Breaking:
ConfigInfoExperimental.VideoGeneratechanges frombool?toConfigInfoExperimentalVideoGenerate?, which holds either aBooleanor aConfigVideoGenerateOptionsnaming the video tool's defaultModel. Before:new ConfigInfoExperimental { VideoGenerate = true }. After:new ConfigInfoExperimental { VideoGenerate = ConfigInfoExperimentalVideoGenerate.FromBoolean(true) }. - Breaking:
VoiceModelgains requiredEngineandName, so code that constructs the record sets both. ExperimentalClient.CreateVideoGenerationAsyncandGetVideoGenerationAsyncno longer answer403ForbiddenError: opencode 2.4.0 no longer checks a flag before generating video. A video generation is listed as a background job,JobVideo, withJobKind.Video.ExperimentalClient.CancelJobAsync(experimental.job.cancel) cancels a background job, andExperimentalJobUpdated, withExperimentalJobUpdatedData, joinsIEvent;EventType.ExperimentalJobUpdatedfilters the event subscription toexperimental.job.updated.ExperimentalClient.ListMachinesAsync,AddMachineAsyncandRemoveMachineAsync(experimental.machine.list,.add,.remove) manage machines.AddMachineAsyncreturns aMachineInvitewhoseJoinis a single-use join string carrying the join secret; the record's printed form masks it.ConfigInfoExperimental.Machinesexposes 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:
AutomationShellActionInputcreates one, andAutomationActionShellreads it back. ModelInfo.Experimental.Speed(ModelSpeed) names a model's service tier, andConfigInfoExperimental.ModelSpeedsexposes its flag.ConfigInfoExperimental.HomeMemory,OpencodeApi,ProjectOverlay,RecommendedApiandSqliteFtsexpose 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
503ServiceUnavailableErrorwhile plugins load.Plugins.WaitForPluginsAsyncandLanguageModels.WaitForDefaultAsyncare unchanged and still poll the plugin list as opencode's CLI does.
Sessions.GetTotalCostAsyncreturns 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.
- An
OpenCodeApiExceptionwhose 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 "..".
- 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
*.updatedevents a long-lived application can refresh on. The README's streaming example and QuickStart no longer treat a503as "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.
- The SDK pins opencode
2.3.2, where it pinned2.3.0. - Breaking: schedules become automations, as opencode 2.3.1 replaced them.
ExperimentalClient'sCreateScheduleAsync,GetScheduleAsync,ListSchedulesAsync,PauseScheduleAsync,ResumeScheduleAsyncandDeleteScheduleAsyncbecomeCreateAutomationAsync,GetAutomationAsync,ListAutomationsAsync,PauseAutomationAsync,ResumeAutomationAsyncandDeleteAutomationAsync, and theSchedule*types,ExperimentalSchedule*requests and responses, andScheduleNotFoundErrorare removed forAutomation*,ExperimentalAutomation*andAutomationNotFoundError. An automation has a requiredName, aTrigger(AutomationTriggerAt,AutomationTriggerEvery,AutomationTriggerCron, orAutomationTriggerEventfor a connected MCP server's push event), and anActionthat sends a prompt or runs a Code Mode program; it has noIf,UntilorEnds. 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 withexperimental.automations;ConfigInfoExperimental.Schedulesstays 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 noIforUntilcondition and noEnds.Timeslimit, as automations with the same ID suffix and anaut_prefix, and deletes the rest, finished ones included. - Breaking:
ConfigInfoExperimental.BackgroundCompactionis removed, because opencode 2.3.1 replaced thebackground_compactionflag withcompaction.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'sCompaction. - Breaking:
ConfigInfoExperimental.ShellTimeoutBackgroundis 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 asGenerateVideoRunning,GenerateVideoCompletedwith the video's blob, orGenerateVideoErrorwith aGenerateVideoErrorReason, and answersVideoNotFoundErrorfor an unknown ID. The server keeps jobs in memory and enables them withexperimental.video_generate.ModelType.Videonames a video model.ExperimentalClient.GetBlobAsync(experimental.blob.get) streams a stored blob, such as a generated video, and answersBlobNotFoundErrorfor an unknown ID; opencode deletes blobs 7 days after writing them.JobKind.CodemodeandJobCodeModelist a Code Mode program as a background job, andExperimentalJobListRequest's kind filter accepts it.ConfigInfoExperimental.Automations,VideoGenerateandFullCodemodeexpose the new feature flags;FullCodemodeis off in every build unless set.
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.
EventsClient.SubscribeAsyncuses 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 throwsOpenCodeEventSubscriberOverflowException. A sole subscriber's overflow stops the source.- The first
server.connectedchanges 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
Errorexposes 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:
Typeswent 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.ReadinessTimeoutnow defaults toTimeout.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: setReadinessTimeout = TimeSpan.FromSeconds(60)to keep that failure, anOpenCodeServerExceptionnaming the bound; a cancellation token bounds the wait too, but ends the start withOperationCanceledException.- A background service registered without a password is used, as opencode's CLI uses it.
OpenCodeServer.Passwordisstring?: such a service is now discovered and reused, and its handle'sPasswordis null. Before:string password = server.Password;. After:string? password = server.Password;. LanguageModels.WaitForDefaultAsynccalls a mocking client'sGetDefaultAsyncdirectly. 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.DiscoverAsyncand the probeEnsureAsyncruns) 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 behindHTTP_PROXY,HTTPS_PROXYorALL_PROXYwithoutNO_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.1orlocalhost) toNO_PROXY, or to a system proxy's bypass list; the SDK has no proxy option of its own for discovery. .NET Framework is unchanged.
- Breaking:
SessionMessageUser.FilesandSessionInboxUserPayload.Filesnow containPromptAttachment, withPromptAttachmentKindselecting the unchangedPromptFileAttachment, the newPromptMediaFileAttachment, or rawUnknown. Before:PromptFileAttachment file = user.Files![0];. After:PromptAttachment file = user.Files![0];, then readfile.PromptFileAttachment.Dataorfile.PromptMediaFileAttachment.Uriaccording tofile.Kind. This also changes the files inSessionInboxEnqueued.Data.Item(SessionInboxEnqueuedData.Item→SessionInboxItemUser.Payload→SessionInboxUserPayload). A media file appears only with the experimentalexperimental-media-uricapability on; without it every element's known arm isPromptFileAttachment. Code that setsFileswraps 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.
- Experimental client-hosted MCP exposes application tools through
ConnectClientMcpover a reconnecting WebSocket, including text/image results and the browserCreateClientMcpConnectTokenAsyncdoor (OPENCODE001). ClientMcpSchema.FromTypeexports object input schemas from source-generated metadata without a new dependency.OpenCodeClientOptions.HttpHandleraccepts a caller-owned HTTP transport for requests and event streams on every target, and for terminal upgrades onnet10.0andnet11.0. The SDK never disposes it;net472andnetstandard2.0terminal upgrades keep their own socket transport.OpenCodeClientOptions.MediaReferencesasks the message and inbox reads for media references, as opencode's own client does withwithMediaRefs: when the session location'sexperimental.media_blobis on, a stored user file then reads asPromptMediaFileAttachment, andMediaReference.HashFromUri(file.Uri)gives the hashclient.Experimental.GetMediaAsyncfetches.OpenCodeRequestOptions.InlineMediastops 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.HeadersandOpenCodeRequestOptions.Headersset 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 headerMediaReferencessends replaces both. They do not reach terminal upgrades or background-service info probes;SubscribeAsyncrefuses per-call Headers. A 401's missing-credential hint now depends on whether the request carriedAuthorization, including a caller's header, rather than whetherPasswordwas set.OpenCodeServer.ResolveAsyncselects an explicit endpoint, an owned standalone server or the shared service with the CLI's precedence, including the saveddisabledflag. Connections expose resolve-timeServerVersion; explicit mismatches can invokeOnServerVersionMismatch. ManagedServiceOperationsreconnect or restart with a best-effort persistent-terminal handoff using the resolve-time snapshot.OpenCodeServerStopOptions.PtyacceptsOpenCodeServerStopPtyMode.Handoffso thatStopAsyncattempts a best-effort persistent-terminal handoff after it reads the registration and before it signals the process. Follow it withEnsureAsyncusing the same registration selection to restart as the managed connection does; preservation depends on preparing and adopting the ticket before it expires. Null andClearkeep the default: terminals end with the service, as with the CLI'sservice restart.Plugins.WaitForPluginsAsyncruns 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.WaitForDefaultAsyncnow runs it.OpenCodeServer.ShutdownPersistentPtyAsyncdiscovers 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()andWatchConnectionAsync(CancellationToken)exposeEventConnectionStateandEventConnectionStatus(Idle, Connecting, Connected, Reconnecting). Watches coalesce to the latest unread state and do not start or retain a source. OpenCodeEventSubscriberOverflowException.Capacityreports the SDK's fixed 4,096 bound, including for instances constructed through its standard public constructors.OpenCodeServer.FindIncumbentAsyncreports whether the registered background service that answers at a given URL is ready, starting or stopping, or failed (OpenCodeServerIncumbent,OpenCodeServerState), as opencode'sserve --servicechecks, before it binds, whether a compatible service already owns its address; it answers null when no compatible registered service answers there.RpcDefinitiondeclares a plugin's RPC definition once, withMethod(RpcMethod<TInput, TOutput>) andEvent(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 throwsOpenCodeRpcExceptionwith itsErrorType, its message andErrorData. It derives fromOpenCodeApiException, which is no longer sealed, so an existingcatch (OpenCodeApiException)still catches it.client.Events.SubscribeAsync(rpcEvent)yields one RPC definition's events asRpcEventPayload<TData>, the sharedEventRpcand 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 skipsserver.connected; read markers on a separate subscription to detect gaps. An event whose data does not match your type, or reads as null, throwsOpenCodeTransportException.OpenCodeServiceConfigurationadds typed administration of the background service's config, matching the CLI'sservice get,set, andunsetsurface.ReadAsyncreturns anOpenCodeServiceConfigwithout the password or remote route and migrates or repairs legacy config as the CLI's read does.GetOrCreatePasswordAsyncreturns 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)andUnsetEnvironmentVariableAsyncremove settings, andDisableRemoteAsyncturns remote access off. Sets and unsets stop the registered service first exceptSetDisabledAsync(false)and unsetting Disabled; nothing restarts it.OpenCodeServiceConfigOptionsselects 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.EnableRemoteAsyncturns remote access on through the installedopencode service set remote true, using theCliCommandandEnvironmentmembers ofOpenCodeServiceConfigOptions. OnlyEnableRemoteAsyncreads 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.
StopAsyncand theEnsureAsyncversion-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 anOpenCodeServerExceptionendedStopAsyncbefore it terminated the old service, and endedEnsureAsyncat once. After:StopAsyncterminates the old service;EnsureAsynckeeps polling, and the last replacement failure becomes the inner exception of its timeout. The caller's cancellation still ends both.- The
EnsureAsyncreplacement and the newStopAsynchandoff 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 anOpenCodeExceptioncould 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.13to the10.0.15servicing release: onnet472andnetstandard2.0,System.Text.Json,System.Threading.Channels,System.Collections.Immutable,Microsoft.Bcl.AsyncInterfaces,Microsoft.Bcl.MemoryandMicrosoft.Bcl.TimeProvider; inOpenCodeDotNet.Sdk.Extensions, on every target,Microsoft.Extensions.DependencyInjection.AbstractionsandMicrosoft.Extensions.Options.ConfigurationExtensions. No security advisory of the .NET 10.0.14 or 10.0.15 release lists these packages.
OpenCodeServiceConfiguration.SetCorsOriginsAsyncaccepted 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.CallAsyncruns until the plugin's method returns, as opencode's own client does: it no longer takes the client-wideNetworkTimeout(100 s by default). A per-callNetworkTimeoutstill 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.
- The streaming guide says that a turn's end and
client.Experimental.WaitForSessionAsynccover one session, not the background jobs its prompt started, and that a jobListJobsAsynclists is not necessarily still running. It recommends aMessagewith 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 ascancelledwith 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
RunShellCommandAsyncfor 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 innerWebSocketExceptionreplaces 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.persistand 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 experimentalMediaReferences. - The connection and getting-started guides explain that a null
Passwordomits SDK-generated Basic authentication, not callerAuthorization: client-wide headers can authenticate the shared feed, per-call headers cannot, and authenticated terminal upgrades requirePassword. 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 includesOpenCodeEventSubscriberOverflowExceptionand distinguishes subscriber overflow from retried attempt failures.- The terminals guide and
PersistentPtyConnectOptions.Takeover's andConnectAsync's XML documentation say a controller attach withoutTakeoverfails while another attachment controls the terminal: the server closes with 4404 andConnectAsyncthrowsOpenCodeTransportException, whose message names that case. The attach is not downgraded to an observer. CreateClient's XML documentation onOpenCodeServerandOpenCodeServerConnection, and its refusal message, state the identity rule it enforces:EndpointandPasswordmust stay null andUsernamemust stayopencode. 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.
- The SDK pins opencode
2.3.0, where it pinned2.2.6. - Breaking:
CredentialUpdated.Datachanges fromIReadOnlyDictionary<string, JsonElement>toCredentialUpdatedData, because opencode 2.2.7 declares the event's data as the required string membersIntegrationIdandCredentialId. A reader changesIReadOnlyDictionary<string, JsonElement> data = updated.Data;toCredentialUpdatedData data = updated.Data;and reads those members directly. - Breaking:
SessionGenerateDatagains requiredTokenUsageInfo Tokensanddouble Cost, so code that constructs the record sets both alongsideText; the generation's usage counts toward the session's totals. GeneratePredicateQuestion.Criteriaaccepts aGeneratePredicateQuestionCriteriawith optionalTrueandFalsestrings describing the two outcomes.ConfigInfoExperimental.ConsoleWatchesexposes the console-watch feature flag.SessionUsageRecordedDataSource.Generatenames usage recorded by session generation.ProviderSettings.TlsandConfigProviderSettings.TlsacceptProviderTls, with requiredCertandKeystrings and optionalPassphrase, for a provider gateway's mutual TLS. The three values are masked in the record's printed form.ToolFreeformFormatnamesText,RegexandLark;ModelCapabilities.FreeformandConfigModelCapabilities.Freeformlist the formats a model supports.ConfigInfoExperimental.McpEventsexposes the MCP-event feature flag.ConfigInfoExperimental.ShellTimeoutBackgroundexposes the shell-timeout-background feature flag.SessionMessageAssistantTime.FirstTokenrecords when the provider streamed the first output token, in epoch milliseconds, asdouble?.ExperimentalMcpEvent, withExperimentalMcpEventData, joinsIEvent, andEventType.ExperimentalMcpEventfilters the event subscription toexperimental.mcp.event.SessionStepFirstToken, withSessionStepFirstTokenDataandSessionStepFirstTokenDurable, joinsIEvent,ISessionEventDurable,ISessionLogItemandISessionScopedEvent;EventType.SessionStepFirstTokenfilters the event subscription tosession.step.first-token.AgentsClient.ListAgentsAsync(agent.list) no longer declares503, 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.Intervaldefaults toautoat opencode 2.3.0: 90% of the model'scache.ttl, or 4 minutes when the model has none. The default was 4 minutes, andautoskipped models without a ttl. The property's summary says so.- A failed persistent-terminal rename (
PersistentPtyClient.UpdateAsyncwith aTitle) answers404or503on opencode 2.3.0.501withPtyFeatureUnsupportedErrorstays declared, but the pinned server no longer answers it.
LanguageModels.WaitForDefaultAsyncnow 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. AServiceUnavailableErrorfrom that read now surfaces where it was retried up to twelve times. The call is unchanged:await client.LanguageModels.WaitForDefaultAsync();.OpenCodeServer.StopAsyncno 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'sservice stopdoes since opencode 2.3.0; ending the daemon still ends its terminals.- The status sentence of
OpenCodeApiException.Messagenow includes the server's own message, chosen as opencode's own client chooses it, for exampleThe opencode API returned status 503 ('ServiceUnavailableError'): opencode-pty request timed out..Error,StatusandRawBodyare unchanged; code that matched the old message text exactly now sees the longer text whenever the server sends a non-empty message.
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
401challenge asWWW-Authenticate: Basic realm="Secure Area", where it saidWWW-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.
- The SDK pins opencode
2.2.6, where it pinned2.2.5. - Breaking:
ConfigWarming.Intervalchanges fromstring? IntervaltoConfigWarmingInterval? Interval, because opencode 2.2.6 declares it as"auto"or a duration. A reader changesstring? interval = warming.Interval;tostring? interval = warming.Interval?.Value;; assigning a non-null string still compiles through the implicit conversion, while a nullstring?now throwsArgumentNullExceptionwhere it was a valid value, andConfigWarmingInterval.Autonames"auto". - Breaking:
IMcpServerConfiggainsbool? Pool { get; }, so a type outside the SDK that implements the interface adds that member.McpLocalConfig.PoolandMcpRemoteConfig.Poolset opencode's option to share one connection to a server across every directory that configures it identically. client.Experimental.ListJobsAsynclists the server's active and unconsumed background jobs:JobShell,JobSubagentandJobImagebehindIJobInfo.ExperimentalJobListRequestfilters them bySessionId,Descendants,KindandStatus.ProviderCache.Warmingis a provider's or model's cache warming, which overrides the top-levelConfigWarming: a boolean, orProviderCacheWarmingSettingswithIntervalandDuration.client.FileSystem.ReadFileAsyncreportsFsReadResponse.ContentTypeastext/plain; charset=utf-8for 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
OpenCodeTransportExceptionnaming 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.CompactAsyncandSessionClient.AddSyntheticMessageAsyncno longer declare a404LocationNotFoundError: opencode 2.2.6 stops resolving a location for these two calls, so a missing session is their only404.ConfigInfoExperimentalgainsAllFlags,PartRowsandCodemodeVm, the policy actions gainWebsearchUse, andIntegrationAttempt.Pastesays an automatic OAuth attempt also accepts the redirect URL pasted from the browser as its code.
- Disposing a standalone server on Linux and macOS now reports
Exitedwith code 143, where it was 130: the pinned opencode 2.2.6 exits with 143 onSIGTERM.SIGINTstill exits with 130, and Windows still reports code 1. - The packages are built on the GA .NET 11 SDK (
11.0.100), where1.0.0was 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).
- The domain glossary is
GLOSSARY.md(previouslyCONTEXT.md), and the getting-started guide points there. OpenCodeServer's andOpenCodeServer.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,
IMcpServerConfigamong 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 andOpenCodeServerExitKind'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.
- The version rule differs from the one
1.0.0stated. A version follows the bump type of the upstream opencode release it pins, where1.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 said1.0.1would have no API change; it moves the pin to opencode2.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.
client.LanguageModels.WaitForDefaultAsyncreturns the default model, asking again while the location's plugins activate. On a503ServiceUnavailableErrorit 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 refusesNoThrowat the call, as streams and cursor traversals do.
- 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
net472andnetstandard2.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 onnet472goes 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; onnet472, 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 onnet472the 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.
- 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 onlyResizeAsyncchanges 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.
EnsureAsyncwarns 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.
- 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.0is built on the go-live .NET 11 release-candidate SDK, a one-time exception to the GA-SDK rule;1.0.1rebuilds 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.
- 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,OnStartandOptional<T>entries are the SDK's own. - The session log moves to
ExperimentalClient.ReadSessionLogAsync. Upstream serves it asexperimental.session.log, soSessionClient.ReadLogAsyncis gone andSessionLogRequestisExperimentalSessionLogRequest, with the sameAfterandFollow. Migrateclient.Sessions.GetSessionClient(id).ReadLogAsync(new SessionLogRequest { … })toclient.Experimental.ReadSessionLogAsync(id, new ExperimentalSessionLogRequest { … }). The session-log types now carryOPENCODE001, the experimental client's diagnostic, andOPENCODE003is retired: a suppression ofOPENCODE003becomes one ofOPENCODE001. ExperimentalClient.SetVoiceSessionInstructionsAsyncis removed, withExperimentalVoiceInstructionsRequestandExperimentalVoiceInstructionsResponse: upstream removed the operation.EventsClient.SubscribeAsynctakes an optionalEventSubscribeRequestfirst. ItsTypeslimits the stream to the listed event types. A call that passedrequestOptionsby position names it instead:SubscribeAsync(requestOptions: options).- Model variants have their own settings type.
ModelVariant.SettingsisModelVariantSettings?andConfigModelVariants.SettingsisConfigModelVariantSettings?, as upstream separates a variant's settings from a model's. VoiceModel.Integration,VoiceModel.WorkspaceandExperimentalVoiceSessionData.Sessionare removed, withVoiceSessionReference: upstream no longer declares them.ConfigInfoCompaction.BufferisConfigInfoCompactionBuffer?, notlong?. Upstream now accepts a share of the context window such as"20%"besides a token count, so the value is a carrier:Kindsays which arm it holds,Textthe percentage andWholeNumberthe token count. Migrateconfig.Compaction.Buffertobuffer.WholeNumberafter checkingbuffer.Kind == ConfigInfoCompactionBufferKind.WholeNumber, and set it withConfigInfoCompactionBuffer.FromWholeNumber(...)orFromText("20%").PersistentPtyInfo.UserTitleis required. It is the title a user gave the terminal, ornullwhen 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 aPersistentPtyInfomust set it.PersistentPtyUpdateRequest.Sizeis 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.ReasoningFieldandProviderCompatibility.ReasoningFieldareModelReasoningField?,TuiCommandExecuteData.CommandisTuiCommandName,ConfigWebSearchInfo.ProviderisWebSearchProviderChoice, andSessionInstructionsUpdatedData.Delta's values areSessionInstructionChange. Migrate a comparison withModelReasoningField.ReasoningContent(or the type'sValuesstrings), and read the text withToString(); nothing on the wire changes. IMcpis nowIMcpServerConfig, andUnknownMcpis nowUnknownMcpServerConfig. The union represents one MCP server's configuration, the value type ofConfigInfoMcp.Serversand ofExperimentalMcpAddRequest.Config. Migrate by renaming type references;IMcpTimeoutkeeps its name, and nothing on the wire changes.PermissionsClient.UpdateSavedAsynctakessavedPermissionId. Its route value was a bareid; it now matchesRemoveSavedAsync. Only calls that name the argument (id: …) need to change; nothing on the wire changes.OpenCodeServerEnsureOptions.OnStartnow takes anOpenCodeServerEnsureStartContext.Action<OpenCodeServerEnsureReason, string?>becomesAction<OpenCodeServerEnsureStartContext>. Migrate(reason, previous) => …tostart => … start.Reason … start.PreviousVersion.Optional<T>.Valueis annotated[MaybeNull]. Reading anOptional<string>(non-nullableT) may produce a new nullable warning. Migrate a receivingstringlocal tostring?and check for null before dereferencing it.
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 (
HttpClientalone 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
JsonElementdictionary 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, andClone()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
PtySessionframe keeps the UTF-8 it was received as.PtyOutputFrame.Textdecodes 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.
- Rename persistent terminals through
PersistentPtyClient.UpdateAsync. SetTitleto a non-empty string, or null to clear the user's title; a terminal service that predates renaming answers 501 withPtyFeatureUnsupportedError. - Deleting a session now removes its persistent terminals.
- The operations the refresh adds.
ExperimentalClientgainsWatchFileAsync,UnwatchFileAsync,GenerateDecisionsAsync,GenerateImagesAsync,GetMediaAsync,GetUsageLimitsAsync, and the schedule operationsCreateScheduleAsync,GetScheduleAsync,ListSchedulesAsync,PauseScheduleAsync,ResumeScheduleAsyncandDeleteScheduleAsync;PluginsClientgainsGetGuiAsync.event.subscribetakes atypesfilter ofEventTypevalues, andmodel.listtakes atypesfilter. 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 themSessionInfoTime.Busy, aCachesetting on models and providers,ConfigInfo.TimezoneandVcsDiffRequest.Untracked, and a local plugin'sPluginSourceLocal.Pathis now the path it was configured with.ExperimentalClientalso gains the artifacts operationsListArtifactsAsync,GetArtifactAsync,CreateArtifactAsync,UpdateArtifactAsync,DeleteArtifactAsync,ListArtifactProvidersAsyncandGetArtifactFileAsync; they needexperimental.artifactsin the location's config. The event stream gainsArtifactUpdatedandPersistentPtyUpdated, the error family gainsArtifactNotFoundErrorandPtyFeatureUnsupportedError,ConfigInfoExperimentalgainsArtifacts, and policy actions gainintegration.connect,mcp.use,skill.useandplugin.use. A schedule's condition is a shell check or a Code Mode script:ScheduleInfo.IfandUntilareIScheduleCondition?, andScheduleConditionInputis built withFromScheduleConditionInputRunorFromScheduleConditionInputCode. Other new members includeConfigInfoExperimental.Schedules,MediaBlobandImageGenerate,PromptInputFileAttachment.Source,ModelCompatibility.MediaInput,ModelInfo.Type,ServerInfo.Hostname,FileDiffInfo.More,McpServer.TitleandPluginFeatures.Gui. - Clearer IntelliSense documentation.
EnumerateSessionsAsyncandEnumerateMessagesAsynclink their page methods and carry those methods' summaries;server.connectedrenders as code inSubscribeAsync's remarks. - Known stream tags can now arrive as the unknown arm. On
event.subscribeand the session log, a frame whose normal decoding fails arrives asUnknownEventorUnknownSessionLogItemwhen 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 withis EventServerConnectedor a replay boundary withis EventLogSyncedshould matchTypeagainst"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'sEndsTurnandSessionOfhelpers 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
JsonElementdictionary no longer compare equal by default. Repeatedtrue,falseandnullvalues no longer compare equal underJsonElement's default equality; compare JSON values withJsonElement.DeepEquals, as System.Text.Json recommends.
- Response envelope logging keeps the page cursor and resolved location.
ToString()now includesCursorandLocationwhen the response has them, so a logged page such asSessionListResponsekeeps 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.StartAsyncrefuses a NUL in anOpenCodeServerOptions.CommandorOpenCodeServerOptions.Environmententry, or inOpenCodeServerOptions.WorkingDirectory, withArgumentExceptionbefore 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'sParamNameisoptions, 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
OpenCodeServerExceptionfromOpenCodeServer.StartAsyncwas 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.EnsureAsyncrefused a NUL in anOpenCodeServerEnsureOptions.Environmententry but not in aCommandentry, so a command entry with a NUL could reach the contender's spawn and be cut short there. It now refuses it withArgumentExceptionforoptionsbefore 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_homemoved the registration away from clients looking under the host's root. A caller'sPATHstill replaces the host'sPath. - A saved
XDG_STATE_HOMEno longer moves a background service.EnsureAsyncused 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 ownEnvironmententry still applies. - A persistent PTY's bad
Cwdis now refused. A givenCwdwhose path doesn't exist or isn't a directory used to start the terminal in the home directory. The server now answers 400 with anInvalidRequestErrorwhoseKindisinvalid_cwd, and no terminal starts. The SDK's code didn't change.
- 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, andPersistentPtyHandoff.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.
- Protocol model changes.
Recentis removed from compaction messages and event data.ProviderState,State,ResultStateandProviderResultStatebecomeNativeacross assistant messages, parts and turn events.SessionProviderContextandSessionProviderContextProvenanceare deleted, along withProviderContexton completed compaction messages and compaction-ended data;CredentialKey.Configurationis removed.ExperimentalSessionImportRequest.Messagesnow takesIReadOnlyList<JsonElement>;ToolFileContent.NameandSessionMessageLocationSwitched.PreviousloseOptional<>.
- New protocol doors and members.
DebugClient.WriteHeapSnapshotAsync,PermissionsClient.UpdateSavedAsync, and experimentalListVoiceModelsAsyncandSetVoiceSessionInstructionsAsyncjoin the surface, and experimental voice session responses gainSession, aVoiceSessionReference. Sessions gainArchivedfilters and updates and archived/unarchived events; models and provider compatibility gainStreamUsage, structured errors gainRetryAfterMs, and experimental config gainsTodo,BackgroundCompactionandLocationIdleTimeout. - Persistent PTYs work on Windows hosts. opencode 2.1.x ships the
opencode-ptydaemon for win32 too, socreateno longer answers the daemon-absent 503 there.
- 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-Alivehint, and now does so after three. Thenetstandard2.0asset on a modern .NET runtime keeps the four seconds.
- 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, aProcesswait 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.
- The SDK speaks opencode 2.0.32.
ExperimentalClient.CreateVoiceSessionAsyncopens an experimental voice session over WebRTC or WebSocket.ConfigModelCapabilities.Reasoningtells a model that does not reason (ConfigModelReasoningUnsupported) from one that does (ConfigModelReasoningSupported, with its toggle, efforts andConfigModelReasoningBudget);ConfigModelCapabilities.TemperatureandModelCapabilities.Temperaturesay whether a model takes a temperature, andConfigModel.ReleaseDatecarries its release date.
- A spawned background service's saved
envwins after startup.OpenCodeServerEnsureOptions.Environmententries still win over the channel's service-configenvat spawn, but a 2.0.32 service re-applies its savedenvwhen it starts, so a key set in both takes the saved value for everything the service reads after startup.
- Stopping a background service waits for its child process to be reaped. On Linux and macOS,
OpenCodeServer.StopAsyncno 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'
SeqandVersion, the MCP timeouts andCodemode, inbox and compactionCreatedtimes) 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.
- Isolating a background service needs separate state and config roots. The connection-modes
guide now says to give
XDG_STATE_HOMEandXDG_CONFIG_HOMEdifferent directories: the registration and the CLI's service configuration are both namedservice.json, so one folder for both makes them the same file, andEnsureAsyncthen fails now and then on Windows withEPERM. - A stopped service's files unlock a moment after
StopAsyncon Windows. The connection-modes guide now says that the daemon'sopencode.db-shmand-walstay 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.
-
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: tokenwhen omitting the new options argument. Calls that omit options keep their behavior. Streams and traversals refuseNoThrow; the event bus also refuses a per-callNetworkTimeout, includingTimeout.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
requestOptionsin exceptions. An undefinedErrorBehavioron a one-shot call now reportsArgumentOutOfRangeException.ParamNameas"requestOptions"rather than"options", and the new stream and traversal refusals name"requestOptions"too. -
IOpenCodeStreamFailureCauseexposesTag. Every cause inOpenCodeStreamFailureException.Causesexposes its wire tag without a cast, including an unknown cause. Custom test implementations must supply the property.IStreamFailureCauseinherits it rather than redeclaring it; concrete causes and their wire representation are unchanged. -
Instruction-entry DTO names retain
Put.ExperimentalSessionInstructionsEntryRequestis nowExperimentalSessionInstructionsEntryPutRequest, andExperimentalSessionInstructionsEntryResponseis nowExperimentalSessionInstructionsEntryPutResponse.ExperimentalClient.SetSessionInstructionsEntryAsynckeeps its method name. -
The instruction-entry list method names its subject in the plural.
ExperimentalClient.ListSessionInstructionsEntryAsyncis nowListSessionInstructionsEntriesAsync, andExperimentalSessionInstructionsEntryListResponse.SessionInstructionsEntryis nowSessionInstructionsEntries. -
The session log uses stream-reading terminology.
SessionClient.GetLogAsyncis nowReadLogAsync; its request and stream item types and its behavior are unchanged. -
OpenCodeRoutesis 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.ContentitemISessionMessageAssistantContentEncodedISessionMessageAssistantContentUnknown assistant-content record UnknownSessionMessageAssistantContentEncodedUnknownSessionMessageAssistantContent -
PTY requests share
PtySize. Replace the three old size names withPtySize. ItsColsandRowsmembers remain requiredlongvalues. The persistent requests remain experimental. Thepty.updatebody now writescolsbeforerows, which the server does not observe.Property Was Now PtyUpdateRequest.SizePtyUpdateSize?PtySize?PersistentPtyCreateRequest.SizePersistentPtyCreateInputSize?PtySize?PersistentPtyUpdateRequest.SizePersistentPtyUpdateInputSizePtySize -
Boolean query parameters use
bool?.QueryBooleanis removed. Passtrueorfalse, notQueryBoolean.TrueorQueryBoolean.False; leave the member null to omit it. The query text remains lowercasetrueorfalse.Property Was Now SessionLogRequest.FollowQueryBoolean?bool?SessionInterruptRequest.ResumeQueryBoolean?bool?ProjectListRequest.ArchivedQueryBoolean?bool?ExperimentalSessionExportRequest.SanitizeQueryBoolean?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, notLimit = "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.Limitstring?int?VcsBranchListRequest.Limitstring?int?ShellOutputRequest.Limitstring?int?ShellOutputRequest.Cursorstring?long?PersistentPtyReadRequest.Linesstring?int?SessionLogRequest.Afterstring?long?SessionDiffRequest.Contextstring?int?VcsDiffRequest.Contextstring?int?ExperimentalSessionStatsRequest.From,.To(milliseconds since the Unix epoch)string?long? -
OpenCodeApiExceptionandOpenCodeServerExceptionare sealed. They can no longer be used as base classes; their constructors and error data are unchanged. -
SessionParentFilteris a record with value equality. Filters for the same parent compare equal and have the same hash code, soSessionListRequestrecords built with equal filters compare equal too.ToString()identifiesRootOnlyorOfand includes the parent id forOf.
-
Per-call
Locationapplies to streams and automatic cursor traversals. PassOpenCodeRequestOptionsto 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-callNetworkTimeoutbounds only opening the session log, and bounds each page request separately on a traversal, not the whole walk. -
OpenCodeClientOptions.EventStreamIdleTimeoutsets 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 mostint.MaxValuemilliseconds is accepted, but notTimeout.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
switchand in patterns. Every generated enum carries its pinned wire spellings asconst stringmembers of a nestedValuesclass, and aValueproperty that returns a value's spelling. Match one against the other in acaselabel 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,
==,IsKnownand the wire format stay as they were.
- 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.
- 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
Valueread "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
OpenCodeServerExceptionmessages. - Caller cancellation preserves your token across public async doors: HTTP, SSE, cursor
traversal, both terminal families, and
OpenCodeServer.StartAsync,DiscoverAsync,EnsureAsync, andStopAsync.OperationCanceledException.CancellationTokenis 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
OpenCodeServerExceptionnaming the command, with the underlyingIOExceptionretained. - 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-Lengthwhen 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.
AddOpenCodekeeps existing client registrations. Calling it again does not add anotherOpenCodeClientor 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.
-
EventsClient.SubscribeAsyncreconnects, 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
EventServerConnectedinstead.OpenCodeClientOptions.NetworkTimeoutno 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 disableor<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, todaySessionClient.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
OAuthas the brand does. Names built from operation ids and wire members saidOauth, beside the schema-derivedCredentialOAuthandMcpOAuthConfig. They are nowBeginOAuthConnectionAsync,CancelOAuthConnectionAsync,CompleteOAuthConnectionAsync,GetOAuthStatusAsync, theIntegrationOAuth*request and response types with theirOAuthConnectandOAuthStatusmembers,McpRemoteConfigOAuth(with itsKind), theOpenCodeRoutesbuilders and templates, and theOAuthvalue ofConnectionCredentialInfoMethod. Rename the uses; nothing on the wire changes. -
The shell and saved-permission ids have descriptive parameter names.
ShellsClient.GetShellClient, and theOpenCodeRoutes.Shellsbuilders, takeshellId.PermissionsClient.RemoveSavedAsyncandOpenCodeRoutes.Permissions.RemoveSavedtakesavedPermissionId.- 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,SessionInboxDeliveryandAgentInfoMode, is now areadonly 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.Committedstill compiles. -
IsKnownreports whether this SDK's pin defines a value.new VcsMode("…"), the implicit conversion fromstring, andFromStringcreate 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
defaultvalue has no spelling. A request body or query refuses it. -
What breaks: enum values used as constant patterns, and code that relied on
enumbehaviour (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) { /* … */ }
-
-
ISessionScopedEventroutes an event by its session. Every event whose payload names the session it happened in (58 at the pin: thesession.*events,permission.asked/replied,persistent-pty.added/removedandtui.session.select) implements it, soe 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". -
NetworkTimeoutsets how long a call may go without network progress.OpenCodeClientOptions.NetworkTimeoutsets it for the client andOpenCodeRequestOptions.NetworkTimeoutfor one call; the default stays 100 seconds.WaitForSessionAsync,RunShellCommandAsync,RunCommandAsyncand bothGenerateTextAsyncmethods (onSessionClientandExperimentalClient) 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.CreateClientcarries the client value over. See Requests.
- 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.Internalnamespace. The public API is unchanged, byte for byte; only internal type names differ, as a stack trace or reflection shows them.
- 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
reasononsession.execution.interrupted, failed to materialize and ended the subscription withOpenCodeTransportException. The frame now reads as its typed event, with the value kept (IsKnownis 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.
- The streaming guide streams an answer as it arrives. The recipe follows upstream's own client:
- wait for
EventServerConnectedbefore you prompt; - prompt with your own
msg_id, and match it toSessionInboxDelivered'sInboxId; - append
SessionTextDeltatext, and replace it withSessionTextEnded's finalText; - stop on the session's execution event.
- wait for
- The requests guide names the session-create location.
SessionCreateRequest.Locationis a bodyLocationPublicRef, not theLocationSelectorthat headers and queries use. The guide also shows that a collection expression cannot fill anOptionalcollection member (CS9174). - The terminals guide documents the two normal-PTY gaps. It says which shell a PTY gets without a
Command: the configuredshell, then$SHELL, then a per-OS fallback. It also shows how to resize a normal PTY, throughPtyClient.UpdateAsyncwithSize. - The connection guide keeps a launched server around a host, and fixes the 401.
- A launched server stays in
await usingaround the host'sRunAsync. The container does not dispose a handle you register. - A passwordless 401 carries the typed
UnauthorizedError, not an empty body.
- A launched server stays in
- The guides wait for a turn on the execution events, not on
SessionIdle. The pinned server never publishessession.idleorsession.status, so a loop that waited forSessionIdlenever ended. A turn ends with exactly one ofSessionExecutionSucceeded,SessionExecutionFailedorSessionExecutionInterrupted.
- 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.0asset needs the .NET 11 runtime, and anet10.0app keeps using thenet10.0asset.
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.
- The packages target
netstandard2.0,net472,net10.0, andnet11.0.net8.0andnet9.0leave ahead of their end of support on 2026-11-10, andnet11.0joins on its go-live release candidate.0.9.0-preview.9is the last version withnet8.0andnet9.0assets. Anet8.0ornet9.0project still installs the packages through thenetstandard2.0asset, 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 tonet10.0or later. A project that treats warnings as errors fails its build on it until it does one or the other. OpenCodeServerOptionsrefuses an out-of-range timeout when it is set.ReadinessTimeouttakes a value above zero and at mostint.MaxValuemilliseconds, orTimeout.InfiniteTimeSpanto wait until the start's cancellation token fires;GracefulShutdownTimeouttakes zero toint.MaxValuemilliseconds. A value outside that range throwsArgumentOutOfRangeExceptionfrom the setter. A zero or negative readiness timeout and a negative grace were refused byOpenCodeServer.StartAsyncbefore; a value past the ceiling was accepted and failed only after the server had been spawned.IOpenCodeClientOptionsis removed. No public API accepted it, and every option added later would have broken its implementers, becausenet472andnetstandard2.0have no default interface members. Configure clients throughOpenCodeClientOptions, which a client still snapshots at construction. Code that declared a variable or parameter asIOpenCodeClientOptionsusesOpenCodeClientOptionsinstead.OpenCodeStreamFailureException.Causeis nowCauses. It is a list of causes, so the name is now plural. The constructor parameter is nowcausesas well. Readfailure.Causeswhere you readfailure.Cause, and passcauses:where you named the argument.PersistentPtyReplayBoundstakes camelCase constructor parameters. They arerequestedOffset,availableOffset,endOffsetandtruncated, like the other frame types' constructors. The properties keep their names, and positional construction,withand deconstruction are unchanged. Only a call that named an argument (RequestedOffset: 0) changes.
OpenCodeServer.Exitedreports how a started server ended. The task completes with anOpenCodeServerExit. It holds an exit code (on Windows the full 32-bit code), a terminating signal by name and number, orUnknownwhen 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'sexiteddoes. It never faults. On a handle fromDiscoverAsyncorEnsureAsyncit throwsInvalidOperationException, 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 withnpm install -g @opencode/cli@2.0.29. It adds and changes no operation, so all 142 remain callable. - Provider compatibility defaults.
ProviderInfo.CompatibilityandConfigProvider.Compatibilitycarry aProviderCompatibility, the defaults a provider's models inherit:ReasoningField,RequireReasoning,MaxTokensField,RequireFinishReason,RequireAssistantAfterTool,SupportsPromptCacheKey, andCacheFormat. - Prompt-cache marker format.
ModelCompatibility.CacheFormatandProviderCompatibility.CacheFormatname the marker syntax the endpoint accepts, as the newModelCacheFormatenum (Anthropic,Alibaba). - Request-body encoding.
ProviderSettings.Encoding,ConfigProviderSettings.Encoding,ModelSettings.Encoding, andConfigModelSettings.Encodingname the compression upstream applies to the provider request body, as the newProviderEncodingenum (Zstd,Gzip,None). - Top-level config policies.
ConfigInfo.Policiescarries the ordered policies that control access to providers, tools, and integrations, as the newConfigInfoPolicies(Action,Resource,Effect) with the newConfigInfoPoliciesAction(ProviderUse,ToolUse,IntegrationUse) andConfigInfoPoliciesEffect(Allow,Deny) enums. Upstream deprecatesexperimental.policies: a 2.0.29 server reports those policies here, andConfigInfoExperimental.Policiesstaysnull.
- The packages depend on the .NET 10.0.13 servicing builds of their dependencies.
OpenCodeDotNet.SdkrequiresSystem.Text.Json,Microsoft.Bcl.AsyncInterfaces,Microsoft.Bcl.Memory,Microsoft.Bcl.TimeProvider,System.Collections.Immutable, andSystem.Threading.Channels10.0.13 onnetstandard2.0andnet472, up from 10.0.11; itsnet10.0andnet11.0assets declare no dependency.OpenCodeDotNet.Sdk.ExtensionsrequiresMicrosoft.Extensions.DependencyInjection.AbstractionsandMicrosoft.Extensions.Options.ConfigurationExtensions10.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
OpenCodeServerExceptionthatOpenCodeServer.StartAsyncthrows then carries the readiness bound'sOperationCanceledExceptionas itsInnerException, which wasnull. - A settings
encodingmember is read as the typedEncoding. OnProviderSettings,ConfigProviderSettings,ModelSettings, andConfigModelSettingsit is no longer inAdditionalProperties, where0.9.0-preview.9kept 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.
- 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.Exitedcompleted 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.EnsureAsyncstarted through a.cmdor.batshim on Windows opens no console window. With a batch shim such as npm'sopencode.cmdas 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.exestill starts detached, with no console.- On Unix under Mono, a failed
chmodof an owner-only file fails its write. Thenetstandard2.0andnet472assets set mode0600on the files discovery andEnsureAsyncwrite through achmodchild 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.
- 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.0asset needs the .NET 11 runtime, and anet10.0app keeps using thenet10.0asset. - 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.
- 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/failuretoeffect/http-api/stream/failure. Against a 2.0.27 server a failure onEventsClientor the session log surfaces asOpenCodeStreamFailureExceptionwith its typed causes; against an older server it surfaces asOpenCodeTransportExceptionnaming the undeclared frame. On0.9.0-preview.8it was the other way round. OpenCodeRoutes.Projects.ListProjectsis now a method.project.listtakes an optionalarchivedquery, so the route helper isListProjects(ProjectListRequest? request = null)and the template constant isListProjectsTemplate.ProjectsClient.ListProjectsAsyncgains a leading optionalProjectListRequest? requestparameter: a call that passesrequestOptionspositionally moves it one place, and the change needs a recompile.
- The accepted snapshot moved to upstream release tag
v2.0.27(1f4d07a4a519185955ae8ab2ea3607805509e386), published as@opencode/cli@2.0.27; install it withnpm 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.Archivedcarries when it was archived, andproject.listleaves archived projects out unlessProjectListRequest.ArchivedisQueryBoolean.True. SessionMessageIdle.Errorcarries theSessionStructuredErrorof a turn that went idle with a failed outcome.
- The
netstandard2.0andnet472assets depend onMicrosoft.Bcl.TimeProvider. The request progress window and the standalone launcher's output drain now run onTimeProvider, whichnet8.0and later carry inbox. Behaviour does not change: both still run on the system clock. - The background-service config reader validates
remoteAcceptedas upstream 2.0.27 decodes it. The CLI records an accepted remote access as the literaltrue; a document whoseremoteAcceptedis anything else is no config at all, so itsenvoverlay 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.connector persistent-terminal connection, it now closes with 1001 or 1011, whichPtySessionandPersistentPtySessionreport 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.ListEntriesAsyncreports a missing directory as the typedFileNotFoundError, which upstream 2.0.27 now answers, and declares onfs.list's 404 besideLocationNotFoundError; an older server answered an undeclared server error.
OpenCodeServer.DiscoverAsyncandEnsureAsyncread 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.
net8.0andnet9.0leave the packages, andnet11.0joins, in an upcoming preview, ahead of their end of support on 2026-11-10; this release still ships them. The packages will then targetnetstandard2.0;net472;net10.0;net11.0. An app on .NET 8 or 9 still installs through thenetstandard2.0asset, 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 that0.9.0-preview.8noted 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.
ConfigInfoExperimentalPoliciesAction.Permissionis nowToolUse. Upstream 2.0.26 renames the experimental policy actionpermissiontotool.useand addsintegration.use, which gates MCP servers and skills, so the enum's members areProviderUse,ToolUse, andIntegrationUse. A 2.0.26 server drops apermissionpolicy entry when it loads its config; against an older server whose config still has one, reading the config fails to decode.
- The accepted snapshot moved to upstream release tag
v2.0.26(9b4ec5714d481559990db0a816d5dec19541a814), published as@opencode/cli@2.0.26; install it withnpm 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 byMethodIdwith an optional formAnswerandLabel, and stores a reference to its credential source. The integration lists such a method asIntegrationExternalMethod, and the stored credential reads asCredentialExternal(MethodId,Metadata). The route helper isOpenCodeRoutes.Integrations.ConnectWithExternalCredentials. Behaviour change: on0.9.0-preview.7a 2.0.26 server'sexternalmethod surfaced asUnknownIntegrationMethod, and itsexternalcredential value asUnknownCredentialValue. ConnectionCredentialInfoMethod.Externalnames a credential stored through an external method. Before, a server that returned one failed the decode of its connection.ModelCompatibility.SupportsThinkingBlockBindingandSupportsEffortUpdatescarry the two compatibility flags upstream 2.0.26 adds.
- On Windows a standalone server is placed in a job that ends it with its owner, however the owner
ends.
StartAsynccreates 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 withERROR_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 withOpenCodeServerExceptionand leave nothing running. - With the default npm install, pass the path of
opencode.exeinCommandfor that guarantee. The bareopencoderesolves to npm'sopencode.cmdshim, which runs throughcmd.exe: the job then holdscmd.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.cmdfile 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
Outputcollector 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
taskkillrun, about 300 ms, where a server that left on its stdin's end-of-stream used to take about 10 ms. GracefulShutdownTimeoutnow starts with that first kill and bounds it: when the server is still running at its end, the same kill runs once more, andTerminateProcessends 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.0and later the forced end istaskkill, 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
StartAsynccan take up to the grace plus 26 seconds to throw. - On
net8.0and later the descendants of a server that exits before readiness are no longer ended: the runtime's tree kill used to end them, buttaskkillreaches no descendant of an exited root, so it does not run.
- 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
- 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.
StartAsyncon 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
WorkingDirectorycounts 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=1in 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
ArgumentExceptionon Windows too, before anything is spawned, and a spawn that fails in aWorkingDirectorynames the directory. StopAsyncand 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 whileStopAsyncwas asking the old one to shut its terminals down is the one stopped, where it used to be left running.- The service config's
remotekey is read as upstream reads it. Remote access is set only through the CLI (opencode service set remote true, oropencode pair --remote); the SDK reads the key and never writes it. While the service's tunnel is attached, its remote URL is listed inServerInfo.Urls. Behaviour change: aremotethat is neither an object holding a stringroutenor the legacy boolean makes the whole document no config, as upstream decides, so itsenvoverlay 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.7ignoredremotein 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
OpenCodeTransportExceptionmessage 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.ReadFileAsyncwith a path that leaves the location answers the declared 404 with a typedFileNotFoundError. 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, andErroris aFileNotFoundError.- A server bound to every interface lists its loopback URL first in
ServerInfo.Urls. Upstream 2.0.26 putshttp://127.0.0.1:{port}(orhttp://[::1]:{port}) before the interface addresses of a server bound to0.0.0.0or::.
OpenCodeServer.EnsureAsyncstarts 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.Starton 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.
net8.0andnet9.0leave the packages, andnet11.0joins, in an upcoming preview, ahead of their end of support on 2026-11-10; this release still ships them. The packages will then targetnetstandard2.0;net472;net10.0;net11.0. An app on .NET 8 or 9 still installs through thenetstandard2.0asset, 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 lacksLocationNotFoundError, and with it the 404 that location-scoped operations declare for a missing location, and it lacksintegration.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.
WorktreeErroris a tagged error. Upstream 2.0.23 declares it with_tagbeside itsnameanddata, soTagreads_tagand a new requiredNamecarriesname. A body without_tag, from a server older than 2.0.23, no longer decodes to a typed error:Erroris null andRawBodykeeps the body._tagis the only error marker. Every error the 2.0.23 contract declares is tagged, so anameis no longer read as an error's marker:- Any error body whose only marker is
name, not just a worktree failure, no longer decodes toUnknownOpenCodeError:Erroris null andRawBodykeeps the body. - The public
UnknownOpenCodeError(tag, payload)constructor throwsArgumentExceptionfor a payload whose only marker isname; the payload must carry the tag under_tag.
- Any error body whose only marker is
OpenCodeServer.EnsureAsyncthrowsOpenCodeServerExceptionon a service whose health protocol is incompatible, where it used to replace it. A registered daemon that answers/api/infowith 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 withStopAsyncto replace it.OpenCodeServer.StartAsyncrefuses POSIX systems other than Linux and macOS, FreeBSD among them, withOpenCodeServerExceptionbefore anything is spawned; they used to start throughProcess. On Linux and macOS a NUL in a command entry or an environment entry is now refused withArgumentException, because the C string it is passed as would end there.
- The accepted snapshot moved to upstream release tag
v2.0.23(0fd7e2829449b052abf0078666669302923d77af), published as@opencode/cli@2.0.23; install it withnpm 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 optionalProvider(git by default); a provider without initialization answers 501VcsInitNotSupportedError. The route helper isOpenCodeRoutes.Vcs.InitializeRepository. - A missing directory is a typed 404. Every location- and session-scoped route, and
experimental.generate.text,session.diff, andsession.permission.listby name, now declareLocationNotFoundError(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 itsOpenCodeTransportExceptionnow names both causes: the PTY session or the requested location does not exist. ServerInfo.Capabilities.PersistentPtysays whether the server can run the persistent-terminal daemon:falseon Windows, whereopencode-ptyships no binaries. A server older than 2.0.23 leavesCapabilitiesnull.
- 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
SIGTERMto the server's process group, andSIGKILLto whatever is left of the group afterGracefulShutdownTimeout, as upstream's own launcher does. Behaviour changes:- The pinned server answers the
SIGTERMby 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
SIGCHLDon Linux, or runs as pid 1); one that exited with code 0 or on a signal leaves them alone, as before.
- The pinned server answers the
- A failed
StartAsyncon 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 afterSIGKILL, 1 for draining its output, and 5 for releasing the output readers. Behaviour change: it used to kill the server at once. StartAsyncon 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.WorkingDirectoryworks 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 blankWorkingDirectorycounts 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:Processtried 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=1in 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.EnsureAsyncreports 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.
StopAsyncand the Ensure replacement end the service even when the sidecar cannot be removed. Behaviour change:StopAsyncused to throwOpenCodeServerExceptionwhen it could not remove the sidecar. StopAsyncescalates 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
IsAotCompatibleon every modern target (net8.0and later), not onlynet10.0, so trimming and native AOT analysis cover thenet8.0andnet9.0assets too.
- 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 ofMcpRemoteConfigOauth,ConfigInfoFormatter,ConfigInfoLsp, andConfigLspEntry.Payloaditself and serialization are unchanged. - Every user-configured header and environment map is masked in
ToString(), now includingConfigProvider.Headers,ConfigModel.Headers,ConfigModelVariants.Headers,ConfigAgentRequest.Headers,ConfigFormatterEntry.Environment,ConfigLspServer.Env, andSessionEnvironmentRequest.Variables. - The open provider options are masked in
ToString().ProviderSettings,ConfigProviderSettings,ModelSettings, andConfigModelSettingskeep upstream's provider options,apiKeyamong them, inAdditionalProperties. 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.
- 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
OpenCodeServerOutputcollector 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 undernohupignoresSIGINTandSIGHUP). - 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.DisposeAsyncno longer throws when the forced tree kill is incomplete. The runtime raisesAggregateExceptionwhen 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 theOpenCodeServerOutputcollector. A failedStartAsyncwhose tree kill was incomplete threw thatAggregateExceptioninstead ofOpenCodeServerExceptionorOperationCanceledException. 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.
Processnever 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
net472andnetstandard2.0Windows tree kill no longer leaves taskkill running. A taskkill still running at its 10-second bound is now ended instead of left running.
- On Windows a standalone server is still started and ended through
Process. The session placement and theSIGTERM-then-SIGKILLladder above apply to Linux and macOS only. On Windows, disposal closes the server's stdin, waits up toGracefulShutdownTimeout, and only then kills the server's process tree; a server that exits inside the grace leaves its descendants running. net8.0andnet9.0leave the packages, andnet11.0joins, in an upcoming preview, ahead of their end of support on 2026-11-10; this release still ships them. The packages will then targetnetstandard2.0;net472;net10.0;net11.0. An app on .NET 8 or 9 still installs through thenetstandard2.0asset, 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 lacksLocationNotFoundError, 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.
CancelFormAsynctakes an optionalSessionFormCancelRequestbeforerequestOptions. A call that passedrequestOptionspositionally names it now (requestOptions: options). The method is virtual, so overrides and mock setups move to the new signature, and an assembly compiled against0.9.0-preview.5must be rebuilt. The route helperOpenCodeRoutes.Sessions.CancelFormgained the same optionalrequest.ProviderSettings.ChunkTimeoutandConfigProviderSettings.ChunkTimeoutare number-or-falseunions, notdouble?. Upstream accepts a number of milliseconds orfalse(no timeout), so a provider configured withfalsenow decodes. ReadKind, thenNumberorBoolean; a value neither arm claims is kept asUnknown.ChunkTimeout = 30000becomesChunkTimeout = ProviderSettingsChunkTimeout.FromNumber(30000)(ConfigProviderSettingsChunkTimeouton the config side), andFromBoolean(false)turns the timeout off; upstream refusestrue.ConfigModel.Capabilitiesis aConfigModelCapabilities, not the catalog'sModelCapabilities. It is the shape upstream's config accepts, and every member is optional:Toolsisbool?, andInputandOutputmay be null.ModelInfo.Capabilitiesis unchanged.IConnectionInfohas aStatusmember. A type outside the SDK that implements the interface, such as a test fake, addsConnectionStatus? Status; code that only reads connections is unaffected.
- The accepted snapshot moved to upstream release tag
v2.0.22(527f0b931d1f9b3ebd34e106c51b31ce5db5b075), published as@opencode/cli@2.0.22; install it withnpm install -g @opencode/cli@2.0.22. - Stored credentials can be listed and created.
client.Credentials.ListCredentialsAsync()(credential.list) returns everyCredentialEntry(Id,IntegrationId,Label,Active,Value), andCreateCredentialAsync(request)(credential.create) stores one and returns it; anIdthat already exists answers with the declared 409. They join activate, update, and remove.Valueis aCredentialKeyor aCredentialOAuth. Upstream returns secrets in clear text, so the API key (CredentialKey.Key) and the OAuth tokens (CredentialOAuth.Access,Refresh) are masked inToString(). SessionCreateRequest.ParentIdcreates a linked child session at its parent's location; a missing parent answers with the declared 404SessionNotFoundError.- A cancelled form can tell the asker why.
CancelFormAsync(formId, new SessionFormCancelRequest { Message = "..." })sends it, andFormStateCancelled.Messagecarries it back. HeaderTimeoutonProviderSettingsandConfigProviderSettingsbounds the wait for a provider's response headers, as the same number-of-milliseconds-or-falseunion.- A connection reports when it needs attention.
IConnectionInfo.Statusis aConnectionStatuswith theStatus, aMessage, and, when set, theUrlto sign in again at. SessionStructuredError.Responsecarries the failed provider response'sBody.
OpenCodeServer.DiscoverAsync,EnsureAsync, andStopAsyncdecode the CLI's service files exactly as the CLI does. A whole-valued number such as8080.0is an integer for the service config'sportand for the pid in the registration and the info probe. Before, such a config was ignored, soEnsureAsynclost itsenvoverlay, and such a registration was not found. A service config whosedisabledmember is not a boolean is no config at all, so itsenvoverlay and the legacy config copy do not apply, as in the CLI.disabled: trueitself does not stopEnsureAsync: only CLI commands read it, never the CLI's service operations.
net8.0andnet9.0leave the packages, andnet11.0joins, in an upcoming preview, ahead of their end of support on 2026-11-10. The packages will then targetnetstandard2.0;net472;net10.0;net11.0. An app on .NET 8 or 9 still installs through thenetstandard2.0asset, 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.
- The packages are now
OpenCodeDotNet.SdkandOpenCodeDotNet.Sdk.Extensions. Change thePackageReferencefromOpenCodeAI.SdkandOpenCodeAI.Sdk.Extensions; the earlier ids receive no further versions. Assemblies and namespaces are stillOpenCode.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 existingOpenCodeAI.*nightlies and receives no new ones.
- A standalone server no longer holds two thread-pool threads on Windows.
Processcreates 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 theOpenCodeServerOutputsnapshot 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.
- The accepted snapshot moved to upstream release tag
v2.0.18(cd9a14a6b688d4021bee381dfd39d2cef9c0f862), published as@opencode/cli@2.0.18; install it withnpm 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 withPassword = tokenwithout ever holding the server password. The token is masked inPairingSession.ToString(), and so is the code inPairingCode.ToString(). ShellInfo.Signalnames 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: aConfigDocumentcarries itsConfigInfo, aConfigDirectorythe directory it came from.Experimental.UpdateConfigAsyncwrites the global file and the server reloads it asynchronously, publishingconfig.updatedonce the loaded configuration changes, so read after that event. client.Experimental.GetMigrationV1StatusAsync()(experimental.migration.v1.status) returns the V1 session-history migration status:ExperimentalMigrationV1StatusIdle(RequiredorCompleted),…Runningwith 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 asFile.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 relativePathresolves 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 asContent(ReadOnlyMemory<byte>) and the MIME type the server declared asContentType.Pathis 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 404FileNotFoundError; 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*Asynccompanion, and each hand-written PTY and persistent-PTY door carries an XML<remarks>with its operation id, HTTP method, and route, for exampleOperation session.permission.create: POST /api/session/{sessionID}/permission.
- 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, soErrorisUnauthorizedErrorinstead ofnull. Nothing changed in the SDK; the errors guide now says so.
- A logged response no longer prints the raw error body. Every response envelope's
ToString()printedRawBody, so logging a failed response wrote whatever the server echoed into its error body, request data included. The printed form now keepsStatus,IsError, and the typedError;RawBodyitself is unchanged and still carries the body. OpenCodeServer.EnsureAsyncno 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'sProcessand libuv.
- 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, thenRedeemPairingCodeAsync, thenPassword = token), and it lists the launcher'sOutputoption. - 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 = Truedelivery 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 distributedopencodeCLI started,GetLogAsyncdelivers oneEventLogSyncedand no durable event either way. Both now say so and point live session activity toclient.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
WorktreeErrorremoved nothing. WithForceRequiredfalse, 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 answersWorktree directory unavailablewithForceRequirednull. 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.EvictLocationAsyncbefore the removal) and how to recover (evict, delete the directory,RefreshWorktreesAsync). - An empty VCS summary is explained. Getting started says that
Vcs.GetVcsAsyncfor a directory the server has not served before can answer with anullProviderandnullbranch values until that location's plugins settle, that the caller waits for a non-nullProvider, and that anullBranch.Currentwith a provider set is a detached HEAD. - Getting started shows a prompt answered in a console app:
PromptAsync, thenExperimental.WaitForSessionAsyncunder a caller-owned deadline, thenEnumerateMessagesAsync. - Getting started has a .NET Framework section. A
net472project 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
Directoryas the parent andNameas the child, and a shellTimeoutin milliseconds with0or 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/guidediffer.
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.
- The accepted snapshot moved to upstream release tag
v2.0.15(6f3639d82ed0760091792189b78f8eeb44f699b1), which published as@opencode/cli@2.0.15; install it withnpm install -g @opencode/cli@2.0.15. No operation was added, removed, or moved sincev2.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.Methodis required. A stored connection credential now says how it was obtained,ConnectionCredentialInfoMethod.KeyorConnectionCredentialInfoMethod.Oauth; a credential from a server that omits it no longer deserializes.ProjectTime.Activeis required. It is the project's most recent activity, in the same unit asCreatedandUpdated, and upstream now orders the project list by it; a project from a server that omits it no longer deserializes.
-
Session metadata updates.
SessionUpdateRequest.Metadatareplaces a session's metadata as a whole — keys the update leaves out are removed, not kept — and the server logs the replacement as the durableSessionMetadataUpdatedevent (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 toOpenCodeServerEnsureOptions.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, andOnStartfires at most once before a new service process is spawned.
- Generated models no longer print secrets. A model's
ToString()— string interpolation, logging templates, the debugger — printed every member, so logging anMcpOAuthConfig, or theMcpRemoteConfigholding it, wrote itsClientSecret. Members upstream's own recorder redacts (client_secret,password,api_key,token, …) now print[REDACTED], as doIntegrationConnectKeyRequest.Keyand the user-configured header and environment maps; an absent secret prints empty, and every other member prints as before. Equality and JSON are unchanged.
- 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, soDiscoverAsyncreturned null andStopAsynccould 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.
DiscoverAsyncandStopAsyncthrewInvalidOperationExceptionfor 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.Passwordrefused 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.StopAsynctreats 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()onFormValue,FormWhenValue,McpRemoteConfigOauth, andProviderSettingsTimeoutthrewInvalidOperationException("The structural value does not contain the requested arm."): a record's compiler-synthesizedPrintMembersread 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 anUnknownarm 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.
- The accepted snapshot moved to upstream release tag
v2.0.11(9eb6902aaf3c35ce985b67c605a775992249066b), which published as@opencode/cli@2.0.11; install it withnpm install -g @opencode/cli@2.0.11. No operation was added, removed, or moved sincev2.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.Settingsis aProviderSettings(Timeout,ChunkTimeout,Compaction,Transport) andModelInfo.SettingsandModelVariant.Settingsare aModelSettings(Compaction) instead ofIReadOnlyDictionary<string, JsonElement>;ProviderRequestOptions.Settingsis the sameProviderSettings. Every other member the server puts insettings—baseURL,apiKey,region, and whatever a provider adds — is inAdditionalProperties, anIReadOnlyDictionary<string, JsonElement>keyed by wire name that is empty, never null, when the body carried none; read it the way upstream does, by checking theValueKindyou expect.CompactionandTransportare removed fromModelInfoandProviderInfothemselves: upstream moved them undersettings.Timeoutis aProviderSettingsTimeoutstructural union (Number,Booleanfor the wire'sfalse,Unknown). - The compaction union changed its arms and marker.
IProviderCompactionnow dispatches ontypewithProviderCompactionSummary(summary) andProviderCompactionNative(native);ProviderCompactionLocal,ProviderCompactionProvider, itsThreshold, and themodemarker 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, orupdate; aGETwithout one is a read and namesGet<Subject>Async; every other operation is named by a reviewed, reason-bearing curation row, and the generator refuses to fall back toPost…,Put…,Patch…, orDelete…. Three consequences reach your code:- Every
Post…/Put…/Patch…/Delete…method is renamed. OnSessionClient: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. OnIntegrationClient:PostConnectKeyAsync→ConnectWithKeyAsync,PostOauthConnectAsync→BeginOauthConnectionAsync,PostOauthCompleteAsync→CompleteOauthConnectionAsync,DeleteOauthCancelAsync→CancelOauthConnectionAsync,PostCommandConnectAsync→BeginCommandConnectionAsync,DeleteCommandCancelAsync→CancelCommandConnectionAsync. OnExperimentalClient:PostSessionImportAsync→ImportSessionAsync,PostSessionSkillAsync→ActivateSessionSkillAsync,PostSessionWaitAsync→WaitForSessionAsync,PutSessionInstructionsEntryAsync→SetSessionInstructionsEntryAsync. OnPtyClient: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; likewiseShellClient.GetShellAsync/RemoveShellAsync,IntegrationClient.GetIntegrationAsync,PtyClient.GetPtyAsync/RemovePtyAsync, andPersistentPtyClient.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,…DeleteRequestand the matching…Response/…Datatype 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 bodysession.interruptanswers with was upstream'sSessionInterruptResponseand is nowSessionInterruptOutcome, so that the operation's own response record can carrySessionInterruptResponse(response.Interrupt.Interruptedreads as before); and the three update responses whose payload was mislabelledUpdatenow name their subject —PtyUpdateResponse.Pty,PersistentPtyUpdateResponse.PersistentPty,ProjectUpdateResponse.Project. The route builders inOpenCodeRoutesfollow their methods (Sessions.PostPrompt(id)→Sessions.Prompt(id),Sessions.GetSession(id)→Sessions.Get(id),…Templateconstants alike).
- Every
McpProtocol.Value20260728isMcpProtocol.Revision20260728. The wire value2026-07-28is unchanged; a reviewed enum member-name row names the member.
OpenCodeServer.StopAsyncstops the registered background service — opencode'sservice stopfor your code, shaped byOpenCodeServerStopOptions(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, thenSIGKILL; 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 throwsOpenCodeServerExceptionand leaves the registration in place. Disposing a discovered handle still stops nothing.
- Discovery answers a stale registration at once on Windows.
OpenCodeServer.DiscoverAsyncprobes 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_PROXYwithoutNO_PROXYno 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.
- The accepted snapshot moved to upstream release tag
v2.0.8(7673ed6bd6547ee0dcb81aab55f1392fb751d652), which published as@opencode/cli@2.0.8; install it withnpm install -g @opencode/cli@2.0.8. Operation identities lost theirv2.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, andServerResponseare removed with upstream's/api/healthand/api/server. Callclient.Server.GetInfoAsync()(GET /api/info) and readServerInfoResponse.ServerInfo:Version,Pid,Urls, andPaths.Tmp, the server's temporary directory. There is noHealthymember; 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.WorkspaceandSessionListRequest.Workspaceare removed: upstream dropped thelocation[workspace]query and thex-opencode-workspaceheader. TheLocationa location-scoped response carries is nowLocationPublicRefwithDirectoryalone, andlocation.getanswersLocationPublicInfo;LocationInfoandLocationInfoProjectare removed. Theclient.Workspacesfamily (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 memberSessionExport),SessionsClient.PostImportAsync→Experimental.PostSessionImportAsync,SessionsClient.GetStatsAsync→Experimental.GetSessionStatsAsync.SessionClient.PostSkillAsync/PostWaitAsync→Experimental.PostSessionSkillAsync/PostSessionWaitAsync, and the three…InstructionsEntryAsyncmethods →Experimental.ListSessionInstructionsEntryAsync,PutSessionInstructionsEntryAsync, andRemoveSessionInstructionsEntryAsync.- The
McpServerClienthandle andMcpServersClient.GetMcpServerClientare removed; adding, connecting, disconnecting, and removing a server areExperimental.AddMcpServerAsync,ConnectMcpServerAsync,DisconnectMcpServerAsync, andRemoveMcpServerAsync.McpServersClientkeeps the list and the resource catalog. client.Generation.GenerateTextAsync→Experimental.GenerateTextAsync;GenerationClientis removed.
- Configuration preferences are gone upstream.
ConfigClient.GetPreferencesAsync,PatchUpdatePreferencesAsync, and theConfigPreferences*andConfigWebSearchInfomodels are removed with/api/config/preferences. Write throughExperimental.UpdateConfigAsync, whoseShellis required and nullable: a string sets the shell,nullclears it, and there is no "leave it unchanged" form any more. There is no configuration read at this pin: upstream folded it intoconfig.get, which this SDK does not generate yet (coverage).ConfigClientkeepsGetShellsAsync. - Session operations that changed shape.
RenameSessionAsyncandPutPermissionRulesAsync→SessionClient.UpdateSessionAsync(Title,Permissions).PostInboxQueueAsyncandPostInboxSteerAsync→UpdateInboxAsyncwith the delivery to switch to.GetFormStateAsyncis removed; the state isGetFormAsync(…).Form.Stateon the newFormDetail.PostFormCancelAsync→DeleteFormCancelAsyncandPostRevertClearAsync→DeleteRevertClearAsync(upstream changed the method). The fork boundary union (ISessionForkRequestBoundary,SessionForkRequestBoundaryBefore,…Through) is removed; setSessionForkPostRequest.Before.SessionInterruptPostRequest.Continue→Resume.MessageListRequest,MessageListResponse, andMessageListRequestType→SessionMessageListRequest,SessionMessageListResponse, andSessionMessageListRequestType. - Events.
session.permissions.updatedis nowsession.permissions:SessionPermissionsUpdatedand itsDataandDurablecompanions →SessionPermissions,SessionPermissionsData, andSessionPermissionsDurable.catalog.updated(CatalogUpdated) is removed;provider.updatedandmodel.updatedarrive asProviderUpdatedandModelUpdated. - Worktrees name their project. Every worktree request requires
ProjectId, and the requests no longer take aLocation;WorktreeCreateRequest.Strategyis removed. - Smaller renames and removals.
VcsClient.GetBranchesAsync→ListBranchesAsync(VcsBranchListRequest/VcsBranchListResponse).FormsClient.ListRequestsAsync→ListFormsAsync, and its payloadRequests→Forms.ProjectsClient.GetCurrentAsyncis removed; the current project arrives onclient.Location.GetLocationAsync().ShellClient.TimeoutShellAsyncis removed.ShellCreateRequest.Timeoutis optional (long→long?).SkillInfo.LocationandSlash→Path. An unknown integration now throws the declared 404 instead of returning null. PluginsClient.AwaitPluginActivationAsyncis 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.
- Background-service discovery.
OpenCodeServer.DiscoverAsyncopens 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/infoprobe under a two-second bound whose pid must match. A ready daemon comes back as a non-owningOpenCodeServer: the newOwnsProcessmember is false,DisposeAsyncis a no-op, andCreateClient()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.OpenCodeServerDiscoverOptionscarriesChannel,RegistrationFilePath,ExpectedVersion, andInstalledVersion, validated at the call. This is the one SDK door that reads the environment, and it reads exactlyXDG_STATE_HOME,XDG_CONFIG_HOME,OPENCODE_CONFIG_DIR, and the user profile (USERPROFILEfirst on Windows,HOMEelsewhere) — 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 ownserve --servicedaemon 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.GetDiffAsyncbindssession.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.SessionDiffRequestcarries the optionalFromandTouser-message anchors and theContextline count, andSessionDiffResponse.Diffsis the sameFileDiffInfolist 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.
SessionMessageIdlejoins the message union with itsOutcome(Succeeded,Failed, orInterrupted). The server writes one at the end of every turn; on0.8.0-preview.2those entries surfaced asUnknownSessionMessageInfo. - Reloading every loaded location.
client.ReloadLocationsAsync()bindslocation.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 newlocation.shutdownevent (LocationShutdown) arrives on the event stream for each location it tears down, so a consumer can revalidate its reads. The declaredServiceUnavailableErroris its one typed failure. - Smaller additions.
SessionStepStartedData.Startedcarries the step's request dispatch time, before the provider answers, and everyForm*Fieldhas an optionalHiddenthat skips the interactive prompt when a default exists.
- The version line is
0.9.0. Discovery is the M4 milestone's background-service boundary; nightlies are0.9.0-nightly.*. OpenCodeServerExceptionnow 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.OpenCodeServeris 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 throughOwnsProcess.- 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 fromPATHby the SDK's own launcher. The new Consumer leg workflow — on demand and weekly, Linux and Windows — uses it to run that suite againstnpm install -g @opencode/cliat the versionspec/SNAPSHOT.mdpins, 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.
- A request property the API document declares both optional and nullable is now
Optional<T?>instead ofT?— 39 properties across 21 operations, one of them the sharedToolFileContent.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,= nullandOptional<T?>.Nullboth write JSON null, and a value assigns through an implicit conversion, soTitle = "Fix the build"keeps compiling unchanged. Reading one back goes throughIsSetandValue, and= defaultreturns a member to absent. Response-only schemas are untouched;ToolFileContentis the one schema shared both ways, so itsNamecarries 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/cliscope 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.messageUpdateis 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 theISessionMessageAssistantunion and itsUnknownSessionMessageAssistantcarrier, which only that request body referenced. Assistant content records keepISessionMessageAssistantContent.session.message.content.updatedleft the live event union.SessionMessageContentUpdatedno longer implementsIEvent; it remains a durable session-log item.
-
A preference can be cleared, not just overwritten.
PatchUpdatePreferencesAsyncsends an explicit JSON null forShellorWebsearchwhen you assignOptional<T?>.Null(or plainnull), 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.2snapshot added four operations and all four are generated and covered:OpenCodeClient.ConfigcarriesGetPreferencesAsync,GetShellsAsync, andPatchUpdatePreferencesAsync(global preferences read, the host shell catalog, and the preferences patch), andSessionClient.PutPermissionRulesAsyncreplaces a session's permission ruleset.ConfigPreferences.WebsearchandConfigUpdatePreferencesPatchRequest.Websearchare structural unions overfalseand aConfigWebSearchInfoprovider. 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, andSessionCreatedDatagainedPermissions, and the new durable eventsession.permissions.updatedmaterializes asSessionPermissionsUpdatedonIEvent,ISessionEventDurable, andISessionLogItem, carrying the session id and the new ruleset. -
One door submits a command line on both terminal families.
PtySession.SubmitAsync(string)andPersistentPtySession.SubmitAsync(string)send the line plus the carriage return a terminal's Enter key sends, through the same serialized send path as the matchingWriteAsync— 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\ror an\ninside it is refused withArgumentException, an empty line is a bare Enter, and nothing is trimmed.WriteAsyncis 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
switchover concrete types. The landmark case is the session log:ISessionEventDurablegainedId,Created,Metadata,Location, andDurable, and the 43 per-event envelope records now implement one newIDurableEnvelopecarryingAggregateID,Seq, andVersion— soitem.Durable?.Seqreplaces a partial type switch.IEvent,IFormField,IMcp,IReferenceSource,ISessionMessageInfo,ISessionMessageCompaction,ISessionInboxInfo,ISessionInboxItem,ISessionForkBoundary,IIntegrationAttemptStatus, andIIntegrationCommandAttemptStatusgained members the same way, withIMcpTimeout,ISessionMessageCompactionTime,IIntegrationAttemptStatusTime, andIIntegrationCommandAttemptStatusTimeas further carriers. Members are declared nullable because a union'sUnknown*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.EnumerateSessionsAsyncjoinsSessionClient.EnumerateMessagesAsyncas an automatic cursor walk. A list query now binds the sharedListRequestspine whenever it includeslimit,order, andcursor— extra filters no longer disqualify it — soSessionListRequestderives fromListRequestand gains the companion. Every filter of the first request rides each continuation unchanged; only the first-page-onlyorderis dropped and the opaque cursor replaced. -
Every automatic walk can be read as pages.
Enumerate*Asyncnow returnsCursorSequence<TPage, TItem>, whosePagesproperty yields each generated response envelope —Status,Cursor,RawBodyand 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.
- The docs no longer claim an anonymous opencode server exists, and a 401 now says so. The
guide and the shipped XML on
OpenCodeClientOptions.Passwordtold readers thatnullwas the right value "for a server started without authentication". No such server can be started: theopencodeCLI always runs its server with a password — the one set throughOPENCODE_PASSWORD, or one it generates and prints asserver 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 withPasswordleftnull, theOpenCodeApiExceptionmessage 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 theNoThrowenvelope 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 insidenode_modules, whileProcess.Startappends only.exeand ignoresPATHEXT— so the shipped defaultCommandfailed on every npm-installed Windows machine with a bare "Failed to start the server command 'opencode'" and no stderr. The launcher now resolvesCommand[0]the way a shell does before spawning anything, so the.cmdshim 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.
-
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 thePATHdirectories in order, skipping empty entries and resolving relative ones against the current directory. On Windows a bare name with no extension is tried with eachPATHEXTextension inPATHEXTorder (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 anOpenCodeServerExceptionthat 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/.batshim is launched through the systemcmd.exe(/d /s /c, every token quoted) rather than throughCreateProcess's implicit batch handling. Two consequences:ProcessIdthen reports thecmd.exehost rather than the server process — ask the server forhealth.Health.Pidwhen 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 withOpenCodeServerExceptionbefore anything starts, becausecmd.exere-parses the line (the fail-closed answer to BatBadBut / CVE-2024-24576). The SDK's own--stdio --port 0are 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 throughSubmitAsync, and the terminator rule is stated once: Enter is\r,\nis a line feed that the Windows console host does not accept as a submit, and the SDK never rewrites whatWriteAsyncis given. -
Snapshot additions.
MessageListRequest.Typefilters a message list by message type (MessageListRequestType) and rides every continuation unchanged;ModelInfo.WebsocketandProviderInfo.Websocketare new optional flags; compaction ended and failed data, and the compaction message records, carry optionalCostandTokens. -
SessionClient.EnumerateMessagesAsyncreturnsCursorSequence<MessageListResponse, ISessionMessageInfo>instead ofIAsyncEnumerable<ISessionMessageInfo>.await foreachover it is unchanged, and code that stored the result in a variable typedIAsyncEnumerable<T>still compiles, becauseCursorSequence<TPage, TItem>implementsIAsyncEnumerable<TItem>. Code that declared the variable withvarand then assigned anIAsyncEnumerable<T>to the same variable is the one shape that needs its type written out. -
SessionListRequestno longer declaresLimit,Order, andCursoritself; it inherits all three fromListRequest. Reading and initializing them is unchanged.
- Durable replay now says which servers can actually do it. The streaming guide and the
README's known issues state that the distributed
opencodeCLI starts its server without event persistence and exposes no switch for it, so a replay from a CLI-started server answers with thelog.syncedmarker 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 carriesModelInfo.Idand neverModelInfo.ModelId, and neither create nor prompt validates the reference. The same recipe runs in the in-repo sandbox's--standaloneleg. - Session export documents what
Sanitizedoes. 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
WorktreeErrorremoved nothing — the directory and its inventory row both remain — andForceRequiredfalse means git ran and failed for a reasonForcecannot fix, such as the Windows permission denial observed on the then-pinned@opencode/cli@0.0.0-beta-19242while 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.
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 toEventRpc— tried after the literal tags and before the carrier. Anything matching neither lands in that union'sUnknown*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 privateopencode2 servechild — generated lease credential, stdin-EOF ownership, bounded tree termination — andCreateClient()hands back a client already bound to it. An optionalOpenCodeServerOutputcollector, supplied throughOpenCodeServerOptions.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;ProcessIdstays readable after disposal for the same diagnostic use. Real-process lifecycle acceptance runs on Windows, Linux, and macOS. - Server-sent event streaming.
EventsClient.SubscribeAsyncfollows the global bus andSessionClient.GetLogAsyncfollows one session's log, both asIAsyncEnumerable<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.
PtySessionandPersistentPtySessionare 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<…>)orAddOpenCode(IConfiguration)registers one singleton client owning its transport for the container's lifetime, plus every sub-client resolved from that same instance — injectSessionsClientorEventsClientdirectly. - A typed error model. Calls throw typed exceptions by default;
OpenCodeRequestOptions.NoThrowreturns 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.EnumerateMessagesAsyncfollows it to exhaustion as anIAsyncEnumerable<T>. - Source-generated JSON.
System.Text.Jsonsource generation throughout, with no reflection fallback anywhere in the serialization path. Both packages declareIsAotCompatibleonnet10.0; the one reflective seam,AddOpenCode(IConfiguration), is annotated[RequiresDynamicCode]/[RequiresUnreferencedCode]so a trimmed or AOT build is warned rather than surprised.
- Target frameworks:
netstandard2.0,net472,net8.0,net9.0,net10.0— for both packages. The suite runs onnet472on Windows, real-process launcher tests included, and onnet8.0/net9.0/net10.0on all three OSes.netstandard2.0is a consumption target rather than a test target — it has no runtime to execute on, and thenet472leg is what exercises its compile surface. - Protocol identity: built against an accepted OpenAPI snapshot of upstream's
v2branch, not a live branch. The exact commit, its digest, and the receipt-governed refresh procedure live inspec/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
net472assemblies. Linux and macOS run the same suite on the three modern targets.
- Unofficial. This project is not affiliated with or endorsed by the opencode team.
- Three operations are declined by decision, not by omission.
v2.config.getandv2.experimental.migration.v1.statushit an undiscriminated object-union wall;v2.fs.readis 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.connectandv2.persistentPty.connectare WebSocket upgrades, so they are served by the hand-writtenPtySession/PersistentPtySessiondoors 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.