Dart SDK conventions
The per-language half of sdk. It records the decisions the packages in
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:
coreimports only its own files,dart:async,collection,convert,math,typed_data,http,metaandweb_socket: an allowlist, so a dependency added forrtccannot slip in.chataddsstream_chatandcore's barrel to that list.chatandrtcreachcoreonly, never each other.- Across areas, only through the area's barrel (
package:stream_agents/src/core/core.dart); inside one, relative imports. stream_chatischat's alone;stream_video_flutterandimagearertc's.- A test under
test/<area>imports its own area (barrel or internals), the barrels its area reaches, or, inrtconly,package:stream_agents/stream_agents.dart.test/coreandtest/chatimport 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.
corehas no Flutter import and no Stream dependency.dart:iostays out oflib/too, so it runs on the web:package:httpandpackage:web_socketpick the platform themselves.rtckeeps Stream Video's types out ofcore.VoiceState.callis 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 toStreamChatAI; see Views. There was auipackage with widgets of its own; it went the way Swift's did, so the two SDKs stay one shape. chatdepends onstream_chat, which is pure Dart, so the area stays pure Dart likecore. Import it with a prefix (as stream): it exports aTokenProviderof 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'sfrom: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.lockis 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)andsession.chat(), which answers the conversation'sChannel, unwatched. A session with no conversation is aStateError.rtc:agents.useVideo(client)andVoiceSession.join(), which joins the session'scallType:callId. Leaving disposes nothing.- Dart has no overloading, hence
useChatanduseVideorather than Kotlin'suse. A client for another user, or a missing key, user or token, is anArgumentError.
shared, give, headers, requestUri, disconnectStream and anonymous are @internal, as
are the constructors of AgentSession, Sessions, ScheduledTasks and SearchRouter: an app
reaches them through StreamAgents, useChat and useVideo. The token provider is private
(_tokenProvider): it is passed in as token: and never read back. socketUri stays public
beside the exported SessionSocket, for a caller following a session itself.
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"), one naming no code (1005) or one we
asked for finishes the stream; anything else throws
SocketClosedExceptionwith 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-ClientnorUser-Agent(off the web, dart:io sends its ownDart/<version>):package:web_sockettakes no headers, so a socket's credentials, andX-Stream-Client, are all in its query. - No automatic reconnection.
respondandtool_resultare not idempotent and the protocol has nothing to resume from.AgentSession.connectionreportsDisconnected(failure)and the caller decides. - A tool result echoes
request_idandturn_idonly when the call carried arequest_id; a bareturn_idroutes to a path that fails for a persisted session. StreamAgents.attachreturns once the socket is open, and throws if it cannot;attach(id, start: false)returns before, since watching an ended conversation waits seconds while the router carries it on, and a screen shows the conversation's channel meanwhile (flutter_assistant'sAgentChat).start()then opens it, and throws why it could not.
Frames in tests are quoted verbatim from frameOf in
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 markedx-client-accessible. Adding an endpoint means adding its id and rerunning. --checkregenerates in memory and fails if the committed file differs. Run it in CI.- Enums are strings in generated code and Dart enums with an
unknownvalue inmodels.dart. - Dates go through
parseRouterDate: Go writes up to nine fractional digits, Dart reads six. - Generated
toJsonomits 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
UnreadableExceptionnaming the field, not aTypeError.
Errors
sealed class AgentsException implements Exception: RouterException (status, message, the
operation; isServerSideOnly on a 403 server_side_only), 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
dartfinal 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, ScheduledTaskQuery), 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
The SDK ships no widgets, as Swift and Kotlin ship no views: the call's controls and its video
are the app's, drawn over voice.state and VoiceState.call. A conversation is shown with
Stream Chat's AI components, and
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, withgeneratingtrue until done. - Its steps are
ai_reasoningandai_tool_callattachments, in order:AIMessagePart.parseAllover(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.updatedevents;LiveReasoninginchatputs it back together, and the demo'sAIMessage.reasoningTextreads it. - A tool that asks first is answered by an
AIToolApproverwhosedecidefinds the reply showing the callawaiting_approvaland callssession.decideShownwith its step and the reply'ssupport_runtime(command_id,turn_id), orsession.decidefor a call only the session holds; on a call, by anAIToolApprovalCardoversession.approvals. A call the router holds itself (a connector's underrequire_approval, the agent's scheduling tools for a repeating task, #2533) never reachesapprovals, so onlydecideShownanswers it. - An incognito session has no channel, and
chat()throws.Conversationfoldsreasoning_delta,tool_started,tool_updatedandtool_ranintoTurn.stepsandTurn.isDone, as Kotlin's does;session.turnMessagesgives the channel's message shape, and a waiting call asksbackend.userId, notSession.userId(the agent's name on the call).flutter_demo'sAgentChat.unkeptshows it. AIConversationViewlays the channel out in turns,ChatComposerasks and stops, andAIVoiceGlowView/AIVoiceWaveViewshow 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.value, call.getTrack(...).captureScreenshot().
Results are Result<T>; a Failure becomes VoiceState.failure.
- A token provider, not a token:
tokenLoaderasks 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_framestool call, answered byAgentSessionthroughcameraand never offered to the app's tools.camerais aCameraHandler,(at, limit)to a list ofCameraPicturerecords (both hidden from core's exports), and is public only becausertcis a separate area. It is@internal(package:meta), so the analyzer warns an app that touches it and its signature isrtc's to change;rtc's uses carry anignore. Withcameranull the call is left alone (a backend video worker may own it); withrun: falseit is left alone too, as JS does; atool_canceldrops the answer, as for the app's tools. Core readsat_msandlimit(1 to 8), sends the pictures oldest first ascamera-n, and answers an empty list or a throw with the nothing-recent words. VoiceSessionsetscamerawhile its camera is on, andstops and clears it on camera off (before Stream Video turns it off, so a look under way cannot finish on the pictures it took),leaveandend. Stream Video 1.6 has no Dart hook on outgoing frames, soCameraShotstakes a screenshot of the call's own track when the agent asks:limitpictures 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 incompute(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, soatis 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 inrtc(ProcessorProviderandsetVideoEffects);cameraalready carriesatand eachcapturedAt, 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.
stopmakes 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.captureFramewrites every picture to the onecaptureFrame.pngin the temp directory, so an app taking its owntakeScreenshotat 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 itstoolsmust nameget_video_framestoo, or the router sends the call withrun: falseand 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.
- The state machine, on real frames, with no network.
- The client against a real HTTP and WebSocket server on loopback (
test/support/router.dartin core; rtc has its own small one), recording what arrived. - Live tests, tagged
liveand skipped unlessVISION_AGENTS_URLis set: real sessions, a real model answer, a real tool call, rewind and fork, guests, search. - The posture:
posture_test.dartdrives every public operation against the loopback router and checks each request againstx-client-accessiblein the spec;keyed_router_posture_test.dart(taggedlive, skipped withoutINTEGRATION_ROUTER_KEY) checks a realapi_keyrouter answers a device 403server_side_only.stream_clients_test.dartcovers the shared clients.
Wait on a condition with a deadline (_until), never a fixed sleep.
CI is 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:
bashdocker 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:ioor a Stream package intolib/src/core, or crosses areas other than throughcore'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
StreamVideosingleton factory; - adds a widget to the SDK, rather than leaving it to the app or Stream Chat's AI components;
- mocks, or asserts that a method was called.


