Skip to content

2.0.0

Choose a tag to compare

@Blind-Striker Blind-Striker released this 17 Nov 20:38
6586961

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

💥 Breaking changes

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

🔌 Protocol changes

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

✨ Added

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

🔧 Changes

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

🐛 Fixes

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

📚 Documentation

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