Repository navigation
2.0.0
2.0.0 keeps the opencode 2.3.0 pin shipped in 1.1.0. It is a major for hand-written
breaks: the shared event connection changes buffering, admission, retries, error reporting and
subscription lifetime (#902, ADR-0041); standalone readiness has no default timeout, a discovered
server's password can be null, mock default-model failures can throw synchronously, and loopback
discovery follows the client's proxy decision. User files now read through PromptAttachment; the
Protocol changes below cover that migration.
💥 Breaking changes
EventsClient.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.
🔌 Protocol changes
- 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.
✨ Added
- 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 an
OpenCodeServiceConfigwithout 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)and
UnsetEnvironmentVariableAsyncremove 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 installed
opencode service set remote true, using theCliCommandandEnvironmentmembers of
OpenCodeServiceConfigOptions. 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.
🔧 Changes
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.
🐛 Fixes
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.
📚 Documentation
- 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.