opencode_sdk_dart
A cross-platform Dart 3 SDK for the OpenCode V2 HTTP API.
The SDK is generated from the official OpenAPI 3.1 contract served at
opencode.ai/v2/openapi.json and mirrors the semantics of the
reference TypeScript client (@opencode/client): identical resource layout,
envelope unwrapping, error decoding, shared event connection, plugin RPC
behavior, PTY WebSocket handshake, and background service discovery.
A ready-made macOS client built on this SDK lives in
chat_app/:
streaming transcripts, tool cards, session management, agent/model switching,
and permission prompts. The larger
opencode_cockpit/
workbench adds project tabs, a session tree, files and git panels, session
diffs, worktree management, a statistics dashboard, and real PTY terminals.
A typed-effect adapter lives in
opencode_effect: the SDK stays a
plain, generated, dependency-light client, while every
operation can be bound as a lazy Effect on effect_core — one sealed error
family, interruption that aborts in-flight requests, scoped client lifetime,
pull streams for events and turns, and read-only retry schedules. All four
consumer projects use it at their service/controller boundary.
Highlights
- Typed resources for all 28 API groups —
client.session,client.pty,client.mcp,client.permission,client.vcs, and more. - 438 generated declarations: sealed unions with exhaustive
switchsupport, branded scalar types (extension type SessionID(String)), real Dart enums with wire mapping, and data classes withfromJson/toJson. - Structured errors: every
_tag-encoded error becomes a typed exception (SessionNotFoundError,RpcError, ...) carrying the HTTP status code. - One lazy event connection shared by native events and plugin RPC, with
server.connectedreplay for late subscribers and per-subscriber overflow protection, exactly like the reference client. - Plugin RPC with typed method calls and event streams
(
client.rpc('acme').call(...),.subscribe(...),.on(...)). - PTY support: ticket handshake plus WebSocket connect helpers for both regular and persistent PTYs.
- Local service management:
OpenCodeService.discover(),ensure(),stop(), and Basic-auth headers, including persistent-terminal handoff. - Cross-platform: pure Dart on
dart:ioplatforms and the web (package:http+web_socket_channel); cancellation viaCancellationTokenaborts in-flight requests and streams.
Getting started
dependencies:
opencode_sdk_dart: ^0.1.0
import 'package:opencode_sdk_dart/opencode_sdk_dart.dart';
Future<void> main() async {
// Discover (or start) the local background service and authenticate.
final client = await OpenCodeClient.connectLocal();
// For a remote server:
// final client = OpenCodeClient.make(baseUrl: Uri.parse('http://host:4096'));
final info = await client.server.info();
print('OpenCode ${info.version} at ${info.urls}');
final session = await client.session.create(title: 'Hello');
await client.session.prompt(sessionID: session.id, text: 'Hi there!');
await for (final event in client.event.subscribe()) {
print(event.type);
if (event.type == 'session.idle') break;
}
client.close();
}
OpenCode.connectLocal() is the same entry point exported as a static on the
OpenCode helper class, matching the reference naming.
A complete, runnable tour lives in example/main.dart:
dart run example/main.dart connects, streams a turn with deltas and step
usage, and lists recent sessions.
Working with resources
Method arguments are named and flattened, so request bodies read as plain arguments:
final session = await client.session.create(
title: 'Review',
agent: AgentID('build'),
location: const LocationRef.directory('/workspace'),
);
await client.session.prompt(
sessionID: session.id,
text: 'Review the current changes',
);
final messages = await client.session.message.list(sessionID: session.id);
final diff = await client.session.diff(sessionID: session.id);
Grouped endpoints keep the reference client's nesting:
client.session.form.reply(formID: ..., sessionID: ..., answers: ...)
client.session.revert.stage(sessionID: ...)
client.permission.saved.list()
client.mcp.resourceCatalog()
client.vcs.branchList()
Envelope handling matches the reference behavior: {data: ...} responses are
unwrapped (session.create() returns SessionInfo), while
{location, data} responses return a LocatedResponse<T> exposing both
fields.
Request options
Every call accepts RequestOptions:
final token = CancellationToken();
final agents = await client.agent.list(
options: RequestOptions(
location: const LocationRef.directory('/workspace'),
headers: {'x-my-header': 'value'},
cancelToken: token,
),
);
token.cancel(); // aborts the request and closes its stream
Transient failures can be retried with an opt-in RetryPolicy — either on the
transport (every request) or per request:
client.transport.retry = const RetryPolicy(); // GET/HEAD only, 3 attempts
await client.session.get(
sessionID: session.id,
options: const RequestOptions(
retry: RetryPolicy(maxAttempts: 5, retryNonIdempotent: false),
),
);
Writes are never retried unless retryNonIdempotent is set: a prompt that
timed out may already have been admitted, and a blind retry would run it
twice. Retry-After hints (whole seconds) are honored, and retries abort
promptly when the request's cancellation token fires.
Events
client.event.subscribe() and client.events.subscribe() are aliases backed
by one lazily opened connection:
- no connection opens until the first listener subscribes;
- late subscribers immediately receive the
server.connectedmarker; - cancelling one subscription leaves the others running; the last one closes the connection;
- slow consumers buffer up to 4096 events and then fail their stream;
- subscriptions are live-only: a source failure ends current subscriptions and a new subscription opens a fresh connection.
final subscription = client.event.subscribe().listen((event) {
switch (event.type) {
case 'server.connected':
print('connected');
case 'session.updated':
print(event.data);
}
});
Sessions and turns
client.streamPrompt(...) runs one session turn end to end: it sends the
prompt, streams text and reasoning deltas, and resolves with the server's own
record of the message.
final turn = client.streamPrompt(
sessionID: session.id,
text: 'Explain what this repository does.',
);
await for (final event in turn) {
switch (event) {
case SessionTurnTextDelta(:final delta):
stdout.write(delta);
case SessionTurnReasoningDelta(:final delta):
stderr.write(delta);
case SessionTurnStepUsage(:final usage):
print('${usage.totalTokens} tokens so far');
case SessionTurnCompleted():
break;
}
}
final result = await turn.result;
print(result.text); // reconciled full answer
print(result.reasoning); // full reasoning, when the model produced any
print(result.usage.totalTokens);
The event stream is treated as best-effort: it is live-only and can end
mid-turn (reconnects, slow-consumer overflow, server restarts), so each turn
races the events against session.wait plus an assistant-message check, and
reconciles the final text with the server's record. A dropped event stream
delays the answer but never loses it. A failed execution surfaces as
OpenCodeExecutionException on turn.result.
Listing endpoints that page with cursors have listAll helpers that follow
cursor.next until it runs out:
await for (final session in client.session.listAll(search: 'coach')) {
print(session.title);
}
await for (final message in client.session.message
.listAll(sessionID: session.id, type: SessionMessageListType.assistant)) {
print(message.id);
}
Plugin RPC
final acme = client.rpc('acme');
// Typed call; `input` is serialized as-is, `decode` receives the raw output.
final result = await acme.call(
'search',
input: {'query': 'hello'},
decode: (output) => asJsonMap(output)['text'] as String,
);
// Streaming subscription (filtered from the shared event connection).
final stream = acme.subscribe<String>(
'updated',
decode: (data) => asJsonMap(data)['text'] as String,
);
// Callback subscription with sequential async handling; returns unsubscribe.
final unsubscribe = acme.on<String>(
'updated',
(event) async => print(event.data),
decode: (data) => asJsonMap(data)['text'] as String,
);
Declared RPC errors surface as RpcError (with type, data, and
statusCode); framework failures surface as RpcInternalError.
PTY WebSockets
final socket = await client.pty.connectSocket(ptyID: PtyID('pty_1'));
socket.text.listen(stdout.write);
socket.send('ls\n');
await socket.close();
client.persistentPty.connectSocket(...) mirrors the persistent PTY handshake
(with cursor, role, attachmentID, and takeover).
Errors
try {
await client.session.get(sessionID: SessionID('ses_missing'));
} on SessionNotFoundError catch (error) {
print(error.statusCode); // 404
print(error.sessionID);
} on OpenCodeApiException catch (error) {
print(error.tag); // wire discriminator
}
Transport failures throw OpenCodeTransportException; invalid payloads throw
OpenCodeDecodeException with a dotted path; cancelled calls throw
OpenCodeCancelledException; non-declared statuses throw
OpenCodeStatusException.
Models
Unions are sealed classes with exhaustive pattern matching:
final kind = switch (message) {
SessionMessageUser() => 'user',
SessionMessageAssistant() => 'assistant',
SessionMessageCompaction() => 'compaction',
_ => message.type,
};
Union parents expose members shared by every variant (message.id,
message.type). Scalar schemas are zero-cost extension types:
final id = SessionID('ses_123'); // implements String
final cost = MoneyUSD(0.25); // implements double
Enums carry their wire value: PtyStatus.running.wire == 'running'.
Local service management
final endpoint = await OpenCodeService.discover(); // no process start
final ensured = await OpenCodeService.ensure(); // discovers or starts
final headers = OpenCodeService.headers(ensured); // Basic auth headers
await OpenCodeService.stop(); // stop exact instance
// Version constraints and lifecycle callbacks:
await OpenCodeService.ensure(
options: EnsureOptions(
version: ServiceVersionConstraint.matches((v) => v.startsWith('2.')),
onStart: (reason, previous) => print('$reason $previous'),
),
);
On the web, discovery throws UnsupportedError; connect to a reachable server
directly instead.
Phone access over Wi-Fi
All three apps build for the web, and tool/lan_host.dart serves those builds
plus a reverse proxy for the OpenCode API, so a phone on the same Wi-Fi can use
them without any build-time configuration:
# one-time, from each app directory you want to use on the phone:
cd chat_app && flutter build web --release --base-href /chat/
# gym_coach uses --base-href /openfit/, opencode_cockpit uses /cockpit/
# from the repository root: start the host (discovers or starts the service)
dart run tool/lan_host.dart # --port 8080 --host 0.0.0.0
The host prints the LAN URL for each app plus an ASCII QR code of the index;
scan it and open http://<lan-ip>:8080/chat/ (or /openfit/, /cockpit/).
Missing web builds render a placeholder page with the exact
flutter build web command to run. Keep the host running while you use the
phone; stopping it leaves the OpenCode service untouched.
The /api/... proxy injects the service's Basic-auth headers, forwards
methods, headers, and bodies, streams responses (including SSE) without
buffering, and upgrades PTY WebSockets. File and photo attachments from the web
apps go through POST /_upload — raw bytes plus an x-filename header — which
stores the file under <system temp>/openfit-uploads/ and answers
{"path": "<absolute path>"}, the server-local path the OpenCode API expects
for attachments.
Every app ships a PWA manifest, branded icons (dart run tool/make_icons.dart
regenerates them for web and macOS), and iOS home-screen meta tags, so Add to
Home Screen from the phone browser opens them full-screen like an app. The
full install prompt and offline caching need a secure context (HTTPS or
localhost); over the plain-HTTP LAN URL you get the home-screen shortcut and
everything works live while the host is running.
Regenerating the SDK
The entire lib/src/generated tree is produced from openapi/openapi.json:
curl -o openapi/openapi.json https://opencode.ai/v2/openapi.json
dart run tool/generate.dart
dart format lib tool --line-length 80
dart analyze --fatal-infos
The generator (tool/generate.dart) handles the contract's OpenAPI 3.1
constructs: dotted schema names, anyOf nullability, _tag/type/status
discriminators, nested unions, deepObject location parameters, wildcard
paths, binary bodies, SSE endpoints, and envelope shapes.
Testing
dart test # unit suite with mocked HTTP
dart run tool/live_smoke.dart # read-only checks against a running server
dart run example/main.dart # end-to-end tour: streaming turn + pagination
The unit suite covers models, unions, error decoding, query/URL encoding,
cancellation, SSE framing, multiplexer semantics, RPC calls and events,
resource envelopes, and service discovery. tool/live_smoke.dart validates
discovery, typed resources, and SSE against a live service.
Publishing
Publish in dependency order from a clean checkout:
dart run tool/publish.dart sdk --dry-run
dart run tool/publish.dart sdk
dart run tool/publish.dart effect
dart run tool/publish.dart genkit
tool/publish.dart stages the sibling packages outside the repository so the
root .pubignore does not hide them, and drops their local
pubspec_overrides.yaml files before uploading. The sdk target publishes
from the repository root. dart pub publish prompts for pub.dev authorization
on first use.
Repository layout
The published SDK contains lib/, example/, test/, and tool/. The
remaining directories are separate packages and apps in the repository:
lib/
opencode_sdk_dart.dart # public API
src/core/ # transport, SSE, events, errors, options
src/rpc/ # plugin RPC subclient
src/pty/ # WebSocket helpers + resource extensions
src/session/ # turn streaming + pagination helpers
src/service/ # local background service management
src/generated/ # models + 28 resources + client (generated)
opencode_effect/ # effect_core adapter: typed effects, layers,
# pull streams, scoped client lifetime
chat_app/ # chat client: macOS + phone web
opencode_cockpit/ # workbench: macOS + phone web (projects, git, PTY)
genkit_opencode_custom/ # Genkit Dart plugin: OpenCode server bridge
# (openCode()) through this SDK, plus an
# OpenAI-compatible handle (openAI())
gym_coach/ # OpenFit: coach for macOS + phone web (typed
# plans, ask-coach chat, interactive workout)
example/
main.dart # SDK tour: streaming turn, step usage, pagination
tool/
generate.dart # OpenAPI 3.1 -> Dart 3 code generator
lan_host.dart # LAN host: serves the web builds + proxies the API
live_smoke.dart # live read-only smoke test
make_icons.dart # branded app icons for web + macOS
publish.dart # publishes the SDK and sibling packages
openapi/openapi.json # pinned contract snapshot
opencode_effect and genkit_opencode_custom are published separately and
depend on this SDK through hosted version constraints; their
pubspec_overrides.yaml files point them at this checkout during development.
The client apps (chat_app, opencode_cockpit, and gym_coach) are not
published.
Notes on divergence from @opencode/client
- Errors expose a
statusCodecaptured from the HTTP response. {location, data}envelopes decode toLocatedResponse<T>instead of stripping the location.- JSON bodies are encoded as UTF-8 bytes with an explicit
application/json; charset=utf-8content type. - Web-only builds cannot manage a local service; everything else is platform-independent.
License
This project is licensed under the MIT License — see LICENSE.
Libraries
- opencode_sdk_dart
- Cross-platform Dart SDK for the OpenCode V2 HTTP API.