Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,32 @@ Nightly builds of `master` are on
[GitHub Packages](README.md#nightly-builds-github-packages) as nightlies of the next version,
`{version}-nightly.{yyyyMMdd}.g{shortSha}`.

The next SDK version is **2.0.0**, on the same opencode **2.3.0** pin already released in SDK 1.1.0.

### 💥 Breaking changes

- `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;`.
- `EventsClient.SubscribeAsync` now uses one shared background source per root client. Each enumeration 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` is an admission marker, possibly cached and sharing its Id with neighbours, not a new physical connection or liveness proof. Earlier business events are not replayed. A later marker still announces a possible gap.
- Ordinary event-attempt failures retry forever instead of giving up after a minute. API, transport and failure-frame exceptions are exposed on connection state rather than ending the subscription. Consumers that require a deadline own a cancellation token.
- 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.

### ✨ Added

- `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` waits for a location's plugins to load, as the CLI does before listing agents, models and integrations; `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.

### 🔧 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. (#871)
- 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.
- Event 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 accept but no longer forward per-call Location. Every shared attempt sends only the client's ambient header snapshot; other operations retain their existing override behavior.
- Event idle detection keeps running while a consumer holds an event. Disposing an enumerator with a pending move 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.
- Background-service discovery (`OpenCodeServer.DiscoverAsync` and the probe `EnsureAsync` runs) now takes the client's proxy decision for a loopback service. Behind an environment proxy (`HTTP_PROXY`, `HTTPS_PROXY` or `ALL_PROXY`), set `NO_PROXY` to reach a loopback service directly, as with opencode's CLI; behind a system proxy, that proxy's own bypass list applies, as it does for the client. .NET Framework is unchanged.

### 🐛 Fixes
Expand Down
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<!-- The single source of the package version; nothing else declares Version or PackageVersion.
Nightlies add their suffix at pack time (the pack command's version-suffix option). The release
lane stamps its exact version input with -p:Version, and refuses one whose core differs from this. -->
<VersionPrefix>1.1.1</VersionPrefix>
<VersionPrefix>2.0.0</VersionPrefix>
<Authors>Deniz İrgin</Authors>
<Company>Deniz İrgin</Company>
<Owners>Deniz İrgin</Owners>
Expand Down
20 changes: 20 additions & 0 deletions GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,26 @@ An explicit, registered runtime exception to the fail-closed default.
The hand-written transport core where all request behavior lives; generated methods only delegate to
it.

**Event feed**:
The SDK's client-wide background source, reconnect loop and ordered fan-out of the Live event
stream. It decodes the bus once and shares Event references; ordinary attempt failures retry
without end and are reported through Connection state.

**Event subscription**:
One enumeration of SubscribeAsync, with its own call-time, local, exact-ordinal Event selection and
up to 4,096 queued selected Events. A null or empty selection takes every Event, and connection
markers always pass. A source fault leaves its queued prefix readable before the same exception
is thrown.

**Subscriber overflow**:
The ending when an Event subscription cannot queue its next selected Event. It discards that
subscription's unread backlog and ends it alone, while other subscriptions continue.

**Connection state**:
The Event feed's Idle, Connecting, Connected or Reconnecting snapshot, with its retry count and
last classified exception. Its watch coalesces to the latest unread state and never keeps a source
alive; the state is neither an Event position nor a liveness or resynchronization barrier.

**Envelope**:
The generated, typed response object of one operation, carrying its status and error state and its
named payload properties.
Expand Down
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -385,9 +385,11 @@ has the two properties to set.
## Known Issues

- **The event bus has no replay.** `EventsClient.SubscribeAsync` is a live stream: events published
while you are disconnected are lost, and a consumer slower than the producer can overflow and
fail the stream. This is the server's contract, not an SDK limitation. See the
[streaming guide](https://github.com/opencode-dotnet/opencode-sdk-dotnet/blob/master/docs/guide/streaming.md).
while you are disconnected are lost. The SDK shares one source per client and bounds each
subscription to 4,096 queued selected events; the next refused offer ends that subscriber with
`OpenCodeEventSubscriberOverflowException`. Recover by resubscribing, awaiting admission, then
refreshing and applying the buffered tail idempotently. See
[overflow recovery](https://github.com/opencode-dotnet/opencode-sdk-dotnet/blob/master/docs/guide/streaming.md#-recovering-after-subscriber-overflow).

- **A CLI-started server's durable session event stream holds only the sync marker.** It reads from
the server's event store, and the distributed `opencode` CLI starts its server without event
Expand Down
12 changes: 8 additions & 4 deletions docs/adr/0007-error-model.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Error model: typed exception spine carrying tagged error data

Date: 2026-10-16
Date: 2026-11-15

API failures throw through a typed exception spine (`OpenCodeException` →
`OpenCodeApiException`) by default; per-call `NoThrow` returns them on the response spine.
Expand All @@ -9,10 +9,13 @@ no arbitrary header dictionary (sealed 2026-08-26; internal research, 2026-08-25
coverage-program grilling seal?").

Streams and automatic cursor traversals take the shared `OpenCodeRequestOptions`.
`Location` applies to each stream connection attempt and every page request. A stream yields
`Location` applies to other streams' connection attempts and every page request; the shared event
bus accepts but ignores per-call Location and follows ADR-0041. A stream yields
an `IAsyncEnumerable<T>` rather than a response envelope, so it has no envelope to carry an
API error; streams and automatic traversals refuse `NoThrow` at the call, before enumeration,
and always throw API errors when encountered. Explicit page methods retain `NoThrow`.
and other streams and automatic traversals throw API errors when encountered. The shared event
bus reports ordinary attempt errors on connection state while retrying (ADR-0041).
Explicit page methods retain `NoThrow`.
On `event.subscribe`, per-call `NetworkTimeout` is refused, including
`Timeout.InfiniteTimeSpan`: its 2-second connection and default 45-second idle windows follow
upstream's first-party behavior. Other streams apply `NetworkTimeout` only while opening;
Expand All @@ -23,7 +26,8 @@ surface is chosen over a dedicated stream options type so callers use the same p
location and behavior vocabulary. The trade-off is that the compiler cannot prevent a caller
from selecting a member a stream or traversal must refuse at run time.

Transport and protocol failures always throw `OpenCodeTransportException`. The spec's tagged error
Outside the shared event bus's retry loop, transport and protocol failures throw
`OpenCodeTransportException`. The spec's tagged error
payloads are generated as typed models under an `OpenCodeError` base and ride **as data** on either
channel, pattern-matchable without string sniffing. There is no client-level switch. Throwing API
errors retain the raw body on `OpenCodeApiException`; `NoThrow` responses retain it on their shared
Expand Down
8 changes: 5 additions & 3 deletions docs/adr/0021-normal-pty-public-surface-hand-written.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@ input, a cursor domain without a live-only mode, no pre-upgrade existence check)
families' public doors are hand-written over generated internal raw clients and share one
family-neutral socket core behind named decode, close, and upgrade seams.

The Events family's public door is hand-written over its raw client, so behaviour above the
generated stream belongs to hand-written code. Its raw endpoint, routes, adapters, wire models and
serializer metadata stay generated; its signature and SSE behaviour are the generated stream method's.
The Events family's public door owns the shared feed and local selection (ADR-0041), opening physical
attempts through the generated route and adapter on the stream plane rather than delegating to its
raw twin's subscribe method. The raw endpoint, routes, adapters, wire models and serializer metadata
stay generated; the public subscription signature stays stable while its runtime contract belongs
to hand-written code.

## Considered options

Expand Down
71 changes: 71 additions & 0 deletions docs/adr/0041-one-shared-event-feed-per-client.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# One shared event feed per client

Date: 2026-11-15

The default Events door follows the pinned first-party shared-feed model: one lazy physical source
per root client, with an independent subscription per enumeration. A feed gate makes admission,
marker replay, selected publication, endings and source state atomic. Reference identity fences
retired generations; an observed runner ledger owns cleanup after synchronous logical detachment.
This replaces pull-only per-enumeration connections so one consumer cannot postpone idle detection
for the others, and several consumers do not duplicate wire traffic and decoding.

## Contract and trade-offs

- Each subscription allows 4,096 queued selected events. The next refused selected offer ends only
that subscription and releases its backlog. A pending move's direct handoff takes no queue slot.
A sole subscriber's overflow stops the source. The limit counts events, not bytes, and there is
no subscriber-count limit.
- The latest cached `server.connected` marks admission in the feed's fan-out order, not liveness or a
new server connection. Its Id can be shared. Earlier business events are not replayed; a later
marker announces a possible gap. Recovery admits a replacement before refreshing, then applies
its buffered tail idempotently and restarts if that replacement overflows. Exactly-once and
cross-operation transactional snapshots are not promised.
- Types are copied and validated at the call and matched locally, ordinally, with markers always
included. The source sends no Types query and only the ambient Location header. It decodes the
whole bus once, shares event/metadata references and couples malformed unselected traffic to the
shared attempt. Consumers treat payload graphs as read-only.
- Ordinary failures retry forever with fixed connect, idle and retry windows. Virtual snapshot and
coalescing-watch members expose the last classified Exception, the retry counter and Idle when
no source exists. They are not a transition log, cursor or liveness barrier. Watchers neither
open nor retain a source.
- An escaping source/cleanup fault detaches the generation, publishes Idle and preserves each
subscription's queued prefix before the same exception. Any still-current runner completion
takes this path, including cancellation and unexpected normal return. New admission starts fresh.
- A settled move is immutable. A live caller token wins over unread data and every stored ending
on later selections; otherwise a prefix precedes its first stored fault. Explicit enumerator
disposal drains unread references and later pulls end false unless cancelled, without changing
a move already settled. Root disposal closes admission before lifetime/transport cleanup and
does not rewrite subscriptions already ended by source fault.
- Physical stop uses the sanctioned worker-cancellation helper. Runner and cancel completion are
both observed before CTS disposal. Retired cancel failures are recorded and dropped; they cannot
poison a replacement. Pipeline remains Events-neutral through its owned-resource hook.

## Considered options

- Retain pull-only connections: rejected because a held event pauses detection and every consumer
duplicates I/O. A second opt-in feed door would leave the default first-party model inconsistent.
- Await a full queue, drop items, or use an unbounded queue: rejected because one slow subscriber
would stall neighbours, silently lose data, or grow without its explicit overflow boundary.
- Reconnect/resignal every subscriber for a late joiner: rejected because joining would disrupt
healthy neighbours merely to manufacture a fresh marker. Replay remains marker-only admission.
- Discard a source-fault prefix: rejected; upstream preserves that valid prefix. Preserve an earlier
fault after explicit disposal: rejected; upstream later pulls end done after iterator return.
- Keep a minute give-up or add backoff/configurable capacities: rejected. Observable connection
state supplies the missing failure channel, and fixed policy follows the pinned first-party model.
- Deep-copy each payload: rejected because sharing is upstream's model and copying adds whole-graph
cost. Immutable treatment is documented rather than falsely implied by IReadOnlyDictionary.

## Divergences and reversal triggers

Retry composes inside the SDK source where upstream's shared layer and Solid split those layers.
Cancellation throws OCE, including over a fault-preserved prefix or a stored overflow ending,
because that is the SDK-wide cancellation contract; upstream abort returns done while subscribed
and leaves a stored ending unchanged after source completion or overflow. Exception-valued Error, explicit Idle and the
typed overflow exception are idiomatic .NET forms. Standard public exception constructors remain
available and Capacity always reports the SDK's bound. Current runtime canon records these and the
omitted application facilities (history, resync, lifecycle, re-resolution, batching and onActivity).
Revisit with a corresponding upstream contract change, a change to the SDK cancellation contract,
or a concrete consumer need. A one-off preference does not silently change the shared policy.

The hand-written runtime/error-channel breaks require SDK 2.0.0 under ADR-0034. This does not move
the protocol pin: opencode 2.3.0 already shipped with SDK 1.1.0.
Loading
Loading