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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ Nightly builds of `master` are on
[GitHub Packages](docs/guide/getting-started.md#nightly-builds-github-packages) as nightlies of the next version,
`{version}-nightly.{yyyyMMdd}.g{shortSha}`.

### ✨ Added

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

### πŸ› Fixes

- An `OpenCodeApiException` whose server message already ends in `.`, `!` or `?` no longer gets a
Expand Down
16 changes: 14 additions & 2 deletions docs/architecture/client-runtime.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Client Runtime Architecture

Date: 2026-11-17
Date: 2026-11-23

Canonical current rules for client construction, transport ownership, API errors, streams, and the
local server launcher. Protocol and generated-model rules live in
Expand Down Expand Up @@ -532,7 +532,7 @@ resolves the message's network window from those carried traits.
([Typed plugin RPC](#typed-plugin-rpc)).
- A one-shot call may select per-call `NoThrow`, returning the same typed error data on its response
spine. There is no client-level error-behavior switch (ADR-0007). Streams, cursor traversals,
both waits and the typed RPC call refuse it at the call.
both waits, the session cost total and the typed RPC call refuse it at the call.
- `Plugins.WaitForPluginsAsync` follows the CLI's one-shot wait (`plugin-startup.ts:6-13`): it
lists the location's plugins until non-empty, waiting 25 ms after each empty answer for about five
seconds. The schedule limit is checked after each answer, not a deadline that interrupts
Expand Down Expand Up @@ -878,6 +878,18 @@ resolves the message's network window from those carried traits.
- Automatic pagination is a finite pull sequence over ordinary buffered HTTP calls, not SSE. A
different pagination dialect does not inherit these rules from naming or prose; it requires a
mechanically proven binding of its own (ADR-0013, ADR-0017).
- `Sessions.GetTotalCostAsync` follows upstream's client data store
(`packages/client/src/solid/data.ts:1582-1590` at the pin): a session with a parent returns its
own `Cost`; any other session returns its own `Cost` plus the `Cost` of every descendant session,
the subtree upstream's store converges on as it loads them. It reads the descendants depth-first,
each level through the children traversal with `ParentId`, descending order and pages of 200, as
upstream's family sync reads a level, and counts each session once. It refuses `NoThrow` at the
call, and every failure propagates.
- Recorded divergence: upstream's store returns 0 for a session it has not loaded, and the SDK
fails with the server's not-found error for an unknown session. Upstream reads a local cache,
where an absent session is one not loaded yet; the SDK asks the server, where an absent session
is a wrong identifier, and returning 0 would hide it. If upstream's client starts treating an
unknown session as an error, this follows.

## Launcher

Expand Down
5 changes: 3 additions & 2 deletions docs/guide/errors-and-responses.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# 🧱 Errors and responses

Date: 2026-11-22
Date: 2026-11-23

Every one-shot call of a client family answers with a **response envelope** that carries the same four members no
matter which operation produced it, and every failure is either a typed API error you can branch on
Expand Down Expand Up @@ -94,7 +94,7 @@ instance, and `new OpenCodeRequestOptions { ErrorBehavior = ErrorBehavior.NoThro
thing spelled out. There is deliberately no client-level switch: whether a failure is exceptional
depends on the call, not on the client.

Four limits worth internalising:
Five limits worth internalising:

- **`NoThrow` covers declared API errors only.** It never suppresses a transport failure.
- **Streams and automatic cursor traversals refuse `NoThrow` at the call, before enumeration.**
Expand All @@ -103,6 +103,7 @@ Four limits worth internalising:
on connection state while retrying. See [streaming](streaming.md#-stream-error-channels) and [pagination](pagination.md).
- **`Plugins.WaitForPluginsAsync` and `LanguageModels.WaitForDefaultAsync` refuse `NoThrow` at the call,**
because they decide on each plugin-list answer whether to keep waiting.
- **`Sessions.GetTotalCostAsync` refuses `NoThrow` at the call,** because it returns a number, not an envelope.
- **The typed plugin RPC call refuses `NoThrow` at the call,** because it returns the output,
not an envelope. See [Calling a plugin's RPC](requests.md#-calling-a-plugins-rpc).

Expand Down
2 changes: 1 addition & 1 deletion spec/SNAPSHOT.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# OpenAPI Snapshot

Date: 2026-11-22
Date: 2026-11-23

`openapi.json` is the accepted snapshot of the upstream opencode OpenAPI 3.1 document
(ADR-0005). The SDK is built against this snapshot, never against a live branch; the pin is
Expand Down
39 changes: 20 additions & 19 deletions spec/receipt.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,25 +34,8 @@
"normalizedDocumentPath": null,
"operationSetDigest": "7cb3e37b2498257d72ed0d5e46fdb6ba6e8738cbe7070f3919fd685a3d00fa7f",
"operationCount": 173,
"addedOperations": [
"experimental.automation.create",
"experimental.automation.delete",
"experimental.automation.get",
"experimental.automation.list",
"experimental.automation.pause",
"experimental.automation.resume",
"experimental.blob.get",
"experimental.generate.video.create",
"experimental.generate.video.get"
],
"removedOperations": [
"experimental.schedule.create",
"experimental.schedule.delete",
"experimental.schedule.get",
"experimental.schedule.list",
"experimental.schedule.pause",
"experimental.schedule.resume"
],
"addedOperations": [],
"removedOperations": [],
"componentCount": 521,
"contentSchemaCount": 2,
"watchedSources": [
Expand Down Expand Up @@ -1120,6 +1103,24 @@
}
]
},
{
"path": "packages/client/src/solid/data.ts",
"sha256": "6083ed87dd52b7000da6613158461986cda5ee5573ed841473f4303acaf1eda9",
"anchors": [
{
"text": "if (session.parentID) return session.cost",
"matched": true
},
{
"text": "const CHILD_PAGE = 200",
"matched": true
},
{
"text": "const rootID = resolveRoot(sessionID)",
"matched": true
}
]
},
{
"path": "packages/client/src/promise/media.ts",
"sha256": "ebfde36489ae44cb51505cbeba7d854fa6cf0c5ab92c1ff8fc67b7a71b4b640d",
Expand Down
30 changes: 30 additions & 0 deletions spec/source-watch.json
Original file line number Diff line number Diff line change
Expand Up @@ -1517,6 +1517,36 @@
}
]
},
{
"path": "packages/client/src/solid/data.ts",
"sha256": "6083ed87dd52b7000da6613158461986cda5ee5573ed841473f4303acaf1eda9",
"behaviors": [
{
"owner": "opencode-sdk-dotnet",
"behavior": "cost(sessionID) returns 0 for a session the store has not loaded, a session's own cost when it has a parent, and otherwise the sum of cost over the family index of its root. Sessions.GetTotalCostAsync follows it, except that an unknown session fails.",
"anchor": {
"type": "contains",
"text": "if (session.parentID) return session.cost"
}
},
{
"owner": "opencode-sdk-dotnet",
"behavior": "listChildren reads a parent's direct children with session.list {parentID, order desc, limit 200}, following cursor.next while a page is full; sync with children fills the family index with them. Sessions.GetTotalCostAsync reads each level of descendants the same way.",
"anchor": {
"type": "contains",
"text": "const CHILD_PAGE = 200"
}
},
{
"owner": "opencode-sdk-dotnet",
"behavior": "registerSession files every loaded session, at any depth, under the family of its resolved root, so cost() converges on the whole loaded subtree. Sessions.GetTotalCostAsync walks the whole subtree for the same total.",
"anchor": {
"type": "contains",
"text": "const rootID = resolveRoot(sessionID)"
}
}
]
},
{
"path": "packages/client/src/promise/media.ts",
"sha256": "ebfde36489ae44cb51505cbeba7d854fa6cf0c5ab92c1ff8fc67b7a71b4b640d",
Expand Down
51 changes: 51 additions & 0 deletions src/OpenCode.Sdk/Sessions/Internal/SessionCostTotal.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using OpenCode.Sdk.Models;

namespace OpenCode.Sdk.Internal;

/// <summary>Totals every descendant's cost for a root, or a child's own cost, matching packages/client/src/solid/data.ts:1582-1590.</summary>
/// <param name="client">The sessions family.</param>
internal sealed class SessionCostTotal(SessionsClient client)
{
/// <summary>Reads the session's own cost, adding every descendant only for a root session.</summary>
/// <param name="session">The session client.</param>
/// <param name="sessionId">The session identifier.</param>
/// <param name="requestOptions">Options for each request.</param>
/// <param name="cancellationToken">Cancels the read or traversal.</param>
/// <returns>The session's cost total.</returns>
public async Task<double> ReadAsync(SessionClient session, string sessionId,
OpenCodeRequestOptions? requestOptions, CancellationToken cancellationToken)
{
var response = await session.GetAsync(requestOptions, cancellationToken).ConfigureAwait(false);
var info = response.Session;
if (info.ParentId is not null)
{
return info.Cost;
}

var visited = new HashSet<string>(StringComparer.Ordinal) { sessionId, info.Id };
return await ReadDescendantsAsync(sessionId, info.Cost, visited, requestOptions, cancellationToken).ConfigureAwait(false);
}

private async Task<double> ReadDescendantsAsync(string sessionId, double total, HashSet<string> visited,
OpenCodeRequestOptions? requestOptions, CancellationToken cancellationToken)
{
var children = new List<SessionInfo>();
await foreach (var child in client.EnumerateSessionsAsync(new SessionListRequest
{
ParentId = SessionParentFilter.Of(sessionId),
Order = ListOrder.Descending,
Limit = 200,
}, requestOptions, cancellationToken).ConfigureAwait(false))
{
children.Add(child);
}

foreach (var child in children.Where(child => visited.Add(child.Id)))
{
total += child.Cost;
total = await ReadDescendantsAsync(child.Id, total, visited, requestOptions, cancellationToken).ConfigureAwait(false);
}

return total;
}
}
32 changes: 32 additions & 0 deletions src/OpenCode.Sdk/Sessions/SessionsClientExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using OpenCode.Sdk.Internal;

namespace OpenCode.Sdk;

/// <summary>Reads session costs including every descendant subagent session.</summary>
public static class SessionsClientExtensions
{
/// <summary>Returns a session's own cost plus the cost of every descendant session, or only its own cost for a child session.</summary>
/// <param name="client">The sessions family.</param>
/// <param name="sessionId">The session identifier.</param>
/// <param name="requestOptions">Options for each request.</param>
/// <param name="cancellationToken">Cancels the session read or children traversal.</param>
/// <returns>The session's cost total.</returns>
/// <remarks>
/// Reads the session, then every descendant session depth-first, each level across every page,
/// and counts each session once. NoThrow is refused at the call. Every failure propagates,
/// including the server's not-found error for an unknown session.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is null.</exception>
/// <exception cref="ArgumentException">The session identifier is invalid, or <paramref name="requestOptions"/> selects NoThrow.</exception>
/// <exception cref="OpenCodeApiException">The session read or children traversal returned an API error.</exception>
/// <exception cref="OpenCodeTransportException">The session read or children traversal failed in transport.</exception>
/// <exception cref="OperationCanceledException">The caller canceled the session read or children traversal.</exception>
public static Task<double> GetTotalCostAsync(this SessionsClient client, string sessionId,
OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(client);
ErrorBehaviorPolicy.RefuseNoThrow(requestOptions, "Session cost totals");
var session = client.GetSessionClient(sessionId);
return new SessionCostTotal(client).ReadAsync(session, sessionId, requestOptions, cancellationToken);
}
}
5 changes: 5 additions & 0 deletions tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ private static IEnumerable<DoorCase> Cases()
yield return new("http", "raw-upload", caller => AtBodyAsync(upload: true, caller));
yield return new("default-wait", "headers", caller => AtHeadersAsync(
static (client, token) => client.LanguageModels.WaitForDefaultAsync(cancellationToken: token), caller));
yield return new("session-cost-total", "headers", caller => AtHeadersAsync(
static (client, token) => client.Sessions.GetTotalCostAsync(SessionId, cancellationToken: token), caller));
yield return new("plugin-wait", "headers", caller => AtHeadersAsync(
static (client, token) => client.Plugins.WaitForPluginsAsync(cancellationToken: token), caller));
yield return new("client-mcp-token", "headers", caller => AtHeadersAsync(
Expand Down Expand Up @@ -590,6 +592,7 @@ public bool Is(Type owner, string name, Type result, params Type[] parameters) =
DeclaringType == owner && Name == name && ReturnType == result &&
IsStatic == (owner == typeof(OpenCodeServer) || owner == typeof(OpenCodeServiceConfiguration) ||
owner == typeof(LanguageModelsClientExtensions) || owner == typeof(PluginsClientExtensions) ||
owner == typeof(SessionsClientExtensions) ||
owner == typeof(ExperimentalClientMcpExtensions)) &&
Parameters.SequenceEqual(parameters);

Expand Down Expand Up @@ -684,6 +687,8 @@ _ when member.Is(typeof(EventsClient), nameof(EventsClient.WatchConnectionAsync)
_ when ClientFamilies.Contains(member.DeclaringType) && IsGeneric(member.ReturnType, typeof(IAsyncEnumerable<>)) => "other-sse",
_ when member.Is(typeof(LanguageModelsClientExtensions), nameof(LanguageModelsClientExtensions.WaitForDefaultAsync), typeof(Task<ModelDefaultResponse>),
typeof(LanguageModelsClient), typeof(ModelDefaultRequest), typeof(OpenCodeRequestOptions), typeof(CancellationToken)) => "default-wait",
_ when member.Is(typeof(SessionsClientExtensions), nameof(SessionsClientExtensions.GetTotalCostAsync), typeof(Task<double>),
typeof(SessionsClient), typeof(string), typeof(OpenCodeRequestOptions), typeof(CancellationToken)) => "session-cost-total",
_ when member.Is(typeof(PluginsClientExtensions), nameof(PluginsClientExtensions.WaitForPluginsAsync), typeof(Task),
typeof(PluginsClient), typeof(PluginListRequest), typeof(OpenCodeRequestOptions), typeof(CancellationToken)) => "plugin-wait",
_ when member.IsStatic && member.DeclaringType == typeof(RpcClientExtensions) && member.Name == nameof(RpcClientExtensions.CallAsync)
Expand Down
Loading