Swift SDK conventions
The per-language half of sdk. It records the decisions the package in
sdks/swift already follow, so a change lands consistently rather than
re-litigating them. Where a rule has an exception, the exception is written down.
Assume Swift 6 language mode with complete strict concurrency, iOS 15, SPM only.
The package
One package, core, with one product, StreamAgents: the generated client, the socket,
the conversation state, session.chat() (the Stream Chat channel a text session is kept in)
and VoiceSession (joining the agent's call over Stream Video). It is the only thing published.
It depends on stream-chat-swift (StreamChat only) and stream-video-swift (StreamVideo
only), so every app resolves Stream Video's 47 MB StreamWebRTC binary, text-only or not.
That is the price of one artifact; do not split it back up without being asked.
- No views in core. The views are Stream Chat's AI components,
StreamChatAIfrom the samestream-chat-swift, which the app adds itself; see Views. - Stream's types cross the public API only where an app uses Stream's own SDK: the app's
StreamVideoorChatClientinuse,chat()answering aChatChannelController,VoiceSession.call,LiveReasoning.read(_:)taking aChatMessage, andsetUsertaking Stream Chat'sTokenProvider, so one closure connects aChatClientand this. The exception is StreamCore, which Chat and Video both stand on: itsUseris whosetUseracts for and itsRawJSONis every open-ended value, and core@_exported imports it as they do. Do not write a secondUseror JSON enum beside them. Nothing generated crosses. - iOS only, because Stream Video is and Stream Chat's macOS build does not compile under
Swift 6.
stream-chat-swiftis required from 5.13, the first withStreamChatAI, so an app adding the views resolves the version core does;StreamChatalone would build from 5.3 (4.x'sChatClientis notSendable, and 5.0 to 5.2 fail insidestream-core-swift). - Core builds with Xcode 26 and 27.
StreamChatAIneeds Xcode 27 to add with SPM, andstream-video-swiftis required from 1.54.0, since 1.51.0'sStreamVideoSwiftUIdoes not compile under Xcode 27.swift_demousesStreamChatAIand builds. - Declare
platforms:. An unspecified platform makes consumers discover availability failures inside generated code.
Published from this repository. SwiftPM reads a manifest and version tags only at a
repository's root, so the manifest is the root Package.swift, its targets reaching into
sdks/swift/core with path:, and the examples reference the root by path. A release is a v
tag, shared with the Python packages: there is nothing to upload, and SwiftPM has no tag prefix
that would give Swift versions of its own. Never move or delete a released tag. Backend.version
is the tag's version, a literal the release PR sets (step 2 of the release skill), since a
package cannot read its own tag; it is the release X-Stream-Client names. An app clones
the whole repository once (git clone --mirror, about 300 MB); that is the price of one
repository. Do not make Package.swift branch on an environment variable between path: and
url: — resolution stops being reproducible and development paths leak into releases.
A library's Package.resolved is not a promise to consumers; it is gitignored for the package
and committed for the demo apps.
Concurrency
The conversation state is a @MainActor ObservableObject; the socket is an actor. Not an actor
holding the state with a main-actor projection beside it: that is two truths and a window in
which they disagree.
The state machine itself is a value type (Conversation) with mutating func apply(_:).
That is what makes it testable without a network, and it is where new event handling goes.
One read loop per connection, weakly capturing its owner inside the loop:
swiftpump = Task { [weak self] in for try await event in stream { guard let self else { return } // inside, so each iteration is the only strong hold self.apply(event) // inherits @MainActor: no Task { @MainActor in } } }
guard let self outside an infinite loop is the same retain cycle written differently: the
task owns the object that owns the task, and deinit never runs to cancel it.
Where AgentSession stands is one private enum, Lifecycle (unwatched, waiting, connecting,
connected, reconnecting, dropped, closed), never flags beside each other. Each change is one assignment made
before the next await, isConnected and failure are written from it alone, and an attempt to
connect carries an id it checks after every await, since close() can run during any of them.
close() stops the session over the socket only while it is connected, and over HTTP
(stopSession) otherwise: before start(), while it starts or reconnects, once the socket
stopped. An attempt still connecting or reconnecting is over before that request, since the router
carries an ended text conversation on when it is watched again. A socket the
router refused never reads as connected. detach() closes the socket and leaves the session
running, for a screen following a conversation something else holds; VoiceSession.leave() on an
attached voice session does that. A VoiceSession holds its AgentSession one of three ways
(VoiceSession.Holding), and leave() follows it: owned (start) closes it, watching
(attach) detaches it, handed (VoiceSession(_:), a chat moved onto its call) leaves it
followed, since the chat goes on. end() closes it in every case, and deinit leaves the call
only.
- Exactly one
receive()in flight per connection. Concurrent receives reorder frames. - Never
Task { @MainActor in }per frame. It loses ordering and cancellation. - Never a callback the socket invokes to mutate state. One sequential pump.
- Tool handlers are
@Sendable ... async throws, so their bodies run off the main actor even though they are called from it. - Do not mark a type
@unchecked Sendableto silence the compiler. Map a non-Sendablegenerated value into one of ours instead. - Answering a tool call must not depend on anybody consuming a public event stream. It happens
inside
AgentSession. - A tool added while the session runs (
add(tools:)) answers calls before the router says it is added: the next turn can call it while that answer is on its way. An add refused with a 4xx takes the handler back; any other failure (a 5xx, no answer, cancellation) leaves it and marks the name unsettled, since the router may have added it. Changes go one at a time.remove(toolNamed:)drops the handler once the router answers, which waits until no call of the tool can still arrive; a removal that gets no answer or a 5xx leaves it unsettled too, and the name's next add or remove withdraws it first, a 404 counting as done. - A tool with an
approvalis not run when its call arrives. The call waits inAgentSession.approvalsuntildecidesendstool_approval; then the tool runs (allowed) or the call is answered with an error (declined), since the router wants atool_resulteither way. Atool_canceldrops a waiting call, stops a running one (its task is cancelled, and nothing is sent for it), and keeps an answer on its way from running it. A failed send puts the call back, so the person can answer again. A call the conversation shows waiting that the socket never asked, one the router holds itself (a connector'srequire_approval, the agent's scheduling tools for a repeating task) or one shown from the channel after a restart, is answered withdecide(_: ShownToolCall, ...), which sendstool_approvalwith the reply'ssupport_runtimerequest and turn and runs an allowed call only if it is one of the session's tools. A call answered or run here, either way, is neither asked about nor run again when the router sends it again, and one the router cancelled is not answered.
Observation
ObservableObject with @Published, which is why the floor can be iOS 15: @Observable is
iOS 17. Do not add an @Observable path beside it; two state systems in one SDK diverge.
VoiceSession passes its AgentSession's objectWillChange on as its own, so a view
observing the voice session follows voice.session too, as nested reads did under
@Observable. An app holding a session it does not have yet keeps it in an ObservableObject
of its own, the shape of StreamVideo's CallViewModel; the demos' CurrentVoice is one.
The public stream of events is AgentSession.events(), handing each caller its own bounded
continuation — never one stored AsyncThrowingStream property. A single stream is not a broadcast:
two iterators compete for elements. It uses .bufferingOldest(256), checks the yield result, and
ends a subscriber that falls behind with AgentsError.fellBehind once it has read the 256 it holds,
in order, rather than dropping an unknown number of events silently or finishing it as though the
session had ended (as JavaScript's EventsOverrunError); every subscriber finishes when the socket
stops for good or the session closes, not
when an attempt that never got a socket fails, so a reader waits for start() to try again, nor
while a dropped socket is being reconnected.
.unbounded turns a stalled
consumer into a leak.
The socket
URLSessionWebSocketTask. Not a third-party library, which adds TLS, proxy and threading risk
for nothing; not NWConnection, which means implementing the upgrade, framing, masking and
control frames yourself.
- The task answers the router's pings itself. Do not decode ping frames as application
messages, and do not send JSON
"ping". - The task never says when a ping came, and never notices a connection that went away without a
close (out of a network's range, a node lost):
receive()waits on, and the request timeout does not apply once the socket is open. So every session's socket asks for the router's healthchecks (healthcheck=true), a call's too, and once one has come, three of its intervals going by with nothing read is a lost connection (SessionSocket.watch). Nothing is timed before the first healthcheck: a router from before them sends none, and its quiet socket is not a dead one. A healthcheck never reachesevents(). - A socket the session lets go while it still looks open (no healthchecks, the network gone, the
background task over) goes through
SessionSocket.drop, which ends its stream withsocketCloseditself and then cancels the task, for the opening it was decided for only. Neverclose(): a cancelled read finishes quietly, which reads as the session ending. - Set
maximumMessageSize. A socket gone wrong at the far end otherwise buffers without bound. - Closing is idempotent: cancel the reader, then
cancel(with: .normalClosure, reason:). Never a barecancel()for a close the user asked for. - A cancelled read is a close we asked for, not a failure. Finish the stream, do not throw.
- A 1000 close (or 1005, no code) is the router saying the session ended, not a failure: finish
the stream, so
failurestays nil. Any other close throwssocketClosedwith the router'scloseReason, never URLSession's description of the connection going. - URLSession names only the close codes in
CloseCode. One it does not know, such as the 1012 the router closes a resumable socket with on its way down, comes back as 1005 with the whole close payload ascloseReason, its first two bytes the code.SessionSocket.closingreads it back; without that, a router restart reads as the session ending.
Every session's socket is resumed (AgentSession.reconnect), as the sdk
skill's paragraph on resuming watchSession describes, a call's too: its audio is Stream Video's,
which a dropped socket never touches, as JavaScript's does (2026-11-30-session-socket-resume.md).
But a router going down takes a call with it (the agent leaves it, and a watch on the next router
reopens the conversation in writing), so a call's socket the router closes with 1012 is the call's
end, and a call's socket looks its session up (sessions.get) before each attempt and stops once
it ended. That is decided when the socket first opens: a text session moved onto a call
(startVoice()) is still a text one, as its conversation outlives the call. It opens with resumable=true, keeps the last cursor a frame carried (not every
frame carries one, and a reconnected socket's resumed names the newest frame before the missed
ones follow, so its cursor is taken only when complete is false), and skips the resumed its
first socket starts with. On any close but 1000
or 1005, a connection lost without one, or a socket let go here (no healthchecks, the network gone,
the background task over), it opens again with the cursor and the request_id of
the last question asked through responses, until it opens, a 4xx refuses it (a 401 is tried once
more with a fresh token, a 429 is not a refusal), or the session is closed. Nothing is resent:
a command is not idempotent, and what the router missed it resends itself. Meanwhile readers of
events() read on, approvals wait and tools keep running; a result that could not be sent waits
for the socket that carries on. A reconnected socket's resumed reaches events(). When
complete is false the router may have restarted and lost the calls waiting for approval, so
approvals is emptied and the ones it still waits on are asked again after it; the reply in
flight is finished in Conversation when the receipt says the question is settled, or there is
none, rather than left streaming; and one interrupted is asked once more under a new request id,
if it was asked within Reconnection.askAgainWithin, and closing waits for that request before
stopping the session. Missed turns are not read back into turns.
The waits are StreamCore's, the ones Stream Chat and Video reconnect with: DefaultRetryStrategy
for the backoff, one for the session, whose failures are counted across reconnects and started
over (resetConsecutiveFailures) only after a socket that stayed open Reconnection.steadyAfter
(10 s, one healthcheck interval), as Chat starts over once a socket is connected. Started over on
every accepted upgrade, a router that takes the socket and closes it at once would be asked again
with no wait, for good. Its count lives in a class every copy shares, so reset it rather than
trust a copy to start from none.
Recovery (Reconnection.swift) watches InternetConnection and IOSBackgroundTaskScheduler
for as long as a session is followed, as StreamCore's DefaultConnectionRecoveryHandler does
for Stream Chat: the network going lets the socket go at once; no attempt is made while the
network is gone or the app is in the background, and the first after either comes back is at once.
Only a change to no network counts, to let the socket go or to hold an attempt back: a first
reading of none is not believed, as when a router on the device can still be reached, and a
monitor that never changes it would stop every reconnect.
Background state comes from the app's notifications, never isAppActive, which is false where
there is no UIApplication (an app extension, a test) and would stop every reconnect there. StreamCore's WebSocketClient is not
used: it counts a socket connected only after Stream's own health-check event, which the router
never sends, and then drops it unless another comes every 25 seconds; it retries a refused upgrade
forever; and it reopens with a fixed request, where a reconnect needs a new cursor and token. A Combine
closure handed one of them is built in a nonisolated function: one formed on the main actor is
isolated to it, and the monitor calls it on a queue of its own, which traps.
Backgrounding will break the socket; that is iOS, not a bug. Do not promise uninterrupted
background streaming, and do not hold a chat socket open with repeated background tasks. A text
session's socket is kept for one background task, as Stream Chat keeps its own
(staysConnectedInBackground), so a reply in flight or a tool running can finish, and let go when
its time runs out, or at once when iOS gives none; it is resumed when the app comes back. One that
opens while the app is in the background with no time left, as when the app went while it was
opening, is let go at once, so Recovery is made before the first socket opens. Letting go when
the time runs out is best effort: StreamCore ends the task before it calls the expiration handler,
so iOS may suspend the app first, and the socket is let go when the app comes back. A session on a call, opened on one or moved onto one (startVoice()), keeps it: the call
keeps the app running and its tools are still called, as Video exempts a call in progress. The
background task is ended on every way out (foreground, close(), detach(), the socket stopping,
the session released): one left running past its time gets the app killed.
Frames
Distinct types per direction: AgentEvent in, Command out. Never one bidirectional type
with invalid combinations.
Decoding is forward compatible by keeping the whole frame as RawJSON and exposing type
plus a kind, a RawRepresentable struct with a constant for every frame the router's
frameOf writes (WireTests reads sessionws.go and fails on one it does not name). An event
added to the router after this SDK shipped still reaches the caller whole, its kind carrying
its name. A frame that cannot be decoded at all is skipped rather
than closing the socket, which is what the router does with a command it cannot read.
Never [String: Any]: not Codable, not Sendable, and it loses the type guarantees.
Tool-call arguments stay an opaque JSON string, because that is the wire contract. Decoding
them is a convenience on top (argumentValues), not a requirement.
Quote frames verbatim from frameOf in
sessionws.go in tests, so a rename on the
Go side fails here rather than in somebody's app.
The generated client
Committed, generated by sdks/swift/generate.py, never hand-edited. Committed rather than a
build-tool plugin because an SDK's generated source should be reviewable and diffable, needs no
generator on a consumer's machine, and needs no plugin trusted in Xcode.
The generator is Stream's own, the one Stream Chat and Stream Video use: tools/openapi in the
chat repository, checked out beside this one and run with go run. Its DefaultAPI and
models run on StreamCore (Request, DefaultAPITransport, DefaultAPIClientMiddleware,
APIHelper, RawJSON), so Backend.swift supplies a transport and two middlewares rather
than a client of its own. It is run with Stream Chat's options: internal, immutable models,
enums as RawRepresentable classes that keep a value the router added, shared coding keys.
generate.py hands it a copy of the spec in terms it reads: an integer enum is a plain
integer, a reference to a string-or-object union (Equals) is its string shorthand, since the
generator would drop the field, a required field that may be null is not required, since the
generator ignores nullable and the null would fail to decode, and a model whose name a
hand-written type has is renamed (RENAMED: Session is SessionPayload). A collision RENAMED misses fails the build.
DefaultEndpoints.swift is discarded: it is Stream Chat's request path, written against its
internals.
Each run writes sdks/swift/core/generated.json: the sha256 of the spec copy it handed the
generator, the options and the generator's chat commit. --check fails ("Swift client is
stale") when the spec's client part (without info and servers) no longer hashes to it, or when
the files under Generated/ are not the ones the last run wrote, so commit that file with the
client.
A spec change to the client part needs a regeneration by someone with access to the private
GetStream/chat repository, because the generator is in it and CI does not check it out: an
outside contributor's PR cannot pass the swift job. Check out chat beside this repository
at the commit in generated.json's generator (git -C ../chat checkout <sha>), run
uv run sdks/swift/generate.py, and commit the result. Move to another chat commit only on
purpose: chat's master changes generated enum files for every author. The rules of the check
are tested in sdks/swift/test_generate.py; CI runs it before --check.
Generated code is internal. Every type crossing the public API is hand-written in
Models.swift. Leaking one generated type couples the SDK's semantic version to the schema and
to the generator. Never return a generated model or DefaultAPI.
Rewrap deliberately:
- Enums the router sends become a
RawRepresentablestruct with static constants, asToolCallState.Statusis: a value the router added keeps itsrawValueand equals none of the known ones, and a constant added later breaks no app'sswitch. Never a closed enum, an.unknownthat drops the value, a fallback to a known case, orfatalError. - Dates go through
RouterDates, whichJSONDecoder.default, the decoderDefaultAPIis built with, reads every timestamp with. It exists because Go writes as many fractional digits as a value needs and none when it needs none. Before iOS 26, a format style that includes fractional seconds refuses a timestamp without them, soRouterDatesreads twice. Test fractional seconds, no fractional seconds, offsets and malformed input, on the oldest simulator runtime there is as well as the newest: Foundation parses differently across them. - Open-ended objects are StreamCore's
RawJSON, which the generator already emits.
generate.py carries an explicit allowlist of operation ids and fails if any of them is
marked x-server-side-only. That is how the server-side/client-side split is enforced at the
SDK boundary: marking an operation server-side only in the spec is the whole of removing it
from iOS. Adding an endpoint to the Swift SDK means adding it to OPERATIONS and rerunning.
The filter is an API-surface tool, not a security boundary — the router still enforces it, and
that is why every request sends Stream-Auth-Type: jwt.
Errors
One AgentsError, deliberately: it has seven cohesive cases over one service, not a dumping
ground. If it starts collecting unrelated cases, split it per domain (REST, socket, session)
rather than letting it grow. Every failure the SDK publishes is one: AgentSession.failure,
VoiceSession.failure (Stream Video's own errors as .transport, with them inside) and
Conversation.failure, the router's error frame as .reported(code:context:message:).
AgentsError(reporting:) is how an error becomes one, and a cancellation becomes none. It is not
built on StreamCore's ClientError, whose APIError is Stream Chat and Video's error body, not
the router's (type, code as strings, doc_url), and whose subclasses cannot be switched
over exhaustively.
CancellationError is never wrapped and never mapped. A view that goes away mid-request is not
a failure. It must never be confused with a timeout, a lost connection, an HTTP 408, a normal
socket close, or a session ending.
Distinguish, and keep distinguishing: transport failure before any response; an HTTP status;
a decoded error body; a socket close code. Never classify by parsing localizedDescription.
The one exception is a voice session's failure: what Stream Video, the microphone or the
camera failed with is .transport too, with their error inside to tell it apart.
http carries an HTTPFailure: the status, the envelope's type, code, message and
docURL, and requestID from X-Request-Id, which is what a user quotes for a 500. type and
code are strings, so a value the router adds later still reads, and a body that is not the
envelope keeps its trimmed text as message with the rest empty. FailureMiddleware throws every
non-2xx, documented or not, before the generated client decodes it, which is why generate.py
hands the generator the spec with only each operation's 2xx responses. It also hands a 204 on as
{}, since DefaultAPI decodes EmptyResponse from every success. Backend.call reports a
DecodingError as unreadable and anything else the transport threw as transport.
A refused socket upgrade is an http too, with only the status and request id: URLSession never
hands over its body.
Public API
StreamAgents(apiKey:), defaulting to Stream's hosted router, then setUser with a token
provider: the shape sdk gives every client SDK. ID and URL are
capitalised as Swift does. The initialiser does no I/O. StreamAgents(url:customerID:) is
only for a router running locally with nothing in front of it; an apiKey: beside it is
Stream's alone, for chat and video, and the router is still reached by customer id.
swiftlet agents = StreamAgents(apiKey: "your_api_key") agents.setUser(User(id: "jlahey")) { completion in // Stream Chat's TokenProvider Task { do { completion(.success(try Token(rawValue: try await yourBackend.agentToken()))) } catch { completion(.failure(error)) } } } let session = try await agents.agent("myagent").sessions.create() let turn = try await session.responses.create("Where is order 1042?")
sessions.create returns once the session's socket is open, so the tools in its options are
answered from the first turn, as in JS. watch = false opens it with no socket. agents.chat
and agents.voice open as it does, the one held in writing and the other a VoiceSession, the
same as VoiceSession.start, which takes SessionOptions too. VoiceSession(session) joins
the call of a session already on one (startVoice()) with no second socket, and throws
.configuration for one held in writing, as JavaScript's VoiceSession.of does. sessions.attach(_:) returns
once the socket is open too, and throws if it cannot; sessions.attach(_: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 (swift_assistant's AgentChat).
and the advanced form is a request value, not thirty initialiser parameters:
swiftvar options = SessionOptions(agent: "myagent") options.title = "Order 1042" let session = try await agents.sessions.create(options)
The key is public and goes in the query, where Stream's proxy and the router both read it;
the token goes in Authorization and never in a URL.
nil means "omit the field and let the config or the router decide", never "send a copy of the
server's default". A schema default copied into the client is how a caller silently loses the
model their config named.
@discardableResult goes on a call made for what it does that also hands back the result:
an update or a change of state (update, pin, unpin, startVoice, stopVoice, pause,
resume) and asking (responses.create). Never on one made for what it returns: a read, a
list, opening, attaching or forking a session, minting a guest.
Async/await only. No completion handlers, no .shared singleton, no configuration read from
Info.plist or the environment.
A token provider, not a token, for anything with credentials. Backend takes Stream Chat's
TokenProvider in setUser, asks it through Backend.ask (on the main queue, as Stream Chat
does; the first answer heard, a second ignored rather than resuming a continuation twice, and a
completion released uncalled failing the fetch rather than hanging it) and threads the result
through requests, the socket handshake and a single 401 retry, single-flighted. Inside, a token
is the async FetchToken, which the string form of setUser and guest renewal hand over
directly. There is no public TokenProvider of our own: one beside Stream Chat's is ambiguous
wherever an app importing both names it.
It is the one completion handler in the public API, so that an app writes its provider once.
Stream is set up once. The key, the user and the token from setUser are the one identity
for the router, Stream Chat and Stream Video. VoiceSession.join() and session.chat() take
no credentials: Backend.shared builds one client per kind, key and user, single-flighted and
shared by every session, and hands Stream a provider that asks streamCredentials(refresh: true), so an hour-long call outlives its token and two clients refreshing at once fetch one.
agents.use(_:) hands over the app's own ChatClient or StreamVideo, which is used first,
kept across setUser and never disconnected here; one connected as another user is a
.configuration error. agents.disconnect() closes only what was built, and closing a session
closes nothing. Signing out (clearUser, forgetGuest) and setUser with another user
disconnect what was built for the last user, since it would go on receiving what was theirs, and
a client built next waits for that, so two of a kind are never connected at once; the same user
with a new token keeps them. A client is built only when a session first asks for one.
Guests. agents.guestUser(_:store:) mints a guest (createGuestUser), or hands back the
one a GuestStore remembers; one whose token has expired is asked for again with its id and
the refresh_secret the store keeps beside it, which the router answers with the same guest, a
fresh token and the next secret. A secret works once, so whatever comes back replaces what was
stored; one lost or spent gets a new guest. The secret stays in the store, never on Guest.
setUser(_ guest:) acts as them, and forgetGuest(store:) clears the store and the user.
A guest from a store is renewed through it once the router refuses their token (a day after it
was minted): Backend.guests remembers each guest's store, a renewal goes anonymously, since the
expired token proves nothing and the secret does, and one secret is spent on one renewal, which
two at once share. A renewal answered with another guest is an error, never acted on. GuestStore is three methods so an app
keeps the guest wherever it keeps things, the keychain included; FileGuestStore(url:) is the
one provided, and a store holding something unreadable means a new guest, not an error.
GuestOptions(fresh: true) is a "not me" button. Claiming a guest's history for an account is
server-side only and not here.
Views
Core has none. An app shows a conversation with Stream Chat's AI components (StreamChatAI),
and the demo (examples/voice_agents/swift_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:StreamingMessageView(content:isGenerating:). - Its steps are
ai_reasoningandai_tool_callattachments, in order:AIMessagePart.parts(from:)andAIMessagePartsView. - A reasoning step stores only its opening. The whole of it comes a window at a time on the
live updates'
reasoningfield;LiveReasoningreassembles it, fed from the client'sMessageUpdatedEvents (the channel's message list can fold updates together), and goes toStreamingReasoningView(part:text:). Look a step up by its reply and its id: every reply numbers its steps fromr1. - A call that asks first is
awaiting_approvalwith anapproval:AIToolApprovalView, with anAIToolApproverwhosedecideissession.decidewith aShownToolCallread from the reply that shows the call waiting (swift_assistant'sAgentChat.decide), with the reply's author aswrittenByand the step'stargetUserID: a call on a message the agent did not write, or one waiting for somebody else, is refused, since anybody in the channel can post a step. On a call there is no channel; showsession.approvalswithAIToolApprovalCard. - A connector call that waits for the person to sign in is
awaiting_authorizationwith anauthorization, whichAIToolAuthorizationViewshows when theAIToolApproverhas anAIToolAuthorizer. ItscallbackSchemeis the scheme of the session'sSessionOptions.returnURL(the app's own, in reverse domain form), and itsdeclineissession.declineLogin. The view opensauthorization.launchURL, the page with the handoff token in its fragment, in a web authentication sheet. The router updates the step once the provider has answered, and the call runs in the same reply. A session made without areturnURLsends the sign-in back to the dashboard, and the sheet never comes back. - A reply's interactive UI (
ai_ui) reaches the session's socket first, asui_deltaandui_completed, whichConversationfolds onto the turn asTurn.ui(TurnUI), merging anopenuipatch onto the router's base: the latest card before the turn that is complete and was not interrupted, in any format (one that is not OpenUI leaves the turn no UI), as Kotlin and Dart merge it. While OpenUI streams,TurnUI.contentholds only its finished statements, so a card grows a part at a time.LiveUIshows it on the reply while Chat is writing it and its ownai_uiisn't complete, by the rules in thegenerative-uiskill:observethe conversation, and read each message's custom data throughoverlay(_:)intoAIUIDocument(customData:). On a call there is no channel; show the newestTurn.uiwith anAIUIHostof its own. ai_indicator.updateand.clearsay what the agent is doing before the answer starts:AITypingIndicatorView. Read them fromchatClient.eventsController(); a channel's events controller never sees them.AIComposerView's stop button issession.interrupt(), which cancels the reply in flight. The router does not listen forai_indicator.stop.- An incognito session has no channel, and
chat()throws.Conversationfolds the socket'sreasoning_deltaand each call'stool_call.*state (aToolCallState, the one type a call's progress is kept in) intoTurn.steps, whose calls alone areTurn.toolCalls, leaving thetool_started,tool_updatedandtool_ranthe router sends beside them alone so no call shows twice, andsession.turnMessages(TurnMessage) is the conversation in the channel's shape: one reply per question, its steps as attachment payloads forAIMessagePart.parts(from:), rounds numbered across the reply, the whole thinking inreasoning, and a call inapprovalsasawaiting_approvalforSession.userID. The app's message type wraps either source; seeswift_assistant'sAgentChat. Build from the value the$conversationsink hands over:@Publishedsends it before the session holds it.
A spoken session has no channel. The demo shows the agent as AIVoiceGlowView, whose
AIVoiceAgentState comes from the call and the session together: connecting until
VoiceSession.call is joined, speaking while a remote participant isSpeaking, and otherwise
session.state (listening, thinking while responding or working, idle). Speaking is the call's
to say because a reply is written before it is spoken, and responded arrives before the agent
stops talking. An app that wants the words too renders session.turns with
StreamingMessageView.
Tests
Swift Testing, not XCTest. Never mock; assert on state and outputs, never on a call happening.
Three layers, in order of how much they cost to run:
- The state machine.
Conversationis a value type, so what a stream of real router frames means for a transcript is tested in milliseconds with no network. Most new behaviour belongs here. - Live tests.
LiveTestsis gated onVISION_AGENTS_URL, which is the Swift answer to@pytest.mark.integration. It creates a real session, asks the model something and waits for a real tool call. Mark the suite@MainActor, becauseAgentSessionis.PostureTestsfails offline if the generated client holds an operation the spec does not markx-client-accessible, and withINTEGRATION_ROUTER_KEYand_SECRETchecks a device token's 403s against a router inapi_keymode (see the JS README for that router). - Builds.
VoiceSessionandchat()are wrappers over Stream's SDKs, and the demos are views; build them for the simulator. What they share is inBackendand tested there (StreamCredentialsTests).
The package is iOS only, so the tests run on a simulator, from the root of the repository:
xcodebuild test -scheme stream-agents -destination 'platform=iOS Simulator,name=iPhone 18 Pro', with TEST_RUNNER_VISION_AGENTS_URL for the live tests and
TEST_RUNNER_INTEGRATION_ROUTER_KEY and _SECRET for the keyed posture checks.
CI is client-sdks.yml, on the xcode-27 runner,
on any change under sdks/swift, the demo's app or the spec. It runs generate.py --check
(the generator is in the chat repository, which CI does not check out, so it cannot
regenerate, and compares the spec against generated.json instead), runs the core tests on
the first iPhone simulator the runner has, and builds swift_demo. Regenerate locally after a spec change.
Wait on a condition with a deadline, never Task.sleep for a fixed guess:
swifttry await until(20) { session.state == .idle && session.turns.count >= 2 }
If a loopback server is ever needed for close codes, malformed bodies or reconnect timing,
write a real one on 127.0.0.1:0 rather than a URLProtocol subclass — URLProtocol cannot
test a genuine WebSocket upgrade. Do not spend tests re-testing the generated client's
forwarding; it is machine-produced.
Audio and permissions, for VoiceSession
- One owner of
AVAudioSession. A WebRTC SDK and the app both setting category, mode or active state gives dropped Bluetooth, wrong routing and activation failures. Use Stream's supported hooks; do not set audio policy at initialisation, and do not "save the category at startup and restore it later" — something else may have legitimately changed it in between. - Remote audio plays through the audio session once joined. There is no view to add for it;
enableSpeakerPhone()is what makes it hands-free instead of the earpiece. NSMicrophoneUsageDescriptionis the host app's, and a package cannot supply it. Missing it terminates the app — not a recoverable permission denial. Check authorisation before joining, and distinguish not-determined, denied, restricted and granted.- The simulator does not test echo cancellation, Bluetooth routing, receiver versus speaker, interruption by a call, or route changes. Release RTC changes only after device testing.
Logging
Transcripts, prompts, tool arguments and tokens are the most sensitive data here. Do not log frames or bodies by default. Never put a token in a query string.
Reviewing a change
Reject it if it:
- mutates conversation state off the main actor, or hops per frame;
- exposes a generated type publicly, or a Stream type outside
use,chat(),VoiceSession.call,LiveReasoningandsetUser'sTokenProvider; - runs a tool that has an
approvalbeforedecideallows it; - builds a second Stream client for a user who already has one, or disconnects one the app handed over;
- uses
[String: Any], or@unchecked Sendableto quiet a warning; - starts more than one receive per connection, or replays
respond/tool_result; - treats an unknown frame as fatal, or discards its payload;
- wraps
CancellationError, or reports an HTTP status as a transport failure; - hand-edits generated code, or adds a client method for an
x-server-side-onlyoperation; - adds a view to core, or a second package beside it;
- asserts that a method was called.


