How to build and extend the Flutter SDK in sdks/dart. Read this before changing stream_agents (its core, chat or rtc area), the Flutter demo's use of Stream's AI components, or before adding a Dart client for a new endpoint.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Sdk Dart?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/getstream-sdk-dart)
---
name: sdk-dart
description: How to build and extend the Flutter SDK in sdks/dart. Read this before changing stream_agents (its core, chat or rtc area), the Flutter demo's use of Stream's AI components, or before adding a Dart client for a new endpoint.
---
# Dart SDK conventions
The per-language half of [sdk](../sdk/SKILL.md). It records the decisions the packages in
[`sdks/dart`](../../../sdks/dart) already follow, so a change lands consistently rather than
re-litigating them. It is a **client-side** SDK: what a phone, a browser or a desktop app does.
Folder sync, dispatch and writing configs are backend work and stay out.
Dart 3.12 and Flutter 3.44 are the floors, because Stream Chat 10.4's are; Stream Video 1.6's
are lower.
## The package
One Flutter package, `stream_agents` in `sdks/dart/stream_agents`. Inside it, three areas:
```
lib/src/core pure Dart: generated client, socket, conversation state
lib/src/chat pure Dart: the conversation's Stream Chat channel -> core
lib/src/rtc joining the call over Stream Video -> core
```
Each area is self-contained: `lib/src/<area>` and `test/<area>` hold all of it, and the only way
in from another area is one import. `test/area_boundaries_test.dart` enforces it:
1. `core` imports only its own files, `dart:async`, `collection`, `convert`, `math`,
`typed_data`, `http`, `meta` and `web_socket`: an allowlist, so a dependency added for `rtc`
cannot slip in. `chat` adds `stream_chat` and `core`'s barrel to that list.
2. `chat` and `rtc` reach `core` only, never each other.
3. Across areas, only through the area's barrel (`package:stream_agents/src/core/core.dart`);
inside one, relative imports.
4. `stream_chat` is `chat`'s alone; `stream_video_flutter` and `image` are `rtc`'s.
5. A test under `test/<area>` imports its own area (barrel or internals), the barrels its area
reaches, or, in `rtc` only, `package:stream_agents/stream_agents.dart`. `test/core` and
`test/chat` import no Flutter. Every test but the boundary test is under an area.
`lib/stream_agents.dart` is the only public library and exports the three barrels. A new public
type goes in its area's barrel.
- `core` has no Flutter import and no Stream dependency. `dart:io` stays out of `lib/` too, so
it runs on the web: `package:http` and `package:web_socket` pick the platform themselves.
- `rtc` keeps Stream Video's types out of `core`. `VoiceState.call` is the one Stream type it
exposes, because rendering video needs it.
- **No conversation views.** The views are Stream Chat's AI components,
`stream_chat_flutter_ai`, which the app adds itself, as the Swift SDK leaves them to
`StreamChatAI`; see [Views](#views). There was a `ui` package with widgets of its own; it went
the way Swift's did, so the two SDKs stay one shape.
- `chat` depends on `stream_chat`, which is pure Dart, so the area stays pure Dart like
`core`. Import it with a prefix (`as stream`): it exports a `TokenProvider` of its own.
- Stream's packages take a caret range from a tested floor (`stream_video_flutter: ^1.6.0`,
`stream_chat: ^10.4.0`), as Swift's `from:` and JavaScript's `^` do: a published package
pinned to one version would refuse every app on another patch. Raising a floor is a
deliberate change: read the changelog, rerun the rtc tests, and check the APIs used (listed
below) in the new source. The examples pin exact versions, as apps may.
- `pubspec.lock` is gitignored: a library leaves resolving to the app.
Stream Video's singleton: use `StreamVideo.create`, never the `StreamVideo(...)` factory, which
installs a process-wide instance and collides with a host that has its own.
## Stream is set up once
The key, `userId` and token are the one identity for the router, Stream Chat and Stream Video.
`Backend` fetches the token single-flighted once and reuses it across router requests, socket
handshakes and Stream clients, refreshing only on an HTTP 401 (with a single retry) or
`streamCredentials(refresh: true)`. `Backend.shared(kind, open:, disconnect:)` holds one client
per `kind:apiKey:userId`: sessions asking at once share one opening, one that failed to open is
opened again, and `withUser` keeps the registry so another user gets their own. `Backend.give`
holds the app's own client, which `StreamAgents.disconnect()` never touches; it closes only what
`shared` built. Beside a `customerId` the key is Stream's alone and the router is reached by
customer id.
- `chat`: `agents.useChat(client)` and `session.chat()`, which answers the
conversation's `Channel`, unwatched. A session with no conversation is a `StateError`.
- `rtc`: `agents.useVideo(client)` and `VoiceSession.join()`, which joins the
session's `callType:callId`. Leaving disposes nothing.
- Dart has no overloading, hence `useChat` and `useVideo` rather than Kotlin's `use`. A
client for another user, or a missing key, user or token, is an `ArgumentError`.
## State
`LiveValue<T>`: a `value` and a `stream` that emits the current value first, then each change.
`LiveValueController` skips equal values and conflates while a listener is paused. No
dependency on provider, riverpod, bloc or rxdart — a host adapts it in a line, such as a
`StreamBuilder` over `stream` with `initialData: value`, without which its first frame has no data.
The state machine is an **immutable value**, `Conversation`, with `apply(event)` returning the
next value (or `this` when nothing changed, so equality skips a rebuild). That is what makes it
testable without a network, and it is where new event handling goes.
`AgentSession.events()` hands each caller its own bounded stream (256), and finishes a listener
that falls that far behind rather than buffering without bound. Never one shared broadcast
stream property. Answering a tool call does not depend on anybody listening: it happens inside
`AgentSession`'s own read loop.
## The socket
`package:web_socket`, one read loop per connection.
- A close with 1000 (the router's "the session ended") or one we asked for finishes the stream;
anything else throws `SocketClosedException` with the code.
- A frame that cannot be decoded is skipped, not fatal.
- Closing is idempotent and sends 1000.
- A handshake carries none of the SDK's headers, neither `X-Stream-Client` nor `User-Agent`
(off the web, dart:io sends its own `Dart/<version>`): `package:web_socket` takes no headers,
so a socket's credentials are all in its query.
- **No automatic reconnection.** `respond` and `tool_result` are not idempotent and the protocol
has nothing to resume from. `AgentSession.connection` reports `Disconnected(failure)` and the
caller decides.
- A tool result echoes `request_id` and `turn_id` only when the call carried a `request_id`; a
bare `turn_id` routes to a path that fails for a persisted session.
Frames in tests are quoted verbatim from `frameOf` in
[`sessionws.go`](../../../acceleration/internal/api/sessionws.go).
## The generated client
`tool/generate.dart` reads the spec and writes `lib/src/core/generated/api.dart`: one model
class per schema reached by an allowlisted operation, and an `Operations` class with a method
per operation. Committed, formatted, never hand-edited, **never exported**. Every public type is
hand-written in `models.dart` and mapped in `convert.dart`, so a spec field is invisible until
it is wrapped and the SDK's semver is not the schema's.
- The allowlist (`operations`, `sockets`) fails generation if an id is missing or not marked
`x-client-accessible`. Adding an endpoint means adding its id and rerunning.
- `--check` regenerates in memory and fails if the committed file differs. Run it in CI.
- Enums are strings in generated code and Dart enums with an `unknown` value in `models.dart`.
- Dates go through `parseRouterDate`: Go writes up to nine fractional digits, Dart reads six.
- Generated `toJson` omits nulls. **Null means omit** and let the config or the router decide,
never a copy of the server's default.
- A wrong type in an answer throws `UnreadableException` naming the field, not a `TypeError`.
## Errors
`sealed class AgentsException implements Exception`: `RouterException` (status, message, the
operation; `isServerSideOnly` on 403), `TransportException` (no answer at all),
`UnreadableException` (an answer that is not what the spec says), `SocketClosedException`.
Callers `switch` over it exhaustively. Never classify by parsing a message. Argument mistakes
are `ArgumentError`, thrown before any I/O.
`RouterException` also carries the envelope `{"error": {"message", "type", "code", "doc_url"}}`
as `type` (a `RouterErrorType`, `unknown` for one newer than the SDK), `code` (an open string
to branch on), `docUrl` and `requestId` (the `X-Request-Id` header, what a 500 is quoted by),
and `retryAfterSeconds`, the `Retry-After` header as whole seconds (null for a date).
`_refusalOf` in `wire.dart` reads it by hand, since the generator only reaches request and
success schemas; any other body keeps its trimmed text (at most 1000 characters) or the
status phrase as the message, with the request id and the wait and nothing else. A refused socket
handshake stays a `TransportException`: `package:web_socket` gives a message only, no status,
headers or body.
## Public API
```dart
final agents = StreamAgents(url: url, customerId: 'acme');
final session = await agents.agent('support').sessions.create();
```
The constructor does no I/O. Advanced forms take an options value (`SessionOptions`,
`ForkOptions`, `SessionQuery`, `SearchOptions`), not thirty named parameters.
Names chosen to not collide with what a Flutter app imports: `SearchRouter` (not `Router`),
`AgentImage` (not `ImageSource`), commands suffixed `Command`. Stream Chat also exports a
`Command`; a host importing both hides one.
Guests: `guestUser` reuses what the `GuestStore` holds until a minute before it expires, then
asks again with its id and the `refresh_secret` stored beside it (`readGuest` and `writeGuest`
keep it off the public `GuestUser`). A secret works once, so whatever comes back replaces what was
stored; one lost or spent gets a new guest. The store is the host's (shared preferences, secure storage);
`MemoryGuestStore` is for tests and CLIs.
## Views
`rtc` has the only widgets, `AgentVideoView` and `VoiceCallView`: no theme object, no route push
and no `Scaffold`. A conversation is shown with Stream Chat's AI components, and
[`flutter_demo`](../../../examples/voice_agents/flutter_demo) is where that composition lives and
is kept working. What the router writes is what it renders:
- A text session's reply is a message marked `ai_generated`, with `generating` true until done.
- Its steps are `ai_reasoning` and `ai_tool_call` attachments, in order: `AIMessagePart.parseAll`
over `(type: attachment.rawType, payload: {'id': attachment.id, ...attachment.extraData})`.
- A reasoning step stores only its opening. The whole of it comes a window at a time on the
`message.updated` events; `LiveReasoning` in `chat` puts it back together, and the demo's
`AIMessage.reasoningText` reads it.
- A tool that asks first is answered by an `AIToolApprover` whose `decide` finds the reply
showing the call `awaiting_approval` and calls `session.decideShown` with its step and the
reply's `support_runtime` (`command_id`, `turn_id`), or `session.decide` for a call only the
session holds; on a call, by an `AIToolApprovalCard` over `session.approvals`. A call the
router holds itself (a connector's under `require_approval`, the agent's scheduling tools for a repeating task, #2533) never
reaches `approvals`, so only `decideShown` answers it.
- `AIConversationView` lays the channel out in turns, `ChatComposer` asks and stops, and
`AIVoiceGlowView` / `AIVoiceWaveView` show the agent on a call.
## rtc
The Stream Video 1.6 surface used: `StreamVideo.create(apiKey, user: User.regular(...),
userToken:, tokenLoader:)`, `makeCall(callType:, id:)`, `call.join(connectOptions:
CallConnectOptions(microphone:, camera:, cameraFacingMode: FacingMode.environment,
speakerDefaultOn: true))` (which creates the call too), `setMicrophoneEnabled`,
`setCameraEnabled(constraints: CameraConstraints(...))`, `call.leave()`, `dispose()`,
`call.state.valueStream`, `StreamVideoRenderer`, `call.getTrack(...).captureScreenshot()`.
Results are `Result<T>`; a `Failure` becomes `VoiceState.failure`.
- A token provider, not a token: `tokenLoader` asks the agents' token function again when the
token expires an hour in.
- The camera starts on the back lens as a join setting, so no front-facing frame is published.
- The agent looks through the camera with the router's `get_video_frames` tool call, answered by
`AgentSession` through `camera` and never offered to the app's tools. `camera` is a
`CameraHandler`, `(at, limit)` to a list of `CameraPicture` records (both hidden from core's
exports), and is public only because `rtc` is a separate area. It is `@internal` (`package:meta`), so the analyzer warns an
app that touches it and its signature is `rtc`'s to change; `rtc`'s uses carry an `ignore`. With `camera` null the call is
left alone (a backend video worker may own it); with `run: false` it is left alone too, as JS
does; a `tool_cancel` drops the answer, as for the app's tools. Core reads `at_ms` and `limit`
(1 to 8), sends the pictures oldest first as `camera-n`, and answers an empty list or a throw
with the nothing-recent words.
- `VoiceSession` sets `camera` while its camera is on, and `stop`s and clears it on camera off
(before Stream Video turns it off, so a look under way cannot finish on the pictures it took),
`leave` and `end`. Stream Video 1.6 has no Dart hook on outgoing frames, so `CameraShots` takes
a screenshot of the call's own track when the agent asks: `limit` pictures asked for 0.5 s apart, each
the camera's next frame at full size (a JPEG on Android, a PNG on iOS), scaled to 1024 px and
made JPEG q70 in `compute` (`package:image`, its JPEG and PNG decoders only, from 4.12.0, the first whose
decoders do not throw on short data). Nothing is taken while idle and nothing kept, so
`at` is not looked back to: the pictures come from just after the question, where iOS and
Android send the ones from just before it. Matching them needs a native frame processor in
`rtc` (`ProcessorProvider` and `setVideoEffects`); `camera` already carries `at` and each
`capturedAt`, so that changes nothing public.
- A screenshot cannot be called off: its sink stays on the track until a frame comes. So a track
that still owes a picture shares it rather than being asked again, even across the camera
turned off and on. `stop` makes a look under way come back empty at once, even one waiting on
a stalled track, since what a camera turned off showed is not for the agent. `captureFrame`
writes every picture to the one `captureFrame.png` in the temp directory, so an app taking its
own `takeScreenshot` at the same moment can swap pictures with it. Several full-size pictures pass the router's 5 MiB socket
frame limit, which closes the socket; hence the scaling. A socket that names its `tools` must
name `get_video_frames` too, or the router sends the call with `run: false` and drops the
answer.
- Permissions are the host app's: `RECORD_AUDIO`, `MODIFY_AUDIO_SETTINGS`, `CAMERA`,
`BLUETOOTH_CONNECT`, `INTERNET`, `ACCESS_NETWORK_STATE`; `NSMicrophoneUsageDescription`,
`NSCameraUsageDescription`. Emulators do not test echo cancellation or audio routing.
## Tests
`package:test` in core and chat, `flutter_test` in rtc, all run by `flutter test`. Never mock; assert on state and outputs,
never on a call happening.
1. **The state machine**, on real frames, with no network.
2. **The client** against a real HTTP and WebSocket server on loopback (`test/support/router.dart`
in core; rtc has its own small one), recording what arrived.
3. **Live tests**, tagged `live` and skipped unless `VISION_AGENTS_URL` is set: real sessions, a
real model answer, a real tool call, rewind and fork, guests, search.
4. **The posture**: `posture_test.dart` drives every public operation against the loopback
router and checks each request against `x-client-accessible` in the spec;
`keyed_router_posture_test.dart` (tagged `live`, skipped without `INTEGRATION_ROUTER_KEY`)
checks a real `api_key` router answers a device 403 `server_side_only`.
`stream_clients_test.dart` covers the shared clients.
Wait on a condition with a deadline (`_until`), never a fixed sleep.
CI is [`client-sdks.yml`](../../../.github/workflows/client-sdks.yml), on any change under
`sdks/dart`, `flutter_demo`, `flutter_assistant` or the spec: one Flutter job with the checks and
tests below, then `flutter analyze` and `flutter test` in both examples against the package as
it is in the checkout.
Flutter 3.50 deprecates `package:flutter/material.dart`. Each import of it carries
`// ignore: deprecated_member_use` rather than a global ignore, so any other deprecation still
fails the analyzer.
Docker only, pub's cache in the named volume `va-dart-pub`:
```bash
docker run --rm -v "$PWD":/repo -v va-dart-pub:/pub-cache -e PUB_CACHE=/pub-cache \
-w /repo/sdks/dart/stream_agents ghcr.io/cirruslabs/flutter:3.44.0 \
sh -c 'flutter pub get && dart format --set-exit-if-changed . && flutter analyze && dart run tool/generate.dart --check && flutter test'
# live, against a router on the host
docker run --rm -v "$PWD":/repo -v va-dart-pub:/pub-cache -e PUB_CACHE=/pub-cache \
-e VISION_AGENTS_URL=http://host.docker.internal:8080 -e VISION_AGENTS_CUSTOMER_ID=examples \
-e VISION_AGENTS_AGENT=simple_voice_ai -w /repo/sdks/dart/stream_agents ghcr.io/cirruslabs/flutter:3.44.0 flutter test -t live
```
## Releasing
`.github/workflows/release-sdk-dart.yml` publishes the version `pubspec.yaml` names, by hand or
with every other SDK (see the `release-sdks` skill); by hand it is `flutter pub publish` from
`sdks/dart/stream_agents`, after the CI dry run passes. A release
sets `sdkVersion` in `lib/src/core/backend.dart` with the `version` in `pubspec.yaml`, since a
package cannot read its own pubspec when it runs: it is the release `X-Stream-Client` and
`User-Agent` name, and a test fails until the two match. A browser sends no `User-Agent` of
the SDK's (`userAgent` is null there), since neither CORS list allows it. The first
release of `stream_agents` also discontinues `stream_agents_core`, `stream_agents_chat` and
`stream_agents_rtc` on pub.dev, each with `stream_agents` as its replacement (the package's
admin page, "Mark as discontinued"), so an app on 0.1.0 is pointed at the one package.
## Reviewing a change
Reject it if it:
- imports Flutter, `dart:io` or a Stream package into `lib/src/core`, or crosses areas other
than through `core`'s barrel;
- exports generated code, or hand-edits it;
- adds a method for an operation the spec does not mark `x-client-accessible`;
- sends a default the caller did not choose;
- reconnects the socket, or replays `respond`/`tool_result`;
- treats an unknown frame as fatal;
- uses the `StreamVideo` singleton factory;
- adds conversation views to the SDK rather than to Stream Chat's AI components;
- adds a theme object, a route push or a `Scaffold` to `rtc`;
- mocks, or asserts that a method was called.